answer
stringlengths 17
10.2M
|
|---|
package ca.corefacility.bioinformatics.irida.service.analysis.execution.galaxy.impl.integration;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContextTestExcecutionListener;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig;
import ca.corefacility.bioinformatics.irida.config.conditions.WindowsPlatformCondition;
import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.exceptions.ExecutionManagerException;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowException;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException;
import ca.corefacility.bioinformatics.irida.exceptions.NoSuchValueException;
import ca.corefacility.bioinformatics.irida.exceptions.WorkflowException;
import ca.corefacility.bioinformatics.irida.exceptions.galaxy.GalaxyDatasetNotFoundException;
import ca.corefacility.bioinformatics.irida.exceptions.galaxy.NoGalaxyHistoryException;
import ca.corefacility.bioinformatics.irida.exceptions.galaxy.WorkflowUploadException;
import ca.corefacility.bioinformatics.irida.model.enums.AnalysisCleanedState;
import ca.corefacility.bioinformatics.irida.model.enums.AnalysisState;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.Analysis;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisAssemblyAnnotation;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisOutputFile;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisPhylogenomicsPipeline;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.ToolExecution;
import ca.corefacility.bioinformatics.irida.model.workflow.description.IridaWorkflowParameter;
import ca.corefacility.bioinformatics.irida.model.workflow.execution.galaxy.GalaxyWorkflowStatus;
import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission;
import ca.corefacility.bioinformatics.irida.pipeline.upload.galaxy.integration.LocalGalaxy;
import ca.corefacility.bioinformatics.irida.repositories.analysis.AnalysisRepository;
import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.AnalysisSubmissionRepository;
import ca.corefacility.bioinformatics.irida.service.AnalysisService;
import ca.corefacility.bioinformatics.irida.service.AnalysisSubmissionService;
import ca.corefacility.bioinformatics.irida.service.DatabaseSetupGalaxyITService;
import ca.corefacility.bioinformatics.irida.service.analysis.execution.AnalysisExecutionService;
import ca.corefacility.bioinformatics.irida.service.analysis.workspace.galaxy.AnalysisParameterServiceGalaxy;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService;
import com.github.jmchilton.blend4j.galaxy.GalaxyResponseException;
import com.github.jmchilton.blend4j.galaxy.WorkflowsClient;
import com.github.jmchilton.blend4j.galaxy.beans.WorkflowDetails;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Tests out the analysis service for the Galaxy analyses.
*
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiGalaxyTestConfig.class })
@ActiveProfiles("test")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class,
WithSecurityContextTestExcecutionListener.class })
@DatabaseSetup("/ca/corefacility/bioinformatics/irida/repositories/analysis/AnalysisRepositoryIT.xml")
@DatabaseTearDown("/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml")
public class AnalysisExecutionServiceGalaxyIT {
private static final float DELTA = 0.000001f;
private static final String CMD_LINE_PATTERN = "echo \"csv\" > (/.*?)+; echo \"output_tree\" > (/.*?)+; echo \"positions\" > (/.*?)+";
private static final Logger logger = LoggerFactory.getLogger(AnalysisExecutionServiceGalaxyIT.class);
@Autowired
private DatabaseSetupGalaxyITService analysisExecutionGalaxyITService;
@Autowired
private LocalGalaxy localGalaxy;
@Autowired
private AnalysisSubmissionRepository analysisSubmissionRepository;
@Autowired
private AnalysisSubmissionService analysisSubmissionService;
@Autowired
private AnalysisService analysisService;
@Autowired
private AnalysisRepository analysisRepository;
@Autowired
private AnalysisExecutionService analysisExecutionService;
@Autowired
private IridaWorkflowsService iridaWorkflowsService;
@Autowired
private ExecutorService analysisTaskExecutor;
@Autowired
private AnalysisParameterServiceGalaxy analysisParameterServiceGalaxy;
private WorkflowsClient workflowsClient;
private Path sequenceFilePath;
private Path sequenceFilePath2;
private Path referenceFilePath;
private List<Path> pairedPaths1;
private List<Path> pairedPaths2;
private Path expectedSnpMatrix;
private Path expectedSnpTable;
private Path expectedTree;
private Path expectedOutputFile1;
private Path expectedOutputFile2;
private Path expectedContigs;
private Path expectedAnnotations;
private Path expectedAnnotationsLog;
private UUID validIridaWorkflowId = UUID.fromString("c5f29cb2-1b68-4d34-9b93-609266af7551");
private UUID invalidIridaWorkflowId = UUID.fromString("8ec369e8-1b39-4b9a-97a1-70ac1f6cc9e6");
private UUID iridaPhylogenomicsWorkflowId = UUID.fromString("1f9ea289-5053-4e4a-bc76-1f0c60b179f8");
private UUID iridaPhylogenomicsPairedWorkflowId = UUID.fromString("b8c3916c-846e-4a78-96a9-9630911257cd");
private UUID iridaPhylogenomicsPairedParametersWorkflowId = UUID.fromString("23434bf8-e551-4efd-9957-e61c6f649f8b");
private UUID iridaPhylogenomicsPairedMultiLeveledParametersWorkflowId = UUID.fromString("12734a7d-a0d7-4ede-9cc3-a76b1f8c14e7");
private UUID iridaAssemblyAnnotationWorkflowId = UUID.fromString("8c438951-484a-48da-be2b-93b7d29aa2a3");
private UUID iridaTestAnalysisWorkflowId = UUID.fromString("c5f29cb2-1b68-4d34-9b93-609266af7551");
private UUID iridaWorkflowIdInvalidWorkflowFile = UUID.fromString("d54f1780-e6c9-472a-92dd-63520ec85967");
private UUID iridaTestAnalysisWorkflowIdMissingOutput = UUID.fromString("63038f49-9f2c-4850-9de3-deb9eaf57512");
/**
* Sets up variables for testing.
*
* @throws URISyntaxException
* @throws IOException
* @throws IridaWorkflowNotFoundException
*/
@Before
public void setup() throws URISyntaxException, IOException, IridaWorkflowNotFoundException {
Assume.assumeFalse(WindowsPlatformCondition.isWindows());
Path sequenceFilePathReal = Paths
.get(DatabaseSetupGalaxyITService.class.getResource("testData1.fastq").toURI());
Path referenceFilePathReal = Paths.get(DatabaseSetupGalaxyITService.class.getResource("testReference.fasta")
.toURI());
expectedOutputFile1 = Paths
.get(DatabaseSetupGalaxyITService.class.getResource("output1.txt").toURI());
expectedOutputFile2 = Paths
.get(DatabaseSetupGalaxyITService.class.getResource("output2.txt").toURI());
Path tempDir = Files.createTempDirectory("analysisExecutionTest");
sequenceFilePath = tempDir.resolve("testData1_R1_001.fastq");
Files.copy(sequenceFilePathReal, sequenceFilePath, StandardCopyOption.REPLACE_EXISTING);
sequenceFilePath2 = tempDir.resolve("testData1_R2_001.fastq");
Files.copy(sequenceFilePathReal, sequenceFilePath2, StandardCopyOption.REPLACE_EXISTING);
referenceFilePath = Files.createTempFile("testReference", ".fasta");
Files.copy(referenceFilePathReal, referenceFilePath, StandardCopyOption.REPLACE_EXISTING);
expectedSnpMatrix = localGalaxy.getWorkflowCorePipelineTestMatrix();
expectedSnpTable = localGalaxy.getWorkflowCorePipelineTestSnpTable();
expectedTree = localGalaxy.getWorkflowCorePipelineTestTree();
expectedContigs = Paths
.get(DatabaseSetupGalaxyITService.class.getResource("contigs.fasta").toURI());
expectedAnnotations = Paths
.get(DatabaseSetupGalaxyITService.class.getResource("genome.gbk").toURI());
expectedAnnotationsLog = Paths
.get(DatabaseSetupGalaxyITService.class.getResource("prokka.log").toURI());
pairedPaths1 = Lists.newArrayList();
pairedPaths1.add(sequenceFilePath);
pairedPaths2 = Lists.newArrayList();
pairedPaths2.add(sequenceFilePath2);
workflowsClient = localGalaxy.getGalaxyInstanceAdmin().getWorkflowsClient();
}
/**
* Tests out failing to get a workflow status.
*
* @throws InterruptedException
* @throws NoSuchValueException
* @throws ExecutionManagerException
* @throws IridaWorkflowNotFoundException
* @throws IOException
* @throws ExecutionException
*/
@Test(expected=ExecutionManagerException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testGetWorkflowStatusFail() throws InterruptedException, NoSuchValueException,
IridaWorkflowNotFoundException, ExecutionManagerException, IOException, ExecutionException {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
analysisSubmitted.setRemoteAnalysisId("invalid");
analysisExecutionService.getWorkflowStatus(analysisSubmitted);
}
/**
* Tests out successfully submitting a workflow for execution.
*
* @throws InterruptedException
* @throws NoSuchValueException
* @throws ExecutionManagerException
* @throws IOException
* @throws ExecutionException
* @throws IridaWorkflowException
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testExecuteAnalysisSuccess() throws InterruptedException, NoSuchValueException,
ExecutionManagerException, IOException, ExecutionException, IridaWorkflowException {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutedFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutedFuture.get();
assertEquals(AnalysisState.RUNNING, analysisExecuted.getAnalysisState());
assertNotNull("remoteAnalysisId is null", analysisExecuted.getRemoteAnalysisId());
assertNotNull("remoteInputDataId is null", analysisExecuted.getRemoteInputDataId());
GalaxyWorkflowStatus status = analysisExecutionService.getWorkflowStatus(analysisExecuted);
analysisExecutionGalaxyITService.assertValidStatus(status);
AnalysisSubmission savedSubmission = analysisSubmissionRepository.findOne(analysisExecuted.getId());
assertEquals(analysisExecuted.getRemoteAnalysisId(), savedSubmission.getRemoteAnalysisId());
assertEquals(analysisExecuted.getRemoteWorkflowId(), savedSubmission.getRemoteWorkflowId());
assertEquals(analysisExecuted.getWorkflowId(), savedSubmission.getWorkflowId());
assertEquals(analysisExecuted.getSingleInputFiles(), savedSubmission.getSingleInputFiles());
assertEquals(analysisExecuted.getReferenceFile(), savedSubmission.getReferenceFile());
assertEquals(analysisExecuted.getAnalysisState(), savedSubmission.getAnalysisState());
}
/**
* Tests out attempting to execute an analysis with an invalid remote
* workflow id.
*
* @throws Throwable
*
*/
@Test(expected = WorkflowException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testExecuteAnalysisFailRemoteWorkflowId() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
analysisSubmitted.setRemoteWorkflowId(localGalaxy.getInvalidWorkflowId());
analysisSubmissionService.update(analysisSubmitted.getId(),
ImmutableMap.of("remoteWorkflowId", localGalaxy.getInvalidWorkflowId()));
Future<AnalysisSubmission> analysisExecutedFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
try {
analysisExecutedFuture.get();
} catch (ExecutionException e) {
// check to make sure the submission is in the error state
AnalysisSubmission savedSubmission = analysisSubmissionRepository.findOne(analysisSubmitted.getId());
assertEquals(AnalysisState.ERROR, savedSubmission.getAnalysisState());
throw e.getCause();
}
}
/**
* Tests out attempting to execute an analysis with an invalid remote
* analysis id.
*
* @throws Throwable
*/
@Test(expected = NoGalaxyHistoryException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testExecuteAnalysisFailRemoteAnalysisId() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
analysisSubmitted.setRemoteAnalysisId("invalid");
analysisSubmissionService.update(analysisSubmitted.getId(), ImmutableMap.of("remoteAnalysisId", "invalid"));
Future<AnalysisSubmission> analysisExecutedFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
try {
analysisExecutedFuture.get();
} catch (ExecutionException e) {
// check to make sure the submission is in the error state
AnalysisSubmission savedSubmission = analysisSubmissionRepository.findOne(analysisSubmitted.getId());
logger.debug("Submission on exception=" + savedSubmission.getId());
assertEquals(AnalysisState.ERROR, savedSubmission.getAnalysisState());
throw e.getCause();
}
}
/**
* Tests out attempting to execute an analysis with an invalid parameter value.
*
* @throws Throwable
*/
@Test(expected = WorkflowException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testExecuteAnalysisFailInvalidParameterValue() throws Throwable {
Map<String, String> parameters = ImmutableMap.of("coverage", "not an integer for coverage");
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService
.setupPairSubmissionInDatabase(1L, pairedPaths1, pairedPaths2, referenceFilePath, parameters,
iridaPhylogenomicsPairedParametersWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
try {
analysisExecutionFuture.get();
} catch (ExecutionException e) {
// check to make sure the submission is in the error state
AnalysisSubmission savedSubmission = analysisSubmissionRepository.findOne(analysisSubmitted.getId());
logger.debug("Submission on exception=" + savedSubmission.getId());
assertEquals(AnalysisState.ERROR, savedSubmission.getAnalysisState());
throw e.getCause();
}
}
/**
* Tests out attempting to execute an analysis with an invalid initial
* state.
*
* @throws NoSuchValueException
* @throws ExecutionManagerException
* @throws IOException
* @throws IridaWorkflowException
*/
@Test(expected = IllegalArgumentException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testExecuteAnalysisFailState() throws NoSuchValueException, ExecutionManagerException, IOException, IridaWorkflowException {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
analysisExecutionService.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmissionRepository.findOne(analysisSubmission.getId());
analysisSubmitted.setAnalysisState(AnalysisState.NEW);
analysisExecutionService.executeAnalysis(analysisSubmitted);
}
/**
* Tests out successfully preparing a workflow submission.
*
* @throws InterruptedException
* @throws NoSuchValueException
* @throws ExecutionManagerException
* @throws IOException
* @throws IridaWorkflowNotFoundException
* @throws ExecutionException
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testPrepareSubmissionSuccess() throws InterruptedException, NoSuchValueException,
IridaWorkflowNotFoundException, IOException, ExecutionManagerException, ExecutionException {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmissionFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmissionFuture.get();
assertEquals(AnalysisState.PREPARED, analysisSubmitted.getAnalysisState());
AnalysisSubmission analysisSaved = analysisSubmissionRepository.findOne(analysisSubmission.getId());
assertEquals(analysisSaved.getId(), analysisSubmitted.getId());
assertNotNull("analysisSubmitted is null", analysisSaved);
assertNotNull("remoteWorkflowId is null", analysisSaved.getRemoteWorkflowId());
assertNotNull("remoteAnalysisId is null", analysisSaved.getRemoteAnalysisId());
assertEquals(AnalysisState.PREPARED, analysisSaved.getAnalysisState());
}
/**
* Tests out attempting to prepare a workflow with an invalid id for
* execution.
*
* @throws Throwable
*/
@Test(expected = IridaWorkflowNotFoundException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testPrepareSubmissionFailInvalidWorkflow() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, invalidIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmissionFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
try {
analysisSubmissionFuture.get();
} catch (ExecutionException e) {
logger.debug("Submission on exception=" + analysisSubmissionService.read(analysisSubmission.getId()));
assertEquals(AnalysisState.ERROR, analysisSubmissionService.read(analysisSubmission.getId())
.getAnalysisState());
// pull out real exception
throw e.getCause();
}
}
/**
* Tests out attempting to prepare a workflow with an invalid Galaxy
* workflow file.
*
* @throws Throwable
*/
@Test(expected = WorkflowUploadException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testPrepareSubmissionFailInvalidGalaxyWorkflowFile() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaWorkflowIdInvalidWorkflowFile);
Future<AnalysisSubmission> analysisSubmissionFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
try {
analysisSubmissionFuture.get();
} catch (ExecutionException e) {
logger.debug("Submission on exception=" + analysisSubmissionService.read(analysisSubmission.getId()));
assertEquals(AnalysisState.ERROR, analysisSubmissionService.read(analysisSubmission.getId())
.getAnalysisState());
// pull out real exception
throw e.getCause();
}
}
/**
* Tests out getting analysis results successfully.
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessPhylogenomics() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaPhylogenomicsWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
float percentComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(analysisSubmitted.getId());
assertEquals("percent complete is incorrect", 1.0f, percentComplete, DELTA);
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
assertNotNull("remoteInputDataId is null", analysisExecuted.getRemoteInputDataId());
String remoteInputDataId = analysisExecuted.getRemoteInputDataId();
percentComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(analysisSubmitted.getId());
assertTrue("percent complete is incorrect", 10.0f <= percentComplete && percentComplete <= 90.0f);
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
percentComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(analysisSubmitted.getId());
assertEquals("percent complete is incorrect", 90.0f, percentComplete, DELTA);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
percentComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(analysisSubmitted.getId());
assertEquals("percent complete is incorrect", 90.0f, percentComplete, DELTA);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
AnalysisSubmission analysisSubmissionCompleted = analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals(AnalysisState.COMPLETED, analysisSubmissionCompletedDatabase.getAnalysisState());
assertEquals(AnalysisState.COMPLETED, analysisSubmissionCompleted.getAnalysisState());
assertEquals("remoteInputDataId should be unchanged in the completed analysis", remoteInputDataId,
analysisSubmissionCompletedDatabase.getRemoteInputDataId());
percentComplete = analysisSubmissionService.getPercentCompleteForAnalysisSubmission(analysisSubmitted.getId());
assertEquals("percent complete is incorrect", 100.0f, percentComplete, DELTA);
Analysis analysisResults = analysisSubmissionCompleted.getAnalysis();
Analysis analysisResultsDatabase = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results in returned submission and from database should be the same",
analysisResults.getId(), analysisResultsDatabase.getId());
assertEquals(AnalysisPhylogenomicsPipeline.class, analysisResults.getClass());
AnalysisPhylogenomicsPipeline analysisResultsPhylogenomics = (AnalysisPhylogenomicsPipeline) analysisResults;
String analysisId = analysisExecuted.getRemoteAnalysisId();
assertEquals("id should be set properly for analysis", analysisId,
analysisResultsPhylogenomics.getExecutionManagerAnalysisId());
assertEquals(3, analysisResultsPhylogenomics.getAnalysisOutputFiles().size());
AnalysisOutputFile phylogeneticTree = analysisResultsPhylogenomics.getPhylogeneticTree();
AnalysisOutputFile snpMatrix = analysisResultsPhylogenomics.getSnpMatrix();
AnalysisOutputFile snpTable = analysisResultsPhylogenomics.getSnpTable();
assertTrue("phylogenetic trees should be equal",
com.google.common.io.Files.equal(expectedTree.toFile(), phylogeneticTree.getFile().toFile()));
assertEquals(expectedTree.getFileName(), phylogeneticTree.getFile().getFileName());
assertTrue("snp matrices should be correct",
com.google.common.io.Files.equal(expectedSnpMatrix.toFile(), snpMatrix.getFile().toFile()));
assertEquals(expectedSnpMatrix.getFileName(), snpMatrix.getFile().getFileName());
assertTrue("snpTable should be correct",
com.google.common.io.Files.equal(expectedSnpTable.toFile(), snpTable.getFile().toFile()));
assertEquals(expectedSnpTable.getFileName(), snpTable.getFile().getFileName());
AnalysisSubmission finalSubmission = analysisSubmissionRepository.findOne(analysisExecuted.getId());
Analysis analysis = finalSubmission.getAnalysis();
assertNotNull(analysis);
Analysis savedAnalysisFromDatabase = analysisService.read(analysisResultsPhylogenomics.getId());
assertTrue(savedAnalysisFromDatabase instanceof AnalysisPhylogenomicsPipeline);
AnalysisPhylogenomicsPipeline savedPhylogenomics = (AnalysisPhylogenomicsPipeline) savedAnalysisFromDatabase;
assertEquals("Analysis from submission and from database should be the same",
savedAnalysisFromDatabase.getId(), analysis.getId());
assertEquals(analysisResultsPhylogenomics.getId(), savedPhylogenomics.getId());
assertEquals(analysisResultsPhylogenomics.getPhylogeneticTree().getFile(), savedPhylogenomics
.getPhylogeneticTree().getFile());
assertEquals(analysisResultsPhylogenomics.getSnpMatrix().getFile(), savedPhylogenomics.getSnpMatrix().getFile());
assertEquals(analysisResultsPhylogenomics.getSnpTable().getFile(), savedPhylogenomics.getSnpTable().getFile());
}
/**
* Tests out getting analysis results successfully for phylogenomics
* pipeline (paired test version).
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessPhylogenomicsPaired() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupPairSubmissionInDatabase(1L,
pairedPaths1, pairedPaths2, referenceFilePath, iridaPhylogenomicsPairedWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
AnalysisSubmission analysisSubmissionCompleted = analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompletedDatabase.getAnalysisState());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompleted.getAnalysisState());
Analysis analysisResults = analysisSubmissionCompleted.getAnalysis();
Analysis analysisResultsDatabase = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results in returned submission and from database should be the same",
analysisResults.getId(), analysisResultsDatabase.getId());
assertEquals("analysis results is an invalid class", AnalysisPhylogenomicsPipeline.class,
analysisResults.getClass());
AnalysisPhylogenomicsPipeline analysisResultsPhylogenomics = (AnalysisPhylogenomicsPipeline) analysisResults;
String analysisId = analysisExecuted.getRemoteAnalysisId();
assertEquals("id should be set properly for analysis", analysisId,
analysisResultsPhylogenomics.getExecutionManagerAnalysisId());
assertEquals("invalid number of output files", 3, analysisResultsPhylogenomics.getAnalysisOutputFiles().size());
AnalysisOutputFile phylogeneticTree = analysisResultsPhylogenomics.getPhylogeneticTree();
AnalysisOutputFile snpMatrix = analysisResultsPhylogenomics.getSnpMatrix();
AnalysisOutputFile snpTable = analysisResultsPhylogenomics.getSnpTable();
assertTrue("phylogenetic trees should be equal",
com.google.common.io.Files.equal(expectedTree.toFile(), phylogeneticTree.getFile().toFile()));
assertEquals("invalid file name for snp tree", expectedTree.getFileName(), phylogeneticTree.getFile()
.getFileName());
assertTrue("command line should match the defined pattern (phylogenetic tree).",
phylogeneticTree.getCreatedByTool().getCommandLine().matches(CMD_LINE_PATTERN));
final ToolExecution phyTreeCoreInputs = phylogeneticTree.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired v0.1.0",
"core_pipeline_outputs_paired", phyTreeCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired v0.1.0", "0.1.0",
phyTreeCoreInputs.getToolVersion());
final ToolExecution phyTreeCoreUpload = phyTreeCoreInputs.getPreviousSteps().iterator().next();
assertTrue("Second step should be input tool.", phyTreeCoreUpload.isInputTool());
assertTrue("snp matrices should be correct",
com.google.common.io.Files.equal(expectedSnpMatrix.toFile(), snpMatrix.getFile().toFile()));
assertEquals("invalid file name for snp matrix", expectedSnpMatrix.getFileName(), snpMatrix.getFile()
.getFileName());
assertTrue("command line should match the defined pattern (snp matrix).",
snpMatrix.getCreatedByTool().getCommandLine().matches(CMD_LINE_PATTERN));
final ToolExecution snpMatrixCoreInputs = snpMatrix.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired v0.1.0",
"core_pipeline_outputs_paired", snpMatrixCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired v0.1.0", "0.1.0",
snpMatrixCoreInputs.getToolVersion());
final ToolExecution snpMatrixCoreUpload = snpMatrixCoreInputs.getPreviousSteps().iterator().next();
assertTrue("Second step should be input tool.", snpMatrixCoreUpload.isInputTool());
assertTrue("snpTable should be correct",
com.google.common.io.Files.equal(expectedSnpTable.toFile(), snpTable.getFile().toFile()));
assertEquals("invalid file name for snp table", expectedSnpTable.getFileName(), snpTable.getFile()
.getFileName());
assertTrue("command line should match the defined pattern (snp table).",
snpTable.getCreatedByTool().getCommandLine().matches(CMD_LINE_PATTERN));
final ToolExecution snpTableCoreInputs = snpTable.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired v0.1.0",
"core_pipeline_outputs_paired", snpTableCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired v0.1.0", "0.1.0",
snpTableCoreInputs.getToolVersion());
final ToolExecution snpTableCoreUpload = snpTableCoreInputs.getPreviousSteps().iterator().next();
assertTrue("Second step should be input tool.", snpTableCoreUpload.isInputTool());
AnalysisSubmission finalSubmission = analysisSubmissionRepository.findOne(analysisExecuted.getId());
Analysis analysis = finalSubmission.getAnalysis();
assertNotNull("analysis should not be null in submission", analysis);
Analysis savedAnalysisFromDatabase = analysisService.read(analysisResultsPhylogenomics.getId());
assertTrue("saved analysis in submission is not correct class",
savedAnalysisFromDatabase instanceof AnalysisPhylogenomicsPipeline);
AnalysisPhylogenomicsPipeline savedPhylogenomics = (AnalysisPhylogenomicsPipeline) savedAnalysisFromDatabase;
assertEquals("Analysis from submission and from database should be the same",
savedAnalysisFromDatabase.getId(), analysis.getId());
assertEquals("analysis results from database and from submission should have correct id",
analysisResultsPhylogenomics.getId(), savedPhylogenomics.getId());
assertEquals("analysis results from database and from submission should have correct tree output file",
analysisResultsPhylogenomics.getPhylogeneticTree().getFile(), savedPhylogenomics.getPhylogeneticTree()
.getFile());
assertEquals("analysis results from database and from submission should have correct matrix output file",
analysisResultsPhylogenomics.getSnpMatrix().getFile(), savedPhylogenomics.getSnpMatrix().getFile());
assertEquals("analysis results from database and from submission should have correct table output file",
analysisResultsPhylogenomics.getSnpTable().getFile(), savedPhylogenomics.getSnpTable().getFile());
}
/**
* Tests out getting analysis results successfully for phylogenomics
* pipeline (paired test version with parameters).
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessPhylogenomicsPairedParameters() throws Exception {
String validCoverage = "20";
String validCoverageFromProvenance = "\"20\""; // coverage from
// provenance has quotes
String validMidCoverageFromProvenance = "20"; // this value does not have quotes around it in final results.
Map<String, String> parameters = ImmutableMap.of("coverage", validCoverage);
String validTreeFile = "20 20 20"; // I verify parameters were set
// correctly by checking output file
// (where parameters were printed).
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService
.setupPairSubmissionInDatabase(1L, pairedPaths1, pairedPaths2, referenceFilePath, parameters,
iridaPhylogenomicsPairedParametersWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompletedDatabase.getAnalysisState());
Analysis analysisResults = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results is an invalid class", AnalysisPhylogenomicsPipeline.class,
analysisResults.getClass());
AnalysisPhylogenomicsPipeline analysisResultsPhylogenomics = (AnalysisPhylogenomicsPipeline) analysisResults;
assertEquals("invalid number of output files", 3, analysisResultsPhylogenomics.getAnalysisOutputFiles().size());
AnalysisOutputFile phylogeneticTree = analysisResultsPhylogenomics.getPhylogeneticTree();
AnalysisOutputFile snpMatrix = analysisResultsPhylogenomics.getSnpMatrix();
AnalysisOutputFile snpTable = analysisResultsPhylogenomics.getSnpTable();
// verify parameters were set properly by checking contents of file
@SuppressWarnings("resource")
String treeContent = new Scanner(phylogeneticTree.getFile().toFile()).useDelimiter("\\Z").next();
assertEquals("phylogenetic trees containing the parameters should be equal", validTreeFile, treeContent);
// phy tree
final ToolExecution phyTreeCoreInputs = phylogeneticTree.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", phyTreeCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", phyTreeCoreInputs.getToolVersion());
Map<String, String> phyTreeCoreParameters = phyTreeCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, phyTreeCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> phyTreeCorePreviousSteps = phyTreeCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, phyTreeCorePreviousSteps.size());
Set<String> uploadedFileTypesPhy = Sets.newHashSet();
for (ToolExecution previousStep : phyTreeCorePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesPhy.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesPhy);
// snp matrix
final ToolExecution matrixCoreInputs = snpMatrix.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", matrixCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", matrixCoreInputs.getToolVersion());
Map<String, String> matrixCoreParameters = matrixCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, matrixCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validCoverageFromProvenance,
matrixCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validCoverageFromProvenance,
matrixCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> matrixCorePreviousSteps = matrixCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, matrixCorePreviousSteps.size());
Set<String> uploadedFileTypesMatrix = Sets.newHashSet();
for (ToolExecution previousStep : matrixCorePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesMatrix.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesMatrix);
// snp table
final ToolExecution tableCoreInputs = snpTable.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", tableCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", tableCoreInputs.getToolVersion());
Map<String, String> tableCoreParameters = tableCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, tableCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validCoverageFromProvenance,
tableCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validCoverageFromProvenance,
tableCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> tablePreviousSteps = tableCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, tablePreviousSteps.size());
Set<String> uploadedFileTypesTable = Sets.newHashSet();
for (ToolExecution previousStep : tablePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesTable.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesTable);
}
/**
* Tests out getting analysis results successfully for phylogenomics
* pipeline (paired test version with no parameters, using defaults).
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessPhylogenomicsPairedNoParameters() throws Exception {
String validCoverageFromProvenance = "\"10\"";
String validMidCoverageFromProvenance = "10";
String validTreeFile = "10 10 10"; // I verify parameters were set
// correctly by checking output file
// (where parameters were printed).
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupPairSubmissionInDatabase(1L,
pairedPaths1, pairedPaths2, referenceFilePath, iridaPhylogenomicsPairedParametersWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompletedDatabase.getAnalysisState());
Analysis analysisResults = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results is an invalid class", AnalysisPhylogenomicsPipeline.class,
analysisResults.getClass());
AnalysisPhylogenomicsPipeline analysisResultsPhylogenomics = (AnalysisPhylogenomicsPipeline) analysisResults;
assertEquals("invalid number of output files", 3, analysisResultsPhylogenomics.getAnalysisOutputFiles().size());
AnalysisOutputFile phylogeneticTree = analysisResultsPhylogenomics.getPhylogeneticTree();
AnalysisOutputFile snpMatrix = analysisResultsPhylogenomics.getSnpMatrix();
AnalysisOutputFile snpTable = analysisResultsPhylogenomics.getSnpTable();
// verify parameters were set properly by checking contents of file
@SuppressWarnings("resource")
String treeContent = new Scanner(phylogeneticTree.getFile().toFile()).useDelimiter("\\Z").next();
assertEquals("phylogenetic trees containing the parameters should be equal", validTreeFile, treeContent);
// phy tree
final ToolExecution phyTreeCoreInputs = phylogeneticTree.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", phyTreeCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", phyTreeCoreInputs.getToolVersion());
Map<String, String> phyTreeCoreParameters = phyTreeCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, phyTreeCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> phyTreeCorePreviousSteps = phyTreeCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, phyTreeCorePreviousSteps.size());
Set<String> uploadedFileTypesPhy = Sets.newHashSet();
for (ToolExecution previousStep : phyTreeCorePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesPhy.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesPhy);
// snp matrix
final ToolExecution matrixCoreInputs = snpMatrix.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", matrixCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", matrixCoreInputs.getToolVersion());
Map<String, String> matrixCoreParameters = matrixCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, matrixCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validCoverageFromProvenance,
matrixCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validCoverageFromProvenance,
matrixCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
matrixCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> matrixCorePreviousSteps = matrixCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, matrixCorePreviousSteps.size());
Set<String> uploadedFileTypesMatrix = Sets.newHashSet();
for (ToolExecution previousStep : matrixCorePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesMatrix.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesMatrix);
// snp table
final ToolExecution tableCoreInputs = snpTable.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", tableCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", tableCoreInputs.getToolVersion());
Map<String, String> tableCoreParameters = tableCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, tableCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validCoverageFromProvenance,
tableCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validCoverageFromProvenance,
tableCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
tableCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> tablePreviousSteps = tableCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, tablePreviousSteps.size());
Set<String> uploadedFileTypesTable = Sets.newHashSet();
for (ToolExecution previousStep : tablePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesTable.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesTable);
}
/**
* Tests out getting analysis results successfully for phylogenomics
* pipeline (paired test version and ignoring default parameters).
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessPhylogenomicsPairedParametersIgnoreDefaultValues() throws Exception {
String validMinCoverageFromProvenance = "\"5\"";
String validMidCoverageFromProvenance = "15";
String validMaxCoverageFromProvenance = "\"20\"";
Map<String, String> parameters = ImmutableMap.of("coverage", IridaWorkflowParameter.IGNORE_DEFAULT_VALUE);
String validTreeFile = "5 15 20"; // I verify parameters were set
// correctly by checking output file
// (where parameters were printed).
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService
.setupPairSubmissionInDatabase(1L, pairedPaths1, pairedPaths2, referenceFilePath, parameters,
iridaPhylogenomicsPairedParametersWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompletedDatabase.getAnalysisState());
Analysis analysisResults = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results is an invalid class", AnalysisPhylogenomicsPipeline.class,
analysisResults.getClass());
AnalysisPhylogenomicsPipeline analysisResultsPhylogenomics = (AnalysisPhylogenomicsPipeline) analysisResults;
assertEquals("invalid number of output files", 3, analysisResultsPhylogenomics.getAnalysisOutputFiles().size());
AnalysisOutputFile phylogeneticTree = analysisResultsPhylogenomics.getPhylogeneticTree();
AnalysisOutputFile snpMatrix = analysisResultsPhylogenomics.getSnpMatrix();
AnalysisOutputFile snpTable = analysisResultsPhylogenomics.getSnpTable();
// verify parameters were set properly by checking contents of file
@SuppressWarnings("resource")
String treeContent = new Scanner(phylogeneticTree.getFile().toFile()).useDelimiter("\\Z").next();
assertEquals("phylogenetic trees containing the parameters should be equal", validTreeFile, treeContent);
// phy tree
final ToolExecution phyTreeCoreInputs = phylogeneticTree.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", phyTreeCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", phyTreeCoreInputs.getToolVersion());
Map<String, String> phyTreeCoreParameters = phyTreeCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, phyTreeCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validMinCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validMaxCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> phyTreeCorePreviousSteps = phyTreeCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, phyTreeCorePreviousSteps.size());
Set<String> uploadedFileTypesPhy = Sets.newHashSet();
for (ToolExecution previousStep : phyTreeCorePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesPhy.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesPhy);
// snp matrix
final ToolExecution matrixCoreInputs = snpMatrix.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", matrixCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", matrixCoreInputs.getToolVersion());
Map<String, String> matrixCoreParameters = matrixCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, matrixCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validMinCoverageFromProvenance,
matrixCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validMaxCoverageFromProvenance,
matrixCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> matrixCorePreviousSteps = matrixCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, matrixCorePreviousSteps.size());
Set<String> uploadedFileTypesMatrix = Sets.newHashSet();
for (ToolExecution previousStep : matrixCorePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesMatrix.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesMatrix);
// snp table
final ToolExecution tableCoreInputs = snpTable.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"core_pipeline_outputs_paired_with_parameters", tableCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_parameters v0.1.0",
"0.1.0", tableCoreInputs.getToolVersion());
Map<String, String> tableCoreParameters = tableCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 5, tableCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validMinCoverageFromProvenance,
tableCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter coverageMax set incorrectly", validMaxCoverageFromProvenance,
tableCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
Set<ToolExecution> tablePreviousSteps = tableCoreInputs.getPreviousSteps();
assertEquals("there should exist 2 previous steps", 2, tablePreviousSteps.size());
Set<String> uploadedFileTypesTable = Sets.newHashSet();
for (ToolExecution previousStep : tablePreviousSteps) {
assertTrue("previous steps should be input tools.", previousStep.isInputTool());
uploadedFileTypesTable.add(previousStep.getExecutionTimeParameters().get("file_type"));
}
assertEquals("uploaded files should have correct types", Sets.newHashSet("\"fastqsanger\"", "\"fasta\""),
uploadedFileTypesTable);
}
/**
* Tests out getting analysis results successfully for phylogenomics
* pipeline (paired test version with multiple levels of parameters).
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessPhylogenomicsPairedMultiLeveledParameters() throws Exception {
String validCoverage = "20";
String validCoverageFromProvenance = "\"20\""; // coverage from
// provenance has quotes
String validMidCoverageFromProvenance = "20"; // this value does not have quotes around it in final results.
String validParameterValueFromProvenance = "20";
Map<String, String> parameters = ImmutableMap.of("coverage", validCoverage);
String validTreeFile = "20 20 20 20"; // I verify parameters were set
// correctly by checking output file
// (where parameters were printed).
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService
.setupPairSubmissionInDatabase(1L, pairedPaths1, pairedPaths2, referenceFilePath, parameters,
iridaPhylogenomicsPairedMultiLeveledParametersWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompletedDatabase.getAnalysisState());
Analysis analysisResults = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results is an invalid class", AnalysisPhylogenomicsPipeline.class,
analysisResults.getClass());
AnalysisPhylogenomicsPipeline analysisResultsPhylogenomics = (AnalysisPhylogenomicsPipeline) analysisResults;
assertEquals("invalid number of output files", 3, analysisResultsPhylogenomics.getAnalysisOutputFiles().size());
AnalysisOutputFile phylogeneticTree = analysisResultsPhylogenomics.getPhylogeneticTree();
// verify parameters were set properly by checking contents of file
@SuppressWarnings("resource")
String treeContent = new Scanner(phylogeneticTree.getFile().toFile()).useDelimiter("\\Z").next();
assertEquals("phylogenetic trees containing the parameters should be equal", validTreeFile, treeContent);
// phy tree
final ToolExecution phyTreeCoreInputs = phylogeneticTree.getCreatedByTool();
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_multi_level_parameters v0.1.0",
"core_pipeline_outputs_paired_with_multi_level_parameters", phyTreeCoreInputs.getToolName());
assertEquals("The first tool execution should be by core_pipeline_outputs_paired_with_multi_level_parameters v0.1.0",
"0.1.0", phyTreeCoreInputs.getToolVersion());
Map<String, String> phyTreeCoreParameters = phyTreeCoreInputs.getExecutionTimeParameters();
assertEquals("incorrect number of non-file parameters", 7, phyTreeCoreParameters.size());
assertEquals("parameter coverageMin set incorrectly", validCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMin"));
assertEquals("parameter coverageMid set incorrectly", validMidCoverageFromProvenance,
phyTreeCoreParameters.get("conditional.coverageMid"));
assertEquals("parameter 'parameter' set incorrectly", validParameterValueFromProvenance,
phyTreeCoreParameters.get("conditional.level2.parameter"));
assertEquals("parameter coverageMax set incorrectly", validCoverageFromProvenance,
phyTreeCoreParameters.get("coverageMax"));
assertEquals("parameter conditional_select set incorrectly", "all",
phyTreeCoreParameters.get("conditional.conditional_select"));
assertEquals("parameter conditional_select set incorrectly", "all2",
phyTreeCoreParameters.get("conditional.level2.level2_select"));
assertNotNull("parameter __workflow_invocation_uuid__ exists",
phyTreeCoreParameters.get("__workflow_invocation_uuid__"));
}
/**
* Tests out getting analysis results successfully for assembly and annotation pipeline (test version).
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessAssemblyAnnotation() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupPairSubmissionInDatabase(1L,
pairedPaths1, pairedPaths2, iridaAssemblyAnnotationWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
AnalysisSubmission analysisSubmissionCompleted = analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompletedDatabase.getAnalysisState());
assertEquals("analysis state is not completed", AnalysisState.COMPLETED,
analysisSubmissionCompleted.getAnalysisState());
Analysis analysisResults = analysisSubmissionCompleted.getAnalysis();
Analysis analysisResultsDatabase = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results in returned submission and from database should be the same",
analysisResults.getId(), analysisResultsDatabase.getId());
assertEquals("analysis results is an invalid class", AnalysisAssemblyAnnotation.class,
analysisResults.getClass());
AnalysisAssemblyAnnotation analysisResultsAssembly = (AnalysisAssemblyAnnotation) analysisResults;
String analysisId = analysisExecuted.getRemoteAnalysisId();
assertEquals("id should be set properly for analysis", analysisId,
analysisResultsAssembly.getExecutionManagerAnalysisId());
assertEquals("invalid number of output files", 3, analysisResultsAssembly.getAnalysisOutputFiles().size());
AnalysisOutputFile contigs = analysisResultsAssembly.getAnalysisOutputFile("contigs");
AnalysisOutputFile annotations = analysisResultsAssembly.getAnalysisOutputFile("annotations-genbank");
AnalysisOutputFile prokkaLog = analysisResultsAssembly.getAnalysisOutputFile("annotations-log");
assertTrue("contigs should be equal",
com.google.common.io.Files.equal(expectedContigs.toFile(), contigs.getFile().toFile()));
assertEquals("invalid file name for contigs", expectedContigs.getFileName(), contigs.getFile()
.getFileName());
assertTrue("annotations should be correct",
com.google.common.io.Files.equal(expectedAnnotations.toFile(), annotations.getFile().toFile()));
assertEquals("invalid file name for annotations", expectedAnnotations.getFileName(), annotations.getFile()
.getFileName());
assertTrue("annotations log should be correct",
com.google.common.io.Files.equal(expectedAnnotationsLog.toFile(), prokkaLog.getFile().toFile()));
assertEquals("invalid file name for annotations log", expectedAnnotationsLog.getFileName(), prokkaLog.getFile()
.getFileName());
}
/**
* Tests out getting analysis results successfully.
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsSuccessTestAnalysis() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
AnalysisSubmission analysisSubmissionCompleted = analysisSubmissionCompletedFuture.get();
AnalysisSubmission analysisSubmissionCompletedDatabase = analysisSubmissionService.read(analysisSubmission
.getId());
assertEquals(AnalysisState.COMPLETED, analysisSubmissionCompletedDatabase.getAnalysisState());
assertEquals(AnalysisState.COMPLETED, analysisSubmissionCompleted.getAnalysisState());
Analysis analysisResults = analysisSubmissionCompleted.getAnalysis();
Analysis analysisResultsDatabase = analysisSubmissionCompletedDatabase.getAnalysis();
assertEquals("analysis results in returned submission and from database should be the same",
analysisResults.getId(), analysisResultsDatabase.getId());
assertEquals(Analysis.class, analysisResults.getClass());
String analysisId = analysisExecuted.getRemoteAnalysisId();
assertEquals("id should be set properly for analysis", analysisId,
analysisResults.getExecutionManagerAnalysisId());
assertEquals(2, analysisResults.getAnalysisOutputFiles().size());
AnalysisOutputFile output1 = analysisResults.getAnalysisOutputFile("output1");
AnalysisOutputFile output2 = analysisResults.getAnalysisOutputFile("output2");
assertTrue("output files 1 should be equal",
com.google.common.io.Files.equal(expectedOutputFile1.toFile(), output1.getFile().toFile()));
assertEquals(expectedOutputFile1.getFileName(), output1.getFile().getFileName());
assertTrue("output files 2 should be equal",
com.google.common.io.Files.equal(expectedOutputFile2.toFile(), output2.getFile().toFile()));
assertEquals(expectedOutputFile2.getFileName(), output2.getFile().getFileName());
AnalysisSubmission finalSubmission = analysisSubmissionRepository.findOne(analysisExecuted.getId());
Analysis analysis = finalSubmission.getAnalysis();
assertNotNull(analysis);
Analysis savedAnalysisFromDatabase = analysisService.read(analysisResults.getId());
assertTrue(savedAnalysisFromDatabase instanceof Analysis);
Analysis savedTest = (Analysis) savedAnalysisFromDatabase;
assertEquals("Analysis from submission and from database should be the same",
savedAnalysisFromDatabase.getId(), analysis.getId());
assertEquals(analysisResults.getId(), savedTest.getId());
assertEquals(analysisResults.getAnalysisOutputFile("output1").getFile(),
savedTest.getAnalysisOutputFile("output1").getFile());
assertEquals(analysisResults.getAnalysisOutputFile("output2").getFile(),
savedTest.getAnalysisOutputFile("output2").getFile());
}
/**
* Tests failure to get analysis results due to a missing output file.
* @throws Throwable
*/
@Test(expected=GalaxyDatasetNotFoundException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsFailTestAnalysisMissingOutput() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowIdMissingOutput);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
try {
analysisSubmissionCompletedFuture.get();
} catch (ExecutionException e) {
logger.debug("Submission on exception=" + analysisSubmissionService.read(analysisSubmission.getId()));
assertEquals(AnalysisState.ERROR, analysisSubmissionService.read(analysisSubmission.getId())
.getAnalysisState());
// pull out real exception
throw e.getCause();
}
}
/**
* Tests out failing to get analysis results due to analysis submission
* having an invalid id (not submitted).
*
* @throws Throwable
*/
@Test(expected = EntityNotFoundException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsFailInvalidId() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setId(555L);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
try {
analysisSubmissionCompletedFuture.get();
} catch (ExecutionException e) {
logger.debug("Submission on exception=" + analysisSubmissionService.read(analysisSubmission.getId()));
assertEquals(AnalysisState.ERROR, analysisSubmissionService.read(analysisSubmission.getId())
.getAnalysisState());
// pull out real exception
throw e.getCause();
}
}
/**
* Tests out failing to get analysis results due to analysis submission
* having an invalid remote analysis id (submission not existing in Galaxy).
*
* @throws Throwable
*/
@Test(expected = GalaxyResponseException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testTransferAnalysisResultsFailInvalidRemoteAnalysisId() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, validIridaWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisSubmissionService.update(analysisExecuted.getId(), ImmutableMap.of("remoteAnalysisId", "invalid"));
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
try {
analysisSubmissionCompletedFuture.get();
} catch (ExecutionException e) {
logger.debug("Submission on exception=" + analysisSubmissionService.read(analysisSubmission.getId()));
assertEquals(AnalysisState.ERROR, analysisSubmissionService.read(analysisSubmission.getId())
.getAnalysisState());
// pull out real exception
throw e.getCause();
}
}
/**
* Tests out cleaning up a completed analysis successfully.
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testCleanupCompletedAnalysisSuccess() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
AnalysisSubmission analysisSubmissionCompleted = analysisSubmissionCompletedFuture.get();
assertEquals(AnalysisState.COMPLETED, analysisSubmissionCompleted.getAnalysisState());
assertEquals(AnalysisCleanedState.NOT_CLEANED, analysisSubmissionCompleted.getAnalysisCleanedState());
WorkflowDetails workflowDetails = workflowsClient.showWorkflow(analysisSubmissionCompleted
.getRemoteWorkflowId());
assertFalse("Workflow is already deleted", workflowDetails.isDeleted());
// Once analysis is complete, attempt to clean up
Future<AnalysisSubmission> analysisSubmissionCleanedFuture = analysisExecutionService
.cleanupSubmission(analysisSubmissionCompleted);
AnalysisSubmission analysisSubmissionCleaned = analysisSubmissionCleanedFuture.get();
assertEquals("Analysis submission not properly cleaned", AnalysisCleanedState.CLEANED,
analysisSubmissionCleaned.getAnalysisCleanedState());
workflowDetails = workflowsClient.showWorkflow(analysisSubmissionCompleted.getRemoteWorkflowId());
assertTrue("Workflow is not deleted", workflowDetails.isDeleted());
}
/**
* Tests out cleaning up an analysis in error successfully.
*
* @throws Exception
*/
@Test
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testCleanupErrorAnalysisSuccess() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
analysisSubmitted.setAnalysisState(AnalysisState.ERROR);
analysisSubmissionRepository.save(analysisSubmitted);
WorkflowDetails workflowDetails = workflowsClient.showWorkflow(analysisSubmitted.getRemoteWorkflowId());
assertFalse("Workflow is already deleted", workflowDetails.isDeleted());
// Once analysis is complete, attempt to clean up
Future<AnalysisSubmission> analysisSubmissionCleanedFuture = analysisExecutionService
.cleanupSubmission(analysisSubmitted);
AnalysisSubmission analysisSubmissionCleaned = analysisSubmissionCleanedFuture.get();
assertEquals("Analysis submission not properly cleaned", AnalysisCleanedState.CLEANED,
analysisSubmissionCleaned.getAnalysisCleanedState());
workflowDetails = workflowsClient.showWorkflow(analysisSubmitted.getRemoteWorkflowId());
assertTrue("Workflow is not deleted", workflowDetails.isDeleted());
}
/**
* Tests out cleaning up a new analysis and failing.
*
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testCleanupNewAnalysisError() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
analysisExecutionService.cleanupSubmission(analysisSubmitted);
}
/**
* Tests out cleaning up an analysis that's already been cleaned and
* failing.
*
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testCleanupCleanedAnalysisError() throws Exception {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
analysisSubmitted.setAnalysisState(AnalysisState.ERROR);
analysisSubmissionRepository.save(analysisSubmitted);
Future<AnalysisSubmission> analysisSubmissionCleanedFuture = analysisExecutionService
.cleanupSubmission(analysisSubmitted);
AnalysisSubmission cleanedSubmission = analysisSubmissionCleanedFuture.get();
analysisExecutionService.cleanupSubmission(cleanedSubmission);
}
/**
* Tests out cleaning up a completed analysis and failing due to a Galaxy
* exception.
*
* @throws Throwable
*/
@Test(expected = ExecutionManagerException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testCleanupCompletedAnalysisFailGalaxy() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
Future<AnalysisSubmission> analysisExecutionFuture = analysisExecutionService
.executeAnalysis(analysisSubmitted);
AnalysisSubmission analysisExecuted = analysisExecutionFuture.get();
analysisExecutionGalaxyITService.waitUntilSubmissionComplete(analysisExecuted);
analysisExecuted.setAnalysisState(AnalysisState.FINISHED_RUNNING);
Future<AnalysisSubmission> analysisSubmissionCompletedFuture = analysisExecutionService
.transferAnalysisResults(analysisExecuted);
AnalysisSubmission analysisSubmissionCompleted = analysisSubmissionCompletedFuture.get();
assertEquals(AnalysisState.COMPLETED, analysisSubmissionCompleted.getAnalysisState());
assertEquals(AnalysisCleanedState.NOT_CLEANED, analysisSubmissionCompleted.getAnalysisCleanedState());
analysisSubmissionCompleted.setRemoteAnalysisId("invalid");
analysisSubmissionRepository.save(analysisSubmissionCompleted);
// Once analysis is complete, attempt to clean up
Future<AnalysisSubmission> analysisSubmissionCleanedFuture = analysisExecutionService
.cleanupSubmission(analysisSubmissionCompleted);
try {
analysisSubmissionCleanedFuture.get();
fail("No exception thrown");
} catch (ExecutionException e) {
assertEquals("The AnalysisState was changed from COMPLETED", AnalysisState.COMPLETED,
analysisSubmissionService.read(analysisSubmission.getId()).getAnalysisState());
assertEquals("The AnalysisCleanedState was not changed to error", AnalysisCleanedState.CLEANING_ERROR,
analysisSubmissionService.read(analysisSubmission.getId()).getAnalysisCleanedState());
// pull out real exception
throw e.getCause();
}
}
/**
* Tests out cleaning up an analysis in error and failing due to an error in
* Galaxy.
*
* @throws Throwable
*/
@Test(expected = ExecutionManagerException.class)
@WithMockUser(username = "aaron", roles = "ADMIN")
public void testCleanupErrorAnalysisFailGalaxy() throws Throwable {
AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L,
sequenceFilePath, referenceFilePath, iridaTestAnalysisWorkflowId);
Future<AnalysisSubmission> analysisSubmittedFuture = analysisExecutionService
.prepareSubmission(analysisSubmission);
AnalysisSubmission analysisSubmitted = analysisSubmittedFuture.get();
analysisSubmitted.setAnalysisState(AnalysisState.ERROR);
analysisSubmitted.setRemoteWorkflowId("invalid");
analysisSubmissionRepository.save(analysisSubmitted);
// Once analysis is complete, attempt to clean up
Future<AnalysisSubmission> analysisSubmissionCleanedFuture = analysisExecutionService
.cleanupSubmission(analysisSubmitted);
try {
analysisSubmissionCleanedFuture.get();
fail("No exception thrown");
} catch (ExecutionException e) {
assertEquals("The AnalysisState was changed from ERROR", AnalysisState.ERROR, analysisSubmissionService
.read(analysisSubmission.getId()).getAnalysisState());
assertEquals("The AnalysisCleanedState was not changed to error", AnalysisCleanedState.CLEANING_ERROR,
analysisSubmissionService.read(analysisSubmission.getId()).getAnalysisCleanedState());
// pull out real exception
throw e.getCause();
}
}
}
|
package org.csstudio.trends.databrowser2;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import org.csstudio.csdata.ProcessVariable;
import org.csstudio.csdata.TimestampedPV;
import org.csstudio.trends.databrowser2.editor.DataBrowserEditor;
import org.csstudio.trends.databrowser2.model.ArchiveDataSource;
import org.csstudio.trends.databrowser2.model.ChannelInfo;
import org.csstudio.trends.databrowser2.model.Model;
import org.csstudio.trends.databrowser2.model.PVItem;
import org.csstudio.trends.databrowser2.preferences.Preferences;
import org.csstudio.ui.util.AdapterUtil;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.handlers.HandlerUtil;
/** Command handler for opening Data Browser on the current selection.
* Linked from popup menu that is sensitive to {@link ProcessVariable}
* @author Kay Kasemir
*/
public class OpenDataBrowserPopup extends AbstractHandler
{
final double period = Preferences.getScanPeriod();
/** {@inheritDoc} */
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException
{
// Get selection first because the ApplicationContext might change.
// This works for both context menu and double-clicks.
ISelection selection = HandlerUtil.getCurrentSelection(event);
// Create new editor
final DataBrowserEditor editor = DataBrowserEditor.createInstance();
if (editor == null)
return null;
// Add received items
final Model model = editor.getModel();
try
{
if (selection instanceof IStructuredSelection
&& ((IStructuredSelection)selection).getFirstElement() instanceof ChannelInfo)
{ // Received items are from search dialog
final Object channels[] = ((IStructuredSelection)selection).toArray();
for (Object channel : channels)
{
final ChannelInfo info = (ChannelInfo) channel;
add(model, info.getProcessVariable(), info.getArchiveDataSource());
}
}
else
{
// Add received PVs with default archive data sources
final List<TimestampedPV> timestampedPVs = Arrays
.asList(AdapterUtil.convert(selection,
TimestampedPV.class));
if (!timestampedPVs.isEmpty())
{
// Add received items, tracking their start..end time
long start_ms = Long.MAX_VALUE, end_ms = 0;
for (TimestampedPV timestampedPV : timestampedPVs)
{
final long time = timestampedPV.getTime();
if (time < start_ms)
start_ms = time;
if (time > end_ms)
end_ms = time;
final PVItem item = new PVItem(timestampedPV.getName().trim(), period);
item.setAxis(model.addAxis());
item.useDefaultArchiveDataSources();
model.addItem(item);
}
final Instant start = Instant.ofEpochMilli(start_ms).minus(Duration.ofMinutes(30));
final Instant end = Instant.ofEpochMilli(end_ms).plus(Duration.ofMinutes(30));
model.enableScrolling(false);
model.setTimerange(start, end);
}
else
{
final ProcessVariable[] pvs = AdapterUtil.convert(
selection, ProcessVariable.class);
for (ProcessVariable pv : pvs)
add(model, pv, null);
}
}
}
catch (Exception ex)
{
MessageDialog.openError(editor.getSite().getShell(),
Messages.Error,
NLS.bind(Messages.ErrorFmt, ex.getMessage()));
}
return null;
}
/** Add item
* @param model Model to which to add the item
* @param pv PV to add
* @param archive Archive to use or <code>null</code>
* @throws Exception on error
*/
private void add(final Model model, final ProcessVariable pv,
final ArchiveDataSource archive) throws Exception
{
final PVItem item = new PVItem(pv.getName(), period);
if (archive == null)
item.useDefaultArchiveDataSources();
else
item.addArchiveDataSource(archive);
// Add item to new axis
item.setAxis(model.addAxis());
model.addItem(item);
}
}
|
package org.csstudio.display.builder.representation.javafx.widgets;
import java.util.ArrayList;
import java.util.List;
import org.csstudio.display.builder.model.DirtyFlag;
import org.csstudio.display.builder.model.UntypedWidgetPropertyListener;
import org.csstudio.display.builder.model.WidgetProperty;
import org.csstudio.display.builder.model.WidgetPropertyListener;
import org.csstudio.display.builder.model.widgets.BaseLEDWidget;
import org.csstudio.display.builder.representation.javafx.JFXUtil;
import org.diirt.vtype.AlarmSeverity;
import org.diirt.vtype.VType;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Paint;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
/** Base for LED type widgets
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
abstract class BaseLEDRepresentation<LED extends BaseLEDWidget> extends RegionBaseRepresentation<Pane, LED>
{
private final DirtyFlag typeChanged = new DirtyFlag();
private final DirtyFlag styleChanged = new DirtyFlag();
protected final DirtyFlag dirty_content = new DirtyFlag();
private final UntypedWidgetPropertyListener styleChangedListener = this::styleChanged;
private final WidgetPropertyListener<VType> contentChangedListener = this::contentChanged;
private final WidgetPropertyListener<Boolean> typeChangedListener = this::typeChanged;
protected volatile Color[] colors = new Color[0];
protected volatile Paint value_color;
protected volatile String value_label;
/** Actual LED Ellipse or Rectangle inside {@link Pane} to allow for border */
private Shape led;
protected Label label;
@Override
public Pane createJFXNode() throws Exception
{
colors = createColors();
value_color = colors[0];
final Pane pane = new Pane();
// Avoid expensive Node.notifyParentOfBoundsChange()
pane.setManaged(false);
return pane;
}
private void createLED()
{
jfx_node.getChildren().clear();
if (model_widget.propSquare().getValue())
led = new Rectangle();
else
led = new Ellipse();
led.getStyleClass().add("led");
led.setManaged(false);
label = new Label();
label.getStyleClass().add("led_label");
label.setAlignment(Pos.CENTER);
label.setManaged(false);
jfx_node.getChildren().addAll(led, label);
}
@Override
public int[] getBorderRadii()
{
if (led instanceof Ellipse)
return new int[]
{
model_widget.propWidth().getValue()/2,
model_widget.propHeight().getValue()/2,
};
return super.getBorderRadii();
}
/** Create colors for the states of the LED
* @return Colors, must contain at least one element
*/
abstract protected Color[] createColors();
/** Compute the index of the currently active color
* @param value Current value
* @return Index 0, 1, .. to maximum index of array provided by <code>createColors</code>
*/
abstract protected int computeColorIndex(final VType value);
/** Compute the label for currently active color index
* @param color_index Color index returned by <code>computeColorIndex()</code>
* @return String to show in label
*/
abstract protected String computeLabel(final int color_index);
@Override
protected void registerListeners()
{
super.registerListeners();
model_widget.propSquare().addPropertyListener(typeChangedListener);
model_widget.propWidth().addUntypedPropertyListener(styleChangedListener);
model_widget.propHeight().addUntypedPropertyListener(styleChangedListener);
model_widget.propFont().addUntypedPropertyListener(styleChangedListener);
model_widget.propForegroundColor().addUntypedPropertyListener(styleChangedListener);
model_widget.propLineColor().addUntypedPropertyListener(styleChangedListener);
model_widget.runtimePropValue().addPropertyListener(contentChangedListener);
contentChanged(null, null, null);
}
@Override
protected void unregisterListeners()
{
model_widget.propSquare().removePropertyListener(typeChangedListener);
model_widget.propWidth().removePropertyListener(styleChangedListener);
model_widget.propHeight().removePropertyListener(styleChangedListener);
model_widget.propFont().removePropertyListener(styleChangedListener);
model_widget.propForegroundColor().removePropertyListener(styleChangedListener);
model_widget.propLineColor().removePropertyListener(styleChangedListener);
model_widget.runtimePropValue().removePropertyListener(contentChangedListener);
super.unregisterListeners();
}
private void typeChanged(final WidgetProperty<Boolean> property, final Boolean old_value, final Boolean new_value)
{
typeChanged.mark();
toolkit.scheduleUpdate(this);
}
private void styleChanged(final WidgetProperty<?> property, final Object old_value, final Object new_value)
{
styleChanged.mark();
toolkit.scheduleUpdate(this);
}
/** For derived class to invoke when color changed
* and current color needs to be re-evaluated
* @param property Ignored
* @param old_value Ignored
* @param new_value Ignored
*/
protected void configChanged(final WidgetProperty<?> property, final Object old_value, final Object new_value)
{
colors = createColors();
contentChanged(model_widget.runtimePropValue(), null, model_widget.runtimePropValue().getValue());
}
private void contentChanged(final WidgetProperty<VType> property, final VType old_value, final VType new_value)
{
final boolean editMode = toolkit.isEditMode();
final VType value = model_widget.runtimePropValue().getValue();
if (value == null && ! editMode)
{
value_color = alarm_colors[AlarmSeverity.UNDEFINED.ordinal()];
value_label = "";
}
else
{
int value_index = computeColorIndex(new_value);
final Color[] save_colors = colors;
if (value_index < 0)
value_index = 0;
if (value_index >= save_colors.length)
value_index = save_colors.length-1;
value_color = editMode ? editColor(save_colors) : save_colors[value_index];
value_label = computeLabel(value_index);
}
dirty_content.mark();
toolkit.scheduleUpdate(this);
}
private Paint editColor ( final Color[] save_colors ) {
List<Stop> stops = new ArrayList<>(2 * save_colors.length);
double offset = 1.0 / save_colors.length;
for ( int i = 0; i < save_colors.length; i++ ) {
stops.add(new Stop(i * offset, save_colors[i]));
stops.add(new Stop(( i + 1 ) * offset, save_colors[i]));
}
return new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
}
@Override
public void updateChanges()
{
if (typeChanged.checkAndClear())
{
createLED();
styleChanged.mark();
dirty_content.mark();
}
super.updateChanges();
if (styleChanged.checkAndClear())
{
final Color color = JFXUtil.convert(model_widget.propForegroundColor().getValue());
label.setTextFill(color);
label.setFont(JFXUtil.convert(model_widget.propFont().getValue()));
led.setStyle("-fx-stroke: " + JFXUtil.webRGB(model_widget.propLineColor().getValue()));
final int w = model_widget.propWidth().getValue();
final int h = model_widget.propHeight().getValue();
jfx_node.resize(w, h);
if (led instanceof Ellipse)
{
final Ellipse ell = (Ellipse) led;
ell.setCenterX(w/2);
ell.setCenterY(h/2);
ell.setRadiusX(w/2);
ell.setRadiusY(h/2);
}
else if (led instanceof Rectangle)
{
final Rectangle rect = (Rectangle) led;
rect.setWidth(w);
rect.setHeight(h);
}
label.resize(w, h);
}
if (dirty_content.checkAndClear())
{
led.setFill(value_color);
if (! value_label.equals(label.getText()))
{
label.setText(value_label);
label.layout();
}
}
}
}
|
package org.apereo.cas.support.oauth.authenticator;
import lombok.val;
import org.apereo.cas.authentication.principal.NullPrincipal;
import org.apereo.cas.authentication.principal.PrincipalResolver;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.support.oauth.OAuth20GrantTypes;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.RetryingTest;
import org.pac4j.core.context.JEEContext;
import org.pac4j.core.context.session.JEESessionStore;
import org.pac4j.core.credentials.UsernamePasswordCredentials;
import org.pac4j.core.credentials.authenticator.Authenticator;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.util.AopTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* This is {@link OAuth20ClientIdClientSecretAuthenticatorTests}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@Tag("OAuth")
@DirtiesContext
public class OAuth20ClientIdClientSecretAuthenticatorTests extends BaseOAuth20AuthenticatorTests {
@Autowired
private Authenticator oAuthClientAuthenticator;
@RetryingTest(3)
public void verifyAuthentication() {
val credentials = new UsernamePasswordCredentials("client", "secret");
val request = new MockHttpServletRequest();
val ctx = new JEEContext(request, new MockHttpServletResponse());
oAuthClientAuthenticator.validate(credentials, ctx, JEESessionStore.INSTANCE);
assertNotNull(credentials.getUserProfile());
assertEquals("client", credentials.getUserProfile().getId());
}
@Test
public void verifyAuthenticationWithGrantTypePassword() {
val credentials = new UsernamePasswordCredentials("client", "secret");
val request = new MockHttpServletRequest();
val ctx = new JEEContext(request, new MockHttpServletResponse());
request.addParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.PASSWORD.name());
oAuthClientAuthenticator.validate(credentials, ctx, JEESessionStore.INSTANCE);
assertNull(credentials.getUserProfile());
}
@Test
public void verifyAuthenticationWithGrantTypeRefreshToken() {
val refreshToken = getRefreshToken(serviceWithoutSecret);
ticketRegistry.addTicket(refreshToken);
val credentials = new UsernamePasswordCredentials("serviceWithoutSecret", refreshToken.getId());
val request = new MockHttpServletRequest();
val ctx = new JEEContext(request, new MockHttpServletResponse());
request.addParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name());
request.addParameter(OAuth20Constants.CLIENT_ID, "serviceWithoutSecret");
request.addParameter(OAuth20Constants.REFRESH_TOKEN, refreshToken.getId());
val oAuth20ClientIdClientSecretAuthenticator = (OAuth20ClientIdClientSecretAuthenticator) AopTestUtils.getTargetObject(oAuthClientAuthenticator);
assertNotNull(oAuth20ClientIdClientSecretAuthenticator);
assertFalse(oAuth20ClientIdClientSecretAuthenticator.canAuthenticate(ctx));
oAuth20ClientIdClientSecretAuthenticator.validate(credentials, ctx, JEESessionStore.INSTANCE);
assertNull(credentials.getUserProfile());
request.removeAllParameters();
request.addParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name());
request.addParameter(OAuth20Constants.REFRESH_TOKEN, refreshToken.getId());
assertTrue(oAuth20ClientIdClientSecretAuthenticator.canAuthenticate(ctx));
request.removeAllParameters();
request.addParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name());
request.addParameter(OAuth20Constants.CLIENT_ID, "serviceWithoutSecret");
request.addParameter(OAuth20Constants.CLIENT_SECRET, "serviceWithoutSecret");
request.addParameter(OAuth20Constants.REFRESH_TOKEN, refreshToken.getId());
assertTrue(oAuth20ClientIdClientSecretAuthenticator.canAuthenticate(ctx));
}
@Test
public void verifyAuthenticationWithAttributesMapping() {
val credentials = new UsernamePasswordCredentials("serviceWithAttributesMapping", "secret");
val request = new MockHttpServletRequest();
val ctx = new JEEContext(request, new MockHttpServletResponse());
oAuthClientAuthenticator.validate(credentials, ctx, JEESessionStore.INSTANCE);
assertNotNull(credentials.getUserProfile());
assertEquals("servicewithattributesmapping", credentials.getUserProfile().getId());
assertNotNull(credentials.getUserProfile().getAttribute("eduPersonAffiliation"));
assertNull(credentials.getUserProfile().getAttribute("groupMembership"));
}
@Import(TestConfigForNullPrincipalResolution.class)
@SuppressWarnings("ClassCanBeStatic")
@Nested
public class OAuth20ClientIdClientSecretAuthenticatorNullPrincipalTests {
@Autowired
private Authenticator oAuthClientAuthenticator;
@Autowired
@Qualifier("servicesManager")
private ObjectProvider<ServicesManager> servicesManager;
@Test
public void verifyAuthenticationWithoutResolvedPrincipal() {
val id = "serviceWithAttributesMapping";
val credentials = new UsernamePasswordCredentials(id, "secret");
val service = new OAuthRegisteredService();
service.setClientId(id);
servicesManager.getObject().save(service);
val request = new MockHttpServletRequest();
val ctx = new JEEContext(request, new MockHttpServletResponse());
oAuthClientAuthenticator.validate(credentials, ctx, JEESessionStore.INSTANCE);
assertNotNull(credentials.getUserProfile());
assertEquals(id, credentials.getUserProfile().getId());
}
}
@TestConfiguration
public static class TestConfigForNullPrincipalResolution {
@Bean
public PrincipalResolver defaultPrincipalResolver() {
PrincipalResolver mockPrincipalResolver = mock(PrincipalResolver.class);
when(mockPrincipalResolver.resolve(any())).thenReturn(new NullPrincipal());
return mockPrincipalResolver;
}
}
}
|
package org.eclipse.birt.report.item.crosstab.internal.ui.dialogs;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.aggregation.AggregationManager;
import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction;
import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.CubeQueryUtil;
import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil;
import org.eclipse.birt.report.data.adapter.api.DataRequestSession;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter.ExpressionLocation;
import org.eclipse.birt.report.data.adapter.api.timeFunction.IArgumentInfo;
import org.eclipse.birt.report.data.adapter.api.timeFunction.IArgumentInfo.Period_Type;
import org.eclipse.birt.report.data.adapter.api.timeFunction.ITimeFunction;
import org.eclipse.birt.report.data.adapter.api.timeFunction.TimeFunctionManager;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.data.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.dialogs.AbstractBindingDialogHelper;
import org.eclipse.birt.report.designer.internal.ui.dialogs.ResourceEditDialog;
import org.eclipse.birt.report.designer.internal.ui.dialogs.expression.ExpressionButton;
import org.eclipse.birt.report.designer.internal.ui.swt.custom.CLabel;
import org.eclipse.birt.report.designer.internal.ui.util.ExpressionButtonUtil;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages;
import org.eclipse.birt.report.designer.ui.dialogs.IExpressionProvider;
import org.eclipse.birt.report.designer.ui.util.ExceptionUtil;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.ColorManager;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.ComputedMeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.core.util.CrosstabUtil;
import org.eclipse.birt.report.item.crosstab.internal.ui.editors.model.CrosstabAdaptUtil;
import org.eclipse.birt.report.model.api.AggregationArgumentHandle;
import org.eclipse.birt.report.model.api.CalculationArgumentHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.ExpressionHandle;
import org.eclipse.birt.report.model.api.ExpressionType;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument;
import org.eclipse.birt.report.model.api.elements.structures.CalculationArgument;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.extension.ExtendedElementException;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.MeasureGroupHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
import org.eclipse.birt.report.model.elements.interfaces.ICubeModel;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
public class CrosstabBindingDialogHelper extends AbstractBindingDialogHelper
{
protected static final String NAME = Messages.getString( "BindingDialogHelper.text.Name" ); //$NON-NLS-1$
protected static final String DATA_TYPE = Messages.getString( "BindingDialogHelper.text.DataType" ); //$NON-NLS-1$
protected static final String FUNCTION = Messages.getString( "BindingDialogHelper.text.Function" ); //$NON-NLS-1$
protected static final String DATA_FIELD = Messages.getString( "BindingDialogHelper.text.DataField" ); //$NON-NLS-1$
protected static final String FILTER_CONDITION = Messages.getString( "BindingDialogHelper.text.Filter" ); //$NON-NLS-1$
protected static final String AGGREGATE_ON = Messages.getString( "BindingDialogHelper.text.AggOn" ); //$NON-NLS-1$
protected static final String EXPRESSION = Messages.getString( "BindingDialogHelper.text.Expression" ); //$NON-NLS-1$
protected static final String ALL = Messages.getString( "CrosstabBindingDialogHelper.AggOn.All" ); //$NON-NLS-1$
protected static final String DISPLAY_NAME = Messages.getString( "BindingDialogHelper.text.displayName" ); //$NON-NLS-1$
protected static final String DISPLAY_NAME_ID = Messages.getString( "BindingDialogHelper.text.displayNameID" ); //$NON-NLS-1$
protected static final String DEFAULT_ITEM_NAME = Messages.getString( "BindingDialogHelper.bindingName.dataitem" ); //$NON-NLS-1$
protected static final String DEFAULT_AGGREGATION_NAME = Messages.getString( "BindingDialogHelper.bindingName.aggregation" ); //$NON-NLS-1$
private static final String DEFAULT_TIMEPERIOD_NAME = Messages.getString( "CrosstabBindingDialogHelper.bindngName.timeperiod" ); //$NON-NLS-1$
private static final String CALCULATION_TYPE = Messages.getString( "CrosstabBindingDialogHelper.calculation.labe" ); //$NON-NLS-1$
private static final String EMPTY_STRING = ""; //$NON-NLS-1$
protected static final IChoiceSet DATA_TYPE_CHOICE_SET = DEUtil.getMetaDataDictionary( )
.getStructure( ComputedColumn.COMPUTED_COLUMN_STRUCT )
.getMember( ComputedColumn.DATA_TYPE_MEMBER )
.getAllowedChoices( );
protected static final IChoice[] DATA_TYPE_CHOICES = DATA_TYPE_CHOICE_SET.getChoices( null );
protected String[] dataTypes = ChoiceSetFactory.getDisplayNamefromChoiceSet( DATA_TYPE_CHOICE_SET );
private Text txtName, txtFilter, txtExpression;
private Text dateText;
private Combo cmbType, cmbFunction, cmbAggOn, calculationType,
timeDimension;
private Composite paramsComposite, calculationComposite;
private Map<String, Control> paramsMap = new HashMap<String, Control>( );
private Map<String, String> paramsValueMap = new HashMap<String, String>( );
private Composite composite;
private Text txtDisplayName, txtDisplayNameID;
private ComputedColumn newBinding;
private CLabel messageLine;
private Label lbName, lbDisplayNameID;
private Object container;
private Button btnDisplayNameID, btnRemoveDisplayNameID;
private List<ITimeFunction> times;
private Button todayButton, dateSelectionButton, recentButton;
private Label recentLabel;
private Map<String, Control> calculationParamsMap = new HashMap<String, Control>( );
private Map<String, String> calculationParamsValueMap = new HashMap<String, String>( );
private boolean isStatic = true;
public void createContent( Composite parent )
{
composite = parent;
( (GridLayout) composite.getLayout( ) ).numColumns = 4;
lbName = new Label( composite, SWT.NONE );
lbName.setText( NAME );
txtName = new Text( composite, SWT.BORDER );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
gd.widthHint = 250;
txtName.setLayoutData( gd );
// WidgetUtil.createGridPlaceholder( composite, 1, false );
txtName.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
}
} );
lbDisplayNameID = new Label( composite, SWT.NONE );
lbDisplayNameID.setText( DISPLAY_NAME_ID );
lbDisplayNameID.addTraverseListener( new TraverseListener( ) {
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_MNEMONIC && e.doit )
{
e.detail = SWT.TRAVERSE_NONE;
if ( btnDisplayNameID.isEnabled( ) )
{
openKeySelectionDialog( );
}
}
}
} );
txtDisplayNameID = new Text( composite, SWT.BORDER | SWT.READ_ONLY );
txtDisplayNameID.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
}
} );
txtDisplayNameID.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
btnDisplayNameID = new Button( composite, SWT.NONE );
btnDisplayNameID.setEnabled( getAvailableResourceUrls( ) != null
&& getAvailableResourceUrls( ).length > 0 ? true : false );
btnDisplayNameID.setText( "..." ); //$NON-NLS-1$
btnDisplayNameID.setToolTipText( Messages.getString( "ResourceKeyDescriptor.button.browse.tooltip" ) ); //$NON-NLS-1$
btnDisplayNameID.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
openKeySelectionDialog( );
}
} );
btnRemoveDisplayNameID = new Button( composite, SWT.NONE );
btnRemoveDisplayNameID.setImage( ReportPlatformUIImages.getImage( ISharedImages.IMG_TOOL_DELETE ) );
btnRemoveDisplayNameID.setToolTipText( Messages.getString( "ResourceKeyDescriptor.button.reset.tooltip" ) ); //$NON-NLS-1$
btnRemoveDisplayNameID.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
txtDisplayNameID.setText( EMPTY_STRING );
txtDisplayName.setText( EMPTY_STRING );
updateRemoveBtnState( );
}
} );
new Label( composite, SWT.NONE ).setText( DISPLAY_NAME );
txtDisplayName = new Text( composite, SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
txtDisplayName.setLayoutData( gd );
txtDisplayName.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
}
} );
// WidgetUtil.createGridPlaceholder( composite, 1, false );
new Label( composite, SWT.NONE ).setText( DATA_TYPE );
cmbType = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
cmbType.setLayoutData( gd );
cmbType.setVisibleItemCount( 30 );
cmbType.addSelectionListener( new SelectionListener( ) {
public void widgetDefaultSelected( SelectionEvent arg0 )
{
validate( );
}
public void widgetSelected( SelectionEvent arg0 )
{
modifyDialogContent( );
validate( );
}
} );
if ( isTimePeriod( ) )
{
createCalculationSelection( composite );
}
// WidgetUtil.createGridPlaceholder( composite, 1, false );
if ( isAggregate( ) )
{
createAggregateSection( composite );
}
else
{
createCommonSection( composite );
}
if ( isTimePeriod( ) )
{
new Label( composite, SWT.NONE ).setText( Messages.getString( "CrosstabBindingDialogHelper.timedimension.label" ) ); //$NON-NLS-1$
timeDimension = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
timeDimension.setLayoutData( gd );
timeDimension.setVisibleItemCount( 30 );
timeDimension.addSelectionListener( new SelectionListener( ) {
public void widgetDefaultSelected( SelectionEvent arg0 )
{
validate( );
}
public void widgetSelected( SelectionEvent arg0 )
{
handleTimeDimensionSelectEvent( );
modifyDialogContent( );
validate( );
}
} );
createDataSelection( composite );
}
createMessageSection( composite );
gd = new GridData( GridData.FILL_BOTH );
composite.setLayoutData( gd );
setContentSize( composite );
}
private void createDataSelection( Composite composite )
{
Label referDataLabel = new Label( composite, SWT.NONE );
referDataLabel.setText( Messages.getString( "CrosstabBindingDialogHelper.referencedate.label" ) ); //$NON-NLS-1$
GridData gd = new GridData( );
gd.verticalAlignment = SWT.BEGINNING;
referDataLabel.setLayoutData( gd );
Composite radioContainer = new Composite( composite, SWT.NONE );
GridLayout layout = new GridLayout( );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
radioContainer.setLayoutData( gd );
layout = new GridLayout( );
layout.marginWidth = layout.marginHeight = 0;
layout.numColumns = 2;
radioContainer.setLayout( layout );
todayButton = new Button( radioContainer, SWT.RADIO );
todayButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
if ( !isStatic )
{
isStatic = true;
initCalculationTypeCombo( getTimeDimsionName( ) );
}
modifyDialogContent( );
validate( );
}
} );
new Label( radioContainer, SWT.NONE ).setText( Messages.getString( "CrosstabBindingDialogHelper.today.label" ) ); //$NON-NLS-1$
dateSelectionButton = new Button( radioContainer, SWT.RADIO );
dateSelectionButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
if ( !isStatic )
{
isStatic = true;
initCalculationTypeCombo( getTimeDimsionName( ) );
}
modifyDialogContent( );
validate( );
}
} );
Composite dateContainer = new Composite( radioContainer, SWT.NONE );
dateContainer.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
layout = new GridLayout( );
layout.marginWidth = layout.marginHeight = 0;
layout.numColumns = 3;
dateContainer.setLayout( layout );
new Label( dateContainer, SWT.NONE ).setText( Messages.getString( "CrosstabBindingDialogHelper.thisdate.label" ) ); //$NON-NLS-1$
Composite dateSelecionContainer = new Composite( dateContainer,
SWT.NONE );
dateSelecionContainer.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
layout = new GridLayout( );
layout.marginWidth = layout.marginHeight = 0;
layout.horizontalSpacing = 0;
layout.numColumns = 3;
dateSelecionContainer.setLayout( layout );
dateText = new Text( dateSelecionContainer, SWT.BORDER );
dateText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
}
} );
dateText.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
if ( expressionProvider == null )
{
if ( isAggregate( ) )
expressionProvider = new CrosstabAggregationExpressionProvider( this.bindingHolder,
this.binding );
else
expressionProvider = new CrosstabBindingExpressionProvider( this.bindingHolder,
this.binding );
}
ExpressionButton button = ExpressionButtonUtil.createExpressionButton( dateSelecionContainer,
dateText,
expressionProvider,
this.bindingHolder,
true,
SWT.PUSH );
dateText.setData( ExpressionButtonUtil.EXPR_TYPE,
ExpressionType.CONSTANT );
button.refresh( );
new Label(radioContainer, SWT.NONE);
Label dateFormatLbl = new Label( radioContainer, SWT.NONE );
dateFormatLbl.setText(Messages.getString("CrosstabBindingDialogHelper.thisdate.example.label")); //$NON-NLS-1$
dateFormatLbl.setForeground( ColorManager.getColor( 128, 128, 128 ) );
dateFormatLbl.setLayoutData( new GridData(GridData.FILL_HORIZONTAL));
recentButton = new Button( radioContainer, SWT.RADIO );
recentButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
if ( isStatic )
{
isStatic = false;
initCalculationTypeCombo( getTimeDimsionName( ) );
}
modifyDialogContent( );
validate( );
}
} );
recentLabel = new Label( radioContainer, SWT.NONE );
recentLabel.setText( Messages.getString( "CrosstabBindingDialogHelper.recentday.description" ) ); //$NON-NLS-1$
}
private void handleTimeDimensionSelectEvent( )
{
String dimensionName = getTimeDimsionName( );
initCalculationTypeCombo( dimensionName );
boolean inUseDimsion = isUseDimension( dimensionName );
if ( inUseDimsion )
{
recentButton.setEnabled( true );
recentLabel.setEnabled( true );
}
else
{
recentButton.setEnabled( false );
recentLabel.setEnabled( false );
}
}
private boolean isUseDimension( String dimensionName )
{
boolean inUseDimsion = false;
CrosstabReportItemHandle crosstab = getCrosstabReportItemHandle( );
int count = crosstab.getDimensionCount( ICrosstabConstants.COLUMN_AXIS_TYPE );
for ( int i = 0; i < count; i++ )
{
if ( crosstab.getDimension( ICrosstabConstants.COLUMN_AXIS_TYPE, i )
.getCubeDimensionName( )
.equals( dimensionName ) )
{
inUseDimsion = true;
}
}
count = crosstab.getDimensionCount( ICrosstabConstants.ROW_AXIS_TYPE );
for ( int i = 0; i < count; i++ )
{
if ( crosstab.getDimension( ICrosstabConstants.ROW_AXIS_TYPE, i )
.getCubeDimensionName( )
.equals( dimensionName ) )
{
inUseDimsion = true;
}
}
return inUseDimsion;
}
private void initCalculationTypeCombo( String dimensionName )
{
DimensionHandle handle = getCrosstabReportItemHandle( ).getCube( )
.getDimension( dimensionName );
String cal = calculationType.getText( );
isStatic = true;
if ( recentButton.getSelection( ) )
{
isStatic = false;
}
times = TimeFunctionManager.getCalculationTypes( handle,
getUseLevels( dimensionName ),
isStatic );
String[] items = new String[times.size( )];
String[] names = new String[times.size( )];
for ( int i = 0; i < times.size( ); i++ )
{
items[i] = times.get( i ).getDisplayName( );
names[i] = times.get( i ).getName( );
}
calculationType.setItems( items );
if ( getBinding( ) == null )
{
if ( cal != null && getItemIndex( items, cal ) >= 0 )
{
calculationType.select( getItemIndex( items, cal ) );
}
else
{
calculationType.select( 0 );
}
handleCalculationSelectEvent( );
}
else
{
if ( cal != null && getItemIndex( items, cal ) >= 0 )
{
calculationType.select( getItemIndex( items, cal ) );
}
else
{
ITimeFunction function = getTimeFunctionByDisplaName( getBinding( ).getCalculationType( ) );
String name = function.getName( );
int itemIndex = getItemIndex( names, name );
if ( itemIndex >= 0 )
{
calculationType.select( itemIndex );
}
else
{
calculationType.select( 0 );
}
}
handleCalculationSelectEvent( );
ITimeFunction function = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) );
List<IArgumentInfo> infos = function.getArguments( );
for ( int i = 0; i < infos.size( ); i++ )
{
String argName = infos.get( i ).getName( );
String argValue = calculationParamsValueMap.get( argName );
if ( calculationParamsMap.containsKey( argName ) )
{
if ( getArgumentValue( getBinding( ), argName ) != null )
{
Control control = calculationParamsMap.get( argName );
ExpressionHandle obj = (ExpressionHandle) getArgumentValue( getBinding( ),
argName );
if ( infos.get( i ).getPeriodChoices( ) == null
|| infos.get( i ).getPeriodChoices( ).isEmpty( ) )
{
initExpressionButtonControl( control, obj );
}
else
{
// Period_Type type = (Period_Type)obj;
Combo combo = (Combo) control;
String str = obj.getStringExpression( );
if ( str == null || str.length( ) == 0 )
{
combo.select( 0 );
}
else
{
int comboIndex = getItemIndex( combo.getItems( ),
str );
if ( comboIndex >= 0 )
{
combo.select( comboIndex );
}
else
{
combo.select( 0 );
}
}
}
// restore arg value
if ( control instanceof Text && argValue != null )
{
((Text)control).setText(argValue);
}
}
}
}
// init args
}
}
private static ExpressionButton getExpressionButton( Control control )
{
Object button = control.getData( ExpressionButtonUtil.EXPR_BUTTON );
if ( button instanceof ExpressionButton )
{
return ( (ExpressionButton) button );
}
return null;
}
public static void initExpressionButtonControl( Control control,
ExpressionHandle value )
{
ExpressionButton button = getExpressionButton( control );
if ( button != null && button.getExpressionHelper( ) != null )
{
button.getExpressionHelper( ).setExpressionType( value == null
|| value.getType( ) == null ? UIUtil.getDefaultScriptType( )
: (String) value.getType( ) );
String stringValue = value == null
|| value.getExpression( ) == null ? "" : (String) value.getExpression( ); //$NON-NLS-1$
button.getExpressionHelper( ).setExpression( stringValue );
button.refresh( );
}
}
private List<String> getUseLevels( String dimensionName )
{
List<String> retValue = new ArrayList<String>( );
DimensionViewHandle viewHandle = getCrosstabReportItemHandle( ).getDimension( dimensionName );
if ( viewHandle == null )
{
return retValue;
}
int count = viewHandle.getLevelCount( );
for ( int i = 0; i < count; i++ )
{
LevelViewHandle levelHandle = viewHandle.getLevel( i );
retValue.add( levelHandle.getCubeLevel( ).getName( ) );
}
return retValue;
}
private CrosstabReportItemHandle getCrosstabReportItemHandle( )
{
try
{
return (CrosstabReportItemHandle) ( ( (ExtendedItemHandle) bindingHolder ).getReportItem( ) );
}
catch ( ExtendedElementException e )
{
return null;
}
}
private Object getArgumentValue( ComputedColumnHandle handle, String name )
{
Iterator iter = handle.calculationArgumentsIterator( );
while ( iter.hasNext( ) )
{
CalculationArgumentHandle argument = (CalculationArgumentHandle) iter.next( );
if ( name.equals( argument.getName( ) ) )
{
return argument.getValue( );
}
}
return null;
}
private String getTimeDimsionName( )
{
String dimensionName = timeDimension.getText( );
return dimensionName;
// Set<IDimLevel> sets;
// try
// sets = ExpressionUtil.getReferencedDimLevel( dimensionName );
// catch ( CoreException e )
// return null;
// Iterator<IDimLevel> iter = sets.iterator( );
// if ( iter.hasNext( ) )
// return iter.next( ).getDimensionName( );
// return null;
}
private void createCalculationSelection( Composite composite )
{
new Label( composite, SWT.NONE ).setText( CALCULATION_TYPE );
calculationType = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
calculationType.setLayoutData( gd );
calculationType.setVisibleItemCount( 30 );
calculationType.addSelectionListener( new SelectionListener( ) {
public void widgetDefaultSelected( SelectionEvent arg0 )
{
validate( );
}
public void widgetSelected( SelectionEvent arg0 )
{
handleCalculationSelectEvent( );
modifyDialogContent( );
validate( );
}
} );
calculationComposite = new Composite( composite, SWT.NONE );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.horizontalSpan = 4;
gridData.exclude = true;
calculationComposite.setLayoutData( gridData );
GridLayout layout = new GridLayout( );
// layout.horizontalSpacing = layout.verticalSpacing = 0;
layout.marginWidth = layout.marginHeight = 0;
layout.numColumns = 4;
Layout parentLayout = calculationComposite.getParent( ).getLayout( );
if ( parentLayout instanceof GridLayout )
layout.horizontalSpacing = ( (GridLayout) parentLayout ).horizontalSpacing;
calculationComposite.setLayout( layout );
}
private void handleCalculationSelectEvent( )
{
Control[] children = calculationComposite.getChildren( );
for ( int i = 0; i < children.length; i++ )
{
children[i].dispose( );
}
ITimeFunction function = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) );
if ( function == null )
{
( (GridData) calculationComposite.getLayoutData( ) ).heightHint = 0;
( (GridData) calculationComposite.getLayoutData( ) ).exclude = true;
calculationComposite.setVisible( false );
}
else
{
calculationParamsMap.clear( );
List<IArgumentInfo> infos = function.getArguments( );
if ( infos == null || infos.size( ) == 0 )
{
( (GridData) calculationComposite.getLayoutData( ) ).heightHint = 0;
( (GridData) calculationComposite.getLayoutData( ) ).exclude = true;
calculationComposite.setVisible( false );
}
else
{
( (GridData) calculationComposite.getLayoutData( ) ).exclude = false;
( (GridData) calculationComposite.getLayoutData( ) ).heightHint = SWT.DEFAULT;
calculationComposite.setVisible( true );
int width = 0;
if ( calculationComposite.getParent( ).getLayout( ) instanceof GridLayout )
{
Control[] controls = calculationComposite.getParent( )
.getChildren( );
for ( int i = 0; i < controls.length; i++ )
{
if ( controls[i] instanceof Label
&& ( (GridData) controls[i].getLayoutData( ) ).horizontalSpan == 1 )
{
int labelWidth = controls[i].getBounds( ).width
- controls[i].getBorderWidth( )
* 2;
if ( labelWidth > width )
width = labelWidth;
}
}
}
for ( int i = 0; i < infos.size( ); i++ )
{
final String name = infos.get( i ).getName( );
Label lblParam = new Label( calculationComposite, SWT.NONE );
lblParam.setText( infos.get( i ).getDisplayName( ) + ":" ); //$NON-NLS-1$
//if ( !infos.get( i ).isOptional( ) )
// lblParam.setText( "*" + lblParam.getText( ) );
GridData gd = new GridData( );
gd.widthHint = lblParam.computeSize( SWT.DEFAULT,
SWT.DEFAULT ).x;
if ( gd.widthHint < width )
gd.widthHint = width;
lblParam.setLayoutData( gd );
final List<Period_Type> types = infos.get( i )
.getPeriodChoices( );
if ( types != null && types.size( ) > 0 )
{
final Combo cmbDataField = new Combo( calculationComposite,
SWT.BORDER | SWT.READ_ONLY );
cmbDataField.setLayoutData( GridDataFactory.fillDefaults( )
.grab( true, false )
.span( 3, 1 )
.create( ) );
cmbDataField.setVisibleItemCount( 30 );
initCalculationDataFields( cmbDataField, name, types );
cmbDataField.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
calculationParamsValueMap.put( name,
cmbDataField.getText( ) );
}
} );
calculationParamsMap.put( name, cmbDataField );
}
else
{
final Text txtParam = new Text( calculationComposite,
SWT.BORDER );
initCalculationTextFild( txtParam, name );
txtParam.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
calculationParamsValueMap.put( name,
txtParam.getText( ) );
}
} );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.horizontalIndent = 0;
gridData.horizontalSpan = 2;
txtParam.setLayoutData( gridData );
createExpressionButton( calculationComposite, txtParam );
calculationParamsMap.put( name, txtParam );
}
}
}
}
composite.layout( true, true );
setContentSize( composite );
}
private void initCalculationTextFild( Text txtParam, String name )
{
if ( calculationParamsValueMap.containsKey( name ) )
{
txtParam.setText( calculationParamsValueMap.get( name ) );
return;
}
}
private void initCalculationDataFields( Combo cmbDataField, String name,
List<Period_Type> list )
{
String[] strs = new String[list.size( )];
for ( int i = 0; i < list.size( ); i++ )
{
strs[i] = list.get( i ).displayName( );
}
cmbDataField.setItems( strs );
if ( calculationParamsValueMap.containsKey( name ) )
{
cmbDataField.setText( calculationParamsValueMap.get( name ) );
return;
}
cmbDataField.select( 0 );
}
private ITimeFunction getTimeFunctionByIndex( int index )
{
if ( times == null )
{
return null;
}
if ( index < 0 || index >= times.size( ) )
{
return null;
}
return times.get( index );
}
private ITimeFunction getTimeFunctionByDisplaName( String name )
{
if ( times == null )
{
return null;
}
for ( int i = 0; i < times.size( ); i++ )
{
if ( times.get( i ).getName( ).equals( name ) )
{
return times.get( i );
}
}
return null;
}
private void openKeySelectionDialog( )
{
ResourceEditDialog dlg = new ResourceEditDialog( composite.getShell( ),
Messages.getString( "ResourceKeyDescriptor.title.SelectKey" ) ); //$NON-NLS-1$
dlg.setResourceURLs( getResourceURLs( ) );
if ( dlg.open( ) == Window.OK )
{
String[] result = (String[]) dlg.getDetailResult( );
txtDisplayNameID.setText( result[0] );
txtDisplayName.setText( result[1] );
updateRemoveBtnState( );
}
}
private boolean hasInitDialog = false;
public void initDialog( )
{
cmbType.setItems( dataTypes );
txtDisplayName.setFocus( );
if ( isAggregate( ) )
{
initFunction( );
initFilter( );
// if (!isTimePeriod( ))
{
initAggOn( );
}
}
if ( isTimePeriod( ) )
{
initTimeDimension( );
initReferenceDate( );
initCalculationTypeCombo( getTimeDimsionName( ) );
}
if ( getBinding( ) == null )// create
{
if ( cmbType.getSelectionIndex( ) < 0 )
{
setTypeSelect( dataTypes[0] );
}
if ( isTimePeriod( ) )
{
this.newBinding = StructureFactory.newComputedColumn( getBindingHolder( ),
DEFAULT_TIMEPERIOD_NAME );
}
else
{
this.newBinding = StructureFactory.newComputedColumn( getBindingHolder( ),
isAggregate( ) ? DEFAULT_AGGREGATION_NAME
: DEFAULT_ITEM_NAME );
}
setName( this.newBinding.getName( ) );
}
else
{
setName( getBinding( ).getName( ) );
setDisplayName( getBinding( ).getDisplayName( ) );
setDisplayNameID( getBinding( ).getDisplayNameID( ) );
if ( getBinding( ).getDataType( ) != null )
if ( DATA_TYPE_CHOICE_SET.findChoice( getBinding( ).getDataType( ) ) != null )
setTypeSelect( DATA_TYPE_CHOICE_SET.findChoice( getBinding( ).getDataType( ) )
.getDisplayName( ) );
else
cmbType.setText( "" ); //$NON-NLS-1$
if ( getBinding( ).getExpression( ) != null )
setDataFieldExpression( getBinding( ) );
}
if ( this.getBinding( ) != null )
{
this.txtName.setEnabled( false );
}
validate( );
hasInitDialog = true;
composite.getShell( ).pack( );
}
private void initReferenceDate( )
{
String dimensionName = getTimeDimsionName( );
boolean inUseDimsion = isUseDimension( dimensionName );
if ( getBinding( ) == null ) // new Relative Time Period
{
ExtendedItemHandle handle = (ExtendedItemHandle) getBindingHolder( ) ;
List<ComputedColumnHandle> dimensionHandle = new ArrayList();
for (Iterator<ComputedColumnHandle> iter = handle.columnBindingsIterator(); iter.hasNext();)
{
ComputedColumnHandle cHandle = iter.next();
if (cHandle.getTimeDimension() != null && !cHandle.getTimeDimension().equals(EMPTY_STRING))
{
dimensionHandle.add(0, cHandle);
}
}
if(0 == dimensionHandle.size() || !setRefDate(dimensionHandle.get(0), inUseDimsion))
{
todayButton.setSelection( true );
}
}
else // edit Relative Time Period
{
setRefDate(getBinding(), inUseDimsion);
}
if ( inUseDimsion )
{
recentButton.setEnabled( true );
recentLabel.setEnabled( true );
}
else
{
recentButton.setEnabled( false );
recentLabel.setEnabled( false );
}
}
private boolean setRefDate (ComputedColumnHandle handle, boolean inUseDimsion)
{
String type = handle.getReferenceDateType( );
if (type == null)
return false;
if ( DesignChoiceConstants.REFERENCE_DATE_TYPE_TODAY.equals( type ) )
{
todayButton.setSelection( true );
return true;
}
else if ( DesignChoiceConstants.REFERENCE_DATE_TYPE_FIXED_DATE.equals( type ) )
{
dateSelectionButton.setSelection( true );
ExpressionHandle value = handle.getReferenceDateValue( );
dateText.setText( value == null
|| value.getExpression( ) == null ? "" : (String) value.getExpression( ) ); //$NON-NLS-1$
dateText.setData( ExpressionButtonUtil.EXPR_TYPE, value == null
|| value.getType( ) == null ? ExpressionType.CONSTANT
: (String) value.getType( ) );
ExpressionButton button = (ExpressionButton) dateText.getData( ExpressionButtonUtil.EXPR_BUTTON );
if ( button != null )
button.refresh( );
return true;
}
else if ( DesignChoiceConstants.REFERENCE_DATE_TYPE_ENDING_DATE_IN_DIMENSION.equals( type ) )
{
if(getBinding() == null && !inUseDimsion )
{
return false;
}
else
{
recentButton.setSelection( true );
return true;
}
}
return false;
}
private void initTimeDimension( )
{
String[] strs = getTimeDimensions( );
timeDimension.setItems( strs );
if ( getBinding( ) == null )
{
String str = getFirstUseDimensonDisplayName( );
if ( str != null && str.length( ) > 0 )
{
int itemIndex = getItemIndex( strs, str );
if ( itemIndex >= 0 )
{
timeDimension.select( itemIndex );
}
else
{
timeDimension.select( 0 );
}
}
else
{
timeDimension.select( 0 );
}
}
else
{
String value = getBinding( ).getTimeDimension( );
int itemIndex = getItemIndex( strs, value );
timeDimension.select( itemIndex );
}
}
private String getFirstUseDimensonDisplayName( )
{
CrosstabReportItemHandle crosstab = getCrosstabReportItemHandle( );
int count = crosstab.getDimensionCount( ICrosstabConstants.COLUMN_AXIS_TYPE );
for ( int i = 0; i < count; i++ )
{
DimensionViewHandle viewHandle = crosstab.getDimension( ICrosstabConstants.COLUMN_AXIS_TYPE,
i );
if ( isAvaliableTimeDimension( viewHandle.getCubeDimension( ) ) )
{
// return ExpressionUtil.createJSDimensionExpression(
// viewHandle.getCubeDimension( )
// .getName( ),
// null );
return viewHandle.getCubeDimension( ).getName( );
}
}
count = crosstab.getDimensionCount( ICrosstabConstants.ROW_AXIS_TYPE );
for ( int i = 0; i < count; i++ )
{
DimensionViewHandle viewHandle = crosstab.getDimension( ICrosstabConstants.ROW_AXIS_TYPE,
i );
if ( isAvaliableTimeDimension( viewHandle.getCubeDimension( ) ) )
{
// return ExpressionUtil.createJSDimensionExpression(
// viewHandle.getCubeDimension( )
// .getName( ),
// null );
return viewHandle.getCubeDimension( ).getName( );
}
}
return null;
}
private boolean isAvaliableTimeDimension( DimensionHandle dimension )
{
if ( CrosstabAdaptUtil.isTimeDimension( dimension ) )
{
DimensionViewHandle viewHandle = getCrosstabReportItemHandle( ).getDimension( dimension.getName( ) );
if ( viewHandle == null )
{
int count = dimension.getDefaultHierarchy( ).getLevelCount( );
if ( count == 0 )
{
return false;
}
LevelHandle levelHandle = dimension.getDefaultHierarchy( )
.getLevel( 0 );
if ( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_YEAR.equals( levelHandle.getDateTimeLevelType( ) ) )
{
return true;
}
}
else
{
int count = viewHandle.getLevelCount( );
if ( count == 0 )
{
return false;
}
LevelViewHandle levelViewHandle = viewHandle.getLevel( 0 );
if ( DesignChoiceConstants.DATE_TIME_LEVEL_TYPE_YEAR.equals( levelViewHandle.getCubeLevel( )
.getDateTimeLevelType( ) ) )
{
return true;
}
}
}
return false;
}
private String[] getTimeDimensions( )
{
List<String> strs = new ArrayList<String>( );
CrosstabReportItemHandle crosstab = getCrosstabReportItemHandle( );
CubeHandle cube = crosstab.getCube( );
List list = cube.getPropertyHandle( ICubeModel.DIMENSIONS_PROP )
.getContents( );
for ( int i = 0; i < list.size( ); i++ )
{
DimensionHandle dimension = (DimensionHandle) list.get( i );
if ( isAvaliableTimeDimension( dimension ) )
{
// strs.add( ExpressionUtil.createJSDimensionExpression(
// dimension.getName( ),
// null ) );
strs.add( dimension.getName( ) );
}
}
return strs.toArray( new String[strs.size( )] );
}
private void initAggOn( )
{
try
{
CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( );
String[] aggOns = getAggOns( xtabHandle );
cmbAggOn.setItems( aggOns );
String aggstr = ""; //$NON-NLS-1$
if ( getBinding( ) != null )
{
List aggOnList = getBinding( ).getAggregateOnList( );
int i = 0;
for ( Iterator iterator = aggOnList.iterator( ); iterator.hasNext( ); )
{
if ( i > 0 )
aggstr += ","; //$NON-NLS-1$
String name = (String) iterator.next( );
aggstr += name;
i++;
}
}
else if ( isTimePeriod( ) )
{
List rowLevelList = getCrosstabViewHandleLevels( xtabHandle,
ICrosstabConstants.ROW_AXIS_TYPE );
List columnLevelList = getCrosstabViewHandleLevels( xtabHandle,
ICrosstabConstants.COLUMN_AXIS_TYPE );
if ( rowLevelList.size( ) != 0 && columnLevelList.size( ) == 0 )
{
aggstr = (String) rowLevelList.get( rowLevelList.size( ) - 1 );
}
else if ( rowLevelList.size( ) == 0
&& columnLevelList.size( ) != 0 )
{
aggstr = (String) columnLevelList.get( columnLevelList.size( ) - 1 );
}
else if ( rowLevelList.size( ) != 0
&& columnLevelList.size( ) != 0 )
{
aggstr = (String) rowLevelList.get( rowLevelList.size( ) - 1 )
+ ","
+ (String) columnLevelList.get( columnLevelList.size( ) - 1 );
}
}
else if ( getDataItemContainer( ) instanceof AggregationCellHandle )
{
AggregationCellHandle cellHandle = (AggregationCellHandle) getDataItemContainer( );
if ( cellHandle.getAggregationOnRow( ) != null )
{
aggstr += cellHandle.getAggregationOnRow( ).getFullName( );
if ( cellHandle.getAggregationOnColumn( ) != null )
{
aggstr += ","; //$NON-NLS-1$
}
}
if ( cellHandle.getAggregationOnColumn( ) != null )
{
aggstr += cellHandle.getAggregationOnColumn( )
.getFullName( );
}
}
else if ( container instanceof AggregationCellHandle )
{
AggregationCellHandle cellHandle = (AggregationCellHandle) container;
if ( cellHandle.getAggregationOnRow( ) != null )
{
aggstr += cellHandle.getAggregationOnRow( ).getFullName( );
if ( cellHandle.getAggregationOnColumn( ) != null )
{
aggstr += ","; //$NON-NLS-1$
}
}
if ( cellHandle.getAggregationOnColumn( ) != null )
{
aggstr += cellHandle.getAggregationOnColumn( )
.getFullName( );
}
}
String[] strs = aggstr.split( "," );//$NON-NLS-1$
String temAddOns = "";//$NON-NLS-1$
if ( strs != null && strs.length > 1 )
{
for ( int i = strs.length - 1; i >= 0; i
{
temAddOns = temAddOns + strs[i];
if ( i != 0 )
{
temAddOns = temAddOns + ",";//$NON-NLS-1$
}
}
}
for ( int j = 0; j < aggOns.length; j++ )
{
if ( aggOns[j].equals( aggstr ) )
{
cmbAggOn.select( j );
return;
}
if ( aggOns[j].equals( temAddOns ) )
{
cmbAggOn.select( j );
return;
}
}
cmbAggOn.select( 0 );
}
catch ( ExtendedElementException e )
{
ExceptionUtil.handle( e );
}
}
private String[] getAggOns( CrosstabReportItemHandle xtabHandle )
{
List rowLevelList = getCrosstabViewHandleLevels( xtabHandle,
ICrosstabConstants.ROW_AXIS_TYPE );
List columnLevelList = getCrosstabViewHandleLevels( xtabHandle,
ICrosstabConstants.COLUMN_AXIS_TYPE );
List aggOnList = new ArrayList( );
aggOnList.add( ALL );
for ( Iterator iterator = rowLevelList.iterator( ); iterator.hasNext( ); )
{
String name = (String) iterator.next( );
aggOnList.add( name );
}
for ( Iterator iterator = columnLevelList.iterator( ); iterator.hasNext( ); )
{
String name = (String) iterator.next( );
aggOnList.add( name );
}
for ( Iterator iterator = rowLevelList.iterator( ); iterator.hasNext( ); )
{
String name = (String) iterator.next( );
for ( Iterator iterator2 = columnLevelList.iterator( ); iterator2.hasNext( ); )
{
String name2 = (String) iterator2.next( );
aggOnList.add( name + "," + name2 ); //$NON-NLS-1$
}
}
return (String[]) aggOnList.toArray( new String[aggOnList.size( )] );
}
private List getCrosstabViewHandleLevels( CrosstabReportItemHandle xtab,
int type )
{
List levelList = new ArrayList( );
CrosstabViewHandle viewHandle = xtab.getCrosstabView( type );
if ( viewHandle != null )
{
int dimensions = viewHandle.getDimensionCount( );
for ( int i = 0; i < dimensions; i++ )
{
DimensionViewHandle dimension = viewHandle.getDimension( i );
int levels = dimension.getLevelCount( );
for ( int j = 0; j < levels; j++ )
{
LevelViewHandle level = dimension.getLevel( j );
if ( level.getCubeLevel( ) != null )
{
levelList.add( level.getCubeLevel( ).getFullName( ) );
}
}
}
}
return levelList;
}
private void initFilter( )
{
ExpressionButtonUtil.initExpressionButtonControl( txtFilter,
binding,
ComputedColumn.FILTER_MEMBER );
}
private void initFunction( )
{
cmbFunction.setItems( getFunctionDisplayNames( ) );
// cmbFunction.add( NULL, 0 );
if ( binding == null )
{
cmbFunction.select( 0 );
handleFunctionSelectEvent( );
return;
}
try
{
String functionString = getFunctionDisplayName( DataAdapterUtil.adaptModelAggregationType( binding.getAggregateFunction( ) ) );
int itemIndex = getItemIndex( getFunctionDisplayNames( ),
functionString );
cmbFunction.select( itemIndex );
handleFunctionSelectEvent( );
}
catch ( AdapterException e )
{
ExceptionUtil.handle( e );
}
// List args = getFunctionArgs( functionString );
// bindingColumn.argumentsIterator( )
for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); )
{
AggregationArgumentHandle arg = (AggregationArgumentHandle) iterator.next( );
String argName = DataAdapterUtil.adaptArgumentName( arg.getName( ) );
if ( paramsMap.containsKey( argName ) )
{
if ( arg.getValue( ) != null )
{
Control control = paramsMap.get( argName );
ExpressionButtonUtil.initExpressionButtonControl( control,
arg,
AggregationArgument.VALUE_MEMBER );
}
}
}
}
private String[] getFunctionDisplayNames( )
{
IAggrFunction[] choices = getFunctions( );
if ( choices == null )
return new String[0];
String[] displayNames = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
displayNames[i] = choices[i].getDisplayName( );
}
return displayNames;
}
private IAggrFunction getFunctionByDisplayName( String displayName )
{
IAggrFunction[] choices = getFunctions( );
if ( choices == null )
return null;
for ( int i = 0; i < choices.length; i++ )
{
if ( choices[i].getDisplayName( ).equals( displayName ) )
{
return choices[i];
}
}
return null;
}
private String getFunctionDisplayName( String function )
{
try
{
return DataUtil.getAggregationManager( )
.getAggregation( function )
.getDisplayName( );
}
catch ( BirtException e )
{
ExceptionUtil.handle( e );
return null;
}
}
private IAggrFunction[] getFunctions( )
{
try
{
List aggrInfoList = DataUtil.getAggregationManager( )
.getAggregations( AggregationManager.AGGR_XTAB );
return (IAggrFunction[]) aggrInfoList.toArray( new IAggrFunction[0] );
}
catch ( BirtException e )
{
ExceptionUtil.handle( e );
return new IAggrFunction[0];
}
}
private String getDataTypeDisplayName( String dataType )
{
for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
{
if ( dataType.equals( DATA_TYPE_CHOICES[i].getName( ) ) )
{
return DATA_TYPE_CHOICES[i].getDisplayName( );
}
}
return ""; //$NON-NLS-1$
}
private void initTextField( Text txtParam, IParameterDefn param )
{
if ( paramsValueMap.containsKey( param.getName( ) ) )
{
txtParam.setText( paramsValueMap.get( param.getName( ) ) );
return;
}
if ( binding != null )
{
for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); )
{
AggregationArgumentHandle arg = (AggregationArgumentHandle) iterator.next( );
if ( arg.getName( ).equals( param.getName( ) ) )
{
if ( arg.getValue( ) != null )
txtParam.setText( arg.getValue( ) );
return;
}
}
}
}
/**
* fill the cmbDataField with binding holder's bindings
*
* @param param
*/
private void initDataFields( Combo cmbDataField, IParameterDefn param )
{
List<String> datas = getMesures( );
datas.addAll( getDatas( ) );
String[] items = datas.toArray( new String[datas.size( )] );
cmbDataField.setItems( items );
if ( paramsValueMap.containsKey( param.getName( ) ) )
{
cmbDataField.setText( paramsValueMap.get( param.getName( ) ) );
return;
}
if ( binding != null )
{
for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); )
{
AggregationArgumentHandle arg = (AggregationArgumentHandle) iterator.next( );
if ( arg.getName( ).equals( param.getName( ) ) )
{
if ( arg.getValue( ) != null )
{
for ( int i = 0; i < items.length; i++ )
{
if ( items[i].equals( arg.getValue( ) ) )
{
cmbDataField.select( i );
return;
}
}
cmbDataField.setText( arg.getValue( ) );
return;
}
}
}
// backforward compatble
if ( binding.getExpression( ) != null )
{
for ( int i = 0; i < items.length; i++ )
{
if ( items[i].equals( binding.getExpression( ) ) )
{
cmbDataField.select( i );
}
}
}
}
}
private List<String> getMesures( )
{
List<String> measures = new ArrayList<String>( );
try
{
CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( );
measures.add( "" ); //$NON-NLS-1$
// for ( int i = 0; i < xtabHandle.getMeasureCount( ); i++ )
// MeasureViewHandle mv = xtabHandle.getMeasure( i );
// if ( mv instanceof ComputedMeasureViewHandle )
// continue;
// measures.add( DEUtil.getExpression( mv.getCubeMeasure( ) ) );
CubeHandle cubeHandle = xtabHandle.getCube( );
List children = cubeHandle.getContents( CubeHandle.MEASURE_GROUPS_PROP );
for (int i=0; i<children.size( ); i++)
{
MeasureGroupHandle group = (MeasureGroupHandle)children.get( i );
List measreHandles = group.getContents( MeasureGroupHandle.MEASURES_PROP );
for (int j=0; j<measreHandles.size( ); j++)
{
MeasureHandle measure = (MeasureHandle)measreHandles.get( j );
String str = DEUtil.getExpression( measure );
if (!measures.contains( str ))
{
measures.add( str );
}
}
}
}
catch ( ExtendedElementException e )
{
}
return measures;
}
private List<String> getDatas( )
{
List<String> datas = new ArrayList<String>( );
try
{
CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( );
try
{
IBinding[] aggregateBindings = CubeQueryUtil.getAggregationBindings( getCrosstabBindings( xtabHandle ) );
for ( IBinding binding : aggregateBindings )
{
if ( getBinding( ) == null
|| !getBinding( ).getName( )
.equals( binding.getBindingName( ) ) )
datas.add( ExpressionUtil.createJSDataExpression( binding.getBindingName( ) ) );
}
}
catch ( AdapterException e )
{
}
catch ( BirtException e )
{
}
}
catch ( ExtendedElementException e )
{
}
return datas;
}
private IBinding[] getCrosstabBindings( CrosstabReportItemHandle xtabHandle )
throws BirtException
{
Iterator bindingItr = ( (ExtendedItemHandle) xtabHandle.getModelHandle( ) ).columnBindingsIterator( );
ModuleHandle module = ( (ExtendedItemHandle) xtabHandle.getModelHandle( ) ).getModuleHandle( );
List<IBinding> bindingList = new ArrayList<IBinding>( );
if ( bindingItr != null )
{
Map cache = new HashMap( );
List rowLevelNameList = new ArrayList( );
List columnLevelNameList = new ArrayList( );
DataRequestSession session = DataRequestSession.newSession( new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION ) );
try
{
IModelAdapter modelAdapter = session.getModelAdaptor( );
while ( bindingItr.hasNext( ) )
{
ComputedColumnHandle column = (ComputedColumnHandle) bindingItr.next( );
// now user dte model adpater to transform the binding
IBinding binding;
try
{
binding = modelAdapter.adaptBinding( column,
ExpressionLocation.CUBE );
}
catch ( Exception e )
{
continue;
}
if ( binding == null )
{
continue;
}
// still need add aggregateOn field
List aggrList = column.getAggregateOnList( );
if ( aggrList != null )
{
for ( Iterator aggrItr = aggrList.iterator( ); aggrItr.hasNext( ); )
{
String baseLevel = (String) aggrItr.next( );
CrosstabUtil.addHierachyAggregateOn( module,
binding,
baseLevel,
rowLevelNameList,
columnLevelNameList,
cache );
}
}
bindingList.add( binding );
}
}
finally
{
session.shutdown( );
}
}
return bindingList.toArray( new IBinding[bindingList.size( )] );
}
private void setDataFieldExpression( ComputedColumnHandle binding )
{
if ( binding.getExpression( ) != null )
{
if ( isAggregate( ) )
{
IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) );
if ( function != null )
{
IParameterDefn[] params = function.getParameterDefn( );
for ( final IParameterDefn param : params )
{
if ( param.isDataField( ) )
{
Control control = paramsMap.get( param.getName( ) );
if ( ExpressionButtonUtil.getExpressionButton( control ) != null )
{
ExpressionButtonUtil.initExpressionButtonControl( control,
binding,
ComputedColumn.EXPRESSION_MEMBER );
}
else
{
if ( control instanceof Combo )
{
( (Combo) control ).setText( binding.getExpression( ) );
}
else if ( control instanceof CCombo )
{
( (CCombo) control ).setText( binding.getExpression( ) );
}
else if ( control instanceof Text )
{
( (Text) control ).setText( binding.getExpression( ) );
}
}
}
}
}
}
else
{
if ( txtExpression != null && !txtExpression.isDisposed( ) )
{
ExpressionButtonUtil.initExpressionButtonControl( txtExpression,
binding,
ComputedColumn.EXPRESSION_MEMBER );
}
}
}
}
private void setName( String name )
{
if ( name != null && txtName != null )
txtName.setText( name );
}
private void setDisplayName( String displayName )
{
if ( displayName != null && txtDisplayName != null )
txtDisplayName.setText( displayName );
}
private void setDisplayNameID( String displayNameID )
{
if ( displayNameID != null && txtDisplayNameID != null )
txtDisplayNameID.setText( displayNameID );
}
private void setTypeSelect( String typeSelect )
{
if ( cmbType != null )
{
if ( typeSelect != null )
cmbType.select( getItemIndex( cmbType.getItems( ), typeSelect ) );
else
cmbType.select( 0 );
}
}
private int getItemIndex( String[] items, String item )
{
for ( int i = 0; i < items.length; i++ )
{
if ( items[i].equals( item ) )
return i;
}
return -1;
}
private void createAggregateSection( Composite composite )
{
new Label( composite, SWT.NONE ).setText( FUNCTION );
cmbFunction = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
cmbFunction.setLayoutData( gd );
cmbFunction.setVisibleItemCount( 30 );
// WidgetUtil.createGridPlaceholder( composite, 1, false );
cmbFunction.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleFunctionSelectEvent( );
modifyDialogContent( );
validate( );
}
} );
paramsComposite = new Composite( composite, SWT.NONE );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.horizontalSpan = 4;
gridData.exclude = true;
paramsComposite.setLayoutData( gridData );
GridLayout layout = new GridLayout( );
// layout.horizontalSpacing = layout.verticalSpacing = 0;
layout.marginWidth = layout.marginHeight = 0;
layout.numColumns = 4;
Layout parentLayout = paramsComposite.getParent( ).getLayout( );
if ( parentLayout instanceof GridLayout )
layout.horizontalSpacing = ( (GridLayout) parentLayout ).horizontalSpacing;
paramsComposite.setLayout( layout );
new Label( composite, SWT.NONE ).setText( FILTER_CONDITION );
txtFilter = new Text( composite, SWT.BORDER );
gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.horizontalSpan = 2;
txtFilter.setLayoutData( gridData );
txtFilter.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
}
} );
//createExpressionButton( composite, txtFilter );
IExpressionProvider filterExpressionProvider = new CrosstabAggregationExpressionProvider( this.bindingHolder,
this.binding )
{
protected List getChildrenList( Object parent )
{
List children = super.getChildrenList( parent );
List retValue = new ArrayList( );
retValue.addAll( children );
if (parent instanceof MeasureGroupHandle)
{
for (int i=0; i<children.size( ); i++)
{
Object obj = children.get( i );
if (obj instanceof MeasureHandle && ((MeasureHandle)obj).isCalculated( ))
{
retValue.remove( obj );
}
}
}
return retValue;
}
};
ExpressionButtonUtil.createExpressionButton( composite,
txtFilter,
filterExpressionProvider,
this.bindingHolder );
// if (!isTimePeriod( ))
{
Label lblAggOn = new Label( composite, SWT.NONE );
lblAggOn.setText( AGGREGATE_ON );
gridData = new GridData( );
gridData.verticalAlignment = GridData.BEGINNING;
lblAggOn.setLayoutData( gridData );
cmbAggOn = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.horizontalSpan = 3;
cmbAggOn.setLayoutData( gridData );
cmbAggOn.setVisibleItemCount( 30 );
cmbAggOn.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
modifyDialogContent( );
}
} );
}
}
private void createCommonSection( Composite composite )
{
new Label( composite, SWT.NONE ).setText( EXPRESSION );
txtExpression = new Text( composite, SWT.BORDER );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
txtExpression.setLayoutData( gd );
createExpressionButton( composite, txtExpression );
txtExpression.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
}
} );
}
private void createMessageSection( Composite composite )
{
messageLine = new CLabel( composite, SWT.LEFT );
GridData layoutData = new GridData( GridData.FILL_HORIZONTAL );
layoutData.horizontalSpan = 4;
messageLine.setLayoutData( layoutData );
}
protected void handleFunctionSelectEvent( )
{
Control[] children = paramsComposite.getChildren( );
for ( int i = 0; i < children.length; i++ )
{
children[i].dispose( );
}
IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) );
if ( function != null )
{
paramsMap.clear( );
IParameterDefn[] params = function.getParameterDefn( );
if ( params.length > 0 )
{
( (GridData) paramsComposite.getLayoutData( ) ).exclude = false;
( (GridData) paramsComposite.getLayoutData( ) ).heightHint = SWT.DEFAULT;
int width = 0;
if ( paramsComposite.getParent( ).getLayout( ) instanceof GridLayout )
{
Control[] controls = paramsComposite.getParent( )
.getChildren( );
for ( int i = 0; i < controls.length; i++ )
{
if ( controls[i] instanceof Label
&& ( (GridData) controls[i].getLayoutData( ) ).horizontalSpan == 1 )
{
int labelWidth = controls[i].getBounds( ).width
- controls[i].getBorderWidth( )
* 2;
if ( labelWidth > width )
width = labelWidth;
}
}
}
for ( final IParameterDefn param : params )
{
Label lblParam = new Label( paramsComposite, SWT.NONE );
lblParam.setText( param.getDisplayName( ) + ":" ); //$NON-NLS-1$
//if ( !param.isOptional( ) )
// lblParam.setText( "*" + lblParam.getText( ) );
GridData gd = new GridData( );
gd.widthHint = lblParam.computeSize( SWT.DEFAULT,
SWT.DEFAULT ).x;
if ( gd.widthHint < width )
gd.widthHint = width;
lblParam.setLayoutData( gd );
if ( param.isDataField( ) )
{
final Combo cmbDataField = new Combo( paramsComposite,
SWT.BORDER );
cmbDataField.setLayoutData( GridDataFactory.fillDefaults( )
.grab( true, false )
.span( 3, 1 )
.create( ) );
cmbDataField.setVisibleItemCount( 30 );
initDataFields( cmbDataField, param );
cmbDataField.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
paramsValueMap.put( param.getName( ),
cmbDataField.getText( ) );
}
} );
paramsMap.put( param.getName( ), cmbDataField );
}
else
{
final Text txtParam = new Text( paramsComposite,
SWT.BORDER );
initTextField( txtParam, param );
txtParam.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
modifyDialogContent( );
validate( );
paramsValueMap.put( param.getName( ),
txtParam.getText( ) );
}
} );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.horizontalIndent = 0;
gridData.horizontalSpan = 2;
txtParam.setLayoutData( gridData );
createExpressionButton( paramsComposite, txtParam );
paramsMap.put( param.getName( ), txtParam );
}
}
}
else
{
( (GridData) paramsComposite.getLayoutData( ) ).heightHint = 0;
// ( (GridData) paramsComposite.getLayoutData( ) ).exclude =
// true;
}
// this.cmbDataField.setEnabled( function.needDataField( ) );
try
{
cmbType.setText( getDataTypeDisplayName( DataAdapterUtil.adapterToModelDataType( DataUtil.getAggregationManager( )
.getAggregation( function.getName( ) )
.getDataType( ) ) ) );
}
catch ( BirtException e )
{
ExceptionUtil.handle( e );
}
}
else
{
( (GridData) paramsComposite.getLayoutData( ) ).heightHint = 0;
( (GridData) paramsComposite.getLayoutData( ) ).exclude = true;
// new Label( argsComposite, SWT.NONE ).setText( "no args" );
}
composite.layout( true, true );
setContentSize( composite );
}
private void createExpressionButton( final Composite parent,
final Control control )
{
if ( expressionProvider == null )
{
if ( isAggregate( ) )
expressionProvider = new CrosstabAggregationExpressionProvider( this.bindingHolder,
this.binding );
else
expressionProvider = new CrosstabBindingExpressionProvider( this.bindingHolder,
this.binding );
}
ExpressionButtonUtil.createExpressionButton( parent,
control,
expressionProvider,
this.bindingHolder );
}
public void validate( )
{
if ( txtName != null
&& ( txtName.getText( ) == null || txtName.getText( )
.trim( )
.equals( "" ) ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
}
else if ( txtExpression != null
&& ( txtExpression.getText( ) == null || txtExpression.getText( )
.trim( )
.equals( "" ) ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
}
else
{
if ( this.binding == null )// create bindnig, we should check if
// the binding name already exists.
{
for ( Iterator iterator = this.bindingHolder.getColumnBindings( )
.iterator( ); iterator.hasNext( ); )
{
ComputedColumnHandle computedColumn = (ComputedColumnHandle) iterator.next( );
if ( computedColumn.getName( ).equals( txtName.getText( ) ) )
{
dialog.setCanFinish( false );
this.messageLine.setText( Messages.getFormattedString( "BindingDialogHelper.error.nameduplicate", //$NON-NLS-1$
new Object[]{
txtName.getText( )
} ) );
this.messageLine.setImage( PlatformUI.getWorkbench( )
.getSharedImages( )
.getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) );
return;
}
}
}
// bugzilla 273368
// if expression is "measure['...']", aggregation do not support
// IAggrFunction.RUNNING_AGGR function
if ( isAggregate( ) )
{
IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) );
IParameterDefn[] params = function.getParameterDefn( );
if ( params.length > 0 )
{
for ( final IParameterDefn param : params )
{
if ( param.isDataField( ) )
{
Combo cmbDataField = (Combo) paramsMap.get( param.getName( ) );
String expression = cmbDataField.getText( );
DataRequestSession session = null;
try
{
session = DataRequestSession.newSession( new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION ) );
if ( session.getCubeQueryUtil( )
.getReferencedMeasureName( expression ) != null
&& function.getType( ) == IAggrFunction.RUNNING_AGGR )
{
dialog.setCanFinish( false );
this.messageLine.setText( Messages.getFormattedString( "BindingDialogHelper.error.improperexpression", //$NON-NLS-1$
new Object[]{
function.getName( )
} ) );
this.messageLine.setImage( PlatformUI.getWorkbench( )
.getSharedImages( )
.getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) );
return;
}
dialog.setCanFinish( true );
}
catch ( Exception e )
{
}
finally
{
if ( session != null )
{
session.shutdown( );
}
}
}
}
}
}
dialogCanFinish( );
this.messageLine.setText( "" ); //$NON-NLS-1$
this.messageLine.setImage( null );
if ( txtExpression != null
&& ( txtExpression.getText( ) == null || txtExpression.getText( )
.trim( )
.equals( "" ) ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
return;
}
if ( isAggregate( ) )
{
try
{
IAggrFunction aggregation = DataUtil.getAggregationManager( )
.getAggregation( getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) );
if ( aggregation.getParameterDefn( ).length > 0 )
{
IParameterDefn[] parameters = aggregation.getParameterDefn( );
for ( IParameterDefn param : parameters )
{
if ( !param.isOptional( ) )
{
String paramValue = getControlValue( paramsMap.get( param.getName( ) ) );
if ( paramValue == null
|| paramValue.trim( ).equals( "" ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
return;
}
}
}
}
}
catch ( BirtException e )
{
// TODO show error message in message panel
}
}
if ( isTimePeriod( ) )
{
ITimeFunction timeFunction = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) );
List<IArgumentInfo> infos = timeFunction.getArguments( );
for ( int i = 0; i < infos.size( ); i++ )
{
String paramValue = getControlValue( calculationParamsMap.get( infos.get( i )
.getName( ) ) );
if ( paramValue == null
|| paramValue.trim( ).equals( "" ) && !infos.get( i ).isOptional( ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
return;
}
}
String dimensionName = getTimeDimsionName( );
if ( !isUseDimension( dimensionName )
&& recentButton.getSelection( ) )
{
this.messageLine.setText( Messages.getString( "CrosstabBindingDialogHelper.timeperiod.wrongdate" ) ); //$NON-NLS-1$
this.messageLine.setImage( PlatformUI.getWorkbench( )
.getSharedImages( )
.getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) );
dialog.setCanFinish( false );
return;
}
if ( dateSelectionButton.getSelection( )
&& ( dateText.getText( ) == null || dateText.getText( )
.trim( )
.equals( "" ) ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
return;
}
}
dialogCanFinish( );
}
updateRemoveBtnState( );
}
private void dialogCanFinish( )
{
if ( !hasModified && isEditModal( ) )
dialog.setCanFinish( false );
else
dialog.setCanFinish( true );
}
public boolean differs( ComputedColumnHandle binding )
{
if ( isAggregate( ) )
{
if ( !strEquals( binding.getName( ), txtName.getText( ) ) )
return true;
if ( !strEquals( binding.getDisplayName( ),
txtDisplayName.getText( ) ) )
return true;
if ( !strEquals( binding.getDisplayNameID( ),
txtDisplayNameID.getText( ) ) )
return true;
if ( !strEquals( binding.getDataType( ), getDataType( ) ) )
return true;
try
{
if ( !strEquals( DataAdapterUtil.adaptModelAggregationType( binding.getAggregateFunction( ) ),
getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) ) )
return true;
}
catch ( AdapterException e )
{
}
if ( !exprEquals( (Expression) binding.getExpressionProperty( ComputedColumn.FILTER_MEMBER )
.getValue( ),
ExpressionButtonUtil.getExpression( txtFilter ) ) )
return true;
if ( /* !isTimePeriod( ) && */!strEquals( cmbAggOn.getText( ),
DEUtil.getAggregateOn( binding ) ) )
return true;
IAggrFunction function = getFunctionByDisplayName( cmbFunction.getText( ) );
if ( function != null )
{
IParameterDefn[] params = function.getParameterDefn( );
for ( final IParameterDefn param : params )
{
if ( paramsMap.containsKey( param.getName( ) ) )
{
Expression paramValue = ExpressionButtonUtil.getExpression( paramsMap.get( param.getName( ) ) );
for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); )
{
AggregationArgumentHandle handle = (AggregationArgumentHandle) iterator.next( );
if ( param.getName( ).equals( handle.getName( ) )
&& !exprEquals( (Expression) handle.getExpressionProperty( AggregationArgument.VALUE_MEMBER )
.getValue( ),
paramValue ) )
{
return true;
}
}
if ( param.isDataField( )
&& binding.getExpression( ) != null
&& !exprEquals( (Expression) binding.getExpressionProperty( ComputedColumn.EXPRESSION_MEMBER )
.getValue( ),
paramValue ) )
{
return true;
}
}
}
}
}
else
{
if ( !strEquals( txtName.getText( ), binding.getName( ) ) )
return true;
if ( !strEquals( txtDisplayName.getText( ),
binding.getDisplayName( ) ) )
return true;
if ( !strEquals( txtDisplayNameID.getText( ),
binding.getDisplayNameID( ) ) )
return true;
if ( !strEquals( getDataType( ), binding.getDataType( ) ) )
return true;
if ( !exprEquals( ExpressionButtonUtil.getExpression( txtExpression ),
(Expression) binding.getExpressionProperty( ComputedColumn.EXPRESSION_MEMBER )
.getValue( ) ) )
return true;
}
return false;
}
private boolean exprEquals( Expression left, Expression right )
{
if ( left == null && right == null )
{
return true;
}
else if ( left == null && right != null )
{
return right.getExpression( ) == null;
}
else if ( left != null && right == null )
{
return left.getExpression( ) == null;
}
else if ( left.getStringExpression( ) == null
&& right.getStringExpression( ) == null )
return true;
else if ( strEquals( left.getStringExpression( ),
right.getStringExpression( ) )
&& strEquals( left.getType( ), right.getType( ) ) )
return true;
return false;
}
private String getControlValue( Control control )
{
if ( control instanceof Text )
{
return ( (Text) control ).getText( );
}
else if ( control instanceof Combo )
{
return ( (Combo) control ).getText( );
}
return null;
}
private boolean strEquals( String left, String right )
{
if ( left == right )
return true;
if ( left == null )
return "".equals( right ); //$NON-NLS-1$
if ( right == null )
return "".equals( left ); //$NON-NLS-1$
return left.equals( right );
}
private String getDataType( )
{
for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
{
if ( DATA_TYPE_CHOICES[i].getDisplayName( )
.equals( cmbType.getText( ) ) )
{
return DATA_TYPE_CHOICES[i].getName( );
}
}
return ""; //$NON-NLS-1$
}
public ComputedColumnHandle editBinding( ComputedColumnHandle binding )
throws SemanticException
{
if ( isAggregate( ) )
{
binding.setDisplayName( txtDisplayName.getText( ) );
binding.setDisplayNameID( txtDisplayNameID.getText( ) );
for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
{
if ( DATA_TYPE_CHOICES[i].getDisplayName( )
.equals( cmbType.getText( ) ) )
{
binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
break;
}
}
binding.setAggregateFunction( getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) );
ExpressionButtonUtil.saveExpressionButtonControl( txtFilter,
binding,
ComputedColumn.FILTER_MEMBER );
binding.clearAggregateOnList( );
// if (!isTimePeriod( ))
{
String aggStr = cmbAggOn.getText( );
StringTokenizer token = new StringTokenizer( aggStr, "," ); //$NON-NLS-1$
while ( token.hasMoreTokens( ) )
{
String agg = token.nextToken( );
if ( !agg.equals( ALL ) )
binding.addAggregateOn( agg );
}
}
// remove expression created in old version.
binding.setExpression( null );
binding.clearArgumentList( );
for ( Iterator iterator = paramsMap.keySet( ).iterator( ); iterator.hasNext( ); )
{
String arg = (String) iterator.next( );
String value = getControlValue( paramsMap.get( arg ) );
if ( value != null )
{
AggregationArgument argHandle = StructureFactory.createAggregationArgument( );
argHandle.setName( arg );
if ( ExpressionButtonUtil.getExpressionButton( paramsMap.get( arg ) ) != null )
{
ExpressionButtonUtil.saveExpressionButtonControl( paramsMap.get( arg ),
argHandle,
AggregationArgument.VALUE_MEMBER );
}
else
{
Expression expression = new Expression( value,
ExpressionType.JAVASCRIPT );
argHandle.setExpressionProperty( AggregationArgument.VALUE_MEMBER,
expression );
}
binding.addArgument( argHandle );
}
}
}
else
{
for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
{
if ( DATA_TYPE_CHOICES[i].getDisplayName( )
.equals( cmbType.getText( ) ) )
{
binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
break;
}
}
binding.setDisplayName( txtDisplayName.getText( ) );
binding.setDisplayNameID( txtDisplayNameID.getText( ) );
if ( ExpressionButtonUtil.getExpressionButton( txtExpression ) != null )
{
ExpressionButtonUtil.saveExpressionButtonControl( txtExpression,
binding,
ComputedColumn.EXPRESSION_MEMBER );
}
else
{
Expression expression = new Expression( getControlValue( txtExpression ),
ExpressionType.JAVASCRIPT );
binding.setExpressionProperty( AggregationArgument.VALUE_MEMBER,
expression );
}
}
if ( isTimePeriod( ) )
{
ITimeFunction timeFunction = getTimeFunctionByIndex( calculationType.getSelectionIndex( ) );
String dimensionName = timeDimension.getText( );
// Expression dimensionExpression = new Expression( dimensionName,
// ExpressionType.JAVASCRIPT );
// binding.setExpressionProperty(
// ComputedColumn.TIME_DIMENSION_MEMBER,
// dimensionExpression );
binding.setTimeDimension( dimensionName );
binding.setCalculationType( timeFunction.getName( ) );
binding.setProperty( ComputedColumn.CALCULATION_ARGUMENTS_MEMBER,
null );
// save the args
for ( Iterator iterator = calculationParamsMap.keySet( ).iterator( ); iterator.hasNext( ); )
{
CalculationArgument argument = StructureFactory.createCalculationArgument( );
String arg = (String) iterator.next( );
argument.setName( arg );
String value = getControlValue( calculationParamsMap.get( arg ) );
if ( value != null )
{
if ( ExpressionButtonUtil.getExpressionButton( calculationParamsMap.get( arg ) ) != null )
{
Expression expr = getExpressionByControl( calculationParamsMap.get( arg ) );
argument.setValue( expr );
}
else
{
Expression expr = new Expression( value,
ExpressionType.JAVASCRIPT );
argument.setValue( expr );
}
binding.addCalculationArgument( argument );
}
}
// add refred day
if ( todayButton.getSelection( ) )
{
binding.setReferenceDateType( DesignChoiceConstants.REFERENCE_DATE_TYPE_TODAY );
}
else if ( dateSelectionButton.getSelection( ) )
{
binding.setReferenceDateType( DesignChoiceConstants.REFERENCE_DATE_TYPE_FIXED_DATE );
ExpressionButtonUtil.saveExpressionButtonControl( dateText,
binding,
ComputedColumn.REFERENCE_DATE_VALUE_MEMBER );
}
else if ( recentButton.getSelection( ) )
{
binding.setReferenceDateType( DesignChoiceConstants.REFERENCE_DATE_TYPE_ENDING_DATE_IN_DIMENSION );
}
}
return binding;
}
public static Expression getExpressionByControl( Control control )
throws SemanticException
{
ExpressionButton button = getExpressionButton( control );
if ( button != null && button.getExpressionHelper( ) != null )
{
Expression expression = new Expression( button.getExpressionHelper( )
.getExpression( ),
button.getExpressionHelper( ).getExpressionType( ) );
return expression;
}
return null;
}
public ComputedColumnHandle newBinding( ReportItemHandle bindingHolder,
String name ) throws SemanticException
{
ComputedColumn column = StructureFactory.newComputedColumn( bindingHolder,
name == null ? txtName.getText( ) : name );
ComputedColumnHandle binding = DEUtil.addColumn( bindingHolder,
column,
true );
return editBinding( binding );
}
public void setContainer( Object container )
{
this.container = container;
}
public boolean canProcessAggregation( )
{
return true;
}
private URL[] getAvailableResourceUrls( )
{
List<URL> urls = new ArrayList<URL>( );
String[] baseNames = getBaseNames( );
if ( baseNames == null )
return urls.toArray( new URL[0] );
else
{
for ( int i = 0; i < baseNames.length; i++ )
{
URL url = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.findResource( baseNames[i],
IResourceLocator.MESSAGE_FILE );
if ( url != null )
urls.add( url );
}
return urls.toArray( new URL[0] );
}
}
private String[] getBaseNames( )
{
List<String> resources = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.getIncludeResources( );
if ( resources == null )
return null;
else
return resources.toArray( new String[0] );
}
private URL[] getResourceURLs( )
{
String[] baseNames = getBaseNames( );
if ( baseNames == null )
return null;
else
{
URL[] urls = new URL[baseNames.length];
for ( int i = 0; i < baseNames.length; i++ )
{
urls[i] = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.findResource( baseNames[i],
IResourceLocator.MESSAGE_FILE );
}
return urls;
}
}
private void updateRemoveBtnState( )
{
btnRemoveDisplayNameID.setEnabled( txtDisplayNameID.getText( )
.equals( EMPTY_STRING ) ? false : true );
}
private boolean isEditModal = false;
public void setEditModal( boolean isEditModal )
{
this.isEditModal = isEditModal;
}
public boolean isEditModal( )
{
return isEditModal;
}
private void modifyDialogContent( )
{
if ( hasInitDialog && isEditModal( ) && hasModified == false )
{
hasModified = true;
validate( );
}
}
private boolean hasModified = false;
}
|
package org.innovateuk.ifs.project.status.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.competition.resource.CompetitionOpenQueryResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.SpendProfileStatusResource;
import org.innovateuk.ifs.competition.service.CompetitionPostSubmissionRestService;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.project.bankdetails.service.BankDetailsRestService;
import org.innovateuk.ifs.project.status.populator.CompetitionStatusViewModelPopulator;
import org.innovateuk.ifs.project.status.resource.CompetitionProjectsStatusResource;
import org.innovateuk.ifs.project.status.security.StatusPermission;
import org.innovateuk.ifs.project.status.viewmodel.CompetitionOpenQueriesViewModel;
import org.innovateuk.ifs.project.status.viewmodel.CompetitionPendingSpendProfilesViewModel;
import org.innovateuk.ifs.project.status.viewmodel.CompetitionStatusViewModel;
import org.innovateuk.ifs.user.resource.Role;
import org.innovateuk.ifs.user.resource.UserResource;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.test.web.servlet.MvcResult;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import static java.lang.Boolean.TRUE;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.any;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
public class CompetitionStatusControllerTest extends BaseControllerMockMVCTest<CompetitionStatusController> {
@Mock
private CompetitionPostSubmissionRestService competitionPostSubmissionRestService;
@Mock
private CompetitionRestService competitionRestServiceMock;
@Mock
private BankDetailsRestService bankDetailsRestServiceMock;
@Mock
private CompetitionStatusViewModelPopulator competitionStatusViewModelPopulatorMock;
@Test
public void testViewCompetitionStatusPage() throws Exception {
Long competitionId = 123L;
mockMvc.perform(get("/competition/" + competitionId + "/status"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("/competition/%s/status/all", competitionId)));
}
@Test
public void testViewCompetitionStatusPageAllProjectFinance() throws Exception {
Long competitionId = 123L;
String applicationSearchString = "12";
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(Role.PROJECT_FINANCE)).build());
CompetitionStatusViewModel competitionStatusViewModel = new CompetitionStatusViewModel(new CompetitionProjectsStatusResource(), TRUE, new HashMap<Long, StatusPermission>(), 1L, 4L);
when(competitionStatusViewModelPopulatorMock.populate(Mockito.any(UserResource.class), anyLong(), anyString())).thenReturn(competitionStatusViewModel);
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/all?applicationSearchString=" + applicationSearchString))
.andExpect(view().name("project/competition-status-all"))
.andExpect(model().attribute("model", any(CompetitionStatusViewModel.class)))
.andReturn();
CompetitionStatusViewModel viewModel = (CompetitionStatusViewModel) result.getModelAndView().getModel().get("model");
assertEquals(1L, viewModel.getOpenQueryCount());
assertEquals(4L, viewModel.getPendingSpendProfilesCount());
assertTrue(viewModel.isShowTabs());
}
@Test
public void testViewCompetitionStatusPageAllCompAdmin() throws Exception {
long competitionId = 123L;
String applicationSearchString = "12";
CompetitionStatusViewModel competitionStatusViewModel = new CompetitionStatusViewModel(new CompetitionProjectsStatusResource(), TRUE, new HashMap<Long, StatusPermission>(), 0L, 0L);
when(competitionStatusViewModelPopulatorMock.populate(Mockito.any(UserResource.class), anyLong(), anyString())).thenReturn(competitionStatusViewModel);
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/all?applicationSearchString=" + applicationSearchString))
.andExpect(view().name("project/competition-status-all"))
.andExpect(model().attribute("model", any(CompetitionStatusViewModel.class)))
.andReturn();
CompetitionStatusViewModel viewModel = (CompetitionStatusViewModel) result.getModelAndView().getModel().get("model");
assertEquals(0L, viewModel.getOpenQueryCount());
assertEquals(0L, viewModel.getPendingSpendProfilesCount());
assertTrue(viewModel.isShowTabs());
verify(competitionPostSubmissionRestService, never()).getCompetitionOpenQueriesCount(competitionId);
verify(competitionPostSubmissionRestService, never()).countPendingSpendProfiles(competitionId);
}
@Test
public void testViewCompetitionStatusPageQueries() throws Exception {
long competitionId = 123L;
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(Role.PROJECT_FINANCE)).build());
CompetitionResource competition = newCompetitionResource().withName("comp1").withId(123L).build();
List<CompetitionOpenQueryResource> openQueries = singletonList(new CompetitionOpenQueryResource(1L, 2L, "org", 3L, "proj"));
when(competitionRestServiceMock.getCompetitionById(competitionId)).thenReturn(restSuccess(competition));
when(competitionPostSubmissionRestService.getCompetitionOpenQueriesCount(competitionId)).thenReturn(restSuccess(1L));
when(competitionPostSubmissionRestService.getCompetitionOpenQueries(competitionId)).thenReturn(restSuccess(openQueries));
when(competitionPostSubmissionRestService.countPendingSpendProfiles(competitionId)).thenReturn(restSuccess(4L));
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/queries"))
.andExpect(view().name("project/competition-status-queries"))
.andExpect(model().attribute("model", any(CompetitionOpenQueriesViewModel.class)))
.andReturn();
CompetitionOpenQueriesViewModel viewModel = (CompetitionOpenQueriesViewModel) result.getModelAndView().getModel().get("model");
assertEquals(123L, viewModel.getCompetitionId());
assertEquals("comp1", viewModel.getCompetitionName());
assertEquals(1L, viewModel.getOpenQueryCount());
assertEquals(1, viewModel.getOpenQueries().size());
assertEquals(1L, viewModel.getOpenQueries().get(0).getApplicationId().longValue());
assertEquals(2L, viewModel.getOpenQueries().get(0).getOrganisationId().longValue());
assertEquals("org", viewModel.getOpenQueries().get(0).getOrganisationName());
assertEquals(3L, viewModel.getOpenQueries().get(0).getProjectId().longValue());
assertEquals("proj", viewModel.getOpenQueries().get(0).getProjectName());
assertEquals(4L, viewModel.getPendingSpendProfilesCount());
assertTrue(viewModel.isShowTabs());
}
@Test
public void testViewPendingSpendProfiles() throws Exception {
long competitionId = 123L;
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(Role.PROJECT_FINANCE)).build());
SpendProfileStatusResource pendingSpendProfile1 = new SpendProfileStatusResource(11L, 1L, "Project Name 1");
SpendProfileStatusResource pendingSpendProfile2 = new SpendProfileStatusResource(11L, 2L, "Project Name 2");
List<SpendProfileStatusResource> pendingSpendProfiles = asList(pendingSpendProfile1, pendingSpendProfile2);
CompetitionResource competition = newCompetitionResource().withName("comp1").withId(123L).build();
when(competitionPostSubmissionRestService.getCompetitionOpenQueriesCount(competitionId)).thenReturn(restSuccess(4L));
when(competitionPostSubmissionRestService.getPendingSpendProfiles(competitionId)).thenReturn(restSuccess(pendingSpendProfiles));
when(competitionRestServiceMock.getCompetitionById(competitionId)).thenReturn(restSuccess(competition));
MvcResult result = mockMvc.perform(get("/competition/" + competitionId + "/status/pending-spend-profiles"))
.andExpect(view().name("project/competition-pending-spend-profiles"))
.andExpect(model().attribute("model", any(CompetitionPendingSpendProfilesViewModel.class)))
.andReturn();
CompetitionPendingSpendProfilesViewModel viewModel = (CompetitionPendingSpendProfilesViewModel) result.getModelAndView().getModel().get("model");
assertEquals(123L, viewModel.getCompetitionId());
assertEquals("comp1", viewModel.getCompetitionName());
assertEquals(pendingSpendProfiles, viewModel.getPendingSpendProfiles());
assertEquals(4L, viewModel.getOpenQueryCount());
assertEquals(2, viewModel.getPendingSpendProfilesCount());
assertTrue(viewModel.isShowTabs());
}
@Test
public void exportBankDetails() throws Exception {
Long competitionId = 123L;
ByteArrayResource result = new ByteArrayResource("My content!".getBytes());
when(bankDetailsRestServiceMock.downloadByCompetition(competitionId)).thenReturn(restSuccess(result));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm");
mockMvc.perform(get("/competition/123/status/bank-details/export"))
.andExpect(status().isOk())
.andExpect(content().contentType(("text/csv")))
.andExpect(header().string("Content-Type", "text/csv"))
.andExpect(header().string("Content-disposition", "attachment;filename=" + String.format("Bank_details_%s_%s.csv", competitionId, ZonedDateTime.now().format(formatter))))
.andExpect(content().string("My content!"));
verify(bankDetailsRestServiceMock).downloadByCompetition(123L);
}
@Override
protected CompetitionStatusController supplyControllerUnderTest() {
return new CompetitionStatusController();
}
}
|
package io.subutai.core.environment.rest.ui;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.subutai.common.environment.ContainerHostNotFoundException;
import io.subutai.common.environment.Environment;
import io.subutai.common.environment.EnvironmentModificationException;
import io.subutai.common.environment.EnvironmentNotFoundException;
import io.subutai.common.environment.NodeGroup;
import io.subutai.common.environment.Topology;
import io.subutai.common.gson.required.RequiredDeserializer;
import io.subutai.common.host.ContainerHostState;
import io.subutai.common.host.HostInterface;
import io.subutai.common.metric.ResourceHostMetric;
import io.subutai.common.network.DomainLoadBalanceStrategy;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.ContainerSize;
import io.subutai.common.peer.EnvironmentContainerHost;
import io.subutai.common.peer.Peer;
import io.subutai.common.peer.PeerException;
import io.subutai.common.protocol.TemplateKurjun;
import io.subutai.common.quota.ContainerQuota;
import io.subutai.common.resource.PeerGroupResources;
import io.subutai.common.settings.Common;
import io.subutai.common.util.JsonUtil;
import io.subutai.core.environment.api.EnvironmentManager;
import io.subutai.core.environment.api.ShareDto.ShareDto;
import io.subutai.core.environment.api.exception.EnvironmentDestructionException;
import io.subutai.core.kurjun.api.TemplateManager;
import io.subutai.core.lxc.quota.api.QuotaManager;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.core.strategy.api.ContainerPlacementStrategy;
import io.subutai.core.strategy.api.NodeSchema;
import io.subutai.core.strategy.api.StrategyManager;
import io.subutai.core.strategy.api.UnlimitedStrategy;
public class RestServiceImpl implements RestService
{
private static final Logger LOG = LoggerFactory.getLogger( RestServiceImpl.class );
private static final String ERROR_KEY = "ERROR";
private final EnvironmentManager environmentManager;
private final PeerManager peerManager;
private final TemplateManager templateRegistry;
private final StrategyManager strategyManager;
private final QuotaManager quotaManager;
private Gson gson = RequiredDeserializer.createValidatingGson();
public RestServiceImpl( final EnvironmentManager environmentManager, final PeerManager peerManager,
final TemplateManager templateRegistry, final StrategyManager strategyManager,
final QuotaManager quotaManager )
{
Preconditions.checkNotNull( environmentManager );
Preconditions.checkNotNull( peerManager );
Preconditions.checkNotNull( templateRegistry );
Preconditions.checkNotNull( strategyManager );
this.environmentManager = environmentManager;
this.peerManager = peerManager;
this.templateRegistry = templateRegistry;
this.strategyManager = strategyManager;
this.quotaManager = quotaManager;
}
@Override
public Response listTemplates()
{
Set<String> templates =
templateRegistry.list().stream().map( TemplateKurjun::getName ).collect( Collectors.toSet() );
return Response.ok().entity( gson.toJson( templates ) ).build();
}
@Override
public Response getDefaultDomainName()
{
return Response.ok( environmentManager.getDefaultDomainName() ).build();
}
@Override
public Response listEnvironments()
{
Set<Environment> environments = environmentManager.getEnvironments();
Set<EnvironmentDto> environmentDtos = Sets.newHashSet();
for ( Environment environment : environments )
{
EnvironmentDto environmentDto =
new EnvironmentDto( environment.getId(), environment.getName(), environment.getStatus(),
convertContainersToContainerJson( environment.getContainerHosts() ),
environment.getRelationDeclaration() );
environmentDtos.add( environmentDto );
}
return Response.ok( JsonUtil.toJson( environmentDtos ) ).build();
}
@Override
public Response buildAuto( final String name, final String containersJson )
{
Environment environment = null;
try
{
ContainerPlacementStrategy placementStrategy = strategyManager.findStrategyById( UnlimitedStrategy.ID );
List<NodeSchema> schema =
JsonUtil.fromJson( containersJson, new TypeToken<List<NodeSchema>>() {}.getType() );
final PeerGroupResources peerGroupResources = peerManager.getPeerGroupResources();
final Map<ContainerSize, ContainerQuota> quotas = quotaManager.getDefaultQuotas();
Topology topology = placementStrategy.distribute( name, 0, 0, schema, peerGroupResources, quotas );
environment = environmentManager.createEnvironment( topology, true );
}
catch ( Exception e )
{
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
return Response.ok( JsonUtil.toJson( environment.getId() ) ).build();
}
@Override
public Response buildAdvanced( final String name, final String containersJson )
{
Environment environment = null;
try
{
List<NodeGroup> schema = JsonUtil.fromJson( containersJson, new TypeToken<List<NodeGroup>>() {}.getType() );
Topology topology = new Topology( name, 0, 0 );
schema.forEach( s -> topology.addNodeGroupPlacement( s.getPeerId(), s ) );
environment = environmentManager.createEnvironment( topology, true );
}
catch ( Exception e )
{
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
return Response.ok( JsonUtil.toJson( environment.getId() ) ).build();
}
@Override
public Response modifyEnvironment( final String environmentId, final String topologyJson, final String containers )
{
try
{
String name = environmentManager.getEnvironments().stream()
.filter( e -> e.getEnvironmentId().getId().equals( environmentId ) )
.findFirst().get().getName();
ContainerPlacementStrategy placementStrategy = strategyManager.findStrategyById( UnlimitedStrategy.ID );
List<NodeSchema> schema = JsonUtil.fromJson( topologyJson, new TypeToken<List<NodeSchema>>() {}.getType() );
final PeerGroupResources peerGroupResources = peerManager.getPeerGroupResources();
final Map<ContainerSize, ContainerQuota> quotas = quotaManager.getDefaultQuotas();
Topology topology = placementStrategy.distribute( name, 0, 0, schema, peerGroupResources, quotas );
environmentManager.setupRequisites( topology );
}
catch ( Exception e )
{
LOG.error( "Error validating parameters #modifyEnvrionment", e );
return Response.status( Response.Status.BAD_REQUEST ).entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) )
.build();
}
return Response.ok().build();
}
@Override
public Response destroyEnvironment( final String environmentId )
{
try
{
environmentManager.destroyEnvironment( environmentId, false, false );
}
catch ( EnvironmentNotFoundException e )
{
LOG.warn( "Error getting environment by id {}", environmentId );
return Response.status( Response.Status.NOT_FOUND ).build();
}
catch ( EnvironmentDestructionException e )
{
LOG.error( "Error destroying environment #destroyEnvironment", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
return Response.ok().build();
}
@Override
public Response getEnvironmentSShKeys( final String environmentId )
{
try
{
Environment environment = environmentManager.loadEnvironment( environmentId );
return Response.ok( JsonUtil.toJson( environment.getSshKeys() ) ).build();
}
catch ( EnvironmentNotFoundException e )
{
LOG.error( "Cannot find environment ", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
}
@Override
public Response addSshKey( final String environmentId, final String key )
{
if ( Strings.isNullOrEmpty( environmentId ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid environment id" ) ).build();
}
else if ( Strings.isNullOrEmpty( key ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid ssh key" ) ).build();
}
try
{
byte[] bytesEncoded = Base64.decodeBase64( key.getBytes() );
environmentManager.addSshKey( environmentId, new String( bytesEncoded ), false );
}
catch ( EnvironmentNotFoundException e )
{
LOG.warn( "Environment not found by id {}", environmentId );
return Response.status( Response.Status.NOT_FOUND ).build();
}
catch ( EnvironmentModificationException e )
{
LOG.error( "Environment modification failed", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
catch ( Exception e )
{
LOG.error( "Exception setting ssh key", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
return Response.ok().build();
}
@Override
public Response removeSshKey( final String environmentId, final String key )
{
if ( Strings.isNullOrEmpty( environmentId ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid environment id" ) ).build();
}
else if ( Strings.isNullOrEmpty( key ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid ssh key" ) ).build();
}
try
{
byte[] bytesEncoded = Base64.decodeBase64( key.getBytes() );
environmentManager.removeSshKey( environmentId, new String( bytesEncoded ), false );
}
catch ( EnvironmentNotFoundException e )
{
LOG.warn( "Exception getting environment by id {}", environmentId );
return Response.status( Response.Status.NOT_FOUND ).build();
}
catch ( EnvironmentModificationException e )
{
LOG.error( "Error modifying environment", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
return Response.ok().build();
}
@Override
public Response getEnvironmentDomain( final String environmentId )
{
try
{
return Response.ok( JsonUtil.toJson( environmentManager.getEnvironmentDomain( environmentId ) ) ).build();
}
catch ( Exception e )
{
LOG.error( "getEnvironmentDomain error", e );
return Response.status( Response.Status.BAD_REQUEST ).entity( JsonUtil.toJson( e.getMessage() ) ).build();
}
}
@Override
public Response listDomainLoadBalanceStrategies()
{
return Response.ok( JsonUtil.toJson( DomainLoadBalanceStrategy.values() ) ).build();
}
@Override
public Response addEnvironmentDomain( String environmentId, String hostName, String strategyJson, Attachment attr )
{
try
{
DomainLoadBalanceStrategy strategy = JsonUtil.fromJson( strategyJson, DomainLoadBalanceStrategy.class );
if ( attr == null )
{
throw new Exception( "Error, cannot read an attachment", null );
}
File file = new File( System.getProperty( "java.io.tmpdir" ) + "/" + environmentId );
file.createNewFile();
attr.transferTo( file );
environmentManager.assignEnvironmentDomain( environmentId, hostName, strategy,
System.getProperty( "java.io.tmpdir" ) + "/" + environmentId );
}
catch ( Exception e )
{
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
return Response.ok().build();
}
@Override
public Response removeEnvironmentDomain( String environmentId )
{
try
{
environmentManager.removeEnvironmentDomain( environmentId );
}
catch ( EnvironmentModificationException e )
{
LOG.error( "Error removing sshKey ", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
catch ( EnvironmentNotFoundException e )
{
LOG.error( "Cannot find environment ", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
return Response.ok().build();
}
@Override
public Response isContainerDomain( final String environmentId, final String containerId )
{
try
{
return Response.ok( environmentManager.isContainerInEnvironmentDomain( containerId, environmentId ) )
.build();
}
catch ( Exception e )
{
LOG.error( "Cannot check domain status of container", e );
return Response.status( Response.Status.BAD_REQUEST ).entity( JsonUtil.toJson( e.getMessage() ) ).build();
}
}
@Override
public Response setContainerDomain( final String environmentId, final String containerId )
{
try
{
if ( environmentManager.isContainerInEnvironmentDomain( containerId, environmentId ) )
{
environmentManager.removeContainerFromEnvironmentDomain( containerId, environmentId );
}
else
{
environmentManager.addContainerToEnvironmentDomain( containerId, environmentId );
}
}
catch ( Exception e )
{
return Response.status( Response.Status.BAD_REQUEST ).entity( JsonUtil.toJson( e.getMessage() ) ).build();
}
return Response.ok().build();
}
@Override
public Response getContainerEnvironmentId( final String containerId )
{
if ( Strings.isNullOrEmpty( containerId ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid container id" ) ).build();
}
Environment environment = findEnvironmentByContainerId( containerId );
if ( environment != null )
{
return Response.ok( environment.getId() ).build();
}
return Response.status( Response.Status.NOT_FOUND ).build();
}
@Override
public Response destroyContainer( final String containerId )
{
if ( Strings.isNullOrEmpty( containerId ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid container id" ) ).build();
}
Environment environment = findEnvironmentByContainerId( containerId );
if ( environment != null )
{
try
{
ContainerHost containerHost = environment.getContainerHostById( containerId );
environmentManager.destroyContainer( environment.getId(), containerHost.getId(), false, false );
return Response.ok().build();
}
catch ( ContainerHostNotFoundException | EnvironmentNotFoundException | EnvironmentModificationException e )
{
LOG.error( "Error destroying container #destroyContainer", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
}
return Response.status( Response.Status.NOT_FOUND ).build();
}
@Override
public Response getContainerState( final String containerId )
{
if ( Strings.isNullOrEmpty( containerId ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid container id" ) ).build();
}
Environment environment = findEnvironmentByContainerId( containerId );
if ( environment != null )
{
try
{
ContainerHost containerHost = environment.getContainerHostById( containerId );
return Response.ok().entity( JsonUtil.toJson( "STATE", containerHost.getState() ) ).build();
}
catch ( ContainerHostNotFoundException e )
{
LOG.error( "Error getting container state", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
}
return Response.status( Response.Status.NOT_FOUND ).build();
}
@Override
public Response startContainer( final String containerId )
{
if ( Strings.isNullOrEmpty( containerId ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid container id" ) ).build();
}
Environment environment = findEnvironmentByContainerId( containerId );
if ( environment != null )
{
try
{
ContainerHost containerHost = environment.getContainerHostById( containerId );
containerHost.start();
return Response.ok().build();
}
catch ( ContainerHostNotFoundException | PeerException e )
{
LOG.error( "Exception starting container host", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
}
return Response.status( Response.Status.NOT_FOUND ).build();
}
@Override
public Response stopContainer( final String containerId )
{
if ( Strings.isNullOrEmpty( containerId ) )
{
return Response.status( Response.Status.BAD_REQUEST )
.entity( JsonUtil.toJson( ERROR_KEY, "Invalid container id" ) ).build();
}
Environment environment = findEnvironmentByContainerId( containerId );
if ( environment != null )
{
try
{
ContainerHost containerHost = environment.getContainerHostById( containerId );
containerHost.stop();
return Response.ok().build();
}
catch ( ContainerHostNotFoundException | PeerException e )
{
LOG.error( "Exception stopping container host", e );
return Response.serverError().entity( JsonUtil.toJson( ERROR_KEY, e.getMessage() ) ).build();
}
}
return Response.status( Response.Status.NOT_FOUND ).build();
}
@Override
public Response listContainerTypes()
{
return Response.ok().entity( gson.toJson( ContainerSize.values() ) ).build();
}
@Override
public Response getContainerQuota( final String containerId )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// return Response.ok( String.format("{\"cpu\": %s, \"ram\": %s, \"disk\": {\"HOME\": %s, \"VAR\":
// %s, \"ROOT_FS\": %s, \"OPT\": %s}}",
// localPeer.getContainerHostById( containerId ).getCpuQuota(),
// localPeer.getContainerHostById( containerId ).getRamQuota(),
// JsonUtil.toJson(
// localPeer.getContainerHostById(containerId).getDiskQuota(
// JsonUtil.<DiskPartition>fromJson("HOME", new TypeToken<DiskPartition>() {}
// .getType())
// JsonUtil.toJson(
// localPeer.getContainerHostById(containerId).getDiskQuota(
// JsonUtil.<DiskPartition>fromJson("VAR", new TypeToken<DiskPartition>() {}
// .getType())
// JsonUtil.toJson(
// localPeer.getContainerHostById(containerId).getDiskQuota(
// JsonUtil.<DiskPartition>fromJson("ROOT_FS", new TypeToken<DiskPartition>() {}
// .getType())
// JsonUtil.toJson(
// localPeer.getContainerHostById(containerId).getDiskQuota(
// JsonUtil.<DiskPartition>fromJson("OPT", new TypeToken<DiskPartition>() {}
// .getType())
// ) ).build();
// catch ( Exception e )
// LOG.error( "Error getting container quota #getContainerQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response setContainerQuota( final String containerId, final int cpu, final int ram, final Double diskHome,
final Double diskVar, final Double diskRoot, final Double diskOpt )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// localPeer.getContainerHostById( containerId ).setCpuQuota( cpu );
// localPeer.getContainerHostById( containerId ).setRamQuota( ram );
// if(diskHome > 0) {
// DiskQuota homeDiskQuota = new DiskQuota(DiskPartition.HOME, DiskQuotaUnit.GB, diskHome);
// localPeer.getContainerHostById(containerId).setDiskQuota(homeDiskQuota);
// if(diskVar > 0) {
// DiskQuota varDiskQuota = new DiskQuota(DiskPartition.HOME, DiskQuotaUnit.GB, diskVar);
// localPeer.getContainerHostById(containerId).setDiskQuota(varDiskQuota);
// if(diskRoot > 0) {
// DiskQuota rootDiskQuota = new DiskQuota(DiskPartition.HOME, DiskQuotaUnit.GB, diskRoot);
// localPeer.getContainerHostById(containerId).setDiskQuota(rootDiskQuota);
// if(diskOpt > 0) {
// DiskQuota optDiskQuota = new DiskQuota(DiskPartition.HOME, DiskQuotaUnit.GB, diskOpt);
// localPeer.getContainerHostById(containerId).setDiskQuota(optDiskQuota);
// return Response.ok().build();
// catch ( Exception e )
// LOG.error( "Error setting container quota #setContainerQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response getRamQuota( final String containerId )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// return Response.ok( localPeer.getContainerHostById( containerId ).getRamQuota() ).build();
// } catch (Exception e) {
// LOG.error( "Error getting ram quota #getRamQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response setRamQuota( final String containerId, final int ram )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// localPeer.getContainerHostById( containerId ).setRamQuota( ram );
// return Response.ok().build();
// catch ( Exception e )
// LOG.error( "Error setting ram quota #setRamQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response getCpuQuota( final String containerId )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// return Response.ok( localPeer.getContainerHostById( containerId ).getCpuQuota() ).build();
// catch ( Exception e )
// LOG.error( "Error getting cpu quota #getCpuQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response setCpuQuota( final String containerId, final int cpu )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// localPeer.getContainerHostById( containerId ).setCpuQuota( cpu );
// return Response.ok().build();
// catch ( Exception e )
// LOG.error( "Error setting cpu quota #setCpuQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response getDiskQuota( final String containerId, final String diskPartition )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// return Response.ok( JsonUtil.toJson(localPeer.getContainerHostById(containerId).getDiskQuota(
// JsonUtil.<DiskPartition>fromJson(diskPartition, new TypeToken<DiskPartition>() {
// }.getType()))) ).build();
// catch ( Exception e )
// LOG.error( "Error getting disk quota #getDiskQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response setDiskQuota( final String containerId, final String diskQuota )
{
// try
// Preconditions.checkArgument( !Strings.isNullOrEmpty( containerId ) );
// LocalPeer localPeer = peerManager.getLocalPeer();
// localPeer.getContainerHostById( containerId )
// .setDiskQuota( JsonUtil.<DiskQuota>fromJson(diskQuota, new TypeToken<DiskQuota>() {
// }.getType()) );
// return Response.ok().build();
// catch ( Exception e )
// LOG.error( "Error setting disk quota #setDiskQuota", e );
// return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).build();
}
@Override
public Response listPlacementStrategies()
{
return Response.ok( JsonUtil.toJson( strategyManager.getPlacementStrategyTitles() ) ).build();
}
protected CompletionService<Boolean> getCompletionService( Executor executor )
{
return new ExecutorCompletionService<>( executor );
}
@Override
public Response getPeers()
{
List<Peer> peers = peerManager.getPeers();
ExecutorService taskExecutor = Executors.newFixedThreadPool( peers.size() );
CompletionService<Boolean> taskCompletionService = getCompletionService( taskExecutor );
Map<String, List<String>> peerHostMap = Maps.newHashMap();
try
{
for ( Peer peer : peers )
{
taskCompletionService.submit( () -> {
Collection<ResourceHostMetric> collection = peer.getResourceHostMetrics().getResources();
peerHostMap.put( peer.getId(), Lists.newArrayList() );
for ( ResourceHostMetric metric : collection.toArray( new ResourceHostMetric[collection.size()] ) )
{
peerHostMap.get( peer.getId() ).add( metric.getHostInfo().getId() );
}
return true;
} );
}
taskExecutor.shutdown();
for ( Peer ignored : peers )
{
try
{
Future<Boolean> future = taskCompletionService.take();
future.get();
}
catch ( ExecutionException | InterruptedException e )
{
}
}
}
catch ( Exception e )
{
LOG.error( "Resource hosts are empty", e );
}
return Response.ok().entity( JsonUtil.toJson( peerHostMap ) ).build();
}
@Override
public Response addTags( final String environmentId, final String containerId, final String tagsJson )
{
try
{
Environment environment = environmentManager.loadEnvironment( environmentId );
ContainerHost containerHost = environment.getContainerHostById( containerId );
Set<String> tags = JsonUtil.fromJson( tagsJson, new TypeToken<Set<String>>()
{}.getType() );
tags.stream().forEach( tag -> containerHost.addTag( tag ) );
environmentManager.notifyOnContainerStateChanged( environment, null );
}
catch ( Exception e )
{
return Response.status( Response.Status.BAD_REQUEST ).entity( JsonUtil.toJson( e ) ).build();
}
return Response.ok().build();
}
@Override
public Response removeTag( final String environmentId, final String containerId, final String tag )
{
try
{
Environment environment = environmentManager.loadEnvironment( environmentId );
environment.getContainerHostById( containerId ).removeTag( tag );
environmentManager.notifyOnContainerStateChanged( environment, null );
}
catch ( Exception e )
{
return Response.status( Response.Status.BAD_REQUEST ).entity( JsonUtil.toJson( e ) ).build();
}
return Response.ok().build();
}
@Override
public Response setupContainerSsh( final String environmentId, final String containerId )
{
try
{
return Response.ok( environmentManager.setupContainerSsh( containerId, environmentId ) ).build();
}
catch ( Exception e )
{
return Response.status( Response.Status.BAD_REQUEST ).entity( e ).build();
}
}
@Override
public Response getSharedUsers( final String objectId )
{
try
{
List<ShareDto> sharedUsers = environmentManager.getSharedUsers( objectId );
return Response.ok( JsonUtil.toJson( sharedUsers ) ).build();
}
catch ( Exception e )
{
return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e.toString() ).build();
}
}
@Override
public Response shareEnvironment( final String users, final String environmentId )
{
ShareDto[] shareDto = gson.fromJson( users, ShareDto[].class );
environmentManager.shareEnvironment( shareDto, environmentId );
return Response.ok().build();
}
private Environment findEnvironmentByContainerId( String containerId )
{
for ( Environment environment : environmentManager.getEnvironments() )
{
for ( ContainerHost containerHost : environment.getContainerHosts() )
{
if ( containerHost.getId().equals( containerId ) )
{
return environment;
}
}
}
return null;
}
private Set<ContainerDto> convertContainersToContainerJson( Set<EnvironmentContainerHost> containerHosts )
{
Set<ContainerDto> containerDtos = Sets.newHashSet();
for ( EnvironmentContainerHost containerHost : containerHosts )
{
ContainerHostState state = containerHost.getState();
HostInterface iface = containerHost.getInterfaceByName( Common.DEFAULT_CONTAINER_INTERFACE );
containerDtos.add( new ContainerDto( containerHost.getId(), containerHost.getEnvironmentId().getId(),
containerHost.getHostname(), state, iface.getIp(), iface.getMac(), containerHost.getTemplateName(),
containerHost.getContainerSize(), containerHost.getArch().toString(), containerHost.getTags() ) );
}
return containerDtos;
}
}
|
package org.webrtc;
import android.graphics.Matrix;
import android.os.Handler;
import android.support.annotation.Nullable;
/**
* Android texture buffer that glues together the necessary information together with a generic
* release callback. ToI420() is implemented by providing a Handler and a YuvConverter.
*/
public class TextureBufferImpl implements VideoFrame.TextureBuffer {
interface RefCountMonitor {
void onRetain(TextureBufferImpl textureBuffer);
void onRelease(TextureBufferImpl textureBuffer);
void onDestroy(TextureBufferImpl textureBuffer);
}
// This is the full resolution the texture has in memory after applying the transformation matrix
// that might include cropping. This resolution is useful to know when sampling the texture to
// avoid downscaling artifacts.
private final int unscaledWidth;
private final int unscaledHeight;
// This is the resolution that has been applied after cropAndScale().
private final int width;
private final int height;
private final Type type;
private final int id;
private final Matrix transformMatrix;
private final Handler toI420Handler;
private final YuvConverter yuvConverter;
private final RefCountDelegate refCountDelegate;
private final RefCountMonitor refCountMonitor;
public TextureBufferImpl(int width, int height, Type type, int id, Matrix transformMatrix,
Handler toI420Handler, YuvConverter yuvConverter, @Nullable Runnable releaseCallback) {
this(width, height, width, height, type, id, transformMatrix, toI420Handler, yuvConverter,
new RefCountMonitor() {
@Override
public void onRetain(TextureBufferImpl textureBuffer) {}
@Override
public void onRelease(TextureBufferImpl textureBuffer) {}
@Override
public void onDestroy(TextureBufferImpl textureBuffer) {
if (releaseCallback != null) {
releaseCallback.run();
}
}
});
}
TextureBufferImpl(int width, int height, Type type, int id, Matrix transformMatrix,
Handler toI420Handler, YuvConverter yuvConverter, RefCountMonitor refCountMonitor) {
this(width, height, width, height, type, id, transformMatrix, toI420Handler, yuvConverter,
refCountMonitor);
}
private TextureBufferImpl(int unscaledWidth, int unscaledHeight, int width, int height, Type type,
int id, Matrix transformMatrix, Handler toI420Handler, YuvConverter yuvConverter,
RefCountMonitor refCountMonitor) {
this.unscaledWidth = unscaledWidth;
this.unscaledHeight = unscaledHeight;
this.width = width;
this.height = height;
this.type = type;
this.id = id;
this.transformMatrix = transformMatrix;
this.toI420Handler = toI420Handler;
this.yuvConverter = yuvConverter;
this.refCountDelegate = new RefCountDelegate(() -> refCountMonitor.onDestroy(this));
this.refCountMonitor = refCountMonitor;
}
@Override
public VideoFrame.TextureBuffer.Type getType() {
return type;
}
@Override
public int getTextureId() {
return id;
}
@Override
public Matrix getTransformMatrix() {
return transformMatrix;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public VideoFrame.I420Buffer toI420() {
return ThreadUtils.invokeAtFrontUninterruptibly(
toI420Handler, () -> yuvConverter.convert(this));
}
@Override
public void retain() {
refCountMonitor.onRetain(this);
refCountDelegate.retain();
}
@Override
public void release() {
refCountMonitor.onRelease(this);
refCountDelegate.release();
}
@Override
public VideoFrame.Buffer cropAndScale(
int cropX, int cropY, int cropWidth, int cropHeight, int scaleWidth, int scaleHeight) {
final Matrix cropAndScaleMatrix = new Matrix();
// In WebRTC, Y=0 is the top row, while in OpenGL Y=0 is the bottom row. This means that the Y
// direction is effectively reversed.
final int cropYFromBottom = height - (cropY + cropHeight);
cropAndScaleMatrix.preTranslate(cropX / (float) width, cropYFromBottom / (float) height);
cropAndScaleMatrix.preScale(cropWidth / (float) width, cropHeight / (float) height);
return applyTransformMatrix(cropAndScaleMatrix,
(int) Math.round(unscaledWidth * cropWidth / (float) width),
(int) Math.round(unscaledHeight * cropHeight / (float) height), scaleWidth, scaleHeight);
}
/**
* Returns the width of the texture in memory. This should only be used for downscaling, and you
* should still respect the width from getWidth().
*/
public int getUnscaledWidth() {
return unscaledWidth;
}
/**
* Returns the height of the texture in memory. This should only be used for downscaling, and you
* should still respect the height from getHeight().
*/
public int getUnscaledHeight() {
return unscaledHeight;
}
public Handler getToI420Handler() {
return toI420Handler;
}
public YuvConverter getYuvConverter() {
return yuvConverter;
}
/**
* Create a new TextureBufferImpl with an applied transform matrix and a new size. The
* existing buffer is unchanged. The given transform matrix is applied first when texture
* coordinates are still in the unmodified [0, 1] range.
*/
public TextureBufferImpl applyTransformMatrix(
Matrix transformMatrix, int newWidth, int newHeight) {
return applyTransformMatrix(transformMatrix, /* unscaledWidth= */ newWidth,
/* unscaledHeight= */ newHeight, /* scaledWidth= */ newWidth,
/* scaledHeight= */ newHeight);
}
private TextureBufferImpl applyTransformMatrix(Matrix transformMatrix, int unscaledWidth,
int unscaledHeight, int scaledWidth, int scaledHeight) {
final Matrix newMatrix = new Matrix(this.transformMatrix);
newMatrix.preConcat(transformMatrix);
retain();
return new TextureBufferImpl(unscaledWidth, unscaledHeight, scaledWidth, scaledHeight, type, id,
newMatrix, toI420Handler, yuvConverter, new RefCountMonitor() {
@Override
public void onRetain(TextureBufferImpl textureBuffer) {
refCountMonitor.onRetain(TextureBufferImpl.this);
}
@Override
public void onRelease(TextureBufferImpl textureBuffer) {
refCountMonitor.onRelease(TextureBufferImpl.this);
}
@Override
public void onDestroy(TextureBufferImpl textureBuffer) {
release();
}
});
}
}
|
package org.nuxeo.drive.hierarchy.permission.factory;
import java.security.Principal;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.drive.adapter.FileSystemItem;
import org.nuxeo.drive.adapter.FolderItem;
import org.nuxeo.drive.hierarchy.permission.adapter.UserSyncRootParentFolderItem;
import org.nuxeo.drive.hierarchy.userworkspace.adapter.UserWorkspaceHelper;
import org.nuxeo.drive.service.FileSystemItemFactory;
import org.nuxeo.drive.service.FileSystemItemManager;
import org.nuxeo.drive.service.VirtualFolderItemFactory;
import org.nuxeo.drive.service.impl.AbstractFileSystemItemFactory;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.LifeCycleConstants;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.platform.userworkspace.api.UserWorkspaceService;
import org.nuxeo.runtime.api.Framework;
/**
* User workspace based implementation of {@link FileSystemItemFactory} for the
* parent {@link FolderItem} of the user's synchronization roots.
*
* @author Antoine Taillefer
*/
public class UserSyncRootParentFactory extends AbstractFileSystemItemFactory
implements VirtualFolderItemFactory {
private static final Log log = LogFactory.getLog(UserSyncRootParentFactory.class);
protected static final String FOLDER_NAME_PARAM = "folderName";
protected String folderName;
@Override
public void handleParameters(Map<String, String> parameters)
throws ClientException {
// Look for the "folderName" parameter
String folderNameParam = parameters.get(FOLDER_NAME_PARAM);
if (StringUtils.isEmpty(folderNameParam)) {
throw new ClientException(String.format(
"Factory %s has no %s parameter, please provide one.",
getName(), FOLDER_NAME_PARAM));
}
folderName = folderNameParam;
}
@Override
public boolean isFileSystemItem(DocumentModel doc, boolean includeDeleted)
throws ClientException {
// Check user workspace
boolean isUserWorkspace = UserWorkspaceHelper.isUserWorkspace(doc);
if (!isUserWorkspace) {
log.trace(String.format(
"Document %s is not a user workspace, it cannot be adapted as a FileSystemItem.",
doc.getId()));
return false;
}
// Check "deleted" life cycle state
if (!includeDeleted
&& LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState())) {
log.debug(String.format(
"Document %s is in the '%s' life cycle state, it cannot be adapted as a FileSystemItem.",
doc.getId(), LifeCycleConstants.DELETED_STATE));
return false;
}
return true;
}
@Override
protected FileSystemItem adaptDocument(DocumentModel doc,
boolean forceParentItem, FolderItem parentItem)
throws ClientException {
return new UserSyncRootParentFolderItem(getName(), doc, parentItem,
folderName);
}
/**
* Force parent item using {@link #getTopLevelFolderItem(Principal)}.
*/
@Override
public FileSystemItem getFileSystemItem(DocumentModel doc,
boolean includeDeleted) throws ClientException {
Principal principal = doc.getCoreSession().getPrincipal();
return getFileSystemItem(doc, getTopLevelFolderItem(principal),
includeDeleted);
}
@Override
public FolderItem getVirtualFolderItem(Principal principal)
throws ClientException {
DocumentModel userWorkspace = getUserPersonalWorkspace(principal);
return (FolderItem) getFileSystemItem(userWorkspace);
}
@Override
public String getFolderName() {
return folderName;
}
@Override
public void setFolderName(String folderName) {
this.folderName = folderName;
}
protected FolderItem getTopLevelFolderItem(Principal principal)
throws ClientException {
FolderItem topLevelFolder = getFileSystemItemManager().getTopLevelFolder(
principal);
if (topLevelFolder == null) {
throw new ClientException(
"Found no top level folder item. Please check your "
+ "contribution to the following extension point:"
+ " <extension target=\"org.nuxeo.drive.service.FileSystemItemAdapterService\""
+ " point=\"topLevelFolderItemFactory\">.");
}
return topLevelFolder;
}
protected DocumentModel getUserPersonalWorkspace(Principal principal)
throws ClientException {
UserWorkspaceService userWorkspaceService = Framework.getLocalService(UserWorkspaceService.class);
RepositoryManager repositoryManager = Framework.getLocalService(RepositoryManager.class);
// TODO: handle multiple repositories
CoreSession session = getSession(
repositoryManager.getDefaultRepository().getName(), principal);
DocumentModel userWorkspace = userWorkspaceService.getCurrentUserPersonalWorkspace(
session, null);
if (userWorkspace == null) {
throw new ClientException(String.format(
"No personal workspace found for user %s.",
principal.getName()));
}
return userWorkspace;
}
protected FileSystemItemManager getFileSystemItemManager() {
return Framework.getLocalService(FileSystemItemManager.class);
}
protected CoreSession getSession(String repositoryName, Principal principal)
throws ClientException {
return getFileSystemItemManager().getSession(repositoryName, principal);
}
}
|
package fr.openwide.core.wicket.more.security.page;
import org.springframework.security.web.savedrequest.SavedRequest;
import fr.openwide.core.spring.util.StringUtils;
import fr.openwide.core.wicket.more.AbstractCoreSession;
import fr.openwide.core.wicket.more.markup.html.CoreWebPage;
import fr.openwide.core.wicket.more.request.cycle.RequestCycleUtils;
public class LoginSuccessPage extends CoreWebPage {
private static final long serialVersionUID = -875304387617628398L;
private static final String SPRING_SECURITY_SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
private static final String WICKET_BEHAVIOR_LISTENER_URL_FRAGMENT = "IBehaviorListener";
public LoginSuccessPage() {
}
@Override
protected void onInitialize() {
super.onInitialize();
redirectToSavedPage();
}
protected void redirectToSavedPage() {
AbstractCoreSession<?> session = AbstractCoreSession.get();
String redirectUrl = null;
if (StringUtils.hasText(session.getRedirectUrl())) {
redirectUrl = session.getRedirectUrl();
} else {
Object savedRequest = RequestCycleUtils.getCurrentContainerRequest().getSession().getAttribute(SPRING_SECURITY_SAVED_REQUEST);
if (savedRequest instanceof SavedRequest) {
redirectUrl = ((SavedRequest) savedRequest).getRedirectUrl();
}
}
if (isUrlValid(redirectUrl)) {
redirect(redirectUrl);
} else {
redirect(this.getApplication().getHomePage());
}
}
protected boolean isUrlValid(String url) {
return StringUtils.hasText(url) && !StringUtils.contains(url, WICKET_BEHAVIOR_LISTENER_URL_FRAGMENT);
}
}
|
package org.camunda.bpm.demo.cockpit.plugin.recentinstances;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ProcessInstance;
public class RecentProcessInstanceResource extends AbstractCockpitPluginResource {
public RecentProcessInstanceResource(String engineName) {
super(engineName);
}
@GET
@Path("process-instance")
public List<ExtendedProcessInstanceDto> getRecentProcessInstances() {
ArrayList<ExtendedProcessInstanceDto> recentProcessInstances = new ArrayList<ExtendedProcessInstanceDto>();
// processes being started by us:
List<ProcessInstance> processInstances = getProcessEngine().getRuntimeService()
.createProcessInstanceQuery()
.orderByProcessInstanceId().desc()
.listPage(0, 20);
for (ProcessInstance pi : processInstances) {
ExtendedProcessInstanceDto dto = ExtendedProcessInstanceDto.fromProcessInstance(pi);
ProcessDefinition pd = getProcessEngine().getRepositoryService().getProcessDefinition(dto.getProcessDefinitionId());
dto.setProcessDefinition(pd);
HistoricProcessInstance historicProcessInstance = getProcessEngine().getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pi.getId()).singleResult();
if (historicProcessInstance!=null) {
dto.setStartTime(historicProcessInstance.getStartTime());
}
recentProcessInstances.add( dto );
}
return recentProcessInstances;
}
}
|
package org.innovateuk.ifs.application.overview.populator;
import org.innovateuk.ifs.application.ApplicationUrlHelper;
import org.innovateuk.ifs.application.overview.ApplicationOverviewData;
import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewRowViewModel;
import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewSectionViewModel;
import org.innovateuk.ifs.application.overview.viewmodel.ApplicationOverviewViewModel;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.QuestionStatusResource;
import org.innovateuk.ifs.application.service.*;
import org.innovateuk.ifs.application.viewmodel.AssignButtonsViewModel;
import org.innovateuk.ifs.async.generation.AsyncAdaptor;
import org.innovateuk.ifs.async.generation.AsyncFuturesGenerator;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.competition.service.CompetitionThirdPartyConfigRestService;
import org.innovateuk.ifs.form.resource.QuestionResource;
import org.innovateuk.ifs.form.resource.SectionResource;
import org.innovateuk.ifs.form.resource.SectionType;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.question.resource.QuestionSetupType;
import org.innovateuk.ifs.user.resource.ProcessRoleResource;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.service.OrganisationRestService;
import org.innovateuk.ifs.user.service.ProcessRoleRestService;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.Future;
import static java.lang.Boolean.TRUE;
import static java.lang.String.format;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toCollection;
import static org.innovateuk.ifs.competition.resource.CollaborationLevel.SINGLE;
import static org.innovateuk.ifs.form.resource.SectionType.OVERVIEW_FINANCES;
import static org.innovateuk.ifs.question.resource.QuestionSetupType.ASSESSED_QUESTION;
import static org.innovateuk.ifs.question.resource.QuestionSetupType.TERMS_AND_CONDITIONS;
/**
* view model for the application overview page
*/
@Component
public class ApplicationOverviewModelPopulator extends AsyncAdaptor {
private final CompetitionRestService competitionRestService;
private final SectionRestService sectionRestService;
private final QuestionRestService questionRestService;
private final ProcessRoleRestService processRoleRestService;
private final MessageSource messageSource;
private final OrganisationRestService organisationRestService;
private final QuestionStatusRestService questionStatusRestService;
private final SectionStatusRestService sectionStatusRestService;
private final QuestionService questionService;
private final ApplicationUrlHelper applicationUrlHelper;
private static CompetitionThirdPartyConfigRestService competitionThirdPartyConfigRestService;
public ApplicationOverviewModelPopulator(AsyncFuturesGenerator asyncFuturesGenerator, CompetitionRestService competitionRestService,
SectionRestService sectionRestService, QuestionRestService questionRestService,
ProcessRoleRestService processRoleRestService, MessageSource messageSource,
OrganisationRestService organisationRestService, QuestionStatusRestService questionStatusRestService,
SectionStatusRestService sectionStatusRestService,
QuestionService questionService,
ApplicationUrlHelper applicationUrlHelper,
CompetitionThirdPartyConfigRestService competitionThirdPartyConfigRestService) {
super(asyncFuturesGenerator);
this.competitionRestService = competitionRestService;
this.sectionRestService = sectionRestService;
this.questionRestService = questionRestService;
this.processRoleRestService = processRoleRestService;
this.messageSource = messageSource;
this.organisationRestService = organisationRestService;
this.questionStatusRestService = questionStatusRestService;
this.sectionStatusRestService = sectionStatusRestService;
this.questionService = questionService;
this.applicationUrlHelper = applicationUrlHelper;
this.competitionThirdPartyConfigRestService = competitionThirdPartyConfigRestService;
}
public ApplicationOverviewViewModel populateModel(ApplicationResource application, UserResource user) {
Future<OrganisationResource> organisation = async(() -> organisationRestService.getByUserAndApplicationId(user.getId(), application.getId()).getSuccess());
Future<CompetitionResource> competition = async(() -> competitionRestService.getCompetitionById(application.getCompetition()).getSuccess());
Future<List<SectionResource>> sections = async(() -> sectionRestService.getByCompetition(application.getCompetition()).getSuccess());
Future<List<QuestionResource>> questions = async(() -> questionRestService.findByCompetition(application.getCompetition()).getSuccess());
Future<List<ProcessRoleResource>> processRoles = async(() -> processRoleRestService.findProcessRole(application.getId()).getSuccess());
Future<List<QuestionStatusResource>> statuses = async(() -> questionStatusRestService.findByApplicationAndOrganisation(application.getId(), resolve(organisation).getId()).getSuccess());
Future<List<Long>> completedSectionIds = async(() -> sectionStatusRestService.getCompletedSectionIds(application.getId(), resolve(organisation).getId()).getSuccess());
Future<Map<Long, Set<Long>>> completedSectionsByOrganisation = async(() -> sectionStatusRestService.getCompletedSectionsByOrganisation(application.getId()).getSuccess());
async(() -> {
List<QuestionStatusResource> notifications = questionService.getNotificationsForUser(resolve(statuses), user.getId());
questionService.removeNotifications(notifications);
});
ApplicationOverviewData data = new ApplicationOverviewData(resolve(competition), application, resolve(sections),
resolve(questions), resolve(processRoles), resolve(organisation), resolve(statuses),
resolve(completedSectionIds), resolve(completedSectionsByOrganisation), user);
Set<ApplicationOverviewSectionViewModel> sectionViewModels = data.getSections()
.values()
.stream()
.sorted(comparing(SectionResource::getPriority))
.filter(section -> section.getParentSection() == null)
.filter(section -> section.getType() != SectionType.KTP_ASSESSMENT)
.filter(section -> !application.isEnabledForExpressionOfInterest() || section.isEnabledForPreRegistration())
.map(section -> sectionViewModel(section, data))
.collect(toCollection(LinkedHashSet::new));
return new ApplicationOverviewViewModel(data.getUserProcessRole(), data.getCompetition(), application, sectionViewModels, application.hasBeenReopened(), application.getLastStateChangeDate());
}
private ApplicationOverviewSectionViewModel sectionViewModel(SectionResource section, ApplicationOverviewData data) {
Set<ApplicationOverviewRowViewModel> rows;
if (!section.getChildSections().isEmpty()) {
rows = section.getChildSections()
.stream()
.map(data.getSections()::get)
.filter(childSection -> !(data.getCompetition().isFullyFunded() && childSection.getType().equals(OVERVIEW_FINANCES)))
.filter(childSection -> !data.getApplication().isEnabledForExpressionOfInterest() || section.isEnabledForPreRegistration())
.map(childSection ->
new ApplicationOverviewRowViewModel(
childSection.getName(),
format("/application/%d/form/section/%d", data.getApplication().getId(), childSection.getId()),
data.getCompletedSectionIds().contains(childSection.getId()),
true,
childSection.isEnabledForPreRegistration()
)
)
.collect(toCollection(LinkedHashSet::new));
} else {
rows = section.getQuestions()
.stream()
.map(data.getQuestions()::get)
.filter(question -> !data.getApplication().isEnabledForExpressionOfInterest() || question.isEnabledForPreRegistration())
.map(question -> getApplicationOverviewRowViewModel(data, question, section))
.collect(toCollection(LinkedHashSet::new));
}
if (section.isTermsAndConditions() && data.getCompetition().getTermsAndConditions().isProcurementThirdParty()) {
String labelName = competitionThirdPartyConfigRestService.findOneByCompetitionId(data.getCompetition().getId()).getSuccess().getTermsAndConditionsLabel();
section.setName(labelName);
}
String subtitle = subtitle(data.getCompetition(), section);
return new ApplicationOverviewSectionViewModel(section.getId(),
data.getApplication().isEnabledForExpressionOfInterest() && section.isEnabledForPreRegistration() &&
SectionType.APPLICATION_QUESTIONS.equals(section.getType()) ? "Expression of interest questions" : section.getName(),
subtitle, rows, section.isTermsAndConditions());
}
private String subtitle(CompetitionResource competition, SectionResource section) {
String messageCode;
switch (section.getType()) {
case FINANCES:
messageCode = getFinanceSectionSubTitle(competition);
break;
case PROJECT_DETAILS:
if (competition.isKtp()) {
messageCode = "ifs.section.projectDetails.ktp.description";
} else {
messageCode = "ifs.section.projectDetails.description";
}
break;
case TERMS_AND_CONDITIONS:
if (competition.isExpressionOfInterest()) {
messageCode = "ifs.section.termsAndConditionsEoi.description";
} else {
messageCode = competition.getTermsAndConditions().isProcurementThirdParty()
? "ifs.section.termsAndConditionsProcurementThirdParty.description"
: "ifs.section.termsAndConditions.description";
}
break;
case APPLICATION_QUESTIONS:
if (!competition.isKtp() && competition.isHasAssessmentStage()) {
messageCode = "ifs.section.applicationQuestions.description";
break;
}
return null;
default:
return null;
}
return messageSource.getMessage(messageCode, null, Locale.getDefault());
}
private ApplicationOverviewRowViewModel getApplicationOverviewRowViewModel(ApplicationOverviewData data, QuestionResource question, SectionResource section) {
boolean complete = (question.getQuestionSetupType() == QuestionSetupType.NORTHERN_IRELAND_DECLARATION) ? isSubsidyBasisComplete(data, question) :
(section.isTermsAndConditions() ? isTermsAndConditionsComplete(data, question, section) :
(data.getStatuses().get(question.getId())
.stream()
.anyMatch(status -> TRUE.equals(status.getMarkedAsComplete()))
)
);
boolean showStatus = !(section.isTermsAndConditions() && data.getCompetition().isExpressionOfInterest());
return getAssignableViewModel(question, data)
.map(avm ->
new ApplicationOverviewRowViewModel(
getQuestionTitle(question, data),
getRowUrlFromQuestion(question, data),
complete,
avm,
showStatus,
question.isEnabledForPreRegistration())
).orElse(
new ApplicationOverviewRowViewModel(
getQuestionTitle(question, data),
getRowUrlFromQuestion(question, data),
complete,
showStatus,
question.isEnabledForPreRegistration())
);
}
private String getRowUrlFromQuestion(QuestionResource question, ApplicationOverviewData data) {
return applicationUrlHelper.getQuestionUrl(question.getQuestionSetupType(), question.getId(), data.getApplication().getId(), data.getOrganisation().getId())
.orElse(format("/application/%d/form/question/%d", data.getApplication().getId(), question.getId()));
}
private boolean isSubsidyBasisComplete(ApplicationOverviewData data, QuestionResource question) {
boolean completeForOrganisation = data.getStatuses().get(question.getId())
.stream()
.anyMatch(questionStatus -> questionStatus.getMarkedAsComplete() != null && questionStatus.getMarkedAsComplete());
boolean leadOrganisation = data.getLeadApplicant().getOrganisationId().equals(data.getOrganisation().getId());
long totalOrganisations = organisationRestService.getOrganisationsByApplicationId(data.getApplication().getId()).getSuccess().size();
long answeredOrganisations = questionStatusRestService.findQuestionStatusesByQuestionAndApplicationId(question.getId(), data.getApplication().getId()).getSuccess().stream()
.filter(questionStatus -> questionStatus.getMarkedAsComplete() != null && questionStatus.getMarkedAsComplete()).count();
boolean completeForAll = totalOrganisations == answeredOrganisations;
return (!leadOrganisation && completeForOrganisation) || completeForAll;
}
private static boolean isTermsAndConditionsComplete(ApplicationOverviewData data, QuestionResource question, SectionResource section) {
boolean completeForOrganisation = data.getStatuses().get(question.getId())
.stream()
.anyMatch(status -> status.getMarkedAsComplete() != null && status.getMarkedAsComplete());
boolean leadOrganisation = data.getLeadApplicant().getOrganisationId().equals(data.getOrganisation().getId());
boolean completeForAll = data.getCompletedSectionsByOrganisation()
.values()
.stream()
.allMatch(completedSections -> completedSections.contains(section.getId()));
return !leadOrganisation && completeForOrganisation || completeForAll;
}
private static Optional<AssignButtonsViewModel> getAssignableViewModel(QuestionResource question, ApplicationOverviewData data) {
if (!question.isAssignEnabled()) {
return Optional.empty();
} else {
AssignButtonsViewModel viewModel = new AssignButtonsViewModel();
Optional<QuestionStatusResource> maybeStatus = data.getStatuses().get(question.getId())
.stream()
.filter(status -> status.getAssignee() != null)
.findFirst();
viewModel.setCurrentApplicant(data.getUserProcessRole());
viewModel.setLeadApplicant(data.getLeadApplicant());
viewModel.setAssignableApplicants(new ArrayList<>(data.getProcessRoles().values()));
viewModel.setQuestion(question);
viewModel.setAssignedBy(maybeStatus.map(status -> data.getProcessRoles().get(status.getAssignedBy())).orElse(null));
viewModel.setAssignee(maybeStatus.map(status -> data.getProcessRoles().get(status.getAssignee())).orElse(null));
return Optional.of(viewModel);
}
}
private static String getQuestionTitle(QuestionResource question, ApplicationOverviewData data) {
CompetitionResource competition = data.getCompetition();
ApplicationResource application = data.getApplication();
boolean preRegistration = application.isEnabledForExpressionOfInterest();
String questionTitle = preRegistration ? format("%s", question.getShortName()) : format("%s. %s", question.getQuestionNumber(), question.getShortName());
return (question.getQuestionSetupType() == ASSESSED_QUESTION) ?
questionTitle : thirdPartyTermsAndConditionsQuestion(question, competition) ?
getThirdPartyTermsAndConditionsQuestionTitle(competition) : question.getShortName();
}
private String getFinanceSectionSubTitle(CompetitionResource competition) {
if (competition.isFullyFunded()) {
return "ifs.section.finances.fullyFunded.description";
} else if (competition.getCollaborationLevel() == SINGLE) {
return "ifs.section.finances.description";
} else {
return "ifs.section.finances.collaborative.description";
}
}
private static boolean thirdPartyTermsAndConditionsQuestion(QuestionResource question, CompetitionResource competition) {
return question.getQuestionSetupType().equals(TERMS_AND_CONDITIONS) && competition.getTermsAndConditions().isProcurementThirdParty();
}
private static String getThirdPartyTermsAndConditionsQuestionTitle(CompetitionResource competition) {
return competitionThirdPartyConfigRestService.findOneByCompetitionId(competition.getId()).getSuccess().getTermsAndConditionsLabel();
}
}
|
package fr.openwide.maven.artifact.notifier.core.business.url.hibernate;
import org.hibernate.type.Type;
import fr.openwide.maven.artifact.notifier.core.business.url.model.ExternalLinkStatus;
import fr.openwide.maven.artifact.notifier.core.business.url.model.ExternalLinkWrapper;
public class ExternalLinkWrapperInterceptor extends AbstractPropertyChangeInterceptor<ExternalLinkWrapper> {
private static final long serialVersionUID = 1L;
private static final String URL_FIELD_NAME = "url";
private static final String STATUS_FIELD_NAME = "status";
private static final String CONSECUTIVE_FAILURES_FIELD_NAME = "consecutiveFailures";
private static final String LAST_CHECK_DATE_FIELD_NAME = "lastCheckDate";
private static final String LAST_STATUS_CODE_FIELD_NAME = "lastStatusCode";
@Override
protected Class<ExternalLinkWrapper> getObservedClass() {
return ExternalLinkWrapper.class;
}
@Override
protected String getObservedFieldName() {
return URL_FIELD_NAME;
}
@Override
protected boolean onChange(Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
// If the link's URL field changes, we reset its other properties
for (int i = 0; i < currentState.length; ++i) {
if (STATUS_FIELD_NAME.equals(propertyNames[i])) {
currentState[i] = ExternalLinkStatus.ONLINE;
} else if (CONSECUTIVE_FAILURES_FIELD_NAME.equals(propertyNames[i])) {
currentState[i] = 0;
} else if (LAST_CHECK_DATE_FIELD_NAME.equals(propertyNames[i]) ||
LAST_STATUS_CODE_FIELD_NAME.equals(propertyNames[i])) {
currentState[i] = null;
}
}
return true;
}
}
|
package fr.openwide.core.jpa.migration.processor;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionTemplate;
import com.google.common.collect.Lists;
import fr.openwide.core.jpa.migration.monitor.ProcessorMonitorContext;
import fr.openwide.core.jpa.migration.monitor.ThreadLocalInitializingCallable;
import fr.openwide.core.jpa.migration.transaction.TransactionWrapperCallable;
import fr.openwide.core.spring.config.CoreConfigurer;
import fr.openwide.core.spring.util.StringUtils;
public class ThreadedProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadedProcessor.class);
private final int threadPoolSize;
private final int keepAliveTime;
private final TimeUnit unit;
private final int maxTotalDuration;
private final TimeUnit maxTotalDurationTimeUnit;
private final Integer loggingCheckIntervalTime;
private final TimeUnit loggingCheckIntervalTimeUnit;
private final Integer maxLoggingTime;
private final TimeUnit maxLoggingTimeUnit;
private final Integer maxLoggingIncrement;
private final Logger progressLogger;
private final CoreConfigurer configurer;
private String loggerContext;
private ProcessorMonitorContext monitorContext;
public ThreadedProcessor(int threadPoolSize,
int maxTotalDuration, TimeUnit maxTotalDurationUnit,
int keepAliveTime, TimeUnit unit, CoreConfigurer configurer) {
this(threadPoolSize, maxTotalDuration, maxTotalDurationUnit, keepAliveTime, maxTotalDurationUnit, configurer,
null, null, null, null, null, null);
}
public ThreadedProcessor(int threadPoolSize,
int maxTotalDuration, TimeUnit maxTotalDurationUnit,
int keepAliveTime, TimeUnit unit,
CoreConfigurer configurer,
Integer loggingCheckIntervalTime, TimeUnit loggingCheckIntervalTimeUnit,
Integer maxLoggingTime, TimeUnit maxLoggingTimeUnit,
Integer maxLoggingIncrement,
Logger progressLogger) {
super();
this.threadPoolSize = threadPoolSize;
this.keepAliveTime = keepAliveTime;
this.unit = unit;
this.maxTotalDuration = maxTotalDuration;
this.maxTotalDurationTimeUnit = maxTotalDurationUnit;
this.loggingCheckIntervalTime = loggingCheckIntervalTime;
this.loggingCheckIntervalTimeUnit = loggingCheckIntervalTimeUnit;
this.maxLoggingTime = maxLoggingTime;
this.maxLoggingTimeUnit = maxLoggingTimeUnit;
this.maxLoggingIncrement = maxLoggingIncrement;
this.progressLogger = progressLogger;
this.configurer = configurer;
}
public <T> List<Future<T>> runWithoutTransaction(String loggerContext, List<Callable<T>> callables) {
return runWithoutTransaction(loggerContext, callables, null);
}
public <T> List<Future<T>> runWithoutTransaction(String loggerContext, List<Callable<T>> callables, Integer totalItems) {
return runWithTransaction(loggerContext, callables, null, totalItems);
}
public <T> List<Future<T>> runWithTransaction(String loggerContext, List<Callable<T>> callables, TransactionTemplate transactionTemplate, Integer totalItems) {
this.loggerContext = loggerContext;
List<Future<T>> futures = Lists.newArrayList();
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
ThreadPoolExecutor executor = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, keepAliveTime, unit, workQueue);
executor.prestartAllCoreThreads();
Thread loggingThread = null;
this.monitorContext = new ProcessorMonitorContext();
if (progressLogger != null) {
loggingThread = new Thread(new LoggingRunnable());
}
if (totalItems != null) {
this.monitorContext.getTotalItems().set(totalItems);
}
try {
for (Callable<T> callable : callables) {
Callable<T> wrappedCallable = new ThreadLocalInitializingCallable<>(callable, ProcessorMonitorContext.getThreadLocal(), monitorContext);
if (transactionTemplate != null) {
futures.add(executor.submit(new TransactionWrapperCallable<T>(transactionTemplate, wrappedCallable)));
} else {
futures.add(executor.submit(wrappedCallable));
}
}
executor.shutdown();
if (loggingThread != null) {
loggingThread.start();
}
List<Future<T>> terminatedFutures = Lists.newArrayList();
boolean interrupted = false;
try {
boolean terminated = executor.awaitTermination(maxTotalDuration, maxTotalDurationTimeUnit);
if (!terminated) {
LOGGER.warn("Les tâches n'ont pas été terminées avant expiration du timeout de {} {}", maxTotalDuration, maxTotalDurationTimeUnit.name());
}
LOGGER.warn("{} - {} éléments importés", loggerContext, this.monitorContext.getDoneItems());
if (this.monitorContext.getFailedItems().get() > 0) {
LOGGER.error("{} - {} élément(s) en erreur", loggerContext, this.monitorContext.getFailedItems().get());
}
for (Future<T> future : futures) {
try {
future.get(0, TimeUnit.SECONDS);
if (future.isDone()) {
terminatedFutures.add(future);
} else {
interrupted = true;
}
} catch (ExecutionException e) {
throw new IllegalStateException("Une tâche d'import d'objets a échoué ; interruption de l'import.", e);
} catch (TimeoutException timeoutException) {
future.cancel(true);
interrupted = true;
}
}
} catch (InterruptedException e) {
throw new IllegalStateException("Erreur d'import : timeout.", e);
}
if (interrupted) {
throw new IllegalStateException("Erreur d'import : interruption d'un thread de traitement.");
}
return terminatedFutures;
} finally {
ProcessorMonitorContext.unset();
if (loggingThread != null) {
loggingThread.interrupt();
try {
loggingThread.join();
} catch (InterruptedException e) {
LOGGER.warn("Thread interrompu pendant l'attente de la fin de l'exécution du thread de logging d'avancement.");
}
}
}
}
protected class LoggingRunnable implements Runnable {
private long startTime;
private long lastLoggingTime;
private int lastDoneItems;
@Override
public void run() {
startTime = System.currentTimeMillis();
lastLoggingTime = startTime;
lastDoneItems = 0;
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(loggingCheckIntervalTimeUnit.toMillis(loggingCheckIntervalTime));
log(false);
} catch (InterruptedException e) {
log(true);
LOGGER.info("Thread de logging d'avancement interrompu.");
return;
}
}
log(true);
}
public void log(boolean force) {
long currentTime = System.currentTimeMillis();
int doneItems = monitorContext.getDoneItems().get();
if (force
|| (lastLoggingTime - currentTime) > maxLoggingTimeUnit.toMillis(maxLoggingTime)
|| (doneItems - lastDoneItems) > maxLoggingIncrement) {
Float speedSinceStart = (float) doneItems / (float) (currentTime - startTime);
int roundedSpeedSinceStart = Math.round(speedSinceStart * 1000);
Float speedSinceLast = (float) (doneItems - lastDoneItems) / (float) (currentTime - lastLoggingTime);
int roundedSpeedSinceLast = Math.round(speedSinceLast * 1000);
lastLoggingTime = currentTime;
lastDoneItems = doneItems;
StringBuilder sb = new StringBuilder();
if (StringUtils.hasText(loggerContext)) {
sb.append(loggerContext).append(" - ");
}
sb.append("Avancement {} / {} ({} items / s. depuis début, {} items / s. depuis dernier log)");
if (configurer.isMigrationLoggingMemory()) {
sb.append(" - Mémoire disponible {} / {}");
progressLogger.info(sb.toString(), doneItems, monitorContext.getTotalItems().get(),
roundedSpeedSinceStart, roundedSpeedSinceLast,
StringUtils.humanReadableByteCount(Runtime.getRuntime().freeMemory(), true),
StringUtils.humanReadableByteCount(Runtime.getRuntime().totalMemory(), true));
} else {
progressLogger.info(sb.toString(), doneItems, monitorContext.getTotalItems().get(),
roundedSpeedSinceStart, roundedSpeedSinceLast);
}
}
}
}
}
|
package com.techshroom.tscore.math.exceptions;
public class EvalException extends RuntimeException {
public static enum Reason {
/**
* No numbers to eval. Args: []
*/
NO_NUMBERS("No numbers were provided"),
/**
* Too many numbers to eval. Args: [expected, found]
*/
TOO_MANY_NUMBERS("Expected %s numbers but found %s"),
/**
* No operator found. Args: [operator]
*/
NO_SUCH_OPERATOR("No such operator %s"),
/**
* No function found. Args: [function_name]
*/
NO_SUCH_FUNCTION("No such function %s"),
/**
* Needed an operator. Args: []
*/
NEEDED_OPERATOR("Needed an operator."),
/**
* Needed a function. Args: []
*/
NEEDED_FUNCTION("Needed a function."),
/**
* Unexpected error. Args: [expected_char, index_or_str]
*/
PARSE_ERROR("Unexpected error while reading string, expected %s @ %s"),
/**
* Operator failed during processing. Args: [operator]
*/
OPERATOR_ERROR("Operator %s threw an error while being processed"),
/**
* Function failed during processing. Args: [function_name]
*/
FUNCTION_ERROR("Function %s threw an error while being processed");
private final String message;
private Reason(String msg) {
message = msg;
}
public String formmated(Object... args) {
return String.format(message, args);
}
public String unformmated() {
return message;
}
}
private static final long serialVersionUID = -987635654396074492L;
private final Reason reason;
public EvalException(Reason r) {
super(r.unformmated());
reason = r;
}
public EvalException(Reason r, Object... args) {
super(r.formmated(args));
reason = r;
}
public EvalException(Reason r, Throwable cause) {
super(r.unformmated(), cause);
reason = r;
}
public EvalException(Reason r, Throwable cause, Object... args) {
super(r.formmated(args), cause);
reason = r;
}
public Reason getReason() {
return reason;
}
}
|
package dr.app.seqgen;
import dr.evolution.tree.Tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.datatype.Microsatellite;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.Patterns;
import dr.evolution.sequence.Sequence;
import dr.evolution.util.Taxa;
import dr.evomodel.sitemodel.SiteModel;
import dr.evomodel.branchratemodel.BranchRateModel;
/**
* @author Chieh-Hsi Wu
*
* Simulates a pattern of microsatellites given a tree and microsatellite model
*
*/
public class MicrosatelliteSimulator extends SequenceSimulator{
private Taxa taxa;
private Microsatellite dataType;
public MicrosatelliteSimulator(
Microsatellite dataType,
Taxa taxa,
Tree tree,
SiteModel siteModel,
BranchRateModel branchRateModel) {
super(tree, siteModel, branchRateModel, 1);
this.dataType = dataType;
this.taxa = taxa;
}
/**
* Convert integer representation of microsatellite length to string.
*/
Sequence intArray2Sequence(int [] seq, NodeRef node) {
String sSeq = ""+seq[0];
return new Sequence(m_tree.getNodeTaxon(node), sSeq);
} // intArray2Sequence
/**
* Convert an alignment to a pattern
*/
public Patterns simulateMsatPattern(){
Alignment align = simulate();
System.out.println(align);
int[] pattern = new int[align.getTaxonCount()];
for(int i = 0; i < pattern.length; i++){
String taxonName = align.getSequence(i).getTaxon().getId();
int index = taxa.getTaxonIndex(taxonName);
pattern[index] = Integer.parseInt(align.getSequence(i).getSequenceString());
}
Patterns patterns = new Patterns(dataType,taxa);
patterns.addPattern(pattern);
return patterns;
}
}
|
package org.xwiki.logging.internal.tail;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.logging.event.LogEvent;
import org.xwiki.xstream.internal.SafeXStream;
/**
* Read and write the log in XStream XML format.
*
* @version $Id$
* @since 11.9RC1
*/
@Component(roles = XStreamFileLoggerTail.class)
@Singleton
public class XStreamFileLoggerTail extends AbstractTextFileLoggerTail
{
protected static final String FILE_EXTENSION = ".xml";
@Inject
private SafeXStream xstream;
/**
* @param path the base path of the log
* @throws IOException when failing to create the log files
*/
@Override
public void initialize(Path path, boolean readonly) throws IOException
{
super.initialize(path, StandardCharsets.UTF_8, readonly);
}
@Override
protected String getFileExtension()
{
return FILE_EXTENSION;
}
/**
* @param path the base path of the log
* @return true of a log has been stored at this location
*/
public static boolean exist(Path path)
{
return exist(path, FILE_EXTENSION);
}
@Override
protected LogEvent read(Reader reader)
{
return (LogEvent) this.xstream.fromXML(reader);
}
@Override
protected void write(LogEvent logEvent, Writer writer)
{
this.xstream.toXML(logEvent, writer);
}
}
|
package dr.inference.model;
import dr.util.NumberFormatter;
import dr.xml.Reportable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
/**
* A likelihood function which is simply the product of a set of likelihood functions.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $
*/
public class CompoundLikelihood implements Likelihood, Reportable {
public final static boolean UNROLL_COMPOUND = true;
public final static boolean EVALUATION_TIMERS = true;
public final long[] evaluationTimes;
public final int[] evaluationCounts;
public CompoundLikelihood(int threads, Collection<Likelihood> likelihoods) {
int i = 0;
for (Likelihood l : likelihoods) {
addLikelihood(l, i, true);
i++;
}
if (threads < 0 && this.likelihoods.size() > 1) {
// asking for an automatic threadpool size and there is more than one likelihood to compute
threadCount = this.likelihoods.size();
} else if (threads > 0) {
threadCount = threads;
} else {
// no thread pool requested or only one likelihood
threadCount = 0;
}
if (threadCount > 0) {
pool = Executors.newFixedThreadPool(threadCount);
// } else if (threads < 0) {
// // create a cached thread pool which should create one thread per likelihood...
// pool = Executors.newCachedThreadPool();
} else {
pool = null;
}
if (EVALUATION_TIMERS) {
evaluationTimes = new long[this.likelihoods.size()];
evaluationCounts = new int[this.likelihoods.size()];
} else {
evaluationTimes = null;
evaluationCounts = null;
}
}
public CompoundLikelihood(Collection<Likelihood> likelihoods) {
pool = null;
threadCount = 0;
int i = 0;
for (Likelihood l : likelihoods) {
addLikelihood(l, i, false);
i++;
}
if (EVALUATION_TIMERS) {
evaluationTimes = new long[this.likelihoods.size()];
evaluationCounts = new int[this.likelihoods.size()];
} else {
evaluationTimes = null;
evaluationCounts = null;
}
}
protected void addLikelihood(Likelihood likelihood, int index, boolean addToPool) {
// unroll any compound likelihoods
if (UNROLL_COMPOUND && addToPool && likelihood instanceof CompoundLikelihood) {
for (Likelihood l : ((CompoundLikelihood)likelihood).getLikelihoods()) {
addLikelihood(l, index, addToPool);
}
} else {
if (!likelihoods.contains(likelihood)) {
likelihoods.add(likelihood);
if (likelihood.getModel() != null) {
compoundModel.addModel(likelihood.getModel());
}
if (likelihood.evaluateEarly()) {
earlyLikelihoods.add(likelihood);
} else {
// late likelihood list is used to evaluate them if the thread pool is not being used...
lateLikelihoods.add(likelihood);
if (addToPool) {
likelihoodCallers.add(new LikelihoodCaller(likelihood, index));
}
}
}
}
}
public int getLikelihoodCount() {
return likelihoods.size();
}
public final Likelihood getLikelihood(int i) {
return likelihoods.get(i);
}
public List<Likelihood> getLikelihoods() {
return likelihoods;
}
public List<Callable<Double>> getLikelihoodCallers() {
return likelihoodCallers;
}
// Likelihood IMPLEMENTATION
public Model getModel() {
return compoundModel;
}
// // todo: remove in release
// static int DEBUG = 0;
public double getLogLikelihood() {
double logLikelihood = evaluateLikelihoods(earlyLikelihoods);
if( logLikelihood == Double.NEGATIVE_INFINITY ) {
return Double.NEGATIVE_INFINITY;
}
if (pool == null) {
// Single threaded
logLikelihood += evaluateLikelihoods(lateLikelihoods);
} else {
try {
List<Future<Double>> results = pool.invokeAll(likelihoodCallers);
for (Future<Double> result : results) {
double logL = result.get();
logLikelihood += logL;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// if( DEBUG > 0 ) {
// int t = DEBUG; DEBUG = 0;
// System.err.println(getId() + ": " + getDiagnosis(0) + " = " + logLikelihood);
// DEBUG = t;
return logLikelihood;
}
private double evaluateLikelihoods(ArrayList<Likelihood> likelihoods) {
double logLikelihood = 0.0;
int i = 0;
for (Likelihood likelihood : likelihoods) {
if (EVALUATION_TIMERS) {
// this code is only compiled if EVALUATION_TIMERS is true
long time = System.nanoTime();
double l = likelihood.getLogLikelihood();
evaluationTimes[i] += System.nanoTime() - time;
evaluationCounts[i] ++;
if( l == Double.NEGATIVE_INFINITY )
return Double.NEGATIVE_INFINITY;
logLikelihood += l;
i++;
} else {
final double l = likelihood.getLogLikelihood();
// if the likelihood is zero then short cut the rest of the likelihoods
// This means that expensive likelihoods such as TreeLikelihoods should
// be put after cheap ones such as BooleanLikelihoods
if( l == Double.NEGATIVE_INFINITY )
return Double.NEGATIVE_INFINITY;
logLikelihood += l;
}
}
return logLikelihood;
}
public void makeDirty() {
for( Likelihood likelihood : likelihoods ) {
likelihood.makeDirty();
}
}
public boolean evaluateEarly() {
return false;
}
public String getDiagnosis() {
return getDiagnosis(0);
}
public String getDiagnosis(int indent) {
String message = "";
boolean first = true;
final NumberFormatter nf = new NumberFormatter(6);
for( Likelihood lik : likelihoods ) {
if( !first ) {
message += ", ";
} else {
first = false;
}
if (indent >= 0) {
message += "\n";
for (int i = 0; i < indent; i++) {
message += " ";
}
}
message += lik.prettyName() + "=";
if( lik instanceof CompoundLikelihood ) {
final String d = ((CompoundLikelihood) lik).getDiagnosis(indent < 0 ? -1 : indent + 2);
if( d != null && d.length() > 0 ) {
message += "(" + d;
if (indent >= 0) {
message += "\n";
for (int i = 0; i < indent; i++) {
message += " ";
}
}
message += ")";
}
} else {
final double logLikelihood = lik.getLogLikelihood();
if( logLikelihood == Double.NEGATIVE_INFINITY ) {
message += "-Inf";
} else if( Double.isNaN(logLikelihood) ) {
message += "NaN";
} else if( logLikelihood == Double.POSITIVE_INFINITY ) {
message += "+Inf";
} else {
message += nf.formatDecimal(logLikelihood, 4);
}
}
}
message += "\n";
for (int i = 0; i < indent; i++) {
message += " ";
}
message += "Total = " + this.getLogLikelihood();
return message;
}
public String toString() {
return getId();
// really bad for debugging
//return Double.toString(getLogLikelihood());
}
public String prettyName() {
return Abstract.getPrettyName(this);
}
public boolean isUsed() {
return used;
}
public void setUsed() {
used = true;
for (Likelihood l : likelihoods) {
l.setUsed();
}
}
public int getThreadCount() {
return threadCount;
}
// Loggable IMPLEMENTATION
/**
* @return the log columns.
*/
public dr.inference.loggers.LogColumn[] getColumns() {
return new dr.inference.loggers.LogColumn[]{
new LikelihoodColumn(getId() == null ? "likelihood" : getId())
};
}
private class LikelihoodColumn extends dr.inference.loggers.NumberColumn {
public LikelihoodColumn(String label) {
super(label);
}
public double getDoubleValue() {
return getLogLikelihood();
}
}
// Reportable IMPLEMENTATION
public String getReport() {
return getReport(0);
}
public String getReport(int indent) {
if (EVALUATION_TIMERS) {
String message = "";
boolean first = true;
final NumberFormatter nf = new NumberFormatter(6);
int index = 0;
for( Likelihood lik : likelihoods ) {
if( !first ) {
message += ", ";
} else {
first = false;
}
if (indent >= 0) {
message += "\n";
for (int i = 0; i < indent; i++) {
message += " ";
}
}
message += lik.prettyName() + "=";
if( lik instanceof CompoundLikelihood ) {
final String d = ((CompoundLikelihood) lik).getReport(indent < 0 ? -1 : indent + 2);
if( d != null && d.length() > 0 ) {
message += "(" + d;
if (indent >= 0) {
message += "\n";
for (int i = 0; i < indent; i++) {
message += " ";
}
}
message += ")";
}
} else {
double secs = (double)evaluationTimes[index] / 1.0E9;
message += evaluationCounts[index] + " evaluations in " +
nf.format(secs) + " secs (" +
nf.format(secs / evaluationCounts[index]) + " secs/eval)";
}
index++;
}
return message;
} else {
return "No evaluation timer report available";
}
}
// Identifiable IMPLEMENTATION
private String id = null;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
private boolean used = false;
private final int threadCount;
private final ExecutorService pool;
private final ArrayList<Likelihood> likelihoods = new ArrayList<Likelihood>();
private final CompoundModel compoundModel = new CompoundModel("compoundModel");
private final ArrayList<Likelihood> earlyLikelihoods = new ArrayList<Likelihood>();
private final ArrayList<Likelihood> lateLikelihoods = new ArrayList<Likelihood>();
private final List<Callable<Double>> likelihoodCallers = new ArrayList<Callable<Double>>();
class LikelihoodCaller implements Callable<Double> {
public LikelihoodCaller(Likelihood likelihood, int index) {
this.likelihood = likelihood;
this.index = index;
}
public Double call() throws Exception {
if (EVALUATION_TIMERS) {
long time = System.nanoTime();
double logL = likelihood.getLogLikelihood();
evaluationTimes[index] += System.nanoTime() - time;
evaluationCounts[index] ++;
return logL;
}
return likelihood.getLogLikelihood();
}
private final Likelihood likelihood;
private final int index;
}
}
|
package edu.dynamic.dynamiz.parser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* OptionType enum class is a class to hold the various options applicable to many commands.
* Using OptionType allows the users to specify the PRIORITY, START_TIME, END_TIME, or
* ORDER_BY options for each items.
*
* This enum class mainly facilitates the functionalities of Command classes as well as help in
* Parsing of the command.
*
* @author nhan
*
*/
public enum OptionType {
PRIORITY("-p", "--priority", "priority") {
}, START_TIME("-s", "--starttime", "from", "on") {
}, END_TIME("-d", "--deadline", "--endtime", "to", "by") {
}, ORDER_BY("-o", "--orderby", "sort by");
private static final Map<String, OptionType> ALIAS_TABLE = new HashMap<String, OptionType>();
private static String ALL_ALIASES = "";
public static int PRIORITY_URGENT = 8;
public static int PRIORITY_HIGH = 4;
public static int PRIORITY_MEDIUM = 2;
public static int PRIORITY_LOW = 1;
public static int PRIORITY_NONE = 0;
public static int PRIORITY_UNCHANGED = -1;
private static final char OPTION_SIGNAL_CHARACTER = '-';
static {
StringBuffer allAliases = new StringBuffer();
String toBeAppended = "";
for (OptionType opt: OptionType.values()) {
// Normalising by lowercase all
for (String alias: opt.aliases) {
ALIAS_TABLE.put(alias.toLowerCase(), opt);
if (alias.charAt(0) == OPTION_SIGNAL_CHARACTER) {
String wordRegex = "[\\w" + OPTION_SIGNAL_CHARACTER + "]";
toBeAppended = String.format("(?<!%1$s)(?=%1$s)%2$s\\b|", wordRegex, alias);
} else {
toBeAppended = "\\b" + alias + "\\b" + "|";
}
allAliases.append(toBeAppended);
}
}
// Remove the last | character
ALL_ALIASES = allAliases.substring(0, allAliases.length() - 1);
}
/**
* Retrieve the OptionType instance given the string of one of the option
* alias
*
* @param value the String identification of the option
* @return OptionType instance corresponding to the string value
*/
public static OptionType fromString(String value) {
if (value == null) {
throw new NullPointerException("Null alias");
}
// Normalising input
OptionType opt = ALIAS_TABLE.get(value.toLowerCase());
if (opt == null) {
throw new IllegalArgumentException("Not an alias: " + value);
}
return opt;
}
/**
* Retrieve the OptionType instance given a parsed Option.
*
* @param opt the Option to get the OptionType from
* @return the OptionType instance indicating the Option given
*/
public static OptionType fromOption(Option opt) {
if (opt == null) {
throw new NullPointerException("Null option");
}
return fromString(opt.getOptName());
}
/**
* Retrieve a List<String> of all the aliases of all the OptionType
*
* @return a List of String of all the string representation of the OptionType
*/
public static List<String> getAllAliases() {
List<String> allAliases = new ArrayList<String>();
for (OptionType opts: OptionType.values()) {
allAliases.addAll(opts.aliases);
}
return allAliases;
}
public static String getAllAliasesRegex() {
return ALL_ALIASES;
}
private List<String> aliases;
private OptionType(String... aliases) {
this.aliases = new ArrayList<String>(Arrays.asList(aliases));
this.aliases.add(this.toString().toLowerCase());
}
}
|
package org.eclipse.birt.report.designer.internal.ui.dialogs.resource;
import java.io.File;
import org.eclipse.birt.report.designer.internal.ui.resourcelocator.ResourceEntry;
import org.eclipse.birt.report.designer.internal.ui.resourcelocator.ResourceLocator;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
/**
* A dialog to select resource folder files or folder.
*/
public class ResourceFileFolderSelectionDialog extends
ElementTreeSelectionDialog
{
private File rootFile;
private static class FileViewerSorter extends ViewerSorter
{
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ViewerSorter#category(java.lang.Object)
*/
public int category( Object element )
{
if ( element instanceof File && !( (File) element ).isDirectory( ) )
{
return 1;
}
return 0;
}
}
public ResourceFileFolderSelectionDialog( )
{
this( true, false, null );
}
public ResourceFileFolderSelectionDialog( boolean showFiles )
{
this( showFiles, false, null );
}
public ResourceFileFolderSelectionDialog( String[] fileNamePattern )
{
this( true, false, fileNamePattern );
}
public ResourceFileFolderSelectionDialog( boolean includeFragments,
String[] fileNamePattern )
{
this( true, includeFragments, fileNamePattern );
}
public ResourceFileFolderSelectionDialog( boolean showFiles,
boolean includeFragments, String[] fileNamePattern )
{
this( UIUtil.getDefaultShell( ),
new ResourceFileLabelProvider( ),
new ResourceFileContentProvider( showFiles ) );
if ( includeFragments )
setInput( ResourceLocator.getRootEntries( fileNamePattern ) );
else
setInput( ResourceLocator.getResourceFolder( fileNamePattern ) );
}
private ResourceFileFolderSelectionDialog( Shell parent,
ILabelProvider labelProvider, ITreeContentProvider contentProvider )
{
super( parent, labelProvider, contentProvider );
setSorter( new FileViewerSorter( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.dialogs.ElementTreeSelectionDialog#setInput(java.lang.Object)
*/
public void setInput( Object input )
{
rootFile = new File( input.toString( ) );
super.setInput( input );
}
/**
* Get the relative path to BIRT resource folder.
*
* @return
*/
public String getPath( )
{
Object[] selected = getResult( );
if ( selected.length > 0 && rootFile != null )
{
ResourceEntry entry = (ResourceEntry) selected[0];
if(entry == null || entry.getURL( ) == null)
{
return null;
}
return ResourceLocator.relativize( entry.getURL( ) );
}
return null;
}
/**
* Get the relative path to BIRT resource folder.
*
* @return
*/
public String getPath( int index )
{
Object[] selected = getResult( );
if ( index < 0 || index >= selected.length || rootFile == null )
{
return null;
}
ResourceEntry entry = (ResourceEntry) selected[index];
return ResourceLocator.relativize( entry.getURL( ) );
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea( Composite parent )
{
UIUtil.bindHelp( parent, IHelpContextIds.RESOURCE_SELECT_DIALOG_ID );
Control control = super.createDialogArea( parent );
addToolTip( );
return control;
}
/**
* Add Tooltip for root TreeItem.
*/
protected void addToolTip( )
{
final Tree tree = getTreeViewer( ).getTree( );
tree.addMouseTrackListener( new MouseTrackAdapter( ) {
public void mouseHover( MouseEvent event )
{
Widget widget = event.widget;
if ( widget == tree )
{
Point pt = new Point( event.x, event.y );
TreeItem item = tree.getItem( pt );
if ( item == null )
{
tree.setToolTipText( null );
}
else
{
if ( getTreeViewer( ).getLabelProvider( ) instanceof ResourceFileLabelProvider )
{
tree.setToolTipText( ( (ResourceFileLabelProvider) getTreeViewer( ).getLabelProvider( ) ).getToolTip( item.getData( ) ) );
}
else
{
tree.setToolTipText( null );
}
}
}
}
} );
}
}
|
import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.ToolCall;
class format {
public static void main(String... args) throws Exception {
var bach = Bach.ofDefaults();
if (bach.configuration().finder().find("format@1.15.0").isEmpty()) {
bach.run(
}
var format = ToolCall.of("format@1.15.0").with("--replace").withFindFiles("**/*.java");
bach.run("banner", "Format %d .java files".formatted(format.arguments().size() - 1));
bach.run(format);
}
}
|
package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIAdditionalPropertiesDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIBusinessInformationDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIEndpointSecurityDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMaxTpsDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationInfoDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIScopeDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIServiceInfoDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIThreatProtectionPoliciesDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AdvertiseInfoDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MediationPolicyDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WSDLInfoDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WebsubSubscriptionConfigurationDTO;
import javax.validation.constraints.*;
import io.swagger.annotations.*;
import java.util.Objects;
import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope;
import com.fasterxml.jackson.annotation.JsonCreator;
import javax.validation.Valid;
@Scope(name = "apim:api_create", description="", value ="")
@Scope(name = "apim:api_import_export", description="", value ="")
public class APIDTO {
private String id = null;
private String name = null;
private String description = null;
private String context = null;
private String version = null;
private String provider = null;
@Scope(name = "apim:api_publish", description="", value ="")
private String lifeCycleStatus = null;
private WSDLInfoDTO wsdlInfo = null;
private String wsdlUrl = null;
private String testKey = null;
private Boolean responseCachingEnabled = null;
private Integer cacheTimeout = null;
private String destinationStatsEnabled = null;
private Boolean hasThumbnail = null;
private Boolean isDefaultVersion = null;
private Boolean isRevision = null;
private String revisionedApiId = null;
private Integer revisionId = null;
private Boolean enableSchemaValidation = null;
@Scope(name = "apim:api_publish", description="", value ="")
private Boolean enableStore = null;
@XmlType(name="TypeEnum")
@XmlEnum(String.class)
public enum TypeEnum {
HTTP("HTTP"),
WS("WS"),
SOAPTOREST("SOAPTOREST"),
SOAP("SOAP"),
GRAPHQL("GRAPHQL"),
WEBSUB("WEBSUB"),
SSE("SSE");
private String value;
TypeEnum (String v) {
value = v;
}
public String value() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static TypeEnum fromValue(String v) {
for (TypeEnum b : TypeEnum.values()) {
if (String.valueOf(b.value).equals(v)) {
return b;
}
}
return null;
}
}
private TypeEnum type = TypeEnum.HTTP;
private List<String> transport = new ArrayList<String>();
@Scope(name = "apim:api_publish", description="", value ="")
private List<String> tags = new ArrayList<String>();
@Scope(name = "apim:api_publish", description="", value ="")
private List<String> policies = new ArrayList<String>();
@Scope(name = "apim:api_publish", description="", value ="")
private String apiThrottlingPolicy = null;
private String authorizationHeader = null;
private List<String> securityScheme = new ArrayList<String>();
private APIMaxTpsDTO maxTps = null;
@XmlType(name="VisibilityEnum")
@XmlEnum(String.class)
public enum VisibilityEnum {
PUBLIC("PUBLIC"),
PRIVATE("PRIVATE"),
RESTRICTED("RESTRICTED");
private String value;
VisibilityEnum (String v) {
value = v;
}
public String value() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static VisibilityEnum fromValue(String v) {
for (VisibilityEnum b : VisibilityEnum.values()) {
if (String.valueOf(b.value).equals(v)) {
return b;
}
}
return null;
}
}
@Scope(name = "{apim:api_publish=null}", description="", value ="")
private VisibilityEnum visibility = VisibilityEnum.PUBLIC;
@Scope(name = "apim:api_publish", description="", value ="")
private List<String> visibleRoles = new ArrayList<String>();
private List<String> visibleTenants = new ArrayList<String>();
private APIEndpointSecurityDTO endpointSecurity = null;
@Scope(name = "apim:api_publish", description="", value ="")
private List<String> gatewayEnvironments = new ArrayList<String>();
private List<MediationPolicyDTO> mediationPolicies = new ArrayList<MediationPolicyDTO>();
@XmlType(name="SubscriptionAvailabilityEnum")
@XmlEnum(String.class)
public enum SubscriptionAvailabilityEnum {
CURRENT_TENANT("CURRENT_TENANT"),
ALL_TENANTS("ALL_TENANTS"),
SPECIFIC_TENANTS("SPECIFIC_TENANTS");
private String value;
SubscriptionAvailabilityEnum (String v) {
value = v;
}
public String value() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static SubscriptionAvailabilityEnum fromValue(String v) {
for (SubscriptionAvailabilityEnum b : SubscriptionAvailabilityEnum.values()) {
if (String.valueOf(b.value).equals(v)) {
return b;
}
}
return null;
}
}
@Scope(name = "apim:api_publish", description="", value ="")
private SubscriptionAvailabilityEnum subscriptionAvailability = SubscriptionAvailabilityEnum.CURRENT_TENANT;
private List<String> subscriptionAvailableTenants = new ArrayList<String>();
@Scope(name = "apim:api_publish", description="", value ="")
private List<APIAdditionalPropertiesDTO> additionalProperties = new ArrayList<APIAdditionalPropertiesDTO>();
private APIMonetizationInfoDTO monetization = null;
@XmlType(name="AccessControlEnum")
@XmlEnum(String.class)
public enum AccessControlEnum {
NONE("NONE"),
RESTRICTED("RESTRICTED");
private String value;
AccessControlEnum (String v) {
value = v;
}
public String value() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static AccessControlEnum fromValue(String v) {
for (AccessControlEnum b : AccessControlEnum.values()) {
if (String.valueOf(b.value).equals(v)) {
return b;
}
}
return null;
}
}
private AccessControlEnum accessControl = AccessControlEnum.NONE;
private List<String> accessControlRoles = new ArrayList<String>();
@Scope(name = "apim:api_publish", description="", value ="")
private APIBusinessInformationDTO businessInformation = null;
private APICorsConfigurationDTO corsConfiguration = null;
private WebsubSubscriptionConfigurationDTO websubSubscriptionConfiguration = null;
private String workflowStatus = null;
private String createdTime = null;
@Scope(name = "apim:api_publish", description="", value ="")
private String lastUpdatedTime = null;
private Object endpointConfig = null;
@XmlType(name="EndpointImplementationTypeEnum")
@XmlEnum(String.class)
public enum EndpointImplementationTypeEnum {
INLINE("INLINE"),
ENDPOINT("ENDPOINT");
private String value;
EndpointImplementationTypeEnum (String v) {
value = v;
}
public String value() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static EndpointImplementationTypeEnum fromValue(String v) {
for (EndpointImplementationTypeEnum b : EndpointImplementationTypeEnum.values()) {
if (String.valueOf(b.value).equals(v)) {
return b;
}
}
return null;
}
}
private EndpointImplementationTypeEnum endpointImplementationType = EndpointImplementationTypeEnum.ENDPOINT;
private List<APIScopeDTO> scopes = new ArrayList<APIScopeDTO>();
private List<APIOperationsDTO> operations = new ArrayList<APIOperationsDTO>();
private APIThreatProtectionPoliciesDTO threatProtectionPolicies = null;
@Scope(name = "apim:api_publish", description="", value ="")
private List<String> categories = new ArrayList<String>();
private Object keyManagers = null;
private APIServiceInfoDTO serviceInfo = null;
private AdvertiseInfoDTO advertiseInfo = null;
/**
* UUID of the api registry artifact
**/
public APIDTO id(String id) {
this.id = id;
return this;
}
@ApiModelProperty(example = "01234567-0123-0123-0123-012345678901", value = "UUID of the api registry artifact ")
@JsonProperty("id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public APIDTO name(String name) {
this.name = name;
return this;
}
@ApiModelProperty(example = "PizzaShackAPI", required = true, value = "")
@JsonProperty("name")
@NotNull
@Pattern(regexp="(^[^~!@#;:%^*()+={}|\\\\<>\"',&$\\s+\\[\\]/]*$)") @Size(min=1,max=50) public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public APIDTO description(String description) {
this.description = description;
return this;
}
@ApiModelProperty(example = "This is a simple API for Pizza Shack online pizza delivery store.", value = "")
@JsonProperty("description")
@Size(max=32766) public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public APIDTO context(String context) {
this.context = context;
return this;
}
@ApiModelProperty(example = "pizza", required = true, value = "")
@JsonProperty("context")
@NotNull
@Size(min=1,max=82) public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public APIDTO version(String version) {
this.version = version;
return this;
}
@ApiModelProperty(example = "1.0.0", required = true, value = "")
@JsonProperty("version")
@NotNull
@Pattern(regexp="^[^~!@#;:%^*()+={}|\\\\<>\"',&/$\\[\\]\\s+/]+$") @Size(min=1,max=30) public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
/**
* If the provider value is not given user invoking the api will be used as the provider.
**/
public APIDTO provider(String provider) {
this.provider = provider;
return this;
}
@ApiModelProperty(example = "admin", value = "If the provider value is not given user invoking the api will be used as the provider. ")
@JsonProperty("provider")
@Size(max=50) public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public APIDTO lifeCycleStatus(String lifeCycleStatus) {
this.lifeCycleStatus = lifeCycleStatus;
return this;
}
@ApiModelProperty(example = "CREATED", value = "")
@JsonProperty("lifeCycleStatus")
public String getLifeCycleStatus() {
return lifeCycleStatus;
}
public void setLifeCycleStatus(String lifeCycleStatus) {
this.lifeCycleStatus = lifeCycleStatus;
}
public APIDTO wsdlInfo(WSDLInfoDTO wsdlInfo) {
this.wsdlInfo = wsdlInfo;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("wsdlInfo")
public WSDLInfoDTO getWsdlInfo() {
return wsdlInfo;
}
public void setWsdlInfo(WSDLInfoDTO wsdlInfo) {
this.wsdlInfo = wsdlInfo;
}
public APIDTO wsdlUrl(String wsdlUrl) {
this.wsdlUrl = wsdlUrl;
return this;
}
@ApiModelProperty(example = "/apimgt/applicationdata/wsdls/admin--soap1.wsdl", value = "")
@JsonProperty("wsdlUrl")
public String getWsdlUrl() {
return wsdlUrl;
}
public void setWsdlUrl(String wsdlUrl) {
this.wsdlUrl = wsdlUrl;
}
public APIDTO testKey(String testKey) {
this.testKey = testKey;
return this;
}
@ApiModelProperty(example = "8swdwj9080edejhj", value = "")
@JsonProperty("testKey")
public String getTestKey() {
return testKey;
}
public void setTestKey(String testKey) {
this.testKey = testKey;
}
public APIDTO responseCachingEnabled(Boolean responseCachingEnabled) {
this.responseCachingEnabled = responseCachingEnabled;
return this;
}
@ApiModelProperty(example = "true", value = "")
@JsonProperty("responseCachingEnabled")
public Boolean isResponseCachingEnabled() {
return responseCachingEnabled;
}
public void setResponseCachingEnabled(Boolean responseCachingEnabled) {
this.responseCachingEnabled = responseCachingEnabled;
}
public APIDTO cacheTimeout(Integer cacheTimeout) {
this.cacheTimeout = cacheTimeout;
return this;
}
@ApiModelProperty(example = "300", value = "")
@JsonProperty("cacheTimeout")
public Integer getCacheTimeout() {
return cacheTimeout;
}
public void setCacheTimeout(Integer cacheTimeout) {
this.cacheTimeout = cacheTimeout;
}
public APIDTO destinationStatsEnabled(String destinationStatsEnabled) {
this.destinationStatsEnabled = destinationStatsEnabled;
return this;
}
@ApiModelProperty(example = "Disabled", value = "")
@JsonProperty("destinationStatsEnabled")
public String getDestinationStatsEnabled() {
return destinationStatsEnabled;
}
public void setDestinationStatsEnabled(String destinationStatsEnabled) {
this.destinationStatsEnabled = destinationStatsEnabled;
}
public APIDTO hasThumbnail(Boolean hasThumbnail) {
this.hasThumbnail = hasThumbnail;
return this;
}
@ApiModelProperty(example = "false", value = "")
@JsonProperty("hasThumbnail")
public Boolean isHasThumbnail() {
return hasThumbnail;
}
public void setHasThumbnail(Boolean hasThumbnail) {
this.hasThumbnail = hasThumbnail;
}
public APIDTO isDefaultVersion(Boolean isDefaultVersion) {
this.isDefaultVersion = isDefaultVersion;
return this;
}
@ApiModelProperty(example = "false", value = "")
@JsonProperty("isDefaultVersion")
public Boolean isIsDefaultVersion() {
return isDefaultVersion;
}
public void setIsDefaultVersion(Boolean isDefaultVersion) {
this.isDefaultVersion = isDefaultVersion;
}
public APIDTO isRevision(Boolean isRevision) {
this.isRevision = isRevision;
return this;
}
@ApiModelProperty(example = "false", value = "")
@JsonProperty("isRevision")
public Boolean isIsRevision() {
return isRevision;
}
public void setIsRevision(Boolean isRevision) {
this.isRevision = isRevision;
}
/**
* UUID of the api registry artifact
**/
public APIDTO revisionedApiId(String revisionedApiId) {
this.revisionedApiId = revisionedApiId;
return this;
}
@ApiModelProperty(example = "01234567-0123-0123-0123-012345678901", value = "UUID of the api registry artifact ")
@JsonProperty("revisionedApiId")
public String getRevisionedApiId() {
return revisionedApiId;
}
public void setRevisionedApiId(String revisionedApiId) {
this.revisionedApiId = revisionedApiId;
}
public APIDTO revisionId(Integer revisionId) {
this.revisionId = revisionId;
return this;
}
@ApiModelProperty(example = "1", value = "")
@JsonProperty("revisionId")
public Integer getRevisionId() {
return revisionId;
}
public void setRevisionId(Integer revisionId) {
this.revisionId = revisionId;
}
public APIDTO enableSchemaValidation(Boolean enableSchemaValidation) {
this.enableSchemaValidation = enableSchemaValidation;
return this;
}
@ApiModelProperty(example = "false", value = "")
@JsonProperty("enableSchemaValidation")
public Boolean isEnableSchemaValidation() {
return enableSchemaValidation;
}
public void setEnableSchemaValidation(Boolean enableSchemaValidation) {
this.enableSchemaValidation = enableSchemaValidation;
}
public APIDTO enableStore(Boolean enableStore) {
this.enableStore = enableStore;
return this;
}
@ApiModelProperty(example = "true", value = "")
@JsonProperty("enableStore")
public Boolean isEnableStore() {
return enableStore;
}
public void setEnableStore(Boolean enableStore) {
this.enableStore = enableStore;
}
/**
* The api creation type to be used. Accepted values are HTTP, WS, SOAPTOREST, GRAPHQL, WEBSUB, SSE
**/
public APIDTO type(TypeEnum type) {
this.type = type;
return this;
}
@ApiModelProperty(example = "HTTP", value = "The api creation type to be used. Accepted values are HTTP, WS, SOAPTOREST, GRAPHQL, WEBSUB, SSE")
@JsonProperty("type")
public TypeEnum getType() {
return type;
}
public void setType(TypeEnum type) {
this.type = type;
}
/**
* Supported transports for the API (http and/or https).
**/
public APIDTO transport(List<String> transport) {
this.transport = transport;
return this;
}
@ApiModelProperty(example = "[\"http\",\"https\"]", value = "Supported transports for the API (http and/or https). ")
@JsonProperty("transport")
public List<String> getTransport() {
return transport;
}
public void setTransport(List<String> transport) {
this.transport = transport;
}
public APIDTO tags(List<String> tags) {
this.tags = tags;
return this;
}
@ApiModelProperty(example = "[\"pizza\",\"food\"]", value = "")
@JsonProperty("tags")
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public APIDTO policies(List<String> policies) {
this.policies = policies;
return this;
}
@ApiModelProperty(example = "[\"Unlimited\"]", value = "")
@JsonProperty("policies")
public List<String> getPolicies() {
return policies;
}
public void setPolicies(List<String> policies) {
this.policies = policies;
}
/**
* The API level throttling policy selected for the particular API
**/
public APIDTO apiThrottlingPolicy(String apiThrottlingPolicy) {
this.apiThrottlingPolicy = apiThrottlingPolicy;
return this;
}
@ApiModelProperty(example = "Unlimited", value = "The API level throttling policy selected for the particular API")
@JsonProperty("apiThrottlingPolicy")
public String getApiThrottlingPolicy() {
return apiThrottlingPolicy;
}
public void setApiThrottlingPolicy(String apiThrottlingPolicy) {
this.apiThrottlingPolicy = apiThrottlingPolicy;
}
/**
* Name of the Authorization header used for invoking the API. If it is not set, Authorization header name specified in tenant or system level will be used.
**/
public APIDTO authorizationHeader(String authorizationHeader) {
this.authorizationHeader = authorizationHeader;
return this;
}
@ApiModelProperty(example = "Authorization", value = "Name of the Authorization header used for invoking the API. If it is not set, Authorization header name specified in tenant or system level will be used. ")
@JsonProperty("authorizationHeader")
@Pattern(regexp="(^[^~!@#;:%^*()+={}|\\\\<>\"',&$\\s+]*$)") public String getAuthorizationHeader() {
return authorizationHeader;
}
public void setAuthorizationHeader(String authorizationHeader) {
this.authorizationHeader = authorizationHeader;
}
/**
* Types of API security, the current API secured with. It can be either OAuth2 or mutual SSL or both. If it is not set OAuth2 will be set as the security for the current API.
**/
public APIDTO securityScheme(List<String> securityScheme) {
this.securityScheme = securityScheme;
return this;
}
@ApiModelProperty(example = "[\"oauth2\"]", value = "Types of API security, the current API secured with. It can be either OAuth2 or mutual SSL or both. If it is not set OAuth2 will be set as the security for the current API. ")
@JsonProperty("securityScheme")
public List<String> getSecurityScheme() {
return securityScheme;
}
public void setSecurityScheme(List<String> securityScheme) {
this.securityScheme = securityScheme;
}
public APIDTO maxTps(APIMaxTpsDTO maxTps) {
this.maxTps = maxTps;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("maxTps")
public APIMaxTpsDTO getMaxTps() {
return maxTps;
}
public void setMaxTps(APIMaxTpsDTO maxTps) {
this.maxTps = maxTps;
}
/**
* The visibility level of the API. Accepts one of the following. PUBLIC, PRIVATE, RESTRICTED.
**/
public APIDTO visibility(VisibilityEnum visibility) {
this.visibility = visibility;
return this;
}
@ApiModelProperty(example = "PUBLIC", value = "The visibility level of the API. Accepts one of the following. PUBLIC, PRIVATE, RESTRICTED.")
@JsonProperty("visibility")
public VisibilityEnum getVisibility() {
return visibility;
}
public void setVisibility(VisibilityEnum visibility) {
this.visibility = visibility;
}
/**
* The user roles that are able to access the API in Developer Portal
**/
public APIDTO visibleRoles(List<String> visibleRoles) {
this.visibleRoles = visibleRoles;
return this;
}
@ApiModelProperty(example = "[]", value = "The user roles that are able to access the API in Developer Portal")
@JsonProperty("visibleRoles")
public List<String> getVisibleRoles() {
return visibleRoles;
}
public void setVisibleRoles(List<String> visibleRoles) {
this.visibleRoles = visibleRoles;
}
public APIDTO visibleTenants(List<String> visibleTenants) {
this.visibleTenants = visibleTenants;
return this;
}
@ApiModelProperty(example = "[]", value = "")
@JsonProperty("visibleTenants")
public List<String> getVisibleTenants() {
return visibleTenants;
}
public void setVisibleTenants(List<String> visibleTenants) {
this.visibleTenants = visibleTenants;
}
public APIDTO endpointSecurity(APIEndpointSecurityDTO endpointSecurity) {
this.endpointSecurity = endpointSecurity;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("endpointSecurity")
public APIEndpointSecurityDTO getEndpointSecurity() {
return endpointSecurity;
}
public void setEndpointSecurity(APIEndpointSecurityDTO endpointSecurity) {
this.endpointSecurity = endpointSecurity;
}
/**
* List of gateway environments the API is available
**/
public APIDTO gatewayEnvironments(List<String> gatewayEnvironments) {
this.gatewayEnvironments = gatewayEnvironments;
return this;
}
@ApiModelProperty(example = "[\"Default\"]", value = "List of gateway environments the API is available ")
@JsonProperty("gatewayEnvironments")
public List<String> getGatewayEnvironments() {
return gatewayEnvironments;
}
public void setGatewayEnvironments(List<String> gatewayEnvironments) {
this.gatewayEnvironments = gatewayEnvironments;
}
public APIDTO mediationPolicies(List<MediationPolicyDTO> mediationPolicies) {
this.mediationPolicies = mediationPolicies;
return this;
}
@ApiModelProperty(example = "[{\"name\":\"json_to_xml_in_message\",\"type\":\"in\"},{\"name\":\"xml_to_json_out_message\",\"type\":\"out\"},{\"name\":\"json_fault\",\"type\":\"fault\"}]", value = "")
@Valid
@JsonProperty("mediationPolicies")
public List<MediationPolicyDTO> getMediationPolicies() {
return mediationPolicies;
}
public void setMediationPolicies(List<MediationPolicyDTO> mediationPolicies) {
this.mediationPolicies = mediationPolicies;
}
/**
* The subscription availability. Accepts one of the following. CURRENT_TENANT, ALL_TENANTS or SPECIFIC_TENANTS.
**/
public APIDTO subscriptionAvailability(SubscriptionAvailabilityEnum subscriptionAvailability) {
this.subscriptionAvailability = subscriptionAvailability;
return this;
}
@ApiModelProperty(example = "CURRENT_TENANT", value = "The subscription availability. Accepts one of the following. CURRENT_TENANT, ALL_TENANTS or SPECIFIC_TENANTS.")
@JsonProperty("subscriptionAvailability")
public SubscriptionAvailabilityEnum getSubscriptionAvailability() {
return subscriptionAvailability;
}
public void setSubscriptionAvailability(SubscriptionAvailabilityEnum subscriptionAvailability) {
this.subscriptionAvailability = subscriptionAvailability;
}
public APIDTO subscriptionAvailableTenants(List<String> subscriptionAvailableTenants) {
this.subscriptionAvailableTenants = subscriptionAvailableTenants;
return this;
}
@ApiModelProperty(example = "[]", value = "")
@JsonProperty("subscriptionAvailableTenants")
public List<String> getSubscriptionAvailableTenants() {
return subscriptionAvailableTenants;
}
public void setSubscriptionAvailableTenants(List<String> subscriptionAvailableTenants) {
this.subscriptionAvailableTenants = subscriptionAvailableTenants;
}
/**
* Map of custom properties of API
**/
public APIDTO additionalProperties(List<APIAdditionalPropertiesDTO> additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
@ApiModelProperty(value = "Map of custom properties of API")
@Valid
@JsonProperty("additionalProperties")
public List<APIAdditionalPropertiesDTO> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(List<APIAdditionalPropertiesDTO> additionalProperties) {
this.additionalProperties = additionalProperties;
}
public APIDTO monetization(APIMonetizationInfoDTO monetization) {
this.monetization = monetization;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("monetization")
public APIMonetizationInfoDTO getMonetization() {
return monetization;
}
public void setMonetization(APIMonetizationInfoDTO monetization) {
this.monetization = monetization;
}
public APIDTO accessControl(AccessControlEnum accessControl) {
this.accessControl = accessControl;
return this;
}
@ApiModelProperty(value = "Is the API is restricted to certain set of publishers or creators or is it visible to all the publishers and creators. If the accessControl restriction is none, this API can be modified by all the publishers and creators, if not it can only be viewable/modifiable by certain set of publishers and creators, based on the restriction. ")
@JsonProperty("accessControl")
public AccessControlEnum getAccessControl() {
return accessControl;
}
public void setAccessControl(AccessControlEnum accessControl) {
this.accessControl = accessControl;
}
/**
* The user roles that are able to view/modify as API publisher or creator.
**/
public APIDTO accessControlRoles(List<String> accessControlRoles) {
this.accessControlRoles = accessControlRoles;
return this;
}
@ApiModelProperty(example = "[]", value = "The user roles that are able to view/modify as API publisher or creator.")
@JsonProperty("accessControlRoles")
public List<String> getAccessControlRoles() {
return accessControlRoles;
}
public void setAccessControlRoles(List<String> accessControlRoles) {
this.accessControlRoles = accessControlRoles;
}
public APIDTO businessInformation(APIBusinessInformationDTO businessInformation) {
this.businessInformation = businessInformation;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("businessInformation")
public APIBusinessInformationDTO getBusinessInformation() {
return businessInformation;
}
public void setBusinessInformation(APIBusinessInformationDTO businessInformation) {
this.businessInformation = businessInformation;
}
public APIDTO corsConfiguration(APICorsConfigurationDTO corsConfiguration) {
this.corsConfiguration = corsConfiguration;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("corsConfiguration")
public APICorsConfigurationDTO getCorsConfiguration() {
return corsConfiguration;
}
public void setCorsConfiguration(APICorsConfigurationDTO corsConfiguration) {
this.corsConfiguration = corsConfiguration;
}
public APIDTO websubSubscriptionConfiguration(WebsubSubscriptionConfigurationDTO websubSubscriptionConfiguration) {
this.websubSubscriptionConfiguration = websubSubscriptionConfiguration;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("websubSubscriptionConfiguration")
public WebsubSubscriptionConfigurationDTO getWebsubSubscriptionConfiguration() {
return websubSubscriptionConfiguration;
}
public void setWebsubSubscriptionConfiguration(WebsubSubscriptionConfigurationDTO websubSubscriptionConfiguration) {
this.websubSubscriptionConfiguration = websubSubscriptionConfiguration;
}
public APIDTO workflowStatus(String workflowStatus) {
this.workflowStatus = workflowStatus;
return this;
}
@ApiModelProperty(example = "APPROVED", value = "")
@JsonProperty("workflowStatus")
public String getWorkflowStatus() {
return workflowStatus;
}
public void setWorkflowStatus(String workflowStatus) {
this.workflowStatus = workflowStatus;
}
public APIDTO createdTime(String createdTime) {
this.createdTime = createdTime;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("createdTime")
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public APIDTO lastUpdatedTime(String lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("lastUpdatedTime")
public String getLastUpdatedTime() {
return lastUpdatedTime;
}
public void setLastUpdatedTime(String lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
public APIDTO endpointConfig(Object endpointConfig) {
this.endpointConfig = endpointConfig;
return this;
}
@ApiModelProperty(example = "{\"endpoint_type\":\"http\",\"sandbox_endpoints\":{\"url\":\"https:
@Valid
@JsonProperty("endpointConfig")
public Object getEndpointConfig() {
return endpointConfig;
}
public void setEndpointConfig(Object endpointConfig) {
this.endpointConfig = endpointConfig;
}
public APIDTO endpointImplementationType(EndpointImplementationTypeEnum endpointImplementationType) {
this.endpointImplementationType = endpointImplementationType;
return this;
}
@ApiModelProperty(example = "INLINE", value = "")
@JsonProperty("endpointImplementationType")
public EndpointImplementationTypeEnum getEndpointImplementationType() {
return endpointImplementationType;
}
public void setEndpointImplementationType(EndpointImplementationTypeEnum endpointImplementationType) {
this.endpointImplementationType = endpointImplementationType;
}
public APIDTO scopes(List<APIScopeDTO> scopes) {
this.scopes = scopes;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("scopes")
public List<APIScopeDTO> getScopes() {
return scopes;
}
public void setScopes(List<APIScopeDTO> scopes) {
this.scopes = scopes;
}
public APIDTO operations(List<APIOperationsDTO> operations) {
this.operations = operations;
return this;
}
@ApiModelProperty(example = "[{\"target\":\"/order/{orderId}\",\"verb\":\"POST\",\"authType\":\"Application & Application User\",\"throttlingPolicy\":\"Unlimited\"},{\"target\":\"/menu\",\"verb\":\"GET\",\"authType\":\"Application & Application User\",\"throttlingPolicy\":\"Unlimited\"}]", value = "")
@Valid
@JsonProperty("operations")
public List<APIOperationsDTO> getOperations() {
return operations;
}
public void setOperations(List<APIOperationsDTO> operations) {
this.operations = operations;
}
public APIDTO threatProtectionPolicies(APIThreatProtectionPoliciesDTO threatProtectionPolicies) {
this.threatProtectionPolicies = threatProtectionPolicies;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("threatProtectionPolicies")
public APIThreatProtectionPoliciesDTO getThreatProtectionPolicies() {
return threatProtectionPolicies;
}
public void setThreatProtectionPolicies(APIThreatProtectionPoliciesDTO threatProtectionPolicies) {
this.threatProtectionPolicies = threatProtectionPolicies;
}
/**
* API categories
**/
public APIDTO categories(List<String> categories) {
this.categories = categories;
return this;
}
@ApiModelProperty(value = "API categories ")
@JsonProperty("categories")
public List<String> getCategories() {
return categories;
}
public void setCategories(List<String> categories) {
this.categories = categories;
}
/**
* API Key Managers
**/
public APIDTO keyManagers(Object keyManagers) {
this.keyManagers = keyManagers;
return this;
}
@ApiModelProperty(value = "API Key Managers ")
@Valid
@JsonProperty("keyManagers")
public Object getKeyManagers() {
return keyManagers;
}
public void setKeyManagers(Object keyManagers) {
this.keyManagers = keyManagers;
}
public APIDTO serviceInfo(APIServiceInfoDTO serviceInfo) {
this.serviceInfo = serviceInfo;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("serviceInfo")
public APIServiceInfoDTO getServiceInfo() {
return serviceInfo;
}
public void setServiceInfo(APIServiceInfoDTO serviceInfo) {
this.serviceInfo = serviceInfo;
}
public APIDTO advertiseInfo(AdvertiseInfoDTO advertiseInfo) {
this.advertiseInfo = advertiseInfo;
return this;
}
@ApiModelProperty(value = "")
@Valid
@JsonProperty("advertiseInfo")
public AdvertiseInfoDTO getAdvertiseInfo() {
return advertiseInfo;
}
public void setAdvertiseInfo(AdvertiseInfoDTO advertiseInfo) {
this.advertiseInfo = advertiseInfo;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
APIDTO API = (APIDTO) o;
return Objects.equals(id, API.id) &&
Objects.equals(name, API.name) &&
Objects.equals(description, API.description) &&
Objects.equals(context, API.context) &&
Objects.equals(version, API.version) &&
Objects.equals(provider, API.provider) &&
Objects.equals(lifeCycleStatus, API.lifeCycleStatus) &&
Objects.equals(wsdlInfo, API.wsdlInfo) &&
Objects.equals(wsdlUrl, API.wsdlUrl) &&
Objects.equals(testKey, API.testKey) &&
Objects.equals(responseCachingEnabled, API.responseCachingEnabled) &&
Objects.equals(cacheTimeout, API.cacheTimeout) &&
Objects.equals(destinationStatsEnabled, API.destinationStatsEnabled) &&
Objects.equals(hasThumbnail, API.hasThumbnail) &&
Objects.equals(isDefaultVersion, API.isDefaultVersion) &&
Objects.equals(isRevision, API.isRevision) &&
Objects.equals(revisionedApiId, API.revisionedApiId) &&
Objects.equals(revisionId, API.revisionId) &&
Objects.equals(enableSchemaValidation, API.enableSchemaValidation) &&
Objects.equals(enableStore, API.enableStore) &&
Objects.equals(type, API.type) &&
Objects.equals(transport, API.transport) &&
Objects.equals(tags, API.tags) &&
Objects.equals(policies, API.policies) &&
Objects.equals(apiThrottlingPolicy, API.apiThrottlingPolicy) &&
Objects.equals(authorizationHeader, API.authorizationHeader) &&
Objects.equals(securityScheme, API.securityScheme) &&
Objects.equals(maxTps, API.maxTps) &&
Objects.equals(visibility, API.visibility) &&
Objects.equals(visibleRoles, API.visibleRoles) &&
Objects.equals(visibleTenants, API.visibleTenants) &&
Objects.equals(endpointSecurity, API.endpointSecurity) &&
Objects.equals(gatewayEnvironments, API.gatewayEnvironments) &&
Objects.equals(mediationPolicies, API.mediationPolicies) &&
Objects.equals(subscriptionAvailability, API.subscriptionAvailability) &&
Objects.equals(subscriptionAvailableTenants, API.subscriptionAvailableTenants) &&
Objects.equals(additionalProperties, API.additionalProperties) &&
Objects.equals(monetization, API.monetization) &&
Objects.equals(accessControl, API.accessControl) &&
Objects.equals(accessControlRoles, API.accessControlRoles) &&
Objects.equals(businessInformation, API.businessInformation) &&
Objects.equals(corsConfiguration, API.corsConfiguration) &&
Objects.equals(websubSubscriptionConfiguration, API.websubSubscriptionConfiguration) &&
Objects.equals(workflowStatus, API.workflowStatus) &&
Objects.equals(createdTime, API.createdTime) &&
Objects.equals(lastUpdatedTime, API.lastUpdatedTime) &&
Objects.equals(endpointConfig, API.endpointConfig) &&
Objects.equals(endpointImplementationType, API.endpointImplementationType) &&
Objects.equals(scopes, API.scopes) &&
Objects.equals(operations, API.operations) &&
Objects.equals(threatProtectionPolicies, API.threatProtectionPolicies) &&
Objects.equals(categories, API.categories) &&
Objects.equals(keyManagers, API.keyManagers) &&
Objects.equals(serviceInfo, API.serviceInfo) &&
Objects.equals(advertiseInfo, API.advertiseInfo);
}
@Override
public int hashCode() {
return Objects.hash(id, name, description, context, version, provider, lifeCycleStatus, wsdlInfo, wsdlUrl, testKey, responseCachingEnabled, cacheTimeout, destinationStatsEnabled, hasThumbnail, isDefaultVersion, isRevision, revisionedApiId, revisionId, enableSchemaValidation, enableStore, type, transport, tags, policies, apiThrottlingPolicy, authorizationHeader, securityScheme, maxTps, visibility, visibleRoles, visibleTenants, endpointSecurity, gatewayEnvironments, mediationPolicies, subscriptionAvailability, subscriptionAvailableTenants, additionalProperties, monetization, accessControl, accessControlRoles, businessInformation, corsConfiguration, websubSubscriptionConfiguration, workflowStatus, createdTime, lastUpdatedTime, endpointConfig, endpointImplementationType, scopes, operations, threatProtectionPolicies, categories, keyManagers, serviceInfo, advertiseInfo);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class APIDTO {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" context: ").append(toIndentedString(context)).append("\n");
sb.append(" version: ").append(toIndentedString(version)).append("\n");
sb.append(" provider: ").append(toIndentedString(provider)).append("\n");
sb.append(" lifeCycleStatus: ").append(toIndentedString(lifeCycleStatus)).append("\n");
sb.append(" wsdlInfo: ").append(toIndentedString(wsdlInfo)).append("\n");
sb.append(" wsdlUrl: ").append(toIndentedString(wsdlUrl)).append("\n");
sb.append(" testKey: ").append(toIndentedString(testKey)).append("\n");
sb.append(" responseCachingEnabled: ").append(toIndentedString(responseCachingEnabled)).append("\n");
sb.append(" cacheTimeout: ").append(toIndentedString(cacheTimeout)).append("\n");
sb.append(" destinationStatsEnabled: ").append(toIndentedString(destinationStatsEnabled)).append("\n");
sb.append(" hasThumbnail: ").append(toIndentedString(hasThumbnail)).append("\n");
sb.append(" isDefaultVersion: ").append(toIndentedString(isDefaultVersion)).append("\n");
sb.append(" isRevision: ").append(toIndentedString(isRevision)).append("\n");
sb.append(" revisionedApiId: ").append(toIndentedString(revisionedApiId)).append("\n");
sb.append(" revisionId: ").append(toIndentedString(revisionId)).append("\n");
sb.append(" enableSchemaValidation: ").append(toIndentedString(enableSchemaValidation)).append("\n");
sb.append(" enableStore: ").append(toIndentedString(enableStore)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" transport: ").append(toIndentedString(transport)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" policies: ").append(toIndentedString(policies)).append("\n");
sb.append(" apiThrottlingPolicy: ").append(toIndentedString(apiThrottlingPolicy)).append("\n");
sb.append(" authorizationHeader: ").append(toIndentedString(authorizationHeader)).append("\n");
sb.append(" securityScheme: ").append(toIndentedString(securityScheme)).append("\n");
sb.append(" maxTps: ").append(toIndentedString(maxTps)).append("\n");
sb.append(" visibility: ").append(toIndentedString(visibility)).append("\n");
sb.append(" visibleRoles: ").append(toIndentedString(visibleRoles)).append("\n");
sb.append(" visibleTenants: ").append(toIndentedString(visibleTenants)).append("\n");
sb.append(" endpointSecurity: ").append(toIndentedString(endpointSecurity)).append("\n");
sb.append(" gatewayEnvironments: ").append(toIndentedString(gatewayEnvironments)).append("\n");
sb.append(" mediationPolicies: ").append(toIndentedString(mediationPolicies)).append("\n");
sb.append(" subscriptionAvailability: ").append(toIndentedString(subscriptionAvailability)).append("\n");
sb.append(" subscriptionAvailableTenants: ").append(toIndentedString(subscriptionAvailableTenants)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append(" monetization: ").append(toIndentedString(monetization)).append("\n");
sb.append(" accessControl: ").append(toIndentedString(accessControl)).append("\n");
sb.append(" accessControlRoles: ").append(toIndentedString(accessControlRoles)).append("\n");
sb.append(" businessInformation: ").append(toIndentedString(businessInformation)).append("\n");
sb.append(" corsConfiguration: ").append(toIndentedString(corsConfiguration)).append("\n");
sb.append(" websubSubscriptionConfiguration: ").append(toIndentedString(websubSubscriptionConfiguration)).append("\n");
sb.append(" workflowStatus: ").append(toIndentedString(workflowStatus)).append("\n");
sb.append(" createdTime: ").append(toIndentedString(createdTime)).append("\n");
sb.append(" lastUpdatedTime: ").append(toIndentedString(lastUpdatedTime)).append("\n");
sb.append(" endpointConfig: ").append(toIndentedString(endpointConfig)).append("\n");
sb.append(" endpointImplementationType: ").append(toIndentedString(endpointImplementationType)).append("\n");
sb.append(" scopes: ").append(toIndentedString(scopes)).append("\n");
sb.append(" operations: ").append(toIndentedString(operations)).append("\n");
sb.append(" threatProtectionPolicies: ").append(toIndentedString(threatProtectionPolicies)).append("\n");
sb.append(" categories: ").append(toIndentedString(categories)).append("\n");
sb.append(" keyManagers: ").append(toIndentedString(keyManagers)).append("\n");
sb.append(" serviceInfo: ").append(toIndentedString(serviceInfo)).append("\n");
sb.append(" advertiseInfo: ").append(toIndentedString(advertiseInfo)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
//$HeadURL$
package org.deegree.feature.persistence.sql.mapper;
import static org.apache.xerces.xs.XSComplexTypeDefinition.CONTENTTYPE_ELEMENT;
import static org.apache.xerces.xs.XSComplexTypeDefinition.CONTENTTYPE_EMPTY;
import static org.deegree.commons.tom.primitive.BaseType.BOOLEAN;
import static org.deegree.commons.tom.primitive.BaseType.STRING;
import static org.deegree.commons.xml.CommonNamespaces.XLNNS;
import static org.deegree.commons.xml.CommonNamespaces.XSINS;
import static org.deegree.feature.persistence.sql.blob.BlobCodec.Compression.NONE;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.xerces.xs.XSAttributeDeclaration;
import org.apache.xerces.xs.XSAttributeUse;
import org.apache.xerces.xs.XSComplexTypeDefinition;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSElementDeclaration;
import org.apache.xerces.xs.XSModelGroup;
import org.apache.xerces.xs.XSObjectList;
import org.apache.xerces.xs.XSParticle;
import org.apache.xerces.xs.XSSimpleTypeDefinition;
import org.apache.xerces.xs.XSTerm;
import org.apache.xerces.xs.XSTypeDefinition;
import org.apache.xerces.xs.XSWildcard;
import org.deegree.commons.jdbc.SQLIdentifier;
import org.deegree.commons.jdbc.TableName;
import org.deegree.commons.tom.gml.property.PropertyType;
import org.deegree.commons.tom.primitive.BaseType;
import org.deegree.commons.tom.primitive.PrimitiveType;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.xml.CommonNamespaces;
import org.deegree.feature.persistence.sql.BBoxTableMapping;
import org.deegree.feature.persistence.sql.FeatureTypeMapping;
import org.deegree.feature.persistence.sql.GeometryStorageParams;
import org.deegree.feature.persistence.sql.MappedAppSchema;
import org.deegree.feature.persistence.sql.blob.BlobCodec;
import org.deegree.feature.persistence.sql.blob.BlobMapping;
import org.deegree.feature.persistence.sql.expressions.TableJoin;
import org.deegree.feature.persistence.sql.id.AutoIDGenerator;
import org.deegree.feature.persistence.sql.id.FIDMapping;
import org.deegree.feature.persistence.sql.id.IDGenerator;
import org.deegree.feature.persistence.sql.id.UUIDGenerator;
import org.deegree.feature.persistence.sql.rules.CompoundMapping;
import org.deegree.feature.persistence.sql.rules.FeatureMapping;
import org.deegree.feature.persistence.sql.rules.GeometryMapping;
import org.deegree.feature.persistence.sql.rules.Mapping;
import org.deegree.feature.persistence.sql.rules.PrimitiveMapping;
import org.deegree.feature.types.AppSchema;
import org.deegree.feature.types.FeatureType;
import org.deegree.feature.types.property.CodePropertyType;
import org.deegree.feature.types.property.CustomPropertyType;
import org.deegree.feature.types.property.FeaturePropertyType;
import org.deegree.feature.types.property.GeometryPropertyType;
import org.deegree.feature.types.property.GeometryPropertyType.GeometryType;
import org.deegree.feature.types.property.ObjectPropertyType;
import org.deegree.feature.types.property.SimplePropertyType;
import org.deegree.filter.expression.ValueReference;
import org.deegree.gml.schema.GMLSchemaInfoSet;
import org.deegree.sqldialect.filter.DBField;
import org.deegree.sqldialect.filter.MappingExpression;
import org.jaxen.NamespaceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Creates {@link MappedAppSchema} instances from {@link AppSchema}s by inferring a canonical database mapping.
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class AppSchemaMapper {
private static final Logger LOG = LoggerFactory.getLogger( AppSchemaMapper.class );
private final AppSchema appSchema;
private final MappingContextManager mcManager;
private final MappedAppSchema mappedSchema;
private final HashMap<String, String> nsToPrefix;
private final GeometryStorageParams geometryParams;
private final boolean useIntegerFids;
private final int MAX_COMPLEXITY_INDEX = 100;
/**
* Creates a new {@link AppSchemaMapper} instance for the given schema.
*
* @param appSchema
* application schema to be mapped, must not be <code>null</code>
* @param createBlobMapping
* true, if BLOB mapping should be performed, false otherwise
* @param createRelationalMapping
* true, if relational mapping should be performed, false otherwise
* @param geometryParams
* parameters for storing geometries, must not be <code>null</code>
*/
public AppSchemaMapper( AppSchema appSchema, boolean createBlobMapping, boolean createRelationalMapping,
GeometryStorageParams geometryParams, int maxLength, boolean usePrefixedSQLIdentifiers,
boolean useIntegerFids ) {
this.appSchema = appSchema;
this.geometryParams = geometryParams;
this.useIntegerFids = useIntegerFids;
List<FeatureType> ftList = appSchema.getFeatureTypes( null, false, false );
List<FeatureType> blackList = new ArrayList<FeatureType>();
for ( FeatureType ft : ftList ) {
if ( ft.getName().getNamespaceURI().equals( appSchema.getGMLSchema().getVersion().getNamespace() ) ) {
blackList.add( ft );
}
}
ftList.removeAll( blackList );
FeatureType[] fts = ftList.toArray( new FeatureType[ftList.size()] );
Map<FeatureType, FeatureType> ftToSuperFt = new HashMap<FeatureType, FeatureType>( appSchema.getFtToSuperFt() );
for ( FeatureType ft : blackList ) {
ftToSuperFt.remove( ft );
}
Map<String, String> prefixToNs = appSchema.getNamespaceBindings();
GMLSchemaInfoSet xsModel = appSchema.getGMLSchema();
FeatureTypeMapping[] ftMappings = null;
nsToPrefix = new HashMap<String, String>();
Iterator<String> nsIter = CommonNamespaces.getNamespaceContext().getNamespaceURIs();
while ( nsIter.hasNext() ) {
String ns = nsIter.next();
nsToPrefix.put( ns, CommonNamespaces.getNamespaceContext().getPrefix( ns ) );
}
nsToPrefix.putAll( xsModel.getNamespacePrefixes() );
mcManager = new MappingContextManager( nsToPrefix, maxLength, usePrefixedSQLIdentifiers );
if ( createRelationalMapping ) {
ftMappings = generateFtMappings( fts );
}
BBoxTableMapping bboxMapping = createBlobMapping ? generateBBoxMapping() : null;
BlobMapping blobMapping = createBlobMapping ? generateBlobMapping() : null;
this.mappedSchema = new MappedAppSchema( fts, ftToSuperFt, prefixToNs, xsModel, ftMappings, bboxMapping,
blobMapping, geometryParams, true, null, appSchema.getGeometryTypes(),
appSchema.getGeometryToSuperType() );
}
/**
* Returns the {@link MappedAppSchema} instance.
*
* @return mapped schema, never <code>null</code>
*/
public MappedAppSchema getMappedSchema() {
return mappedSchema;
}
private BlobMapping generateBlobMapping() {
// TODO
String table = "GML_OBJECTS";
// TODO
BlobCodec codec = new BlobCodec( appSchema.getGMLSchema().getVersion(), NONE );
return new BlobMapping( table, geometryParams.getCrs(), codec );
}
private BBoxTableMapping generateBBoxMapping() {
// TODO
String ftTable = "FEATURE_TYPES";
return new BBoxTableMapping( ftTable, geometryParams.getCrs() );
}
private FeatureTypeMapping[] generateFtMappings( FeatureType[] fts ) {
FeatureTypeMapping[] ftMappings = new FeatureTypeMapping[fts.length];
for ( int i = 0; i < fts.length; i++ ) {
ftMappings[i] = generateFtMapping( fts[i] );
}
return ftMappings;
}
private FeatureTypeMapping generateFtMapping( FeatureType ft ) {
LOG.info( "Mapping feature type '" + ft.getName() + "'" );
MappingContext mc = mcManager.newContext( ft.getName(), detectPrimaryKeyColumnName() );
// TODO
TableName table = new TableName( mc.getTable() );
// TODO
FIDMapping fidMapping = null;
String prefix = ft.getName().getPrefix().toUpperCase() + "_" + ft.getName().getLocalPart().toUpperCase() + "_";
if ( useIntegerFids ) {
IDGenerator generator = new AutoIDGenerator();
Pair<SQLIdentifier, BaseType> fidColumn = new Pair<SQLIdentifier, BaseType>( new SQLIdentifier( "gid" ),
BaseType.INTEGER );
fidMapping = new FIDMapping( prefix, "_", Collections.singletonList( fidColumn ), generator );
} else {
IDGenerator generator = new UUIDGenerator();
Pair<SQLIdentifier, BaseType> fidColumn = new Pair<SQLIdentifier, BaseType>(
new SQLIdentifier(
"attr_gml_id" ),
STRING );
fidMapping = new FIDMapping( prefix, "_", Collections.singletonList( fidColumn ), generator );
}
List<Mapping> mappings = new ArrayList<Mapping>();
for ( PropertyType pt : ft.getPropertyDeclarations() ) {
if ( !pt.getName().getNamespaceURI().equals( appSchema.getGMLSchema().getVersion().getNamespace() ) ) {
mappings.addAll( generatePropMapping( pt, mc ) );
} else if ( pt.getName().getLocalPart().equals( "identifier" ) ) {
mappings.addAll( generatePropMapping( pt, mc ) );
}
}
return new FeatureTypeMapping( ft.getName(), table, fidMapping, mappings );
}
private List<Mapping> generatePropMapping( PropertyType pt, MappingContext mc ) {
LOG.debug( "Mapping property '" + pt.getName() + "'" );
List<Mapping> mappings = new ArrayList<Mapping>();
XSElementDeclaration elDecl = pt.getElementDecl();
int before = mcManager.getContextCount();
try {
if ( elDecl != null && elDecl.getTypeDefinition() instanceof XSComplexTypeDefinition ) {
// consider every concrete element substitution
List<XSElementDeclaration> substitutions = appSchema.getGMLSchema().getSubstitutions( elDecl, null,
true, true );
for ( XSElementDeclaration substitution : substitutions ) {
try {
QName eName = new QName( substitution.getNamespace(), substitution.getName() );
ValueReference path = getPropName( eName );
MappingContext propMc = null;
List<TableJoin> jc = null;
if ( pt.getMaxOccurs() == 1 ) {
propMc = mcManager.mapOneToOneElement( mc, eName );
} else {
propMc = mcManager.mapOneToManyElements( mc, eName );
jc = generateJoinChain( mc, propMc );
}
List<Mapping> particles = null;
ObjectPropertyType opt = appSchema.getGMLSchema().getCustomElDecl( substitution );
before = mcManager.getContextCount();
if ( opt != null ) {
particles = generateMapping( (XSComplexTypeDefinition) substitution.getTypeDefinition(),
propMc, new ArrayList<XSElementDeclaration>(),
new ArrayList<XSComplexTypeDefinition>(), opt );
} else {
particles = generateMapping( (XSComplexTypeDefinition) substitution.getTypeDefinition(),
propMc, new ArrayList<XSElementDeclaration>(),
new ArrayList<XSComplexTypeDefinition>(),
substitution.getNillable() );
}
int complexity = mcManager.getContextCount() - before;
LOG.info( "Mapping complexity index of property type '" + eName + "': " + complexity );
if ( complexity > MAX_COMPLEXITY_INDEX ) {
LOG.warn( "Mapping property type '" + eName + "' exceeds complexity limit: " + complexity );
mappings.clear();
} else {
mappings.add( new CompoundMapping( path, pt.getMinOccurs() == 0, particles, jc, elDecl ) );
}
} catch ( Throwable t ) {
LOG.warn( "Unable to create relational mapping for property type '" + pt.getName() + "': "
+ t.getMessage() );
}
}
return mappings;
}
if ( pt instanceof SimplePropertyType ) {
mappings.add( generatePropMapping( (SimplePropertyType) pt, mc ) );
} else if ( pt instanceof GeometryPropertyType ) {
mappings.add( generatePropMapping( (GeometryPropertyType) pt, mc ) );
} else if ( pt instanceof FeaturePropertyType ) {
mappings.add( generatePropMapping( (FeaturePropertyType) pt, mc ) );
} else if ( pt instanceof CustomPropertyType ) {
mappings.add( generatePropMapping( (CustomPropertyType) pt, mc ) );
} else if ( pt instanceof CodePropertyType ) {
mappings.add( generatePropMapping( (CodePropertyType) pt, mc ) );
} else {
LOG.warn( "Unhandled property type '" + pt.getName() + "': " + pt.getClass().getName() );
}
} catch ( Throwable t ) {
LOG.warn( "Unable to create relational mapping for property type '" + pt.getName() + "': " + t.getMessage() );
}
int complexity = mcManager.getContextCount() - before;
LOG.debug( "Mapping complexity index of property type '" + pt.getName() + "': " + complexity );
if ( complexity > MAX_COMPLEXITY_INDEX ) {
LOG.warn( "Mapping property type '" + pt.getName() + "' exceeds complexity limit: " + complexity );
mappings.clear();
}
return mappings;
}
private PrimitiveMapping generatePropMapping( SimplePropertyType pt, MappingContext mc ) {
LOG.debug( "Mapping simple property '" + pt.getName() + "'" );
ValueReference path = getPropName( pt.getName() );
MappingContext propMc = null;
List<TableJoin> jc = null;
MappingExpression mapping = null;
if ( pt.getMaxOccurs() == 1 ) {
propMc = mcManager.mapOneToOneElement( mc, pt.getName() );
mapping = new DBField( propMc.getColumn() );
} else {
propMc = mcManager.mapOneToManyElements( mc, pt.getName() );
jc = generateJoinChain( mc, propMc );
mapping = new DBField( "value" );
}
return new PrimitiveMapping( path, false, mapping, pt.getPrimitiveType(), jc, null );
}
private GeometryMapping generatePropMapping( GeometryPropertyType pt, MappingContext mc ) {
LOG.debug( "Mapping geometry property '" + pt.getName() + "'" );
ValueReference path = getPropName( pt.getName() );
MappingContext propMc = null;
List<TableJoin> jc = null;
MappingExpression mapping = null;
if ( pt.getMaxOccurs() == 1 ) {
propMc = mcManager.mapOneToOneElement( mc, pt.getName() );
mapping = new DBField( propMc.getColumn() );
} else {
propMc = mcManager.mapOneToManyElements( mc, pt.getName() );
jc = generateJoinChain( mc, propMc );
mapping = new DBField( "value" );
}
return new GeometryMapping( path, pt.getMinOccurs() == 0, mapping, pt.getGeometryType(), geometryParams, jc );
}
private Mapping generatePropMapping( FeaturePropertyType pt, MappingContext mc ) {
LOG.debug( "Mapping feature property '" + pt.getName() + "'" );
ValueReference path = getPropName( pt.getName() );
List<TableJoin> jc = null;
MappingContext fkMC = null;
MappingContext hrefMC = null;
if ( pt.getMaxOccurs() == 1 ) {
fkMC = mcManager.mapOneToOneElement( mc, pt.getName() );
String ns = pt.getName().getNamespaceURI();
String prefix = pt.getName().getPrefix();
String localName = pt.getName().getLocalPart() + "_href";
hrefMC = mcManager.mapOneToOneElement( mc, new QName( ns, localName, prefix ) );
} else {
MappingContext mc2 = mcManager.mapOneToManyElements( mc, pt.getName() );
jc = generateJoinChain( mc, mc2 );
fkMC = mcManager.mapOneToOneElement( mc, new QName( "fk" ) );
hrefMC = mcManager.mapOneToOneElement( mc, new QName( "href" ) );
}
FeatureType valueFt = pt.getValueFt();
if ( valueFt != null && valueFt.getSchema().getSubtypes( valueFt ).length == 1 ) {
TableJoin ftJoin = generateFtJoin( fkMC, valueFt );
if ( ftJoin != null ) {
jc = new ArrayList<TableJoin>( jc );
jc.add( ftJoin );
} else {
jc = Collections.singletonList( ftJoin );
}
} else {
LOG.warn( "Ambigous feature property type '" + pt.getName() + "'. Not creating a Join mapping." );
}
return new FeatureMapping( path, pt.getMinOccurs() == 0, new DBField( hrefMC.getColumn() ), pt.getFTName(), jc );
}
private CompoundMapping generatePropMapping( CustomPropertyType pt, MappingContext mc ) {
LOG.debug( "Mapping custom property '" + pt.getName() + "'" );
XSComplexTypeDefinition xsTypeDef = pt.getXSDValueType();
if ( xsTypeDef == null ) {
LOG.warn( "No XSD type definition available for custom property '" + pt.getName() + "'. Skipping it." );
return null;
}
ValueReference path = getPropName( pt.getName() );
MappingContext propMc = null;
List<TableJoin> jc = null;
if ( pt.getMaxOccurs() == 1 ) {
propMc = mcManager.mapOneToOneElement( mc, pt.getName() );
} else {
propMc = mcManager.mapOneToManyElements( mc, pt.getName() );
jc = generateJoinChain( mc, propMc );
}
List<XSElementDeclaration> parentEls = new ArrayList<XSElementDeclaration>();
parentEls.add( pt.getElementDecl() );
List<XSComplexTypeDefinition> parentCts = new ArrayList<XSComplexTypeDefinition>();
List<Mapping> particles = new ArrayList<Mapping>();
try {
particles = generateMapping( pt.getXSDValueType(), propMc, parentEls, parentCts, pt.isNillable() );
return new CompoundMapping( path, pt.getMinOccurs() == 0, particles, jc, pt.getElementDecl() );
} catch ( Throwable t ) {
LOG.warn( "Full relational mapping of property '" + pt.getName() + "' failed: " + t.getMessage() );
}
return new CompoundMapping( path, pt.getMinOccurs() == 0, particles, jc, pt.getElementDecl() );
}
private CompoundMapping generatePropMapping( CodePropertyType pt, MappingContext mc ) {
LOG.debug( "Mapping code property '" + pt.getName() + "'" );
ValueReference path = getPropName( pt.getName() );
MappingContext propMc = null;
MappingContext codeSpaceMc = null;
List<TableJoin> jc = null;
MappingExpression mapping = null;
if ( pt.getMaxOccurs() == 1 ) {
propMc = mcManager.mapOneToOneElement( mc, pt.getName() );
codeSpaceMc = mcManager.mapOneToOneAttribute( propMc, new QName( "codeSpace" ) );
mapping = new DBField( propMc.getColumn() );
} else {
propMc = mcManager.mapOneToManyElements( mc, pt.getName() );
codeSpaceMc = mcManager.mapOneToOneAttribute( propMc, new QName( "codeSpace" ) );
jc = generateJoinChain( mc, propMc );
mapping = new DBField( "value" );
}
MappingExpression csMapping = new DBField( codeSpaceMc.getColumn() );
List<Mapping> particles = new ArrayList<Mapping>();
particles.add( new PrimitiveMapping( new ValueReference( "text()", null ), false, mapping,
new PrimitiveType( STRING ), null, null ) );
particles.add( new PrimitiveMapping( new ValueReference( "@codeSpace", null ), true, csMapping,
new PrimitiveType( STRING ), null, null ) );
return new CompoundMapping( path, pt.getMinOccurs() == 0, particles, jc, pt.getElementDecl() );
}
private List<TableJoin> generateJoinChain( MappingContext from, MappingContext to ) {
TableName fromTable = new TableName( from.getTable() );
TableName toTable = new TableName( to.getTable() );
List<String> fromColumns = Collections.singletonList( from.getIdColumn() );
List<String> toColumns = Collections.singletonList( "parentfk" );
List<String> orderColumns = Collections.singletonList( "num" );
Map<SQLIdentifier, IDGenerator> keyColumnToIdGenerator = new HashMap<SQLIdentifier, IDGenerator>();
keyColumnToIdGenerator.put( new SQLIdentifier( "id" ), new AutoIDGenerator() );
TableJoin join = new TableJoin( fromTable, toTable, fromColumns, toColumns, orderColumns, true,
keyColumnToIdGenerator );
return Collections.singletonList( join );
}
private TableJoin generateFtJoin( MappingContext from, FeatureType valueFt ) {
if ( valueFt != null && valueFt.getSchema().getSubtypes( valueFt ).length == 1 ) {
LOG.warn( "Ambigous feature join." );
}
TableName fromTable = new TableName( from.getTable() );
TableName toTable = new TableName( "?" );
List<String> fromColumns = Collections.singletonList( from.getColumn() );
List<String> toColumns = Collections.singletonList( detectPrimaryKeyColumnName() );
Map<SQLIdentifier, IDGenerator> keyColumnToIdGenerator = new HashMap<SQLIdentifier, IDGenerator>();
keyColumnToIdGenerator.put( new SQLIdentifier( "id" ), new AutoIDGenerator() );
return new TableJoin( fromTable, toTable, fromColumns, toColumns, Collections.EMPTY_LIST, false,
keyColumnToIdGenerator );
}
private List<Mapping> generateMapping( XSComplexTypeDefinition typeDef, MappingContext mc,
List<XSElementDeclaration> parentEls,
List<XSComplexTypeDefinition> parentCTs, boolean isNillable ) {
if ( typeDef.getName() != null ) {
for ( XSComplexTypeDefinition ct : parentCTs ) {
if ( ct.getName() != null ) {
if ( typeDef.getName().equals( ct.getName() ) && typeDef.getNamespace().equals( ct.getNamespace() ) ) {
handleCycle( parentEls, parentCTs );
return Collections.emptyList();
}
}
}
}
parentCTs.add( typeDef );
List<Mapping> particles = new ArrayList<Mapping>();
// text node
if ( typeDef.getContentType() != CONTENTTYPE_EMPTY && typeDef.getContentType() != CONTENTTYPE_ELEMENT ) {
// TODO
NamespaceContext nsContext = null;
ValueReference path = new ValueReference( "text()", nsContext );
String column = mc.getColumn();
if ( column == null || column.isEmpty() ) {
column = "value";
}
DBField dbField = new DBField( mc.getTable(), column );
PrimitiveType pt = new PrimitiveType( BaseType.STRING );
if ( typeDef.getSimpleType() != null ) {
pt = new PrimitiveType( typeDef.getSimpleType() );
}
particles.add( new PrimitiveMapping( path, false, dbField, pt, null, null ) );
}
// attributes
XSObjectList attributeUses = typeDef.getAttributeUses();
for ( int i = 0; i < attributeUses.getLength(); i++ ) {
XSAttributeUse attrUse = ( (XSAttributeUse) attributeUses.item( i ) );
XSAttributeDeclaration attrDecl = attrUse.getAttrDeclaration();
QName attrName = new QName( attrDecl.getName() );
if ( attrDecl.getNamespace() != null ) {
attrName = new QName( attrDecl.getNamespace(), attrDecl.getName() );
}
MappingContext attrMc = mcManager.mapOneToOneAttribute( mc, attrName );
// TODO
NamespaceContext nsContext = null;
ValueReference path = new ValueReference( "@" + getName( attrName ), nsContext );
DBField dbField = new DBField( attrMc.getTable(), attrMc.getColumn() );
PrimitiveType pt = new PrimitiveType( attrDecl.getTypeDefinition() );
particles.add( new PrimitiveMapping( path, !attrUse.getRequired(), dbField, pt, null, null ) );
}
// xsi:nil attribute
if ( isNillable ) {
QName attrName = new QName( XSINS, "nil", "xsi" );
MappingContext attrMc = mcManager.mapOneToOneAttribute( mc, attrName );
ValueReference path = new ValueReference( "@" + getName( attrName ), null );
DBField dbField = new DBField( attrMc.getTable(), attrMc.getColumn() );
particles.add( new PrimitiveMapping( path, true, dbField, new PrimitiveType( BOOLEAN ), null, null ) );
}
// child elements
XSParticle particle = typeDef.getParticle();
if ( particle != null ) {
List<Mapping> childElMappings = generateMapping( particle, 1, mc, parentEls, parentCTs );
particles.addAll( childElMappings );
}
return particles;
}
private void handleCycle( List<XSElementDeclaration> parentEls, List<XSComplexTypeDefinition> parentCTs ) {
StringBuffer sb = new StringBuffer( "Path: " );
for ( XSElementDeclaration qName : parentEls ) {
sb.append( "{" );
sb.append( qName.getNamespace() );
sb.append( "}" );
sb.append( qName.getName() );
sb.append( " -> " );
}
throw new RuntimeException( "Detected unhandled cycle '" + sb + "'." );
}
private List<Mapping> generateMapping( XSComplexTypeDefinition typeDef, MappingContext mc,
List<XSElementDeclaration> parentEls,
List<XSComplexTypeDefinition> parentCTs, ObjectPropertyType opt ) {
List<Mapping> particles = new ArrayList<Mapping>();
// attributes
XSObjectList attributeUses = typeDef.getAttributeUses();
for ( int i = 0; i < attributeUses.getLength(); i++ ) {
XSAttributeUse attrUse = ( (XSAttributeUse) attributeUses.item( i ) );
XSAttributeDeclaration attrDecl = attrUse.getAttrDeclaration();
QName attrName = new QName( attrDecl.getName() );
if ( XLNNS.equals( attrDecl.getNamespace() ) ) {
// TODO should all xlink attributes be skipped?
continue;
}
if ( attrDecl.getNamespace() != null ) {
attrName = new QName( attrDecl.getNamespace(), attrDecl.getName() );
}
MappingContext attrMc = mcManager.mapOneToOneAttribute( mc, attrName );
// TODO
NamespaceContext nsContext = null;
ValueReference path = new ValueReference( "@" + getName( attrName ), nsContext );
DBField dbField = new DBField( attrMc.getTable(), attrMc.getColumn() );
PrimitiveType pt = new PrimitiveType( attrDecl.getTypeDefinition() );
particles.add( new PrimitiveMapping( path, !attrUse.getRequired(), dbField, pt, null, null ) );
}
// xsi:nil attribute
if ( opt.isNillable() ) {
QName attrName = new QName( XSINS, "nil", "xsi" );
MappingContext attrMc = mcManager.mapOneToOneAttribute( mc, attrName );
ValueReference path = new ValueReference( "@" + getName( attrName ), null );
DBField dbField = new DBField( attrMc.getTable(), attrMc.getColumn() );
particles.add( new PrimitiveMapping( path, true, dbField, new PrimitiveType( BOOLEAN ), null, null ) );
}
ValueReference path = new ValueReference( ".", null );
if ( opt instanceof GeometryPropertyType ) {
GeometryType gt = GeometryType.GEOMETRY;
MappingContext elMC = mcManager.mapOneToOneElement( mc, new QName( "value" ) );
particles.add( new GeometryMapping( path, true, new DBField( elMC.getColumn() ), gt, geometryParams, null ) );
} else if ( opt instanceof FeaturePropertyType ) {
QName valueFtName = ( (FeaturePropertyType) opt ).getFTName();
MappingContext fkMC = mcManager.mapOneToOneElement( mc, new QName( "fk" ) );
List<TableJoin> jc = Collections.emptyList();
TableJoin ftJoin = generateFtJoin( fkMC, ( (FeaturePropertyType) opt ).getValueFt() );
if ( ftJoin != null ) {
jc = new ArrayList<TableJoin>( jc );
jc.add( ftJoin );
}
MappingContext hrefMC = mcManager.mapOneToOneElement( mc, new QName( "href" ) );
particles.add( new FeatureMapping( path, true, new DBField( hrefMC.getColumn() ), valueFtName, jc ) );
} else {
LOG.warn( "Unhandled object property type '" + opt.getClass() + "'." );
}
return particles;
}
private List<Mapping> generateMapping( XSParticle particle, int maxOccurs, MappingContext mc,
List<XSElementDeclaration> parentEls, List<XSComplexTypeDefinition> parentCTs ) {
List<Mapping> childElMappings = new ArrayList<Mapping>();
// // check if the particle term defines a GMLObjectPropertyType
// if ( particle.getTerm() instanceof XSElementDeclaration ) {
// XSElementDeclaration elDecl = (XSElementDeclaration) particle.getTerm();
// QName elName = new QName( elDecl.getNamespace(), elDecl.getName() );
// int minOccurs = particle.getMinOccurs();
// maxOccurs = particle.getMaxOccursUnbounded() ? -1 : particle.getMaxOccurs();
// // TODO
// List<PropertyType> ptSubstitutions = null;
// ObjectPropertyType pt = appSchema.getXSModel().getGMLPropertyDecl( elDecl, elName, minOccurs, maxOccurs,
// ptSubstitutions );
// if ( pt != null ) {
// if ( pt instanceof GeometryPropertyType ) {
// childElMappings.add( generatePropMapping( (GeometryPropertyType) pt, mc ) );
// } else if ( pt instanceof FeaturePropertyType ) {
// childElMappings.add( generatePropMapping( (FeaturePropertyType) pt, mc ) );
// } else {
// LOG.warn( "TODO: Generic object property type " + pt );
if ( childElMappings.isEmpty() ) {
if ( particle.getMaxOccursUnbounded() ) {
childElMappings.addAll( generateMapping( particle.getTerm(), -1, mc, parentEls, parentCTs ) );
} else {
for ( int i = 1; i <= particle.getMaxOccurs(); i++ ) {
childElMappings.addAll( generateMapping( particle.getTerm(), i, mc,
new ArrayList<XSElementDeclaration>( parentEls ),
new ArrayList<XSComplexTypeDefinition>( parentCTs ) ) );
}
}
}
return childElMappings;
}
private List<Mapping> generateMapping( XSTerm term, int occurence, MappingContext mc,
List<XSElementDeclaration> parentEls, List<XSComplexTypeDefinition> parentCTs ) {
List<Mapping> mappings = new ArrayList<Mapping>();
if ( term instanceof XSElementDeclaration ) {
mappings.addAll( generateMapping( (XSElementDeclaration) term, occurence, mc, parentEls, parentCTs ) );
} else if ( term instanceof XSModelGroup ) {
mappings.addAll( generateMapping( (XSModelGroup) term, occurence, mc, parentEls, parentCTs ) );
} else {
mappings.addAll( generateMapping( (XSWildcard) term, occurence, mc, parentEls, parentCTs ) );
}
return mappings;
}
private List<Mapping> generateMapping( XSElementDeclaration elDecl, int occurence, MappingContext mc,
List<XSElementDeclaration> parentEls, List<XSComplexTypeDefinition> parentCTs ) {
if ( elDecl.getScope() == XSConstants.SCOPE_GLOBAL ) {
for ( XSElementDeclaration el : parentEls ) {
if ( elDecl.getName().equals( el.getName() ) && elDecl.getNamespace().equals( el.getNamespace() ) ) {
handleCycle( parentEls, parentCTs );
return Collections.emptyList();
}
}
}
parentEls.add( elDecl );
List<Mapping> mappings = new ArrayList<Mapping>();
QName eName = new QName( elDecl.getNamespace(), elDecl.getName() );
// LOG.warn( "Skipping mapping of AbstractCRS element" );
// return mappings;
// LOG.warn( "Skipping mapping of TimeOrdinalEra element" );
// return mappings;
// LOG.warn( "Skipping mapping of TimePeriod element" );
// return mappings;
// LOG.warn( "Skipping mapping of EX_GeographicDescription element" );
// consider every concrete element substitution
List<XSElementDeclaration> substitutions = appSchema.getGMLSchema().getSubstitutions( elDecl, null, true, true );
if ( eName.equals( new QName( "http:
substitutions.clear();
substitutions.add( elDecl );
}
if ( eName.equals( new QName( "http:
substitutions.clear();
substitutions.add( elDecl );
}
NamespaceContext nsContext = null;
for ( XSElementDeclaration substitution : substitutions ) {
ObjectPropertyType opt = appSchema.getGMLSchema().getCustomElDecl( substitution );
if ( opt != null ) {
mappings.addAll( generatePropMapping( opt, mc ) );
} else {
QName elName = new QName( substitution.getName() );
if ( substitution.getNamespace() != null ) {
elName = new QName( substitution.getNamespace(), substitution.getName() );
}
MappingContext elMC = null;
if ( occurence == 1 ) {
elMC = mcManager.mapOneToOneElement( mc, elName );
} else {
elMC = mcManager.mapOneToManyElements( mc, elName );
}
XSTypeDefinition typeDef = substitution.getTypeDefinition();
List<TableJoin> jc = null;
if ( occurence == -1 ) {
jc = generateJoinChain( mc, elMC );
}
ValueReference path = new ValueReference( getName( elName ), nsContext );
if ( typeDef instanceof XSComplexTypeDefinition ) {
List<Mapping> particles = generateMapping( (XSComplexTypeDefinition) typeDef, elMC,
new ArrayList<XSElementDeclaration>( parentEls ),
new ArrayList<XSComplexTypeDefinition>( parentCTs ),
substitution.getNillable() );
// TODO
mappings.add( new CompoundMapping( path, false, particles, jc, substitution ) );
} else {
MappingExpression mapping = new DBField( elMC.getColumn() );
PrimitiveType pt = new PrimitiveType( (XSSimpleTypeDefinition) typeDef );
mappings.add( new PrimitiveMapping( path, false, mapping, pt, jc, null ) );
}
}
}
return mappings;
}
private List<Mapping> generateMapping( XSModelGroup modelGroup, int occurrence, MappingContext mc,
List<XSElementDeclaration> parentEls, List<XSComplexTypeDefinition> parentCTs ) {
List<Mapping> mappings = new ArrayList<Mapping>();
XSObjectList particles = modelGroup.getParticles();
for ( int i = 0; i < particles.getLength(); i++ ) {
XSParticle particle = (XSParticle) particles.item( i );
mappings.addAll( generateMapping( particle, occurrence, mc,
new ArrayList<XSElementDeclaration>( parentEls ),
new ArrayList<XSComplexTypeDefinition>( parentCTs ) ) );
}
return mappings;
}
private List<Mapping> generateMapping( XSWildcard wildCard, int occurrence, MappingContext mc,
List<XSElementDeclaration> parentEls, List<XSComplexTypeDefinition> parentCTs ) {
LOG.debug( "Handling of wild cards not implemented yet." );
StringBuffer sb = new StringBuffer( "Path: " );
for ( XSElementDeclaration parentEl : parentEls ) {
sb.append( parentEl.getName() );
sb.append( " -> " );
}
sb.append( "wildcard" );
LOG.debug( "Skipping wildcard at path: " + sb );
return new ArrayList<Mapping>();
}
// private String getPrimitiveTypeName( XSSimpleTypeDefinition typeDef ) {
// if ( typeDef == null ) {
// return "string";
// return XMLValueMangler.getPrimitiveType( typeDef ).getXSTypeName();
private QName getQName( XSTypeDefinition xsType ) {
QName name = null;
if ( !xsType.getAnonymous() ) {
name = new QName( xsType.getNamespace(), xsType.getName() );
}
return name;
}
private String getName( QName name ) {
if ( name.getNamespaceURI() != null && !name.getNamespaceURI().equals( "" ) ) {
String prefix = nsToPrefix.get( name.getNamespaceURI() );
return prefix + ":" + name.getLocalPart();
}
return name.getLocalPart();
}
private ValueReference getPropName( QName name ) {
if ( name.getNamespaceURI() != null && !name.getNamespaceURI().equals( "" ) ) {
String prefix = name.getPrefix();
if ( prefix == null || prefix.isEmpty() ) {
prefix = nsToPrefix.get( name.getNamespaceURI() );
}
name = new QName( name.getNamespaceURI(), name.getLocalPart(), prefix );
}
return new ValueReference( name );
}
private String detectPrimaryKeyColumnName() {
return useIntegerFids ? "gid" : "attr_gml_id";
}
}
|
package org.eclipse.hawkbit.repository;
import static org.fest.assertions.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.junit.Test;
import org.springframework.security.access.prepost.PreAuthorize;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Unit Tests - Repository")
@Stories("Security Test")
public class RepositoryManagementMethodPreAuthorizeAnnotatedTest {
private static final Set<Method> METHOD_SECURITY_EXCLUSION = new HashSet<>();
static {
METHOD_SECURITY_EXCLUSION.add(getMethod(SystemManagement.class, "currentTenant"));
}
@Test
@Description("Verfies that repository methods are @PreAuthorize annotated")
public void repositoryManagementMethodsArePreAuthorizedAnnotated()
throws ClassNotFoundException, URISyntaxException, IOException {
final List<Class<?>> findInterfacesInPackage = findInterfacesInPackage(getClass().getPackage(),
Pattern.compile(".*Management"));
assertThat(findInterfacesInPackage).isNotEmpty();
for (final Class<?> interfaceToCheck : findInterfacesInPackage) {
assertDeclaredMethodsContainsPreAuthorizeAnnotaions(interfaceToCheck);
}
}
/**
* asserts that the given methods are annotated with the
* {@link PreAuthorize} annotation for security. Inherited methods are not
* checked. The following methods are excluded due inherited from
* {@link Object}, like equals() or toString().
*
* @param clazz
* the class to retrieve the public declared methods
*/
private static void assertDeclaredMethodsContainsPreAuthorizeAnnotaions(final Class<?> clazz) {
final Method[] declaredMethods = clazz.getDeclaredMethods();
for (final Method method : declaredMethods) {
if (!METHOD_SECURITY_EXCLUSION.contains(method) && !method.isSynthetic()
&& Modifier.isPublic(method.getModifiers())) {
final PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
assertThat(annotation).as("The public method " + method.getName() + " in class " + clazz.getName()
+ " is not annoated with @PreAuthorize, security leak?").isNotNull();
}
}
}
/**
* Finds all interfaces in a given packages which matches the given filter.
*
* @param p
* the package to search for interfaces in
* @param includeFilter
* the pattern which interfaces class names should be included
* @return a list of loaded interfaces in a specific package and matches the
* given filter
* @throws URISyntaxException
* @throws IOException
* @throws ClassNotFoundException
*/
private List<Class<?>> findInterfacesInPackage(final Package p, final Pattern includeFilter)
throws URISyntaxException, IOException, ClassNotFoundException {
final List<Class<?>> interfacesToReturn = new ArrayList<>();
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final Enumeration<URL> resources = classLoader.getResources(p.getName().replace(".", "/"));
while (resources.hasMoreElements()) {
final String uriPath = new URI(resources.nextElement().toString()).getPath();
if (uriPath != null) {
final File packageDirectory = new File(uriPath);
final File[] filesInPackage = packageDirectory.listFiles();
for (final File classFile : filesInPackage) {
final String classNameWithExtension = classFile.getName();
final int indexOfExtension = classNameWithExtension.indexOf(".class");
if (indexOfExtension > 0) {
final String classNameWithoutExtension = classNameWithExtension.substring(0, indexOfExtension);
if (includeFilter.matcher(classNameWithoutExtension).matches()) {
final Class<?> classInPackage = Class
.forName(p.getName() + "." + classNameWithoutExtension);
if (classInPackage.isInterface()) {
interfacesToReturn.add(classInPackage);
}
}
}
}
}
}
return interfacesToReturn;
}
private static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>... parameterTypes) {
try {
return clazz.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
|
package eu.project.rapid.common;
/**
* Control Messages for client-server communication Message IDs up to 255 - one byte only, as they
* are sent over sockets using write()/read() - only one byte read/written.
*/
public class RapidMessages {
// Generic Messages
public static final int OK = 1;
public static final int ERROR = 0;
public static final int PING = 11;
public static final int PONG = 12;
// Communication Phone <-> VM
public static final int AC_REGISTER_AS = 13;
public static final int AS_APP_PRESENT_AC = 14;
public static final int AS_APP_REQ_AC = 15;
public static final int AC_OFFLOAD_REQ_AS = 16;
// Communication Phone <-> VM (for testing purposes)
public static final int SEND_INT = 17;
public static final int SEND_BYTES = 18;
public static final int RECEIVE_INT = 19;
public static final int RECEIVE_BYTES = 20;
// Communication Main VM <-> Helper VM
public static final int CLONE_ID_SEND = 21;
// Communication Phone/VM <-> DS/Manager
public static final int PHONE_CONNECTION = 30;
public static final int CLONE_CONNECTION = 31;
public static final int MANAGER_CONNECTION = 32;
public static final int PHONE_AUTHENTICATION = 33;
public static final int AC_REGISTER_NEW_DS = 34;
public static final int AC_REGISTER_PREV_DS = 35;
public static final int AC_REGISTER_SLAM = 36;
public static final int AS_RM_REGISTER_DS = 37;
public static final int AS_RM_REGISTER_VMM = 38;
public static final int AS_RM_NOTIFY_VMM = 39;
public static final int CLONE_AUTHENTICATION = 40;
public static final int MANAGER_AUTHENTICATION = 41;
public static final int GET_ASSOCIATED_CLONE_INFO = 42;
public static final int GET_NEW_CLONE_INFO = 43;
public static final int GET_PORT = 44;
public static final int GET_SSL_PORT = 45;
public static final int DOWNLOAD_FILE = 146;
public static final int UPLOAD_FILE = 147;
public static final int UPLOAD_FILE_RESULT = 48;
public static final int DATA_RATE_THROTTLE = 49;
public static final int DATA_RATE_UNTHROTTLE = 50;
public static final int FORWARD_REQ = 51;
public static final int FORWARD_START = 52;
public static final int FORWARD_END = 53;
public static final int PARALLEL_REQ = 54;
public static final int PARALLEL_START = 55;
public static final int PARALLEL_END = 56;
public static final int AS_RM_MIGRATION_VM = 57;
// Demo server registers with the DS so that the others can find its IP
public static final int DEMO_SERVER_REGISTER_DS = 80;
// Everyone to DS for asking for demo animation ip
public static final int GET_DEMO_SERVER_IP_DS = 81;
// Communication SLAM <-> VMM
public static final int SLAM_START_VM_VMM = 60;
public static final int VMM_REGISTER_SLAM = 61;
public static final int SLAM_GET_VMCPU_VMM = 62;
public static final int SLAM_GET_VMINFO_VMM = 63;
public static final int SLAM_CHANGE_VMFLV_VMM = 64;
public static final int SLAM_CONFIRM_VMFLV_VMM = 65;
// Communication DS <-> VMM
public static final int VMM_REGISTER_DS = 70;
public static final int VMM_NOTIFY_DS = 71;
public static final int VM_REGISTER_DS = 72;
public static final int VM_NOTIFY_DS = 73;
public static final int HELPER_NOTIFY_DS = 74;
public static final int DS_VM_DEREGISTER_VMM = 75;
// Communication DS <-> SLAM
public static final int SLAM_REGISTER_DS = 90;
// Communication Phone <-> Registration Manager
public static final int AC_HELLO_AC_RM = 1;
// Messages to send to the demo server, which will create the animation
// of the events happening on the system
public enum AnimationMsg {
PING,
// Scenario 1: DS, SLAM, VMM starting up
INITIAL_IMG_0,
DS_UP,
SLAM_UP,
SLAM_REGISTER_DS,
VMM_UP,
VMM_REGISTER_DS,
VMM_REGISTER_SLAM,
// Scenario 2:
AC_INITIAL_IMG,
AC_NEW_REGISTER_DS,
DS_NEW_FIND_MACHINES,
DS_NEW_IP_LIST_AC,
AC_NEW_REGISTER_SLAM,
SLAM_NEW_VM_VMM,
VMM_NEW_START_VM,
VMM_NEW_REGISTER_AS,
VMM_NEW_VM_REGISTER_DS,
VMM_NEW_VM_IP_SLAM,
SLAM_NEW_VM_IP_AC,
AC_NEW_REGISTER_VM,
AC_NEW_CONN_VM,
AC_NEW_APK_VM,
AC_NEW_RTT_VM,
AC_NEW_DL_RATE_VM,
AC_NEW_UL_RATE_VM,
AC_NEW_REGISTRATION_OK_VM,
// Scenario 3:
AC_PREV_REGISTRATION_OK_VM,
AC_PREV_UL_RATE_VM,
AC_PREV_DL_RATE_VM,
AC_PREV_RTT_VM,
AC_PREV_APK_VM,
AC_PREV_CONN_VM,
AC_PREV_REGISTER_VM,
AC_REGISTER_VM_ERROR,
SLAM_PREV_VM_IP_AC,
VMM_PREV_VM_IP_SLAM,
VMM_PREV_FIND_VM,
SLAM_PREV_VM_REQ_VMM,
AC_PREV_REGISTER_SLAM,
DS_PREV_IP_AC,
DS_PREV_FIND_MACHINE,
AC_PREV_VM_DS,
// AC_INITIAL_IMG
// Scenario 4: offload execution
AC_OFFLOADING_FINISHED,
AS_RESULT_AC,
AS_RUN_METHOD,
AC_DECISION_OFFLOAD_AS,
AC_PREPARE_DATA,
// AC_INITIAL_IMG,
// Scenario 5: local execution
AC_LOCAL_FINISHED,
AC_DECISION_LOCAL,
//AC_PREPARE_DATA,
//AC_INITIAL_IMG,
// Scenario 6: D2D 1
AC_OFFLOADING_FINISHED_D2D,
AS_RESULT_AC_D2D,
AS_RUN_METHOD_D2D,
AC_OFFLOAD_D2D,
AC_PREPARE_DATA_D2D,
//Scenario 7: D2D 2
AC_RECEIVED_D2D,
AC_NO_MORE_D2D,
AS_BROADCASTING_D2D,
AC_LISTENING_D2D,
D2D_INITIAL_IMG,
}
}
|
package com.rebirthlab.naualgorithms04;
import com.rebirthlab.naualgorithms04.commons.Constants;
import com.rebirthlab.naualgorithms04.commons.RandomNamber;
/**
*
* @author Anastasiy Tovstik <anastasiy.tovstik@gmail.com>
*/
public class StudentId {
private final String series;
private final int number;
public StudentId() {
series = Constants.SERIES.values()[RandomNamber.randInt(0, 4)].toString();
number = RandomNamber.randInt(100, 1000);
}
@Override
public String toString() {
return series + "-" + number;
}
}
|
package owltools.gaf.lego;
import java.util.ArrayList;
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.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.HypergeometricDistributionImpl;
import org.apache.log4j.Logger;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLNamedObject;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLObjectPropertyExpression;
import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLPropertyExpression;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary;
import owltools.gaf.ExtensionExpression;
import owltools.gaf.GafDocument;
import owltools.gaf.GeneAnnotation;
import owltools.graph.OWLGraphEdge;
import owltools.graph.OWLGraphWrapper;
import owltools.util.MinimalModelGenerator;
import owltools.vocab.OBOUpperVocabulary;
public class LegoModelGenerator extends MinimalModelGenerator {
private static Logger LOG = Logger.getLogger(LegoModelGenerator.class);
/**
* E<sup>A</sup> ⊆ A x A x T<sup>A</sup>
*/
//public ActivityNetwork activityNetwork;
Map<String,Set<String>> proteinInteractionMap;
Set<String> populationGeneSet;
Map<Object,String> labelMap;
Map<OWLClass,Set<String>> geneByInferredClsMap;
Map<OWLClass,Set<OWLClass>> anctesorMap;
HashMap<String, Set<OWLClass>> clsByGeneMap;
Set<OWLClass> activityClassSet;
public Set<OWLClass> processClassSet;
private Map<String,Set<OWLNamedIndividual>> activityByGene;
Double ccp = null; // cumulative
/**
* M ⊆ N x N, N = A ∪ P
*/
//public Partonomy partonomy;
//Set<Process> processSet; // P : process *instances*
OWLGraphWrapper ogw;
/**
* @param tbox
* @throws OWLOntologyCreationException
*/
public LegoModelGenerator(OWLOntology tbox) throws OWLOntologyCreationException {
super(tbox);
}
/**
* @param tbox
* @param abox
* @param rf
* @throws OWLOntologyCreationException
*/
@Deprecated
public LegoModelGenerator(OWLOntology tbox, OWLOntology abox, OWLReasonerFactory rf)
throws OWLOntologyCreationException {
super(tbox, abox, rf);
// TODO Auto-generated constructor stub
}
/**
* @param tbox
* @param abox
* @throws OWLOntologyCreationException
*/
public LegoModelGenerator(OWLOntology tbox, OWLOntology abox)
throws OWLOntologyCreationException {
super(tbox, abox);
// TODO Auto-generated constructor stub
}
/**
* @param tbox
* @param reasonerFactory
* @throws OWLOntologyCreationException
*/
public LegoModelGenerator(OWLOntology tbox, OWLReasonerFactory reasonerFactory)
throws OWLOntologyCreationException {
super(tbox, reasonerFactory);
// TODO Auto-generated constructor stub
}
/**
* Unregisters abox ontology
*/
public void dispose() {
// getOWLOntologyManager().removeOntology(getAboxOntology());
super.dispose();
}
/**
* @param gafdoc (optional)
* @param g
*/
public void initialize(GafDocument gafdoc, OWLGraphWrapper g) {
ogw = g;
geneByInferredClsMap = new HashMap<OWLClass,Set<String>>();
populationGeneSet = new HashSet<String>();
clsByGeneMap = new HashMap<String,Set<OWLClass>>();
labelMap = new HashMap<Object,String>();
proteinInteractionMap = new HashMap<String,Set<String>>();
activityByGene = new HashMap<String,Set<OWLNamedIndividual>>();
setRemoveAmbiguousIndividuals(false);
//this.setPrecomputePropertyClassCombinations(true);
Set<OWLPropertyExpression> rels =
new HashSet<OWLPropertyExpression>(getInvolvedInRelations());
List<GeneAnnotation> anns = new ArrayList<GeneAnnotation>();
if (gafdoc != null) {
anns = gafdoc.getGeneAnnotations();
}
for (GeneAnnotation ann : anns) {
String c = ann.getCls();
OWLClass cls = ogw.getOWLClassByIdentifier(c);
String gene = ann.getBioentity();
// special case : protein binding - we build a PPI
// using the WITH/FROM column
if (c.equals("GO:0005515")) {
for (String b : ann.getWithExpression().split("\\|")) {
//LOG.info("Adding PPI based on WITH col");
addPPI(gene, b);
}
continue;
}
for (List<ExtensionExpression> eel : ann.getExtensionExpressions()) {
for (ExtensionExpression ee : eel) {
// temporary measure - treat all ext expressions as PPIs
addPPI(gene, ee.getCls());
}
}
populationGeneSet.add(gene);
String sym = ann.getBioentityObject().getSymbol();
if (sym != null && !sym.equals(""))
labelMap.put(gene, sym);
if (!clsByGeneMap.containsKey(gene))
clsByGeneMap.put(gene, new HashSet<OWLClass>());
clsByGeneMap.get(gene).add(cls);
//LOG.info("Finding ancestors of "+cls+" over "+rels);
for (OWLObject ancCls : g.getAncestorsReflexive(cls, rels)) { // TODO-use reasoner
if (ancCls instanceof OWLClass) {
OWLClass anc = (OWLClass) ancCls;
if (!isQueryClass(anc)) {
//LOG.info(" "+gene + " => "+c+" => "+anc + " // "+ancCls);
if (!geneByInferredClsMap.containsKey(anc))
geneByInferredClsMap.put(anc, new HashSet<String>());
geneByInferredClsMap.get(anc).add(gene);
}
}
}
}
OWLClass MF = getOWLClass(OBOUpperVocabulary.GO_molecular_function);
OWLClass BP = getOWLClass(OBOUpperVocabulary.GO_biological_process);
activityClassSet = getReasoner().getSubClasses(MF, false).getFlattened();
LOG.info("# subclasses of "+MF+" = "+activityClassSet.size());
processClassSet = getReasoner().getSubClasses(BP, false).getFlattened();
LOG.info("# subclasses of "+BP+" "+processClassSet.size());
for (OWLClass cls : this.getTboxOntology().getClassesInSignature(true)) {
String label = g.getLabel(cls);
if (label != "" && label != null)
labelMap.put(cls, label);
}
}
public void buildNetwork(OWLClass processCls, Collection<String> seedGenes) throws OWLOntologyCreationException {
generateNecessaryIndividuals(processCls, true);
addGenes(processCls, seedGenes);
//inferLocations();
connectGraph();
normalizeDirections();
combineMultipleEnablers();
}
/**
* Wraps {@link #buildNetwork(OWLClass, Collection)}
*
* @param processClsId
* @param seedGenes
* @throws OWLOntologyCreationException
*/
public void buildNetwork(String processClsId, Collection<String> seedGenes) throws OWLOntologyCreationException {
OWLClass processCls = ogw.getOWLClassByIdentifier(processClsId);
buildNetwork(processCls, seedGenes);
}
public void addGenes(String processClsId, Collection<String> seedGenes) throws OWLOntologyCreationException {
OWLClass processCls = ogw.getOWLClassByIdentifier(processClsId);
addGenes(processCls, seedGenes);
}
/**
* @see seedGraph(String p, Set seed)
* @param processCls
* @throws OWLOntologyCreationException
*/
public void addGenes(OWLClass processCls) throws OWLOntologyCreationException {
addGenes(processCls, getGenes(processCls));
}
/**
* Create initial activation node set A for a process P and a set of seed genes
*
* for all g ∈ G<sup>seed</sup>, add a = <g,t> to A where f = argmax(p) { t : t ∈ T<sup>A</sup>, p=Prob( t | g) }
*
* @param processCls
* @param seedGenes
* @throws OWLOntologyCreationException
* @throws MathException
*/
public void addGenes(OWLClass processCls, Collection<String> seedGenes) throws OWLOntologyCreationException {
LOG.info("Adding seed genes, #=" + seedGenes.size());
// TODO - use only instance-level parts and regulators
// Set of all individuals that necessarily exists given P exist;
// (MFs and BPs)
Collection<OWLNamedIndividual> leafNodes =
new HashSet<OWLNamedIndividual>();
Set<OWLObjectPropertyExpression> props = getInvolvedInRelations();
// loop through all individuals generated so far; this includes the input process class P,
// plus other necessary individuals. For example, if P has_part some P2, and P2 has_part some F,
// then a prototypical instance of is also included
for (OWLNamedIndividual i : getGeneratedIndividuals()) {
boolean isOccurrent = false;
for (OWLClass c : getReasoner().getTypes(i, false).getFlattened()) {
if (c.getIRI().equals(OBOUpperVocabulary.GO_biological_process.getIRI())) {
isOccurrent = true;
break;
}
if (c.getIRI().equals(OBOUpperVocabulary.GO_molecular_function.getIRI())) {
isOccurrent = true;
break;
}
}
if (!isOccurrent) {
continue;
}
// note this has the potential to include individuals which p
// is part of - need to contain the scope here. For now, go liberal
//leafNodes.add(i);
boolean isInValidPath = false;
Set<OWLIndividual> path = getIndividualsInProperPath(i, props);
path.add(i); // reflexive
for (OWLIndividual m : path) {
if (m instanceof OWLNamedIndividual && getPrototypeClass((OWLNamedIndividual) m) != null) {
if (getPrototypeClass((OWLNamedIndividual) m).equals(processCls)) {
isInValidPath = true;
break;
}
}
}
LOG.info(" PPATH "+getIdLabelPair(i)+" "+path);
if (isInValidPath) {
LOG.info(" **VALID: "+getIdLabelPair(i));
leafNodes.add(i);
}
}
//contextId = ogw.getIdentifier(processCls); // TODO
ccp = 1.0; // cumulative
// generatedIndividuals = new HashSet<OWLNamedIndividual>();
// // note: here ancestors may be sub-parts
// for (OWLObject obj : ogw.getAncestorsReflexive(prototypeIndividualMap.get(processCls))) {
// LOG.info(" ANCI="+getIdLabelPair(obj));
// generatedIndividuals.add((OWLNamedIndividual) obj);
for (String g : seedGenes) {
LOG.info(" Seed gene="+getIdLabelPair(g));
// each gene, find it's most likely function F and most direct process class P.
// Note each gene can have multiple functions, but here we select one.
// In addition, a gene may be annotated to different parts of processCls;
// we aim to select one as a "join point"
Set<OWLClass> geneActivityTypes = getMostSpecificActivityTypes(g); // candidate functions
Set<OWLClass> geneInferredTypes = getInferredTypes(g); // all annotations
LOG.info(" num activity types = "+geneActivityTypes.size());
LOG.info(" num inferred types = "+geneInferredTypes.size());
// TODO - first find all other annotations for each gene
// and add these if relevant.
// E.g. in nodal pathway, Dand5 has 'sequestering of nodal from receptor via nodal binding'
Collection<OWLNamedIndividual> joinPoints =
new HashSet<OWLNamedIndividual>();
// g is also annotated to multiple other processes; find the more specific ones
Set<OWLClass> alternateProcesses = getMostSpecificProcessTypes(g);
LOG.info(" alt processes = "+alternateProcesses.size());
boolean isReset = false;
for (OWLClass alternateProcessCls : alternateProcesses) {
boolean isCandidate = false;
for (OWLGraphEdge edge : ogw.getOutgoingEdgesClosure(alternateProcessCls)) {
if (edge.getTarget().equals(processCls)) {
// alternateProcessCls is more specific
isCandidate = true;
for (OWLObjectSomeValuesFrom r : getExistentialRelationships(alternateProcessCls)) {
if (getReasoner().getSuperClasses(r.getFiller(), false).getFlattened().contains(processCls)) {
// should not cause a deepening
isCandidate = false;
}
}
}
}
if (isCandidate) {
if (getReasoner().getSuperClasses(alternateProcessCls, false).getFlattened().contains(processCls)) {
// skip
// todo - keep the information somehow that g is annotated to specific
// subtypes of c
}
else {
// experimenting with aggressive approach
OWLNamedIndividual newp = generateNecessaryIndividuals(alternateProcessCls);
if (!isReset) {
LOG.info("Resetting join points");
isReset = true;
joinPoints = new HashSet<OWLNamedIndividual>();
//generatedIndividuals = new HashSet<OWLNamedIndividual>();
}
LOG.info(" Using more specific annotation: "+getIdLabelPair(alternateProcessCls));
joinPoints.add(newp);
}
}
}
if (joinPoints.size() == 0) {
// TODO - use process instance
LOG.info("No more specific process annotations found; using leafNodes, #="+leafNodes.size());
joinPoints.addAll(leafNodes);
}
Double best = null;
Double cp = 1.0;
OWLClass bestActivityClass = null;
OWLClass bestParentClass = null;
OWLNamedIndividual bestParent = null;
for (OWLNamedIndividual joinPoint : joinPoints) {
//OWLClass joinPointClass = getPrototypeClass(joinPoint);
//this seemed to be producing redundant types:
Set<OWLClass> jpcs = getReasoner().getTypes(joinPoint, true).getFlattened();
LOG.info(" candidate join point="+getIdLabelPair(joinPoint)+" directTypes: "+jpcs);
Set<OWLClass> rd = new HashSet<OWLClass>(); // redundant
for (OWLClass jpc : jpcs) {
rd.addAll(getReasoner().getSuperClasses(jpc, false).getFlattened());
}
jpcs.removeAll(rd);
LOG.info(" Post redundancy filter: "+getIdLabelPair(joinPoint)+" directTypes: "+jpcs);
for (OWLClass joinPointClass : jpcs) {
LOG.info(" Testing JPC: "+getIdLabelPair(joinPointClass));
// a gene must have been annotated to some descendant of generatedCls to be considered.
if (true || geneInferredTypes.contains(joinPointClass)) {
for (OWLClass activityCls : geneActivityTypes ) {
// note that generatedCls may be a MF, and may be a subclass,
// which case this would be 1.0
Double pval;
try {
pval = calculatePairwiseEnrichment(activityCls, joinPointClass);
cp = this.calculateConditionalProbaility(joinPointClass, activityCls);
LOG.info(" enrichment of "+getIdLabelPair(activityCls)+" IN: "+getIdLabelPair(joinPointClass)+
" = "+pval);
// temp hack - e.g. frp1 ferric-chelate reductase in iron assimilation by reduction and transport
if (activityCls.equals(joinPointClass)) {
pval = 0.0;
}
if (best == null || pval < best) {
// TODO - pval == best
best = pval;
bestActivityClass = activityCls;
bestParentClass = joinPointClass;
bestParent = joinPoint;
}
} catch (MathException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
LOG.info(" Skpping: "+getIdLabelPair(joinPointClass)+" -- not in geneInferredTypes");
}
}
//LOG.info(" DONE testIndivid="+getIdLabelPair(gi));
}
OWLNamedIndividual ai = addActivity(bestActivityClass, g, best, cp);
ccp *= cp;
OWLObjectPropertyExpression relation = getObjectProperty(OBOUpperVocabulary.BFO_part_of);
LOG.info("Testing if "+getIdLabelPair(bestActivityClass) +
" is under/equiv to "+getIdLabelPair(bestParentClass) +
" for gene: "+g);
if (bestActivityClass != null) {
if (getReasoner().getSubClasses(bestActivityClass, false).getFlattened().contains(bestParentClass) ||
getReasoner().getEquivalentClasses(bestActivityClass).getEntities().contains(bestParentClass)) {
LOG.info("Merging "+bestParent+"
mergeInto(bestParent, ai);
}
else {
addEdge(ai, relation, bestParent);
}
}
}
collapseIndividuals();
}
private void addEdge(OWLNamedIndividual p, OWLObjectPropertyExpression rel, OWLNamedIndividual w) {
if (ogw.getAncestorsReflexive(p).contains(w)) {
LOG.info("ALREADY CONNECTED TO "+w);
return;
}
if (w != null) {
OWLAxiom owlObject =
getOWLDataFactory().getOWLObjectPropertyAssertionAxiom(
rel,
p,
w);
addAxiom(owlObject);
}
else {
LOG.warn("Parent of "+p+" is null");
}
}
private OWLNamedIndividual addActivity(OWLClass bestActivityClass, String gene, Double pval, Double cp) {
if (bestActivityClass == null) {
bestActivityClass = getOWLDataFactory().getOWLClass(OBOUpperVocabulary.GO_molecular_function.getIRI());
}
OWLNamedIndividual ai = this.generateNecessaryIndividuals(bestActivityClass);
//this.collapseIndividuals();
String label = getLabel(bestActivityClass);
OWLClass geneProductClass = null;
if (gene != null) {
geneProductClass = getOWLClassByIdentifier(gene);
}
else {
//geneProductClass = getOWLClass("PR:00000001");
}
if (geneProductClass != null) {
OWLClassExpression x = getOWLDataFactory().getOWLObjectSomeValuesFrom(
getObjectProperty(OBOUpperVocabulary.GOREL_enabled_by),
geneProductClass); // TODO <-- protein IRI should be here
addAxiom(getOWLDataFactory().getOWLClassAssertionAxiom(
x,
ai));
String geneLabel = getLabel(gene);
addOwlLabel(geneProductClass, geneLabel);
label = label + " enabled by " + geneLabel;
if (!activityByGene.containsKey(gene)) {
activityByGene.put(gene, new HashSet<OWLNamedIndividual>());
}
activityByGene.get(gene).add(ai);
}
label = label + " (pVal_uncorrected="+pval+", p(F|P)="+cp+")";
addOwlLabel(ai, label);
return ai;
}
/**
* Add default edges based on PPI network
*
* add ( a<sub>1</sub> , a<sub>2</sub> ) to E
* where ( g<sub>1</sub> , g<sub>2</sub> ) is in PPI, and
* a = (g, _) is in A
*
*/
public void connectGraph() {
// PPI Method
for (String p1 : proteinInteractionMap.keySet()) {
Set<OWLNamedIndividual> aset = lookupActivityByGene(p1);
if (aset == null || aset.size() == 0)
continue;
//LOG.info("P1="+getIdLabelPair(p1));
for (String p2 : proteinInteractionMap.get(p1)) {
//LOG.info(" P2="+getIdLabelPair(p2));
Set<OWLNamedIndividual> aset2 = lookupActivityByGene(p2);
if (aset2 != null) {
// assumption: if P1 and P2 interact then their activities also interact
for (OWLNamedIndividual a1 : aset) {
for (OWLNamedIndividual a2 : aset2) {
LOG.info(" PPI-based edge: "+a1+" => "+a2);
addEdge(a1, getObjectProperty(OBOUpperVocabulary.GOREL_provides_input_for), a2); // TODO
}
}
}
}
}
// Using ontology knowledge (e.g. connected_to relationships; has_input = has_output)
//for (OWLNamedIndividual a : activityNetwork.activitySet) {
// Annotation extension method
// TODO: e.g. PomBase SPCC645.07 rgf1 GO:0032319-regulation of Rho GTPase activity PMID:16324155 IGI PomBase:SPAC1F7.04 P RhoGEF for Rho1, Rgf1 protein taxon:4896 20100429 PomBase
// in: =GO:0051666 ! actin cortical patch localization
}
private Set<OWLNamedIndividual> lookupActivityByGene(String g) {
if (activityByGene.containsKey(g))
return activityByGene.get(g);
else
return null;
}
private void combineMultipleEnablers() {
OWLObjectPropertyExpression enabledBy = this.getObjectProperty(OBOUpperVocabulary.GOREL_enabled_by);
for (OWLNamedIndividual i : getAboxOntology().getIndividualsInSignature(false)) {
Set<OWLAxiom> rmAxioms = new HashSet<OWLAxiom>();
Set<OWLClassExpression> xs = new HashSet<OWLClassExpression>();
for (OWLAxiom ax : getAboxOntology().getAxioms(i)) {
if (ax instanceof OWLClassAssertionAxiom) {
//LOG.info("TESTING:"+ax);
OWLClassAssertionAxiom caa = (OWLClassAssertionAxiom)ax;
if (caa.getClassExpression().getObjectPropertiesInSignature().contains(enabledBy)) {
rmAxioms.add(ax);
if (caa.getClassExpression() instanceof OWLObjectSomeValuesFrom) {
xs.add(((OWLObjectSomeValuesFrom)caa.getClassExpression()).getFiller());
}
else {
LOG.warn("Hmmmm"+caa);
//xs.add(caa.getClassExpression());
}
}
}
}
if (xs.size() > 1) {
LOG.info("Concatenating enables for "+getIdLabelPair(i));
getOWLOntologyManager().removeAxioms(this.getAboxOntology(), rmAxioms);
addAxiom(
getOWLDataFactory().getOWLClassAssertionAxiom(
getOWLDataFactory().getOWLObjectSomeValuesFrom(
enabledBy,
getOWLDataFactory().getOWLObjectUnionOf(xs)
),
i));
}
}
}
/**
* Reroute all has_parts to part_ofs
*
*/
public void normalizeDirections() {
normalizeDirections(getObjectProperty(OBOUpperVocabulary.BFO_part_of));
normalizeDirections(getObjectProperty(OBOUpperVocabulary.BFO_occurs_in));
normalizeDirections(getObjectProperty(OBOUpperVocabulary.RO_starts));
normalizeDirections(getObjectProperty(OBOUpperVocabulary.RO_ends));
}
// Experimental
public Map<OWLClass, Double> fetchScoredCandidateProcesses(OWLClass disease, Integer populationClassSize) {
OWLNamedIndividual ind = this.generateNecessaryIndividuals(disease);
Set<OWLClass> phenotypes = new HashSet<OWLClass>();
for (OWLNamedIndividual j : getGeneratedIndividuals()) {
phenotypes.addAll(getReasoner().getTypes(j, true).getFlattened());
}
OWLClass CELLULAR_PROCESS = getOWLDataFactory().getOWLClass(OBOUpperVocabulary.GO_cellular_process.getIRI());
Map<OWLClass, Double> smap = new HashMap<OWLClass, Double>();
for (OWLClass gc : getReasoner().getSubClasses(CELLULAR_PROCESS, false).getFlattened()) {
double cumLogScore = 0.0;
int n=0;
for (OWLClass pc : phenotypes) {
try {
Double pval = calculatePairwiseEnrichment(pc, gc, populationClassSize);
double logScore = -Math.log(pval)/Math.log(2);
//LOG.info(" PSCORE: "+getIdLabelPair(gc)+ " = "+logScore+" for: "+getIdLabelPair(pc)+ " pval="+pval);
if (pval >= 0.0) {
cumLogScore += logScore;
n++;
}
} catch (MathException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (n>0) {
smap.put(gc, cumLogScore);
LOG.info("SCORE: "+getIdLabelPair(gc)+ " = "+cumLogScore);
}
else {
//smap.remove(key)
}
}
Map<OWLClass, Double> osmap = sortByValue(smap);
return osmap;
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
List<Map.Entry<K, V>> list =
new LinkedList<Map.Entry<K, V>>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) {
return (o1.getValue()).compareTo( o2.getValue() );
}
} );
Collections.reverse(list);
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
// Calculation of gene-class relationships and probabilities
public Double calculatePairwiseEnrichment(OWLClass sampleSetClass, OWLClass enrichedClass) throws MathException {
return calculatePairwiseEnrichment(sampleSetClass, enrichedClass, populationGeneSet.size());
}
public Double calculatePairwiseEnrichment(
OWLClass sampleSetClass, OWLClass enrichedClass, int populationClassSize) throws MathException {
// LOG.info("Hyper :"+populationClass
// +" "+sampleSetClass+" "+enrichedClass);
int sampleSetClassSize = getGenes(sampleSetClass).size();
int enrichedClassSize = getGenes(enrichedClass).size();
// LOG.info("Hyper :"+populationClassSize
// +" "+sampleSetClassSize+" "+enrichedClassSize);
HypergeometricDistributionImpl hg = new HypergeometricDistributionImpl(
populationClassSize, sampleSetClassSize, enrichedClassSize);
/*
* LOG.info("popsize="+getNumElementsForAttribute(populationClass));
* LOG.info("sampleSetSize="+getNumElementsForAttribute(sampleSetClass));
* LOG.info("enrichedClass="+getNumElementsForAttribute(enrichedClass));
*/
Set<String> eiSet = getGenes(sampleSetClass);
eiSet.retainAll(getGenes(enrichedClass));
// LOG.info("both="+eiSet.size());
double p = hg.cumulativeProbability(eiSet.size(),
Math.min(sampleSetClassSize, enrichedClassSize));
//double pCorrected = p * getCorrectionFactor(populationClass);
return p;
}
/**
*
* Pr( F | P ) = Pr(F,P) / Pr(P)
*
*/
public Double calculateConditionalProbaility(OWLClass wholeCls, OWLClass partCls) {
Set<String> wgs = getGenes(wholeCls);
Set<String> cgs = getGenes(partCls);
cgs.retainAll(wgs);
double n = getNumberOfGenes();
Double pr = (cgs.size() / n) / ( wgs.size() / n);
return pr;
}
/**
* Get all activity types a gene enables (i.e. direct MF annotations)
*
* always returns a fresh set
*
* @param g
* @return { t : t ∈ T<sup>A</sup>, g x t ∈ Enables }
*/
public Set<OWLClass> getActivityTypes(String g) {
HashSet<OWLClass> cset = new HashSet<OWLClass>(clsByGeneMap.get(g));
cset.retainAll(activityClassSet);
return cset;
}
public Set<OWLClass> getMostSpecificActivityTypes(String g) {
Set<OWLClass> cset = getActivityTypes(g);
LOG.info("# activity types for "+g+" = "+cset.size());
removeRedundantOrHelper(cset, getInvolvedInRelationsAsPEs());
LOG.info("# post-NR activity types for "+g+" = "+cset.size());
return cset;
}
public Set<OWLClass> getMostSpecificProcessTypes(String g) {
Set<OWLClass> cset = getProcessTypes(g);
removeRedundantOrHelper(cset, getInvolvedInRelationsAsPEs());
return cset;
}
public Set<OWLClass> getProcessTypes(String g) {
HashSet<OWLClass> cset = new HashSet<OWLClass>(clsByGeneMap.get(g));
cset.retainAll(processClassSet);
return cset;
}
public Set<OWLClass> getInferredTypes(String g) {
HashSet<OWLClass> cset = new HashSet<OWLClass>();
Set<OWLPropertyExpression> rels =
new HashSet<OWLPropertyExpression>(getInvolvedInRelations());
for (OWLClass c : clsByGeneMap.get(g)) {
for (OWLObject a : ogw.getAncestorsReflexive(c, rels)) { // TODO-rel
if (a instanceof OWLClass && !isQueryClass((OWLClass) a)) {
cset.add((OWLClass) a);
}
}
}
return cset;
}
public Set<OWLObjectSomeValuesFrom> getInferredRelationshipsForGene(String g) {
Set<OWLObjectSomeValuesFrom> results = new HashSet<OWLObjectSomeValuesFrom>();
HashSet<OWLClass> cset = new HashSet<OWLClass>(clsByGeneMap.get(g));
for (OWLClass c : cset) {
results.addAll(getExistentialRelationships(c));
}
return results;
}
private void removeRedundantOrHelper(Set<OWLClass> cset, Set<OWLPropertyExpression> props) {
Set<OWLClass> allAncs = new HashSet<OWLClass>();
for (OWLClass c : cset) {
if (isQueryClass(c)) {
allAncs.add(c);
continue;
}
Set<OWLObject> ancClsSet = ogw.getAncestors(c, props);
for (OWLObject obj : ancClsSet) {
if (obj instanceof OWLClass) {
// named ancestors only
allAncs.add((OWLClass) obj);
}
}
}
cset.removeAll(allAncs);
}
/**
* Gets all genes annotated to cls or descendant via involved-in relations
* @param t
* @return { g : g x t ∈ InferredInvolvedIn }
*/
public Set<String> getGenes(OWLClass wholeCls) {
if (!geneByInferredClsMap.containsKey(wholeCls)) {
//LOG.info("Nothing known about "+wholeCls);
return new HashSet<String>();
}
return new HashSet<String>(geneByInferredClsMap.get(wholeCls));
}
/**
* @return |G|
*/
public int getNumberOfGenes() {
return populationGeneSet.size();
}
// adds an (external) protein-protein interaction
private void addPPI(String a, String b) {
if (!proteinInteractionMap.containsKey(a))
proteinInteractionMap.put(a, new HashSet<String>());
proteinInteractionMap.get(a).add(b);
}
/**
* @param id
* @return label for any class or entity in the graph
*/
public String getLabel(Object k) {
if (k == null)
return "Null";
if (labelMap.containsKey(k))
return this.labelMap.get(k);
return k.toString();
}
public String getIdLabelPair(Object k) {
if (k == null)
return "Null";
if (labelMap.containsKey(k))
return k+" '"+this.labelMap.get(k)+"'";
return k.toString();
}
public Map<String,Object> getGraphStatistics() {
Map<String,Object> sm = new HashMap<String,Object>();
//sm.put("activity_node_count", activityNetwork.activitySet.size());
//sm.put("activity_edge_count", activityNetwork.activityEdgeSet.size());
//sm.put("process_count", processSet.size());
return sm;
}
private IRI getIRI(String id) {
return ogw.getIRIByIdentifier(id);
}
private OWLNamedIndividual getIndividual(String id) {
return getOWLDataFactory().getOWLNamedIndividual(getIRI(id));
}
private OWLClass getOWLClassByIdentifier(String id) {
return getOWLDataFactory().getOWLClass(ogw.getIRIByIdentifier(id));
}
private OWLClass getOWLClass(OBOUpperVocabulary v) {
return getOWLDataFactory().getOWLClass(v.getIRI());
}
private Set<OWLObjectPropertyExpression> getInvolvedInRelations() {
Set<OWLObjectPropertyExpression> rels = new HashSet<OWLObjectPropertyExpression>();
rels.add(getObjectProperty(OBOUpperVocabulary.BFO_part_of));
rels.add(getObjectProperty(OBOUpperVocabulary.RO_regulates));
// these should be inferred in the future:
rels.add(getObjectProperty(OBOUpperVocabulary.RO_negatively_regulates));
rels.add(getObjectProperty(OBOUpperVocabulary.RO_positively_regulates));
rels.add(getObjectProperty(OBOUpperVocabulary.RO_starts)); // sub of part_of
rels.add(getObjectProperty(OBOUpperVocabulary.BFO_occurs_in));
return rels;
}
private Set<OWLPropertyExpression> getInvolvedInRelationsAsPEs() {
return new HashSet<OWLPropertyExpression>(getInvolvedInRelations());
}
private OWLObjectPropertyExpression getObjectProperty(
OBOUpperVocabulary vocab) {
// TODO Auto-generated method stub
return getObjectProperty(vocab.getIRI());
}
private OWLObjectPropertyExpression getObjectProperty(
IRI iri) {
// TODO Auto-generated method stub
return getOWLDataFactory().getOWLObjectProperty(iri);
}
private void addOwlData(OWLObject subj, OWLAnnotationProperty p, String val) {
OWLLiteral lit = getOWLDataFactory().getOWLLiteral(val);
addAxiom(getOWLDataFactory().getOWLAnnotationAssertionAxiom(
p,
((OWLNamedObject) subj).getIRI(),
lit));
}
private void addOwlLabel(OWLObject owlObject, String val) {
addOwlData(owlObject,
getOWLDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_LABEL.getIRI()),
val);
labelMap.put(owlObject, val);
}
}
|
package org.dspace.administer;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.PosixParser;
import org.dspace.content.Community;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.authorize.AuthorizeException;
import org.dspace.handle.HandleManager;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
public class CommunityFiliator
{
public static void main(String [] argv)
throws Exception
{
// create an options object and populate it
CommandLineParser parser = new PosixParser();
Options options = new Options();
options.addOption( "s", "set", false, "set a parent/child relationship");
options.addOption( "r", "remove", false, "remove a parent/child relationship");
options.addOption( "p", "parent", true, "parent community (handle or database ID)");
options.addOption( "c", "child", true, "child community (handle or databaseID)");
options.addOption( "h", "help", false, "help");
CommandLine line = parser.parse( options, argv );
String command = null; // set or remove
String parentID = null;
String childID = null;
if( line.hasOption('h') )
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp( "CommunityFiliator\n", options );
System.out.println("\nestablish a relationship: CommunityFiliator -s -p parentID -c childID");
System.out.println("remove a relationship: CommunityFiliator -r -p parentID -c childID");
System.exit(0);
}
if( line.hasOption( 's' ) ) { command = "set"; }
if( line.hasOption( 'r' ) ) { command = "remove"; }
if( line.hasOption( 'p' ) ) // parent
{
parentID = line.getOptionValue( 'p' );
}
if( line.hasOption( 'c' ) ) // child
{
childID = line.getOptionValue( 'c' );
}
// now validate
// must have a command set
if( command == null )
{
System.out.println("Error - must run with either set or remove (run with -h flag for details)");
System.exit(1);
}
if( command.equals("set") || command.equals("remove") )
{
if( parentID == null )
{
System.out.println("Error - a parentID must be specified (run with -h flag for details)");
System.exit(1);
}
if( childID == null )
{
System.out.println("Error - a childID must be specified (run with -h flag for details)");
System.exit(1);
}
}
CommunityFiliator filiator = new CommunityFiliator();
Context c = new Context();
// ve are superuser!
c.setIgnoreAuthorization(true);
try
{
// validate and resolve the parent and child IDs into commmunities
Community parent = filiator.resolveCommunity( c, parentID );
Community child = filiator.resolveCommunity( c, childID );
if( parent == null )
{
System.out.println( "Error, parent community cannot be found: " + parentID );
System.exit(1);
}
if( child == null )
{
System.out.println( "Error, child community cannot be found: " + childID );
System.exit(1);
}
if (command.equals( "set" ))
{
filiator.filiate(c, parent, child);
}
else
{
filiator.defiliate(c, parent, child);
}
}
catch ( SQLException sqlE )
{
System.out.println( "Error - SQL exception: " + sqlE.toString() );
}
catch ( AuthorizeException authE )
{
System.out.println( "Error - Authorize exception: " + authE.toString() );
}
catch ( IOException ioE )
{
System.out.println( "Error - IO exception: " + ioE.toString() );
}
}
public void filiate( Context c, Community parent, Community child )
throws SQLException, AuthorizeException, IOException
{
// check that a valid filiation would be established
// first test - proposed child must currently be an orphan (i.e. top-level)
Community childDad = child.getParentCommunity();
if ( childDad != null )
{
System.out.println( "Error, child community: " + child.getID() + " already a child of: " + childDad.getID() );
System.exit(1);
}
// second test - circularity: parent's parents can't include proposed child
Community[] parentDads = parent.getAllParents();
for ( int i = 0; i < parentDads.length; i++ )
{
if ( parentDads[i].getID() == child.getID() )
{
System.out.println( "Error, circular parentage - child is parent of parent" );
System.exit(1);
}
}
// everthing's OK
parent.addSubcommunity( child );
// complete the pending transaction
c.complete();
System.out.println( "Filiation complete. Community: '" + parent.getID() + "' is parent of community: '" + child.getID() + "'" );
}
public void defiliate( Context c, Community parent, Community child )
throws SQLException, AuthorizeException, IOException
{
// verify that child is indeed a child of parent
Community[] parentKids = parent.getSubcommunities();
boolean isChild = false;
for ( int i = 0; i < parentKids.length; i++ )
{
if ( parentKids[i].getID() == child.getID() )
{
isChild = true;
break;
}
}
if ( ! isChild )
{
System.out.println( "Error, child community not a child of parent community" );
System.exit(1);
}
// OK remove the mappings - but leave the community, which will become top-level
DatabaseManager.updateQuery(c,
"DELETE FROM community2community WHERE parent_comm_id=" +
parent.getID() + " AND child_comm_id=" + child.getID() );
// complete the pending transaction
c.complete();
System.out.println( "Defiliation complete. Community: '" + child.getID() + "' is no longer a child of community: '" + parent.getID() + "'" );
}
private Community resolveCommunity( Context c, String communityID)
throws SQLException
{
Community community = null;
if ( communityID.indexOf('/') != -1 )
{
// has a / must be a handle
community = (Community)HandleManager.resolveToObject( c, communityID );
// ensure it's a community
if( (community == null) || (community.getType() != Constants.COMMUNITY) )
{
community = null;
}
}
else
{
community = Community.find( c, Integer.parseInt( communityID ) );
}
return community;
}
}
|
package fitnesse.slim.converters;
import java.util.HashMap;
import java.util.Map;
import fitnesse.html.HtmlTag;
import fitnesse.slim.Converter;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.CompositeTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
public class MapConverter implements Converter<Map> {
private static final String[] specialHtmlChars = new String[] { "&", "<", ">" };
private static final String[] specialHtmlEscapes = new String[] { "&", "<", ">" };
private NodeList nodes;
private NodeList tables;
@Override
public String toString(Map hash) {
HtmlTag table = createTag(hash, 0);
return table.html().trim();
}
protected HtmlTag createTag(Map<?, ?> hash, int depth) {
// Use HtmlTag, same as we do for fitnesse.wikitext.parser.HashTable.
HtmlTag table = new HtmlTag("table");
table.addAttribute("class", "hash_table");
for (Map.Entry<?, ?> entry : hash.entrySet()) {
HtmlTag row = new HtmlTag("tr");
row.addAttribute("class", "hash_row");
table.add(row);
String key = entry.getKey().toString();
HtmlTag keyCell = new HtmlTag("td", key.trim());
keyCell.addAttribute("class", "hash_key");
row.add(keyCell);
HtmlTag valueCell = new HtmlTag("td");
addValueContent(valueCell, entry.getValue());
valueCell.addAttribute("class", "hash_value");
row.add(valueCell);
}
return table;
}
protected void addValueContent(HtmlTag valueCell, Object entryValue) {
if (entryValue != null) {
Converter converter = ConverterRegistry.getConverterForClass(entryValue.getClass());
String convertedValue;
if (converter == null) {
convertedValue = entryValue.toString();
} else {
convertedValue = converter.toString(entryValue);
}
valueCell.add(convertedValue.trim());
} else {
valueCell.add("null");
}
}
@Override
public Map<String, String> fromString(String possibleTable) {
Map<String, String> map = new HashMap<String, String>();
if (tableIsValid(possibleTable))
extractRowsIntoMap(map, tables);
return map;
}
private boolean tableIsValid(String possibleTable) {
if (isValidHtml(possibleTable)) {
return hasOneTable();
} else {
return false;
}
}
private boolean hasOneTable() {
TagNameFilter tableFilter = new TagNameFilter("table");
tables = nodes.extractAllNodesThatMatch(tableFilter);
return tables.size() == 1;
}
private boolean isValidHtml(String possibleTable) {
nodes = parseHtml(possibleTable);
return nodes != null;
}
private void extractRowsIntoMap(Map<String, String> map, NodeList tables) {
extractRows(map, getRows(tables));
}
private void extractRows(Map<String, String> map, NodeList rows) {
for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
extractRow(map, rows, rowIndex);
}
}
private void extractRow(Map<String, String> map, NodeList rows, int rowIndex) {
Node row = rows.elementAt(rowIndex);
if (row != null)
extractColumns(map, row);
}
private void extractColumns(Map<String, String> map, Node row) {
TagNameFilter tdFilter = new TagNameFilter("td");
if (row.getChildren() != null) {
NodeList cols = row.getChildren().extractAllNodesThatMatch(tdFilter);
if (cols.size() == 2)
addColsToMap(map, cols);
}
}
private void addColsToMap(Map<String, String> map, NodeList cols) {
String key = getText(cols.elementAt(0));
String value = getText(cols.elementAt(1));
map.put(key, value);
}
private NodeList getRows(NodeList tables) {
TagNameFilter trFilter = new TagNameFilter("tr");
Node table = tables.elementAt(0);
if (table.getChildren() != null)
return table.getChildren().extractAllNodesThatMatch(trFilter);
return new NodeList();
}
private String getText(Node compositeNode) {
return ((CompositeTag) compositeNode).getChildrenHTML();
}
private NodeList parseHtml(String possibleTable) {
try {
Parser parser = new Parser(possibleTable);
return parser.parse(null);
} catch (ParserException e) {
return null;
}
}
public String escapeHTML(String value) {
return replaceStrings(value, specialHtmlChars, specialHtmlEscapes);
}
private String replaceStrings(String value, String[] originalStrings, String[] replacementStrings) {
String result = value;
for (int i = 0; i < originalStrings.length; i++)
if (result.contains(originalStrings[i]))
result = result.replace(originalStrings[i], replacementStrings[i]);
return result;
}
}
|
package edu.cmu.sphinx.frontend;
import edu.cmu.sphinx.util.SphinxProperties;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* A StreamAudioSource converts data from an InputStream into
* Audio(s). One would obtain the Audios using
* the <code>read()</code> method.
*
* The size of each Audio returned is specified by:
* <pre>
* edu.cmu.sphinx.frontend.bytesPerAudio
* </pre>
*
* @see BatchFileAudioSource
*/
public class StreamAudioSource extends DataProcessor implements AudioSource {
private InputStream audioStream;
private Utterance currentUtterance = null;
private int frameSizeInBytes;
private boolean keepAudioReference;
private boolean streamEndReached = false;
private boolean utteranceEndSent = false;
private boolean utteranceStarted = false;
/**
* Constructs a StreamAudioSource with the given InputStream.
*
* @param name the name of this StreamAudioSource
* @param context the context of this StreamAudioSource
* @param audioStream the InputStream where audio data comes from
* @param streamName the name of the InputStream
*/
public StreamAudioSource(String name, String context,
InputStream audioStream, String streamName) {
super(name, context);
initSphinxProperties();
setInputStream(audioStream, streamName);
}
/**
* Reads the parameters needed from the static SphinxProperties object.
*/
private void initSphinxProperties() {
keepAudioReference = getSphinxProperties().getBoolean
(FrontEnd.PROP_KEEP_AUDIO_REFERENCE, true);
frameSizeInBytes = getSphinxProperties().getInt
(FrontEnd.PROP_BYTES_PER_AUDIO_FRAME, 4000);
if (frameSizeInBytes % 2 == 1) {
frameSizeInBytes++;
}
}
/**
* Sets the InputStream from which this StreamAudioSource reads.
*
* @param inputStream the InputStream from which audio data comes
* @param streamName the name of the InputStream
*/
public void setInputStream(InputStream inputStream, String streamName) {
this.audioStream = inputStream;
streamEndReached = false;
utteranceEndSent = false;
utteranceStarted = false;
if (keepAudioReference) {
currentUtterance = new Utterance(streamName, getContext());
} else {
currentUtterance = null;
}
}
/**
* Reads and returns the next Audio from the InputStream of
* StreamAudioSource, return null if no data is read and end of file
* is reached.
*
* @return the next Audio or <code>null</code> if none is
* available
*
* @throws java.io.IOException
*/
public Audio getAudio() throws IOException {
getTimer().start();
Audio output = null;
if (streamEndReached) {
if (!utteranceEndSent) {
output = new Audio(Signal.UTTERANCE_END);
utteranceEndSent = true;
}
} else {
if (!utteranceStarted) {
utteranceStarted = true;
output = new Audio(Signal.UTTERANCE_START);
} else {
if (audioStream != null) {
output = readNextFrame();
if (output == null) {
if (!utteranceEndSent) {
output = new Audio(Signal.UTTERANCE_END);
utteranceEndSent = true;
}
}
}
}
}
getTimer().stop();
return output;
}
/**
* Returns the next Audio from the input stream, or null if
* there is none available
*
* @return a Audio or null
*
* @throws java.io.IOException
*/
private Audio readNextFrame() throws IOException {
// read one frame's worth of bytes
int read = 0;
int totalRead = 0;
final int bytesToRead = frameSizeInBytes;
byte[] samplesBuffer = new byte[frameSizeInBytes];
do {
read = audioStream.read
(samplesBuffer, totalRead, bytesToRead - totalRead);
if (read > 0) {
totalRead += read;
}
} while (read != -1 && totalRead < bytesToRead);
if (totalRead <= 0) {
closeAudioStream();
return null;
}
// shrink incomplete frames
if (totalRead < bytesToRead) {
totalRead = (totalRead % 2 == 0) ? totalRead + 2 : totalRead + 3;
byte[] shrinkedBuffer = new byte[totalRead];
System.arraycopy(samplesBuffer, 0, shrinkedBuffer, 0, totalRead);
samplesBuffer = shrinkedBuffer;
closeAudioStream();
}
// turn it into an Audio
double[] doubleAudio =
Util.byteToDoubleArray(samplesBuffer, 0, totalRead);
Audio audio = null;
if (keepAudioReference) {
currentUtterance.add(samplesBuffer);
audio = new Audio(doubleAudio, currentUtterance);
} else {
audio = new Audio(doubleAudio);
}
if (getDump()) {
System.out.println("FRAME_SOURCE " + audio.toString());
}
return audio;
}
private void closeAudioStream() throws IOException {
streamEndReached = true;
if (audioStream != null) {
audioStream.close();
}
}
}
|
package nz.mega.sdk;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLConnection;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import mega.privacy.android.app.utils.Util;
public class AndroidGfxProcessor extends MegaGfxProcessor {
Rect size;
int orientation;
String srcPath;
Bitmap bitmap;
byte[] bitmapData;
static Context context = null;
protected AndroidGfxProcessor() {
if (context == null) {
try {
context = (Context) Class.forName("android.app.AppGlobals")
.getMethod("getInitialApplication")
.invoke(null, (Object[]) null);
} catch (Exception e) {
}
}
}
public static boolean isVideoFile(String path) {
try {
String mimeType = URLConnection.guessContentTypeFromName(path);
return mimeType != null && mimeType.startsWith("video");
}
catch(Exception e){
return false;
}
}
public static Rect getImageDimensions(String path, int orientation) {
Rect rect = new Rect();
if(isVideoFile(path)){
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(path);
int width;
int height;
int interchangeOrientation = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
if (interchangeOrientation == 90 || interchangeOrientation == 270) {
width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
}
else {
width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
}
retriever.release();
log("getImageDimensions width: "+width+" height: "+height+" orientation: "+interchangeOrientation);
rect.right = width;
rect.bottom = height;
} catch (Exception e) {
}
}
else{
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(path), null, options);
if ((options.outWidth > 0) && (options.outHeight > 0)) {
if ((orientation < 5) || (orientation > 8)) {
rect.right = options.outWidth;
rect.bottom = options.outHeight;
} else {
rect.bottom = options.outWidth;
rect.right = options.outHeight;
}
}
} catch (Exception e) {
}
}
return rect;
}
public boolean readBitmap(String path) {
if(isVideoFile(path)){
srcPath = path;
size = getImageDimensions(srcPath, orientation);
return (size.right != 0) && (size.bottom != 0);
}
else{
srcPath = path;
orientation = getExifOrientation(path);
size = getImageDimensions(srcPath, orientation);
return (size.right != 0) && (size.bottom != 0);
}
}
public int getWidth() {
return size.right;
}
public int getHeight() {
return size.bottom;
}
static public Bitmap getBitmap(String path, Rect rect, int orientation, int w, int h) {
int width;
int height;
if (isVideoFile(path)) {
Bitmap bmThumbnail = null;
try{
bmThumbnail = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
if(context != null && bmThumbnail == null) {
String SELECTION = MediaStore.MediaColumns.DATA + "=?";
String[] PROJECTION = {BaseColumns._ID};
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] selectionArgs = {path};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(uri, PROJECTION, SELECTION, selectionArgs, null);
if (cursor.moveToFirst()) {
long videoId = cursor.getLong(0);
bmThumbnail = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND, null);
}
cursor.close();
}
}
catch(Exception e){}
if(bmThumbnail==null){
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try{
retriever.setDataSource(path);
bmThumbnail = retriever.getFrameAtTime();
}
catch(Exception e1){
}
finally {
try {
retriever.release();
} catch (Exception ex) {}
}
}
if(bmThumbnail==null){
try{
bmThumbnail = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MINI_KIND);
if(context != null && bmThumbnail == null) {
String SELECTION = MediaStore.MediaColumns.DATA + "=?";
String[] PROJECTION = {BaseColumns._ID};
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] selectionArgs = {path};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(uri, PROJECTION, SELECTION, selectionArgs, null);
if (cursor.moveToFirst()) {
long videoId = cursor.getLong(0);
bmThumbnail = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId, MediaStore.Video.Thumbnails.MINI_KIND, null);
}
cursor.close();
}
}
catch (Exception e2){}
}
try {
if (bmThumbnail != null) {
return Bitmap.createScaledBitmap(bmThumbnail, w, h, true);
}
}catch (Exception e){
}
}
else{
if ((orientation < 5) || (orientation > 8)) {
width = rect.right;
height = rect.bottom;
} else {
width = rect.bottom;
height = rect.right;
}
try {
int scale = 1;
while (width / scale / 2 >= w && height / scale / 2 >= h)
scale *= 2;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = scale;
Bitmap tmp = BitmapFactory.decodeStream(new FileInputStream(path), null, options);
tmp = fixExifOrientation(tmp, orientation);
return Bitmap.createScaledBitmap(tmp, w, h, true);
} catch (Exception e) {
}
}
return null;
}
public static int getExifOrientation(String srcPath) {
int orientation = ExifInterface.ORIENTATION_UNDEFINED;
int i = 0;
while ((i < 5) && (orientation == ExifInterface.ORIENTATION_UNDEFINED)) {
try {
ExifInterface exif = new ExifInterface(srcPath);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, orientation);
} catch (IOException e) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {}
}
i++;
}
return orientation;
}
/*
* Change image orientation based on EXIF image data
*/
public static Bitmap fixExifOrientation(Bitmap bitmap, int orientation) {
if (bitmap == null)
return null;
if ((orientation < 2) || (orientation > 8)) {
// No changes required or invalid orientation
return bitmap;
}
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_TRANSPOSE:
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
if ((orientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL)
|| (orientation == ExifInterface.ORIENTATION_FLIP_VERTICAL))
matrix.preScale(-1, 1);
else if ((orientation == ExifInterface.ORIENTATION_TRANSPOSE)
|| (orientation == ExifInterface.ORIENTATION_TRANSVERSE))
matrix.preScale(1, -1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
public static Bitmap extractRect(Bitmap bitmap, int px, int py, int rw, int rh) {
if (bitmap == null)
return null;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
if ((px != 0) || (py != 0) || (rw != w) || (rh != h)) {
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap scaled = Bitmap.createBitmap(rw, rh, conf);
Canvas canvas = new Canvas(scaled);
canvas.drawBitmap(bitmap, new Rect(px, py, px + rw, py + rh), new Rect(0, 0, rw, rh), null);
bitmap = scaled;
}
return bitmap;
}
public static boolean saveBitmap(Bitmap bitmap, File file) {
if (bitmap == null)
return false;
FileOutputStream stream;
try {
stream = new FileOutputStream(file);
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream))
return false;
stream.close();
return true;
} catch (Exception e) {
}
return false;
}
public int getBitmapDataSize(int w, int h, int px, int py, int rw, int rh) {
if (bitmap == null)
bitmap = getBitmap(srcPath, size, orientation, w, h);
else
bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
bitmap = extractRect(bitmap, px, py, rw, rh);
if (bitmap == null)
return 0;
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream))
return 0;
bitmapData = stream.toByteArray();
return bitmapData.length;
} catch (Exception e) {
}
return 0;
}
public boolean getBitmapData(byte[] buffer) {
try {
System.arraycopy(bitmapData, 0, buffer, 0, bitmapData.length);
return true;
} catch (Exception e) {
}
return false;
}
public void freeBitmap() {
bitmap = null;
bitmapData = null;
size = null;
srcPath = null;
orientation = 0;
}
public static void log(String log) {
Util.log("AndroidGfxProcessor", log);
}
}
|
package edu.umd.cs.findbugs;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
/**
* Version number and release date information.
*/
public class Version {
/**
* Major version number.
*/
public static final int MAJOR = 1;
/**
* Minor version number.
*/
public static final int MINOR = 3;
/**
* Patch level.
*/
public static final int PATCHLEVEL = 10;
/**
* Development version or release candidate?
*/
public static final boolean IS_DEVELOPMENT = true;
/**
* Release candidate number.
* "0" indicates that the version is not a release candidate.
*/
public static final int RELEASE_CANDIDATE = 0;
/**
* Release date.
*/
public static final String COMPUTED_DATE;
public static final String DATE;
private static final String COMPUTED_ECLIPSE_DATE;
static {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss z, dd MMMM, yyyy");
SimpleDateFormat eclipseDateFormat = new SimpleDateFormat("yyyyMMdd");
COMPUTED_DATE = dateFormat.format(new Date());
COMPUTED_ECLIPSE_DATE = eclipseDateFormat.format(new Date()) ;
}
/**
* Preview release number.
* "0" indicates that the version is not a preview release.
*/
public static final int PREVIEW = 0;
private static final String RELEASE_SUFFIX_WORD =
(RELEASE_CANDIDATE > 0
? "rc" + RELEASE_CANDIDATE
: (PREVIEW > 0 ? "preview" + PREVIEW : "dev-" + COMPUTED_ECLIPSE_DATE));
public static final String RELEASE_BASE = MAJOR + "." + MINOR + "." + PATCHLEVEL ;
/**
* Release version string.
*/
public static final String COMPUTED_RELEASE =
RELEASE_BASE + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : "");
/**
* Release version string.
*/
public static final String RELEASE;
/**
* Version of Eclipse plugin.
*/
public static final String COMPUTED_ECLIPSE_UI_VERSION =
RELEASE_BASE + "." + COMPUTED_ECLIPSE_DATE;
static {
InputStream in = null;
String release, date;
try {
Properties versionProperties = new Properties();
in = Version.class.getResourceAsStream("version.properties");
if(in != null) {
versionProperties.load(in);
}
release = (String) versionProperties.get("release.number");
date = (String) versionProperties.get("release.date");
if (release == null)
release = COMPUTED_RELEASE;
if (date == null)
date = COMPUTED_DATE;
} catch (RuntimeException e) {
release = COMPUTED_RELEASE;
date = COMPUTED_DATE;
} catch (IOException e) {
release = COMPUTED_RELEASE;
date = COMPUTED_DATE;
} finally {
try {
if (in != null) in.close();
} catch (IOException e) {
assert true; // nothing to do here
}
}
RELEASE = release;
DATE = date;
}
/**
* FindBugs website.
*/
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/**
* Downloads website.
*/
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
/**
* Support email.
*/
public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html";
public static void main(String[] argv) {
if (argv.length != 1)
usage();
String arg = argv[0];
if (!IS_DEVELOPMENT && RELEASE_CANDIDATE != 0) {
throw new IllegalStateException("Non developmental version, but is release candidate " + RELEASE_CANDIDATE);
}
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.base=" + RELEASE_BASE);
System.out.println("release.number=" + COMPUTED_RELEASE);
System.out.println("release.date=" + COMPUTED_DATE);
System.out.println("eclipse.ui.version=" + COMPUTED_ECLIPSE_UI_VERSION);
System.out.println("findbugs.website=" + WEBSITE);
System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
} else {
usage();
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() +
" (-release|-date|-props)");
}
}
// vim:ts=4
|
package io.codebakery.cellinfo;
import java.util.List;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.content.Context;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
public class CellInfo extends CordovaPlugin {
public static final String TAG = "CellInfo";
private class PrimaryCellPhoneStateListener extends PhoneStateListener {
private CallbackContext callbackContext;
private CordovaInterface cordova;
public PrimaryCellPhoneStateListener(CordovaInterface cordova, CallbackContext callbackContext) {
super();
this.cordova = cordova;
this.callbackContext = callbackContext;
}
private void returnCellInfo(int gsmSignalStrength) throws JSONException {
JSONObject response = new JSONObject();
TelephonyManager telephonyManager = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
CellLocation location = telephonyManager.getCellLocation();
GsmCellLocation gsmLocation = (GsmCellLocation) location;
int cid = gsmLocation.getCid();
if ((telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA ||
telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPA ||
telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPAP) && cid != -1) {
response.put("cid", cid & 0xffff);
} else {
response.put("cid", cid);
}
response.put("lac", gsmLocation.getLac());
response.put("psc", gsmLocation.getPsc());
response.put("networkType", CellInfo.networkTypeToString(telephonyManager.getNetworkType()));
response.put("rssi", gsmSignalStrength);
callbackContext.success(response);
}
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
try {
this.returnCellInfo(signalStrength.getGsmSignalStrength());
} catch (JSONException e) {
System.err.println("JSONException: " + e.getMessage());
}
this.unregister();
}
public void register() {
TelephonyManager telephonyManager = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(this, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
public void unregister() {
TelephonyManager telephonyManager = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(this, PhoneStateListener.LISTEN_NONE);
}
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArray of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("getNeighboringCellInfo")) {
this.getNeighboringCellInfo(callbackContext);
} else if (action.equals("getPrimaryCellInfo")) {
this.getPrimaryCellInfo(callbackContext);
} else {
return false;
}
return true;
}
private void getNeighboringCellInfo(CallbackContext callbackContext) throws JSONException {
JSONArray response = new JSONArray();
TelephonyManager telephonyManager = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
List<NeighboringCellInfo> cellInfoList = telephonyManager.getNeighboringCellInfo();
for(final NeighboringCellInfo info : cellInfoList) {
JSONObject jsonInfo = new JSONObject();
int cid = info.getCid();
if ((telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA ||
telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPA ||
telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPAP) && cid != -1) {
jsonInfo.put("cid", cid & 0xffff);
} else {
jsonInfo.put("cid", cid);
}
jsonInfo.put("lac", info.getLac());
jsonInfo.put("psc", info.getPsc());
jsonInfo.put("networkType", CellInfo.networkTypeToString(info.getNetworkType()));
jsonInfo.put("rssi", info.getRssi());
response.put(jsonInfo);
}
callbackContext.success(response);
}
private void getPrimaryCellInfo(CallbackContext callbackContext) throws JSONException {
PrimaryCellPhoneStateListener listener = new PrimaryCellPhoneStateListener(cordova, callbackContext);
listener.register();
}
/**
* Converts NETWORK_TYPE_* constants to network type names.
*
* @param networkType Network type constant (NETWORK_TYPE_*).
* @return Name of network type.
*/
public static String networkTypeToString(int networkType) {
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT";
case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA";
case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE";
case TelephonyManager.NETWORK_TYPE_EHRPD: return "eHRPD";
case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO rev. 0";
case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO rev. A";
case TelephonyManager.NETWORK_TYPE_EVDO_B: return "EVDO rev. B";
case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS";
case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA";
case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA";
case TelephonyManager.NETWORK_TYPE_HSPAP: return "HSPA+";
case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA";
case TelephonyManager.NETWORK_TYPE_IDEN: return "iDen";
case TelephonyManager.NETWORK_TYPE_LTE: return "LTE";
case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS";
case TelephonyManager.NETWORK_TYPE_UNKNOWN: return "Unknown";
default: return "New type of network";
}
}
}
|
package org.nuxeo.ecm.automation.core.operations.execution;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.automation.AutomationService;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Context;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.automation.core.annotations.Param;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.runtime.transaction.TransactionHelper;
/**
* Run an embedded operation chain inside separated transactions using the
* current input. The output is undefined (Void)
*
* @since 5.7.2
* @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
*
*/
@Operation(id = RunOperationOnListInNewTransaction.ID, category = Constants.CAT_SUBCHAIN_EXECUTION, label = "Run For Each in new TX", description = "Run an operation/chain in a new Transaction for each element from the list defined by the 'list' paramter. The 'list' parameter is pointing to context variable that represent the list which will be iterated. The 'itemName' parameter represent the name of the context varible which will point to the current element in the list at each iteration. You can use the 'isolate' parameter to specify whether or not the evalution context is the same as the parent context or a copy of it. If the isolate is 'true' then a copy of the current contetx is used and so that modifications in this context will not affect the parent context. Any input is accepted. The input is returned back as output when operation terminate.")
public class RunOperationOnListInNewTransaction {
protected static Log log = LogFactory.getLog(RunOperationOnListInNewTransaction.class);
public static final String ID = "Context.RunOperationOnListInNewTx";
@Context
protected OperationContext ctx;
@Context
protected AutomationService service;
@Param(name = "id")
protected String chainId;
@Param(name = "list")
protected String listName;
@Param(name = "itemName", required = false, values = "item")
protected String itemName = "item";
@Param(name = "isolate", required = false, values = "true")
protected boolean isolate = true;
@OperationMethod
public void run() throws Exception {
Map<String, Object> vars = isolate ? new HashMap<String, Object>(
ctx.getVars()) : ctx.getVars();
final CoreSession session = ctx.getCoreSession();
Collection<?> list = null;
if (ctx.get(listName) instanceof Object[]) {
list = Arrays.asList((Object[]) ctx.get(listName));
} else if (ctx.get(listName) instanceof Collection<?>) {
list = (Collection<?>) ctx.get(listName);
} else {
throw new UnsupportedOperationException(
ctx.get(listName).getClass() + " is not a Collection");
}
// commit the ongoing transaction
session.save();
TransactionHelper.commitOrRollbackTransaction();
// execute on list in sub transactions
for (Object value : list) {
TransactionHelper.startTransaction();
try {
OperationContext subctx = new OperationContext(session, vars);
subctx.setInput(ctx.getInput());
subctx.put(itemName, value);
service.run(subctx, chainId, null);
} catch (Exception e) {
e.printStackTrace();
TransactionHelper.setTransactionRollbackOnly();
} finally {
TransactionHelper.commitOrRollbackTransaction();
}
}
TransactionHelper.startTransaction();
if (!isolate) {
for (String varName : vars.keySet()) {
if (!ctx.getVars().containsKey(varName)) {
ctx.put(varName, vars.get(varName));
} else {
Object value = vars.get(varName);
if (value != null && value instanceof DocumentModel) {
ctx.getVars().put(
varName,
session.getDocument(((DocumentModel) value).getRef()));
} else {
ctx.getVars().put(varName, value);
}
}
}
}
}
}
|
package bg.nijel.xswiftkey;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import org.jf.dexlib2.DexFileFactory;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.dexbacked.DexBackedAnnotation;
import org.jf.dexlib2.dexbacked.DexBackedClassDef;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import bg.nijel.xswiftkey.helpers.Swiftkey;
import bg.nijel.xswiftkey.service.SaveThemeIdIntentService;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import static de.robv.android.xposed.XposedBridge.hookMethod;
import static de.robv.android.xposed.XposedHelpers.callMethod;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.findMethodExact;
import static de.robv.android.xposed.XposedHelpers.getIntField;
import static de.robv.android.xposed.XposedHelpers.getObjectField;
public class XSwiftkeyMod implements IXposedHookInitPackageResources, IXposedHookLoadPackage, IXposedHookZygoteInit {
private static String MY_PACKAGE_NAME;
private String selectedThemeId;
private static XSharedPreferences myPrefs;
private static String scrDensityFolder;
/*private boolean hasMethod(DexBackedClassDef dbcd) {
for (Object o : dbcd.getMethods()) {
DexBackedMethod dbm = (DexBackedMethod) o;
if (Arrays.asList(Swiftkey.getMethodsArgs()).contains(dbm.getName() + String.valueOf(dbm.getParameterTypes()))) {
return true;
}
}
return false;
}*/
}
|
package foam.core;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
public abstract class AbstractFObjectPropertyInfo
extends AbstractObjectPropertyInfo
{
// public int compareValues(FObject o1, FObject o2) {
// return o1.compareTo(o2);
@Override
public Object fromXML(X x, XMLStreamReader reader) {
FObject obj = null;
try {
String objClass = reader.getAttributeValue(null, "class");
Class cls = Class.forName(objClass);
obj = (FObject) x.create(cls);
XMLSupport.copyFromXML(x, obj, reader);
} catch (ClassNotFoundException | XMLStreamException ex) {
}
return obj;
}
@Override
public void toXML(FObject obj, Document doc, Element objElement) {
Object nestObj = this.f(obj);
Element objTag = doc.createElement(nestObj.getClass().getName());
objElement.appendChild(objTag);
if ( nestObj.getClass().isEnum() ) {
XMLSupport.enumXML( (Enum) nestObj, doc, objTag);
} else {
XMLSupport.toXML((FObject) nestObj, doc, objTag);
}
}
}
|
package es.uniovi.asw;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorTest {
@Test
public void evalAdd() {
Calculator calc = new Calculator();
Integer expected = 5;
assertEquals(calc.add(3, 2), expected);
assertEquals(calc.substract(7, 2), expected);
assertEquals(calc.divide(20, 4), expected);
assertEquals(calc.multiply(5, 1), expected);
}
}
|
package edu.umd.cs.findbugs;
/**
* Version number and release date information.
*/
public class Version {
/** Major version number. */
public static final int MAJOR = 0;
/** Minor version number. */
public static final int MINOR = 5;
/** Patch level. */
public static final int PATCHLEVEL = 4;
/** Release version string. */
public static final String RELEASE = MAJOR + "." + MINOR + "." + PATCHLEVEL;
/** Release date. */
public static final String DATE = "May 14, 2003";
public static void main(String[] argv) {
if (argv.length != 1)
usage();
String arg = argv[0];
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.number="+RELEASE);
System.out.println("release.date="+DATE);
} else
usage();
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() +
" (-release|-date|-props)");
System.exit(1);
}
}
// vim:ts=4
|
package at.modalog.cordova.plugin.html2pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import android.R.bool;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.print.PrintDocumentAdapter.LayoutResultCallback;
import android.print.PrintAttributes.MediaSize;
//import android.print.PrintDocumentInfo;
//import android.print.PrintDocumentInfo.Builder;
import android.print.PrintDocumentAdapter.WriteResultCallback;
import android.os.CancellationSignal;
import android.os.Bundle;
import android.print.PageRange;
import android.os.ParcelFileDescriptor;
import android.print.pdf.PrintedPdfDocument;
import android.util.SparseIntArray;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Color;
import android.print.PrintAttributes.Resolution;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.printservice.PrintJob;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Log;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class Html2pdf extends CordovaPlugin
{
/**
* Constructor.
*/
public Html2pdf() {
}
@Override
public boolean execute (String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
try{
String html = "<html><head></head><body>" + args.getString(0) + "</body></html>";
Document doc = new Document();
InputStream in = new ByteArrayInputStream(html.getBytes());
File sdCard = Environment.getExternalStorageDirectory();
PdfWriter pdf = PdfWriter.getInstance(doc, new FileOutputStream(sdCard.getAbsolutePath() + "/out.pdf"));
doc.open();
XMLWorkerHelper.getInstance().parseXHtml(pdf, doc,in);
doc.close();
in.close();
// send success result to cordova
PluginResult result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return true;
}
catch(Exception e){
System.out.println(e.getMessage());
return false;
}
return false;
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import org.junit.Test;
import seedu.taskboss.commons.core.Messages;
import seedu.taskboss.logic.commands.MarkDoneCommand;
import seedu.taskboss.model.task.Recurrence.Frequency;
import seedu.taskboss.testutil.TaskBuilder;
import seedu.taskboss.testutil.TestTask;
//@@author A0144904H
public class MarkDoneCommandTest extends TaskBossGuiTest {
// The list of tasks in the task list panel is expected to match this list.
// This list is updated with every successful call to assertEditSuccess().
TestTask[] expectedTasksList = td.getTypicalTasks();
/*
* EP: valid task index, should remove all
* task's current categories and add category "Done" in their place.
*
* Should return true.
*/
@Test
public void markTaskDone_success() throws Exception {
int taskBossIndex = 1;
TestTask markedDoneTask = new TaskBuilder().withName("Clean house").withPriorityLevel("Yes")
.withStartDateTime("Feb 19, 2017 11pm")
.withEndDateTime("Feb 28, 2017 5pm")
.withInformation("wall street").withRecurrence(Frequency.NONE)
.withCategories("Done").build();
assertMarkDoneSuccess(false, false, taskBossIndex, taskBossIndex, markedDoneTask);
}
@Test
public void markTaskDone_MultipleCategories_success() throws Exception {
int taskBossIndex = 5;
TestTask markedDoneTask = new TaskBuilder().withName("Birthday party")
.withInformation("311, Clementi Ave 2, #02-25")
.withPriorityLevel("No")
.withRecurrence(Frequency.NONE)
.withStartDateTime("Feb 23, 2017 10pm")
.withEndDateTime("Jun 28, 2017 5pm")
.withCategories("Done", "Friends", "Owesmoney").build();
assertMarkDoneSuccess(false, false, taskBossIndex, taskBossIndex, markedDoneTask);
}
/*
* Invalid index equivalence partitions for : 1) missing index
* 2) index invalid for not existing in task list.
*
* The two test cases below test one invalid index input type at a time
* for each of the two invalid possible cases.
*/
/*
* EP: invalid task index where index was not entered and is therefore missing,
* should not any of the non-recurring task's
* current categories and will not add category "Done". Or,
* update the dates of the recurring tasks.
*
* Should show error message that command entered was in the wrong format
* and an index should be entered.
*
* Should return false.
*/
@Test
public void markDone_missingTaskIndex_failure() {
commandBox.runCommand("mark ");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE));
}
/*
* EP: invalid task index where the index entered does
* not exist in current task list, should not remove any of the task's
* current categories and will not add category "Done".
*
* Should show error message that index entered is invalid.
*
* Should return false.
*/
@Test
public void markDone_invalidTaskIndex_failure() {
commandBox.runCommand("mark 9");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
/*
* Valid format equivalence partitions for : 1) short command format
* 2) long command format
*
* The two test cases below test one valid command format at a time
* for each of the two valid possible command formats.
*/
/*
* EP: valid format using long command, should remove all task's
* current categories and add category "Done" in their place.
*
* Should return true.
*/
@Test
public void markTaskDoneLong_success() throws Exception {
int taskBossIndex = 1;
TestTask markedDoneTask = new TaskBuilder().withName("Clean house").withPriorityLevel("Yes")
.withStartDateTime("Feb 19, 2017 11pm")
.withEndDateTime("Feb 28, 2017 5pm")
.withInformation("wall street").withRecurrence(Frequency.NONE)
.withCategories("Done").build();
assertMarkDoneSuccess(false, false, taskBossIndex, taskBossIndex, markedDoneTask);
}
/*
* EP: valid format using short command, should remove all task's
* current categories and add category "Done" in their place.
*
* Should return true.
*/
@Test
public void markTaskDone_Short_Command_success() throws Exception {
int taskBossIndex = 4;
TestTask markedDoneTask = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes")
.withStartDateTime("Feb 20, 2017 11.30pm")
.withEndDateTime("Apr 28, 2017 3pm")
.withInformation("10th street").withRecurrence(Frequency.NONE)
.withCategories("Done").build();
assertMarkDoneSuccess(false, true, taskBossIndex, taskBossIndex, markedDoneTask);
}
/*
* EP: Check if successfully marked done a command after performing a find command,
* should should remove all task's current categories and add category "Done" in their place.
* Should return true.
*/
@Test
public void markDone_findThenMarkDone_success() throws Exception {
commandBox.runCommand("find Clean house");
int filteredTaskListIndex = 1;
int taskBossIndex = 1;
TestTask taskToMarkDone = expectedTasksList[taskBossIndex - 1];
TestTask markedDoneTask = new TaskBuilder(taskToMarkDone).withCategories("Done").build();
assertMarkDoneSuccess(true, false, filteredTaskListIndex, taskBossIndex, markedDoneTask);
}
/*
* EP: Check if successfully marked multiple tasks done,
* should should remove all task's current categories and add category "Done" in their place.
* Recurring tasks' dates will be updated
* Should return true.
*/
@Test
public void multiple_markTaskDone_Long_Command_success() throws Exception {
commandBox.runCommand("mark 2 4");
expectedTasksList[1] = new TaskBuilder().withName("Ensure code quality").withPriorityLevel("No")
.withStartDateTime("Mar 22, 2017 5pm")
.withEndDateTime("Mar 28, 2017 5pm")
.withRecurrence(Frequency.MONTHLY)
.withInformation("michegan ave").build();
expectedTasksList[3] = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes")
.withStartDateTime("Feb 20, 2017 11.30pm")
.withEndDateTime("Apr 28, 2017 3pm")
.withRecurrence(Frequency.NONE)
.withInformation("10th street")
.withCategories("Done").build();
TestTask[] markedDone = new TestTask[] {expectedTasksList[3], expectedTasksList[1]};
assertTrue(taskListPanel.isListMatching(expectedTasksList));
assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS,
getDesiredFormat(markedDone)));
}
@Test
public void multiple_SpacesInBetween_markTaskDone_Short_Command_success() throws Exception {
commandBox.runCommand("m 2 4 ");
expectedTasksList[1] = new TaskBuilder().withName("Ensure code quality").withPriorityLevel("No")
.withStartDateTime("Mar 22, 2017 5pm")
.withEndDateTime("Mar 28, 2017 5pm")
.withRecurrence(Frequency.MONTHLY)
.withInformation("michegan ave").build();
expectedTasksList[3] = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes")
.withStartDateTime("Feb 20, 2017 11.30pm")
.withEndDateTime("Apr 28, 2017 3pm")
.withRecurrence(Frequency.NONE)
.withInformation("10th street")
.withCategories("Done").build();
TestTask[] markedDone = new TestTask[] {expectedTasksList[3], expectedTasksList[1]};
assertTrue(taskListPanel.isListMatching(expectedTasksList));
assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS,
getDesiredFormat(markedDone)));
}
@Test
public void multiple_markTaskDone_Command_InvalidIndex() {
commandBox.runCommand("m 1 2 100");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
commandBox.runCommand("mark 0 2 3");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
//user inputs non-numeric index values
commandBox.runCommand("mark a 2 3");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE));
commandBox.runCommand("mark ; 2 3");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE));
}
@Test
public void markDone_taskMarkedDone_failure() {
commandBox.runCommand("m 1");
commandBox.runCommand("m 1");
assertResultMessage(MarkDoneCommand.ERROR_MARKED_TASK);
}
private void assertMarkDoneSuccess(boolean runFind, boolean isShort, int filteredTaskListIndex, int taskBossIndex,
TestTask markedDoneTask) {
if (isShort) {
commandBox.runCommand("m " + filteredTaskListIndex);
} else {
commandBox.runCommand("mark " + filteredTaskListIndex);
}
// confirm the list now contains all previous tasks plus the task with updated details
expectedTasksList[taskBossIndex - 1] = markedDoneTask;
if (runFind) {
commandBox.runCommand("list ");
assertTrue(taskListPanel.isListMatching(expectedTasksList));
assertResultMessage("Listed all tasks");
} else {
assertTrue(taskListPanel.isListMatching(expectedTasksList));
assertResultMessage(String.format(MarkDoneCommand.MESSAGE_MARK_TASK_DONE_SUCCESS ,
"1. " + markedDoneTask));
}
assertTrue(taskListPanel.isListMatching(expectedTasksList));
}
//@@author A0143157J
/**
* Returns a formatted {@code Array} tasksToMarkDone,
* so that each TestTask in the Array is numbered
*/
private String getDesiredFormat(TestTask[] markedDoneTask) {
int indexOne = 1;
String numberingDot = ". ";
int i = indexOne;
StringBuilder builder = new StringBuilder();
for (TestTask task : markedDoneTask) {
builder.append(i + numberingDot).append(task.toString());
i++;
}
return builder.toString();
}
}
|
package edu.umd.cs.findbugs;
/**
* Version number and release date information.
*/
public class Version {
/** Major version number. */
public static final int MAJOR = 0;
/** Minor version number. */
public static final int MINOR = 7;
/** Patch level. */
public static final int PATCHLEVEL = 4;
/** Development version? */
public static final boolean IS_DEVELOPMENT = true;
/** Release version string. */
public static final String RELEASE = MAJOR + "." + MINOR + "." + PATCHLEVEL + (IS_DEVELOPMENT ? "-dev" : "");
/** Release date. */
public static final String DATE = "May 28, 2004";
/** Version of Eclipse UI plugin. */
public static final String ECLIPSE_UI_VERSION = "0.0.5";
/** FindBugs website. */
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/** Downloads website. */
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
public static void main(String[] argv) {
if (argv.length != 1)
usage();
String arg = argv[0];
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.number="+RELEASE);
System.out.println("release.date="+DATE);
System.out.println("eclipse.ui.version="+ECLIPSE_UI_VERSION);
System.out.println("findbugs.website="+WEBSITE);
System.out.println("findbugs.downloads.website="+DOWNLOADS_WEBSITE);
} else
usage();
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() +
" (-release|-date|-props)");
System.exit(1);
}
}
// vim:ts=4
|
package at.jku.aig2qbf.visualizer;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import at.jku.aig2qbf.component.Tree;
import at.jku.aig2qbf.parser.AAG;
import at.jku.aig2qbf.parser.AIG;
import at.jku.aig2qbf.parser.Parser;
import at.jku.aig2qbf.parser.Parser.Extension;
public class TreeVisualizer {
public static void DisplayTree(Tree tree) {
DisplayTree(tree, "Visualize!");
}
public static void DisplayTree(Tree tree, String title) {
if (tree == null) {
throw new RuntimeException("Tree must not be null");
}
if (title == null) {
title = "Undefined title";
}
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final CountDownLatch waitForSignal = new CountDownLatch(1);
TreeFrame frame = new TreeFrame(tree, title, screenSize.width, screenSize.height);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setBounds(0, 0, screenSize.width, screenSize.height);
frame.setVisible(true);
frame.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent arg0) {
}
@Override
public void windowIconified(WindowEvent arg0) {
}
@Override
public void windowDeiconified(WindowEvent arg0) {
}
@Override
public void windowDeactivated(WindowEvent arg0) {
}
@Override
public void windowClosing(WindowEvent arg0) {
waitForSignal.countDown();
}
@Override
public void windowClosed(WindowEvent arg0) {
}
@Override
public void windowActivated(WindowEvent arg0) {
}
});
try {
waitForSignal.await();
}
catch (InterruptedException e) {
}
}
public static void main(String[] args) {
JFrame filechooserComponent = new JFrame();
JFileChooser chooser = new JFileChooser(new File("./"));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int option = chooser.showOpenDialog(filechooserComponent);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().getAbsolutePath();
Extension extension = Parser.getExtension(filename);
Tree tree = null;
if (extension == null) {
throw new RuntimeException(String.format("Unknown extension for filename \"%s\"", filename));
}
else {
switch (extension) {
case AAG:
tree = new AAG().parse(filename);
break;
case AIG:
tree = new AIG().parse(filename);
break;
default:
break;
}
}
TreeVisualizer.DisplayTree(tree, filename);
}
}
}
|
package at.modalog.cordova.plugin.html2pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import android.R.bool;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.print.PrintDocumentAdapter.LayoutResultCallback;
import android.print.PrintAttributes.MediaSize;
//import android.print.PrintDocumentInfo;
//import android.print.PrintDocumentInfo.Builder;
import android.print.PrintDocumentAdapter.WriteResultCallback;
import android.os.CancellationSignal;
import android.os.Bundle;
import android.print.PageRange;
import android.os.ParcelFileDescriptor;
import android.print.pdf.PrintedPdfDocument;
import android.util.SparseIntArray;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Color;
import android.print.PrintAttributes.Resolution;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.printservice.PrintJob;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Log;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class Html2pdf extends CordovaPlugin
{
/**
* Constructor.
*/
public Html2pdf() {
}
@Override
public boolean execute (String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
try{
String html = "<html><head></head><body>" + args.getString(0) + "</body></html>";
Document doc = new Document();
InputStream in = new ByteArrayInputStream(html.getBytes());
PdfWriter pdf = PdfWriter.getInstance(doc, new FileOutputStream(p.getApplication().getExternalFilesDir("MyFileStorage") + "/out.pdf"));
doc.open();
XMLWorkerHelper.getInstance().parseXHtml(pdf, doc,in);
doc.close();
in.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
// send success result to cordova
PluginResult result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
self.callbackContext.sendPluginResult(result);
}
}
|
package org.voltdb;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import com.google.common.collect.UnmodifiableIterator;
import org.apache.cassandra_voltpatches.MurmurHash3;
import org.voltcore.utils.Pair;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSortedMap;
/**
* A hashinator that uses Murmur3_x64_128 to hash values and a consistent hash ring
* to pick what partition to route a particular value.
*/
public class ElasticHashinator extends TheHashinator {
public static int DEFAULT_TOKENS_PER_PARTITION =
Integer.parseInt(System.getProperty("ELASTIC_TOKENS_PER_PARTITION", "8"));
/**
* Tokens on the ring. A value hashes to a token if the token is the first value <=
* the value's hash
*/
private final ImmutableSortedMap<Long, Integer> tokens;
private final byte m_configBytes[];
/**
* Initialize the hashinator from a binary description of the ring.
* The serialization format is big-endian and the first value is the number of tokens
* followed by the token values where each token value consists of the 8-byte position on the ring
* and and the 4-byte partition id. All values are signed.
*/
public ElasticHashinator(byte configureBytes[]) {
m_configBytes = Arrays.copyOf(configureBytes, configureBytes.length);
ByteBuffer buf = ByteBuffer.wrap(configureBytes);
int numEntries = buf.getInt();
TreeMap<Long, Integer> buildMap = new TreeMap<Long, Integer>();
for (int ii = 0; ii < numEntries; ii++) {
final long token = buf.getLong();
final int partitionId = buf.getInt();
if (buildMap.containsKey(token)) {
throw new RuntimeException(
"Duplicate token " + token + " partition "
+ partitionId + " and " + buildMap.get(token));
}
buildMap.put( token, partitionId);
}
ImmutableSortedMap.Builder<Long, Integer> builder = ImmutableSortedMap.naturalOrder();
for (Map.Entry<Long, Integer> e : buildMap.entrySet()) {
builder.put(e.getKey(), e.getValue());
}
tokens = builder.build();
}
/**
* Private constructor to initialize a hashinator with known tokens. Used for adding/removing
* partitions from existing hashinator.
* @param tokens
*/
private ElasticHashinator(Map<Long, Integer> tokens) {
this.tokens = ImmutableSortedMap.copyOf(tokens);
m_configBytes = toBytes();
}
/**
* Given an existing elastic hashinator, add a set of new partitions to the existing hash ring.
* @param oldHashinator An elastic hashinator
* @param newPartitions A set of new partitions to add
* @param tokensPerPartition The number of times a partition appears on the ring
* @return The config bytes of the new hash ring
*/
public static byte[] addPartitions(TheHashinator oldHashinator,
Collection<Integer> newPartitions,
int tokensPerPartition) {
Preconditions.checkArgument(oldHashinator instanceof ElasticHashinator);
ElasticHashinator oldElasticHashinator = (ElasticHashinator) oldHashinator;
Random r = new Random(0);
Map<Long, Integer> newConfig = new HashMap<Long, Integer>(oldElasticHashinator.tokens);
Set<Integer> existingPartitions = new HashSet<Integer>(oldElasticHashinator.tokens.values());
Set<Long> checkSet = new HashSet<Long>(oldElasticHashinator.tokens.keySet());
for (int pid : newPartitions) {
if (existingPartitions.contains(pid)) {
throw new RuntimeException("Partition " + pid + " already exists in the " +
"hashinator");
}
for (int i = 0; i < tokensPerPartition; i++) {
while (true) {
long candidateToken = MurmurHash3.hash3_x64_128(r.nextLong());
if (!checkSet.add(candidateToken)) {
continue;
}
newConfig.put(candidateToken, pid);
break;
}
}
}
return new ElasticHashinator(newConfig).toBytes();
}
/**
* Given an existing elastic hashinator, add a set of new partitions to the existing hash ring
* with calculated ranges.
* @param oldHashinator An elastic hashinator
* @param partitionsAndRanges A set of new partitions and their associated ranges
* @return The config bytes of the new hash ring
*/
public static byte[] addPartitions(TheHashinator oldHashinator,
Map<Long, Integer> tokensToPartitions) {
Preconditions.checkArgument(oldHashinator instanceof ElasticHashinator);
ElasticHashinator oldElasticHashinator = (ElasticHashinator) oldHashinator;
Map<Long, Integer> newConfig = new HashMap<Long, Integer>(oldElasticHashinator.tokens);
Set<Integer> existingPartitions = new HashSet<Integer>(oldElasticHashinator.tokens.values());
for (Map.Entry<Long, Integer> entry : tokensToPartitions.entrySet()) {
long token = entry.getKey();
int pid = entry.getValue();
if (existingPartitions.contains(pid)) {
throw new RuntimeException("Partition " + pid + " already exists in the " +
"hashinator");
}
Integer oldPartition = newConfig.put(token, pid);
if (oldPartition != null) {
throw new RuntimeException("Token " + token + " used to map to partition " +
oldPartition + " but now maps to " + pid);
}
}
return new ElasticHashinator(newConfig).toBytes();
}
/**
* Convenience method for generating a deterministic token distribution for the ring based
* on a given partition count and tokens per partition. Each partition will have N tokens
* placed randomly on the ring.
*/
public static byte[] getConfigureBytes(int partitionCount, int tokensPerPartition) {
Preconditions.checkArgument(partitionCount > 0);
Preconditions.checkArgument(tokensPerPartition > 0);
ElasticHashinator emptyHashinator = new ElasticHashinator(new HashMap<Long, Integer>());
Set<Integer> partitions = new HashSet<Integer>();
for (int ii = 0; ii < partitionCount; ii++) {
partitions.add(ii);
}
return addPartitions(emptyHashinator, partitions, tokensPerPartition);
}
/**
* Serializes the configuration into bytes, also updates the currently cached m_configBytes.
* @return The byte[] of the current configuration.
*/
private byte[] toBytes() {
ByteBuffer buf = ByteBuffer.allocate(4 + (tokens.size() * 12));//long and an int per
buf.putInt(tokens.size());
for (Map.Entry<Long, Integer> e : tokens.entrySet()) {
long token = e.getKey();
int pid = e.getValue();
buf.putLong(token);
buf.putInt(pid);
}
return buf.array();
}
/**
* For a given a value hash, find the token that corresponds to it. This will
* be the first token <= the value hash, or if the value hash is < the first token in the ring,
* it wraps around to the last token in the ring closest to Long.MAX_VALUE
*/
int partitionForToken(long hash) {
Map.Entry<Long, Integer> entry = tokens.floorEntry(hash);
//System.out.println("Finding partition for token " + token);
/*
* Because the tokens are randomly distributed it is likely there is a range
* near Long.MIN_VALUE that isn't covered by a token. Conceptually this is a ring
* so the correct token is the one near Long.MAX_VALUE.
*/
if (entry != null) {
//System.out.println("Floor token was " + entry.getKey());
return entry.getValue();
} else {
//System.out.println("Last entry token " + tokens.lastEntry().getKey());
return tokens.lastEntry().getValue();
}
}
@Override
protected int pHashinateLong(long value) {
if (value == Long.MIN_VALUE) return 0;
return partitionForToken(MurmurHash3.hash3_x64_128(value));
}
@Override
protected int pHashinateBytes(byte[] bytes) {
ByteBuffer buf = ByteBuffer.wrap(bytes);
final long token = MurmurHash3.hash3_x64_128(buf, 0, bytes.length, 0);
return partitionForToken(token);
}
@Override
protected Pair<HashinatorType, byte[]> pGetCurrentConfig() {
return Pair.of(HashinatorType.ELASTIC, m_configBytes);
}
/**
* Find the predecessors of the given partition on the ring. This method runs in linear time,
* use with caution when the set of partitions is large.
* @param partition
* @return The IDs of the partitions that are the predecessors of the given partition.
* If the given partition doesn't exist or it's the only partition on the ring, the
* set is empty.
*/
@Override
protected Set<Integer> pPredecessors(int partition) {
Set<Integer> predecessors = new HashSet<Integer>();
UnmodifiableIterator<Map.Entry<Long,Integer>> iter = tokens.entrySet().iterator();
Set<Long> pTokens = new HashSet<Long>();
while (iter.hasNext()) {
Map.Entry<Long, Integer> next = iter.next();
if (next.getValue() == partition) {
pTokens.add(next.getKey());
}
}
for (Long token : pTokens) {
Map.Entry<Long, Integer> predecessor = null;
if (token != null) {
predecessor = tokens.headMap(token).lastEntry();
// If null, it means partition is the first one on the ring, so predecessor
// should be the last entry on the ring because it wraps around.
if (predecessor == null) {
predecessor = tokens.lastEntry();
}
}
if (predecessor != null && predecessor.getValue() != partition) {
predecessors.add(predecessor.getValue());
}
}
return predecessors;
}
/**
* This runs in linear time with respect to the number of tokens on the ring.
*/
@Override
protected Map<Long, Long> pGetRanges(int partition) {
Map<Long, Long> ranges = new HashMap<Long, Long>();
Long first = null; // start of the very first token on the ring
Long start = null; // start of a range
UnmodifiableIterator<Map.Entry<Long,Integer>> iter = tokens.entrySet().iterator();
// Iterate through the token map to find the ranges assigned to
// the given partition
while (iter.hasNext()) {
Map.Entry<Long, Integer> next = iter.next();
long token = next.getKey();
int pid = next.getValue();
if (first == null) {
first = token;
}
if (pid == partition) {
// if start is null, there's no open range, start one.
// else there is already an open range, leave it open.
if (start == null) {
start = token;
}
} else {
// hit a token that belongs to a different partition.
// if start is not null, there's an open range, now is
// the time to close it.
// else there is no open range, keep on going.
if (start != null) {
ranges.put(start, token);
start = null;
}
}
}
// if there is an open range when we get here, it means that
// the last token on the ring belongs to the partition, and
// it wraps around the origin of the ring, so close the range
// with the the very first token on the ring.
if (start != null) {
assert first != null;
ranges.put(start, first);
}
return ranges;
}
}
|
package hex;
import static water.util.MRUtils.sampleFrame;
import hex.deeplearning.DeepLearning;
import hex.deeplearning.DeepLearningModel;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import water.*;
import water.api.AUC;
import water.exec.Env;
import water.exec.Exec2;
import water.fvec.Frame;
import water.fvec.NFSFileVec;
import water.fvec.ParseDataset2;
import water.util.Log;
import java.util.Random;
public class DeepLearningProstateTest extends TestUtil {
@BeforeClass public static void stall() {
stall_till_cloudsize(JUnitRunnerDebug.NODES);
}
public void runFraction(float fraction) {
long seed = 0xDECAF;
Random rng = new Random(seed);
String[] datasets = new String[2];
int[][] responses = new int[datasets.length][];
datasets[0] = "smalldata/./logreg/prostate.csv"; responses[0] = new int[]{1,2,8};
datasets[1] = "smalldata/iris/iris.csv"; responses[1] = new int[]{4};
int count = 0;
for (int i =0;i<datasets.length;++i) {
String dataset = datasets[i];
Key file = NFSFileVec.make(find_test_file(dataset));
Frame frame = ParseDataset2.parse(Key.make(), new Key[]{file});
Key vfile = NFSFileVec.make(find_test_file(dataset));
Frame tmp = ParseDataset2.parse(Key.make(), new Key[]{vfile});
Frame vframe = sampleFrame(tmp, (long)(0.8*frame.numRows()), seed);
for (boolean replicate : new boolean[]{
true,
false,
}) {
for (boolean load_balance : new boolean[]{
true,
false,
}) {
for (boolean shuffle : new boolean[]{
true,
false,
}) {
for (boolean balance_classes : new boolean[]{
true,
false,
}) {
for (int resp : responses[i]) {
for (DeepLearning.ClassSamplingMethod csm : new DeepLearning.ClassSamplingMethod[] {
DeepLearning.ClassSamplingMethod.Stratified,
DeepLearning.ClassSamplingMethod.Uniform
}) {
for (int scoretraining : new int[]{
200,
0,
}) {
for (int scorevalidation : new int[]{
200,
0,
}) {
for (int vf : new int[]{
0, //no validation
1, //same as source
-1, //different validation frame
}) {
for (int train_samples_per_iteration : new int[] {
// -1, //N epochs per iteration
0, //1 epoch per iteration
// rng.nextInt(100), // <1 epoch per iteration
// 500, //>1 epoch per iteration
})
{
for (Key best_model_key : new Key[]{null}) {
// for (Key best_model_key : new Key[]{null, Key.make()}) {
count++;
if (fraction < rng.nextFloat()) continue;
Log.info("**************************)");
Log.info("Starting test #" + count);
Log.info("**************************)");
Frame valid = null; //no validation
if (vf == 1) valid = frame; //use the same frame for validation
else if (vf == -1) valid = vframe; //different validation frame (here: from the same file)
Key dest_tmp = Key.make();
// build the model, with all kinds of shuffling/rebalancing/sampling
{
Log.info("Using seed: " + seed);
DeepLearning p = new DeepLearning();
p.checkpoint = null;
p.destination_key = dest_tmp;
p.source = frame;
p.response = frame.vecs()[resp];
p.validation = valid;
p.ignored_cols = new int[]{};
p.hidden = new int[]{1 + rng.nextInt(4), 1 + rng.nextInt(6)};
if (i == 0 && resp == 2) p.classification = false;
p.best_model_key = best_model_key;
p.epochs = 7 + rng.nextDouble() + rng.nextInt(4);
p.seed = seed;
p.train_samples_per_iteration = train_samples_per_iteration;
p.force_load_balance = load_balance;
p.replicate_training_data = replicate;
p.shuffle_training_data = shuffle;
p.score_training_samples = scoretraining;
p.score_validation_samples = scorevalidation;
p.balance_classes = balance_classes;
// p.quiet_mode = true;
p.quiet_mode = false;
p.score_validation_sampling = csm;
// Train the model via checkpointing
p.invoke();
}
// Do some more training via checkpoint restart
Key dest = Key.make();
{
DeepLearning p = new DeepLearning();
p.checkpoint = dest_tmp;
p.destination_key = dest;
p.source = frame;
p.validation = valid;
p.response = frame.vecs()[resp];
p.ignored_cols = new int[]{};
if (i == 0 && resp == 2) p.classification = false;
p.best_model_key = best_model_key;
p.epochs = 7 + rng.nextDouble() + rng.nextInt(4);
p.seed = seed;
p.train_samples_per_iteration = train_samples_per_iteration;
p.invoke();
}
// score and check result (on full data)
final DeepLearningModel mymodel = UKV.get(dest); //this actually *requires* frame to also still be in UKV (because of DataInfo...)
// test HTML
{
StringBuilder sb = new StringBuilder();
mymodel.generateHTML("test", sb);
}
if (valid == null ) valid = frame;
double threshold = 0;
if (mymodel.isClassifier()) {
Frame pred = mymodel.score(valid);
StringBuilder sb = new StringBuilder();
AUC auc = new AUC();
double error = 0;
// binary
if (mymodel.nclasses()==2) {
auc.actual = valid;
auc.vactual = valid.vecs()[resp];
auc.predict = pred;
auc.vpredict = pred.vecs()[2];
auc.threshold_criterion = AUC.ThresholdCriterion.maximum_F1;
auc.invoke();
auc.toASCII(sb);
threshold = auc.threshold();
error = auc.err();
Log.info(sb);
// check that auc.cm() is the right CM
Assert.assertEquals(new ConfusionMatrix(auc.cm()).err(), error, 1e-15);
// check that calcError() is consistent as well (for CM=null, AUC!=null)
Assert.assertEquals(mymodel.calcError(valid, valid.lastVec(), pred, pred, "training", false, 0, null, auc, null), error, 1e-15);
}
// Compute CM
double CMerrorOrig;
{
sb = new StringBuilder();
water.api.ConfusionMatrix CM = new water.api.ConfusionMatrix();
CM.actual = valid;
CM.vactual = valid.vecs()[resp];
CM.predict = pred;
CM.vpredict = pred.vecs()[0];
CM.invoke();
sb.append("\n");
sb.append("Threshold: " + "default\n");
CM.toASCII(sb);
Log.info(sb);
CMerrorOrig = new ConfusionMatrix(CM.cm).err();
}
// confirm that orig CM was made with threshold 0.5
// put pred2 into UKV, and allow access
Frame pred2 = new Frame(Key.make("pred2"), pred.names(), pred.vecs());
pred2.delete_and_lock(null);
pred2.unlock(null);
if (mymodel.nclasses()==2) {
// make labels with 0.5 threshold for binary classifier
Env ev = Exec2.exec("pred2[,1]=pred2[,3]>=" + 0.5);
pred2 = ev.popAry();
ev.subRef(pred2, "pred2");
ev.remove_and_unlock();
water.api.ConfusionMatrix CM = new water.api.ConfusionMatrix();
CM.actual = valid;
CM.vactual = valid.vecs()[1];
CM.predict = pred2;
CM.vpredict = pred2.vecs()[0];
CM.invoke();
sb = new StringBuilder();
sb.append("\n");
sb.append("Threshold: " + 0.5 + "\n");
CM.toASCII(sb);
Log.info(sb);
double threshErr = new ConfusionMatrix(CM.cm).err();
Assert.assertEquals(threshErr, CMerrorOrig, 1e-15);
// make labels with AUC-given threshold for best F1
ev = Exec2.exec("pred2[,1]=pred2[,3]>=" + threshold);
pred2 = ev.popAry();
ev.subRef(pred2, "pred2");
ev.remove_and_unlock();
CM = new water.api.ConfusionMatrix();
CM.actual = valid;
CM.vactual = valid.vecs()[1];
CM.predict = pred2;
CM.vpredict = pred2.vecs()[0];
CM.invoke();
sb = new StringBuilder();
sb.append("\n");
sb.append("Threshold: " + threshold + "\n");
CM.toASCII(sb);
Log.info(sb);
double threshErr2 = new ConfusionMatrix(CM.cm).err();
Assert.assertEquals(threshErr2, error, 1e-15);
}
pred2.delete();
pred.delete();
} //classifier
final boolean validation = (vf != 0); //p.validation != null -> DL scores based on validation data set (which can be the same as training data set)
if (mymodel.get_params().best_model_key != null) {
// get the actual best error on training data
float best_err = Float.MAX_VALUE;
long best_samples = 0;
for (DeepLearningModel.Errors err : mymodel.scoring_history()) {
float e;
if (mymodel.isClassifier()) {
e = (float) (validation ? err.valid_err : err.train_err);
} else {
e = (float) (validation ? err.valid_mse : err.train_mse);
}
if (e < best_err) {
best_err = e;
best_samples = err.training_samples;
}
}
Log.info("Actual best error : " + best_err + ".");
Log.info("Actual best training samples : " + best_samples + ".");
// get the error reported by the stored best model
DeepLearningModel bestmodel = UKV.get(mymodel.get_params().best_model_key);
Log.info("Best model\n" + bestmodel.toString());
final Frame fr = valid;
Frame bestPredict = bestmodel.score(fr);
double bestErr = bestmodel.calcError(fr, fr.vecs()[resp], bestPredict, bestPredict, validation ? "validation" : "training",
true, bestmodel.get_params().max_confusion_matrix_size, new water.api.ConfusionMatrix(),
bestmodel.nclasses() == 2 ? new AUC() : null, null); //presence of AUC object allows optimal threshold to be used for bestErr calculation
Log.info("Validation: " + validation);
Log.info("Best_model's samples : " + bestmodel.model_info().get_processed_total() + ".");
Log.info("Best_model's error : " + bestErr + ".");
Assert.assertEquals(bestmodel.model_info().get_processed_total(), best_samples);
if (csm != DeepLearning.ClassSamplingMethod.Stratified && !balance_classes) //cannot compare scoring if we did stratification inside of DL
Assert.assertEquals(bestErr, best_err, 1e-5);
bestmodel.delete();
bestPredict.delete();
}
mymodel.delete();
UKV.remove(dest);
UKV.remove(dest_tmp);
Log.info("Parameters combination " + count + ": PASS");
}
}
}
}
}
}
}
}
}
}
}
frame.delete();
vframe.delete();
tmp.delete();
}
}
public static class Long extends DeepLearningProstateTest {
@Test public void run() throws Exception { runFraction(1.0f); }
}
public static class Short extends DeepLearningProstateTest {
@Test public void run() throws Exception { runFraction(0.02f); }
}
}
|
/**
* A plugin for XunFei voice feature.
*
* [2017-02-14] Add camera input method
* [2017-02-06] Try support voice wakeup.
* [2017-01-22] Avoid blocking the main thread
*/
package org.ioniconline;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.os.Bundle;
import android.hardware.Camera;
import android.util.Base64;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.LexiconListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.util.ResourceUtil;
import com.iflytek.cloud.util.ResourceUtil.RESOURCE_TYPE;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class MySpeech extends CordovaPlugin {
private static final String TAG = "MySpeech";
// the APPID got from the web
//private static final String YOUR_APP_ID = "5631ca67";
private static final String YOUR_APP_ID = "576206f0";
// Totally - 8
private static final String [] mVoiceName = {
"xiaoyan", // lady, madrin
"xiaoyu",
"xiaorong", // SiChuan
"xiaomei", // Guang Dong
"xiaokun", // HeNan
"xiaoqiang", // HuNan
"xiaoqian", // Dong Bei
"xiaolin" // TaiWan
};
private CallbackContext mCb;
private CallbackContext mCamCb;
private Camera.PreviewCallback mCamCallback =
new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] arg0, Camera arg1) {
android.util.Log.e(TAG, "Wow, incoming with "
+ arg0.length + " Bytes data");
if (arg1.getParameters().getPreviewFormat() != ImageFormat.NV21){
android.util.Log.e(TAG, "probably not correct format, check hardware");
// FIXME - currently, we just need one frame at one time
stopCameraPreview();
mCamCb.error("Check your hardware!");
return;
}
String imgB64Val = "";
YuvImage image = new YuvImage(arg0, ImageFormat.NV21,
mCamPrevSize.width,
mCamPrevSize.height,
null);
File pic = new File(mCamDefaultImgName);
FileOutputStream outputStream;
try{
outputStream = new FileOutputStream(pic);
image.compressToJpeg(new Rect(0, 0, image.getWidth(),
image.getHeight()),
70, outputStream);
outputStream.close();
//imgB64Val = imageBase64Format(mCamDefaultImgName);
//mCamCb.success(imgB64Val);
// FIXME - currently, we just need one frame at one time
stopCameraPreview();
} catch (FileNotFoundException e) {
android.util.Log.e(TAG, "exception");
e.printStackTrace();
// FIXME - need send to JS for such case?
} catch (IOException ex) {
android.util.Log.e(TAG, "exception in IO.");
ex.printStackTrace();
}
// try detect
MyFaceDetect mfd = new MyFaceDetect(mCamDefaultImgName);
android.util.Log.i(TAG, "face detected begin...");
// JSON data return to JS side...
mCamCb.success(mfd.faceData());
}
};
private Camera.Size mCamPrevSize;
// TODO as we only do this via oneshot, below variable
// will not be used in the future...
private byte [] mCamPrevBuf;
private int mPreviewFlag = 0; // 1 means keep previewing, otherwise is one-shot
// FIXME - a temp debug code...
private String mCamDefaultImgName = "/sdcard/my.jpg";
private boolean mFirstCall = false;
// the wakeup obj
private VoiceWakeuper mWakeup = null;
// the speaker
private SpeechSynthesizer mSynth = null;
// the listener
private SpeechRecognizer mListen = null;
private HashMap<String, String> mListenResults = new LinkedHashMap<String, String>();
private StringBuffer mFinalResult = new StringBuffer();
private InitListener initListener = new InitListener() {
@Override
public void onInit(int code) {
android.util.Log.e(TAG, "onInit code:" + code);
}
};
private Camera mCamera = null;
private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override
public void onVolumeChanged(int vol, byte [] data) {
}
@Override
public void onEvent(int eventType, int arg1, int arg2, android.os.Bundle obj) {
}
@Override
public void onBeginOfSpeech() {
android.util.Log.e(TAG, ">start of speech");
}
@Override
public void onError(SpeechError error) {
android.util.Log.e(TAG, "onError meet:" + error);
if(error.getErrorCode() == 10118
|| ErrorCode.MSP_ERROR_NO_DATA == error.getErrorCode()) {
android.util.Log.e(TAG, "You said nothing at all!");
mCb.error("Say Nothing!");
} else if (error.getErrorCode() == 10114
|| ErrorCode.MSP_ERROR_TIME_OUT == error.getErrorCode()) {
android.util.Log.e(TAG, "Time out !");
mCb.error("MSP_ERROR_TIME_OUT");
} else if (error.getErrorCode() == 20001
|| ErrorCode.ERROR_NO_NETWORK == error.getErrorCode()) {
android.util.Log.e(TAG, "no network !");
mCb.error("ERROR_NO_NETWORK");
}
}
@Override
public void onEndOfSpeech() {
android.util.Log.e(TAG, "<end of speech");
}
@Override
public void onResult(RecognizerResult results, boolean isLast) {
android.util.Log.e(TAG, "+got the result");
String resultText = parseListenResult(results.getResultString());
String sn = null;
try {
JSONObject resultJson = new JSONObject(resultText);
sn = resultJson.optString("sn");
}catch (JSONException e) {
}
mListenResults.put(sn, resultText);
StringBuffer resultBuffer = new StringBuffer();
for (String key : mListenResults.keySet()) {
resultBuffer.append(mListenResults.get(key));
}
mFinalResult.append(resultBuffer.toString());
android.util.Log.e(TAG, "the text are : " + resultBuffer.toString());
if(isLast) {
PluginResult r = new PluginResult(
PluginResult.Status.OK,
mFinalResult.toString());
r.setKeepCallback(true);
mCb.sendPluginResult(r);
}
}
};
/* FIXME - call this in two thread Pool won't cause race-condition? */
private int initSafe() {
if(mFirstCall == false) {
android.util.Log.i(TAG, "call speech util only once.");
SpeechUtility.createUtility(
cordova.getActivity(),
SpeechConstant.APPID + "=" + YOUR_APP_ID);
mFirstCall = true; // DO NOT Call it twice
}
return 0;
}
@Override
public void onDestroy() {
android.util.Log.e(TAG, "FINAL CALL?");
if(mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext cb) throws JSONException {
boolean ret = true;
mCb = cb;
android.util.Log.e(TAG, "coming with " + action + " action");
if (action.equals("init")) {
// Init ...
android.util.Log.e(TAG, "init the engine in background...");
cordova.getThreadPool().execute(new Runnable(){
@Override
public void run(){
initSafe();
mListen = SpeechRecognizer.createRecognizer(
cordova.getActivity(),
initListener/* use null listen */);
if(mListen == null){
android.util.Log.e(TAG, "listener is a null obj...");
cb.error("XunFei plugin init with null result[Failed]");
} else {
android.util.Log.i(TAG, "got a listener, cool.");
cb.success("init XunFei plugin [OK]");
}
}
});
} else if (action.equals("initCamera")) {
initAndroidCamera(args, cb);
} else if (action.equals("cleanCamera")) {
cleanAndroidCamera(cb);
} else if (action.equals("startCameraPreview")) {
mCamCb = cb;
startCameraPreview(args, cb);
} else if (action.equals("speak")) {
// Speaking...
android.util.Log.e(TAG, "speak...");
int vn = mapTheVoiceName(args.getInt(0));
int speed = args.getInt(1);
String val = args.getString(2);
android.util.Log.e(TAG, "the voice name are : " + mVoiceName[vn]);
android.util.Log.e(TAG, "the voice speed is: " + speed);
SpeechSynthesizer syn = getSynthesizer();
syn.setParameter(SpeechConstant.VOICE_NAME, mVoiceName[vn]);
syn.setParameter(SpeechConstant.SPEED, String.valueOf(speed));
syn.startSpeaking(val,
null // currently use null listener
);
} else if (action.equals("listen")) {
// Listen ...
android.util.Log.i(TAG, "listening...");
if(mListen == null){
android.util.Log.e(TAG, "null listen obj, probably not inited engine.");
cb.error("engine not inited");
return false;
}
mListen.setParameter(SpeechConstant.PARAMS, null);
mListen.setParameter(SpeechConstant.ENGINE_TYPE,SpeechConstant.TYPE_CLOUD);
mListen.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
mListen.setParameter(SpeechConstant.ACCENT, "mandarin ");
mListen.setParameter(SpeechConstant.RESULT_TYPE, "json");
mListen.setParameter(SpeechConstant.VAD_BOS, "4000"); // end timeout setting
mListen.setParameter(SpeechConstant.VAD_EOS, "1000");
mListen.setParameter(SpeechConstant.ASR_PTT, "1");
mListen.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
mListen.setParameter(SpeechConstant.ASR_AUDIO_PATH, android.os.Environment.getExternalStorageDirectory()+"/msc/iat.wav");
mFinalResult = new StringBuffer();
if(mListen.startListening(mRecognizerListener) != ErrorCode.SUCCESS) {
android.util.Log.e(TAG, "Failed listen to you!");
}
} else if (action.equals("initWakeup")) {
android.util.Log.i(TAG, "Try Init Wakeup");
cordova.getThreadPool().execute(new Runnable(){
@Override
public void run(){
initSafe();
cb.success("init my wakeup good");
}
});
} else if (action.equals("startWakeup")){
StringBuffer param =new StringBuffer();
String resPath = ResourceUtil.generateResourcePath(
cordova.getActivity(),
RESOURCE_TYPE.assets,
"ivw/576206f0.jet");
param.append(ResourceUtil.IVW_RES_PATH+"="+resPath);
param.append(","+ResourceUtil.ENGINE_START+"="+SpeechConstant.ENG_IVW);
SpeechUtility.getUtility().setParameter(
ResourceUtil.ENGINE_START,
param.toString());
android.util.Log.e(TAG, "p:" + param.toString());
mWakeup = VoiceWakeuper.createWakeuper(
cordova.getActivity(), null);
if(mWakeup == null) {
cb.error("wakeuper creation got a null obj");
} else {
android.util.Log.i(TAG, "wakuper obj creation[OK]");
//DO NOT CALL this at init phase...
//initWakeupFeature();
// cb.success("createWakeuper good");
}
if(mWakeup != null) {
initWakeupFeature();
/* listener will send back result later */
android.util.Log.i(TAG, "set the listeners...");
mWakeup.startListening(mWakeuperListener);
} else {
android.util.Log.e(TAG, "null wakeup obj, do nohting");
cb.error("error in start wakeup");
}
} else if(action.equals("stopWakeup")) {
android.util.Log.i(TAG, "Try Stop Wakeup");
if (mWakeup == null) {
mWakeup = VoiceWakeuper.getWakeuper();
}
if(mWakeup != null) {
mWakeup.stopListening();
mWakeup.destroy();
mWakeup = null;
cb.success("success stop wakeup");
} else {
android.util.Log.e(TAG, "null wakeup obj, do nohting");
cb.success("success stop null wakeup");
}
} else {
ret = false;
}
return ret;
}
private SpeechSynthesizer getSynthesizer() {
if (mSynth == null) {
mSynth = SpeechSynthesizer.createSynthesizer(
cordova.getActivity(), null);
}
return mSynth;
}
private int mapTheVoiceName(int index) {
int ret = 0;
if(index < 8 ) {
return index;
} else {
// User choose randomly voice name,
// so try a random
ret = (int) (Math.random() * 7);
if (ret > 7) {
ret = 7; // force value within 0~7
}
return ret;
}
}
private String parseListenResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject obj = items.getJSONObject(0);
ret.append(obj.getString("w"));
// for(int j = 0; j < items.length(); j++)
// JSONObject obj = items.getJSONObject(j);
// ret.append(obj.getString("w"));
}
} catch (Exception e) {
e.printStackTrace();
}
return ret.toString();
}
private int initWakeupFeature(){
mWakeup.setParameter(
SpeechConstant.IVW_THRESHOLD,
"0:20;1:20");
mWakeup.setParameter(
SpeechConstant.IVW_SST,
"wakeup");
/* FIXME and TODO - 1 means keep alive,
* if set with 0, the wakup action will auto-closed
* after a successful wakup
*
* Consider set this properly in the future.
*/
mWakeup.setParameter(SpeechConstant.KEEP_ALIVE,"0");
// suggest by Yong Xiaowen....
mWakeup.setParameter(SpeechConstant.AUDIO_SOURCE,
android.media.MediaRecorder.AudioSource.VOICE_RECOGNITION + "");
return 0;
}
private WakeuperListener mWakeuperListener = new WakeuperListener() {
@Override
public void onResult(WakeuperResult result) {
try{
String text = result.getResultString();
android.util.Log.e(TAG, "wakeup listen onResult:" + text);
JSONObject jsobj = new JSONObject(text);
android.util.Log.i(TAG, "The wakeup word id:" + jsobj.optString("id"));
mCb.success("COOL");
} catch (JSONException e) {
android.util.Log.e(TAG, "Exception meet on wakup listen");
}
}
@Override
public void onVolumeChanged(int volume) {
android.util.Log.e(TAG, "onVolumeChanged");
}
@Override
public void onError(SpeechError error) {
/* NOTE
* 10000~20000 are ranges in C/C++ Layer
* 20000~ are ranges in Java/Jar Layer
*/
android.util.Log.e(TAG, "wakeup error:" +
error.getErrorCode() + ", " +
error.getErrorDescription());
}
@Override
public void onBeginOfSpeech() {
android.util.Log.e(TAG, "onBeginOfSpeech");
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
android.util.Log.e(TAG, "onEvent");
if (com.iflytek.cloud.SpeechEvent.EVENT_IVW_RESULT == eventType) {
RecognizerResult reslut =
((RecognizerResult)obj.get(com.iflytek.cloud.SpeechEvent.KEY_EVENT_IVW_RESULT));
}
}
};
private int initAndroidCamera(JSONArray args, final CallbackContext cb) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
// Camera legacy interface
} else {
// camera2 new interface
}
/* FIXME - currently, still use legacy interface, in
* the future, SHOULD use newer camera2 interface
*/
String model = new android.os.Build().MODEL;
if(model.equals("MSM8916 for arm64") == false) {
/* FIXME - is it correct for QLove device? */
android.util.Log.e(TAG, "Sorry, only QLOVE DEVICE can do this.");
cb.error("Non-Qlove device");
return -1;
}
try{
int idx = args.getInt(0);
mPreviewFlag = args.getInt(1);
android.util.Log.i(TAG, "Try init [" + idx + "] camera, with " + mPreviewFlag + " preview flag");
mCamera = Camera.open(idx);
if(mCamera == null) {
android.util.Log.e(TAG, "null obj for opening camera");
cb.error("camera open got null obj");
} else {
cb.success("camera open OK");
}
} catch (JSONException ex) {
android.util.Log.e(TAG, "Exception in init");
cb.error("exception");
}
return 0;
}
private int cleanAndroidCamera(final CallbackContext cb) {
if(mCamera != null) {
mCamera.stopPreview(); // is it necessary?
mCamera.release();
mCamera = null;
}
cb.success("cleaned OK");
return 0;
}
private int startCameraPreview(JSONArray args, final CallbackContext cb) {
if(mCamera == null) {
android.util.Log.e(TAG, "null camera, do nothing");
cb.error("null camera obj");
return -1;
}
Camera.Parameters camParam = mCamera.getParameters();
/* below code suggested by Holly */
camParam.setPreviewSize(640, 480);
camParam.setPreviewFpsRange(20000, 20000);
mCamera.setParameters(camParam);
mCamera.setDisplayOrientation(90);
/* FIXME, seems we only can do this via oneshot way */
mCamera.setOneShotPreviewCallback(mCamCallback);
mCamPrevSize = mCamera.getParameters().getPreviewSize();
android.util.Log.e(TAG, "the preview w:"
+ mCamPrevSize.width + ", h:" + mCamPrevSize.height);
//let's do it!
mCamera.startPreview();
return 0;
}
private int stopCameraPreview() {
if(mCamera == null) {
android.util.Log.e(TAG, "already null camera obj");
return -1;
}
mCamera.stopPreview();
return 0;
}
private String imageBase64Format(String fn) throws FileNotFoundException, IOException {
String b64str = "";
File file = new File(fn);
int fileSize = (int)file.length();
byte[] binBuf = new byte[fileSize];
FileInputStream in = new FileInputStream(file);
DataInputStream ds = new DataInputStream(in);
ds.read(binBuf, 0, fileSize);
ds.close();
in.close();
b64str = Base64.encodeToString(binBuf, Base64.DEFAULT);
return b64str;
}
}
|
package org.voltdb.iv2;
import java.util.concurrent.ExecutionException;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.BinaryPayloadMessage;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.utils.CoreUtils;
import org.voltdb.BackendTarget;
import org.voltdb.CatalogContext;
import org.voltdb.CatalogSpecificPlanner;
import org.voltdb.ProcedureRunnerFactory;
import org.voltdb.iv2.Site;
import org.voltdb.CommandLog;
import org.voltdb.LoadedProcedureSet;
import org.voltdb.MemoryStats;
import org.voltdb.StarvationTracker;
import org.voltdb.StatsAgent;
import org.voltdb.SysProcSelector;
import org.voltdb.VoltDB;
/**
* Subclass of Initiator to manage single-partition operations.
* This class is primarily used for object construction and configuration plumbing;
* Try to avoid filling it with lots of other functionality.
*/
public abstract class BaseInitiator implements Initiator
{
VoltLogger tmLog = new VoltLogger("TM");
public static final String JSON_PARTITION_ID = "partitionId";
public static final String JSON_INITIATOR_HSID = "initiatorHSId";
// External references/config
protected final HostMessenger m_messenger;
protected final int m_partitionId;
protected final String m_zkMailboxNode;
protected final String m_whoami;
// Encapsulated objects
protected final Scheduler m_scheduler;
protected final InitiatorMailbox m_initiatorMailbox;
protected Term m_term = null;
protected Site m_executionSite = null;
protected Thread m_siteThread = null;
protected final RepairLog m_repairLog = new RepairLog();
public BaseInitiator(String zkMailboxNode, HostMessenger messenger, Integer partition,
Scheduler scheduler, String whoamiPrefix, StatsAgent agent)
{
m_zkMailboxNode = zkMailboxNode;
m_messenger = messenger;
m_partitionId = partition;
m_scheduler = scheduler;
RejoinProducer rejoinProducer =
new RejoinProducer(m_partitionId, scheduler.m_tasks);
m_initiatorMailbox = new InitiatorMailbox(
m_partitionId,
m_scheduler,
m_messenger,
m_repairLog,
rejoinProducer);
// Now publish the initiator mailbox to friends and family
m_messenger.createMailbox(null, m_initiatorMailbox);
rejoinProducer.setMailbox(m_initiatorMailbox);
m_scheduler.setMailbox(m_initiatorMailbox);
StarvationTracker st = new StarvationTracker(getInitiatorHSId());
m_scheduler.setStarvationTracker(st);
m_scheduler.setLock(m_initiatorMailbox);
agent.registerStatsSource(SysProcSelector.STARVATION,
getInitiatorHSId(),
st);
String partitionString = " ";
if (m_partitionId != -1) {
partitionString = " for partition " + m_partitionId + " ";
}
m_whoami = whoamiPrefix + " " +
CoreUtils.hsIdToString(getInitiatorHSId()) + partitionString;
}
protected void configureCommon(BackendTarget backend, String serializedCatalog,
CatalogContext catalogContext,
CatalogSpecificPlanner csp,
int numberOfPartitions,
VoltDB.START_ACTION startAction,
StatsAgent agent,
MemoryStats memStats,
CommandLog cl)
throws KeeperException, ExecutionException, InterruptedException
{
int snapshotPriority = 6;
if (catalogContext.cluster.getDeployment().get("deployment") != null) {
snapshotPriority = catalogContext.cluster.getDeployment().get("deployment").
getSystemsettings().get("systemsettings").getSnapshotpriority();
}
// demote rejoin to create for initiators that aren't rejoinable.
if (VoltDB.createForRejoin(startAction) && !isRejoinable()) {
startAction = VoltDB.START_ACTION.CREATE;
}
m_executionSite = new Site(m_scheduler.getQueue(),
m_initiatorMailbox.getHSId(),
backend, catalogContext,
serializedCatalog,
catalogContext.m_transactionId,
m_partitionId,
numberOfPartitions,
startAction,
snapshotPriority,
m_initiatorMailbox,
agent,
memStats);
ProcedureRunnerFactory prf = new ProcedureRunnerFactory();
prf.configure(m_executionSite, m_executionSite.m_sysprocContext);
LoadedProcedureSet procSet = new LoadedProcedureSet(
m_executionSite,
prf,
m_initiatorMailbox.getHSId(),
0, // this has no meaning
numberOfPartitions);
procSet.loadProcedures(catalogContext, backend, csp);
m_executionSite.setLoadedProcedures(procSet);
m_scheduler.setCommandLog(cl);
m_siteThread = new Thread(m_executionSite);
m_siteThread.start();
}
@Override
public void shutdown()
{
// set the shutdown flag on the site thread.
if (m_executionSite != null) {
m_executionSite.startShutdown();
}
try {
if (m_term != null) {
m_term.shutdown();
}
} catch (Exception e) {
tmLog.info("Exception during shutdown.", e );
}
try {
if (m_initiatorMailbox != null) {
m_initiatorMailbox.shutdown();
}
} catch (Exception e) {
tmLog.info("Exception during shutdown.", e);
}
}
@Override
public long getInitiatorHSId()
{
return m_initiatorMailbox.getHSId();
}
protected void acceptPromotion() throws Exception {
/*
* Notify all known client interfaces that the mastership has changed
* for the specified partition and that no responses from previous masters will be forthcoming
*/
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key(JSON_PARTITION_ID).value(m_partitionId);
stringer.key(JSON_INITIATOR_HSID).value(m_initiatorMailbox.getHSId());
stringer.endObject();
BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], stringer.toString().getBytes("UTF-8"));
for (Integer hostId : m_messenger.getLiveHostIds()) {
m_messenger.send(CoreUtils.getHSIdFromHostAndSite(hostId, HostMessenger.CLIENT_INTERFACE_SITE_ID), bpm);
}
}
}
|
package integration;
import com.codeborne.selenide.Configuration;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import static com.codeborne.selenide.Selectors.byText;
import static com.codeborne.selenide.Selenide.$;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class FileDownloadTest extends IntegrationTest {
File folder = new File(Configuration.reportsFolder);
@Before
public void setUp() {
openFile("page_with_uploads.html");
}
@Test
public void downloadsFiles_usingHrefAttribute() throws IOException {
File downloadedFile = $(byText("Download me")).download();
assertEquals("hello_world.txt", downloadedFile.getName());
assertEquals("Hello, WinRar!", FileUtils.readFileToString(downloadedFile, "UTF-8"));
assertTrue(downloadedFile.getAbsolutePath().startsWith(folder.getAbsolutePath()));
}
@Test(expected = FileNotFoundException.class)
public void downloadMissingFile() throws IOException {
$(byText("Download missing file")).download();
}
@Test(expected = IllegalArgumentException.class)
public void throwsIllegalArgumentException_ifElementHasNoHrefAttribute() throws FileNotFoundException {
$("h1").download();
}
}
|
package org.voltdb.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.hadoop_voltpatches.util.PureJavaCrc32;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONException;
import org.mindrot.BCrypt;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.VoltZK;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.CatalogType;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.ConnectorProperty;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.ConstraintRef;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Deployment;
import org.voltdb.catalog.Group;
import org.voltdb.catalog.GroupRef;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.PlanFragment;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.catalog.Statement;
import org.voltdb.catalog.Systemsettings;
import org.voltdb.catalog.Table;
import org.voltdb.compiler.ClusterConfig;
import org.voltdb.compiler.deploymentfile.AdminModeType;
import org.voltdb.compiler.deploymentfile.ClusterType;
import org.voltdb.compiler.deploymentfile.CommandLogType;
import org.voltdb.compiler.deploymentfile.CommandLogType.Frequency;
import org.voltdb.compiler.deploymentfile.DeploymentType;
import org.voltdb.compiler.deploymentfile.ExportConfigurationType;
import org.voltdb.compiler.deploymentfile.ExportType;
import org.voltdb.compiler.deploymentfile.HeartbeatType;
import org.voltdb.compiler.deploymentfile.HttpdType;
import org.voltdb.compiler.deploymentfile.PartitionDetectionType;
import org.voltdb.compiler.deploymentfile.PathEntry;
import org.voltdb.compiler.deploymentfile.PathsType;
import org.voltdb.compiler.deploymentfile.PropertyType;
import org.voltdb.compiler.deploymentfile.SecurityType;
import org.voltdb.compiler.deploymentfile.ServerExportEnum;
import org.voltdb.compiler.deploymentfile.SnapshotType;
import org.voltdb.compiler.deploymentfile.SystemSettingsType;
import org.voltdb.compiler.deploymentfile.SystemSettingsType.Temptables;
import org.voltdb.compiler.deploymentfile.UsersType;
import org.voltdb.compiler.deploymentfile.UsersType.User;
import org.voltdb.compilereport.IndexAnnotation;
import org.voltdb.compilereport.ProcedureAnnotation;
import org.voltdb.compilereport.StatementAnnotation;
import org.voltdb.compilereport.TableAnnotation;
import org.voltdb.export.ExportDataProcessor;
import org.voltdb.expressions.AbstractExpression;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.types.ConstraintType;
import org.voltdb.types.IndexType;
import org.xml.sax.SAXException;
import com.google.common.base.Charsets;
public abstract class CatalogUtil {
private static final VoltLogger hostLog = new VoltLogger("HOST");
public static final String CATALOG_FILENAME = "catalog.txt";
public static final String CATALOG_BUILDINFO_FILENAME = "buildinfo.txt";
/**
* Load a catalog from the jar bytes.
*
* @param catalogBytes
* @param log
* @return The serialized string of the catalog content.
* @throws Exception
* If the catalog cannot be loaded because it's incompatible, or
* if there is no version information in the catalog.
*/
public static String loadCatalogFromJar(byte[] catalogBytes, VoltLogger log) throws IOException {
assert(catalogBytes != null);
String serializedCatalog = null;
String voltVersionString = null;
InMemoryJarfile jarfile = new InMemoryJarfile(catalogBytes);
byte[] serializedCatalogBytes = jarfile.get(CATALOG_FILENAME);
if (null == serializedCatalogBytes) {
throw new IOException("Database catalog not found - please build your application using the current version of VoltDB.");
}
serializedCatalog = new String(serializedCatalogBytes, "UTF-8");
// Get Volt version string
byte[] buildInfoBytes = jarfile.get(CATALOG_BUILDINFO_FILENAME);
if (buildInfoBytes == null) {
throw new IOException("Catalog build information not found - please build your application using the current version of VoltDB.");
}
String buildInfo = new String(buildInfoBytes, "UTF-8");
String[] buildInfoLines = buildInfo.split("\n");
if (buildInfoLines.length != 5) {
throw new IOException("Catalog built with an old version of VoltDB - please build your application using the current version of VoltDB.");
}
voltVersionString = buildInfoLines[0].trim();
// Check if it's compatible
if (!isCatalogCompatible(voltVersionString)) {
throw new IOException("Catalog compiled with '" + voltVersionString + "' is not compatible with the current version of VoltDB (" +
VoltDB.instance().getVersionString() + ") - " + " please build your application using the current version of VoltDB.");
}
return serializedCatalog;
}
/**
* Serialize a file into bytes. Used to serialize catalog and deployment
* file for UpdateApplicationCatalog on the client.
*
* @param path
* @return a byte array of the file
* @throws IOException
* If there are errors reading the file
*/
public static byte[] toBytes(File path) throws IOException {
FileInputStream fin = new FileInputStream(path);
byte[] buffer = new byte[(int) fin.getChannel().size()];
try {
if (fin.read(buffer) == -1) {
throw new IOException("File " + path.getAbsolutePath() + " is empty");
}
} finally {
fin.close();
}
return buffer;
}
/**
* Get a unique id for a plan fragment by munging the indices of it's parents
* and grandparents in the catalog.
*
* @param frag Catalog fragment to identify
* @return unique id for fragment
*/
public static long getUniqueIdForFragment(PlanFragment frag) {
long retval = 0;
CatalogType parent = frag.getParent();
retval = ((long) parent.getParent().getRelativeIndex()) << 32;
retval += ((long) parent.getRelativeIndex()) << 16;
retval += frag.getRelativeIndex();
return retval;
}
/**
*
* @param catalogTable
* @return An empty table with the same schema as a given catalog table.
*/
public static VoltTable getVoltTable(Table catalogTable) {
List<Column> catalogColumns = CatalogUtil.getSortedCatalogItems(catalogTable.getColumns(), "index");
VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[catalogColumns.size()];
int i = 0;
for (Column catCol : catalogColumns) {
columns[i++] = new VoltTable.ColumnInfo(catCol.getTypeName(), VoltType.get((byte)catCol.getType()));
}
return new VoltTable(columns);
}
/**
* Given a set of catalog items, return a sorted list of them, sorted by
* the value of a specified field. The field is specified by name. If the
* field doesn't exist, trip an assertion. This is primarily used to sort
* a table's columns or a procedure's parameters.
*
* @param <T> The type of item to sort.
* @param items The set of catalog items.
* @param sortFieldName The name of the field to sort on.
* @return A list of catalog items, sorted on the specified field.
*/
public static <T extends CatalogType> List<T> getSortedCatalogItems(CatalogMap<T> items, String sortFieldName) {
assert(items != null);
assert(sortFieldName != null);
// build a treemap based on the field value
TreeMap<Object, T> map = new TreeMap<Object, T>();
boolean hasField = false;
for (T item : items) {
// check the first time through for the field
if (hasField == false)
hasField = item.getFields().contains(sortFieldName);
assert(hasField == true);
map.put(item.getField(sortFieldName), item);
}
// create a sorted list from the map
ArrayList<T> retval = new ArrayList<T>();
for (T item : map.values()) {
retval.add(item);
}
return retval;
}
/**
* For a given Table catalog object, return the PrimaryKey Index catalog object
* @param catalogTable
* @return The index representing the primary key.
* @throws Exception if the table does not define a primary key
*/
public static Index getPrimaryKeyIndex(Table catalogTable) throws Exception {
// We first need to find the pkey constraint
Constraint catalog_constraint = null;
for (Constraint c : catalogTable.getConstraints()) {
if (c.getType() == ConstraintType.PRIMARY_KEY.getValue()) {
catalog_constraint = c;
break;
}
}
if (catalog_constraint == null) {
throw new Exception("ERROR: Table '" + catalogTable.getTypeName() + "' does not have a PRIMARY KEY constraint");
}
// And then grab the index that it is using
return (catalog_constraint.getIndex());
}
/**
* Return all the of the primary key columns for a particular table
* If the table does not have a primary key, then the returned list will be empty
* @param catalogTable
* @return An ordered list of the primary key columns
*/
public static Collection<Column> getPrimaryKeyColumns(Table catalogTable) {
Collection<Column> columns = new ArrayList<Column>();
Index catalog_idx = null;
try {
catalog_idx = CatalogUtil.getPrimaryKeyIndex(catalogTable);
} catch (Exception ex) {
// IGNORE
return (columns);
}
assert(catalog_idx != null);
for (ColumnRef catalog_col_ref : getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
columns.add(catalog_col_ref.getColumn());
}
return (columns);
}
/**
* Convert a Table catalog object into the proper SQL DDL, including all indexes,
* constraints, and foreign key references.
* @param catalog_tbl
* @return SQL Schema text representing the table.
*/
public static String toSchema(Table catalog_tbl) {
assert(!catalog_tbl.getColumns().isEmpty());
final String spacer = " ";
Set<Index> skip_indexes = new HashSet<Index>();
Set<Constraint> skip_constraints = new HashSet<Constraint>();
String ret = "CREATE TABLE " + catalog_tbl.getTypeName() + " (";
// Columns
String add = "\n";
for (Column catalog_col : CatalogUtil.getSortedCatalogItems(catalog_tbl.getColumns(), "index")) {
VoltType col_type = VoltType.get((byte)catalog_col.getType());
// this next assert would be great if we dealt with default values well
//assert(! ((catalog_col.getDefaultvalue() == null) && (catalog_col.getNullable() == false) ) );
ret += add + spacer + catalog_col.getTypeName() + " " +
col_type.toSQLString() +
(col_type == VoltType.STRING && catalog_col.getSize() > 0 ? "(" + catalog_col.getSize() + ")" : "");
// Default value
String defaultvalue = catalog_col.getDefaultvalue();
//VoltType defaulttype = VoltType.get((byte)catalog_col.getDefaulttype());
boolean nullable = catalog_col.getNullable();
// TODO: Shouldn't have to check whether the string contains "null"
if (defaultvalue != null && defaultvalue.toLowerCase().equals("null") && nullable) {
defaultvalue = null;
}
else { // XXX: if (defaulttype != VoltType.VOLTFUNCTION) {
// TODO: Escape strings properly
defaultvalue = "'" + defaultvalue + "'";
}
ret += " DEFAULT " + (defaultvalue != null ? defaultvalue : "NULL") +
(!nullable ? " NOT NULL" : "");
// Single-column constraints
for (ConstraintRef catalog_const_ref : catalog_col.getConstraints()) {
Constraint catalog_const = catalog_const_ref.getConstraint();
ConstraintType const_type = ConstraintType.get(catalog_const.getType());
// Check if there is another column in our table with the same constraint
// If there is, then we need to add it to the end of the table definition
boolean found = false;
for (Column catalog_other_col : catalog_tbl.getColumns()) {
if (catalog_other_col.equals(catalog_col)) continue;
if (catalog_other_col.getConstraints().getIgnoreCase(catalog_const.getTypeName()) != null) {
found = true;
break;
}
}
if (!found) {
switch (const_type) {
case FOREIGN_KEY: {
Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
Column catalog_fkey_col = null;
for (ColumnRef ref : catalog_const.getForeignkeycols()) {
catalog_fkey_col = ref.getColumn();
break; // Nasty hack to get first item
}
assert(catalog_fkey_col != null);
ret += " REFERENCES " + catalog_fkey_tbl.getTypeName() + " (" + catalog_fkey_col.getTypeName() + ")";
skip_constraints.add(catalog_const);
break;
}
default:
// Nothing for now
}
}
}
add = ",\n";
}
// Constraints
for (Constraint catalog_const : catalog_tbl.getConstraints()) {
if (skip_constraints.contains(catalog_const)) continue;
ConstraintType const_type = ConstraintType.get(catalog_const.getType());
// Primary Keys / Unique Constraints
if (const_type == ConstraintType.PRIMARY_KEY || const_type == ConstraintType.UNIQUE) {
Index catalog_idx = catalog_const.getIndex();
String idx_suffix = IndexType.getSQLSuffix(catalog_idx.getType());
ret += add + spacer +
(!idx_suffix.isEmpty() ? "CONSTRAINT " + catalog_const.getTypeName() + " " : "") +
(const_type == ConstraintType.PRIMARY_KEY ? "PRIMARY KEY" : "UNIQUE") + " (";
String col_add = "";
for (ColumnRef catalog_colref : CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
ret += col_add + catalog_colref.getColumn().getTypeName();
col_add = ", ";
} // FOR
ret += ")";
skip_indexes.add(catalog_idx);
// Foreign Key
} else if (const_type == ConstraintType.FOREIGN_KEY) {
Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
String col_add = "";
String our_columns = "";
String fkey_columns = "";
for (ColumnRef catalog_colref : catalog_const.getForeignkeycols()) {
// The name of the ColumnRef is the column in our base table
Column our_column = catalog_tbl.getColumns().getIgnoreCase(catalog_colref.getTypeName());
assert(our_column != null);
our_columns += col_add + our_column.getTypeName();
Column fkey_column = catalog_colref.getColumn();
assert(fkey_column != null);
fkey_columns += col_add + fkey_column.getTypeName();
col_add = ", ";
}
ret += add + spacer + "CONSTRAINT " + catalog_const.getTypeName() + " " +
"FOREIGN KEY (" + our_columns + ") " +
"REFERENCES " + catalog_fkey_tbl.getTypeName() + " (" + fkey_columns + ")";
}
skip_constraints.add(catalog_const);
}
ret += "\n);\n";
// All other Indexes
for (Index catalog_idx : catalog_tbl.getIndexes()) {
if (skip_indexes.contains(catalog_idx)) continue;
ret += "CREATE INDEX " + catalog_idx.getTypeName() +
" ON " + catalog_tbl.getTypeName() + " (";
add = "";
String jsonstring = catalog_idx.getExpressionsjson();
if (jsonstring.isEmpty()) {
for (ColumnRef catalog_colref : CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
ret += add + catalog_colref.getColumn().getTypeName();
add = ", ";
}
} else {
List<AbstractExpression> indexedExprs = null;
try {
indexedExprs = AbstractExpression.fromJSONArrayString(jsonstring);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (AbstractExpression expr : indexedExprs) {
ret += add + expr.explain(catalog_tbl.getTypeName());
add = ", ";
}
}
ret += ");\n";
}
return ret;
}
/**
* Return true if a table is a streamed / export table
* This function is duplicated in CatalogUtil.h
* @param database
* @param table
* @return true if a table is export or false otherwise
*/
public static boolean isTableExportOnly(org.voltdb.catalog.Database database,
org.voltdb.catalog.Table table)
{
// no export, no export only tables
if (database.getConnectors().size() == 0) {
return false;
}
// there is one well-known-named connector
org.voltdb.catalog.Connector connector = database.getConnectors().get("0");
// iterate the connector tableinfo list looking for tableIndex
// tableInfo has a reference to a table - can compare the reference
// to the desired table by looking at the relative index. ick.
for (org.voltdb.catalog.ConnectorTableInfo tableInfo : connector.getTableinfo()) {
if (tableInfo.getTable().getRelativeIndex() == table.getRelativeIndex()) {
return tableInfo.getAppendonly();
}
}
return false;
}
/**
* Return true if a table is the source table for a materialized view.
*/
public static boolean isTableMaterializeViewSource(org.voltdb.catalog.Database database,
org.voltdb.catalog.Table table)
{
CatalogMap<Table> tables = database.getTables();
for (Table t : tables) {
Table matsrc = t.getMaterializer();
if ((matsrc != null) && (matsrc.getRelativeIndex() == table.getRelativeIndex())) {
return true;
}
}
return false;
}
/**
* Check if a catalog compiled with the given version of VoltDB is
* compatible with the current version of VoltDB.
*
* @param catalogVersionStr
* The version string of the VoltDB that compiled the catalog.
* @return true if it's compatible, false otherwise.
*/
public static boolean isCatalogCompatible(String catalogVersionStr)
{
if (catalogVersionStr == null || catalogVersionStr.isEmpty()) {
return false;
}
//Check that it is a properly formed verstion string
int[] catalogVersion = MiscUtils.parseVersionString(catalogVersionStr);
if (catalogVersion == null) {
throw new IllegalArgumentException("Invalid version string " + catalogVersionStr);
}
if (!catalogVersionStr.equals(VoltDB.instance().getVersionString())) {
return false;
}
return true;
}
public static long compileDeploymentAndGetCRC(Catalog catalog, String deploymentURL, boolean crashOnFailedValidation) {
DeploymentType deployment = CatalogUtil.parseDeployment(deploymentURL);
if (deployment == null) {
return -1;
}
return compileDeploymentAndGetCRC(catalog, deployment, crashOnFailedValidation);
}
public static long compileDeploymentStringAndGetCRC(Catalog catalog, String deploymentString, boolean crashOnFailedValidation) {
DeploymentType deployment = CatalogUtil.parseDeploymentFromString(deploymentString);
if (deployment == null) {
return -1;
}
return compileDeploymentAndGetCRC(catalog, deployment, crashOnFailedValidation);
}
/**
* Parse the deployment.xml file and add its data into the catalog.
* @param catalog Catalog to be updated.
* @param deployment Parsed representation of the deployment.xml file.
* @param crashOnFailedValidation
* @param printLog Whether or not to print the cluster configuration.
* @return CRC of the deployment contents (>0) or -1 on failure.
*/
public static long compileDeploymentAndGetCRC(Catalog catalog,
DeploymentType deployment,
boolean crashOnFailedValidation)
{
if (!validateDeployment(catalog, deployment)) {
return -1;
}
// add our hacky Deployment to the catalog
catalog.getClusters().get("cluster").getDeployment().add("deployment");
// set the cluster info
setClusterInfo(catalog, deployment);
//Set the snapshot schedule
setSnapshotInfo( catalog, deployment.getSnapshot());
//Set enable security
setSecurityEnabled(catalog, deployment.getSecurity());
//set path and path overrides
// NOTE: this must be called *AFTER* setClusterInfo and setSnapshotInfo
// because path locations for snapshots and partition detection don't
// exist in the catalog until after those portions of the deployment
// file are handled.
setPathsInfo(catalog, deployment.getPaths(), crashOnFailedValidation);
// set the users info
setUsersInfo(catalog, deployment.getUsers());
// set the HTTPD info
setHTTPDInfo(catalog, deployment.getHttpd());
setExportInfo( catalog, deployment.getExport());
setCommandLogInfo( catalog, deployment.getCommandlog());
return getDeploymentCRC(deployment);
}
/*
* Command log element is created in setPathsInfo
*/
private static void setCommandLogInfo(Catalog catalog, CommandLogType commandlog) {
int fsyncInterval = 200;
int maxTxnsBeforeFsync = Integer.MAX_VALUE;
boolean enabled = false;
// enterprise voltdb defaults to CL enabled if not specified in the XML
if (MiscUtils.isPro()) {
enabled = true;
}
boolean sync = false;
int logSizeMb = 1024;
org.voltdb.catalog.CommandLog config = catalog.getClusters().get("cluster").getLogconfig().get("log");
if (commandlog != null) {
logSizeMb = commandlog.getLogsize();
sync = commandlog.isSynchronous();
enabled = commandlog.isEnabled();
Frequency freq = commandlog.getFrequency();
if (freq != null) {
long maxTxnsBeforeFsyncTemp = freq.getTransactions();
if (maxTxnsBeforeFsyncTemp < 1 || maxTxnsBeforeFsyncTemp > Integer.MAX_VALUE) {
throw new RuntimeException("Invalid command log max txns before fsync (" + maxTxnsBeforeFsync
+ ") specified. Supplied value must be between 1 and (2^31 - 1) txns");
}
maxTxnsBeforeFsync = (int)maxTxnsBeforeFsyncTemp;
fsyncInterval = freq.getTime();
if (fsyncInterval < 1 | fsyncInterval > 5000) {
throw new RuntimeException("Invalid command log fsync interval(" + fsyncInterval
+ ") specified. Supplied value must be between 1 and 5000 milliseconds");
}
}
}
config.setEnabled(enabled);
config.setSynchronous(sync);
config.setFsyncinterval(fsyncInterval);
config.setMaxtxns(maxTxnsBeforeFsync);
config.setLogsize(logSizeMb);
}
public static long getDeploymentCRC(String deploymentURL) {
DeploymentType deployment = parseDeployment(deploymentURL);
// wasn't a valid xml deployment file
if (deployment == null) {
hostLog.error("Not a valid XML deployment file at URL: " + deploymentURL);
return -1;
}
return getDeploymentCRC(deployment);
}
/**
* This code is not really tenable, and should be replaced with some
* XML normalization code, but for now it should work and be pretty
* tolerant of XML documents with different formatting for the same
* values.
* @return A positive CRC for the deployment contents
*/
static long getDeploymentCRC(DeploymentType deployment) {
StringBuilder sb = new StringBuilder(1024);
sb.append(" CLUSTER ");
ClusterType ct = deployment.getCluster();
sb.append(ct.getHostcount()).append(",");
sb.append(ct.getKfactor()).append(",");
sb.append(ct.getSitesperhost()).append(",");
sb.append(" PARTITIONDETECTION ");
PartitionDetectionType pdt = deployment.getPartitionDetection();
if (pdt != null) {
sb.append(pdt.isEnabled()).append(",");
PartitionDetectionType.Snapshot st = pdt.getSnapshot();
if (st != null) {
sb.append(st.getPrefix()).append(",");
}
}
sb.append(" SECURITY ");
SecurityType st = deployment.getSecurity();
if (st != null) {
sb.append(st.isEnabled());
}
sb.append(" ADMINMODE ");
AdminModeType amt = deployment.getAdminMode();
if (amt != null)
{
sb.append(amt.getPort()).append(",");
sb.append(amt.isAdminstartup()).append("\n");
}
sb.append(" HEARTBEATCONFIG ");
HeartbeatType hbt = deployment.getHeartbeat();
if (hbt != null)
{
sb.append(hbt.getTimeout()).append("\n");
}
sb.append(" USERS ");
UsersType ut = deployment.getUsers();
if (ut != null) {
List<User> users = ut.getUser();
for (User u : users) {
sb.append(" USER ");
sb.append(u.getName()).append(",");
sb.append(Arrays.toString(mergeUserRoles(u).toArray()));
sb.append(",").append(u.getPassword()).append(",");
sb.append(u.isPlaintext()).append(",");
}
}
sb.append("\n");
sb.append(" HTTPD ");
HttpdType ht = deployment.getHttpd();
if (ht != null) {
HttpdType.Jsonapi jt = ht.getJsonapi();
if (jt != null) {
sb.append(jt.isEnabled()).append(",");
}
sb.append(ht.isEnabled());
sb.append(ht.getPort());
}
sb.append(" SYSTEMSETTINGS ");
SystemSettingsType sst = deployment.getSystemsettings();
if (sst != null)
{
sb.append(" TEMPTABLES ");
Temptables ttt = sst.getTemptables();
if (ttt != null)
{
sb.append(ttt.getMaxsize()).append("\n");
}
}
sb.append(" EXPORT ");
ExportType export = deployment.getExport();
if( export != null) {
sb.append(" ENABLE ").append(export.isEnabled());
// mimic what is done when the catalog is built, which
// ignores anything else within the export XML stanza
// when enabled is false
if (export.isEnabled()) {
ServerExportEnum exportTarget = export.getTarget();
if (exportTarget != null) {
sb.append( "TARGET ").append(exportTarget.name());
if (exportTarget.name().equalsIgnoreCase("CUSTOM")) {
sb.append(" EXPORTCONNECTORCLASS ").append(export.getExportconnectorclass());
}
}
ExportConfigurationType config = export.getConfiguration();
if (config != null) {
List<PropertyType> props = config.getProperty();
if( props != null && !props.isEmpty()) {
sb.append(" CONFIGURATION");
int propCnt = 0;
for( PropertyType prop: props) {
if( propCnt++ > 0) {
sb.append(",");
}
sb.append(" ").append(prop.getName());
sb.append(": ").append(prop.getValue());
}
}
}
}
sb.append("\n");
}
byte[] data = null;
try {
data = sb.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
hostLog.error("CRCing deployment file to determine" +
" compatibility and determined deployment file is"+
" not valid UTF-8. File must be UTF-8 encoded.");
data = new byte[]{0x0}; // should generate a CRC mismatch.
}
PureJavaCrc32 crc = new PureJavaCrc32();
crc.update(data);
long retval = crc.getValue();
return Math.abs(retval);
}
/**
* Parses the deployment XML file.
* @param deploymentURL Path to the deployment.xml file.
* @return a reference to the root <deployment> element.
*/
public static DeploymentType parseDeployment(String deploymentURL) {
// get the URL/path for the deployment and prep an InputStream
InputStream deployIS = null;
try {
URL deployURL = new URL(deploymentURL);
deployIS = deployURL.openStream();
} catch (MalformedURLException ex) {
// Invalid URL. Try as a file.
try {
deployIS = new FileInputStream(deploymentURL);
} catch (FileNotFoundException e) {
deployIS = null;
}
} catch (IOException ioex) {
deployIS = null;
}
// make sure the file exists
if (deployIS == null) {
hostLog.error("Could not locate deployment info at given URL: " + deploymentURL);
return null;
} else {
hostLog.info("URL of deployment info: " + deploymentURL);
}
return getDeployment(deployIS);
}
/**
* Parses the deployment XML string.
* @param deploymentString The deployment file content.
* @return a reference to the root <deployment> element.
*/
public static DeploymentType parseDeploymentFromString(String deploymentString) {
ByteArrayInputStream byteIS;
try {
byteIS = new ByteArrayInputStream(deploymentString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.warn("Unable to read deployment string: " + e.getMessage());
return null;
}
// get deployment info from xml file
return getDeployment(byteIS);
}
/**
* Get a reference to the root <deployment> element from the deployment.xml file.
* @param deployIS
* @return Returns a reference to the root <deployment> element.
*/
@SuppressWarnings("unchecked")
public static DeploymentType getDeployment(InputStream deployIS) {
try {
JAXBContext jc = JAXBContext.newInstance("org.voltdb.compiler.deploymentfile");
// This schema shot the sheriff.
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(VoltDB.class.getResource("compiler/DeploymentFileSchema.xsd"));
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);
JAXBElement<DeploymentType> result =
(JAXBElement<DeploymentType>) unmarshaller.unmarshal(deployIS);
DeploymentType deployment = result.getValue();
return deployment;
} catch (JAXBException e) {
// Convert some linked exceptions to more friendly errors.
if (e.getLinkedException() instanceof java.io.FileNotFoundException) {
hostLog.error(e.getLinkedException().getMessage());
return null;
} else if (e.getLinkedException() instanceof org.xml.sax.SAXParseException) {
hostLog.error("Error schema validating deployment.xml file. " + e.getLinkedException().getMessage());
return null;
} else {
throw new RuntimeException(e);
}
} catch (SAXException e) {
hostLog.error("Error schema validating deployment.xml file. " + e.getMessage());
return null;
}
}
/**
* Validate the contents of the deployment.xml file. This is for things like making sure users aren't being added to
* non-existent groups, not for validating XML syntax.
* @param catalog Catalog to be validated against.
* @param deployment Reference to root <deployment> element of deployment file to be validated.
* @return Returns true if the deployment file is valid.
*/
private static boolean validateDeployment(Catalog catalog, DeploymentType deployment) {
if (deployment.getUsers() == null) {
return true;
}
Cluster cluster = catalog.getClusters().get("cluster");
Database database = cluster.getDatabases().get("database");
Set<String> validGroups = new HashSet<String>();
for (Group group : database.getGroups()) {
validGroups.add(group.getTypeName());
}
for (UsersType.User user : deployment.getUsers().getUser()) {
if (user.getGroups() == null && user.getRoles() == null)
continue;
for (String group : mergeUserRoles(user)) {
if (!validGroups.contains(group)) {
hostLog.error("Cannot assign user \"" + user.getName() + "\" to non-existent group \"" + group +
"\"");
return false;
}
}
}
return true;
}
/**
* Set cluster info in the catalog.
* @param leader The leader hostname
* @param catalog The catalog to be updated.
* @param printLog Whether or not to print cluster configuration.
*/
private static void setClusterInfo(Catalog catalog, DeploymentType deployment) {
ClusterType cluster = deployment.getCluster();
int hostCount = cluster.getHostcount();
int sitesPerHost = cluster.getSitesperhost();
int kFactor = cluster.getKfactor();
ClusterConfig config = new ClusterConfig(hostCount, sitesPerHost, kFactor);
if (!config.validate()) {
hostLog.error(config.getErrorMsg());
} else {
Cluster catCluster = catalog.getClusters().get("cluster");
// copy the deployment info that is currently not recorded anywhere else
Deployment catDeploy = catCluster.getDeployment().get("deployment");
catDeploy.setHostcount(hostCount);
catDeploy.setSitesperhost(sitesPerHost);
catDeploy.setKfactor(kFactor);
// copy partition detection configuration from xml to catalog
String defaultPPDPrefix = "partition_detection";
if (deployment.getPartitionDetection() != null) {
if (deployment.getPartitionDetection().isEnabled()) {
catCluster.setNetworkpartition(true);
CatalogMap<SnapshotSchedule> faultsnapshots = catCluster.getFaultsnapshots();
SnapshotSchedule sched = faultsnapshots.add("CLUSTER_PARTITION");
if (deployment.getPartitionDetection().getSnapshot() != null) {
sched.setPrefix(deployment.getPartitionDetection().getSnapshot().getPrefix());
}
else {
sched.setPrefix(defaultPPDPrefix);
}
}
else {
catCluster.setNetworkpartition(false);
}
}
else {
// Default partition detection on
catCluster.setNetworkpartition(true);
CatalogMap<SnapshotSchedule> faultsnapshots = catCluster.getFaultsnapshots();
SnapshotSchedule sched = faultsnapshots.add("CLUSTER_PARTITION");
sched.setPrefix(defaultPPDPrefix);
}
// copy admin mode configuration from xml to catalog
if (deployment.getAdminMode() != null)
{
catCluster.setAdminport(deployment.getAdminMode().getPort());
catCluster.setAdminstartup(deployment.getAdminMode().isAdminstartup());
}
else
{
// encode the default values
catCluster.setAdminport(VoltDB.DEFAULT_ADMIN_PORT);
catCluster.setAdminstartup(false);
}
setSystemSettings(deployment, catDeploy);
if (deployment.getHeartbeat() != null)
{
catCluster.setHeartbeattimeout(deployment.getHeartbeat().getTimeout());
}
else
{
// default to 10 seconds
catCluster.setHeartbeattimeout(10);
}
}
}
private static void setSystemSettings(DeploymentType deployment,
Deployment catDeployment)
{
// Create catalog Systemsettings
Systemsettings syssettings =
catDeployment.getSystemsettings().add("systemsettings");
int maxtemptablesize = 100;
int snapshotpriority = 6;
if (deployment.getSystemsettings() != null)
{
Temptables temptables = deployment.getSystemsettings().getTemptables();
if (temptables != null)
{
maxtemptablesize = temptables.getMaxsize();
}
SystemSettingsType.Snapshot snapshot = deployment.getSystemsettings().getSnapshot();
if (snapshot != null) {
snapshotpriority = snapshot.getPriority();
}
}
syssettings.setMaxtemptablesize(maxtemptablesize);
syssettings.setSnapshotpriority(snapshotpriority);
}
private static void validateDirectory(String type, File path, boolean crashOnFailedValidation) {
String error = null;
do {
if (!path.exists()) {
error = "Specified " + type + " \"" + path + "\" does not exist"; break;
}
if (!path.isDirectory()) {
error = "Specified " + type + " \"" + path + "\" is not a directory"; break;
}
if (!path.canRead()) {
error = "Specified " + type + " \"" + path + "\" is not readable"; break;
}
if (!path.canWrite()) {
error = "Specified " + type + " \"" + path + "\" is not writable"; break;
}
if (!path.canExecute()) {
error = "Specified " + type + " \"" + path + "\" is not executable"; break;
}
} while(false);
if (error != null) {
if (crashOnFailedValidation) {
VoltDB.crashLocalVoltDB(error, false, null);
} else {
hostLog.warn(error);
}
}
}
/**
* Set deployment time settings for export
* @param catalog The catalog to be updated.
* @param exportsType A reference to the <exports> element of the deployment.xml file.
*/
private static void setExportInfo(Catalog catalog, ExportType exportType) {
if (exportType == null) {
return;
}
boolean adminstate = exportType.isEnabled();
// on-server export always uses the gues processor
String connector = "org.voltdb.export.processors.GuestProcessor";
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
org.voltdb.catalog.Connector catconn = db.getConnectors().get("0");
if (catconn == null) {
if (adminstate) {
hostLog.info("Export configuration enabled in deployment file however no export " +
"tables are present in the project file. Export disabled.");
}
return;
}
catconn.setLoaderclass(connector);
catconn.setEnabled(adminstate);
String exportClientClassName = null;
switch(exportType.getTarget()) {
case FILE: exportClientClassName = "org.voltdb.exportclient.ExportToFileClient"; break;
case JDBC: exportClientClassName = "org.voltdb.exportclient.JDBCExportClient"; break;
//Validate that we can load the class.
case CUSTOM:
try {
CatalogUtil.class.getClassLoader().loadClass(exportType.getExportconnectorclass());
exportClientClassName = exportType.getExportconnectorclass();
}
catch (ClassNotFoundException ex) {
hostLog.error(
"Custom Export failed to configure, failed to load " +
" export plugin class: " + exportType.getExportconnectorclass() +
" Disabling export.");
exportType.setEnabled(false);
return;
}
break;
}
// this is OK as the deployment file XML schema does not allow for
// export configuration property names that begin with underscores
if (exportClientClassName != null && exportClientClassName.trim().length() > 0) {
ConnectorProperty prop = catconn.getConfig().add(ExportDataProcessor.EXPORT_TO_TYPE);
prop.setName(ExportDataProcessor.EXPORT_TO_TYPE);
//Override for tests
String dexportClientClassName = System.getProperty("exportclass", exportClientClassName);
prop.setValue(dexportClientClassName);
}
ExportConfigurationType exportConfiguration = exportType.getConfiguration();
if (exportConfiguration != null) {
List<PropertyType> configProperties = exportConfiguration.getProperty();
if (configProperties != null && ! configProperties.isEmpty()) {
for( PropertyType configProp: configProperties) {
ConnectorProperty prop = catconn.getConfig().add(configProp.getName());
prop.setName(configProp.getName());
prop.setValue(configProp.getValue());
}
}
}
if (!adminstate) {
hostLog.info("Export configuration is present and is " +
"configured to be disabled. Export will be disabled.");
}
}
/**
* Set the security setting in the catalog from the deployment file
* @param catalog the catalog to be updated
* @param securityEnabled security element of the deployment xml
*/
private static void setSecurityEnabled( Catalog catalog, SecurityType securityEnabled) {
Cluster cluster = catalog.getClusters().get("cluster");
boolean enabled = false;
if (securityEnabled != null) {
enabled = securityEnabled.isEnabled();
}
cluster.setSecurityenabled(enabled);
}
/**
* Set the auto-snapshot settings in the catalog from the deployment file
* @param catalog The catalog to be updated.
* @param snapshot A reference to the <snapshot> element of the deployment.xml file.
*/
private static void setSnapshotInfo(Catalog catalog, SnapshotType snapshotSettings) {
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
SnapshotSchedule schedule = db.getSnapshotschedule().add("default");
if (snapshotSettings != null)
{
schedule.setEnabled(snapshotSettings.isEnabled());
String frequency = snapshotSettings.getFrequency();
if (!frequency.endsWith("s") &&
!frequency.endsWith("m") &&
!frequency.endsWith("h")) {
hostLog.error(
"Snapshot frequency " + frequency +
" needs to end with time unit specified" +
" that is one of [s, m, h] (seconds, minutes, hours)" +
" Defaulting snapshot frequency to 10m.");
frequency = "10m";
}
int frequencyInt = 0;
String frequencySubstring = frequency.substring(0, frequency.length() - 1);
try {
frequencyInt = Integer.parseInt(frequencySubstring);
} catch (Exception e) {
hostLog.error("Frequency " + frequencySubstring +
" is not an integer. Defaulting frequency to 10m.");
frequency = "10m";
frequencyInt = 10;
}
String prefix = snapshotSettings.getPrefix();
if (prefix == null || prefix.isEmpty()) {
hostLog.error("Snapshot prefix " + prefix +
" is not a valid prefix. Using prefix of 'SNAPSHOTNONCE' ");
prefix = "SNAPSHOTNONCE";
}
if (prefix.contains("-") || prefix.contains(",")) {
String oldprefix = prefix;
prefix = prefix.replaceAll("-", "_");
prefix = prefix.replaceAll(",", "_");
hostLog.error("Snapshot prefix " + oldprefix + " cannot include , or -." +
" Using the prefix: " + prefix + " instead.");
}
int retain = snapshotSettings.getRetain();
if (retain < 1) {
hostLog.error("Snapshot retain value " + retain +
" is not a valid value. Must be 1 or greater." +
" Defaulting snapshot retain to 1.");
retain = 1;
}
schedule.setFrequencyunit(
frequency.substring(frequency.length() - 1, frequency.length()));
schedule.setFrequencyvalue(frequencyInt);
schedule.setPrefix(prefix);
schedule.setRetain(retain);
}
else
{
schedule.setEnabled(false);
}
}
private static File getFeaturePath(PathsType paths, PathEntry pathEntry,
File voltDbRoot,
String pathDescription, String defaultPath)
{
File featurePath;
if (paths == null || pathEntry == null) {
featurePath = new VoltFile(voltDbRoot, defaultPath);
} else {
featurePath = new VoltFile(pathEntry.getPath());
if (!featurePath.isAbsolute())
{
featurePath = new VoltFile(voltDbRoot, pathEntry.getPath());
}
}
if (!featurePath.exists()) {
hostLog.info("Creating " + pathDescription + " directory: " +
featurePath.getAbsolutePath());
if (!featurePath.mkdirs()) {
hostLog.fatal("Failed to create " + pathDescription + " directory \"" +
featurePath + "\"");
}
}
return featurePath;
}
/**
* Set voltroot path, and set the path overrides for export overflow, partition, etc.
* @param catalog The catalog to be updated.
* @param paths A reference to the <paths> element of the deployment.xml file.
* @param printLog Whether or not to print paths info.
*/
private static void setPathsInfo(Catalog catalog, PathsType paths, boolean crashOnFailedValidation) {
File voltDbRoot;
final Cluster cluster = catalog.getClusters().get("cluster");
// Handles default voltdbroot (and completely missing "paths" element).
voltDbRoot = getVoltDbRoot(paths);
validateDirectory("volt root", voltDbRoot, crashOnFailedValidation);
PathEntry path_entry = null;
if (paths != null)
{
path_entry = paths.getSnapshots();
}
File snapshotPath =
getFeaturePath(paths, path_entry, voltDbRoot,
"snapshot", "snapshots");
validateDirectory("snapshot path", snapshotPath, crashOnFailedValidation);
path_entry = null;
if (paths != null)
{
path_entry = paths.getExportoverflow();
}
File exportOverflowPath =
getFeaturePath(paths, path_entry, voltDbRoot, "export overflow",
"export_overflow");
validateDirectory("export overflow", exportOverflowPath, crashOnFailedValidation);
// only use these directories in the enterprise version
File commandLogPath = null;
File commandLogSnapshotPath = null;
path_entry = null;
if (paths != null)
{
path_entry = paths.getCommandlog();
}
if (VoltDB.instance().getConfig().m_isEnterprise) {
commandLogPath =
getFeaturePath(paths, path_entry, voltDbRoot, "command log", "command_log");
validateDirectory("command log", commandLogPath, crashOnFailedValidation);
}
else {
// dumb defaults if you ask for logging in community version
commandLogPath = new VoltFile(voltDbRoot, "command_log");
}
path_entry = null;
if (paths != null)
{
path_entry = paths.getCommandlogsnapshot();
}
if (VoltDB.instance().getConfig().m_isEnterprise) {
commandLogSnapshotPath =
getFeaturePath(paths, path_entry, voltDbRoot, "command log snapshot", "command_log_snapshot");
validateDirectory("command log snapshot", commandLogSnapshotPath, crashOnFailedValidation);
}
else {
// dumb defaults if you ask for logging in community version
commandLogSnapshotPath = new VoltFile(voltDbRoot, "command_log_snapshot");;
}
//Set the volt root in the catalog
catalog.getClusters().get("cluster").setVoltroot(voltDbRoot.getPath());
//Set the auto-snapshot schedule path if there are auto-snapshots
SnapshotSchedule schedule = cluster.getDatabases().
get("database").getSnapshotschedule().get("default");
if (schedule != null) {
schedule.setPath(snapshotPath.getPath());
}
//Update the path in the schedule for ppd
schedule = cluster.getFaultsnapshots().get("CLUSTER_PARTITION");
if (schedule != null) {
schedule.setPath(snapshotPath.getPath());
}
//Also set the export overflow directory
cluster.setExportoverflow(exportOverflowPath.getPath());
//Set the command log paths, also creates the command log entry in the catalog
final org.voltdb.catalog.CommandLog commandLogConfig = cluster.getLogconfig().add("log");
commandLogConfig.setInternalsnapshotpath(commandLogSnapshotPath.getPath());
commandLogConfig.setLogpath(commandLogPath.getPath());
}
/**
* Get a File object representing voltdbroot. Create directory if missing.
* Use paths if non-null to get override default location.
*
* @param paths override paths or null
* @return File object for voltdbroot
*/
public static File getVoltDbRoot(PathsType paths) {
File voltDbRoot;
if (paths == null || paths.getVoltdbroot() == null || paths.getVoltdbroot().getPath() == null) {
voltDbRoot = new VoltFile("voltdbroot");
if (!voltDbRoot.exists()) {
hostLog.info("Creating voltdbroot directory: " + voltDbRoot.getAbsolutePath());
if (!voltDbRoot.mkdir()) {
hostLog.fatal("Failed to create voltdbroot directory \"" + voltDbRoot.getAbsolutePath() + "\"");
}
}
} else {
voltDbRoot = new VoltFile(paths.getVoltdbroot().getPath());
}
return voltDbRoot;
}
/**
* Set user info in the catalog.
* @param catalog The catalog to be updated.
* @param users A reference to the <users> element of the deployment.xml file.
*/
private static void setUsersInfo(Catalog catalog, UsersType users) {
if (users == null) {
return;
}
// TODO: The database name is not available in deployment.xml (it is defined in project.xml). However, it must
// always be named "database", so I've temporarily hardcoded it here until a more robust solution is available.
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
SecureRandom sr = new SecureRandom();
for (UsersType.User user : users.getUser()) {
String sha1hex = user.getPassword();
if (user.isPlaintext()) {
sha1hex = extractPassword(user.getPassword());
}
org.voltdb.catalog.User catUser = db.getUsers().add(user.getName());
String hashedPW =
BCrypt.hashpw(
sha1hex,
BCrypt.gensalt(BCrypt.GENSALT_DEFAULT_LOG2_ROUNDS,sr));
catUser.setShadowpassword(hashedPW);
// process the @groups and @roles comma separated list
for (final String role : mergeUserRoles(user)) {
final GroupRef groupRef = catUser.getGroups().add(role);
final Group catalogGroup = db.getGroups().get(role);
if (catalogGroup != null) {
groupRef.setGroup(catalogGroup);
}
}
}
}
/**
* Takes the list of roles specified in the groups, and roles user
* attributes and merges the into one set that contains no duplicates
* @param user an instance of {@link UsersType.User}
* @return a {@link Set} of role name
*/
public static Set<String> mergeUserRoles(final UsersType.User user) {
Set<String> roles = new TreeSet<String>();
if (user == null) return roles;
if (user.getGroups() != null && !user.getGroups().trim().isEmpty()) {
String [] grouplist = user.getGroups().trim().split(",");
for (String group: grouplist) {
if( group == null || group.trim().isEmpty()) continue;
roles.add(group.trim());
}
}
if (user.getRoles() != null && !user.getRoles().trim().isEmpty()) {
String [] rolelist = user.getRoles().trim().split(",");
for (String role: rolelist) {
if( role == null || role.trim().isEmpty()) continue;
roles.add(role.trim());
}
}
return roles;
}
private static void setHTTPDInfo(Catalog catalog, HttpdType httpd) {
// defaults
int httpdPort = -1;
boolean jsonEnabled = false;
Cluster cluster = catalog.getClusters().get("cluster");
// if the httpd info is available, use it
if (httpd != null && httpd.isEnabled()) {
httpdPort = httpd.getPort();
HttpdType.Jsonapi jsonapi = httpd.getJsonapi();
if (jsonapi != null)
jsonEnabled = jsonapi.isEnabled();
}
// set the catalog info
cluster.setHttpdportno(httpdPort);
cluster.setJsonapi(jsonEnabled);
}
/** Read a hashed password from password.
* SHA-1 hash it once to match what we will get from the wire protocol
* and then hex encode it
* */
private static String extractPassword(String password) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (final NoSuchAlgorithmException e) {
hostLog.l7dlog(Level.FATAL, LogKeys.compiler_VoltCompiler_NoSuchAlgorithm.name(), e);
System.exit(-1);
}
final byte passwordHash[] = md.digest(password.getBytes(Charsets.UTF_8));
return Encoder.hexEncode(passwordHash);
}
public static void
uploadCatalogToZK(ZooKeeper zk, int catalogVersion, long txnId, long uniqueId, byte[] catalogHash, byte catalogBytes[])
throws KeeperException, InterruptedException {
ByteBuffer versionAndBytes = ByteBuffer.allocate(catalogBytes.length + 20 + 20);
versionAndBytes.putInt(catalogVersion);
versionAndBytes.putLong(txnId);
versionAndBytes.putLong(uniqueId);
versionAndBytes.put(catalogHash);
versionAndBytes.put(catalogBytes);
zk.create(VoltZK.catalogbytes,
versionAndBytes.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public static void
setCatalogToZK(ZooKeeper zk, int catalogVersion, long txnId, long uniqueId, byte[] catalogHash, byte catalogBytes[])
throws KeeperException, InterruptedException {
ByteBuffer versionAndBytes = ByteBuffer.allocate(catalogBytes.length + 20 + 20);
versionAndBytes.putInt(catalogVersion);
versionAndBytes.putLong(txnId);
versionAndBytes.putLong(uniqueId);
versionAndBytes.put(catalogHash);
versionAndBytes.put(catalogBytes);
zk.setData(VoltZK.catalogbytes,
versionAndBytes.array(), -1);
}
public static class CatalogAndIds {
public final long txnId;
public final long uniqueId;
public final int version;
public final byte hash[];
public final byte bytes[];
public CatalogAndIds(long txnId, long uniqueId, int catalogVersion, byte[] catalogHash, byte[] catalogBytes) {
this.txnId = txnId;
this.uniqueId = uniqueId;
this.version = catalogVersion;
this.hash = catalogHash;
this.bytes = catalogBytes;
}
}
public static CatalogAndIds getCatalogFromZK(ZooKeeper zk) throws KeeperException, InterruptedException {
ByteBuffer versionAndBytes =
ByteBuffer.wrap(zk.getData(VoltZK.catalogbytes, false, null));
int version = versionAndBytes.getInt();
long catalogTxnId = versionAndBytes.getLong();
long catalogUniqueId = versionAndBytes.getLong();
byte[] catalogHash = new byte[20]; // sha-1 hash size
versionAndBytes.get(catalogHash);
byte[] catalogBytes = new byte[versionAndBytes.remaining()];
versionAndBytes.get(catalogBytes);
versionAndBytes = null;
return new CatalogAndIds(catalogTxnId, catalogUniqueId, version, catalogHash, catalogBytes);
}
/**
* Given plan graphs and a SQL stmt, compute a bi-directonal usage map between
* schema (indexes, table & views) and SQL/Procedures.
* Use "annotation" objects to store this extra information in the catalog
* during compilation and catalog report generation.
*/
public static void updateUsageAnnotations(Database db,
Statement stmt,
AbstractPlanNode topPlan,
AbstractPlanNode bottomPlan)
{
Collection<String> tablesRead = new TreeSet<String>();
Collection<String> tablesUpdated = new TreeSet<String>();
Collection<String> indexes = new TreeSet<String>();
if (topPlan != null) {
topPlan.getTablesAndIndexes(tablesRead, tablesUpdated, indexes);
}
if (bottomPlan != null) {
bottomPlan.getTablesAndIndexes(tablesRead, tablesUpdated, indexes);
}
// make useage only in either read or updated, not both
tablesRead.removeAll(tablesUpdated);
for (Table table : db.getTables()) {
for (String indexName : indexes) {
Index index = table.getIndexes().get(indexName);
if (index != null) {
updateIndexUsageAnnotation(index, stmt);
}
}
if (tablesRead.contains(table.getTypeName())) {
updateTableUsageAnnotation(table, stmt, true);
tablesRead.remove(table.getTypeName());
}
if (tablesUpdated.contains(table.getTypeName())) {
updateTableUsageAnnotation(table, stmt, false);
tablesUpdated.remove(table.getTypeName());
}
}
assert(tablesRead.size() == 0);
assert(tablesUpdated.size() == 0);
}
private static void updateIndexUsageAnnotation(Index index, Statement stmt) {
Procedure proc = (Procedure) stmt.getParent();
// skip CRUD generated procs
if (proc.getDefaultproc()) {
return;
}
IndexAnnotation ia = (IndexAnnotation) index.getAnnotation();
if (ia == null) {
ia = new IndexAnnotation();
index.setAnnotation(ia);
}
ia.statementsThatUseThis.add(stmt);
ia.proceduresThatUseThis.add(proc);
ProcedureAnnotation pa = (ProcedureAnnotation) proc.getAnnotation();
if (pa == null) {
pa = new ProcedureAnnotation();
proc.setAnnotation(pa);
}
pa.indexesUsed.add(index);
StatementAnnotation sa = (StatementAnnotation) stmt.getAnnotation();
if (sa == null) {
sa = new StatementAnnotation();
stmt.setAnnotation(sa);
}
sa.indexesUsed.add(index);
}
private static void updateTableUsageAnnotation(Table table, Statement stmt, boolean read) {
Procedure proc = (Procedure) stmt.getParent();
// skip CRUD generated procs
if (proc.getDefaultproc()) {
return;
}
TableAnnotation ta = (TableAnnotation) table.getAnnotation();
if (ta == null) {
ta = new TableAnnotation();
table.setAnnotation(ta);
}
if (read) {
ta.statementsThatReadThis.add(stmt);
ta.proceduresThatReadThis.add(proc);
}
else {
ta.statementsThatUpdateThis.add(stmt);
ta.proceduresThatUpdateThis.add(proc);
}
ProcedureAnnotation pa = (ProcedureAnnotation) proc.getAnnotation();
if (pa == null) {
pa = new ProcedureAnnotation();
proc.setAnnotation(pa);
}
if (read) {
pa.tablesRead.add(table);
}
else {
pa.tablesUpdated.add(table);
}
StatementAnnotation sa = (StatementAnnotation) stmt.getAnnotation();
if (sa == null) {
sa = new StatementAnnotation();
stmt.setAnnotation(sa);
}
if (read) {
sa.tablesRead.add(table);
}
else {
sa.tablesUpdated.add(table);
}
}
/**
* Get all normal tables from the catalog. A normal table is one that's NOT a materialized
* view, nor an export table. For the lack of a better name, I call it normal.
* @param catalog Catalog database
* @param isReplicated true to return only replicated tables,
* false to return all partitioned tables
* @return A list of tables
*/
public static List<Table> getNormalTables(Database catalog, boolean isReplicated) {
List<Table> tables = new ArrayList<Table>();
for (Table table : catalog.getTables()) {
if ((table.getIsreplicated() == isReplicated) &&
table.getMaterializer() == null &&
!CatalogUtil.isTableExportOnly(catalog, table)) {
tables.add(table);
}
}
return tables;
}
/**
* Iterate through all the tables in the catalog, find a table with an id that matches the
* given table id, and return its name.
*
* @param catalog Catalog database
* @param tableId table id
* @return table name associated with the given table id (null if no association is found)
*/
public static String getTableNameFromId(Database catalog, int tableId) {
String tableName = null;
for (Table table: catalog.getTables()) {
if (table.getRelativeIndex() == tableId) {
tableName = table.getTypeName();
}
}
return tableName;
}
// Calculate the width of an index:
// -- if the index is a pure-column index, return number of columns in the index
// -- if the index is an expression index, return number of expressions used to create the index
public static int getCatalogIndexSize(Index index) {
int indexSize = 0;
String jsonstring = index.getExpressionsjson();
if (jsonstring.isEmpty()) {
indexSize = getSortedCatalogItems(index.getColumns(), "index").size();
} else {
try {
indexSize = AbstractExpression.fromJSONArrayString(jsonstring).size();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return indexSize;
}
}
|
package com.wkovacs64.mtorch.core;
/**
* A generic torch object that can be toggled on or off.
*/
public interface Torch {
void init() throws IllegalStateException;
void toggle(boolean enabled) throws IllegalStateException;
/**
* Reports the current illumination status of the torch.
*
* @return true if the torch is on, false if it's off
*/
boolean isOn();
/**
* Releases or tears down any necessary torch components or dependencies.
*/
void tearDown();
}
|
package org.elasticsearch.xpack.searchablesnapshots.action;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.StepListener;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.routing.allocation.ExistingShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.indices.ShardLimitValidator;
import org.elasticsearch.indices.SystemIndices;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.repositories.IndexId;
import org.elasticsearch.repositories.RepositoriesService;
import org.elasticsearch.repositories.Repository;
import org.elasticsearch.repositories.RepositoryData;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.cluster.routing.allocation.DataTierAllocationDecider;
import org.elasticsearch.xpack.core.searchablesnapshots.MountSearchableSnapshotAction;
import org.elasticsearch.xpack.core.searchablesnapshots.MountSearchableSnapshotRequest;
import org.elasticsearch.xpack.searchablesnapshots.allocation.SearchableSnapshotAllocator;
import org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshots;
import org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsConstants;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import static org.elasticsearch.index.IndexModule.INDEX_RECOVERY_TYPE_SETTING;
import static org.elasticsearch.index.IndexModule.INDEX_STORE_TYPE_SETTING;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshots.getDataTiersPreference;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshotsConstants.isSearchableSnapshotStore;
/**
* Action that mounts a snapshot as a searchable snapshot, by converting the mount request into a restore request with specific settings
* using {@link #buildIndexSettings}.
*
* This action needs to run on the master node because it retrieves the {@link RepositoryData}.
*/
public class TransportMountSearchableSnapshotAction extends TransportMasterNodeAction<
MountSearchableSnapshotRequest,
RestoreSnapshotResponse> {
private static final Collection<Setting<String>> DATA_TIER_ALLOCATION_SETTINGS = List.of(
DataTierAllocationDecider.INDEX_ROUTING_EXCLUDE_SETTING,
DataTierAllocationDecider.INDEX_ROUTING_INCLUDE_SETTING,
DataTierAllocationDecider.INDEX_ROUTING_REQUIRE_SETTING,
DataTierAllocationDecider.INDEX_ROUTING_PREFER_SETTING
);
private final Client client;
private final RepositoriesService repositoriesService;
private final XPackLicenseState licenseState;
private final SystemIndices systemIndices;
@Inject
public TransportMountSearchableSnapshotAction(
TransportService transportService,
ClusterService clusterService,
Client client,
ThreadPool threadPool,
RepositoriesService repositoriesService,
ActionFilters actionFilters,
IndexNameExpressionResolver indexNameExpressionResolver,
XPackLicenseState licenseState,
SystemIndices systemIndices
) {
super(
MountSearchableSnapshotAction.NAME,
transportService,
clusterService,
threadPool,
actionFilters,
MountSearchableSnapshotRequest::new,
indexNameExpressionResolver,
RestoreSnapshotResponse::new,
// Avoid SNAPSHOT since snapshot threads may all be busy with long-running tasks which would block this action from responding
// with an error. Avoid SAME since getting the repository metadata may block on IO.
ThreadPool.Names.GENERIC
);
this.client = client;
this.repositoriesService = repositoriesService;
this.licenseState = Objects.requireNonNull(licenseState);
this.systemIndices = Objects.requireNonNull(systemIndices);
}
@Override
protected ClusterBlockException checkBlock(MountSearchableSnapshotRequest request, ClusterState state) {
// The restore action checks the cluster blocks.
return null;
}
/**
* Return the index settings required to make a snapshot searchable
*/
private static Settings buildIndexSettings(
String repoUuid,
String repoName,
SnapshotId snapshotId,
IndexId indexId,
MountSearchableSnapshotRequest.Storage storage,
Version minNodeVersion
) {
final Settings.Builder settings = Settings.builder();
if (repoUuid.equals(RepositoryData.MISSING_UUID) == false) {
settings.put(SearchableSnapshots.SNAPSHOT_REPOSITORY_UUID_SETTING.getKey(), repoUuid);
}
settings.put(SearchableSnapshots.SNAPSHOT_REPOSITORY_NAME_SETTING.getKey(), repoName)
.put(SearchableSnapshots.SNAPSHOT_SNAPSHOT_NAME_SETTING.getKey(), snapshotId.getName())
.put(SearchableSnapshots.SNAPSHOT_SNAPSHOT_ID_SETTING.getKey(), snapshotId.getUUID())
.put(SearchableSnapshots.SNAPSHOT_INDEX_NAME_SETTING.getKey(), indexId.getName())
.put(SearchableSnapshots.SNAPSHOT_INDEX_ID_SETTING.getKey(), indexId.getId())
.put(INDEX_STORE_TYPE_SETTING.getKey(), SearchableSnapshotsConstants.SNAPSHOT_DIRECTORY_FACTORY_KEY)
.put(IndexMetadata.SETTING_BLOCKS_WRITE, true)
.put(ExistingShardsAllocator.EXISTING_SHARDS_ALLOCATOR_SETTING.getKey(), SearchableSnapshotAllocator.ALLOCATOR_NAME)
.put(INDEX_RECOVERY_TYPE_SETTING.getKey(), SearchableSnapshotsConstants.SNAPSHOT_RECOVERY_STATE_FACTORY_KEY);
if (storage == MountSearchableSnapshotRequest.Storage.SHARED_CACHE) {
if (minNodeVersion.before(Version.V_7_12_0)) {
throw new IllegalArgumentException("shared cache searchable snapshots require minimum node version " + Version.V_7_12_0);
}
settings.put(SearchableSnapshotsConstants.SNAPSHOT_PARTIAL_SETTING.getKey(), true)
.put(DiskThresholdDecider.SETTING_IGNORE_DISK_WATERMARKS.getKey(), true);
// we cannot apply this setting during rolling upgrade.
if (minNodeVersion.onOrAfter(Version.V_7_13_0)) {
settings.put(ShardLimitValidator.INDEX_SETTING_SHARD_LIMIT_GROUP.getKey(), ShardLimitValidator.FROZEN_GROUP);
}
}
return settings.build();
}
@Override
protected void masterOperation(
Task task,
final MountSearchableSnapshotRequest request,
final ClusterState state,
final ActionListener<RestoreSnapshotResponse> listener
) {
SearchableSnapshots.ensureValidLicense(licenseState);
final String mountedIndexName = request.mountedIndexName();
if (systemIndices.isSystemIndex(mountedIndexName)) {
throw new ElasticsearchException("system index [{}] cannot be mounted as searchable snapshots", mountedIndexName);
}
final String repoName = request.repositoryName();
final String snapName = request.snapshotName();
final String indexName = request.snapshotIndexName();
// Retrieve IndexId and SnapshotId instances, which are then used to create a new restore
// request, which is then sent on to the actual snapshot restore mechanism
final Repository repository = repositoriesService.repository(repoName);
SearchableSnapshots.getSearchableRepository(repository); // just check it's valid
final StepListener<RepositoryData> repositoryDataListener = new StepListener<>();
repository.getRepositoryData(repositoryDataListener);
repositoryDataListener.whenComplete(repoData -> {
final Map<String, IndexId> indexIds = repoData.getIndices();
if (indexIds.containsKey(indexName) == false) {
throw new IndexNotFoundException("index [" + indexName + "] not found in repository [" + repoName + "]");
}
final IndexId indexId = indexIds.get(indexName);
final Optional<SnapshotId> matchingSnapshotId = repoData.getSnapshotIds()
.stream()
.filter(s -> snapName.equals(s.getName()))
.findFirst();
if (matchingSnapshotId.isEmpty()) {
throw new ElasticsearchException("snapshot [" + snapName + "] not found in repository [" + repoName + "]");
}
final SnapshotId snapshotId = matchingSnapshotId.get();
final IndexMetadata indexMetadata = repository.getSnapshotIndexMetaData(repoData, snapshotId, indexId);
if (isSearchableSnapshotStore(indexMetadata.getSettings())) {
throw new IllegalArgumentException(
String.format(
Locale.ROOT,
"index [%s] in snapshot [%s/%s:%s] is a snapshot of a searchable snapshot index "
+ "backed by index [%s] in snapshot [%s/%s:%s] and cannot be mounted; did you mean to restore it instead?",
indexName,
repoName,
repository.getMetadata().uuid(),
snapName,
SearchableSnapshots.SNAPSHOT_INDEX_NAME_SETTING.get(indexMetadata.getSettings()),
SearchableSnapshots.SNAPSHOT_REPOSITORY_NAME_SETTING.get(indexMetadata.getSettings()),
SearchableSnapshots.SNAPSHOT_REPOSITORY_UUID_SETTING.get(indexMetadata.getSettings()),
SearchableSnapshots.SNAPSHOT_SNAPSHOT_NAME_SETTING.get(indexMetadata.getSettings())
)
);
}
final Set<String> ignoreIndexSettings = new LinkedHashSet<>(Arrays.asList(request.ignoreIndexSettings()));
ignoreIndexSettings.add(IndexMetadata.SETTING_DATA_PATH);
for (final String indexSettingKey : indexMetadata.getSettings().keySet()) {
if (indexSettingKey.startsWith(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_PREFIX)
|| indexSettingKey.startsWith(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_PREFIX)
|| indexSettingKey.startsWith(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_PREFIX)) {
ignoreIndexSettings.add(indexSettingKey);
}
}
Settings indexSettings = Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0) // can be overridden
.put(IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS, false) // can be overridden
.put(DataTierAllocationDecider.INDEX_ROUTING_PREFER, getDataTiersPreference(request.storage()))
.put(request.indexSettings())
.put(
buildIndexSettings(
repoData.getUuid(),
request.repositoryName(),
snapshotId,
indexId,
request.storage(),
state.nodes().getMinNodeVersion()
)
)
.build();
// todo: restore archives bad settings, for now we verify just the data tiers, since we know their dependencies are available
// in settings
for (Setting<String> dataTierAllocationSetting : DATA_TIER_ALLOCATION_SETTINGS) {
dataTierAllocationSetting.get(indexSettings);
}
client.admin()
.cluster()
.restoreSnapshot(
new RestoreSnapshotRequest(repoName, snapName)
// Restore the single index specified
.indices(indexName)
// Always rename it to the desired mounted index name
.renamePattern(".+")
.renameReplacement(mountedIndexName)
// Pass through index settings, adding the index-level settings required to use searchable snapshots
.indexSettings(indexSettings)
// Pass through ignored index settings
.ignoreIndexSettings(ignoreIndexSettings.toArray(new String[0]))
// Don't include global state
.includeGlobalState(false)
// Don't include aliases
.includeAliases(false)
// Pass through the wait-for-completion flag
.waitForCompletion(request.waitForCompletion())
// Pass through the master-node timeout
.masterNodeTimeout(request.masterNodeTimeout())
// Fail the restore if the snapshot found above is swapped out from under us before the restore happens
.snapshotUuid(snapshotId.getUUID()),
listener
);
}, listener::onFailure);
}
}
|
package galileo.test.bmp;
import static org.junit.Assert.*;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import galileo.bmp.GeoavailabilityGrid;
import galileo.bmp.Visualization;
import galileo.dataset.Coordinates;
import galileo.dataset.Point;
import galileo.util.GeoHash;
import galileo.util.Pair;
import org.junit.Test;
public class GeoavailabilityTests {
private boolean draw = false;
public GeoavailabilityTests() {
this.draw = Boolean.parseBoolean(System.getProperty(
"galileo.test.bmp.GeoavailabilityTests.draw",
"false"));
}
// @Test
// public void coordinateTransform() {
// GeoavailabilityGrid gg = new GeoavailabilityGrid("9x", 10);
@Test
public void testBitmapCorners() throws IOException {
GeoavailabilityGrid gg = new GeoavailabilityGrid("9x", 10);
gg.addPoint(new Coordinates(44.919f, -112.242f));
gg.addPoint(new Coordinates(44.919f, -101.514f));
gg.addPoint(new Coordinates(39.496f, -112.242f));
gg.addPoint(new Coordinates(39.496f, -101.514f));
if (draw) {
BufferedImage b = Visualization.drawGeoavailabilityGrid(
gg, Color.BLACK);
Visualization.imageToFile(b, "BitmapCorners.gif");
}
}
/**
* Ensures out-of-bounds X points are not inserted into the
* GeoavailabilityGrid.
*/
@Test
public void testXOutOfBounds() {
GeoavailabilityGrid gg = new GeoavailabilityGrid("9x", 10);
assertEquals(gg.addPoint(new Coordinates(44.819f, -113.350f)), false);
assertEquals(gg.addPoint(new Coordinates(44.819f, -100.684f)), false);
assertEquals(gg.addPoint(new Coordinates(39.496f, -113.350f)), false);
assertEquals(gg.addPoint(new Coordinates(39.496f, -100.684f)), false);
assertEquals(gg.addPoint(new Coordinates(0.0f, 0.0f)), false);
}
/**
* Ensures out-of-bounds Y points are not inserted into the
* GeoavailabilityGrid.
*/
@Test
public void testYOutOfBounds() {
GeoavailabilityGrid gg = new GeoavailabilityGrid("9x", 10);
assertEquals(gg.addPoint(new Coordinates(45.333f, -112.242f)), false);
assertEquals(gg.addPoint(new Coordinates(45.360f, -101.514f)), false);
assertEquals(gg.addPoint(new Coordinates(38.992f, -112.242f)), false);
assertEquals(gg.addPoint(new Coordinates(38.992f, -101.514f)), false);
assertEquals(gg.addPoint(new Coordinates(0.0f, 0.0f)), false);
}
/**
* Tests the update procedure for bits that are inserted out of order.
*/
@Test
public void testUpdates() throws Exception {
/* Insert points in indexed order */
GeoavailabilityGrid g1 = new GeoavailabilityGrid("9x", 10);
g1.addPoint(new Coordinates(44.919f, -112.242f));
g1.addPoint(new Coordinates(44.919f, -101.514f));
g1.addPoint(new Coordinates(39.496f, -112.242f));
g1.addPoint(new Coordinates(39.496f, -101.514f));
/* Insert points out of order */
GeoavailabilityGrid g2 = new GeoavailabilityGrid("9x", 10);
g2.addPoint(new Coordinates(39.496f, -101.514f));
g2.addPoint(new Coordinates(39.496f, -112.242f));
g2.addPoint(new Coordinates(44.919f, -101.514f));
g2.addPoint(new Coordinates(44.919f, -112.242f));
if (draw) {
BufferedImage b1 = Visualization.drawGeoavailabilityGrid(g1);
BufferedImage b2 = Visualization.drawGeoavailabilityGrid(g2);
Visualization.imageToFile(b1, "Updates1.gif");
Visualization.imageToFile(b2, "Updates2.gif");
}
assertEquals(true, g1.equals(g2));
}
}
|
package jp.takke.datastats;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import jp.takke.util.MyLog;
public class MainActivity extends Activity {
private boolean mPreparingConfigArea = false;
private ILayerService mServiceIF = null;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyLog.d("onServiceConnected[" + name + "]");
mServiceIF = ILayerService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
MyLog.d("onServiceDisconnected[" + name + "]");
mServiceIF = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prepareStartStopButton();
prepareConfigArea();
preparePreviewArea();
final Intent service = new Intent(this, LayerService.class);
bindService(service, mServiceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onPause() {
if (mServiceIF != null) {
// restart
try {
mServiceIF.restart();
} catch (RemoteException e) {
MyLog.e(e);
}
}
super.onPause();
}
@Override
protected void onDestroy() {
if (mServiceIF != null) {
unbindService(mServiceConnection);
}
super.onDestroy();
}
private void prepareStartStopButton() {
// start
{
final Button button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doRestartService();
}
});
}
// stop
{
final Button button = (Button) findViewById(R.id.stop_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doStopService();
}
});
}
}
private void doStopService() {
if (mServiceIF != null) {
try {
mServiceIF.stop();
} catch (RemoteException e) {
MyLog.e(e);
}
unbindService(mServiceConnection);
mServiceIF = null;
}
}
private void doRestartService() {
if (mServiceIF != null) {
// restart
try {
mServiceIF.restart();
} catch (RemoteException e) {
MyLog.e(e);
}
} else {
// rebind
final Intent service = new Intent(MainActivity.this, LayerService.class);
bindService(service, mServiceConnection, Context.BIND_AUTO_CREATE);
}
final TextView kbText = (TextView) findViewById(R.id.preview_kb_text);
kbText.setText("-");
}
private void prepareConfigArea() {
mPreparingConfigArea = true;
// auto start
final CheckBox autoStartOnBoot = (CheckBox) findViewById(R.id.autoStartOnBoot);
autoStartOnBoot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
final SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(C.PREF_KEY_START_ON_BOOT, isChecked);
editor.apply();
}
});
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
final boolean startOnBoot = pref.getBoolean(C.PREF_KEY_START_ON_BOOT, false);
autoStartOnBoot.setChecked(startOnBoot);
// hide when in fullscreen
final CheckBox hideCheckbox = (CheckBox) findViewById(R.id.hideWhenInFullscreen);
hideCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
final SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(C.PREF_KEY_HIDE_WHEN_IN_FULLSCREEN, isChecked);
editor.apply();
}
});
hideCheckbox.setChecked(pref.getBoolean(C.PREF_KEY_HIDE_WHEN_IN_FULLSCREEN, true));
// Logarithm bar
final CheckBox logCheckbox = (CheckBox) findViewById(R.id.logarithmCheckbox);
logCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
final SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(C.PREF_KEY_LOGARITHM_BAR, isChecked);
editor.apply();
// restart
doRestartService();
}
});
logCheckbox.setChecked(pref.getBoolean(C.PREF_KEY_LOGARITHM_BAR, true));
// Interpolate mode
final CheckBox interpolateCheckBox = (CheckBox) findViewById(R.id.interpolateCheckBox);
interpolateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
final SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(C.PREF_KEY_INTERPOLATE_MODE, isChecked);
editor.apply();
// kill surface
doStopService();
// restart
doRestartService();
}
});
interpolateCheckBox.setChecked(pref.getBoolean(C.PREF_KEY_INTERPOLATE_MODE, false));
// pos
final SeekBar seekBar = (SeekBar) findViewById(R.id.posSeekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
final TextView textView = (TextView) findViewById(R.id.pos_text);
textView.setText("" + progress + "%");
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
final SharedPreferences.Editor editor = pref.edit();
editor.putInt(C.PREF_KEY_X_POS, progress);
editor.apply();
// restart
doRestartService();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final int xPos = pref.getInt(C.PREF_KEY_X_POS, 100);
seekBar.setProgress(xPos);
// Interval Spinner
{
final ArrayAdapter<String> adapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item);
final int[] intervals = new int[]{500, 1000, 1500, 2000};
for (int interval : intervals) {
adapter.add("" + (interval / 1000) + "." + (interval % 1000 / 100) + "sec");
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final Spinner spinner = (Spinner) findViewById(R.id.intervalSpinner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mPreparingConfigArea) {
return;
}
MyLog.d("onItemSelected: [" + position + "]");
final int interval = intervals[position];
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
final SharedPreferences.Editor editor = pref.edit();
editor.putInt(C.PREF_KEY_INTERVAL_MSEC, interval);
editor.apply();
// restart
doRestartService();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final int currentIntervalMsec = pref.getInt(C.PREF_KEY_INTERVAL_MSEC, 1000);
for (int i = 0; i < intervals.length; i++) {
if (currentIntervalMsec == intervals[i]) {
spinner.setSelection(i);
break;
}
}
}
// Max Speed[KB] Spinner (Bar)
{
final ArrayAdapter<String> adapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item);
final int[] speeds = new int[]{10, 50, 100, 500, 1024, 2048, 5120, 10240};
for (int s : speeds) {
if (s >= 1024) {
adapter.add("" + (s / 1024) + "MB/s");
} else {
adapter.add("" + s + "KB/s");
}
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final Spinner spinner = (Spinner) findViewById(R.id.maxSpeedSpinner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mPreparingConfigArea) {
return;
}
MyLog.d("onItemSelected: [" + position + "]");
final int speed = speeds[position];
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
final SharedPreferences.Editor editor = pref.edit();
editor.putInt(C.PREF_KEY_BAR_MAX_SPEED_KB, speed);
editor.apply();
// restart
doRestartService();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final int currentSpeed = pref.getInt(C.PREF_KEY_BAR_MAX_SPEED_KB, 10240);
for (int i = 0; i < speeds.length; i++) {
if (currentSpeed == speeds[i]) {
spinner.setSelection(i);
break;
}
}
}
mPreparingConfigArea = false;
}
private void preparePreviewArea() {
final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
final TextView kbText = (TextView) findViewById(R.id.preview_kb_text);
kbText.setText("" + (progress/10) + "." + (progress%10) + "KB");
restartWithPreview(progress/10, progress%10);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final int[] sampleButtonIds = new int[]{R.id.sample_1kb_button,
R.id.sample_20kb_button,
R.id.sample_50kb_button,
R.id.sample_80kb_button,
R.id.sample_100kb_button
};
final int[] samples = new int[]{1, 20, 50, 80, 100};
for (int i = 0; i < sampleButtonIds.length; i++) {
final Button button = (Button) findViewById(sampleButtonIds[i]);
final int kb = samples[i];
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restartWithPreview(kb, 0);
}
});
}
}
private void restartWithPreview(long kb, long kbd1) {
if (mServiceIF != null) {
// preview
try {
mServiceIF.startSnapshot(kb * 1024 + kbd1*100);
} catch (RemoteException e) {
MyLog.e(e);
}
}
final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setProgress((int) (kb*10+kbd1));
final TextView kbText = (TextView) findViewById(R.id.preview_kb_text);
kbText.setText(kb + "." + kbd1 + "KB");
}
}
|
package net.imglib2.meta;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.meta.axis.LinearAxis;
import net.imglib2.type.numeric.integer.ByteType;
import org.junit.Test;
/**
* @author Barry DeZonia
*/
public class ImgPlusTest {
private ImgPlus<?> imgPlus;
@Test
public void test() {
Img<ByteType> img = ArrayImgs.bytes(9, 8);
imgPlus =
new ImgPlus<ByteType>(img, "HUBBY", new AxisType[] { Axes.X, Axes.Z },
new double[] { 5, 13 });
assertEquals("HUBBY", imgPlus.getName());
assertEquals(Axes.X, imgPlus.axis(0).type());
assertEquals(Axes.Z, imgPlus.axis(1).type());
assertEquals(5, imgPlus.axis(0).averageScale(0, 1), 0);
assertEquals(13, imgPlus.axis(1).averageScale(0, 1), 0);
assertEquals(9, imgPlus.dimension(0));
assertEquals(8, imgPlus.dimension(1));
assertTrue(imgPlus.axis(1) instanceof LinearAxis);
((LinearAxis) imgPlus.axis(1)).setScale(48);
assertEquals(48, imgPlus.axis(1).averageScale(0, 1), 0);
assertEquals(0, imgPlus.min(0));
assertEquals(0, imgPlus.min(1));
assertEquals(8, imgPlus.max(0));
assertEquals(7, imgPlus.max(1));
assertEquals(0, imgPlus.getValidBits());
assertEquals(72, imgPlus.size());
assertNull(imgPlus.axis(0).unit());
imgPlus.axis(0).setUnit("WUNGA");
assertEquals("WUNGA", imgPlus.axis(0).unit());
}
}
|
package networking;
import junit.framework.TestCase;
import java.util.Queue;
public class NetworkServerTest extends TestCase {
private final NetworkServer networkServer = new NetworkServer(80085);
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
}
public void testGetPort() throws Exception {
}
public void testSetPort() throws Exception {
}
public void testListen() throws Exception {
}
public void testSend() throws Exception {
}
public void testConsumeMessage() throws Exception {
// Test for no messages in queue
assertNull("Object appeared in queue", networkServer.consumeMessage());
// Test for message in queue
NetworkMessage message = new NetworkMessage("Testing consumption", "sender", "receiver");
networkServer.getMessageQueue().add(message);
NetworkMessage consumedMessage = networkServer.consumeMessage();
assertEquals(consumedMessage, message);
// Test that there should no longer be any elements in queue
assertNull("Objects still in queue", networkServer.consumeMessage());
}
public void testPeek() throws Exception {
// Test for empty queue
boolean peek = networkServer.peek();
assertFalse("Peek managed to find items while there should be none", peek);
// Test for a non-empty queue
NetworkMessage message = new NetworkMessage("bla bla", "sender", "receiver");
Queue<NetworkMessage> queue = networkServer.getMessageQueue();
queue.add(message);
peek = networkServer.peek();
assertTrue("Peek did not return a value", peek);
// empty the queue and then test again
networkServer.consumeMessage();
peek = networkServer.peek();
assertFalse("Peek should no longer return any elements", peek);
}
}
|
package com.evolveum.midpoint.eclipse.ui.prefs;
import java.util.List;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Widget;
public abstract class AbstractServersFieldEditor<T extends DataItem> extends FieldEditor {
/**
* The table widget; <code>null</code> if none (before creation or after
* disposal).
*/
protected Table table;
/**
* The button box containing the Edit, Add, Remove, Up, and Down and buttons;
* <code>null</code> if none (before creation or after disposal).
*/
protected Composite buttonBox;
protected Button addButton;
protected Button editButton;
protected Button selectButton;
protected Button testButton;
protected Button duplicateButton;
protected Button removeButton;
protected Button upButton;
protected Button downButton;
protected SelectionListener selectionListener;
protected final String[] columnNames;
protected final int[] columnWidths;
protected List<T> currentItems;
/**
* Creates a table field editor.
*
* @param name
* the name of the preference this field editor works on
* @param labelText
* the label text of the field editor
* @param columnNames
* the names of columns
* @param columnWidths
* the widths of columns
* @param parent
* the parent of the field editor's control
*
*/
protected AbstractServersFieldEditor(String name, String labelText,
String[] columnNames, int[] columnWidths, Composite parent) {
init(name, labelText);
this.columnNames = columnNames;
this.columnWidths = columnWidths;
createControl(parent);
}
/**
* Combines the given list of items into a single string. This method is the
* converse of <code>parseStringRepresentation</code>.
* <p>
* Subclasses must implement this method.
* </p>
*
* @param items
* the list of items
* @return the combined string
* @see #parseStringRepresentation
*/
protected abstract String createStringRepresentation(List<T> items);
/**
* Splits the given string into a array of array of value. This method is
* the converse of <code>createList</code>.
* <p>
* Subclasses must implement this method.
* </p>
*
* @param string
* the string
* @return an array of array of <code>string</code>
* @see #createList
*/
protected abstract List<T> parseStringRepresentation(String string);
/**
* Creates and returns a new value row for the table.
* <p>
* Subclasses must implement this method.
* </p>
*
* @return a new item
*/
protected abstract T createNewItem();
/**
* Creates the Add, Remove, Up, and Down button in the given button box.
*
* @param box
* the box for the buttons
*/
private void createButtons(Composite box) {
addButton = createPushButton(box, "New");
editButton = createPushButton(box, "Edit");
selectButton = createPushButton(box, "Select");
testButton = createPushButton(box, "Test");
duplicateButton = createPushButton(box, "Duplicate");
removeButton = createPushButton(box, "Remove");
upButton = createPushButton(box, "Up");
downButton = createPushButton(box, "Down");
}
private Button createPushButton(Composite parent, String name) {
Button button = new Button(parent, SWT.PUSH);
button.setText(name);
button.setFont(parent.getFont());
GridData data = new GridData(GridData.FILL_HORIZONTAL);
int widthHint = convertHorizontalDLUsToPixels(button, IDialogConstants.BUTTON_WIDTH);
data.widthHint = Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
button.setLayoutData(data);
button.addSelectionListener(getSelectionListener());
return button;
}
protected void adjustForNumColumns(int numColumns) {
Control control = getLabelControl();
((GridData) control.getLayoutData()).horizontalSpan = numColumns;
((GridData) table.getLayoutData()).horizontalSpan = numColumns - 1;
}
public void createSelectionListener() {
selectionListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
Widget widget = event.widget;
if (widget == editButton) {
editPressed();
} else if (widget == selectButton) {
selectPressed();
} else if (widget == testButton) {
testPressed();
} else if (widget == addButton) {
addPressed();
} else if (widget == duplicateButton) {
duplicatePressed();
} else if (widget == removeButton) {
removePressed();
} else if (widget == upButton) {
upPressed();
} else if (widget == downButton) {
downPressed();
} else if (widget == table) {
selectionChanged();
}
}
};
}
protected void doFillIntoGrid(Composite parent, int numColumns) {
Control control = getLabelControl(parent);
GridData gd = new GridData();
gd.horizontalSpan = numColumns;
control.setLayoutData(gd);
Composite composite = new Composite(parent, SWT.NONE);
GridData gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
gridData.horizontalSpan = 2;
gridData.widthHint = 550;
composite.setLayoutData(gridData);
composite.setLayout(new GridLayout(2, false));
table = getTableControl(composite);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalAlignment = GridData.FILL;
gd.horizontalSpan = numColumns - 1;
gd.grabExcessHorizontalSpace = true;
table.setLayoutData(gd);
buttonBox = getButtonBoxControl(composite);
gd = new GridData();
gd.verticalAlignment = GridData.BEGINNING;
buttonBox.setLayoutData(gd);
}
protected void doLoad() {
if (table != null) {
String s = getPreferenceStore().getString(getPreferenceName());
loadFromStringRepresentation(s);
}
}
protected void loadFromStringRepresentation(String s) {
table.removeAll();
currentItems = parseStringRepresentation(s);
for (DataItem item : currentItems) {
TableItem tableItem = new TableItem(table, SWT.NONE);
setFontReflectingSelection(item, tableItem);
tableItem.setText(item.getColumnValues());
}
}
protected void setFontReflectingSelection(DataItem item, TableItem tableItem) {
if (item.isSelected()) {
tableItem.setFont(getFontForSelected());
} else {
tableItem.setFont(table.getFont());
}
}
protected Font getFontForSelected() {
return JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT);
}
protected void doLoadDefault() {
if (table != null) {
String s = getPreferenceStore().getDefaultString(getPreferenceName());
loadFromStringRepresentation(s);
}
}
protected void doStore() {
String s = createStringRepresentation(currentItems);
if (s != null) {
getPreferenceStore().setValue(getPreferenceName(), s);
}
}
public Composite getButtonBoxControl(Composite parent) {
if (buttonBox == null) {
buttonBox = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
layout.marginWidth = 0;
buttonBox.setLayout(layout);
createButtons(buttonBox);
buttonBox.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
editButton = null;
selectButton = null;
testButton = null;
addButton = null;
duplicateButton = null;
removeButton = null;
upButton = null;
downButton = null;
buttonBox = null;
}
});
} else {
checkParent(buttonBox, parent);
}
selectionChanged();
return buttonBox;
}
public Table getTableControl(Composite parent) {
if (table == null) {
table = new Table(parent, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL
| SWT.H_SCROLL | SWT.FULL_SELECTION);
table.setFont(parent.getFont());
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.addSelectionListener(getSelectionListener());
table.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
table = null;
}
});
table.addListener(SWT.MouseDoubleClick, new Listener() {
public void handleEvent(Event event) {
Rectangle clientArea = table.getClientArea();
Point pt = new Point(event.x, event.y);
int index = table.getTopIndex();
while (index < table.getItemCount()) {
TableItem item = table.getItem(index);
boolean rowVisible = false;
for (int i = 0; i < columnNames.length; i++) {
Rectangle rect = item.getBounds(i);
if (rect.contains(pt)) {
table.setSelection(index);
selectPressed();
return;
}
if (!rowVisible && rect.intersects(clientArea)) {
rowVisible = true;
}
}
if (!rowVisible) {
return;
}
index++;
}
}
});
for (String columnName : columnNames) {
TableColumn tableColumn = new TableColumn(table, SWT.LEAD);
tableColumn.setText(columnName);
tableColumn.setWidth(100);
}
if (columnNames.length > 0) {
TableLayout layout = new TableLayout();
if (columnNames.length > 1) {
for (int i = 0; i < (columnNames.length - 1); i++) {
layout.addColumnData(new ColumnWeightData(0,
columnWidths[i], false));
}
}
layout.addColumnData(new ColumnWeightData(100,
columnWidths[columnNames.length - 1], true));
table.setLayout(layout);
}
final TableEditor editor = new TableEditor(table);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
} else {
checkParent(table, parent);
}
return table;
}
public int getNumberOfControls() {
return 2;
}
private SelectionListener getSelectionListener() {
if (selectionListener == null) {
createSelectionListener();
}
return selectionListener;
}
/**
* Returns this field editor's shell.
* <p>
* This method is internal to the framework; subclassers should not call
* this method.
* </p>
*
* @return the shell
*/
protected Shell getShell() {
if (addButton == null) {
return null;
}
return addButton.getShell();
}
private void addPressed() {
setPresentsDefaultValue(false);
T newInputObject = createNewItem();
if (newInputObject != null) {
currentItems.add(newInputObject);
if (currentItems.size() == 1) {
newInputObject.setSelected(true);
}
TableItem tableItem = new TableItem(table, SWT.NONE);
setFontReflectingSelection(newInputObject, tableItem);
tableItem.setText(newInputObject.getColumnValues());
selectionChanged();
}
}
protected void editPressed() {
}
protected void testPressed() {
}
protected void selectPressed() {
setPresentsDefaultValue(false);
int index = table.getSelectionIndex();
if (index >= 0) {
for (int i = 0; i < currentItems.size(); i++) {
T item = currentItems.get(i);
boolean wasSelected = item.isSelected();
boolean shouldBeSelected = i == index;
if (wasSelected && !shouldBeSelected) {
item.setSelected(false);
table.getItem(i).setFont(table.getFont());
} else if (!wasSelected && shouldBeSelected) {
item.setSelected(true);
table.getItem(i).setFont(getFontForSelected());
}
}
}
}
private void duplicatePressed() {
setPresentsDefaultValue(false);
int index = table.getSelectionIndex();
int target = index + 1;
if (index >= 0) {
TableItem[] selection = table.getSelection();
Assert.isTrue(selection.length == 1);
T newItem = (T) currentItems.get(index).clone();
newItem.setSelected(false);
currentItems.add(target, newItem);
TableItem tableItem = new TableItem(table, SWT.NONE, target);
setFontReflectingSelection(newItem, tableItem);
tableItem.setText(newItem.getColumnValues());
table.setSelection(target);
}
selectionChanged();
}
private void removePressed() {
setPresentsDefaultValue(false);
int index = table.getSelectionIndex();
if (index >= 0) {
table.remove(index);
currentItems.remove(index);
if (currentItems.size() == 1) {
currentItems.get(0).setSelected(true);
setFontReflectingSelection(currentItems.get(0), table.getItem(0));
}
selectionChanged();
}
}
private void upPressed() {
swap(true);
}
private void downPressed() {
swap(false);
}
/**
* Invoked when the selection in the list has changed.
*
* <p>
* The default implementation of this method utilizes the selection index
* and the size of the list to toggle the enabled state of the up, down and
* remove buttons.
* </p>
*
* <p>
* Subclasses may override.
* </p>
*
*/
protected void selectionChanged() {
int index = table.getSelectionIndex();
int size = table.getItemCount();
selectButton.setEnabled(index >= 0 && !currentItems.get(index).isSelected());
editButton.setEnabled(index >= 0);
testButton.setEnabled(index >= 0);
duplicateButton.setEnabled(index >= 0);
removeButton.setEnabled(index >= 0);
upButton.setEnabled(size > 1 && index > 0);
downButton.setEnabled(size > 1 && index >= 0 && index < size - 1);
}
public void setFocus() {
if (table != null) {
table.setFocus();
}
}
private void swap(boolean up) {
setPresentsDefaultValue(false);
int index = table.getSelectionIndex();
int target = up ? index - 1 : index + 1;
if (index >= 0) {
TableItem[] selection = table.getSelection();
Assert.isTrue(selection.length == 1);
String[] values = new String[columnNames.length];
for (int j = 0; j < columnNames.length; j++) {
values[j] = selection[0].getText(j);
}
table.remove(index);
TableItem tableItem = new TableItem(table, SWT.NONE, target);
tableItem.setText(values);
table.setSelection(target);
T temp = currentItems.get(index);
currentItems.set(index, currentItems.get(target));
currentItems.set(target, temp);
}
selectionChanged();
}
@Override
public void setEnabled(boolean enabled, Composite parent) {
super.setEnabled(enabled, parent);
getTableControl(parent).setEnabled(enabled);
addButton.setEnabled(enabled);
editButton.setEnabled(enabled);
duplicateButton.setEnabled(enabled);
removeButton.setEnabled(enabled);
upButton.setEnabled(enabled);
downButton.setEnabled(enabled);
}
}
|
package nyc.c4q;
import android.app.Activity;
import android.content.res.Resources;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(RobolectricTestRunner.class)
@Config(manifest = "src/main/AndroidManifest.xml", emulateSdk = 18)
public class Unit1AssessmentTests {
public static String getResourceId(View v){
int id = v.getId();
String idString = "no id";
if(id != View.NO_ID) {
Resources res = v.getResources();
if(res != null)
idString = res.getResourceEntryName(id);
}
return idString;
}
public static View findViewByIdString(Activity a, String s){
return a.findViewById(a.getResources().getIdentifier(s, "id", a.getPackageName()));
}
@Test
public void testSomething() throws Exception {
assertTrue(Robolectric.buildActivity(InitialActivity.class).create().get() != null);
}
@Test
public void test01FixInitialActivityLayout() throws Exception {
InitialActivity activity = Robolectric.buildActivity(InitialActivity.class).create().get();
LinearLayout layout = (LinearLayout) activity.findViewById(R.id.activity_initial);
// TODO only need the last assertTrue() method per view
assertTrue("LinearLayout(@+id/activity_initial)[0] should be a LinearLayout", layout.getChildAt(0) instanceof LinearLayout);
LinearLayout counterLayout = (LinearLayout) layout.getChildAt(0);
assertTrue("LinearLayout(@+id/activity_initial)[0] should have R.id.counterLayout", getResourceId(counterLayout).equals("counterLayout"));
assertTrue("LinearLayout(@+id/activity_initial)[0] should be equal to LinearLayout(@+id/counterLayout)", counterLayout == findViewByIdString(activity, "counterLayout"));
assertTrue("LinearLayout(@+id/activity_initial)[0] should have a horizontal orientation", counterLayout.getOrientation() == LinearLayout.HORIZONTAL);
assertTrue("LinearLayout(@+id/counterLayout)[0] should be a LinearLayout", counterLayout.getChildAt(0) instanceof LinearLayout);
LinearLayout counterButtonsLayout = (LinearLayout) counterLayout.getChildAt(0);
assertTrue("LinearLayout(@+id/counterLayout)[0] should have R.id.counterButtonsLayout", getResourceId(counterButtonsLayout).equals("counterButtonsLayout"));
assertTrue("LinearLayout(@+id/counterLayout)[0] should be equal to LinearLayout(@+id/counterButtonsLayout)", counterButtonsLayout == findViewByIdString(activity, "counterButtonsLayout"));
assertTrue("LinearLayout(@+id/counterLayout)[0] should have a vertical orientation", counterButtonsLayout.getOrientation() == LinearLayout.VERTICAL);
assertTrue("LinearLayout(@+id/counterButtonsLayout)[0] should be a Button", counterButtonsLayout.getChildAt(0) instanceof Button);
Button buttonPlus = (Button) counterButtonsLayout.getChildAt(0);
assertTrue("LinearLayout(@+id/counterButtonsLayout)[0] should have R.id.buttonPlus", getResourceId(buttonPlus).equals("buttonPlus"));
assertTrue("LinearLayout(@+id/counterButtonsLayout)[0] should be equal to LinearLayout(@+id/buttonPlus)", buttonPlus == findViewByIdString(activity, "buttonPlus"));
assertEquals("+", buttonPlus.getText());
assertTrue("LinearLayout(@+id/counterButtonsLayout)[1] should be a Button", counterButtonsLayout.getChildAt(1) instanceof Button);
Button buttonMinus = (Button) counterButtonsLayout.getChildAt(1);
assertTrue("LinearLayout(@+id/counterButtonsLayout)[1] should have R.id.buttonMinus", getResourceId(buttonMinus).equals("buttonMinus"));
assertTrue("LinearLayout(@+id/counterButtonsLayout)[1] should be equal to LinearLayout(@+id/buttonMinus)", buttonMinus == findViewByIdString(activity, "buttonMinus"));
assertEquals("-", buttonMinus.getText());
View tvCounter = counterLayout.getChildAt(1);
assertTrue("LinearLayout(@+id/activity_initial)[0][1] should be equal to TextView(@+id/tvCounter)",
tvCounter instanceof TextView && getResourceId(tvCounter).equals("tvCounter"));
assertEquals("0", ((TextView) tvCounter).getText());
View buttonTileActivity = layout.getChildAt(1);
assertTrue("LinearLayout(@+id/activity_initial)[1] should be equal to Button(@+id/buttonTileActivity)",
buttonTileActivity instanceof Button && getResourceId(buttonTileActivity).equals("buttonTileActivity"));
assertEquals("TileActivity", ((Button) buttonTileActivity).getText());
View buttonNewsReaderActivity = layout.getChildAt(2);
assertTrue("LinearLayout(@+id/activity_initial)[1] should be equal to Button(@+id/buttonNewsReaderActivity)",
buttonNewsReaderActivity instanceof Button && getResourceId(buttonNewsReaderActivity).equals("buttonNewsReaderActivity"));
assertEquals("NewsReaderActivity", ((Button) buttonNewsReaderActivity).getText());
View buttonBigTextActivity = layout.getChildAt(3);
assertTrue("LinearLayout(@+id/activity_initial)[1] should be equal to Button(@+id/buttonBigTextActivity)",
buttonBigTextActivity instanceof Button && getResourceId(buttonBigTextActivity).equals("buttonBigTextActivity"));
assertEquals("BigTextActivity", ((Button) buttonBigTextActivity).getText());
assertEquals("LinearLayout(@+id/counterLayout) should have layout_weight='2'", 2, ((LinearLayout.LayoutParams) counterLayout.getLayoutParams()).weight, 0.01);
assertEquals("LinearLayout(@+id/buttonTileActivity) should have layout_weight='1'", 1, ((LinearLayout.LayoutParams) buttonTileActivity.getLayoutParams()).weight, 0.01);
assertEquals("LinearLayout(@+id/buttonNewsReaderActivity) should have layout_weight='1'", 1, ((LinearLayout.LayoutParams) buttonNewsReaderActivity.getLayoutParams()).weight, 0.01);
assertEquals("LinearLayout(@+id/buttonBigTextActivity) should have layout_weight='1'", 1, ((LinearLayout.LayoutParams) buttonBigTextActivity.getLayoutParams()).weight, 0.01);
assertEquals("LinearLayout(@+id/counterButtonsLayout) should have layout_weight='1'", 1, ((LinearLayout.LayoutParams) counterButtonsLayout.getLayoutParams()).weight, 0.01);
assertEquals("LinearLayout(@+id/tvCounter) should have layout_weight='1'", 1, ((LinearLayout.LayoutParams) tvCounter.getLayoutParams()).weight, 0.01);
assertEquals("LinearLayout(@+id/buttonPlus) should have layout_weight='1'", 1, ((LinearLayout.LayoutParams) buttonPlus.getLayoutParams()).weight, 0.01);
assertEquals("LinearLayout(@+id/buttonMinus) should have layout_weight='1'", 1, ((LinearLayout.LayoutParams) buttonMinus.getLayoutParams()).weight, 0.01);
}
@Test
public void test11FixTileActivityLayout() throws Exception {
TileActivity ta = Robolectric.buildActivity(TileActivity.class).create().get();
LinearLayout taLayout = (LinearLayout) ta.findViewById(R.id.activity_tile);
assertTrue("LinearLayout(@+id/activity_tile) should have a vertical orientation",
taLayout.getOrientation() == LinearLayout.VERTICAL);
int leftSideId = ta.getResources().getIdentifier("leftSide", "id", ta.getPackageName());
int rightSideId = ta.getResources().getIdentifier("rightSide", "id", ta.getPackageName());
assertTrue("LinearLayout(@+id/leftSide) not found", leftSideId > 0);
assertTrue("LinearLayout(@+id/rightSide) not found", rightSideId > 0);
View leftSideById = ta.findViewById(leftSideId);
View rightSideById = ta.findViewById(rightSideId);
View leftSide = taLayout.getChildAt(0);
View rightSide = taLayout.getChildAt(1);
assertTrue("leftSide is not a LinearLayout", leftSide instanceof LinearLayout);
assertTrue("rightSide is not a LinearLayout", rightSide instanceof LinearLayout);
assertTrue("LinearLayout(@+id/activity_tile)[0] should be equal to LinearLayout(@+id/leftSide)",
leftSide == leftSideById);
assertTrue("LinearLayout(@+id/activity_tile)[1] should be equal to LinearLayout(@+id/rightSide)",
rightSide == rightSideById);
LinearLayout leftSideLayout = (LinearLayout) leftSide;
LinearLayout rightSideLayout = (LinearLayout) rightSide;
View red = leftSideLayout.getChildAt(0);
View green = leftSideLayout.getChildAt(1);
View yellow = rightSideLayout.getChildAt(0);
View white = rightSideLayout.getChildAt(1);
View blue = rightSideLayout.getChildAt(2);
assertTrue("LinearLayout(@+id/leftSide).getOrientation() should be vertical",
leftSideLayout.getOrientation() == LinearLayout.VERTICAL);
assertTrue("LinearLayout(@+id/rightSide).getOrientation() should be vertical",
leftSideLayout.getOrientation() == LinearLayout.VERTICAL);
Log.d("Unit1Assessment", String.format("red:%d, green: %d, yellow: %d, white: %d, blue: %d",
((LinearLayout.LayoutParams) red.getLayoutParams()).weight,
((LinearLayout.LayoutParams) green.getLayoutParams()).weight,
((LinearLayout.LayoutParams) yellow.getLayoutParams()).weight,
((LinearLayout.LayoutParams) white.getLayoutParams()).weight,
((LinearLayout.LayoutParams) blue.getLayoutParams()).weight));
// TODO test on dp, padding, padding around the views
}
}
|
package org.jinstagram;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.ArrayList;
import java.util.List;
import org.jinstagram.auth.model.Token;
import org.jinstagram.entity.common.Location;
import org.jinstagram.entity.common.Meta;
import org.jinstagram.entity.locations.LocationSearchFeed;
import org.jinstagram.entity.tags.TagMediaFeed;
import org.jinstagram.entity.users.basicinfo.UserInfo;
import org.jinstagram.entity.users.basicinfo.UserInfoData;
import org.jinstagram.entity.users.feed.MediaFeed;
import org.jinstagram.entity.users.feed.MediaFeedData;
import org.jinstagram.entity.users.feed.UserFeed;
import org.jinstagram.entity.users.feed.UserFeedData;
import org.jinstagram.exceptions.InstagramBadRequestException;
import org.jinstagram.exceptions.InstagramException;
import org.jinstagram.exceptions.InstagramRateLimitException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
public class InstagramTest {
private final Logger logger = LoggerFactory.getLogger(InstagramTest.class);
private static final String IG_TOKEN_SYSTEM_PROPERTY = "IG_ACCESS_TOKEN";
private InstagramClient instagram = null;
@Before
public void beforeMethod() {
org.junit.Assume.assumeTrue(isAccessTokenAvailable());
}
private boolean isAccessTokenAvailable() {
if (System.getenv(IG_TOKEN_SYSTEM_PROPERTY) != null) {
logger.info("Access token found...");
String ACCESS_TOKEN = System.getenv(IG_TOKEN_SYSTEM_PROPERTY);
Token token = new Token(ACCESS_TOKEN, null);
instagram = new Instagram(token);
return true;
} else {
logger.error("No access token found...");
}
return false;
}
@Test(expected = InstagramBadRequestException.class)
public void testInvalidAccessToken() throws Exception {
InstagramClient instagram = new Instagram(new Token("InvalidAccessToken", null));
instagram.getPopularMedia();
}
@Test
@Ignore
public void testInvalidRequest() throws Exception {
instagram.getRecentMediaTags("test/u10191");
}
@Test
public void testCurrentUserInfo() throws Exception {
UserInfo userInfo = instagram.getCurrentUserInfo();
UserInfoData userInfoData = userInfo.getData();
logger.info("Username : " + userInfoData.getUsername());
logger.info("Full name : " + userInfoData.getFullName());
logger.info("Bio : " + userInfoData.getBio());
}
@Test
@Ignore //cause getPopularMedia is deprecated
public void testPopularMedia() throws Exception {
logger.info("Printing a list of popular media...");
MediaFeed popularMedia = instagram.getPopularMedia();
printMediaFeedList(popularMedia.getData());
}
@Test
public void searchLocation() throws Exception {
double latitude = 51.5072;
double longitude = 0.1275;
LocationSearchFeed locationSearchFeed = instagram.searchLocation(latitude, longitude);
List<Location> locationList = locationSearchFeed.getLocationList();
logger.info("Printing Location Details for Latitude " + latitude + " and longitude " + longitude);
for (Location location : locationList) {
logger.info("
logger.info("Id : " + location.getId());
logger.info("Name : " + location.getName());
logger.info("Latitude : " + location.getLatitude());
logger.info("Longitude : " + location.getLatitude());
logger.info("
}
}
@Test
public void searchLocationWithDistance() throws Exception {
double latitude = 51.5072;
double longitude = 0.1275;
int distance = 1000;
LocationSearchFeed locationSearchFeed = instagram.searchLocation(latitude, longitude, distance);
List<Location> locationList = locationSearchFeed.getLocationList();
logger.info("Printing Location Details for Latitude " + latitude + " and longitude " + longitude);
for (Location location : locationList) {
logger.info("
logger.info("Id : " + location.getId());
logger.info("Name : " + location.getName());
logger.info("Latitude : " + location.getLatitude());
logger.info("Longitude : " + location.getLatitude());
logger.info("
}
}
@Test
@Ignore // failing due to user not found
public void userFollowedBy() throws Exception {
// instagram user id
String userId = "25025320";
UserFeed feed1 = instagram.getUserFollowedByList(userId);
assertEquals(50, feed1.getUserList().size());
UserFeed feed2 = instagram.getUserFollowedByListNextPage(userId, feed1.getPagination().getNextCursor());
assertEquals(50, feed2.getUserList().size());
assertNotEquals(feed1.getUserList().get(0).getId(), feed2.getUserList().get(1).getId());
}
@Test
@Ignore // failing due to user not found
public void userFollower() throws Exception {
// instagram user id
String userId = "25025320";
UserFeed feed1 = instagram.getUserFollowList(userId);
assertEquals(50, feed1.getUserList().size());
UserFeed feed2 = instagram.getUserFollowListNextPage(userId, feed1.getPagination().getNextCursor());
assertEquals(50, feed2.getUserList().size());
assertNotEquals(feed1.getUserList().get(0).getId(), feed2.getUserList().get(1).getId());
}
@Test
public void searchUser() throws Exception {
String query = "sachin";
UserFeed userFeed = instagram.searchUser(query);
for (UserFeedData userFeedData : userFeed.getUserList()) {
System.out.println("\n\n**************************************************");
System.out.println("Id : " + userFeedData.getId());
System.out.println("Username : " + userFeedData.getUserName());
System.out.println("Name : " + userFeedData.getFullName());
System.out.println("Bio : " + userFeedData.getBio());
System.out.println("Profile Picture URL : " + userFeedData.getProfilePictureUrl());
System.out.println("Website : " + userFeedData.getWebsite());
System.out.println("**************************************************\n\n");
}
}
@Test
public void getMediaByTags() throws Exception {
String tagName = "london";
TagMediaFeed recentMediaTags = instagram.getRecentMediaTags(tagName);
printMediaFeedList(recentMediaTags.getData());
}
@Test
@Ignore
public void getMediaByTagsSpecialCharacters() throws Exception {
String tagName = "london";
TagMediaFeed recentMediaTags = instagram.getRecentMediaTags(tagName);
printMediaFeedList(recentMediaTags.getData());
}
@Test
@Ignore // failing due to user not found
public void testGetAllUserPhotos() throws Exception {
getUserPhotos("18428658");
}
private List<MediaFeedData> getUserPhotos(String userId) throws Exception {
// Don't get all the photos, just break the page count on 5
final int countBreaker = 5;
MediaFeed recentMediaFeed = instagram.getRecentMediaFeed(userId);
List<MediaFeedData> userPhotos = new ArrayList<MediaFeedData>();
for (MediaFeedData mediaFeedData : recentMediaFeed.getData()) {
userPhotos.add(mediaFeedData);
}
int count = 0;
while (recentMediaFeed.getPagination() != null) {
count++;
if (count == countBreaker) {
System.out.println("Too many photos to get!!! Breaking the loop.");
break;
}
try {
recentMediaFeed = instagram.getRecentMediaNextPage(recentMediaFeed.getPagination());
for (MediaFeedData mediaFeedData : recentMediaFeed.getData()) {
userPhotos.add(mediaFeedData);
}
} catch (Exception ex) {
break;
}
}
return userPhotos;
}
private void printMediaFeedList(List<MediaFeedData> mediaFeedDataList) {
for (MediaFeedData mediaFeedData : mediaFeedDataList) {
logger.info("
logger.info("Id : " + mediaFeedData.getId());
logger.info("Image Filter : " + mediaFeedData.getImageFilter());
logger.info("Link : " + mediaFeedData.getLink());
logger.info("
}
}
@Test(expected = InstagramRateLimitException.class)
public void testCheckRateLimitException() throws InstagramException {
int responseCode = 429;
String responseBody = createRateLimitMeta(429);
Instagram instagram2=(Instagram) instagram;
instagram2.handleInstagramError(responseCode, responseBody, null);
}
private String createRateLimitMeta(int code) {
Meta meta = new Meta();
meta.setCode(code);
meta.setErrorMessage("message");
meta.setErrorType("type");
return new Gson().toJson(meta);
}
@Test
public void testGetUserRecentMedia() throws Exception{
MediaFeed mf = instagram.getUserRecentMedia();
List<MediaFeedData> mediaFeedDataList = mf.getData();
printMediaFeedList(mediaFeedDataList);
}
@Test
@Ignore // Will fix later on
public void testGetUserRecentMediaWithParams() throws Exception{
MediaFeed mf = instagram.getUserRecentMedia(2, null, null);
List<MediaFeedData> mediaFeedDataList = mf.getData();
Assert.assertEquals(mediaFeedDataList.size(), 2);
printMediaFeedList(mediaFeedDataList);
}
}
|
package com.jme3.util;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.math.Vector4f;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>BufferUtils</code> is a helper class for generating nio buffers from
* jME data classes such as Vectors and ColorRGBA.
*
* @author Joshua Slack
* @version $Id: BufferUtils.java,v 1.16 2007/10/29 16:56:18 nca Exp $
*/
public final class BufferUtils {
private static boolean trackDirectMemory = false;
private static ReferenceQueue<Buffer> removeCollected = new ReferenceQueue<Buffer>();
private static ConcurrentHashMap<BufferInfo, BufferInfo> trackedBuffers = new ConcurrentHashMap<BufferInfo, BufferInfo>();
static ClearReferences cleanupthread;
/**
* Set it to true if you want to enable direct memory tracking for debugging purpose.
* Default is false.
* To print direct memory usage use BufferUtils.printCurrentDirectMemory(StringBuilder store);
* @param enabled
*/
public static void setTrackDirectMemoryEnabled(boolean enabled) {
trackDirectMemory = enabled;
}
/**
* Creates a clone of the given buffer. The clone's capacity is
* equal to the given buffer's limit.
*
* @param buf The buffer to clone
* @return The cloned buffer
*/
public static Buffer clone(Buffer buf) {
if (buf instanceof FloatBuffer) {
return clone((FloatBuffer) buf);
} else if (buf instanceof ShortBuffer) {
return clone((ShortBuffer) buf);
} else if (buf instanceof ByteBuffer) {
return clone((ByteBuffer) buf);
} else if (buf instanceof IntBuffer) {
return clone((IntBuffer) buf);
} else if (buf instanceof DoubleBuffer) {
return clone((DoubleBuffer) buf);
} else {
throw new UnsupportedOperationException();
}
}
private static void onBufferAllocated(Buffer buffer) {
/**
* StackTraceElement[] stackTrace = new Throwable().getStackTrace(); int
* initialIndex = 0;
*
* for (int i = 0; i < stackTrace.length; i++){ if
* (!stackTrace[i].getClassName().equals(BufferUtils.class.getName())){
* initialIndex = i; break; } }
*
* int allocated = buffer.capacity(); int size = 0;
*
* if (buffer instanceof FloatBuffer){ size = 4; }else if (buffer
* instanceof ShortBuffer){ size = 2; }else if (buffer instanceof
* ByteBuffer){ size = 1; }else if (buffer instanceof IntBuffer){ size =
* 4; }else if (buffer instanceof DoubleBuffer){ size = 8; }
*
* allocated *= size;
*
* for (int i = initialIndex; i < stackTrace.length; i++){
* StackTraceElement element = stackTrace[i]; if
* (element.getClassName().startsWith("java")){ break; }
*
* try { Class clazz = Class.forName(element.getClassName()); if (i ==
* initialIndex){
* System.out.println(clazz.getSimpleName()+"."+element.getMethodName
* ()+"():" + element.getLineNumber() + " allocated " + allocated);
* }else{ System.out.println(" at " +
* clazz.getSimpleName()+"."+element.getMethodName()+"()"); } } catch
* (ClassNotFoundException ex) { } }
*/
if (BufferUtils.trackDirectMemory) {
if (BufferUtils.cleanupthread == null) {
BufferUtils.cleanupthread = new ClearReferences();
BufferUtils.cleanupthread.start();
}
if (buffer instanceof ByteBuffer) {
BufferInfo info = new BufferInfo(ByteBuffer.class, buffer.capacity(), buffer, BufferUtils.removeCollected);
BufferUtils.trackedBuffers.put(info, info);
} else if (buffer instanceof FloatBuffer) {
BufferInfo info = new BufferInfo(FloatBuffer.class, buffer.capacity() * 4, buffer, BufferUtils.removeCollected);
BufferUtils.trackedBuffers.put(info, info);
} else if (buffer instanceof IntBuffer) {
BufferInfo info = new BufferInfo(IntBuffer.class, buffer.capacity() * 4, buffer, BufferUtils.removeCollected);
BufferUtils.trackedBuffers.put(info, info);
} else if (buffer instanceof ShortBuffer) {
BufferInfo info = new BufferInfo(ShortBuffer.class, buffer.capacity() * 2, buffer, BufferUtils.removeCollected);
BufferUtils.trackedBuffers.put(info, info);
} else if (buffer instanceof DoubleBuffer) {
BufferInfo info = new BufferInfo(DoubleBuffer.class, buffer.capacity() * 8, buffer, BufferUtils.removeCollected);
BufferUtils.trackedBuffers.put(info, info);
}
}
}
/**
* Generate a new FloatBuffer using the given array of Vector3f objects.
* The FloatBuffer will be 3 * data.length long and contain the vector data
* as data[0].x, data[0].y, data[0].z, data[1].x... etc.
*
* @param data array of Vector3f objects to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(Vector3f... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(3 * data.length);
for (Vector3f element : data) {
if (element != null) {
buff.put(element.x).put(element.y).put(element.z);
} else {
buff.put(0).put(0).put(0);
}
}
buff.flip();
return buff;
}
/**
* Generate a new FloatBuffer using the given array of Quaternion objects.
* The FloatBuffer will be 4 * data.length long and contain the vector data.
*
* @param data array of Quaternion objects to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(Quaternion... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(4 * data.length);
for (Quaternion element : data) {
if (element != null) {
buff.put(element.getX()).put(element.getY()).put(element.getZ()).put(element.getW());
} else {
buff.put(0).put(0).put(0).put(0);
}
}
buff.flip();
return buff;
}
/**
* Generate a new FloatBuffer using the given array of Vector4 objects.
* The FloatBuffer will be 4 * data.length long and contain the vector data.
*
* @param data array of Vector4 objects to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(Vector4f... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(4 * data.length);
for (int x = 0; x < data.length; x++) {
if (data[x] != null) {
buff.put(data[x].getX()).put(data[x].getY()).put(data[x].getZ()).put(data[x].getW());
} else {
buff.put(0).put(0).put(0).put(0);
}
}
buff.flip();
return buff;
}
/**
* Generate a new FloatBuffer using the given array of float primitives.
* @param data array of float primitives to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(float... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(data.length);
buff.clear();
buff.put(data);
buff.flip();
return buff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector3f object data.
*
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector3Buffer(int vertices) {
FloatBuffer vBuff = createFloatBuffer(3 * vertices);
return vBuff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector3f object data only if the given buffer if not already
* the right size.
*
* @param buf
* the buffer to first check and rewind
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector3Buffer(FloatBuffer buf, int vertices) {
if (buf != null && buf.limit() == 3 * vertices) {
buf.rewind();
return buf;
}
return createFloatBuffer(3 * vertices);
}
/**
* Sets the data contained in the given color into the FloatBuffer at the
* specified index.
*
* @param color
* the data to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of colors not floats
*/
public static void setInBuffer(ColorRGBA color, FloatBuffer buf,
int index) {
buf.position(index * 4);
buf.put(color.r);
buf.put(color.g);
buf.put(color.b);
buf.put(color.a);
}
/**
* Sets the data contained in the given quaternion into the FloatBuffer at the
* specified index.
*
* @param quat
* the {@link Quaternion} to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of quaternions not floats
*/
public static void setInBuffer(Quaternion quat, FloatBuffer buf,
int index) {
buf.position(index * 4);
buf.put(quat.getX());
buf.put(quat.getY());
buf.put(quat.getZ());
buf.put(quat.getW());
}
/**
* Sets the data contained in the given vector4 into the FloatBuffer at the
* specified index.
*
* @param vec
* the {@link Vector4f} to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of vector4 not floats
*/
public static void setInBuffer(Vector4f vec, FloatBuffer buf,
int index) {
buf.position(index * 4);
buf.put(vec.getX());
buf.put(vec.getY());
buf.put(vec.getZ());
buf.put(vec.getW());
}
/**
* Sets the data contained in the given Vector3F into the FloatBuffer at the
* specified index.
*
* @param vector
* the data to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of vectors not floats
*/
public static void setInBuffer(Vector3f vector, FloatBuffer buf, int index) {
if (buf == null) {
return;
}
if (vector == null) {
buf.put(index * 3, 0);
buf.put((index * 3) + 1, 0);
buf.put((index * 3) + 2, 0);
} else {
buf.put(index * 3, vector.x);
buf.put((index * 3) + 1, vector.y);
buf.put((index * 3) + 2, vector.z);
}
}
/**
* Updates the values of the given vector from the specified buffer at the
* index provided.
*
* @param vector
* the vector to set data on
* @param buf
* the buffer to read from
* @param index
* the position (in terms of vectors, not floats) to read from
* the buf
*/
public static void populateFromBuffer(Vector3f vector, FloatBuffer buf, int index) {
vector.x = buf.get(index * 3);
vector.y = buf.get(index * 3 + 1);
vector.z = buf.get(index * 3 + 2);
}
/**
* Generates a Vector3f array from the given FloatBuffer.
*
* @param buff
* the FloatBuffer to read from
* @return a newly generated array of Vector3f objects
*/
public static Vector3f[] getVector3Array(FloatBuffer buff) {
buff.clear();
Vector3f[] verts = new Vector3f[buff.limit() / 3];
for (int x = 0; x < verts.length; x++) {
Vector3f v = new Vector3f(buff.get(), buff.get(), buff.get());
verts[x] = v;
}
return verts;
}
/**
* Copies a Vector3f from one position in the buffer to another. The index
* values are in terms of vector number (eg, vector number 0 is postions 0-2
* in the FloatBuffer.)
*
* @param buf
* the buffer to copy from/to
* @param fromPos
* the index of the vector to copy
* @param toPos
* the index to copy the vector to
*/
public static void copyInternalVector3(FloatBuffer buf, int fromPos, int toPos) {
copyInternal(buf, fromPos * 3, toPos * 3, 3);
}
/**
* Normalize a Vector3f in-buffer.
*
* @param buf
* the buffer to find the Vector3f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to normalize
*/
public static void normalizeVector3(FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
tempVec3.normalizeLocal();
setInBuffer(tempVec3, buf, index);
vars.release();
}
/**
* Add to a Vector3f in-buffer.
*
* @param toAdd
* the vector to add from
* @param buf
* the buffer to find the Vector3f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to add to
*/
public static void addInBuffer(Vector3f toAdd, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
tempVec3.addLocal(toAdd);
setInBuffer(tempVec3, buf, index);
vars.release();
}
/**
* Multiply and store a Vector3f in-buffer.
*
* @param toMult
* the vector to multiply against
* @param buf
* the buffer to find the Vector3f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to multiply
*/
public static void multInBuffer(Vector3f toMult, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
tempVec3.multLocal(toMult);
setInBuffer(tempVec3, buf, index);
vars.release();
}
/**
* Checks to see if the given Vector3f is equals to the data stored in the
* buffer at the given data index.
*
* @param check
* the vector to check against - null will return false.
* @param buf
* the buffer to compare data with
* @param index
* the position (in terms of vectors, not floats) of the vector
* in the buffer to check against
* @return true if the data is equivalent, otherwise false.
*/
public static boolean equals(Vector3f check, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector3f tempVec3 = vars.vect1;
populateFromBuffer(tempVec3, buf, index);
boolean eq = tempVec3.equals(check);
vars.release();
return eq;
}
// // -- VECTOR2F METHODS -- ////
/**
* Generate a new FloatBuffer using the given array of Vector2f objects.
* The FloatBuffer will be 2 * data.length long and contain the vector data
* as data[0].x, data[0].y, data[1].x... etc.
*
* @param data array of Vector2f objects to place into a new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(Vector2f... data) {
if (data == null) {
return null;
}
FloatBuffer buff = createFloatBuffer(2 * data.length);
for (Vector2f element : data) {
if (element != null) {
buff.put(element.x).put(element.y);
} else {
buff.put(0).put(0);
}
}
buff.flip();
return buff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector2f object data.
*
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector2Buffer(int vertices) {
FloatBuffer vBuff = createFloatBuffer(2 * vertices);
return vBuff;
}
/**
* Create a new FloatBuffer of an appropriate size to hold the specified
* number of Vector2f object data only if the given buffer if not already
* the right size.
*
* @param buf
* the buffer to first check and rewind
* @param vertices
* number of vertices that need to be held by the newly created
* buffer
* @return the requested new FloatBuffer
*/
public static FloatBuffer createVector2Buffer(FloatBuffer buf, int vertices) {
if (buf != null && buf.limit() == 2 * vertices) {
buf.rewind();
return buf;
}
return createFloatBuffer(2 * vertices);
}
/**
* Sets the data contained in the given Vector2F into the FloatBuffer at the
* specified index.
*
* @param vector
* the data to insert
* @param buf
* the buffer to insert into
* @param index
* the postion to place the data; in terms of vectors not floats
*/
public static void setInBuffer(Vector2f vector, FloatBuffer buf, int index) {
buf.put(index * 2, vector.x);
buf.put((index * 2) + 1, vector.y);
}
/**
* Updates the values of the given vector from the specified buffer at the
* index provided.
*
* @param vector
* the vector to set data on
* @param buf
* the buffer to read from
* @param index
* the position (in terms of vectors, not floats) to read from
* the buf
*/
public static void populateFromBuffer(Vector2f vector, FloatBuffer buf, int index) {
vector.x = buf.get(index * 2);
vector.y = buf.get(index * 2 + 1);
}
/**
* Generates a Vector2f array from the given FloatBuffer.
*
* @param buff
* the FloatBuffer to read from
* @return a newly generated array of Vector2f objects
*/
public static Vector2f[] getVector2Array(FloatBuffer buff) {
buff.clear();
Vector2f[] verts = new Vector2f[buff.limit() / 2];
for (int x = 0; x < verts.length; x++) {
Vector2f v = new Vector2f(buff.get(), buff.get());
verts[x] = v;
}
return verts;
}
/**
* Copies a Vector2f from one position in the buffer to another. The index
* values are in terms of vector number (eg, vector number 0 is postions 0-1
* in the FloatBuffer.)
*
* @param buf
* the buffer to copy from/to
* @param fromPos
* the index of the vector to copy
* @param toPos
* the index to copy the vector to
*/
public static void copyInternalVector2(FloatBuffer buf, int fromPos, int toPos) {
copyInternal(buf, fromPos * 2, toPos * 2, 2);
}
/**
* Normalize a Vector2f in-buffer.
*
* @param buf
* the buffer to find the Vector2f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to normalize
*/
public static void normalizeVector2(FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
tempVec2.normalizeLocal();
setInBuffer(tempVec2, buf, index);
vars.release();
}
/**
* Add to a Vector2f in-buffer.
*
* @param toAdd
* the vector to add from
* @param buf
* the buffer to find the Vector2f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to add to
*/
public static void addInBuffer(Vector2f toAdd, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
tempVec2.addLocal(toAdd);
setInBuffer(tempVec2, buf, index);
vars.release();
}
/**
* Multiply and store a Vector2f in-buffer.
*
* @param toMult
* the vector to multiply against
* @param buf
* the buffer to find the Vector2f within
* @param index
* the position (in terms of vectors, not floats) of the vector
* to multiply
*/
public static void multInBuffer(Vector2f toMult, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
tempVec2.multLocal(toMult);
setInBuffer(tempVec2, buf, index);
vars.release();
}
/**
* Checks to see if the given Vector2f is equals to the data stored in the
* buffer at the given data index.
*
* @param check
* the vector to check against - null will return false.
* @param buf
* the buffer to compare data with
* @param index
* the position (in terms of vectors, not floats) of the vector
* in the buffer to check against
* @return true if the data is equivalent, otherwise false.
*/
public static boolean equals(Vector2f check, FloatBuffer buf, int index) {
TempVars vars = TempVars.get();
Vector2f tempVec2 = vars.vect2d;
populateFromBuffer(tempVec2, buf, index);
boolean eq = tempVec2.equals(check);
vars.release();
return eq;
}
//// -- INT METHODS -- ////
/**
* Generate a new IntBuffer using the given array of ints. The IntBuffer
* will be data.length long and contain the int data as data[0], data[1]...
* etc.
*
* @param data
* array of ints to place into a new IntBuffer
*/
public static IntBuffer createIntBuffer(int... data) {
if (data == null) {
return null;
}
IntBuffer buff = createIntBuffer(data.length);
buff.clear();
buff.put(data);
buff.flip();
return buff;
}
/**
* Create a new int[] array and populate it with the given IntBuffer's
* contents.
*
* @param buff
* the IntBuffer to read from
* @return a new int array populated from the IntBuffer
*/
public static int[] getIntArray(IntBuffer buff) {
if (buff == null) {
return null;
}
buff.clear();
int[] inds = new int[buff.limit()];
for (int x = 0; x < inds.length; x++) {
inds[x] = buff.get();
}
return inds;
}
/**
* Create a new float[] array and populate it with the given FloatBuffer's
* contents.
*
* @param buff
* the FloatBuffer to read from
* @return a new float array populated from the FloatBuffer
*/
public static float[] getFloatArray(FloatBuffer buff) {
if (buff == null) {
return null;
}
buff.clear();
float[] inds = new float[buff.limit()];
for (int x = 0; x < inds.length; x++) {
inds[x] = buff.get();
}
return inds;
}
//// -- GENERAL DOUBLE ROUTINES -- ////
/**
* Create a new DoubleBuffer of the specified size.
*
* @param size
* required number of double to store.
* @return the new DoubleBuffer
*/
public static DoubleBuffer createDoubleBuffer(int size) {
DoubleBuffer buf = ByteBuffer.allocateDirect(8 * size).order(ByteOrder.nativeOrder()).asDoubleBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new DoubleBuffer of an appropriate size to hold the specified
* number of doubles only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of doubles that need to be held by the newly created
* buffer
* @return the requested new DoubleBuffer
*/
public static DoubleBuffer createDoubleBuffer(DoubleBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createDoubleBuffer(size);
return buf;
}
/**
* Creates a new DoubleBuffer with the same contents as the given
* DoubleBuffer. The new DoubleBuffer is seperate from the old one and
* changes are not reflected across. If you want to reflect changes,
* consider using Buffer.duplicate().
*
* @param buf
* the DoubleBuffer to copy
* @return the copy
*/
public static DoubleBuffer clone(DoubleBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
DoubleBuffer copy;
if (isDirect(buf)) {
copy = createDoubleBuffer(buf.limit());
} else {
copy = DoubleBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL FLOAT ROUTINES -- ////
/**
* Create a new FloatBuffer of the specified size.
*
* @param size
* required number of floats to store.
* @return the new FloatBuffer
*/
public static FloatBuffer createFloatBuffer(int size) {
FloatBuffer buf = ByteBuffer.allocateDirect(4 * size).order(ByteOrder.nativeOrder()).asFloatBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Copies floats from one position in the buffer to another.
*
* @param buf
* the buffer to copy from/to
* @param fromPos
* the starting point to copy from
* @param toPos
* the starting point to copy to
* @param length
* the number of floats to copy
*/
public static void copyInternal(FloatBuffer buf, int fromPos, int toPos, int length) {
float[] data = new float[length];
buf.position(fromPos);
buf.get(data);
buf.position(toPos);
buf.put(data);
}
/**
* Creates a new FloatBuffer with the same contents as the given
* FloatBuffer. The new FloatBuffer is seperate from the old one and changes
* are not reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the FloatBuffer to copy
* @return the copy
*/
public static FloatBuffer clone(FloatBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
FloatBuffer copy;
if (isDirect(buf)) {
copy = createFloatBuffer(buf.limit());
} else {
copy = FloatBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL INT ROUTINES -- ////
/**
* Create a new IntBuffer of the specified size.
*
* @param size
* required number of ints to store.
* @return the new IntBuffer
*/
public static IntBuffer createIntBuffer(int size) {
IntBuffer buf = ByteBuffer.allocateDirect(4 * size).order(ByteOrder.nativeOrder()).asIntBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new IntBuffer of an appropriate size to hold the specified
* number of ints only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of ints that need to be held by the newly created
* buffer
* @return the requested new IntBuffer
*/
public static IntBuffer createIntBuffer(IntBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createIntBuffer(size);
return buf;
}
/**
* Creates a new IntBuffer with the same contents as the given IntBuffer.
* The new IntBuffer is seperate from the old one and changes are not
* reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the IntBuffer to copy
* @return the copy
*/
public static IntBuffer clone(IntBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
IntBuffer copy;
if (isDirect(buf)) {
copy = createIntBuffer(buf.limit());
} else {
copy = IntBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL BYTE ROUTINES -- ////
/**
* Create a new ByteBuffer of the specified size.
*
* @param size
* required number of ints to store.
* @return the new IntBuffer
*/
public static ByteBuffer createByteBuffer(int size) {
ByteBuffer buf = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new ByteBuffer of an appropriate size to hold the specified
* number of ints only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of bytes that need to be held by the newly created
* buffer
* @return the requested new IntBuffer
*/
public static ByteBuffer createByteBuffer(ByteBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createByteBuffer(size);
return buf;
}
public static ByteBuffer createByteBuffer(byte... data) {
ByteBuffer bb = createByteBuffer(data.length);
bb.put(data);
bb.flip();
return bb;
}
public static ByteBuffer createByteBuffer(String data) {
byte[] bytes = data.getBytes();
ByteBuffer bb = createByteBuffer(bytes.length);
bb.put(bytes);
bb.flip();
return bb;
}
/**
* Creates a new ByteBuffer with the same contents as the given ByteBuffer.
* The new ByteBuffer is seperate from the old one and changes are not
* reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the ByteBuffer to copy
* @return the copy
*/
public static ByteBuffer clone(ByteBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
ByteBuffer copy;
if (isDirect(buf)) {
copy = createByteBuffer(buf.limit());
} else {
copy = ByteBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
//// -- GENERAL SHORT ROUTINES -- ////
/**
* Create a new ShortBuffer of the specified size.
*
* @param size
* required number of shorts to store.
* @return the new ShortBuffer
*/
public static ShortBuffer createShortBuffer(int size) {
ShortBuffer buf = ByteBuffer.allocateDirect(2 * size).order(ByteOrder.nativeOrder()).asShortBuffer();
buf.clear();
onBufferAllocated(buf);
return buf;
}
/**
* Create a new ShortBuffer of an appropriate size to hold the specified
* number of shorts only if the given buffer if not already the right size.
*
* @param buf
* the buffer to first check and rewind
* @param size
* number of shorts that need to be held by the newly created
* buffer
* @return the requested new ShortBuffer
*/
public static ShortBuffer createShortBuffer(ShortBuffer buf, int size) {
if (buf != null && buf.limit() == size) {
buf.rewind();
return buf;
}
buf = createShortBuffer(size);
return buf;
}
public static ShortBuffer createShortBuffer(short... data) {
if (data == null) {
return null;
}
ShortBuffer buff = createShortBuffer(data.length);
buff.clear();
buff.put(data);
buff.flip();
return buff;
}
/**
* Creates a new ShortBuffer with the same contents as the given ShortBuffer.
* The new ShortBuffer is seperate from the old one and changes are not
* reflected across. If you want to reflect changes, consider using
* Buffer.duplicate().
*
* @param buf
* the ShortBuffer to copy
* @return the copy
*/
public static ShortBuffer clone(ShortBuffer buf) {
if (buf == null) {
return null;
}
buf.rewind();
ShortBuffer copy;
if (isDirect(buf)) {
copy = createShortBuffer(buf.limit());
} else {
copy = ShortBuffer.allocate(buf.limit());
}
copy.put(buf);
return copy;
}
/**
* Ensures there is at least the <code>required</code> number of entries left after the current position of the
* buffer. If the buffer is too small a larger one is created and the old one copied to the new buffer.
* @param buffer buffer that should be checked/copied (may be null)
* @param required minimum number of elements that should be remaining in the returned buffer
* @return a buffer large enough to receive at least the <code>required</code> number of entries, same position as
* the input buffer, not null
*/
public static FloatBuffer ensureLargeEnough(FloatBuffer buffer, int required) {
if (buffer != null) {
buffer.limit(buffer.capacity());
}
if (buffer == null || (buffer.remaining() < required)) {
int position = (buffer != null ? buffer.position() : 0);
FloatBuffer newVerts = createFloatBuffer(position + required);
if (buffer != null) {
buffer.flip();
newVerts.put(buffer);
newVerts.position(position);
}
buffer = newVerts;
}
return buffer;
}
public static ShortBuffer ensureLargeEnough(ShortBuffer buffer, int required) {
if (buffer != null) {
buffer.limit(buffer.capacity());
}
if (buffer == null || (buffer.remaining() < required)) {
int position = (buffer != null ? buffer.position() : 0);
ShortBuffer newVerts = createShortBuffer(position + required);
if (buffer != null) {
buffer.flip();
newVerts.put(buffer);
newVerts.position(position);
}
buffer = newVerts;
}
return buffer;
}
public static ByteBuffer ensureLargeEnough(ByteBuffer buffer, int required) {
if (buffer != null) {
buffer.limit(buffer.capacity());
}
if (buffer == null || (buffer.remaining() < required)) {
int position = (buffer != null ? buffer.position() : 0);
ByteBuffer newVerts = createByteBuffer(position + required);
if (buffer != null) {
buffer.flip();
newVerts.put(buffer);
newVerts.position(position);
}
buffer = newVerts;
}
return buffer;
}
public static void printCurrentDirectMemory(StringBuilder store) {
long totalHeld = 0;
long heapMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
boolean printStout = store == null;
if (store == null) {
store = new StringBuilder();
}
if (trackDirectMemory) {
// make a new set to hold the keys to prevent concurrency issues.
int fBufs = 0, bBufs = 0, iBufs = 0, sBufs = 0, dBufs = 0;
int fBufsM = 0, bBufsM = 0, iBufsM = 0, sBufsM = 0, dBufsM = 0;
for (BufferInfo b : BufferUtils.trackedBuffers.values()) {
if (b.type == ByteBuffer.class) {
totalHeld += b.size;
bBufsM += b.size;
bBufs++;
} else if (b.type == FloatBuffer.class) {
totalHeld += b.size;
fBufsM += b.size;
fBufs++;
} else if (b.type == IntBuffer.class) {
totalHeld += b.size;
iBufsM += b.size;
iBufs++;
} else if (b.type == ShortBuffer.class) {
totalHeld += b.size;
sBufsM += b.size;
sBufs++;
} else if (b.type == DoubleBuffer.class) {
totalHeld += b.size;
dBufsM += b.size;
dBufs++;
}
}
store.append("Existing buffers: ").append(BufferUtils.trackedBuffers.size()).append("\n");
store.append("(b: ").append(bBufs).append(" f: ").append(fBufs).append(" i: ").append(iBufs).append(" s: ").append(sBufs).append(" d: ").append(dBufs).append(")").append("\n");
store.append("Total heap memory held: ").append(heapMem / 1024).append("kb\n");
store.append("Total direct memory held: ").append(totalHeld / 1024).append("kb\n");
store.append("(b: ").append(bBufsM / 1024).append("kb f: ").append(fBufsM / 1024).append("kb i: ").append(iBufsM / 1024).append("kb s: ").append(sBufsM / 1024).append("kb d: ").append(dBufsM / 1024).append("kb)").append("\n");
} else {
store.append("Total heap memory held: ").append(heapMem / 1024).append("kb\n");
store.append("Only heap memory available, if you want to monitor direct memory use BufferUtils.setTrackDirectMemoryEnabled(true) during initialization.").append("\n");
}
if (printStout) {
System.out.println(store.toString());
}
}
private static final AtomicBoolean loadedMethods = new AtomicBoolean(false);
private static Method cleanerMethod = null;
private static Method cleanMethod = null;
private static Method viewedBufferMethod = null;
private static Method freeMethod = null;
private static Method loadMethod(String className, String methodName) {
try {
Method method = Class.forName(className).getMethod(methodName);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException ex) {
return null; // the method was not found
} catch (SecurityException ex) {
return null; // setAccessible not allowed by security policy
} catch (ClassNotFoundException ex) {
return null; // the direct buffer implementation was not found
}
}
private static void loadCleanerMethods() {
// If its already true, exit, if not, set it to true.
if (BufferUtils.loadedMethods.getAndSet(true)) {
return;
}
// This could potentially be called many times if used from multiple
// threads
synchronized (BufferUtils.loadedMethods) {
// Oracle JRE / OpenJDK
cleanerMethod = loadMethod("sun.nio.ch.DirectBuffer", "cleaner");
cleanMethod = loadMethod("sun.misc.Cleaner", "clean");
viewedBufferMethod = loadMethod("sun.nio.ch.DirectBuffer", "viewedBuffer");
if (viewedBufferMethod == null) {
// They changed the name in Java 7 (???)
viewedBufferMethod = loadMethod("sun.nio.ch.DirectBuffer", "attachment");
}
// Apache Harmony
ByteBuffer bb = BufferUtils.createByteBuffer(1);
Class<?> clazz = bb.getClass();
try {
freeMethod = clazz.getMethod("free");
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
}
}
}
/**
* Direct buffers are garbage collected by using a phantom reference and a
* reference queue. Every once a while, the JVM checks the reference queue and
* cleans the direct buffers. However, as this doesn't happen
* immediately after discarding all references to a direct buffer, it's
* easy to OutOfMemoryError yourself using direct buffers. This function
* explicitly calls the Cleaner method of a direct buffer.
*
* @param toBeDestroyed
* The direct buffer that will be "cleaned". Utilizes reflection.
*
*/
public static void destroyDirectBuffer(Buffer toBeDestroyed) {
if (!isDirect(toBeDestroyed)) {
return;
}
BufferUtils.loadCleanerMethods();
try {
if (freeMethod != null) {
freeMethod.invoke(toBeDestroyed);
} else {
Object cleaner = cleanerMethod.invoke(toBeDestroyed);
if (cleaner != null) {
cleanMethod.invoke(cleaner);
} else {
// Try the alternate approach of getting the viewed buffer first
Object viewedBuffer = viewedBufferMethod.invoke(toBeDestroyed);
if (viewedBuffer != null) {
destroyDirectBuffer((Buffer) viewedBuffer);
} else {
Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "Buffer cannot be destroyed: {0}", toBeDestroyed);
}
}
}
} catch (IllegalAccessException ex) {
Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex);
} catch (SecurityException ex) {
Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex);
}
}
/*
* FIXME when java 1.5 supprt is dropped - replace calls to this method with Buffer.isDirect
*
* Buffer.isDirect() is only java 6. Java 5 only have this method on Buffer subclasses :
* FloatBuffer, IntBuffer, ShortBuffer, ByteBuffer,DoubleBuffer, LongBuffer.
* CharBuffer has been excluded as we don't use it.
*
*/
private static boolean isDirect(Buffer buf) {
if (buf instanceof FloatBuffer) {
return ((FloatBuffer) buf).isDirect();
}
if (buf instanceof IntBuffer) {
return ((IntBuffer) buf).isDirect();
}
if (buf instanceof ShortBuffer) {
return ((ShortBuffer) buf).isDirect();
}
if (buf instanceof ByteBuffer) {
return ((ByteBuffer) buf).isDirect();
}
if (buf instanceof DoubleBuffer) {
return ((DoubleBuffer) buf).isDirect();
}
if (buf instanceof LongBuffer) {
return ((LongBuffer) buf).isDirect();
}
throw new UnsupportedOperationException(" BufferUtils.isDirect was called on " + buf.getClass().getName());
}
private static class BufferInfo extends PhantomReference<Buffer> {
private Class type;
private int size;
public BufferInfo(Class type, int size, Buffer referent, ReferenceQueue<? super Buffer> q) {
super(referent, q);
this.type = type;
this.size = size;
}
}
private static class ClearReferences extends Thread {
ClearReferences() {
this.setDaemon(true);
}
@Override
public void run() {
try {
while (true) {
Reference<? extends Buffer> toclean = BufferUtils.removeCollected.remove();
BufferUtils.trackedBuffers.remove(toclean);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package io.oasp.gastronomy.restaurant.offermanagement.batch.impl.productimport;
import io.oasp.gastronomy.restaurant.general.common.AbstractSpringBatchIntegrationTest;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.Offermanagement;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.to.DrinkEto;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.to.MealEto;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.to.OfferEto;
import io.oasp.gastronomy.restaurant.offermanagement.logic.api.to.ProductEto;
import io.oasp.module.configuration.common.api.ApplicationConfigurationConstants;
import java.util.List;
import javax.inject.Inject;
import org.junit.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.test.context.ContextConfiguration;
/**
* End-To-End test job "import offer management from csv"
*
* @author jczas
*/
@ContextConfiguration(locations = { ApplicationConfigurationConstants.BEANS_BATCH })
public class ProductImportJobTest extends AbstractSpringBatchIntegrationTest {
@Inject
private Job productImportJob;
@Inject
private Offermanagement offermanagement;
/**
* @throws Exception thrown by JobLauncherTestUtils
*/
@Test
public void testJob() throws Exception {
cleanDatabase();
// configure job
JobParametersBuilder jobParameterBuilder = new JobParametersBuilder();
jobParameterBuilder.addString("drinks.file", "classpath:ProductImportJobTest/data/drinks.csv");
jobParameterBuilder.addString("meals.file", "classpath:ProductImportJobTest/data/meals.csv");
JobParameters jobParameters = jobParameterBuilder.toJobParameters();
// run job
JobExecution jobExecution = getJobLauncherTestUtils(this.productImportJob).launchJob(jobParameters);
// check results
// - job status
assertThat(jobExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED);
// - imported data (there is 7 products in setup data)
List<ProductEto> allProducts = this.offermanagement.findAllProducts();
assertThat(allProducts).hasSize(7);
// - exemplary drink
DrinkEto drink = (DrinkEto) allProducts.get(0);
assertThat(drink.getName()).isEqualTo("Heineken");
assertThat(drink.getDescription()).isEqualTo("Pretty good beer");
assertThat(drink.getPictureId()).isEqualTo(1);
assertThat(drink.isAlcoholic()).isTrue();
// - exemplary meal
MealEto meal = (MealEto) allProducts.get(3);
assertThat(meal.getName()).isEqualTo("Bratwurst");
assertThat(meal.getDescription()).isEqualTo("Tasty sausage");
assertThat(meal.getPictureId()).isEqualTo(1);
}
private void cleanDatabase() {
for (OfferEto offer : this.offermanagement.findAllOffers()) {
this.offermanagement.deleteOffer(offer.getId());
}
for (ProductEto product : this.offermanagement.findAllProducts()) {
this.offermanagement.deleteProduct(product.getId());
}
}
}
|
package org.mapdb.issues;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.TT;
import java.io.*;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.*;
public class Issue41Test {
private static int NB_OPERATIONS = 1000;
private File DB_PATH = TT.tempDbFile();
private static String MAP_NAME = "mymap";
private DB db;
private HTreeMap<Key, Value> map;
private ExecutorService threadPool;
private CountDownLatch doneSignal;
@Before
public void setUp() {
if(TT.shortTest())
return;
db =
DBMaker.fileDB(DB_PATH)
.cacheSoftRefEnable()
.closeOnJvmShutdown()
.deleteFilesAfterClose()
.transactionDisable()
.make();
map =
db.hashMapCreate(MAP_NAME)
.keySerializer(new Key.Serializer())
.valueSerializer(new Value.Serializer())
.make();
threadPool = Executors.newFixedThreadPool(16);
doneSignal = new CountDownLatch(NB_OPERATIONS);
}
@Test
public void test1() throws InterruptedException {
if(TT.shortTest())
return;
final Value value = new Value();
final Key key = new Key(value, "http:
for (int i = 0; i < NB_OPERATIONS; i++) {
final int j = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
map.put(key, value);
} finally {
doneSignal.countDown();
// System.out.println("OP " + j);
}
}
});
}
}
@Test
public void test2() throws InterruptedException {
if(TT.shortTest())
return;
final ConcurrentMap<Key, Value> alreadyAdded =
new ConcurrentHashMap<Key, Value>();
for (int i = 0; i < NB_OPERATIONS; i++) {
final int j = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
if (j % 2 == 0) {
Value value = new Value();
Key key = new Key(value, Integer.toString(j));
alreadyAdded.putIfAbsent(key, value);
map.putIfAbsent(key, value);
} else {
Iterator<Key> it = alreadyAdded.keySet().iterator();
if (it.hasNext()) {
map.get(it.next());
}
}
} finally {
doneSignal.countDown();
// System.out.println("OP " + j);
}
}
});
}
}
@After
public void tearDown() throws InterruptedException {
if(TT.shortTest())
return;
doneSignal.await();
threadPool.shutdown();
db.close();
}
public static class Value implements Serializable {
private static final long serialVersionUID = 1L;
public static final Serializer SERIALIZER = new Serializer();
protected final UUID value;
public Value() {
this.value = UUID.randomUUID();
}
private Value(UUID uuid) {
this.value = uuid;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.value == null)
? 0 : this.value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Value)) {
return false;
}
Value other = (Value) obj;
if (this.value == null) {
if (other.value != null) {
return false;
}
} else if (!this.value.equals(other.value)) {
return false;
}
return true;
}
public static final class Serializer extends
org.mapdb.Serializer<Value> implements Serializable {
private static final long serialVersionUID = 140L;
@Override
public void serialize(DataOutput out, Value value)
throws IOException {
out.writeLong(value.value.getMostSignificantBits());
out.writeLong(value.value.getLeastSignificantBits());
}
@Override
public Value deserialize(DataInput in, int available)
throws IOException {
return new Value(new UUID(in.readLong(), in.readLong()));
}
@Override
public int fixedSize() {
return -1;
}
}
}
public static class Key implements Serializable {
private static final long serialVersionUID = 1L;
protected final Value subscriptionId;
protected final String eventId;
public Key(Value subscriptionId, String eventId) {
this.subscriptionId = subscriptionId;
this.eventId = eventId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.eventId == null)
? 0 : this.eventId.hashCode());
result = prime * result + ((this.subscriptionId == null)
? 0 : this.subscriptionId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Key)) {
return false;
}
Key other = (Key) obj;
if (this.eventId == null) {
if (other.eventId != null) {
return false;
}
} else if (!this.eventId.equals(other.eventId)) {
return false;
}
if (this.subscriptionId == null) {
if (other.subscriptionId != null) {
return false;
}
} else if (!this.subscriptionId.equals(other.subscriptionId)) {
return false;
}
return true;
}
public static final class Serializer extends
org.mapdb.Serializer<Key> implements Serializable {
private static final long serialVersionUID = 1L;
@Override
public void serialize(DataOutput out, Key notificationId)
throws IOException {
out.writeUTF(notificationId.eventId);
Value.SERIALIZER.serialize(out, notificationId.subscriptionId);
}
@Override
public Key deserialize(DataInput in, int available)
throws IOException {
String eventId = in.readUTF();
Value subscriptionId =
Value.SERIALIZER.deserialize(in, available);
return new Key(subscriptionId, eventId);
}
}
}
}
|
package be.ibridge.kettle.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import org.eclipse.core.runtime.IProgressMonitor;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Counter;
import be.ibridge.kettle.core.DBCache;
import be.ibridge.kettle.core.DBCacheEntry;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleDatabaseBatchException;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_pun;
private PreparedStatement pstmt_dup;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private Row rowinfo;
private int written;
private LogWriter log;
/**
* Counts the number of rows written to a batch.
*/
private int batchCounter;
/**
* Construnct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
pstmt = null;
rsmd = null;
rowinfo = null;
dbmd = null;
rowlimit=0;
written=0;
log.logDetailed(toString(), "New database connection defined");
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @return true if the connect was succesfull, false if something went wrong.
*/
public void connect()
throws KettleDatabaseException
{
try
{
if (databaseMeta!=null)
{
connect(databaseMeta.getDriverClass());
log.logDetailed(toString(), "Connected to database.");
}
else
{
throw new KettleDatabaseException("No valid database connection defined!");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connect(String classname)
throws KettleDatabaseException
{
// Install and load the jdbc Driver
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
connection = DriverManager.getConnection(databaseMeta.getURL(), databaseMeta.getUsername(), databaseMeta.getPassword());
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
* @return true if the connection and the open prepared statements were closed succesfully, false if something went wrong.
*/
public void disconnect()
{
try
{
if (connection==null) return ; // Nothing to do...
if (connection.isClosed()) return ; // Nothing to do...
if (!isAutoCommit()) commit();
if (pstmt !=null) { pstmt.close(); pstmt=null; }
if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; }
if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; }
if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; }
if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; }
if (connection !=null) { connection.close(); connection=null; }
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
}
}
public void cancelQuery() throws KettleDatabaseException
{
try
{
if (pstmt !=null)
{
pstmt.cancel();
}
if (sel_stmt !=null)
{
sel_stmt.cancel();
}
log.logDetailed(toString(), "Open query canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling query", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit()
throws KettleDatabaseException
{
try
{
if (getDatabaseMetaData().supportsTransactions())
{
connection.commit();
}
else
{
System.out.println("No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions()) // TODO: find a way to examine the exact error thrown, in case it's -255: ignore, everything else: report
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback()
throws KettleDatabaseException
{
try
{
connection.rollback();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param r The row to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @return true if all went well, false if something went wrong.
*/
public void prepareInsert(Row r, String table)
throws KettleDatabaseException
{
if (r.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(table, r);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
try
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(Row r)
throws KettleDatabaseException
{
setValues(r, pstmt);
}
public void setValuesInsert(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementInsert);
}
public void setValuesUpdate(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementUpdate);
}
public void setValuesLookup(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementLookup);
}
public void setProcValues(Row r, int argnrs[], String argdir[], boolean result)
throws KettleDatabaseException
{
int i;
int pos;
if (result) pos=2; else pos=1;
for (i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN"))
{
Value v=r.getValue(argnrs[i]);
setValue(cstmt, v, pos);
pos++;
}
}
}
public void setValue(PreparedStatement ps, Value v, int pos)
throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case Value.VALUE_TYPE_BIGNUMBER:
debug="BigNumber";
if (!v.isNull())
{
ps.setBigDecimal(pos, v.getBigNumber());
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case Value.VALUE_TYPE_NUMBER :
debug="Number";
if (!v.isNull())
{
double num = v.getNumber();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
num = Const.round(num, v.getPrecision());
}
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case Value.VALUE_TYPE_INTEGER:
debug="Integer";
if (!v.isNull())
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, Math.round( v.getNumber() ) );
}
else
{
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, v.getNumber() );
}
else
{
ps.setDouble(pos, Const.round( v.getNumber(), v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.BIGINT);
}
break;
case Value.VALUE_TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (!v.isNull() && v.getString()!=null)
{
ps.setString(pos, v.getString());
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (!v.isNull())
{
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = v.getStringLength();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = v.getString().substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case Value.VALUE_TYPE_DATE :
debug="Date";
if (!v.isNull() && v.getDate()!=null)
{
long dat = v.getDate().getTime();
switch(v.getPrecision())
{
// Convert to DATE!
case 1: java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
break;
default: java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
break;
}
}
else
{
ps.setNull(pos, java.sql.Types.TIME);
}
break;
case Value.VALUE_TYPE_BOOLEAN:
debug="Boolean";
if (!v.isNull())
{
ps.setString(pos, v.getBoolean()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
break;
default:
debug="default";
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
// Sets the values of the preparedStatement pstmt.
public void setValues(Row r, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
//System.out.println("Setting value ["+v+"] on preparedStatement, position="+i);
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+r, e);
}
}
}
public void setDimValues(Row r, Value dateval)
throws KettleDatabaseException
{
setDimValues(r, dateval, prepStatementLookup);
}
// Sets the values of the preparedStatement pstmt.
public void setDimValues(Row r, Value dateval, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
long dat;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("Unable to set value #"+i+" on dimension using row :"+r, e);
}
}
if (dateval!=null && dateval.getDate()!=null && !dateval.isNull())
{
dat = dateval.getDate().getTime();
}
else
{
Calendar cal=Calendar.getInstance(); // use system date!
dat = cal.getTime().getTime();
}
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
try
{
ps.setTimestamp(r.size()+1, sdate); // ? > date_from
ps.setTimestamp(r.size()+2, sdate); // ? <= date_to
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to set timestamp on fromdate or todate", ex);
}
}
public void dimUpdate(Row row,
String table,
String fieldlookup[],
int fieldnrs[],
String returnkey,
Value dimkey
)
throws KettleDatabaseException
{
int i;
if (pstmt_dup==null) // first time: construct prepared statement
{
// Construct the SQL statement...
/*
* UPDATE d_customer
* SET fieldlookup[] = row.getValue(fieldnrs)
* WHERE returnkey = dimkey
* ;
*/
String sql="UPDATE "+table+Const.CR+"SET ";
for (i=0;i<fieldlookup.length;i++)
{
if (i>0) sql+=", "; else sql+=" ";
sql+=fieldlookup[i]+" = ?"+Const.CR;
}
sql+="WHERE "+returnkey+" = ?";
try
{
log.logDebug(toString(), "Preparing statement: ["+sql+"]");
pstmt_dup=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Coudln't prepare statement :"+Const.CR+sql, ex);
}
}
// Assemble information
// New
Row rupd=new Row();
for (i=0;i<fieldnrs.length;i++)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
rupd.addValue( dimkey );
setValues(rupd, pstmt_dup);
insertRow(pstmt_dup);
}
// This inserts new record into dimension
// Optionally, if the entry already exists, update date range from previous version
// of the entry.
public void dimInsert(Row row,
String table,
boolean newentry,
String keyfield,
boolean autoinc,
Value technicalKey,
String versionfield,
Value val_version,
String datefrom,
Value val_datfrom,
String dateto,
Value val_datto,
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
if (prepStatementInsert==null && prepStatementUpdate==null) // first time: construct prepared statement
{
/* Construct the SQL statement...
*
* INSERT INTO
* d_customer(keyfield, versionfield, datefrom, dateto, key[], fieldlookup[])
* VALUES (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[])
* ;
*/
String sql="INSERT INTO "+table+"( ";
if (!autoinc) sql+=keyfield+", "; // NO AUTOINCREMENT
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_INFORMIX) sql+="0, "; // placeholder on informix!
sql+=versionfield+", "+datefrom+", "+dateto;
for (i=0;i<keylookup.length;i++)
{
sql+=", "+keylookup[i];
}
for (i=0;i<fieldlookup.length;i++)
{
sql+=", "+fieldlookup[i];
}
sql+=") VALUES(";
if (!autoinc) sql+="?, ";
sql+="?, ?, ?";
for (i=0;i<keynrs.length;i++)
{
sql+=", ?";
}
for (i=0;i<fieldnrs.length;i++)
{
sql+=", ?";
}
sql+=" )";
try
{
if (keyfield==null)
{
log.logDetailed(toString(), "SQL w/ return keys=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql));
}
//pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } );
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension insert :"+Const.CR+sql, ex);
}
/*
* UPDATE d_customer
* SET dateto = val_datnow
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
String sql_upd="UPDATE "+table+Const.CR+"SET "+dateto+" = ?"+Const.CR;
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=keylookup[i]+" = ?"+Const.CR;
}
sql_upd+="AND "+versionfield+" = ? ";
try
{
log.logDetailed(toString(), "Preparing update: "+Const.CR+sql+Const.CR);
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension update :"+Const.CR+sql, ex);
}
}
Row rins=new Row();
if (!autoinc) rins.addValue(technicalKey);
if (!newentry)
{
Value val_new_version = new Value(val_version);
val_new_version.setValue( val_new_version.getNumber()+1 ); // determine next version
rins.addValue(val_new_version);
}
else
{
rins.addValue(val_version);
}
rins.addValue(val_datfrom);
rins.addValue(val_datto);
for (i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
for (i=0;i<fieldnrs.length;i++)
{
Value val = row.getValue(fieldnrs[i]);
rins.addValue( val );
}
log.logDebug(toString(), "rins, size="+rins.size()+", values="+rins.toString());
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
insertRow(prepStatementInsert);
log.logDebug(toString(), "Row inserted!");
if (keyfield==null)
{
try
{
ResultSet keys=prepStatementInsert.getGeneratedKeys(); // 1 key
if (keys.next()) technicalKey.setValue(keys.getLong(1));
else
{
throw new KettleDatabaseException("Unable to retrieve technical key value from auto-increment field : "+keyfield+", no fields in resultset.");
}
keys.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve technical key value from auto-increment field : "+keyfield, ex);
}
}
if (!newentry) // we have to update the previous version in the dimension!
{
/*
* UPDATE d_customer
* SET dateto = val_datfrom
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
Row rupd = new Row();
rupd.addValue(val_datfrom);
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
rupd.addValue(val_version);
log.logRowlevel(toString(), "UPDATE using rupd="+rupd.toString());
// UPDATE VALUES
setValues(rupd, prepStatementUpdate); // set values for update
log.logDebug(toString(), "Values set for update ("+rupd.size()+")");
insertRow(prepStatementUpdate); // do the actual update
log.logDebug(toString(), "Row updated!");
}
}
// This updates all versions of a dimension entry.
public void dimPunchThrough(Row row,
String table,
int fieldupdate[],
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
boolean first;
if (pstmt_pun==null) // first time: construct prepared statement
{
/*
* UPDATE table
* SET punchv1 = fieldx, ...
* WHERE keylookup[] = keynrs[]
* ;
*/
String sql_upd="UPDATE "+table+Const.CR;
sql_upd+="SET ";
first=true;
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
if (!first) sql_upd+=", "; else sql_upd+=" ";
first=false;
sql_upd+=fieldlookup[i]+" = ?"+Const.CR;
}
}
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=keylookup[i]+" = ?"+Const.CR;
}
try
{
pstmt_pun=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex);
}
}
Row rupd=new Row();
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
}
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
// UPDATE VALUES
setValues(rupd, pstmt_pun); // set values for update
insertRow(pstmt_pun); // do the actual update
}
// This inserts new record into dimension
// Optionally, if the entry already exists, update date range from previous version
// of the entry.
public void combiInsert(Row row,
String table,
String keyfield,
boolean autoinc,
Value val_key,
String keylookup[],
int keynrs[],
boolean crc,
String crcfield,
Value val_crc
)
throws KettleDatabaseException
{
int i;
boolean comma;
if (prepStatementInsert==null) // first time: construct prepared statement
{
/* Construct the SQL statement...
*
* INSERT INTO
* d_test(keyfield, [crcfield,] keylookup[])
* VALUES(val_key, [val_crc], row values with keynrs[])
* ;
*/
String sql="INSERT INTO "+table+"( ";
comma=false;
if (!autoinc) // NO AUTOINCREMENT
{
sql+=keyfield;
comma=true;
}
else
if (databaseMeta.needsPlaceHolder())
{
sql+="0"; // placeholder on informix! Will be replaced in table by real autoinc value.
comma=true;
}
if (crc)
{
if (comma) sql+=", ";
sql+=crcfield;
comma=true;
}
for (i=0;i<keylookup.length;i++)
{
if (comma) sql+=", ";
sql+=keylookup[i];
comma=true;
}
sql+=") VALUES (";
comma=false;
if (keyfield!=null)
{
sql+="?";
comma=true;
}
if (crc)
{
if (comma) sql+=",";
sql+="?";
comma=true;
}
for (i=0;i<keylookup.length;i++)
{
if (comma) sql+=","; else comma=true;
sql+="?";
}
sql+=" )";
try
{
if (keyfield==null)
{
log.logDetailed(toString(), "SQL with return keys: "+sql);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL without return keys: "+sql);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sql, ex);
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sql, ex);
}
}
Row rins=new Row();
if (!autoinc) rins.addValue(val_key);
if (crc)
{
rins.addValue(val_crc);
}
for (i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
//log.logRowlevel("rins="+rins.toString());
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
insertRow(prepStatementInsert);
if (keyfield==null)
{
try
{
ResultSet keys=pstmt.getGeneratedKeys(); // 1 key
if (keys.next()) val_key.setValue(keys.getDouble(1));
else
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield+", no fields in resultset");
}
keys.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex);
}
}
}
public Value getNextSequenceValue(String seq, String keyfield)
throws KettleDatabaseException
{
Value retval=null;
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(seq)));
}
ResultSet rs=pstmt_seq.executeQuery();
if (rs.next())
{
long next = rs.getLong(1);
retval=new Value(keyfield, next);
retval.setLength(9,0);
}
rs.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+seq, ex);
}
return retval;
}
public void insertRow(String tableName, Row fields)
throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, Row fields)
{
String ins="";
ins+="INSERT INTO "+tableName+"(";
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins+=", ";
String name = fields.getValue(i).getName();
ins+=databaseMeta.quoteField(name);
}
ins+=") VALUES (";
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins+=", ";
ins+=" ?";
}
ins+=")";
return ins;
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* @param batchCounter The batchCounter to set.
*/
public void setBatchCounter(int batchCounter)
{
this.batchCounter = batchCounter;
}
/**
* @return Returns the batchCounter.
*/
public int getBatchCounter()
{
return batchCounter;
}
private long testCounter = 0;
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commitsize)
* @throws KettleDatabaseException
*/
public void insertRow(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
String debug="insertRow start";
try
{
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates();
// Add support for batch inserts...
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
batchCounter++;
ps.addBatch(); // Add the batch, but don't forget to run the batch
testCounter++;
// System.out.println("testCounter is at "+testCounter);
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
// System.out.println("EXECUTE BATCH, testcounter is at "+testCounter);
batchCounter=0;
}
else
{
debug="insertRow normal commit";
commit();
}
}
}
catch(BatchUpdateException ex)
{
//System.out.println("Batch update exception "+ex.getMessage());
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
throw kdbe;
}
catch(SQLException ex)
{
// System.out.println("SQLException: "+ex.getMessage());
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
public void insertFinished(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
//System.out.println("Executing batch with "+batchCounter+" elements...");
ps.executeBatch();
commit();
}
else
{
commit();
}
}
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql)
throws KettleDatabaseException
{
return execStatement(sql, null);
}
public Result execStatement(String sql, Row params)
throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
Statement stmt = connection.createStatement();
resultSet = stmt.execute(databaseMeta.stripCR(sql));
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// System.out.println("What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput((long) count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated((long) count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted((long) count);
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script)
throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat = all.substring(from, to);
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Row r = getRow(rs);
while (r!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
log.logDetailed(toString(), r.toString());
r=getRow(rs);
}
}
else
{
log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql)
throws KettleDatabaseException
{
return openQuery(sql, null);
}
public ResultSet openQuery(String sql, Row params)
throws KettleDatabaseException
{
return openQuery(sql, params, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, Row params, int fetch_mode)
throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params); // set the dates etc!
if (databaseMeta.isFetchSizeSupported() && pstmt.getMaxRows()>0)
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
pstmt.setFetchSize(fs);
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>0)
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
sel_stmt.setFetchSize(fs);
debug = "Set fetch direction";
sel_stmt.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "Set max rows";
if (rowlimit>0) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "get metadata";
rsmd = res.getMetaData();
rowinfo = getRowInfo();
}
catch(SQLException ex)
{
log.logError(toString(), "ERROR executing ["+sql+"]");
log.logError(toString(), "ERROR in part: ["+debug+"]");
printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
public ResultSet openQuery(PreparedStatement ps, Row params)
throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, ps); // set the parameters!
if (databaseMeta.isFetchSizeSupported() && ps.getMaxRows()>0)
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
ps.setFetchSize(fs);
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ get metadata";
rsmd = res.getMetaData();
debug = "OQ getRowInfo()";
rowinfo = getRowInfo();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public Row getTableFields(String tablename)
throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public Row getQueryFields(String sql, boolean param)
throws KettleDatabaseException
{
return getQueryFields(sql, param, null);
}
/**
* See if the table specified exists by looking at the data dictionary!
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename)
throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String name = alltables.getString("TABLE_NAME");
if (tablename.equalsIgnoreCase(name))
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName)
throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
try
{
// Get the info from the data dictionary...
String sql = databaseMeta.getSQLSequenceExists(sequenceName);
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+sequenceName+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tablename, String idx_fields[])
throws KettleDatabaseException
{
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
// Get the info from the data dictionary...
String sql = "select i.name table_name, c.name column_name ";
sql += "from sysindexes i, sysindexkeys k, syscolumns c ";
sql += "where i.name = '"+tablename+"' ";
sql += "AND i.id = k.id ";
sql += "AND i.id = c.id ";
sql += "AND k.colid = c.colid ";
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
closeQuery(res);
}
else
{
return false;
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
// Get the info from the data dictionary...
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tablename.toUpperCase()+"'";
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
closeQuery(res);
}
else
{
return false;
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
indexList.close(); }
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
indexList.close();
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
e.printStackTrace();
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+indexname+Const.CR+" ";
cr_index += "ON "+tablename+Const.CR;
cr_index += "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += idx_fields[i]+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.getIndexTablespace();
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
String cr_seq="";
if (sequence==null || sequence.length()==0) return cr_seq;
if (databaseMeta.supportsSequences())
{
cr_seq += "CREATE SEQUENCE "+sequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value>0) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public Row getQueryFields(String sql, boolean param, Row inform)
throws KettleDatabaseException
{
Row fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
String debug="";
try
{
if (inform==null)
{
debug="inform==null";
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug="isFetchSizeSupported()";
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
debug = "Set fetchsize";
sel_stmt.setFetchSize(1); // Only one row needed!
}
debug = "Set max rows to 1";
sel_stmt.setMaxRows(1);
debug = "exec query";
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
debug = "get metadata";
rsmd = r.getMetaData();
fields = getRowInfo();
debug="close resultset";
r.close();
debug="close statement";
sel_stmt.close();
sel_stmt=null;
}
else
{
debug="prepareStatement";
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
Row par = inform;
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(ps);
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(sql, inform);
setValues(par, ps);
}
debug="executeQuery()";
ResultSet r = ps.executeQuery();
debug="getMetaData";
rsmd = ps.getMetaData();
debug="getRowInfo";
fields=getRowInfo(rsmd);
debug="close resultset";
r.close();
debug="close preparedStatement";
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR+"Location: "+debug, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Couldn't get field info in part ["+debug+"]", e);
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
public void closeQuery(ResultSet res)
throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
// Build the row using ResultSetMetaData rsmd
private Row getRowInfo(ResultSetMetaData rm)
throws KettleDatabaseException
{
int nrcols;
int i;
Value v;
String name;
int type, valtype;
int precision;
int length;
if (rm==null) return null;
rowinfo = new Row();
try
{
nrcols=rm.getColumnCount();
for (i=1;i<=nrcols;i++)
{
name=new String(rm.getColumnName(i));
type=rm.getColumnType(i);
valtype=Value.VALUE_TYPE_NONE;
length=rm.getPrecision(i);
precision=rm.getScale(i);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=Value.VALUE_TYPE_STRING;
length=rm.getColumnDisplaySize(i);
// System.out.println("Display of "+name+" = "+precision);
// System.out.println("Precision of "+name+" = "+rm.getPrecision(i));
// System.out.println("Scale of "+name+" = "+rm.getScale(i));
break;
case java.sql.Types.CLOB:
valtype=Value.VALUE_TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
break;
case java.sql.Types.BIGINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=Value.VALUE_TYPE_NUMBER;
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (precision==0 && length<18 && length>0) valtype=Value.VALUE_TYPE_INTEGER;
if (length>18 || precision>18) valtype=Value.VALUE_TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision<=0 && length<=0) // undefined size: BIGNUMBER
{
valtype=Value.VALUE_TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=Value.VALUE_TYPE_DATE;
break;
case java.sql.Types.BOOLEAN:
valtype=Value.VALUE_TYPE_BOOLEAN;
break;
default:
valtype=Value.VALUE_TYPE_STRING;
break;
}
// comment=rm.getColumnLabel(i);
// TODO: change this hack!
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ACCESS)
{
if (valtype==Value.VALUE_TYPE_INTEGER)
{
valtype=Value.VALUE_TYPE_NUMBER;
length = -1;
precision = -1;
}
}
v=new Value(name, valtype);
v.setLength(length, precision);
rowinfo.addValue(v);
}
return rowinfo;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
// Build the row using ResultSetMetaData rsmd
private Row getRowInfo()
throws KettleDatabaseException
{
return getRowInfo(rsmd);
}
public boolean absolute(ResultSet rs, int position)
throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows)
throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Row getRow(ResultSet rs)
throws KettleDatabaseException
{
Row row;
int nrcols, i;
Value val;
try
{
nrcols=rsmd.getColumnCount();
if (rs.next())
{
row=new Row();
for (i=0;i<nrcols;i++)
{
val=new Value(rowinfo.getValue(i)); // copy info from meta-data.
switch(val.getType())
{
case Value.VALUE_TYPE_BOOLEAN : val.setValue( rs.getBoolean(i+1) ); break;
case Value.VALUE_TYPE_NUMBER : val.setValue( rs.getDouble(i+1) ); break;
case Value.VALUE_TYPE_BIGNUMBER : val.setValue( rs.getBigDecimal(i+1) ); break;
case Value.VALUE_TYPE_INTEGER : val.setValue( rs.getLong(i+1) ); break;
case Value.VALUE_TYPE_STRING : val.setValue( rs.getString(i+1) ); break;
case Value.VALUE_TYPE_DATE : val.setValue( rs.getTimestamp(i+1) ); break;
default: break;
}
if (rs.wasNull()) val.setNull(); // null value!
row.addValue(val);
}
}
else
{
row=null;
}
return row;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
// Lookup certain fields in a table
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby)
throws KettleDatabaseException
{
String sql;
int i;
sql = "SELECT ";
for (i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += gets[i];
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+rename[i];
}
}
sql += " FROM "+table+" WHERE ";
for (i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
// Lookup certain fields in a table
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
String sql;
int i;
sql = "UPDATE "+table+Const.CR+"SET ";
for (i=0;i<sets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(sets[i]);
sql+=" = ?"+Const.CR;
}
sql += "WHERE ";
for (i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
int i;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (returnvalue!=null)
{
switch(returntype)
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
/*
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
* datefield: do we have a datefield?
* datefrom, dateto: date-range, if any.
*/
public boolean setDimLookup(String table,
String keys[],
String tk,
String version,
String extra[],
String datefrom,
String dateto
)
throws KettleDatabaseException
{
String sql;
int i;
/*
* SELECT <tk>, <version>, ...
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND <datefield> BETWEEN <datefrom> AND <dateto>
* ;
*
*/
sql = "SELECT "+tk+", "+version;
if (extra!=null)
{
for (i=0;i<extra.length;i++)
{
if (extra[i]!=null && extra[i].length()!=0)
sql+=", "+extra[i];
}
}
sql+= " FROM "+table+" WHERE ";
for (i=0;i<keys.length;i++)
{
if (i!=0) sql += " AND ";
sql += keys[i]+" = ? ";
}
sql += " AND ? >= "+datefrom+" AND ? < "+dateto;
try
{
log.logDetailed(toString(), "Dimension Lookup setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
log.logDetailed(toString(), "Finished preparing dimension lookup statement.");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension lookup", ex);
}
return true;
}
/* CombinationLookup
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
*/
public void setCombiLookup(String table,
String keys[],
String retval,
boolean crc,
String crcfield
)
throws KettleDatabaseException
{
String sql;
int i;
boolean comma;
/*
* SELECT <retval>
* FROM <table>
* WHERE ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
* OR
*
* SELECT <retval>
* FROM <table>
* WHERE <crcfield> = ?
* AND ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
*/
sql = "SELECT "+retval+Const.CR+"FROM "+table+Const.CR+"WHERE ";
comma=false;
if (crc)
{
sql+=crcfield+" = ? "+Const.CR;
comma=true;
}
else
{
sql+="( ( ";
}
for (i=0;i<keys.length;i++)
{
if (comma)
{
sql += " AND ( ( ";
}
else
{
comma=true;
}
sql += keys[i]+" = ? ) OR ( "+keys[i]+" IS NULL AND ? IS NULL ) )"+Const.CR;
}
try
{
log.logDebug(toString(), "preparing combi-lookup statement:"+Const.CR+sql);
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi-lookup statement", ex);
}
}
public Row callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype)
throws KettleDatabaseException
{
Row ret;
try
{
cstmt.execute();
ret=new Row();
int pos=1;
if (resultname!=null && resultname.length()!=0)
{
Value v=new Value(resultname, Value.VALUE_TYPE_NONE);
switch(resulttype)
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos) ); break;
}
ret.addValue(v);
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
Value v=new Value(arg[i], Value.VALUE_TYPE_NONE);
switch(argtype[i])
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos+i) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos+i) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos+i)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos+i) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos+i) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos+i) ); break;
}
ret.addValue(v);
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
public Row getLookup()
throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Row getLookup(PreparedStatement ps)
throws KettleDatabaseException
{
String debug = "start";
Row ret;
try
{
debug = "pstmt.executeQuery()";
ResultSet res = ps.executeQuery();
debug = "res.getMetaData";
rsmd = res.getMetaData();
debug = "getRowInfo()";
rowinfo = getRowInfo();
debug = "getRow(res)";
ret=getRow(res);
debug = "res.close()";
res.close(); // close resultset!
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
}
public DatabaseMetaData getDatabaseMetaData()
throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, Row fields)
throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk)
throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.replaceReservedWords(fields);
if (checkTableExists(tablename))
{
retval=getAlterTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
return retval;
}
public String getCreateTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tablename+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
Value v=fields.getValue(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
Row tabFields = getTableFields(tablename);
// Find the missing fields
Row missing = new Row();
for (int i=0;i<fields.size();i++)
{
Value v = fields.getValue(i);
// Not found?
if (tabFields.searchValue( v.getName() )==null )
{
missing.addValue(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
Value v=missing.getValue(i);
retval+=databaseMeta.getAddColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
Row surplus = new Row();
for (int i=0;i<tabFields.size();i++)
{
Value v = tabFields.getValue(i);
// Found in table, not in input ?
if (fields.searchValue( v.getName() )==null )
{
surplus.addValue(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
Value v=surplus.getValue(i);
retval+=databaseMeta.getDropColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
// OK, see if there are fields for wich we need to modify the type... (length, precision)
Row modify = new Row();
for (int i=0;i<fields.size();i++)
{
Value desiredField = fields.getValue(i);
Value currentField = tabFields.searchValue( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
if (mod)
{
System.out.println("Desired field: ["+desiredField+"], current field: ["+currentField+"]");
modify.addValue(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
Value v=modify.getValue(i);
retval+=databaseMeta.getModifyColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void checkDimZero(String tablename, String tk, String version, boolean use_autoinc)
throws KettleDatabaseException
{
int start_tk = databaseMeta.getNotFoundTK(use_autoinc);
String sql = "SELECT count(*) FROM "+tablename+" WHERE "+tk+" = "+start_tk;
ResultSet rs = openQuery(sql, null);
Row r = getRow(rs); // One value: a number;
Value count = r.getValue(0);
if (count.getNumber() == 0)
{
try
{
Statement st = connection.createStatement();
String isql;
if (!databaseMeta.supportsAutoinc() || !use_autoinc)
{
isql = isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)";
}
else
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_CACHE :
case DatabaseMeta.TYPE_DATABASE_GUPTA :
case DatabaseMeta.TYPE_DATABASE_ORACLE : isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_INFORMIX :
case DatabaseMeta.TYPE_DATABASE_MYSQL : isql = "insert into "+tablename+"("+tk+", "+version+") values (1, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_MSSQL :
case DatabaseMeta.TYPE_DATABASE_DB2 :
case DatabaseMeta.TYPE_DATABASE_DBASE :
case DatabaseMeta.TYPE_DATABASE_GENERIC :
case DatabaseMeta.TYPE_DATABASE_SYBASE :
case DatabaseMeta.TYPE_DATABASE_ACCESS : isql = "insert into "+tablename+"("+version+") values (1)"; break;
default: isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)"; break;
}
}
st.executeUpdate(databaseMeta.stripCR(isql));
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+tablename+"] : "+sql, e);
}
}
}
public Value checkSequence(String seqname)
throws KettleDatabaseException
{
String sql=null;
if (databaseMeta.supportsSequences())
{
sql = databaseMeta.getSQLCurrentSequenceValue(seqname);
ResultSet rs = openQuery(sql, null);
Row r = getRow(rs); // One value: a number;
if (r!=null)
{
Value last = r.getValue(0);
// errorstr="Sequence is at number: "+last.toString();
return last;
}
else
{
return null;
}
}
else
{
throw new KettleDatabaseException("Sequences are only available for Oracle databases.");
}
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
execStatement(databaseMeta.getTruncateTableStatement(tablename));
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public Row getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, null);
if (rs!=null)
{
Row r = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return r;
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public Row getOneRow(String sql, Row param)
throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param);
if (rs!=null)
{
Row r = getRow(rs); // One value: a number;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return r;
}
else
{
return null;
}
}
public Row getParameterMetaData(PreparedStatement ps)
{
Row par = new Row();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
Value val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new Value(name, Value.VALUE_TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new Value(name, Value.VALUE_TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new Value(name, Value.VALUE_TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new Value(name, Value.VALUE_TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
val=new Value(name, Value.VALUE_TYPE_BOOLEAN);
break;
default:
val=new Value(name, Value.VALUE_TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new Value(name, Value.VALUE_TYPE_BIGNUMBER);
}
val.setNull();
par.addValue(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public Row getParameterMetaData(String sql, Row inform)
{
// The database coudln't handle it: try manually!
int q=countParameters(sql);
Row par=new Row();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
Value inf=inform.getValue(i);
Value v = new Value(inf);
par.addValue(v);
}
}
else
{
for (int i=0;i<q;i++)
{
Value v = new Value("name"+i, Value.VALUE_TYPE_NUMBER);
v.setValue( 0.0 );
par.addValue(v);
}
}
return par;
}
public static final Row getTransLogrecordFields(boolean use_batchid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_batchid)
{
v=new Value("ID_BATCH", Value.VALUE_TYPE_INTEGER); v.setLength(8,0); r.addValue(v);
}
v=new Value("TRANSNAME", Value.VALUE_TYPE_STRING ); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING ); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public static final Row getJobLogrecordFields(boolean use_jobid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_jobid)
{
v=new Value("ID_JOB", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
}
v=new Value("JOBNAME", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public void writeLogRecord( String logtable,
boolean use_id,
long id,
boolean job,
String name,
String status,
long read, long written, long updated,
long input, long output, long errors,
java.util.Date startdate, java.util.Date enddate,
java.util.Date logdate, java.util.Date depdate,
String log_string
)
throws KettleDatabaseException
{
int parms;
String sql = "INSERT INTO "+logtable+" ( ";
if (job)
{
if (use_id)
{
sql+="ID_JOB, JOBNAME";
parms=13;
}
else
{
sql+="JOBNAME";
parms=12;
}
}
else
{
if (use_id)
{
sql+="ID_BATCH, TRANSNAME";
parms=13;
}
else
{
sql+="TRANSNAME";
parms=12;
}
}
sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE";
if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB!
sql+=") VALUES(";
for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?";
if (log_string!=null && log_string.length()>0) sql+=", ?";
sql+=")";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
if (job)
{
if (use_id)
{
r.addValue( new Value("ID_BATCH", id ));
}
r.addValue( new Value("TRANSNAME", name ));
}
else
{
if (use_id)
{
r.addValue( new Value("ID_JOB", id ));
}
r.addValue( new Value("JOBNAME", name ));
}
r.addValue( new Value("STATUS", status ));
r.addValue( new Value("LINES_READ", (long)read ));
r.addValue( new Value("LINES_WRITTEN", (long)written));
r.addValue( new Value("LINES_UPDATED", (long)updated));
r.addValue( new Value("LINES_INPUT", (long)input ));
r.addValue( new Value("LINES_OUTPUT", (long)output ));
r.addValue( new Value("ERRORS", (long)errors ));
r.addValue( new Value("STARTDATE", startdate ));
r.addValue( new Value("ENDDATE", enddate ));
r.addValue( new Value("LOGDATE", logdate ));
r.addValue( new Value("DEPDATE", depdate ));
if (log_string!=null && log_string.length()>0)
{
Value large = new Value("LOG_FIELD", log_string );
large.setLength(DatabaseMeta.CLOB_LENGTH);
r.addValue( large );
}
setValues(r);
pstmt.executeUpdate();
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex);
}
}
public Row getLastLogDate( String logtable,
String name,
boolean job,
String status
)
throws KettleDatabaseException
{
Row row=null;
String jobtrans = job?"JOBNAME":"TRANSNAME";
String sql = "";
sql+=" SELECT ENDDATE, DEPDATE, STARTDATE";
sql+=" FROM "+logtable;
sql+=" WHERE ERRORS = 0";
sql+=" AND STATUS = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
r.addValue( new Value("TRANSNAME", name ));
setValues(r);
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rsmd = res.getMetaData();
rowinfo = getRowInfo();
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized void getNextValue(TransMeta transMeta, String table, Value val_key)
throws KettleDatabaseException
{
String lookup = table+"."+val_key.getName();
// Try to find the previous sequence value...
Counter counter = (Counter)transMeta.getCounters().get(lookup);
if (counter==null)
{
Row r = getOneRow("SELECT MAX("+val_key.getName()+") FROM "+table);
if (r!=null)
{
counter = new Counter(r.getValue(0).getInteger()+1, 1);
val_key.setValue(counter.next());
transMeta.getCounters().put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+table);
}
}
else
{
val_key.setValue(counter.next());
}
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
int i=0;
boolean stop=false;
ArrayList result = new ArrayList();
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Row row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
public ArrayList getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
public ArrayList getFirstRows(String table_name, int limit, IProgressMonitor monitor)
throws KettleDatabaseException
{
String sql = "SELECT * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public Row getReturnRow()
{
return rowinfo;
}
public String[] getTableTypes()
throws KettleDatabaseException
{
try
{
ArrayList types = new ArrayList();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return (String[])types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames()
throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got table from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getViews()
throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getSynonyms()
throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
ArrayList procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Row)procs.get(i)).getValue(0).getString();
}
return str;
}
return null;
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLLockTables(tableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLUnlockTables(tableNames);
if (sql!=null)
{
execStatement(sql);
}
}
}
|
package org.republica.db;
import android.content.Context;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.republica.api.RepublicaUrls;
import org.republica.model.FossasiaEvent;
import org.republica.model.Speaker;
import org.republica.utils.StringUtils;
import org.republica.utils.VolleySingleton;
import java.text.ParseException;
import java.util.ArrayList;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class JsonToDatabase {
private final static String TAG = "JSON_TO_DATABASE";
private Context context;
private boolean tracks;
private ArrayList<String> queries;
private JsonToDatabaseCallback mCallback;
private int count;
public JsonToDatabase(Context context) {
count = 0;
this.context = context;
queries = new ArrayList<String>();
tracks = false;
}
public void setOnJsonToDatabaseCallback(JsonToDatabaseCallback callback) {
this.mCallback = callback;
}
public void startDataDownload() {
parse(RepublicaUrls.DATA_URL);
}
public void parse(final String url) {
RequestQueue queue = VolleySingleton.getReqQueue(context);
//Request string reponse from the url
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonData = new JSONObject(response);
parseSession(jsonData);
parseSpeakers(jsonData);
parseTracks(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
DatabaseManager dbManager = DatabaseManager.getInstance();
//Temporary clearing database for testing only
dbManager.clearDatabase();
dbManager.performInsertQueries(queries);
if(mCallback != null) {
mCallback.onDataLoaded();
}
}
}
, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Log.d(TAG, "VOLLEY ERROR :" + error.getMessage());
}
}
);
queue.add(stringRequest);
}
public static interface JsonToDatabaseCallback {
public void onDataLoaded();
}
private void parseSession(JSONObject jsonData) throws JSONException{
long id;
String title;
String subTitle;
ArrayList<String> keyNoteList;
//TODO: Do validation on date and convert to date object;
String date;
//TODO: Get day from Date object
String day;
//TODO: Convert time to date object, will be later used to save as reminder
String startTime = "";
String abstractText;
String description;
String venue;
String track;
String moderator;
JSONArray sessions = jsonData.getJSONArray("sessions");
for (int i = 0; i < sessions.length(); i++) {
try {
JSONObject jsonObject = sessions.getJSONObject(i);
title = jsonObject.getString("title");
abstractText = jsonObject.getString("abstract");
subTitle = jsonObject.getString("type");
JSONObject dayObject = jsonObject.getJSONObject("day");
date = dayObject.getString("label_en");
try {
startTime = dataFormatter(jsonObject.getString("begin"));
} catch (ParseException e) {
e.printStackTrace();
}
description = jsonObject.getString("description");
JSONObject venueObject = jsonObject.getJSONObject("location");
venue = venueObject.getString("label_en");
track = jsonObject.getJSONObject("track").getString("label_en");
moderator = "";
FossasiaEvent event = new FossasiaEvent(i, title, subTitle, date, "", startTime, abstractText, description, venue, track, moderator);
String query = "INSERT INTO %s VALUES ('%s', %d, '%s');";
JSONArray jArray = jsonObject.getJSONArray("speakers");
for (int j = 0; j < jArray.length(); j++) {
JSONObject jObj = jArray.getJSONObject(j);
String fullName = jObj.getString("name");
String speakerId = jObj.getString("id");
String speakerQuery = String.format(query, DatabaseHelper.TABLE_NAME_SPEAKER_EVENT_RELATION, fullName, i, StringUtils.replaceUnicode(title));
queries.add(speakerQuery);
}
queries.add(event.generateSqlQuery());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseSpeakers(JSONObject jsonData) throws JSONException{
JSONArray speakers = jsonData.getJSONArray("speakers");
long id;
String name;
String information;
String linkedInUrl;
String twitterHandle;
String designation;
String profilePicUrl;
String organization;
boolean isKeySpeaker;
for (int i = 0; i < speakers.length(); i++) {
try {
JSONObject jsonObject = speakers.getJSONObject(i);
id = i;
name = jsonObject.getString("name");
information = jsonObject.getString("biography");
designation = jsonObject.getString("position");
organization = jsonObject.getString("organization");
if (organization != null && !organization.equals("")) {
designation += ", " + organization;
}
profilePicUrl = jsonObject.getString("photo");
Speaker speaker = new Speaker(id, name, information, "", "", designation, profilePicUrl, 0);
queries.add(speaker.generateSqlQuery());
// Log.d(TAG,speaker.generateSqlQuery()+"");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseTracks(JSONObject jsonData) throws JSONException{
JSONArray tracks = jsonData.getJSONArray("tracks");
for (int i = 0; i < tracks.length(); i++) {
String trackName = tracks.getJSONObject(i).getString("label_en");
String query = "INSERT INTO %s VALUES (%d, '%s', '%s');";
query = String.format(query, DatabaseHelper.TABLE_NAME_TRACK, i, StringUtils.replaceUnicode(trackName), "");
queries.add(query);
}
}
private String dataFormatter(String begin) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = format.parse(begin);
DateFormat formatter = new SimpleDateFormat("HH:mm a");
String dateFormatted = formatter.format(date);
return dateFormatted;
}
}
|
package org.metaborg.meta.lang.dynsem.interpreter.nodes.matching.lists;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.matching.MatchPattern;
import org.metaborg.meta.lang.dynsem.interpreter.terms.IListTerm;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.source.SourceSection;
public abstract class ListLengthFixedMatch extends MatchPattern {
protected final int expectedLength;
public ListLengthFixedMatch(SourceSection source, int expectedLength) {
super(source);
this.expectedLength = expectedLength;
}
@Specialization(guards = { "list == cachedL" })
public boolean executeCachedList(IListTerm<?> list, @Cached("list") IListTerm<?> cachedL,
@Cached("cachedL.size() == expectedLength") boolean eqLength) {
return eqLength;
}
@Specialization(replaces = "executeCachedList")
public boolean executeList(IListTerm<?> list) {
return list.size() == expectedLength;
}
public final int getExpectedLength() {
return expectedLength;
}
}
|
package org.takes.rq;
import com.google.common.base.Joiner;
import com.jcabi.http.request.JdkRequest;
import com.jcabi.http.response.RestResponse;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import org.apache.commons.lang.StringUtils;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.hamcrest.HmRqHeader;
import org.takes.http.FtRemote;
import org.takes.misc.PerformanceTests;
import org.takes.rs.RsText;
@SuppressWarnings("PMD.TooManyMethods")
public final class RqMultipartTest {
/**
* Carriage return constant.
*/
private static final String CRLF = "\r\n";
/**
* Content disposition.
*/
private static final String DISPOSITION = "Content-Disposition";
/**
* Content disposition plus form data.
*/
private static final String CONTENT = String.format(
"%s: %s",
RqMultipartTest.DISPOSITION,
"form-data; name=\"%s\""
);
/**
* Temp directory.
*/
@Rule
public final transient TemporaryFolder temp = new TemporaryFolder();
/**
* RqMultipart.Base can satisfy equals contract.
* @throws IOException if some problem inside
*/
@Test
public void satisfiesEqualsContract() throws IOException {
final String body = "449 N Wolfe Rd, Sunnyvale, CA 94085";
final String part = "t-1";
final Request req = new RqMultipart.Fake(
new RqFake(),
new RqWithHeaders(
new RqFake("", "", body),
contentLengthHeader(body.getBytes().length),
contentDispositionHeader(
String.format("form-data; name=\"%s\"", part)
)
),
new RqWithHeaders(
new RqFake("", "", ""),
contentLengthHeader(0),
contentDispositionHeader(
"form-data; name=\"data\"; filename=\"a.bin\""
)
)
);
final RqMultipart.Base one = new RqMultipart.Base(req);
final RqMultipart.Base two = new RqMultipart.Base(req);
try {
MatcherAssert.assertThat(one, Matchers.equalTo(two));
} finally {
req.body().close();
one.part(part).iterator().next().body().close();
two.part(part).iterator().next().body().close();
}
}
/**
* RqMultipart.Base can throw exception on no closing boundary found.
* @throws IOException if some problem inside
*/
@Test(expected = IOException.class)
public void throwsExceptionOnNoClosingBoundaryFound() throws IOException {
new RqMultipart.Base(
new RqFake(
Arrays.asList(
"POST /h?a=4 HTTP/1.1",
"Host: rtw.example.com",
"Content-Type: multipart/form-data; boundary=AaB01x",
"Content-Length: 100007"
),
Joiner.on(RqMultipartTest.CRLF).join(
"--AaB01x",
"Content-Disposition: form-data; fake=\"t2\"",
"",
"447 N Wolfe Rd, Sunnyvale, CA 94085",
"Content-Transfer-Encoding: uwf-8"
)
)
);
}
/**
* RqMultipart.Fake can throw exception on no name
* at Content-Disposition header.
* @throws IOException if some problem inside
*/
@Test(expected = IOException.class)
public void throwsExceptionOnNoNameAtContentDispositionHeader()
throws IOException {
new RqMultipart.Fake(
new RqWithHeader(
new RqFake("", "", "340 N Wolfe Rd, Sunnyvale, CA 94085"),
RqMultipartTest.DISPOSITION, "form-data; fake=\"t-3\""
)
);
}
/**
* RqMultipart.Base can throw exception on no boundary
* at Content-Type header.
* @throws IOException if some problem inside
*/
@Test(expected = IOException.class)
public void throwsExceptionOnNoBoundaryAtContentTypeHeader()
throws IOException {
new RqMultipart.Base(
new RqFake(
Arrays.asList(
"POST /h?s=3 HTTP/1.1",
"Host: wwo.example.com",
"Content-Type: multipart/form-data; boundaryAaB03x",
"Content-Length: 100005"
),
""
)
);
}
/**
* RqMultipart.Base can throw exception on invalid Content-Type header.
* @throws IOException if some problem inside
*/
@Test(expected = IOException.class)
public void throwsExceptionOnInvalidContentTypeHeader() throws IOException {
new RqMultipart.Base(
new RqFake(
Arrays.asList(
"POST /h?r=3 HTTP/1.1",
"Host: www.example.com",
"Content-Type: multipart; boundary=AaB03x",
"Content-Length: 100004"
),
""
)
);
}
/**
* RqMultipart.Base can parse http body.
* @throws IOException If some problem inside
*/
@Test
public void parsesHttpBody() throws IOException {
final String body = "40 N Wolfe Rd, Sunnyvale, CA 94085";
final String part = "t4";
final RqMultipart multi = new RqMultipart.Fake(
new RqFake(),
new RqWithHeaders(
new RqFake("", "", body),
contentLengthHeader(body.getBytes().length),
contentDispositionHeader(
String.format("form-data; name=\"%s\"", part)
)
),
new RqWithHeaders(
new RqFake("", "", ""),
contentLengthHeader(0),
contentDispositionHeader(
"form-data; name=\"data\"; filename=\"a.bin\""
)
)
);
try {
MatcherAssert.assertThat(
new RqHeaders.Base(
multi.part(part).iterator().next()
).header(RqMultipartTest.DISPOSITION),
Matchers.hasItem("form-data; name=\"t4\"")
);
MatcherAssert.assertThat(
new RqPrint(
new RqHeaders.Base(
multi.part(part).iterator().next()
)
).printBody(),
Matchers.allOf(
Matchers.startsWith("40 N"),
Matchers.endsWith("CA 94085")
)
);
} finally {
multi.part(part).iterator().next().body().close();
}
}
/**
* RqMultipart.Fake can return empty iterator on invalid part request.
* @throws IOException If some problem inside
*/
@Test
public void returnsEmptyIteratorOnInvalidPartRequest() throws IOException {
final String body = "443 N Wolfe Rd, Sunnyvale, CA 94085";
final RqMultipart multi = new RqMultipart.Fake(
new RqFake(),
new RqWithHeaders(
new RqFake("", "", body),
contentLengthHeader(body.getBytes().length),
contentDispositionHeader(
"form-data; name=\"t5\""
)
),
new RqWithHeaders(
new RqFake("", "", ""),
contentLengthHeader(0),
contentDispositionHeader(
"form-data; name=\"data\"; filename=\"a.zip\""
)
)
);
MatcherAssert.assertThat(
multi.part("fake").iterator().hasNext(),
Matchers.is(false)
);
multi.body().close();
}
/**
* RqMultipart.Fake can return correct name set.
* @throws IOException If some problem inside
*/
@Test
public void returnsCorrectNamesSet() throws IOException {
final String body = "441 N Wolfe Rd, Sunnyvale, CA 94085";
final RqMultipart multi = new RqMultipart.Fake(
new RqFake(),
new RqWithHeaders(
new RqFake("", "", body),
contentLengthHeader(body.getBytes().length),
contentDispositionHeader(
"form-data; name=\"address\""
)
),
new RqWithHeaders(
new RqFake("", "", ""),
contentLengthHeader(0),
contentDispositionHeader(
"form-data; name=\"data\"; filename=\"a.bin\""
)
)
);
try {
MatcherAssert.assertThat(
multi.names(),
Matchers.<Iterable<String>>equalTo(
new HashSet<String>(Arrays.asList("address", "data"))
)
);
} finally {
multi.body().close();
}
}
/**
* RqMultipart.Base can return correct part length.
* @throws IOException If some problem inside
*/
@Test
public void returnsCorrectPartLength() throws IOException {
final int length = 5000;
final String part = "x-1";
final String body =
Joiner.on(RqMultipartTest.CRLF).join(
"--zzz",
String.format(
RqMultipartTest.CONTENT,
part
),
"",
StringUtils.repeat("X", length),
"--zzz
);
final Request req = new RqFake(
Arrays.asList(
"POST /post?u=3 HTTP/1.1",
"Host: www.example.com",
contentLengthHeader(body.getBytes().length),
"Content-Type: multipart/form-data; boundary=zzz"
),
body
);
final RqMultipart.Smart regsmart = new RqMultipart.Smart(
new RqMultipart.Base(req)
);
try {
MatcherAssert.assertThat(
regsmart.single(part).body().available(),
Matchers.equalTo(length)
);
} finally {
req.body().close();
regsmart.part(part).iterator().next().body().close();
}
}
/**
* RqMultipart.Base can work in integration mode.
* @throws IOException if some problem inside
*/
@Test
public void consumesHttpRequest() throws IOException {
final String part = "f-1";
final Take take = new Take() {
@Override
public Response act(final Request req) throws IOException {
return new RsText(
new RqPrint(
new RqMultipart.Smart(
new RqMultipart.Base(req)
).single(part)
).printBody()
);
}
};
final String body =
Joiner.on(RqMultipartTest.CRLF).join(
"--AaB0zz",
String.format(RqMultipartTest.CONTENT,part),
"",
"my picture", "--AaB0zz
);
new FtRemote(take).exec(
// @checkstyle AnonInnerLengthCheck (50 lines)
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
new JdkRequest(home)
.method("POST")
.header(
"Content-Type",
"multipart/form-data; boundary=AaB0zz"
)
.header(
"Content-Length",
String.valueOf(body.getBytes().length)
)
.body()
.set(body)
.back()
.fetch()
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_OK)
.assertBody(Matchers.containsString("pic"));
}
}
);
}
/**
* RqMultipart.Base can handle a big request in an acceptable time.
* @throws IOException If some problem inside
*/
@Test
@Category(PerformanceTests.class)
public void handlesRequestInTime() throws IOException {
final int length = 100000000;
final String part = "test";
final File file = this.temp.newFile("handlesRequestInTime.tmp");
final BufferedWriter bwr = new BufferedWriter(new FileWriter(file));
bwr.write(
Joiner.on(RqMultipartTest.CRLF).join(
"--zzz",
String.format(RqMultipartTest.CONTENT,part),
"",
""
)
);
for (int ind = 0; ind < length; ++ind) {
bwr.write("X");
}
bwr.write(RqMultipartTest.CRLF);
bwr.write("--zzz
bwr.write(RqMultipartTest.CRLF);
bwr.close();
final long start = System.currentTimeMillis();
final Request req = new RqFake(
Arrays.asList(
"POST /post?u=3 HTTP/1.1",
"Host: example.com",
"Content-Type: multipart/form-data; boundary=zzz",
String.format(
"Content-Length:%s",
file.length()
)
),
new TempInputStream(new FileInputStream(file), file)
);
final RqMultipart.Smart smart = new RqMultipart.Smart(
new RqMultipart.Base(req)
);
try {
MatcherAssert.assertThat(
smart.single(part).body().available(),
Matchers.equalTo(length)
);
MatcherAssert.assertThat(
System.currentTimeMillis() - start,
//@checkstyle MagicNumberCheck (1 line)
Matchers.lessThan(3000L)
);
} finally {
req.body().close();
smart.part(part).iterator().next().body().close();
}
}
/**
* RqMultipart.Base doesn't distort the content.
* @throws IOException If some problem inside
*/
@Test
public void notDistortContent() throws IOException {
final int length = 1000000;
final String part = "test1";
final File file = this.temp.newFile("notDistortContent.tmp");
final BufferedWriter bwr = new BufferedWriter(new FileWriter(file));
final String head =
Joiner.on(RqMultipartTest.CRLF).join(
"--zzz1",
String.format(
RqMultipartTest.CONTENT,
part
),
"",
""
);
bwr.write(head);
final int byt = 0x7f;
for (int idx = 0; idx < length; ++idx) {
bwr.write(idx % byt);
}
final String foot =
Joiner.on(RqMultipartTest.CRLF).join(
"",
"--zzz1
""
);
bwr.write(foot);
bwr.close();
final Request req = new RqFake(
Arrays.asList(
"POST /post?u=3 HTTP/1.1",
"Host: exampl.com",
contentLengthHeader(
head.getBytes().length + length + foot.getBytes().length
),
"Content-Type: multipart/form-data; boundary=zzz1"
),
new TempInputStream(new FileInputStream(file), file)
);
final InputStream stream = new RqMultipart.Smart(
new RqMultipart.Base(req)
).single(part).body();
try {
MatcherAssert.assertThat(
stream.available(),
Matchers.equalTo(length)
);
for (int idx = 0; idx < length; ++idx) {
MatcherAssert.assertThat(
String.format("byte %d not matched", idx),
stream.read(),
Matchers.equalTo(idx % byt)
);
}
} finally {
req.body().close();
stream.close();
}
}
/**
* RqMultipart.Base can produce parts with Content-Length.
* @throws IOException If some problem inside
*/
@Test
public void producesPartsWithContentLength() throws IOException {
final String part = "t2";
final RqMultipart.Base multipart = new RqMultipart.Base(
new RqFake(
Arrays.asList(
"POST /h?a=4 HTTP/1.1",
"Host: rtw.example.com",
"Content-Type: multipart/form-data; boundary=AaB01x",
"Content-Length: 100007"
),
Joiner.on("\r\n").join(
"--AaB01x",
String.format(
RqMultipartTest.CONTENT,
part
),
"",
"447 N Wolfe Rd, Sunnyvale, CA 94085",
"--AaB01x"
)
)
);
try {
MatcherAssert.assertThat(
multipart.part(part)
.iterator()
.next(),
new HmRqHeader(
"content-length",
"102"
)
);
} finally {
multipart.body().close();
multipart.part(part).iterator().next()
.body().close();
}
}
/**
* Format Content-Disposition header.
* @param dsp Disposition
* @return Content-Disposition header
*/
private static String contentDispositionHeader(final String dsp) {
return String.format("Content-Disposition: %s", dsp);
}
/**
* Format Content-Length header.
* @param length Body length
* @return Content-Length header
*/
private static String contentLengthHeader(final long length) {
return String.format("Content-Length: %d", length);
}
}
|
package bencoding.alarmmanager;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiUIHelper;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
@Kroll.proxy(creatableInModule=AlarmmanagerModule.class)
public class AlarmManagerProxy extends KrollProxy {
NotificationManager mNotificationManager;
public static String rootActivityClassName = "";
public AlarmManagerProxy() {
super();
rootActivityClassName = TiApplication.getInstance().getApplicationContext().getPackageName() + "." + TiApplication.getAppRootOrCurrentActivity().getClass().getSimpleName();
utils.debugLog("rootActivityClassName = " + rootActivityClassName);
}
private Calendar getSecondBasedCalendar(KrollDict args){
int interval = args.getInt("second");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, interval);
return cal;
}
private Calendar getMinuteBasedCalendar(KrollDict args){
int interval = args.getInt("minute");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, interval);
return cal;
}
private Calendar getFullCalendar(KrollDict args){
Calendar defaultDay = Calendar.getInstance();
int day = args.optInt("day", defaultDay.get(Calendar.DAY_OF_MONTH));
int month = args.optInt("month", defaultDay.get(Calendar.MONTH));
int year = args.optInt("year", defaultDay.get(Calendar.YEAR));
int hour = args.optInt("hour", defaultDay.get(Calendar.HOUR_OF_DAY));
int minute = args.optInt("minute", defaultDay.get(Calendar.MINUTE));
int second = args.optInt("second", defaultDay.get(Calendar.SECOND));
Calendar cal = new GregorianCalendar(year, month, day);
cal.add(Calendar.HOUR_OF_DAY, hour);
cal.add(Calendar.MINUTE, minute);
cal.add(Calendar.SECOND, second);
return cal;
}
private Intent createAlarmNotifyIntent(KrollDict args,int requestCode){
int notificationIcon = 0;
String contentTitle = "";
String contentText = "";
String notificationSound = "";
boolean playSound = optionIsEnabled(args,"playSound");
boolean doVibrate = optionIsEnabled(args,"vibrate");
boolean showLights = optionIsEnabled(args,"showLights");
if (args.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TITLE)
|| args.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TEXT))
{
if (args.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TITLE)) {
contentTitle = TiConvert.toString(args, TiC.PROPERTY_CONTENT_TITLE);
}
if (args.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TEXT)) {
contentText = TiConvert.toString(args, TiC.PROPERTY_CONTENT_TEXT);
};
}
if (args.containsKey(TiC.PROPERTY_ICON)) {
Object icon = args.get(TiC.PROPERTY_ICON);
if (icon instanceof Number) {
notificationIcon = ((Number)icon).intValue();
} else {
String iconUrl = TiConvert.toString(icon);
String iconFullUrl = resolveUrl(null, iconUrl);
notificationIcon = TiUIHelper.getResourceId(iconFullUrl);
if (notificationIcon == 0) {
utils.debugLog("No image found for " + iconUrl);
utils.debugLog("Default icon will be used");
}
}
}
if (args.containsKey(TiC.PROPERTY_SOUND)){
notificationSound = resolveUrl(null, TiConvert.toString(args, TiC.PROPERTY_SOUND));
}
Intent intent = new Intent(TiApplication.getInstance().getApplicationContext(), AlarmNotificationListener.class);
//Add some extra information so when the alarm goes off we have enough to create the notification
intent.putExtra("notification_title", contentTitle);
intent.putExtra("notification_msg", contentText);
intent.putExtra("notification_has_icon", (notificationIcon!=0));
intent.putExtra("notification_icon", notificationIcon);
intent.putExtra("notification_sound", notificationSound);
intent.putExtra("notification_play_sound", playSound);
intent.putExtra("notification_vibrate", doVibrate);
intent.putExtra("notification_show_lights", showLights);
intent.putExtra("notification_requestcode", requestCode);
intent.putExtra("notification_root_classname", rootActivityClassName);
intent.putExtra("notification_request_code", requestCode);
intent.setData(Uri.parse("alarmId://" + requestCode));
return intent;
}
@Kroll.method
public String findStartActivityName(){
return TiApplication.getInstance().getApplicationContext().getPackageManager()
.getLaunchIntentForPackage( TiApplication.getInstance().getApplicationContext().getPackageName() ).getClass().getName();
}
@Kroll.method
public void cancelAlarmNotification(@Kroll.argument(optional=true) Object requestCode){
// To cancel an alarm the signature needs to be the same as the submitting one.
utils.debugLog("Cancelling Alarm Notification");
//Set the default request code
int intentRequestCode = AlarmmanagerModule.DEFAULT_REQUEST_CODE;
//If the optional code was provided, cast accordingly
if(requestCode != null){
if (requestCode instanceof Number) {
intentRequestCode = ((Number)requestCode).intValue();
}
}
utils.debugLog(String.format("Cancelling requestCode = {%d}", intentRequestCode));
//Create a placeholder for the args value
HashMap<String, Object> placeholder = new HashMap<String, Object>(0);
KrollDict args = new KrollDict(placeholder);
//Create the Alarm Manager
AlarmManager am = (AlarmManager) TiApplication.getInstance().getApplicationContext().getSystemService(TiApplication.ALARM_SERVICE);
Intent intent = createAlarmNotifyIntent(args,intentRequestCode);
PendingIntent sender = PendingIntent.getBroadcast( TiApplication.getInstance().getApplicationContext(), intentRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT );
am.cancel(sender);
utils.debugLog("Alarm Notification Canceled");
}
private boolean optionIsEnabled(KrollDict args,String paramName){
if (args.containsKeyAndNotNull(paramName)){
Object value = args.get(paramName);
return TiConvert.toBoolean(value);
}else{
return false;
}
}
private boolean hasRepeating(KrollDict args){
boolean results = (args.containsKeyAndNotNull("repeat"));
utils.debugLog("Repeat Frequency enabled: " + results);
return results;
}
private long repeatingFrequency(KrollDict args){
long freqResults = utils.DAILY_MILLISECONDS;
Object repeat = args.get("repeat");
if (repeat instanceof Number) {
utils.debugLog("Repeat value provided in milliseconds found");
freqResults = ((Number)repeat).longValue();
} else {
String repeatValue = TiConvert.toString(repeat);
utils.debugLog("Repeat value of " + repeatValue + " found");
if(repeatValue.toUpperCase()=="HOURLY"){
freqResults=utils.HOURLY_MILLISECONDS;
}
if(repeatValue.toUpperCase()=="WEEKLY"){
freqResults=utils.WEEKLY_MILLISECONDS;
}
if(repeatValue.toUpperCase()=="MONTHLY"){
freqResults=utils.MONTHLY_MILLISECONDS;
}
if(repeatValue.toUpperCase()=="YEARLY"){
freqResults=utils.YEARLY_MILLISECONDS;
}
}
utils.debugLog("Repeat Frequency in milliseconds is " + freqResults);
return freqResults;
}
@Kroll.method
public void addAlarmNotification(@SuppressWarnings("rawtypes") HashMap hm){
@SuppressWarnings("unchecked")
KrollDict args = new KrollDict(hm);
if(!args.containsKeyAndNotNull("minute") && !args.containsKeyAndNotNull("second")){
throw new IllegalArgumentException("The minute or second field is required");
}
if(!args.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TITLE)){
throw new IllegalArgumentException("The context title field (contentTitle) is required");
}
if(!args.containsKeyAndNotNull(TiC.PROPERTY_CONTENT_TEXT)){
throw new IllegalArgumentException("The context text field (contentText) is required");
}
Calendar calendar = null;
boolean isRepeating = hasRepeating(args);
long repeatingFrequency = 0;
if(isRepeating){
repeatingFrequency=repeatingFrequency(args);
}
//If seconds are provided but not years, we just take the seconds to mean to add seconds until fire
boolean secondBased = (args.containsKeyAndNotNull("second") && !args.containsKeyAndNotNull("year"));
//If minutes are provided but not years, we just take the minutes to mean to add minutes until fire
boolean minuteBased = (args.containsKeyAndNotNull("minute") && !args.containsKeyAndNotNull("year"));
//Based on what kind of duration we build our calendar
if(secondBased) {
calendar=getSecondBasedCalendar(args);
}
else if(minuteBased) {
calendar=getMinuteBasedCalendar(args);
}
else {
calendar=getFullCalendar(args);
}
//Get the requestCode if provided, if none provided
//we use 192837 for backwards compatibility
int requestCode = args.optInt("requestCode", AlarmmanagerModule.DEFAULT_REQUEST_CODE);
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
utils.debugLog("Creating Alarm Notification for: " + sdf.format(calendar.getTime()));
//Create the Alarm Manager
AlarmManager am = (AlarmManager) TiApplication.getInstance().getApplicationContext().getSystemService(TiApplication.ALARM_SERVICE);
Intent intent = createAlarmNotifyIntent(args,requestCode);
PendingIntent sender = PendingIntent.getBroadcast( TiApplication.getInstance().getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT );
if(isRepeating){
utils.debugLog("Setting Alarm to repeat");
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), repeatingFrequency, sender);
}else{
utils.debugLog("Setting Alarm for a single run");
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
}
utils.infoLog("Alarm Notification Created");
}
private Intent createAlarmServiceIntent(KrollDict args){
String serviceName = args.getString("service");
Intent intent = new Intent(TiApplication.getInstance().getApplicationContext(), AlarmServiceListener.class);
intent.putExtra("alarm_service_name", serviceName);
//Pass in flag if we need to restart the service on each call
intent.putExtra("alarm_service_force_restart", (optionIsEnabled(args,"forceRestart")));
//Check if the user has selected to use intervals
boolean hasInterval = (args.containsKeyAndNotNull("interval"));
long intervalValue = 0;
if(hasInterval){
Object interval = args.get("interval");
if (interval instanceof Number) {
intervalValue = ((Number)interval).longValue();
}else{
hasInterval=false;
}
}
intent.putExtra("alarm_service_has_interval", hasInterval);
if(hasInterval){
intent.putExtra("alarm_service_interval", intervalValue);
}
utils.debugLog("created alarm service intent for " + serviceName
+ "(forceRestart: "
+ (optionIsEnabled(args,"forceRestart") ? "true" : "false")
+ ", intervalValue: "
+ intervalValue
+ ")");
return intent;
}
@Kroll.method
public void cancelAlarmService(@Kroll.argument(optional=true) Object requestCode){
// To cancel an alarm the signature needs to be the same as the submitting one.
utils.infoLog("Cancelling Alarm Service");
int intentRequestCode = AlarmmanagerModule.DEFAULT_REQUEST_CODE;
if(requestCode != null){
if (requestCode instanceof Number) {
intentRequestCode = ((Number)requestCode).intValue();
}
}
//Create a placeholder for the args value
HashMap<String, Object> placeholder = new HashMap<String, Object>(0);
KrollDict args = new KrollDict(placeholder);
//Create the Alarm Manager
AlarmManager am = (AlarmManager) TiApplication.getInstance().getApplicationContext().getSystemService(TiApplication.ALARM_SERVICE);
Intent intent = createAlarmServiceIntent(args);
PendingIntent sender = PendingIntent.getBroadcast( TiApplication.getInstance().getApplicationContext(), intentRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT );
am.cancel(sender);
utils.infoLog("Alarm Service Canceled");
}
@Kroll.method
public void addAlarmService(@SuppressWarnings("rawtypes") HashMap hm){
@SuppressWarnings("unchecked")
KrollDict args = new KrollDict(hm);
if(!args.containsKeyAndNotNull("service")){
throw new IllegalArgumentException("Service name (service) is required");
}
if(!args.containsKeyAndNotNull("minute") && !args.containsKeyAndNotNull("second")){
throw new IllegalArgumentException("The minute or second field is required");
}
Calendar calendar = null;
boolean isRepeating = hasRepeating(args);
long repeatingFrequency = 0;
if(isRepeating){
repeatingFrequency=repeatingFrequency(args);
}
//If seconds are provided but not years, we just take the seconds to mean to add seconds until fire
boolean secondBased = (args.containsKeyAndNotNull("second") && !args.containsKeyAndNotNull("year"));
//If minutes are provided but not years, we just take the minutes to mean to add minutes until fire
boolean minuteBased = (args.containsKeyAndNotNull("minute") && !args.containsKeyAndNotNull("year"));
//Based on what kind of duration we build our calendar
if(secondBased) {
calendar=getSecondBasedCalendar(args);
}
else if(minuteBased) {
calendar=getMinuteBasedCalendar(args);
}
else {
calendar=getFullCalendar(args);
}
//Get the requestCode if provided, if none provided
//we use 192837 for backwards compatibility
int requestCode = args.optInt("requestCode", AlarmmanagerModule.DEFAULT_REQUEST_CODE);
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
utils.debugLog("Creating Alarm Notification for: " + sdf.format(calendar.getTime()));
AlarmManager am = (AlarmManager) TiApplication.getInstance().getApplicationContext().getSystemService(TiApplication.ALARM_SERVICE);
Intent intent = createAlarmServiceIntent(args);
if(isRepeating){
utils.debugLog("Setting Alarm to repeat at frequency " + repeatingFrequency);
PendingIntent pendingIntent = PendingIntent.getBroadcast( TiApplication.getInstance().getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT );
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeatingFrequency, pendingIntent);
}else{
PendingIntent sender = PendingIntent.getBroadcast( TiApplication.getInstance().getApplicationContext(), requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT );
utils.debugLog("Setting Alarm for a single run");
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
}
utils.infoLog("Alarm Service Request Created");
}
@Kroll.method
public void cancelNotification(int requestCode){
NotificationManager notificationManager = (NotificationManager) TiApplication.getInstance().getSystemService(TiApplication.NOTIFICATION_SERVICE);
notificationManager.cancel(requestCode);
}
@Kroll.method
public void setRootActivityClassName(@Kroll.argument(optional=true) Object className){
utils.infoLog("Request to set rootActivityClassName");
if (className != null) {
if (className instanceof String) {
utils.infoLog("Setting rootActivityClassName to: " + className);
rootActivityClassName = (String)className;
}
}
}
}
|
package org.rootio.tools.media;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.util.Log;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import org.rootio.handset.BuildConfig;
import org.rootio.handset.R;
import org.rootio.tools.persistence.DBAgent;
import org.rootio.tools.utils.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
/**
* Class for the definition of Playlists
*
* @author Jude Mukundane git
*/
public class PlayList implements Player.EventListener {
private ProgramActionType programActionType;
private ArrayList<String> playlists, streams;
private HashSet<Media> mediaList;
private Iterator<Media> mediaIterator;
private Iterator<String> streamIterator;
private SimpleExoPlayer mediaPlayer, callSignPlayer;
private CallSignProvider callSignProvider;
private Context parent;
private Media currentMedia;
private long mediaPosition;
private static PlayList playListInstance;
private MediaLibrary mediaLib;
private BroadcastReceiver playListener;
private boolean isShuttingDown;
protected PlayList() {
// do not instantiate
}
public void init(Context parent, ArrayList<String> playlists, ArrayList<String> streams, ProgramActionType programActionType) {
this.isShuttingDown = false;
this.playlists = playlists;
this.streams = streams;
this.parent = parent;
this.setUpPlayListener();
this.mediaLib = new MediaLibrary(this.parent);
this.programActionType = programActionType;
this.callSignProvider = new CallSignProvider();
}
public static PlayList getInstance() {
if (PlayList.playListInstance != null) {
PlayList.playListInstance.stop();
}
PlayList.playListInstance = new PlayList();
return playListInstance;
}
private void setUpPlayListener() {
this.playListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (PlayList.this.isShuttingDown) {
return;
}
try {
mediaPlayer.release();
} catch (Exception ex) {
}
PlayList.this.load();
PlayList.this.startPlayer();
}
};
IntentFilter fltr = new IntentFilter();
fltr.addAction("org.rootio.media.playChange");
this.parent.registerReceiver(this.playListener, fltr);
}
/**
* Load media for this playlist from the database
*/
public void load() {
mediaList = loadMedia(this.playlists);
if (BuildConfig.DEBUG) {
Utils.toastOnScreen("Playlist has " + mediaList.size() + " songs in it", this.parent);
}
mediaIterator = mediaList.iterator();
streamIterator = streams.iterator();
}
/**
* Play the media loaded in this playlist
*/
public void play() {
startPlayer();
this.callSignProvider.start();
}
private void startPlayer() {
AudioManager audioManager = (AudioManager) this.parent.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) - (BuildConfig.DEBUG ? 7 : 2), AudioManager.FLAG_SHOW_UI);
//First streams, then audio
try {
if (streamIterator.hasNext()) {
String stream = this.streamIterator.next();
mediaPlayer = ExoPlayerFactory.newSimpleInstance(this.parent, new DefaultTrackSelector()); //.n.newInstance();// MediaPlayer.create(this.parent, Uri.parse(sng));
mediaPlayer.addListener(this);
mediaPlayer.setPlayWhenReady(true);
mediaPlayer.prepare(this.getMediaSource(Uri.parse(stream)));
} else if (mediaIterator.hasNext()) {
currentMedia = mediaIterator.next();
try {
Utils.toastOnScreen("Playing " + Uri.fromFile(new File(currentMedia.getFileLocation())), this.parent);
playMedia(Uri.fromFile(new File(currentMedia.getFileLocation())));
} catch (NullPointerException ex) {
Log.e(this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.startPlayer)" : ex.getMessage());
this.startPlayer();
}
} else {
if (BuildConfig.DEBUG) Utils.toastOnScreen("nothing on the iterator", this.parent);
if (mediaList.size() > 0) // reload playlist if only there were songs in it
// were some songs in it
{
this.load();
this.startPlayer();
}
}
} catch (Exception ex) {
Log.e(this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.play)" : ex.getMessage());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.startPlayer();
}
}
private void playMedia(Uri uri) {
this.playMedia(uri, 0l);
}
private void playMedia(Uri uri, long seekPosition) {
//begin by raising the volume
AudioManager audioManager = (AudioManager) this.parent.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) - 2, AudioManager.FLAG_SHOW_UI);
mediaPlayer = ExoPlayerFactory.newSimpleInstance(this.parent, new DefaultTrackSelector());
mediaPlayer.setVolume(1f); //this is the volume of the individual player, not the music service of the phone
mediaPlayer.addListener(this);
mediaPlayer.prepare(this.getMediaSource(uri));
mediaPlayer.setPlayWhenReady(true);
mediaPlayer.seekTo(seekPosition);
}
private MediaSource getMediaSource(Uri uri) {
return new ExtractorMediaSource.Factory(new DefaultDataSourceFactory(this.parent, "rootio")).createMediaSource(uri);
}
/**
* Stops the media player and disposes it.
*/
public void stop() {
this.isShuttingDown = true; //async nature of stuff means stuff can be called in the middle of shutdown. This flag shd be inspected...
if (this.callSignProvider != null) {
this.callSignProvider.stop();
if (this.callSignPlayer != null)
try {
this.callSignPlayer.stop();
this.callSignPlayer.release();
} catch (Exception ex) {
Log.e(this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.stop)" : ex.getMessage());
}
if (mediaPlayer != null) {
try {
this.fadeOut();
mediaPlayer.stop();
mediaPlayer.removeListener(this);
mediaPlayer.release();
} catch (Exception ex) {
Log.e(this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.stop)" : ex.getMessage());
}
}
}
}
private void fadeOut() {
float volume = 1.0F;
while (volume > 0) {
volume = volume - 0.02F;
mediaPlayer.setVolume(volume);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* Pauses the currently playing media
*/
public void pause() {
try {
if (mediaPlayer.getPlaybackState() == Player.STATE_READY) {
this.mediaPosition = this.mediaPlayer.getCurrentPosition();
mediaPlayer.stop(true); //advised that media players should never be reused, even in pause/play scenarios
mediaPlayer.release();
//stop the call sign player as well
this.callSignPlayer.stop(true);
this.callSignPlayer.release();
}
} catch (Exception ex) {
Log.e(this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.pause)" : ex.getMessage());
}
}
/**
* Resumes playback after it has been paused
*/
public void resume() {
try {
this.playMedia(Uri.fromFile(new File(this.currentMedia.getFileLocation())), this.mediaPosition);
mediaPlayer = ExoPlayerFactory.newSimpleInstance(this.parent, new DefaultTrackSelector());
// resume the callSign provider
this.callSignProvider.start();
} catch (Exception ex) {
Log.e(this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.resume)" : ex.getMessage());
}
}
/**
* Loads media with the specified tag into the playlist
*
* @param tag The tag to be matched for media to be loaded into the playlist
* @return Array of Media objects matching specified tag
*/
private HashSet<Media> loadMedia(ArrayList<String> playlists) {
HashSet<Media> media = new HashSet<>();
for (String playlist : playlists) {
Utils.toastOnScreen(playlist, this.parent);
String query = "select title, item, itemtypeid from playlist where title = ?";
String[] args = new String[]{playlist};
DBAgent dbagent = new DBAgent(this.parent);
String[][] data = dbagent.getData(query, args);
Utils.toastOnScreen(String.valueOf(data.length), this.parent);
for (int i = 0; i < data.length; i++) {
if (playlist.equals("jingle")) {
//Utils.toastOnScreen(data[i][2], this.parent);
}
if (data[i][2].equals("1"))// songs
{
media.add(this.mediaLib.getMedia(data[i][1]));
} else if (data[i][2].equals("2"))// albums
{
media.addAll(this.mediaLib.getMediaForAlbum(data[i][1]));
} else if (data[i][2].equals("3"))// artists
{
media.addAll(this.mediaLib.getMediaForArtist(data[i][1]));
}
}
}
return media;
}
/**
* Gets the media currently loaded in this playlist
*
* @return Array of Media objects loaded in this playlist
*/
public HashSet<Media> getMedia() {
return this.mediaList;
}
void onReceiveCallSign(String Url) {
try {
callSignPlayer = ExoPlayerFactory.newSimpleInstance(this.parent, new DefaultTrackSelector());
callSignPlayer.addListener(new Player.EventListener() {
@Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState) {
case Player.STATE_ENDED:
try {
PlayList.this.mediaPlayer.setVolume(1.0f);
callSignPlayer.removeListener(this);
callSignPlayer.release();
} catch (Exception ex) {
Log.e(PlayList.this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.onCompletion)" : ex.getMessage());
}
break;
}
}
@Override
public void onRepeatModeChanged(int repeatMode) {
}
@Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
@Override
public void onPlayerError(ExoPlaybackException error) {
}
@Override
public void onPositionDiscontinuity(int reason) {
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
@Override
public void onSeekProcessed() {
}
});
this.mediaPlayer.setVolume(0.07f);
callSignPlayer.setVolume(1.0f);
callSignPlayer.prepare(this.getMediaSource(Uri.fromFile(new File(Url))));
this.callSignPlayer.setPlayWhenReady(true);
} catch (Exception ex) {
Log.e(PlayList.this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.onReceiveCallSign)" : ex.getMessage());
}
}
@Override
protected void finalize() {
this.stop();
try {
super.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState) {
case Player.STATE_READY:
try {
if (this.callSignPlayer != null || this.callSignPlayer.getPlaybackState() == Player.STATE_READY) {
this.mediaPlayer.setVolume(0.07f);
} else {
this.mediaPlayer.setVolume(1f);
}
} catch (Exception ex) {
this.mediaPlayer.setVolume(1f);
}
break;
case Player.STATE_ENDED: //a song has ended
if (this.isShuttingDown) {
return;
}
try {
mediaPlayer.release();
} catch (Exception ex) {
}
this.load();
this.startPlayer();
break;
}
}
@Override
public void onRepeatModeChanged(int repeatMode) {
}
@Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
@Override
public void onPlayerError(ExoPlaybackException error) {
}
@Override
public void onPositionDiscontinuity(int reason) {
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
@Override
public void onSeekProcessed() {
}
class CallSignProvider implements Runnable {
private final HashSet<Media> callSigns;
Iterator<Media> mediaIterator;
private boolean isRunning;
CallSignProvider() {
//PlayList.this.parent = parent;
ArrayList jingles = new ArrayList<String>();
jingles.add("jingle");
this.callSigns = PlayList.this.loadMedia(jingles);
this.isRunning = false;
}
@Override
public void run() {
this.isRunning = true;
this.mediaIterator = callSigns.iterator();
while (this.isRunning) {
try {
this.playCallSign();
Thread.sleep(1200000);// 20 mins
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
void stop() {
this.isRunning = false;
}
private void playCallSign() {
try {
if (this.callSigns.size() < 1)
return;
if (!this.mediaIterator.hasNext()) {
this.mediaIterator = callSigns.iterator(); // reset the iterator to 0 if at the end
}
onReceiveCallSign(mediaIterator.next().getFileLocation());
} catch (Exception ex) {
Log.e(PlayList.this.parent.getString(R.string.app_name), ex.getMessage() == null ? "Null pointer exception(PlayList.playCallSign)" : ex.getMessage());
}
}
public void start() {
new Thread(this).start();
}
}
}
|
package org.xwiki.crypto.internal.digest.factory;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.xwiki.crypto.DigestFactory;
/**
* Bouncy Castle based Digest common interface.
*
* @version $Id$
*/
public interface BcDigestFactory extends DigestFactory
{
/**
* @return a new cipher engine instance.
*/
org.bouncycastle.crypto.Digest getDigestInstance();
/**
* @return the algorithm identifier of digest produced by this factory.
*/
AlgorithmIdentifier getAlgorithmIdentifier();
}
|
package test.dependent;
import org.testng.annotations.ExpectedExceptions;
import org.testng.annotations.Test;
import test.BaseTest;
public class DependentTest extends BaseTest {
@Test
public void simpleSkip() {
addClass(SampleDependent1.class.getName());
run();
String[] passed = {
};
String[] failed = {
"fail"
};
String[] skipped = {
"shouldBeSkipped"
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
verifyTests("Skipped", skipped, getSkippedTests());
}
@Test
public void dependentMethods() {
addClass(SampleDependentMethods.class.getName());
run();
String[] passed = {
"oneA", "oneB", "secondA", "thirdA", "canBeRunAnytime"
};
String[] failed = {
};
String[] skipped = {
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
verifyTests("Skipped", skipped, getSkippedTests());
}
@Test
public void dependentMethodsWithSkip() {
addClass(SampleDependentMethods4.class.getName());
run();
String[] passed = {
"step1",
};
String[] failed = {
"step2",
};
String[] skipped = {
"step3"
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
verifyTests("Skipped", skipped, getSkippedTests());
}
@Test
@ExpectedExceptions({ org.testng.TestNGException.class })
public void dependentMethodsWithNonExistentMethod() {
addClass(SampleDependentMethods5.class.getName());
run();
String[] passed = {
"step1", "step2"
};
String[] failed = {
};
String[] skipped = {
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
verifyTests("Skipped", skipped, getSkippedTests());
}
@Test(expectedExceptions = org.testng.TestNGException.class )
public void dependentMethodsWithCycle() {
addClass(SampleDependentMethods6.class.getName());
run();
}
@Test(expectedExceptions = org.testng.TestNGException.class )
public void dependentGroupsWithCycle() {
addClass("test.dependent.SampleDependentMethods7");
run();
}
@Test
public void multipleSkips() {
addClass(MultipleDependentSampleTest.class.getName());
run();
String[] passed = {
"init",
};
String[] failed = {
"fail",
};
String[] skipped = {
"skip1", "skip2"
};
verifyTests("Passed", passed, getPassedTests());
verifyTests("Failed", failed, getFailedTests());
verifyTests("Skipped", skipped, getSkippedTests());
}
} // DependentTest
|
package org.xwiki.rendering.internal.parser.pygments;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.net.URLDecoder;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PyUnicode;
import org.python.util.PythonInterpreter;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.VerbatimBlock;
import org.xwiki.rendering.parser.AbstractHighlightParser;
import org.xwiki.rendering.parser.HighlightParser;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.parser.Syntax;
import org.xwiki.rendering.parser.SyntaxType;
/**
* Highlight provided source using Pygments.
*
* @version $Id$
* @since 1.7RC1
*/
// Note that we force the Component annotation so that this component is only registered as a Highlight Parser
// and not a Parser too since we don't want this parser to be visible to users as a valid standard input parser
// component.
@Component(roles = { HighlightParser.class })
public class PygmentsParser extends AbstractHighlightParser implements Initializable
{
/**
* A Pygments .py file to search for the location of the jar.
*/
private static final String LEXER_PY = "Lib/pygments/lexer.py";
/**
* A Pygments .py file to search for the location of the jar.
*/
private static final String XDOMFORMATTER_PY = "Lib/pygments/formatters/xdom.py";
/**
* The name of the lexer variable in PPython code.
*/
private static final String PY_LEXER_VARNAME = "lexer";
/**
* The name of the formatter variable in PPython code.
*/
private static final String PY_FORMATTER_VARNAME = "formatter";
/**
* The name of the listener variable in PPython code.
*/
private static final String PY_LISTENER_VARNAME = "listener";
/**
* The name of the variable containing the source code to highlight in PPython code.
*/
private static final String PY_CODE_VARNAME = "code";
/**
* Python code to create the lexer.
*/
private static final String PY_LEXER_CREATE =
PY_LEXER_VARNAME + " = pygments.lexers.get_lexer_by_name(\"{0}\", stripall=True)";
/**
* Python code to find the lexer from source.
*/
private static final String PY_LEXER_FIND =
PY_LEXER_VARNAME + " = None\n" + "try:\n" + " " + PY_LEXER_VARNAME + " = guess_lexer(code, stripall=True)\n"
+ "except ClassNotFound:\n" + " pass";
/**
* Java jar URL special characters.
*/
private static final String JAR_URL_PREFIX = "jar:file:";
/**
* Jar path separator.
*/
private static final String JAR_SEPARATOR = "!";
/**
* The character use to separate URL parts.
*/
private static final String URL_SEPARATOR = "/";
/**
* The syntax identifier.
*/
private Syntax syntax;
/**
* The Python interpreter used to execute Pygments.
*/
private PythonInterpreter pythonInterpreter;
/**
* {@inheritDoc}
*
* @see org.xwiki.component.phase.Initializable#initialize()
*/
public void initialize() throws InitializationException
{
this.syntax = new Syntax(SyntaxType.getSyntaxType(getSyntaxId() + "-highlight"), "1.0");
System.setProperty("python.home", findPygmentsPath());
this.pythonInterpreter = new PythonInterpreter();
// imports Pygments
this.pythonInterpreter.exec("import pygments");
this.pythonInterpreter.execfile(getClass().getClassLoader().getResourceAsStream(XDOMFORMATTER_PY));
this.pythonInterpreter.exec("from pygments.lexers import guess_lexer");
this.pythonInterpreter.exec("from pygments.util import ClassNotFound");
}
/**
* {@inheritDoc}
*
* @see org.xwiki.rendering.parser.Parser#getSyntax()
*/
public Syntax getSyntax()
{
return this.syntax;
}
/**
* {@inheritDoc}
*
* @see org.xwiki.rendering.parser.HighlightParser#highlight(java.lang.String, java.io.Reader)
*/
public List<Block> highlight(String syntaxId, Reader source) throws ParseException
{
PythonInterpreter interpreter = getPythonInterpreter();
BlocksGeneratorPygmentsListener listener = new BlocksGeneratorPygmentsListener();
String code;
try {
code = IOUtils.toString(source);
} catch (IOException e) {
throw new ParseException("Failed to read source", e);
}
interpreter.set(PY_LISTENER_VARNAME, listener);
interpreter.set(PY_CODE_VARNAME, new PyUnicode(code));
if (!StringUtils.isEmpty(syntaxId)) {
interpreter.exec(MessageFormat.format(PY_LEXER_CREATE, syntaxId));
} else {
interpreter.exec(PY_LEXER_FIND);
}
PyObject lexer = interpreter.get(PY_LEXER_VARNAME);
if (lexer == null || lexer == Py.None) {
// No lexer found
if (getLogger().isDebugEnabled()) {
getLogger().debug("no lexer found");
}
return Collections.<Block> singletonList(new VerbatimBlock(code, true));
}
interpreter.exec(MessageFormat.format("{0} = XDOMFormatter({1})", PY_FORMATTER_VARNAME, PY_LISTENER_VARNAME));
interpreter.exec(MessageFormat.format("pygments.highlight({0}, {1}, {2})", PY_CODE_VARNAME, PY_LEXER_VARNAME,
PY_FORMATTER_VARNAME));
List<String> vars = Arrays.asList(PY_LISTENER_VARNAME, PY_CODE_VARNAME, PY_LEXER_VARNAME, PY_FORMATTER_VARNAME);
for (String var : vars) {
interpreter.exec("del " + var);
}
return listener.getBlocks();
}
/**
* @return the python interpreter.
*/
protected PythonInterpreter getPythonInterpreter()
{
return this.pythonInterpreter;
}
/**
* Get the full URL root path of provided Python file.
*
* @param fileToFind the Python file to find in the classpath.
* @return the root URL path.
*/
private String findPath(String fileToFind)
{
URL url = getClass().getResource(URL_SEPARATOR + fileToFind);
String urlString = URLDecoder.decode(url.toString());
// we expect an URL like
// jar:file:/jar_dir/jython-lib.jar!/Lib/pygments/lexer.py
int jarSeparatorIndex = urlString.indexOf(JAR_SEPARATOR);
if (urlString.startsWith(JAR_URL_PREFIX) && jarSeparatorIndex > 0) {
urlString = urlString.substring(JAR_URL_PREFIX.length(), jarSeparatorIndex);
} else {
// Just in case we don't get a jar URL
int begin = urlString.indexOf(URL_SEPARATOR);
int lexerPyIndex = urlString.lastIndexOf(fileToFind);
urlString = urlString.substring(begin, lexerPyIndex);
if (urlString.endsWith(URL_SEPARATOR)) {
urlString = urlString.substring(0, urlString.length() - 1);
}
if (urlString.endsWith(JAR_SEPARATOR)) {
urlString = urlString.substring(0, urlString.length() - 1);
}
}
return urlString;
}
/**
* Determine and register the home of the Pygments Pyton files.
*
* @return the root path of Pygments Pyton files.
*/
private String findPygmentsPath()
{
return findPath(LEXER_PY);
}
}
|
package org.wikipedia.page;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.appenguin.onboarding.ToolTip;
import org.json.JSONException;
import org.json.JSONObject;
import org.wikipedia.BackPressedHandler;
import org.wikipedia.NightModeHandler;
import org.wikipedia.R;
import org.wikipedia.Site;
import org.wikipedia.WikipediaApp;
import org.wikipedia.analytics.ConnectionIssueFunnel;
import org.wikipedia.analytics.FindInPageFunnel;
import org.wikipedia.analytics.GalleryFunnel;
import org.wikipedia.analytics.LinkPreviewFunnel;
import org.wikipedia.analytics.PageScrollFunnel;
import org.wikipedia.analytics.SavedPagesFunnel;
import org.wikipedia.analytics.TabFunnel;
import org.wikipedia.bridge.CommunicationBridge;
import org.wikipedia.bridge.StyleBundle;
import org.wikipedia.editing.EditHandler;
import org.wikipedia.history.HistoryEntry;
import org.wikipedia.interlanguage.LangLinksActivity;
import org.wikipedia.page.gallery.GalleryActivity;
import org.wikipedia.page.leadimages.ArticleHeaderView;
import org.wikipedia.page.leadimages.LeadImagesHandler;
import org.wikipedia.page.snippet.CompatActionMode;
import org.wikipedia.page.snippet.ShareHandler;
import org.wikipedia.page.tabs.Tab;
import org.wikipedia.page.tabs.TabsProvider;
import org.wikipedia.savedpages.ImageUrlMap;
import org.wikipedia.savedpages.LoadSavedPageUrlMapTask;
import org.wikipedia.savedpages.SavePageTask;
import org.wikipedia.savedpages.SavedPageCheckTask;
import org.wikipedia.search.SearchBarHideHandler;
import org.wikipedia.settings.Prefs;
import org.wikipedia.tooltip.ToolTipUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.ThrowableUtil;
import org.wikipedia.util.log.L;
import org.wikipedia.views.ObservableWebView;
import org.wikipedia.views.SwipeRefreshLayoutWithScroll;
import org.wikipedia.views.WikiDrawerLayout;
import org.wikipedia.views.WikiErrorView;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static butterknife.ButterKnife.findById;
import static org.wikipedia.util.DeviceUtil.hideSoftKeyboard;
import static org.wikipedia.util.DimenUtil.getContentTopOffset;
import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx;
import static org.wikipedia.util.ResourceUtil.getThemedAttributeId;
import static org.wikipedia.util.UriUtil.decodeURL;
import static org.wikipedia.util.UriUtil.visitInExternalBrowser;
public class PageFragment extends Fragment implements BackPressedHandler {
public static final int TOC_ACTION_SHOW = 0;
public static final int TOC_ACTION_HIDE = 1;
public static final int TOC_ACTION_TOGGLE = 2;
private boolean pageSaved;
private boolean pageRefreshed;
private boolean savedPageCheckComplete;
private boolean errorState = false;
private static final int TOC_BUTTON_HIDE_DELAY = 2000;
private static final int REFRESH_SPINNER_ADDITIONAL_OFFSET = (int) (16 * WikipediaApp.getInstance().getScreenDensity());
private PageLoadStrategy pageLoadStrategy;
private PageViewModel model;
@Nullable private PageInfo pageInfo;
/**
* List of tabs, each of which contains a backstack of page titles.
* Since the list consists of Parcelable objects, it can be saved and restored from the
* savedInstanceState of the fragment.
*/
@NonNull
private final List<Tab> tabList = new ArrayList<>();
@NonNull
private TabFunnel tabFunnel = new TabFunnel();
@Nullable
private PageScrollFunnel pageScrollFunnel;
/**
* Whether to save the full page content as soon as it's loaded.
* Used in the following cases:
* - Stored page content is corrupted
* - Page bookmarks are imported from the old app.
* In the above cases, loading of the saved page will "fail", and will
* automatically bounce to the online version of the page. Once the online page
* loads successfully, the content will be saved, thereby reconstructing the
* stored version of the page.
*/
private boolean saveOnComplete = false;
private ArticleHeaderView articleHeaderView;
private LeadImagesHandler leadImagesHandler;
private SearchBarHideHandler searchBarHideHandler;
private ObservableWebView webView;
private SwipeRefreshLayoutWithScroll refreshView;
private WikiErrorView errorView;
private WikiDrawerLayout tocDrawer;
private FloatingActionButton tocButton;
private CommunicationBridge bridge;
private LinkHandler linkHandler;
private ReferenceDialog referenceDialog;
private EditHandler editHandler;
private ActionMode findInPageActionMode;
@NonNull private ShareHandler shareHandler;
private TabsProvider tabsProvider;
private WikipediaApp app;
private SavedPagesFunnel savedPagesFunnel;
private ConnectionIssueFunnel connectionIssueFunnel;
@NonNull
private final SwipeRefreshLayout.OnRefreshListener pageRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshPage();
}
};
@NonNull
private final View.OnClickListener tocButtonOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyboard(getActivity());
showToCButton();
toggleToC(TOC_ACTION_TOGGLE);
}
};
@NonNull private final Runnable hideToCButtonRunnable = new Runnable() {
@Override
public void run() {
tocButton.hide();
}
};
@Nullable
private PageLoadCallbacks pageLoadCallbacks;
public ObservableWebView getWebView() {
return webView;
}
public PageTitle getTitle() {
return model.getTitle();
}
public PageTitle getTitleOriginal() {
return model.getTitleOriginal();
}
@NonNull public ShareHandler getShareHandler() {
return shareHandler;
}
@Nullable public Page getPage() {
return model.getPage();
}
public HistoryEntry getHistoryEntry() {
return model.getCurEntry();
}
public void setSavedPageCheckComplete(boolean complete) {
savedPageCheckComplete = complete;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (WikipediaApp) getActivity().getApplicationContext();
model = new PageViewModel();
pageLoadStrategy = new JsonPageLoadStrategy();
initTabs();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page, container, false);
webView = (ObservableWebView) rootView.findViewById(R.id.page_web_view);
initWebViewListeners();
tocDrawer = (WikiDrawerLayout) rootView.findViewById(R.id.page_toc_drawer);
tocDrawer.setDragEdgeWidth(getResources().getDimensionPixelSize(R.dimen.drawer_drag_margin));
tocButton = (FloatingActionButton) rootView.findViewById(R.id.floating_toc_button);
tocButton.setOnClickListener(tocButtonOnClickListener);
refreshView = (SwipeRefreshLayoutWithScroll) rootView
.findViewById(R.id.page_refresh_container);
int swipeOffset = getContentTopOffsetPx(getActivity()) + REFRESH_SPINNER_ADDITIONAL_OFFSET;
refreshView.setProgressViewOffset(false, -swipeOffset, swipeOffset);
// if we want to give it a custom color:
//refreshView.setProgressBackgroundColor(R.color.swipe_refresh_circle);
refreshView.setScrollableChild(webView);
refreshView.setOnRefreshListener(pageRefreshListener);
errorView = (WikiErrorView)rootView.findViewById(R.id.page_error);
return rootView;
}
@Override
public void onDestroyView() {
//uninitialize the bridge, so that no further JS events can have any effect.
bridge.cleanup();
shareHandler.onDestroy();
super.onDestroyView();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
connectionIssueFunnel = new ConnectionIssueFunnel(app);
updateFontSize();
// Explicitly set background color of the WebView (independently of CSS, because
// the background may be shown momentarily while the WebView loads content,
// creating a seizure-inducing effect, or at the very least, a migraine with aura).
webView.setBackgroundColor(getResources().getColor(
getThemedAttributeId(getActivity(), R.attr.page_background_color)));
bridge = new CommunicationBridge(webView, "file:///android_asset/index.html");
setupMessageHandlers();
sendDecorOffsetMessage();
linkHandler = new LinkHandler(getActivity(), bridge) {
@Override
public void onPageLinkClicked(String anchor) {
if (referenceDialog != null && referenceDialog.isShowing()) {
referenceDialog.dismiss();
}
JSONObject payload = new JSONObject();
try {
payload.put("anchor", anchor);
} catch (JSONException e) {
throw new RuntimeException(e);
}
bridge.sendMessage("handleReference", payload);
}
@Override
public void onInternalLinkClicked(PageTitle title) {
handleInternalLink(title);
}
@Override
public Site getSite() {
return model.getTitle().getSite();
}
};
new ReferenceHandler(bridge) {
@Override
protected void onReferenceClicked(String refHtml) {
if (!isAdded()) {
Log.d("PageFragment",
"Detached from activity, so stopping reference click.");
return;
}
if (referenceDialog == null) {
referenceDialog = new ReferenceDialog(getActivity(), linkHandler);
}
referenceDialog.updateReference(refHtml);
referenceDialog.show();
}
};
bridge.injectStyleBundle(StyleBundle.getAvailableBundle(StyleBundle.BUNDLE_PAGEVIEW));
// make sure styles get injected before the NightModeHandler and other handlers
if (app.isCurrentThemeDark()) {
new NightModeHandler(bridge).turnOn(true);
}
errorView.setRetryClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
refreshPage();
}
});
errorView.setBackClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
editHandler = new EditHandler(this, bridge);
pageLoadStrategy.setEditHandler(editHandler);
tocHandler = new ToCHandler(getPageActivity(), tocDrawer, bridge);
// TODO: initialize View references in onCreateView().
articleHeaderView = findById(getView(), R.id.page_header_view);
leadImagesHandler = new LeadImagesHandler(this, bridge, webView, articleHeaderView);
searchBarHideHandler = getPageActivity().getSearchBarHideHandler();
searchBarHideHandler.setScrollView(webView);
shareHandler = new ShareHandler(getPageActivity(), bridge);
tabsProvider = new TabsProvider(getPageActivity(), tabList);
tabsProvider.setTabsProviderListener(tabsProviderListener);
PageLongPressHandler.WebViewContextMenuListener contextMenuListener = new LongPressHandler(getPageActivity());
new PageLongPressHandler(getActivity(), webView, HistoryEntry.SOURCE_INTERNAL_LINK,
contextMenuListener);
pageLoadStrategy.setUp(model, this, refreshView, webView, bridge, searchBarHideHandler,
leadImagesHandler, getCurrentTab().getBackStack());
}
private void initWebViewListeners() {
webView.addOnUpOrCancelMotionEventListener(new ObservableWebView.OnUpOrCancelMotionEventListener() {
@Override
public void onUpOrCancelMotionEvent() {
// queue the button to be hidden when the user stops scrolling.
hideToCButton(true);
// update our session, since it's possible for the user to remain on the page for
// a long time, and we wouldn't want the session to time out.
app.getSessionFunnel().touchSession();
}
});
webView.setOnFastScrollListener(new ObservableWebView.OnFastScrollListener() {
@Override
public void onFastScroll() {
// show the ToC button...
showToCButton();
// and immediately queue it to be hidden after a short delay, but only if we're
// not at the top of the page.
if (webView.getScrollY() > 0) {
hideToCButton(true);
}
}
});
webView.addOnScrollChangeListener(new ObservableWebView.OnScrollChangeListener() {
@Override
public void onScrollChanged(int oldScrollY, int scrollY, boolean isHumanScroll) {
if (scrollY <= 0) {
// always show the ToC button when we're at the top of the page.
showToCButton();
}
if (pageScrollFunnel != null) {
pageScrollFunnel.onPageScrolled(oldScrollY, scrollY, isHumanScroll);
}
}
});
}
private void handleInternalLink(PageTitle title) {
if (!isResumed()) {
return;
}
// if it's a Special page, launch it in an external browser, since mobileview
// doesn't support the Special namespace.
// TODO: remove when Special pages are properly returned by the server
if (title.isSpecial()) {
visitInExternalBrowser(getActivity(), Uri.parse(title.getMobileUri()));
return;
}
if (referenceDialog != null && referenceDialog.isShowing()) {
referenceDialog.dismiss();
}
if (!TextUtils.isEmpty(title.getNamespace()) || !app.isLinkPreviewEnabled()) {
HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK);
getPageActivity().loadPage(title, historyEntry);
new LinkPreviewFunnel(app).logNavigate();
} else {
getPageActivity().showLinkPreview(title, HistoryEntry.SOURCE_INTERNAL_LINK);
}
}
private TabsProvider.TabsProviderListener tabsProviderListener = new TabsProvider.TabsProviderListener() {
@Override
public void onEnterTabView() {
tabFunnel = new TabFunnel();
tabFunnel.logEnterList(tabList.size());
}
@Override
public void onCancelTabView() {
tabsProvider.exitTabMode();
tabFunnel.logCancel(tabList.size());
}
@Override
public void onTabSelected(int position) {
// move the selected tab to the bottom of the list, and navigate to it!
// (but only if it's a different tab than the one currently in view!
if (position != tabList.size() - 1) {
Tab tab = tabList.remove(position);
tabList.add(tab);
pageLoadStrategy.updateCurrentBackStackItem();
pageLoadStrategy.setBackStack(tab.getBackStack());
pageLoadStrategy.loadFromBackStack();
}
tabsProvider.exitTabMode();
tabFunnel.logSelect(tabList.size(), position);
}
@Override
public void onNewTabRequested() {
// just load the main page into a new tab...
getPageActivity().loadMainPageInForegroundTab();
tabFunnel.logCreateNew(tabList.size());
}
@Override
public void onCloseTabRequested(int position) {
if (!app.isDevRelease() && (position < 0 || position >= tabList.size())) {
// According to T109998, the position may possibly be out-of-bounds, but we can't
// reproduce it. We'll handle this case, but only for non-dev builds, so that we
// can investigate the issue further if we happen upon it ourselves.
return;
}
tabList.remove(position);
tabFunnel.logClose(tabList.size(), position);
if (position < tabList.size()) {
// if it's not the topmost tab, then just delete it and update the tab list...
tabsProvider.invalidate();
} else if (tabList.size() > 0) {
tabsProvider.invalidate();
// but if it's the topmost tab, then load the topmost page in the next tab.
pageLoadStrategy.setBackStack(getCurrentTab().getBackStack());
pageLoadStrategy.loadFromBackStack();
} else {
tabFunnel.logCancel(tabList.size());
// and if the last tab was closed, then finish the activity!
getActivity().finish();
}
}
};
@Override
public void onPause() {
super.onPause();
Prefs.setTabs(tabList);
closePageScrollFunnel();
}
@Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("");
initPageScrollFunnel();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
sendDecorOffsetMessage();
// if the screen orientation changes, then re-layout the lead image container,
// but only if we've finished fetching the page.
if (!pageLoadStrategy.isLoading()) {
pageLoadStrategy.layoutLeadImage();
}
tabsProvider.onConfigurationChanged();
}
public Tab getCurrentTab() {
return tabList.get(tabList.size() - 1);
}
public void invalidateTabs() {
tabsProvider.invalidate();
}
public void openInNewBackgroundTabFromMenu(PageTitle title, HistoryEntry entry) {
openInNewTabFromMenu(title, entry, getBackgroundTabPosition());
}
public void openInNewForegroundTabFromMenu(PageTitle title, HistoryEntry entry) {
openInNewTabFromMenu(title, entry, getForegroundTabPosition());
loadPage(title, entry, PageLoadStrategy.Cache.FALLBACK, false);
}
public void openInNewTabFromMenu(PageTitle title,
HistoryEntry entry,
int position) {
openInNewTab(title, entry, position);
tabFunnel.logOpenInNew(tabList.size());
}
public void loadPage(PageTitle title, HistoryEntry entry, PageLoadStrategy.Cache cachePreference,
boolean pushBackStack) {
loadPage(title, entry, cachePreference, pushBackStack, 0);
}
public void loadPage(PageTitle title, HistoryEntry entry, PageLoadStrategy.Cache cachePreference,
boolean pushBackStack, int stagedScrollY) {
loadPage(title, entry, cachePreference, pushBackStack, stagedScrollY, false);
}
public void loadPage(PageTitle title, HistoryEntry entry, PageLoadStrategy.Cache cachePreference,
boolean pushBackStack, boolean pageRefreshed) {
loadPage(title, entry, cachePreference, pushBackStack, 0, pageRefreshed);
}
/**
* Load a new page into the WebView in this fragment.
* This shall be the single point of entry for loading content into the WebView, whether it's
* loading an entirely new page, refreshing the current page, retrying a failed network
* request, etc.
* @param title Title of the new page to load.
* @param entry HistoryEntry associated with the new page.
* @param cachePreference Whether to try loading the page from cache or from network.
* @param pushBackStack Whether to push the new page onto the backstack.
*/
public void loadPage(PageTitle title, HistoryEntry entry, PageLoadStrategy.Cache cachePreference,
boolean pushBackStack, int stagedScrollY, boolean pageRefreshed) {
// disable sliding of the ToC while sections are loading
tocHandler.setEnabled(false);
hideToCButton(false);
errorState = false;
errorView.setVisibility(View.GONE);
model.setTitle(title);
model.setTitleOriginal(title);
model.setCurEntry(entry);
savedPagesFunnel = app.getFunnelManager().getSavedPagesFunnel(title.getSite());
getPageActivity().updateProgressBar(true, true, 0);
this.pageRefreshed = pageRefreshed;
if (!pageRefreshed) {
savedPageCheckComplete = false;
checkIfPageIsSaved();
}
closePageScrollFunnel();
pageLoadStrategy.load(pushBackStack, cachePreference, stagedScrollY);
}
public Bitmap getLeadImageBitmap() {
return leadImagesHandler.getLeadImageBitmap();
}
/**
* Returns the normalized (0.0 to 1.0) vertical focus position of the lead image.
* A value of 0.0 represents the top of the image, and 1.0 represents the bottom.
* @return Normalized vertical focus position.
*/
public float getLeadImageFocusY() {
return leadImagesHandler.getLeadImageFocusY();
}
/**
* Update the WebView's base font size, based on the specified font size from the app
* preferences.
*/
public void updateFontSize() {
webView.getSettings().setDefaultFontSize((int) app.getFontSize(getActivity().getWindow()));
}
public void setPageSaved(boolean saved) {
pageSaved = saved;
leadImagesHandler.updateBookmark(pageSaved);
}
public void onActionModeShown(CompatActionMode mode) {
// make sure we have a page loaded, since shareHandler makes references to it.
if (model.getPage() != null) {
shareHandler.onTextSelected(mode);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PageActivity.ACTIVITY_REQUEST_EDIT_SECTION
&& resultCode == EditHandler.RESULT_REFRESH_PAGE) {
pageLoadStrategy.backFromEditing(data);
FeedbackUtil.showMessage(getActivity(), R.string.edit_saved_successfully);
// and reload the page...
loadPage(model.getTitleOriginal(), model.getCurEntry(), PageLoadStrategy.Cache.NONE, false);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (!isAdded() || getPageActivity().isSearching()) {
return;
}
inflater.inflate(R.menu.menu_page_actions, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (!isAdded() || getPageActivity().isSearching()) {
return;
}
MenuItem otherLangItem = menu.findItem(R.id.menu_page_other_languages);
MenuItem findInPageItem = menu.findItem(R.id.menu_page_find_in_page);
MenuItem contentIssues = menu.findItem(R.id.menu_page_content_issues);
MenuItem similarTitles = menu.findItem(R.id.menu_page_similar_titles);
MenuItem themeChooserItem = menu.findItem(R.id.menu_page_font_and_theme);
if (pageLoadStrategy.isLoading() || errorState) {
otherLangItem.setEnabled(false);
findInPageItem.setEnabled(false);
contentIssues.setEnabled(false);
similarTitles.setEnabled(false);
themeChooserItem.setEnabled(false);
} else {
// Only display "Read in other languages" if the article is in other languages
otherLangItem.setVisible(model.getPage() != null && model.getPage().getPageProperties().getLanguageCount() != 0);
otherLangItem.setEnabled(true);
findInPageItem.setEnabled(true);
updateMenuPageInfo(menu);
themeChooserItem.setEnabled(true);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.homeAsUp:
return true;
case R.id.menu_page_other_languages:
Intent langIntent = new Intent();
langIntent.setClass(getActivity(), LangLinksActivity.class);
langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE);
langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle());
getActivity().startActivityForResult(langIntent,
PageActivity.ACTIVITY_REQUEST_LANGLINKS);
return true;
case R.id.menu_page_find_in_page:
showFindInPage();
return true;
case R.id.menu_page_content_issues:
showContentIssues();
return true;
case R.id.menu_page_similar_titles:
showSimilarTitles();
return true;
case R.id.menu_page_font_and_theme:
getPageActivity().showThemeChooser();
return true;
case R.id.menu_page_show_tabs:
tabsProvider.enterTabMode();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showFindInPage() {
if (model.getPage() == null) {
return;
}
final PageActivity pageActivity = getPageActivity();
final FindInPageFunnel funnel = new FindInPageFunnel(app, model.getTitle().getSite(),
model.getPage().getPageProperties().getPageId());
final FindInPageActionProvider findInPageActionProvider
= new FindInPageActionProvider(pageActivity, funnel);
pageActivity.startSupportActionMode(new ActionMode.Callback() {
private final String actionModeTag = "actionModeFindInPage";
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
findInPageActionMode = mode;
MenuItem menuItem = menu.add(R.string.menu_page_find_in_page);
MenuItemCompat.setActionProvider(menuItem, findInPageActionProvider);
hideToCButton(false);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
mode.setTag(actionModeTag);
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
findInPageActionMode = null;
funnel.setPageHeight(webView.getContentHeight());
funnel.logDone();
webView.clearMatches();
pageActivity.showToolbar();
showToCButton();
hideSoftKeyboard(pageActivity);
}
});
}
public boolean closeFindInPage() {
if (findInPageActionMode != null) {
findInPageActionMode.finish();
return true;
}
return false;
}
/**
* Scroll to a specific section in the WebView.
* @param sectionAnchor Anchor link of the section to scroll to.
*/
public void scrollToSection(String sectionAnchor) {
if (!isAdded() || tocHandler == null) {
return;
}
tocHandler.scrollToSection(sectionAnchor);
}
public void onPageLoadComplete() {
showToCButton();
refreshView.setEnabled(true);
editHandler.setPage(model.getPage());
initPageScrollFunnel();
if (saveOnComplete) {
saveOnComplete = false;
savedPagesFunnel.logUpdate();
savePage();
}
checkAndShowSelectTextOnboarding();
updateNavDrawerSelection();
if (pageLoadCallbacks != null) {
pageLoadCallbacks.onLoadComplete();
}
}
public void commonSectionFetchOnCatch(Throwable caught) {
if (!isAdded()) {
return;
}
// in any case, make sure the TOC drawer is closed
tocDrawer.closeDrawers();
getPageActivity().updateProgressBar(false, true, 0);
refreshView.setRefreshing(false);
if (pageRefreshed) {
pageRefreshed = false;
FeedbackUtil.showError(getActivity(), caught);
}
hidePageContent();
errorView.setError(caught);
errorView.setVisibility(View.VISIBLE);
if (getActivity() != null) {
refreshView.setEnabled(ThrowableUtil.isRetryable(getActivity(), caught));
}
errorState = true;
}
public void savePage() {
if (model.getPage() == null) {
return;
}
FeedbackUtil.showMessage(getActivity(), R.string.snackbar_saving_page);
new SavePageTask(app, model.getTitle(), model.getPage()) {
@Override
public void onFinish(Boolean success) {
if (!isAdded()) {
Log.d("PageFragment", "Detached from activity, no snackbar.");
return;
}
setPageSaved(true);
getPageActivity().showPageSavedMessage(model.getTitle().getDisplayText(), success);
}
}.execute();
// Not technically a refresh but this will prevent needless immediate refreshing
pageRefreshed = true;
}
/**
* Read URL mappings from the saved page specific file
*/
public void readUrlMappings() {
new LoadSavedPageUrlMapTask(model.getTitle()) {
@Override
public void onFinish(JSONObject result) {
// have we been unwittingly detached from our Activity?
if (!isAdded()) {
L.d("Detached from activity, so stopping update.");
return;
}
ImageUrlMap.replaceImageSources(bridge, result);
}
@Override
public void onCatch(Throwable e) {
if (!isAdded()) {
return;
}
/*
If anything bad happens during loading of a saved page, then simply bounce it
back to the online version of the page, and re-save the page contents locally when it's done.
*/
L.d(e);
refreshPage(true);
}
}.execute();
}
public void refreshPage() {
refreshPage(pageSaved);
}
public void refreshPage(boolean saveOnComplete) {
if (pageLoadStrategy.isLoading() || !savedPageCheckComplete) {
refreshView.setRefreshing(false);
return;
}
errorView.setVisibility(View.GONE);
errorState = false;
this.saveOnComplete = saveOnComplete;
if (saveOnComplete) {
FeedbackUtil.showMessage(getActivity(), R.string.snackbar_refresh_saved_page);
}
model.setCurEntry(new HistoryEntry(model.getTitle(), HistoryEntry.SOURCE_HISTORY));
loadPage(model.getTitle(), model.getCurEntry(), PageLoadStrategy.Cache.NONE, false, true);
}
private ToCHandler tocHandler;
public void toggleToC(int action) {
// tocHandler could still be null while the page is loading
if (tocHandler == null) {
return;
}
switch (action) {
case TOC_ACTION_SHOW:
tocHandler.show();
break;
case TOC_ACTION_HIDE:
tocHandler.hide();
break;
case TOC_ACTION_TOGGLE:
if (tocHandler.isVisible()) {
tocHandler.hide();
} else {
tocHandler.show();
}
break;
default:
throw new RuntimeException("Unknown action!");
}
}
public void setupToC(PageViewModel model, boolean isFirstPage) {
tocHandler.setupToC(model.getPage(), model.getTitle().getSite(), isFirstPage);
tocHandler.setEnabled(true);
}
private void updateMenuPageInfo(@NonNull Menu menu) {
MenuItem contentIssues = menu.findItem(R.id.menu_page_content_issues);
MenuItem similarTitles = menu.findItem(R.id.menu_page_similar_titles);
contentIssues.setVisible(pageInfo != null && pageInfo.hasContentIssues());
contentIssues.setEnabled(true);
similarTitles.setVisible(pageInfo != null && pageInfo.hasSimilarTitles());
similarTitles.setEnabled(true);
}
private void showContentIssues() {
showPageInfoDialog().showIssues();
}
private void showSimilarTitles() {
showPageInfoDialog().showDisambig();
}
private PageInfoDialog showPageInfoDialog() {
PageInfoDialog dialog = new PageInfoDialog((PageActivity) getActivity(), pageInfo, pageInfoDialogHeight());
dialog.show();
return dialog;
}
private int pageInfoDialogHeight() {
// could have scrolled up a bit but the page info links must still be visible else they couldn't have been clicked
return webView.getHeight() + webView.getScrollY() - articleHeaderView.getHeight();
}
private void openInNewTab(PageTitle title, HistoryEntry entry, int position) {
if (shouldCreateNewTab()) {
// create a new tab
Tab tab = new Tab();
// if the requested position is at the top, then make its backstack current
if (position == getForegroundTabPosition()) {
pageLoadStrategy.setBackStack(tab.getBackStack());
}
// put this tab in the requested position
tabList.add(position, tab);
// add the requested page to its backstack
tab.getBackStack().add(new PageBackStackItem(title, entry));
} else {
getTopMostTab().getBackStack().add(new PageBackStackItem(title, entry));
}
// and... that should be it.
tabsProvider.showAndHideTabs();
}
private Tab getTopMostTab() {
return tabList.get(tabList.size() - 1);
}
private boolean shouldCreateNewTab() {
return !getTopMostTab().getBackStack().isEmpty();
}
private int getBackgroundTabPosition() {
return Math.max(0, getForegroundTabPosition() - 1);
}
private int getForegroundTabPosition() {
return tabList.size();
}
private void setupMessageHandlers() {
bridge.addListener("ipaSpan", new CommunicationBridge.JSEventListener() {
@Override
public void onMessage(String messageType, JSONObject messagePayload) {
try {
String text = messagePayload.getString("contents");
final int textSize = 30;
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
textView.setText(Html.fromHtml(text));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(textView);
builder.show();
} catch (JSONException e) {
L.logRemoteErrorIfProd(e);
}
}
});
bridge.addListener("imageClicked", new CommunicationBridge.JSEventListener() {
@Override
public void onMessage(String messageType, JSONObject messagePayload) {
try {
String href = decodeURL(messagePayload.getString("href"));
if (href.startsWith("/wiki/")) {
PageTitle imageTitle = model.getTitle().getSite().titleForInternalLink(href);
GalleryActivity.showGallery(getActivity(), model.getTitleOriginal(),
imageTitle, GalleryFunnel.SOURCE_NON_LEAD_IMAGE);
} else {
linkHandler.onUrlClick(href);
}
} catch (JSONException e) {
L.logRemoteErrorIfProd(e);
}
}
});
bridge.addListener("mediaClicked", new CommunicationBridge.JSEventListener() {
@Override
public void onMessage(String messageType, JSONObject messagePayload) {
try {
String href = decodeURL(messagePayload.getString("href"));
GalleryActivity.showGallery(getActivity(), model.getTitleOriginal(),
new PageTitle(href, model.getTitle().getSite()), GalleryFunnel.SOURCE_NON_LEAD_IMAGE);
} catch (JSONException e) {
L.logRemoteErrorIfProd(e);
}
}
});
}
private void showToCButton() {
tocButton.removeCallbacks(hideToCButtonRunnable);
if (!errorState) {
// HACK: there appears to be a bug in FloatingActionButton on API 13+ wherein quickly
// calling show() after hide() fails because show() only works when the View is
// not VISIBLE, which is false for a 200 ms window while the hide animation plays.
// The proper fix seems to be to also check if mIsHiding, which hide() does, and
// to not reset scale and alpha when playing the show animation.
final int floatingActionButtonShowDuration = 200;
tocButton.animate()
.scaleX(1f)
.scaleY(1f)
.alpha(1f)
.setDuration(floatingActionButtonShowDuration)
.setInterpolator(new FastOutSlowInInterpolator());
tocButton.show();
}
}
private void hideToCButton(boolean delay) {
if (delay) {
tocButton.postDelayed(hideToCButtonRunnable, TOC_BUTTON_HIDE_DELAY);
} else {
tocButton.hide();
}
}
/**
* Convenience method for hiding all the content of a page.
*/
private void hidePageContent() {
leadImagesHandler.hide();
searchBarHideHandler.setFadeEnabled(false);
pageLoadStrategy.onHidePageContent();
webView.setVisibility(View.INVISIBLE);
}
@Override
public boolean onBackPressed() {
if (tocHandler != null && tocHandler.isVisible()) {
tocHandler.hide();
return true;
}
if (closeFindInPage()) {
return true;
}
if (pageLoadStrategy.popBackStack()) {
return true;
}
if (tabsProvider.onBackPressed()) {
return true;
}
if (tabList.size() > 1) {
// if we're at the end of the current tab's backstack, then pop the current tab.
tabList.remove(tabList.size() - 1);
}
return false;
}
public LinkHandler getLinkHandler() {
return linkHandler;
}
public void updatePageInfo(@Nullable PageInfo pageInfo) {
this.pageInfo = pageInfo;
if (getActivity() != null) {
getActivity().supportInvalidateOptionsMenu();
}
}
private void checkIfPageIsSaved() {
if (getActivity() != null && getTitle() != null) {
new SavedPageCheckTask(getTitle(), app) {
@Override
public void onFinish(Boolean exists) {
setPageSaved(exists);
setSavedPageCheckComplete(true);
}
}.execute();
}
}
private void checkAndShowSelectTextOnboarding() {
if (app.isFeatureSelectTextAndShareTutorialEnabled()
&& model.getPage().isArticle()
&& app.getOnboardingStateMachine().isSelectTextTutorialEnabled()) {
showSelectTextOnboarding();
}
}
private void showSelectTextOnboarding() {
final View targetView = getView().findViewById(R.id.fragment_page_tool_tip_select_text_target);
targetView.postDelayed(new Runnable() {
@Override
public void run() {
if (getActivity() != null) {
ToolTipUtil.showToolTip(getActivity(),
targetView, R.layout.inflate_tool_tip_select_text,
ToolTip.Position.CENTER);
app.getOnboardingStateMachine().setSelectTextTutorial();
}
}
}, TimeUnit.SECONDS.toMillis(1));
}
private void updateNavDrawerSelection() {
if (isAdded()) {
// TODO: define a Fragment host interface instead of assuming a cast is safe.
((PageActivity) getActivity()).updateNavDrawerSelection(this);
}
}
private void initTabs() {
if (Prefs.hasTabs()) {
tabList.addAll(Prefs.getTabs());
}
if (tabList.isEmpty()) {
tabList.add(new Tab());
}
}
private void sendDecorOffsetMessage() {
JSONObject payload = new JSONObject();
try {
payload.put("offset", getContentTopOffset(getActivity()));
} catch (JSONException e) {
throw new RuntimeException(e);
}
bridge.sendMessage("setDecorOffset", payload);
}
private void initPageScrollFunnel() {
if (model.getPage() != null) {
pageScrollFunnel = new PageScrollFunnel(app, model.getPage().getPageProperties().getPageId());
}
}
private void closePageScrollFunnel() {
if (pageScrollFunnel != null && webView.getContentHeight() > 0) {
pageScrollFunnel.setViewportHeight(webView.getHeight());
pageScrollFunnel.setPageHeight(webView.getContentHeight());
pageScrollFunnel.logDone();
}
pageScrollFunnel = null;
}
// TODO: don't assume host is PageActivity. Use Fragment callbacks pattern.
private PageActivity getPageActivity() {
return (PageActivity) getActivity();
}
@VisibleForTesting
public void setPageLoadCallbacks(@Nullable PageLoadCallbacks pageLoadCallbacks) {
this.pageLoadCallbacks = pageLoadCallbacks;
}
private class LongPressHandler extends PageActivityLongPressHandler
implements PageLongPressHandler.WebViewContextMenuListener {
LongPressHandler(@NonNull PageActivity activity) {
super(activity);
}
@Override
public Site getSite() {
return model.getTitleOriginal().getSite();
}
}
}
|
package org.csstudio.opibuilder.converter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.csstudio.opibuilder.converter.writer.OpiWriter;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
/** RCP command line application for ADL file converter
*
* <p>To use, start product like this:
*
* <code>
* css -nosplash
* -application org.csstudio.opibuilder.converter.edl
* /path/to/file1.edl
* /path/to/file2.edl
* </code>
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class ConverterApplication implements IApplication
{
private List<File> inputFiles = new ArrayList<>();
private Optional<File> outputDirectory = Optional.empty();
private boolean force = false;
private static String renameEdlToOpi(String edlFileName)
{
return edlFileName.endsWith(".edl")
? edlFileName.substring(0, edlFileName.length()-4) + ".opi"
: edlFileName + ".opi";
}
private void usage() {
System.out.println("EDM Converter: convert all .edl files to .opi files at the same location.");
System.out.println("Usage: <converter-cmd> [-h] [-f] [-o <output-dir>] edl-file ...");
System.out.println(" -h: print this help and exit");
System.out.println(" -o <output-dir>: place all converted opi files in output-dir");
System.out.println(" -f: overwrite existing files");
}
private void parseArguments(String[] args) {
for (int i=0; i<args.length; ++i)
{
if (args[i].equals("-h"))
{
usage();
System.exit(0);
}
else if (args[i].equals("-f"))
{
force = true;
}
else if (args[i].equals("-o"))
{
outputDirectory = Optional.of(new File(args[i+1]));
++i;
}
else if (args[i].startsWith("-"))
{
if (i+1 < args.length)
{
System.out.println("Ignoring argument " + args[i] + " " + args[i+1]);
++i;
}
else
System.out.println("Ignoring argument " + args[i]);
}
else
inputFiles.add(new File(args[i]));
}
}
@Override
public Object start(final IApplicationContext context) throws Exception
{
System.out.println("************************");
System.out.println("** EDL File Converter **");
System.out.println("************************");
// Prevent long error message when returning non-zero error code.
System.setProperty(IApplicationContext.EXIT_DATA_PROPERTY, "");
final String args[] =
(String []) context.getArguments().get("application.args");
parseArguments(args);
if (outputDirectory.isPresent() && ! outputDirectory.get().exists())
{
System.out.println("ERROR: Output directory " + outputDirectory.get() + " does not exist.");
return -1;
}
if (inputFiles.isEmpty())
{
System.out.println("ERROR: No input files specified.");
return -1;
}
try
{
if (! checkThenConvert())
return -1;
}
catch (Exception ex)
{
System.out.println("Unexpected error while converting.");
ex.printStackTrace();
return -1;
}
return IApplication.EXIT_OK;
}
private boolean checkThenConvert() throws Exception
{
final List<File> inputs = new ArrayList<>();
final List<File> outputs = new ArrayList<>();
for (File input : inputFiles)
{
File output = null;
if (outputDirectory.isPresent())
{
output = new File(outputDirectory.get(), renameEdlToOpi(input.getName()));
}
else
output = new File(renameEdlToOpi(input.getAbsolutePath()));
if (! input.canRead())
{
System.out.println("ERROR: Cannot read input file " + input);
return false;
}
if (output.exists() && ! force)
{
System.out.println("ERROR: Output file already exists: " + output);
return false;
}
// This can happen if the -o option is selected so all output files
// would be put in the same directory.
if (outputs.contains(output)) {
System.out.println("ERROR: Multiple output files with the path " + output + " would be created.");
return false;
}
inputs.add(input);
outputs.add(output);
}
for (int i=0; i<inputs.size(); ++i)
convert(inputs.get(i), outputs.get(i));
return true;
}
private void convert(final File input, final File output) throws Exception
{
System.out.println("\n** Converting " + input + " into " + output);
OpiWriter writer = OpiWriter.getInstance();
writer.writeDisplayFile(input.getAbsolutePath(),
output.getAbsolutePath());
}
@Override
public void stop()
{
}
}
|
package teammemes.tritonbudget;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Date;
import teammemes.tritonbudget.Menus.Menu;
import teammemes.tritonbudget.db.HistoryDataSource;
import teammemes.tritonbudget.db.MenuDataSource;
import teammemes.tritonbudget.db.TranHistory;
public class Checkout extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
LinearLayout mainLayout;
Toolbar mToolbar;
ActionBarDrawerToggle mToggle;
double total = 0;
private DrawerLayout mDrawerLayout;
private ArrayList<TranHistory> trans;
private float dX;
private float dY;
private int lastAction;
@Override
protected void onCreate(Bundle savedInstanceState) {
User usr = User.getInstance(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_checkout);
//Creates the toolbar to the one defined in nav_action
mToolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Checkout");
//Create the Drawer layout and the toggle
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_checkout_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
//Create the navigationView and add a listener to listen for menu selections
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Get the navigation drawer header and set's the name to user's name
View navHeaderView = navigationView.getHeaderView(0);
TextView usrName = (TextView) navHeaderView.findViewById(R.id.header_name);
usrName.setText(usr.getName());
//Fetches the main empty layout
mainLayout = (LinearLayout) findViewById(R.id.page);
//Uses custom adapter to populate list view
populateCOList();
TextView display_total = (TextView)findViewById(R.id.total_cost);
display_total.setText("Total:\t\t\t$" + double_to_string(total));
}
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.checkout_menu, menu);
return true;
}
private void populateCOList() {
LinearLayout ll = (LinearLayout) findViewById(R.id.Checkout);
ll.setBackgroundResource(R.drawable.border_set_top_bottom);
Intent it = getIntent();
ArrayList<String> transtring = it.getStringArrayListExtra("Transactions");
trans = new ArrayList<>();
ArrayList<String> num = it.getStringArrayListExtra("number");
MenuDataSource data = new MenuDataSource(getApplicationContext());
for (int i = 0; i < transtring.size(); i++) {
Menu men = data.getMenuById(Integer.parseInt(transtring.get(i)));
String menuName = men.getName();
int numItems = Integer.parseInt(num.get(i));
if (numItems > 1){
menuName += " x"+numItems;
}
trans.add(new TranHistory(men.getId(), menuName, numItems, new Date(), men.getCost()*numItems));
String cost = "$" + double_to_string(Math.round(trans.get(i).getCost()*100)/100);
total += (trans.get(i).getCost());
total *= 100;
total = Math.round(total);
total /= 100;
LinearLayout borderll = makeLL();
LinearLayout quantityll = makeLL();
quantityll.setBackgroundResource(0);
quantityll.setGravity(Gravity.RIGHT);
TextView item = new TextView(this);
item.setPadding(8, 8, 8, 8);
item.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
item.setTextSize(20);
String itemName = trans.get(i).getName();
item.setText(itemName);
TextView t = makeTV(cost); //, quantity);
t.setPadding(8,8,8,8);
ll.addView(borderll);
borderll.addView(item);
borderll.addView(quantityll);
quantityll.addView(t);
}
}
private LinearLayout makeLL() {
LinearLayout nestedll = new LinearLayout(this);
nestedll.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
nestedll.setOrientation(LinearLayout.VERTICAL);
nestedll.setBackgroundResource(R.drawable.border_set_top_bottom);
return nestedll;
}
private TextView makeTV(String cost) {
TextView tv = new TextView(this);
tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tv.setText(cost);
tv.setTextSize(20);
return tv;
}
// add button then call this in listener
private boolean change_balance(double bal) {
User usr = User.getInstance(getApplicationContext());
if (usr.getBalance() < bal) {
return false;
}
usr.setBalance(usr.getBalance() - bal);
HistoryDataSource data = new HistoryDataSource(getApplicationContext());
for (int i = 0; i < trans.size(); i++) {
data.createTransaction(trans.get(i));
}
return true;
}
private String double_to_string(double number) {
//Gets the balance from the user
String str = "" + number;
int decimalIdx = str.indexOf('.');
//Edge case, where balance == $XXX.00, it wrongly displays one instance of 0. This fixes it.
if (decimalIdx + 1 == str.length() - 1) {
str = str + "0";
}
return str;
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Gets the id of the item that was selected
int id = item.getItemId();
Intent nextScreen;
//Reacts to the item selected depending on which was pressed
//Creates a new Intent for the new page and starts that activity
switch (id) {
case R.id.nav_home:
mDrawerLayout.closeDrawer(GravityCompat.START);
nextScreen = new Intent(this, HomeScreen.class);
nextScreen.putExtra("FROM", "Checkout");
startActivity(nextScreen);
return true;
case R.id.nav_history:
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
case R.id.nav_statistics:
mDrawerLayout.closeDrawer(GravityCompat.START);
nextScreen = new Intent(this, Statistics.class);
nextScreen.putExtra("FROM", "Checkout");
startActivity(nextScreen);
return true;
case R.id.nav_menus:
mDrawerLayout.closeDrawer(GravityCompat.START);
nextScreen = new Intent(this, DiningHallSelection.class);
nextScreen.putExtra("FROM", "Checkout");
startActivity(nextScreen);
return true;
case R.id.nav_settings:
mDrawerLayout.closeDrawer(GravityCompat.START);
nextScreen = new Intent(this, Settings.class);
nextScreen.putExtra("FROM", "Checkout");
startActivity(nextScreen);
return true;
case R.id.nav_help:
mDrawerLayout.closeDrawer(GravityCompat.START);
nextScreen = new Intent(this, Help.class);
nextScreen.putExtra("FROM", "Checkout");
startActivity(nextScreen);
return true;
default:
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == R.id.confirmBtn){
if (change_balance(total)) {
Intent intent = new Intent(getApplicationContext(), HomeScreen.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Purchased!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "You broke though.", Toast.LENGTH_LONG).show();
}
}
return super.onOptionsItemSelected(item);
}
}
|
package wcdi.wcdiplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class PlayingFragment extends Fragment implements View.OnClickListener{
private String dir_path;
private File dir;
private String[] file_list;
private int play_number = 0;
private MediaPlayer mediaplayer;
private ImageButton pause_b,prev_b,next_b;
public static PlayingFragment newInstance(File param1, String param2) {
PlayingFragment fragment = new PlayingFragment();
Bundle args = new Bundle();
args.putString("PATH", param1.toString());
fragment.setArguments(args);
return fragment;
}
@Override
public void setArguments(Bundle args) {
dir_path = args.getString("PATH") + "/";
dir = new File(dir_path);
file_list = dir.list();
}
public PlayingFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
mediaplayer = new MediaPlayer();
MusicStart();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_playing, container, false);
pause_b = (ImageButton)view.findViewById(R.id.pause_button);
prev_b = (ImageButton)view.findViewById(R.id.prev_button);
next_b = (ImageButton)view.findViewById(R.id.next_button);
pause_b.setOnClickListener(this);
prev_b.setOnClickListener(this);
next_b.setOnClickListener(this);
return view;
}
@Override
public void onClick(View view){
switch (view.getId()) {
case R.id.pause_button:
if (mediaplayer.isPlaying()) {
Log.d(String.valueOf(play_number) + " : " + file_list[play_number],"pause");
mediaplayer.pause();
} else {
Log.d(String.valueOf(play_number) + " : " + file_list[play_number],"start");
mediaplayer.start();
}
break;
case R.id.prev_button:
MusicSet(false);
MusicStart();
break;
case R.id.next_button:
MusicSet(true);
MusicStart();
break;
default:
break;
}
Log.d("Test", "Check");
}
public void MusicStart(){
try {
mediaplayer.setDataSource(dir_path + file_list[play_number]);
mediaplayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaplayer.start();
mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.d("Test", "Check");
MusicSet(true);
MusicStart();
}
});
Log.d(String.valueOf(play_number), file_list[play_number]);
}
public void MusicSet(boolean arrow){
mediaplayer.reset();
if(arrow){
if(play_number >= (file_list.length - 1))play_number = 0;
else{++play_number;}
}else{
if(play_number <= 0)play_number = file_list.length - 1;
else{--play_number;}
}
}
}
|
package com.camnter.newlife;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MockitoTest {
private static final String MOCK_TEXT = "CaMnter";
@Test
@SuppressWarnings("unchecked")
public void testList() {
List mockedList = mock(List.class);
mockedList.add(MOCK_TEXT);
mockedList.clear();
verify(mockedList).add(MOCK_TEXT);
verify(mockedList).clear();
// verify(mockedList).remove(MOCK_TEXT);
}
@Test
public void testStub() {
System.out.println("MockitoTest >>>>>> testStub ");
LinkedList mockedList = mock(LinkedList.class);
// , get(0) , "CaMnter"
when(mockedList.get(0)).thenReturn(MOCK_TEXT);
// , get(1) ,
when(mockedList.get(1)).thenThrow(new RuntimeException("testStub custom exception"));
System.out.println(
"MockitoTest >>>>>> testStub >>>>>> mockedList.get(0) >>>>>>" + mockedList.get(0));
try {
System.out.println(
"MockitoTest >>>>>> testStub >>>>>> mockedList.get(1) >>>>>> " + mockedList.get(1));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(
"MockitoTest >>>>>> testStub >>>>>> mockedList.get(666) >>>>>> " + mockedList.get(666));
}
@Test
public void testArgument() {
System.out.println("MockitoTest >>>>>> testArgument ");
LinkedList mockedList = mock(LinkedList.class);
when(mockedList.get(anyInt())).thenReturn(MOCK_TEXT);
System.out.println(
"MockitoTest >>>>>> testStub >>>>>> mockedList.get(666) >>>>>> " + mockedList.get(666));
}
@SuppressWarnings("unchecked")
@Test
public void testCount() {
LinkedList mockedList = mock(LinkedList.class);
mockedList.add(MOCK_TEXT);
mockedList.add(MOCK_TEXT);
mockedList.add(MOCK_TEXT);
mockedList.add(MOCK_TEXT);
mockedList.add(MOCK_TEXT);
mockedList.add(MOCK_TEXT);
verify(mockedList, times(6)).add(MOCK_TEXT);
verify(mockedList, atLeast(2)).add(MOCK_TEXT);
verify(mockedList, atMost(6)).add(MOCK_TEXT);
verify(mockedList, never()).remove(MOCK_TEXT);
}
}
|
package fr.openwide.core.imports.excel.mapping;
import java.text.Collator;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang3.Validate;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import fr.openwide.core.commons.util.functional.Predicates2;
import fr.openwide.core.imports.excel.event.IExcelImportEventHandler;
import fr.openwide.core.imports.excel.event.exception.ExcelImportContentException;
import fr.openwide.core.imports.excel.event.exception.ExcelImportMappingException;
import fr.openwide.core.imports.excel.location.IExcelImportLocationContext;
import fr.openwide.core.imports.excel.location.IExcelImportNavigator;
import fr.openwide.core.imports.excel.mapping.column.IExcelImportColumnDefinition;
import fr.openwide.core.imports.excel.mapping.column.IExcelImportColumnDefinition.IMappedExcelImportColumnDefinition;
import fr.openwide.core.imports.excel.mapping.column.MappedExcelImportColumnDefinitionImpl;
import fr.openwide.core.imports.excel.mapping.column.builder.AbstractColumnBuilder;
import fr.openwide.core.imports.excel.mapping.column.builder.IExcelImportColumnMapper;
import fr.openwide.core.imports.excel.mapping.column.builder.state.TypeState;
/**
* The central class of this Excel import framework.
* See TestApachePoiExcelImporter for an example on how to use this class.
* @author yrodiere
*/
public abstract class AbstractExcelImportColumnSet<TSheet, TRow, TCell, TCellReference> {
private static final Comparator<? super String> DEFAULT_HEADER_LABEL_COLLATOR;
static {
Collator collator = Collator.getInstance(Locale.ROOT);
collator.setStrength(Collator.IDENTICAL);
DEFAULT_HEADER_LABEL_COLLATOR = Ordering.from(collator).nullsFirst();
}
private final Comparator<? super String> defaultHeaderLabelCollator;
private final AbstractColumnBuilder<TSheet, TRow, TCell, TCellReference> builder;
private final Collection<Column<?>> columns = Lists.newArrayList();
public AbstractExcelImportColumnSet(AbstractColumnBuilder<TSheet, TRow, TCell, TCellReference> builder) {
this(builder, DEFAULT_HEADER_LABEL_COLLATOR);
}
public AbstractExcelImportColumnSet(AbstractColumnBuilder<TSheet, TRow, TCell, TCellReference> builder, Comparator<? super String> defaultHeaderLabelCollator) {
super();
this.builder = builder;
this.defaultHeaderLabelCollator = defaultHeaderLabelCollator;
}
public final TypeState<TSheet, TRow, TCell, TCellReference> withHeader(String headerLabel) {
return withHeader(headerLabel, false);
}
public final TypeState<TSheet, TRow, TCell, TCellReference> withHeader(String headerLabel, Comparator<? super String> collator) {
return withHeader(headerLabel, collator, 0, false);
}
public final TypeState<TSheet, TRow, TCell, TCellReference> withHeader(String headerLabel, boolean optional) {
return withHeader(headerLabel, 0, optional);
}
public final TypeState<TSheet, TRow, TCell, TCellReference> withHeader(String headerLabel, int indexAmongMatchedColumns, boolean optional) {
return withHeader(headerLabel, defaultHeaderLabelCollator, indexAmongMatchedColumns, optional);
}
public final TypeState<TSheet, TRow, TCell, TCellReference> withHeader(String headerLabel, Equivalence<? super String> headerEquivalence, int indexAmongMatchedColumns, boolean optional) {
return builder.withHeader(this, headerLabel, headerEquivalence.equivalentTo(headerLabel), indexAmongMatchedColumns, optional);
}
public final TypeState<TSheet, TRow, TCell, TCellReference> withHeader(String headerLabel, Comparator<? super String> collator, int indexAmongMatchedColumns, boolean optional) {
return builder.withHeader(this, headerLabel, Predicates2.comparesEqualTo(headerLabel, collator), indexAmongMatchedColumns, optional);
}
public final TypeState<TSheet, TRow, TCell, TCellReference> withIndex(int index) {
return builder.withIndex(this, index);
}
/**
* The actual column implementation.
* <p>This class is implemented as an inner class in order to get rid of the <TSheet, TRow, TCellReference, TCell, TValue> generic
* parameters when the client references columns.
*/
public class Column<TValue> implements IExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, TValue> {
private final IExcelImportColumnMapper<TSheet, TRow, TCell, TCellReference> mapper;
private final Function<? super TCell, ? extends TValue> cellToValueFunction;
private final Predicate<? super TValue> mandatoryValuePredicate;
public Column(IExcelImportColumnMapper<TSheet, TRow, TCell, TCellReference> mapper,
Function<? super TCell, ? extends TValue> cellToValueFunction, Predicate<? super TValue> mandatoryValuePredicate) {
super();
this.mapper = mapper;
this.cellToValueFunction = cellToValueFunction;
this.mandatoryValuePredicate = mandatoryValuePredicate;
// Register the new column
AbstractExcelImportColumnSet.this.columns.add(this);
}
@Override
public IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, TValue> map(TSheet sheet, IExcelImportNavigator<TSheet, TRow, TCell, TCellReference> navigator,
IExcelImportEventHandler eventHandler) throws ExcelImportMappingException {
Function<? super TRow, ? extends TCellReference> rowToCellReferenceFunction = mapper.map(sheet, navigator, eventHandler);
return new MappedExcelImportColumnDefinitionImpl<TSheet, TRow, TCell, TCellReference, TValue>(sheet, rowToCellReferenceFunction, navigator, cellToValueFunction, mandatoryValuePredicate);
}
}
public final SheetContext map(TSheet sheet, IExcelImportNavigator<TSheet, TRow, TCell, TCellReference> navigator, IExcelImportEventHandler eventHandler) throws ExcelImportMappingException {
return new SheetContext(sheet, navigator, eventHandler);
}
public final class SheetContext implements IExcelImportLocationContext, Iterable<RowContext> {
private final TSheet sheet;
private final IExcelImportNavigator<TSheet, TRow, TCell, TCellReference> navigator;
private final IExcelImportEventHandler eventHandler;
private final Map<Column<?>, IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, ?>> mappings;
private SheetContext(TSheet sheet, IExcelImportNavigator<TSheet, TRow, TCell, TCellReference> navigator, IExcelImportEventHandler eventHandler)
throws ExcelImportMappingException {
Validate.notNull(sheet);
this.sheet = sheet;
this.navigator = navigator;
this.eventHandler = eventHandler;
Map<Column<?>, IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, ?>> mutableMappings = Maps.newHashMap();
for (Column<?> columnDefinition : columns) {
mutableMappings.put(columnDefinition, columnDefinition.map(sheet, navigator, eventHandler));
}
this.mappings = Collections.unmodifiableMap(mutableMappings);
this.eventHandler.checkNoMappingErrorOccurred();
}
public TSheet getSheet() {
return sheet;
}
@Override
public Iterator<RowContext> iterator() {
return toRowContexts(navigator.rows(sheet));
}
protected Iterator<RowContext> toRowContexts(Iterator<TRow> rows) {
return Iterators.transform(rows, new Function<TRow, RowContext>() {
@Override
public RowContext apply(TRow input) {
return row(input);
}
});
}
public Iterable<RowContext> nonEmptyRows() {
return new Iterable<RowContext>() {
@Override
public Iterator<RowContext> iterator() {
return toRowContexts(navigator.nonEmptyRows(sheet));
}
};
}
@SuppressWarnings("unchecked")
private <TValue> IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, TValue> getMappedColumn(
IExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, TValue> columnDefinition) {
IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, TValue> mappedColumn =
(IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, TValue>) mappings.get(columnDefinition);
if (mappedColumn == null) {
throw new IllegalStateException("Column " + columnDefinition
+ " was not properly registered, hence it has not been mapped. Please use AbstractColumns.add() before using AbstractColumns.newMapping().");
}
return mappedColumn;
}
public RowContext row(TRow row) {
return new RowContext(this, row);
}
public <TValue> CellContext<TValue> cell(TRow row, Column<TValue> columnDefinition) {
return row(row).cell(columnDefinition);
}
@Override
public void error(String message) throws ExcelImportContentException {
eventHandler.error(message, navigator.getLocation(sheet, null, null));
}
public void error(String message, TRow row) throws ExcelImportContentException {
eventHandler.error(message, navigator.getLocation(sheet, row, null));
}
public void error(String message, TRow row, TCellReference cellReference) throws ExcelImportContentException {
eventHandler.error(message, navigator.getLocation(sheet, row, cellReference));
}
}
public final class RowContext implements IExcelImportLocationContext {
private final SheetContext sheetContext;
private final TRow row;
private RowContext(SheetContext sheetContext, TRow row) {
super();
this.sheetContext = sheetContext;
this.row = row;
}
public <TValue> CellContext<TValue> cell(Column<TValue> columnDefinition) {
return new CellContext<>(sheetContext, this, sheetContext.getMappedColumn(columnDefinition));
}
@Override
public void error(String message) throws ExcelImportContentException {
sheetContext.error(message, row);
}
public void error(String message, TCellReference cellReference) throws ExcelImportContentException {
sheetContext.error(message, row, cellReference);
}
}
public final class CellContext<T> implements IExcelImportLocationContext {
private final SheetContext sheetContext;
private final RowContext rowContext;
private final IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, T> mappedColumn;
private CellContext(SheetContext sheetContext, RowContext rowContext, IMappedExcelImportColumnDefinition<TSheet, TRow, TCell, TCellReference, T> mappedColumn) {
super();
this.sheetContext = sheetContext;
this.rowContext = rowContext;
this.mappedColumn = mappedColumn;
}
public T get() {
return mappedColumn.getValue(rowContext.row);
}
public T getMandatory(String error) throws ExcelImportContentException {
T value = mappedColumn.getMandatoryValue(rowContext.row);
if (value == null) {
missingValue(error);
}
return value;
}
public void missingValue(String error) throws ExcelImportContentException {
sheetContext.eventHandler.missingValue(
error,
sheetContext.navigator.getLocation(sheetContext.sheet, rowContext.row, mappedColumn.getCellReference(rowContext.row))
);
}
@Override
public void error(String error) throws ExcelImportContentException {
rowContext.error(error, mappedColumn.getCellReference(rowContext.row));
}
}
}
|
package fr.openwide.core.showcase.core.business.user.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import org.bindgen.Bindable;
import fr.openwide.core.jpa.security.business.person.model.AbstractPersonGroup;
@Entity
@Bindable
public class UserGroup extends AbstractPersonGroup<UserGroup, User> {
private static final long serialVersionUID = 1218812080652289263L;
@ManyToMany(mappedBy = "userGroups")
private List<User> users = new ArrayList<User>();
public UserGroup() {
super();
}
public UserGroup(String name) {
super(name);
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public void addUser(User user) {
if (!users.contains(user)) {
users.add(user);
user.addUserGroup(this);
}
}
public void removeUser(User user) {
if (users.contains(user)) {
users.remove(user);
user.removeUserGroup(this);
}
}
}
|
package org.pentaho.reporting.engine.classic.extensions.datasources.kettle;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.parameters.UnknownParamException;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.RepositoryPluginType;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.repository.RepositoriesMeta;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaDataCombi;
import org.pentaho.reporting.engine.classic.core.DataFactory;
import org.pentaho.reporting.engine.classic.core.DataFactoryContext;
import org.pentaho.reporting.engine.classic.core.DataRow;
import org.pentaho.reporting.engine.classic.core.ParameterMapping;
import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException;
import org.pentaho.reporting.libraries.base.util.ArgumentNullException;
import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.FormulaContext;
import org.pentaho.reporting.libraries.formula.parser.ParseException;
import org.pentaho.reporting.libraries.resourceloader.ResourceKey;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
import javax.swing.table.TableModel;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
public abstract class AbstractKettleTransformationProducer implements KettleTransformationProducer {
private static final long serialVersionUID = -2287953597208384424L;
private String stepName;
private String username;
private String password;
private String repositoryName;
private FormulaArgument[] arguments;
private FormulaParameter[] parameter;
private transient Trans currentlyRunningTransformation;
private boolean stopOnError;
@Deprecated
public AbstractKettleTransformationProducer( final String repositoryName,
final String stepName,
final String username,
final String password,
final String[] definedArgumentNames,
final ParameterMapping[] definedVariableNames ) {
this( repositoryName, stepName, username, password,
FormulaArgument.convert( definedArgumentNames ),
FormulaParameter.convert( definedVariableNames ) );
}
protected AbstractKettleTransformationProducer( final String repositoryName,
final String stepName,
final String username,
final String password,
final FormulaArgument[] definedArgumentNames,
final FormulaParameter[] definedVariableNames ) {
if ( repositoryName == null ) {
throw new NullPointerException();
}
if ( definedArgumentNames == null ) {
throw new NullPointerException();
}
if ( definedVariableNames == null ) {
throw new NullPointerException();
}
this.stopOnError = true;
this.repositoryName = repositoryName;
this.stepName = stepName;
this.username = username;
this.password = password;
this.arguments = definedArgumentNames.clone();
this.parameter = definedVariableNames.clone();
}
public boolean isStopOnError() {
return stopOnError;
}
public void setStopOnError( final boolean stopOnError ) {
this.stopOnError = stopOnError;
}
public String getStepName() {
return stepName;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getRepositoryName() {
return repositoryName;
}
public String[] getDefinedArgumentNames() {
return FormulaArgument.convert( arguments );
}
public ParameterMapping[] getDefinedVariableNames() {
return FormulaParameter.convert( parameter );
}
public FormulaArgument[] getArguments() {
return arguments.clone();
}
public FormulaParameter[] getParameter() {
return parameter.clone();
}
public Object clone() {
try {
final AbstractKettleTransformationProducer prod = (AbstractKettleTransformationProducer) super.clone();
prod.arguments = arguments.clone();
prod.parameter = parameter.clone();
prod.currentlyRunningTransformation = null;
return prod;
} catch ( final CloneNotSupportedException e ) {
throw new IllegalStateException( e );
}
}
public TransMeta loadTransformation( final DataFactoryContext context )
throws KettleException, ReportDataFactoryException {
final Repository repository = connectToRepository();
try {
return loadTransformation( repository, context.getResourceManager(), context.getContextKey() );
} finally {
currentlyRunningTransformation = null;
if ( repository != null ) {
repository.disconnect();
}
}
}
public TableModel queryDesignTimeStructure( final DataRow parameter,
final DataFactoryContext context )
throws ReportDataFactoryException, KettleException {
String stepName = getStepName();
if ( stepName == null ) {
throw new ReportDataFactoryException( "No step name defined." );
}
final Repository repository = connectToRepository();
try {
ResourceManager resourceManager = context.getResourceManager();
final TransMeta transMeta = loadTransformation( repository, resourceManager, context.getContextKey() );
if ( isDynamicTransformation( transMeta ) ) {
// we cannot safely guess columns from transformations that use Metadata-Injection.
// So lets solve them the traditional way.
return performQueryOnTransformation( parameter, 1, context, transMeta );
} else {
prepareTransformation( parameter, context, transMeta );
}
StepMeta step = transMeta.findStep( stepName );
if ( step == null ) {
throw new ReportDataFactoryException( "Cannot find the specified transformation step " + stepName );
}
final RowMetaInterface row = transMeta.getStepFields( getStepName() );
final TableProducer tableProducer = new TableProducer( row, 1, true );
return tableProducer.getTableModel();
} catch ( final EvaluationException e ) {
throw new ReportDataFactoryException( "Failed to evaluate parameter", e );
} catch ( final ParseException e ) {
throw new ReportDataFactoryException( "Failed to evaluate parameter", e );
} finally {
if ( repository != null ) {
repository.disconnect();
}
}
}
private boolean isDynamicTransformation( final TransMeta transMeta ) {
List<StepMeta> steps = transMeta.getSteps();
for ( final StepMeta step : steps ) {
if ( step.isEtlMetaInject() ) {
return true;
}
}
return false;
}
public TableModel performQuery( final DataRow parameters,
final int queryLimit,
final DataFactoryContext context )
throws KettleException, ReportDataFactoryException {
ArgumentNullException.validate( "context", context );
ArgumentNullException.validate( "parameters", parameters );
String targetStepName = getStepName();
if ( targetStepName == null ) {
throw new ReportDataFactoryException( "No step name defined." );
}
final Repository repository = connectToRepository();
try {
final TransMeta transMeta =
loadTransformation( repository, context.getResourceManager(), context.getContextKey() );
return performQueryOnTransformation( parameters, queryLimit, context, transMeta );
} catch ( final EvaluationException e ) {
throw new ReportDataFactoryException( "Failed to evaluate parameter", e );
} catch ( final ParseException e ) {
throw new ReportDataFactoryException( "Failed to evaluate parameter", e );
} finally {
if ( repository != null ) {
repository.disconnect();
}
}
}
protected TableModel performQueryOnTransformation( final DataRow parameters,
final int queryLimit,
final DataFactoryContext context,
final TransMeta transMeta )
throws EvaluationException, ParseException, KettleException, ReportDataFactoryException {
final Trans trans = prepareTransformation( parameters, context, transMeta );
StepInterface targetStep = findTargetStep( trans );
final RowMetaInterface row = transMeta.getStepFields( getStepName() );
TableProducer tableProducer = new TableProducer( row, queryLimit, isStopOnError() );
targetStep.addRowListener( tableProducer );
currentlyRunningTransformation = trans;
try {
trans.startThreads();
trans.waitUntilFinished();
} finally {
trans.cleanup();
currentlyRunningTransformation = null;
}
if ( trans.getErrors() != 0 && isStopOnError() ) {
throw new ReportDataFactoryException( String
.format( "Transformation reported %d records with errors and stop-on-error is true. Aborting.",
trans.getErrors() ) );
}
return tableProducer.getTableModel();
}
private Trans prepareTransformation( final DataRow parameters,
final DataFactoryContext context,
final TransMeta transMeta )
throws EvaluationException, ParseException, KettleException {
final FormulaContext formulaContext = new WrappingFormulaContext( context.getFormulaContext(), parameters );
final String[] params = fillArguments( formulaContext );
final Trans trans = new Trans( transMeta );
trans.setArguments( params );
updateTransformationParameter( formulaContext, trans );
transMeta.setInternalKettleVariables();
trans.prepareExecution( params );
return trans;
}
private StepInterface findTargetStep( final Trans trans ) throws ReportDataFactoryException {
final String stepName = getStepName();
final List<StepMetaDataCombi> stepList = trans.getSteps();
for ( int i = 0; i < stepList.size(); i++ ) {
final StepMetaDataCombi metaDataCombi = stepList.get( i );
if ( stepName.equals( metaDataCombi.stepname ) ) {
return metaDataCombi.step;
}
}
throw new ReportDataFactoryException( "Cannot find the specified transformation step " + stepName );
}
private void updateTransformationParameter( final FormulaContext formulaContext,
final Trans trans )
throws UnknownParamException, EvaluationException, ParseException {
for ( int i = 0; i < this.parameter.length; i++ ) {
final FormulaParameter mapping = this.parameter[ i ];
final String sourceName = mapping.getName();
final Object value = mapping.compute( formulaContext );
TransMeta transMeta = trans.getTransMeta();
if ( value != null ) {
String paramValue = String.valueOf( value );
trans.setParameterValue( sourceName, paramValue );
transMeta.setParameterValue( sourceName, paramValue );
} else {
trans.setParameterValue( sourceName, null );
transMeta.setParameterValue( sourceName, null );
}
trans.setTransMeta( transMeta );
}
}
private String[] fillArguments( final FormulaContext context ) throws EvaluationException, ParseException {
final String[] params = new String[ arguments.length ];
for ( int i = 0; i < arguments.length; i++ ) {
final FormulaArgument arg = arguments[ i ];
Object compute = arg.compute( context );
if ( compute == null ) {
params[ i ] = null;
} else {
params[ i ] = String.valueOf( compute );
}
}
return params;
}
private Repository connectToRepository()
throws ReportDataFactoryException, KettleException {
if ( repositoryName == null ) {
throw new NullPointerException();
}
final RepositoriesMeta repositoriesMeta = new RepositoriesMeta();
try {
repositoriesMeta.readData();
} catch ( final KettleException ke ) {
// we're a bit low to bubble a dialog to the user here..
// when ramaiz fixes readData() to stop throwing exceptions
// even when successful we can remove this and use
// the more favorable repositoriesMeta.getException() or something
// like it (I'm guessing on the method name)
}
// Find the specified repository.
final RepositoryMeta repositoryMeta = repositoriesMeta.findRepository( repositoryName );
if ( repositoryMeta == null ) {
// repository object is not necessary for filesystem transformations
return null;
// throw new ReportDataFactoryException("The specified repository " + repositoryName + " is not defined.");
}
final Repository repository =
PluginRegistry.getInstance().loadClass( RepositoryPluginType.class, repositoryMeta.getId(), Repository.class );
repository.init( repositoryMeta );
repository.connect( username, password );
return repository;
}
protected abstract TransMeta loadTransformation( Repository repository,
ResourceManager resourceManager,
ResourceKey contextKey )
throws ReportDataFactoryException, KettleException;
public void cancelQuery() {
final Trans currentlyRunningTransformation = this.currentlyRunningTransformation;
if ( currentlyRunningTransformation != null ) {
currentlyRunningTransformation.stopAll();
this.currentlyRunningTransformation = null;
}
}
public String[] getReferencedFields() throws ParseException {
final LinkedHashSet<String> retval = new LinkedHashSet<String>();
HashSet<String> args = new HashSet<String>();
for ( final FormulaArgument argument : arguments ) {
args.addAll( Arrays.asList( argument.getReferencedFields() ) );
}
for ( final FormulaParameter formulaParameter : parameter ) {
args.addAll( Arrays.asList( formulaParameter.getReferencedFields() ) );
}
retval.addAll( args );
retval.add( DataFactory.QUERY_LIMIT );
return retval.toArray( new String[ retval.size() ] );
}
protected ArrayList<Object> internalGetQueryHash() {
final ArrayList<Object> retval = new ArrayList<Object>();
retval.add( getClass().getName() );
retval.add( getUsername() );
retval.add( getPassword() );
retval.add( getStepName() );
retval.add( isStopOnError() );
retval.add( getRepositoryName() );
retval.add( new ArrayList<FormulaArgument>( Arrays.asList( getArguments() ) ) );
retval.add( new ArrayList<FormulaParameter>( Arrays.asList( getParameter() ) ) );
return retval;
}
protected String computeFullFilename( ResourceKey key ) {
while ( key != null ) {
final Object identifier = key.getIdentifier();
if ( identifier instanceof File ) {
final File file = (File) identifier;
return file.getAbsolutePath();
}
key = key.getParent();
}
return null;
}
}
|
package org.opennms.features.topology.app.internal.gwt.client;
import static org.opennms.features.topology.app.internal.gwt.client.d3.TransitionBuilder.fadeIn;
import static org.opennms.features.topology.app.internal.gwt.client.d3.TransitionBuilder.fadeOut;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.opennms.features.topology.app.internal.gwt.client.d3.D3;
import org.opennms.features.topology.app.internal.gwt.client.d3.D3Behavior;
import org.opennms.features.topology.app.internal.gwt.client.d3.D3Drag;
import org.opennms.features.topology.app.internal.gwt.client.d3.D3Events;
import org.opennms.features.topology.app.internal.gwt.client.d3.D3Events.Handler;
import org.opennms.features.topology.app.internal.gwt.client.d3.Func;
import org.opennms.features.topology.app.internal.gwt.client.handler.DragHandlerManager;
import org.opennms.features.topology.app.internal.gwt.client.handler.DragObject;
import org.opennms.features.topology.app.internal.gwt.client.handler.MarqueeSelectHandler;
import org.opennms.features.topology.app.internal.gwt.client.handler.PanHandler;
import org.opennms.features.topology.app.internal.gwt.client.map.SVGTopologyMap;
import org.opennms.features.topology.app.internal.gwt.client.svg.SVGElement;
import org.opennms.features.topology.app.internal.gwt.client.svg.SVGGElement;
import org.opennms.features.topology.app.internal.gwt.client.svg.SVGMatrix;
import org.opennms.features.topology.app.internal.gwt.client.svg.SVGPoint;
import org.opennms.features.topology.app.internal.gwt.client.svg.SVGRect;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.TooltipInfo;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.VTooltip;
import com.vaadin.terminal.gwt.client.ui.Action;
import com.vaadin.terminal.gwt.client.ui.ActionOwner;
import com.vaadin.terminal.gwt.client.ui.dd.VDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
public class VTopologyComponent extends Composite implements Paintable, ActionOwner, VHasDropHandler, SVGTopologyMap {
public class GraphDrawerNoTransition extends GraphDrawer{
public GraphDrawerNoTransition(GWTGraph graph, Element vertexGroup,Element edgeGroup, D3Behavior dragBehavior, Handler<GWTVertex> clickHandler, Handler<GWTVertex> contextMenuHandler, Handler<GWTVertex> tooltipHandler, Handler<GWTEdge> edgeContextHandler, Handler<GWTEdge> edgeToolTipHandler) {
super(graph, vertexGroup, edgeGroup, dragBehavior, clickHandler,contextMenuHandler, tooltipHandler, edgeContextHandler, edgeToolTipHandler);
}
@Override
protected D3Behavior enterTransition() {
return new D3Behavior() {
@Override
public D3 run(D3 selection) {
return selection;
}
};
}
@Override
protected D3Behavior exitTransition() {
return new D3Behavior() {
@Override
public D3 run(D3 selection) {
return selection;
}
};
}
@Override
protected D3Behavior updateTransition() {
return new D3Behavior() {
@Override
public D3 run(D3 selection) {
return selection;
}
};
}
}
public class GraphDrawer{
GWTGraph m_graph;
Element m_vertexGroup;
Element m_edgeGroup;
D3Behavior m_dragBehavior;
Handler<GWTVertex> m_clickHandler;
Handler<GWTVertex> m_contextMenuHandler;
private Handler<GWTVertex> m_vertexMouseOverHandler;
private Handler<GWTEdge> m_edgeContextHandler;
private Handler<GWTEdge> m_edgeToolTipHandler;
public GraphDrawer(GWTGraph graph, Element vertexGroup, Element edgeGroup, D3Behavior dragBehavior, Handler<GWTVertex> clickHandler, Handler<GWTVertex> contextMenuHandler, Handler<GWTVertex> tooltipHandler, Handler<GWTEdge> edgeContextHandler, Handler<GWTEdge> edgeToolTipHandler) {
m_graph = graph;
m_vertexGroup = vertexGroup;
m_edgeGroup = edgeGroup;
m_dragBehavior = dragBehavior;
setClickHandler(clickHandler);
setContextMenuHandler(contextMenuHandler);
m_vertexMouseOverHandler = tooltipHandler;
setEdgeContextHandler(edgeContextHandler);
setEdgeToolTipHandler(edgeToolTipHandler);
}
public void updateGraph(GWTGraph graph) {
m_graph = graph;
draw();
}
public Handler<GWTVertex> getClickHandler() {
return m_clickHandler;
}
public void setClickHandler(Handler<GWTVertex> clickHandler) {
m_clickHandler = clickHandler;
}
public Handler<GWTVertex> getContextMenuHandler() {
return m_contextMenuHandler;
}
public void setContextMenuHandler(Handler<GWTVertex> contextMenuHandler) {
m_contextMenuHandler = contextMenuHandler;
}
public GWTGraph getGraph() {
return m_graph;
}
public Element getEdgeGroupElement() {
return m_edgeGroup;
}
public Element getVertexGroupElement() {
return m_vertexGroup;
}
D3 getEdgeGroup() {
return D3.d3().select(getEdgeGroupElement());
}
D3 getVertexGroup() {
return D3.d3().select(getVertexGroupElement());
}
public D3Behavior getDragBehavior() {
return m_dragBehavior;
}
void draw() {
GWTGraph graph = getGraph();
D3 edgeSelection = getEdgeSelection(graph);
D3 vertexSelection = getVertexSelection(graph);
vertexSelection.enter().create(GWTVertex.create()).call(setupEventHandlers())
.attr("transform", new Func<String, GWTVertex>() {
public String call(GWTVertex vertex, int index) {
GWTVertex displayVertex = vertex.getDisplayVertex(m_oldSemanticZoomLevel);
return "translate(" + displayVertex.getX() + "," + displayVertex.getY() + ")";
}
}).attr("opacity", 1);
//Exits
edgeSelection.exit().with(exitTransition()).remove();
vertexSelection.exit().with(new D3Behavior() {
@Override
public D3 run(D3 selection) {
return selection.transition().delay(0).duration(500);
}
}).attr("transform", new Func<String, GWTVertex>(){
public String call(GWTVertex vertex, int index) {
GWTVertex displayVertex = vertex.getDisplayVertex(m_semanticZoomLevel);
return "translate(" + displayVertex.getX() + "," + displayVertex.getY() + ")";
}
}).attr("opacity", 0).remove();
//Updates
edgeSelection.with(updateTransition()).call(GWTEdge.draw()).attr("opacity", 1);
vertexSelection.with(updateTransition()).call(GWTVertex.draw()).attr("opacity", 1);
//Enters
edgeSelection.enter().create(GWTEdge.create()).call(setupEdgeEventHandlers()).with(enterTransition());
//vertexSelection.enter().create(GWTVertex.create()).call(setupEventHandlers()).with(enterTransition());
}
protected D3Behavior enterTransition() {
return fadeIn(500, 1000);
}
protected D3Behavior exitTransition() {
return fadeOut(500, 0);
}
protected D3Behavior updateTransition() {
return new D3Behavior() {
@Override
public D3 run(D3 selection) {
return selection.transition().delay(500).duration(500);
}
};
}
private D3Behavior setupEdgeEventHandlers() {
return new D3Behavior() {
@Override
public D3 run(D3 selection) {
return selection.on(D3Events.CONTEXT_MENU.event(), getEdgeContextHandler())
.on(D3Events.MOUSE_OVER.event(), getEdgeToolTipHandler())
.on(D3Events.MOUSE_OUT.event(), getEdgeToolTipHandler());
}
};
}
private D3Behavior setupEventHandlers() {
return new D3Behavior() {
@Override
public D3 run(D3 selection) {
return selection.on(D3Events.CLICK.event(), getClickHandler())
.on(D3Events.CONTEXT_MENU.event(), getContextMenuHandler())
.on(D3Events.MOUSE_OVER.event(), getVertexTooltipHandler())
.on(D3Events.MOUSE_OUT.event(), getVertexTooltipHandler())
.call(getDragBehavior());
}
};
}
private Handler<GWTVertex> getVertexTooltipHandler(){
return m_vertexMouseOverHandler;
}
private D3 getVertexSelection(GWTGraph graph) {
return getVertexGroup().selectAll(GWTVertex.VERTEX_CLASS_NAME)
.data(graph.getVertices(m_semanticZoomLevel), new Func<String, GWTVertex>() {
public String call(GWTVertex param, int index) {
return "" + param.getId();
}
});
}
private D3 getEdgeSelection(GWTGraph graph) {
return getEdgeGroup().selectAll("line")
.data(graph.getEdges(m_semanticZoomLevel), new Func<String, GWTEdge>() {
public String call(GWTEdge edge, int index) {
String edgeId = edge.getId();
return edgeId;
}
});
}
public Handler<GWTEdge> getEdgeContextHandler() {
return m_edgeContextHandler;
}
public void setEdgeContextHandler(Handler<GWTEdge> edgeClickHandler) {
m_edgeContextHandler = edgeClickHandler;
}
public Handler<GWTEdge> getEdgeToolTipHandler() {
return m_edgeToolTipHandler;
}
public void setEdgeToolTipHandler(Handler<GWTEdge> edgeToolTipHandler) {
m_edgeToolTipHandler = edgeToolTipHandler;
}
}
private static VTopologyComponentUiBinder uiBinder = GWT
.create(VTopologyComponentUiBinder.class);
interface VTopologyComponentUiBinder extends
UiBinder<Widget, VTopologyComponent> {
}
private ApplicationConnection m_client;
private String m_paintableId;
private GWTGraph m_graph;
private double m_scale = 1;
private DragObject m_dragObject;
@UiField
Element m_svg;
@UiField
Element m_svgViewPort;
@UiField
Element m_edgeGroup;
@UiField
Element m_vertexGroup;
@UiField
Element m_scaledMap;
@UiField
Element m_referenceMap;
@UiField
Element m_referenceMapViewport;
@UiField
Element m_referenceMapBorder;
@UiField
Element m_marquee;
@UiField
HorizontalPanel m_toolBarPanel;
private final HashMap<String, String> m_actionMap = new HashMap<String, String>();
private String[] m_actionKeys;
private D3Drag m_d3PanDrag;
private GraphDrawer m_graphDrawer;
private GraphDrawerNoTransition m_graphDrawerNoTransition;
private List<Element> m_selectedElements = new ArrayList<Element>();
private int m_semanticZoomLevel;
private int m_oldSemanticZoomLevel;
private DragHandlerManager m_svgDragHandlerManager;
public VTopologyComponent() {
initWidget(uiBinder.createAndBindUi(this));
m_graph = GWTGraph.create();
}
@Override
protected void onLoad() {
super.onLoad();
sinkEvents(Event.ONCONTEXTMENU | VTooltip.TOOLTIP_EVENTS | Event.ONMOUSEWHEEL);
m_svgDragHandlerManager = new DragHandlerManager();
m_svgDragHandlerManager.addDragBehaviorHandler(PanHandler.DRAG_BEHAVIOR_KEY, new PanHandler(this));
m_svgDragHandlerManager.addDragBehaviorHandler(MarqueeSelectHandler.DRAG_BEHAVIOR_KEY, new MarqueeSelectHandler(this));
m_svgDragHandlerManager.setCurrentDragHandler(PanHandler.DRAG_BEHAVIOR_KEY);
setupDragBehavior(m_svg, m_svgDragHandlerManager);
for(ToggleButton btn : m_svgDragHandlerManager.getDragControlsButtons()) {
m_toolBarPanel.add(btn);
}
D3Behavior dragBehavior = new D3Behavior() {
@Override
public D3 run(D3 selection) {
D3Drag drag = D3.getDragBehavior();
drag.on(D3Events.DRAG_START.event(), vertexDragStartHandler());
drag.on(D3Events.DRAG.event(), vertexDragHandler());
drag.on(D3Events.DRAG_END.event(), vertexDragEndHandler());
selection.call(drag);
return selection;
}
};
m_graphDrawer = new GraphDrawer(m_graph, m_vertexGroup, m_edgeGroup, dragBehavior, vertexClickHandler(), vertexContextMenuHandler(), vertexTooltipHandler(), edgeContextHandler(), edgeToolTipHandler());
m_graphDrawerNoTransition = new GraphDrawerNoTransition(m_graph, m_vertexGroup, m_edgeGroup, dragBehavior, vertexClickHandler(), vertexContextMenuHandler(), vertexTooltipHandler(), edgeContextHandler(), edgeToolTipHandler());
}
private void setupDragBehavior(final Element panElem, final DragHandlerManager handlerManager) {
D3Drag d3Pan = D3.getDragBehavior();
d3Pan.on(D3Events.DRAG_START.event(), new Handler<Element>() {
public void call(Element elem, int index) {
handlerManager.onDragStart(elem);
}
});
d3Pan.on(D3Events.DRAG.event(), new Handler<Element>() {
public void call(Element elem, int index) {
handlerManager.onDrag(elem);
}
});
d3Pan.on(D3Events.DRAG_END.event(), new Handler<Element>() {
public void call(Element elem, int index) {
handlerManager.onDragEnd(elem);
}
});
D3 select = D3.d3().select(panElem);
select.call(d3Pan);
}
private void drawGraph(GWTGraph g, boolean now) {
if(now) {
m_graphDrawerNoTransition.updateGraph(g);
}else {
m_graphDrawer.updateGraph(g);
}
//TODO: working here
SVGRect bbox = getSVGElement().getBBox();
SVGGElement map = m_svgViewPort.cast();
SVGRect mapBbox = map.getBBox();
double referenceScale = 0.4;
int x = bbox.getX();
int y = bbox.getY();
int width = (int) (mapBbox.getWidth() * referenceScale);
int height = (int) (mapBbox.getHeight() * referenceScale);
int viewPortWidth = (int) (m_svg.getOffsetWidth() * referenceScale);
int viewPortHeight = (int) (m_svg.getOffsetHeight() * referenceScale);
m_referenceMapViewport.setAttribute("width", "" + viewPortWidth);
m_referenceMapViewport.setAttribute("height", "" + viewPortHeight);
m_referenceMap.setAttribute("transform", "translate(" + (m_svg.getOffsetWidth() - width) + " " + (m_svg.getOffsetHeight() - height) + ")");
//TODO: Fix this calc
m_scaledMap.setAttribute("viewBox", x + " " + y + " " + mapBbox.getWidth() + " " + mapBbox.getHeight());
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch(DOM.eventGetType(event)) {
case Event.ONCONTEXTMENU:
EventTarget target = event.getEventTarget();
Element svg = this.getElement().getElementsByTagName("svg").getItem(0);
if (target.equals(svg)) {
showContextMenu(null, event.getClientX(), event.getClientY(), "map");
//m_client.getContextMenu().showAt(this, event.getClientX(), event.getClientY());
event.preventDefault();
event.stopPropagation();
}
break;
case Event.ONMOUSEDOWN:
break;
case Event.ONMOUSEWHEEL:
double delta = event.getMouseWheelVelocityY() / 30.0;
double oldScale = m_scale;
final double newScale = oldScale + delta;
final int clientX = event.getClientX();
final int clientY = event.getClientY();
//broken now need to fix it
// Command cmd = new Command() {
// public void execute() {
// m_client.updateVariable(m_paintableId, "mapScale", newScale, false);
// m_client.updateVariable(m_paintableId, "clientX", clientX, false);
// m_client.updateVariable(m_paintableId, "clientY", clientY, false);
// m_client.sendPendingVariableChanges();
// if(BrowserInfo.get().isWebkit()) {
// Scheduler.get().scheduleDeferred(cmd);
// }else {
// cmd.execute();
break;
case Event.ONCLICK:
if(event.getEventTarget().equals(m_svg)) {
deselectVertices();
}
break;
}
}
private void deselectVertices() {
m_client.updateVariable(m_paintableId, "clickedVertex", "", false);
m_client.updateVariable(m_paintableId, "shiftKeyPressed", false, false);
m_client.sendPendingVariableChanges();
}
private Handler<GWTVertex> vertexContextMenuHandler() {
return new D3Events.Handler<GWTVertex>() {
public void call(final GWTVertex vertex, int index) {
ActionOwner owner = new ActionOwner() {
public Action[] getActions() {
return VTopologyComponent.this.getActions(vertex.getId(), vertex.getActionKeys());
}
public ApplicationConnection getClient() {
return VTopologyComponent.this.getClient();
}
public String getPaintableId() {
return VTopologyComponent.this.getPaintableId();
}
};
showContextMenu(vertex.getId(), D3.getEvent().getClientX(), D3.getEvent().getClientY(), "vertex");
//m_client.getContextMenu().showAt(owner, D3.getEvent().getClientX(), D3.getEvent().getClientY());
D3.eventPreventDefault();
}
};
}
private Handler<GWTEdge> edgeContextHandler(){
return new D3Events.Handler<GWTEdge>() {
public void call(final GWTEdge edge, int index) {
ActionOwner owner = new ActionOwner() {
public Action[] getActions() {
return VTopologyComponent.this.getActions(edge.getId(), edge.getActionKeys());
}
public ApplicationConnection getClient() {
return VTopologyComponent.this.getClient();
}
public String getPaintableId() {
return VTopologyComponent.this.getPaintableId();
}
};
showContextMenu(edge.getId(), D3.getEvent().getClientX(), D3.getEvent().getClientY(), "edge");
//m_client.getContextMenu().showAt(owner, D3.getEvent().getClientX(), D3.getEvent().getClientY());
D3.eventPreventDefault();
}
};
}
private Handler<GWTVertex> vertexTooltipHandler() {
return new Handler<GWTVertex>() {
public void call(GWTVertex t, int index) {
if(m_client != null) {
Event event = (Event) D3.getEvent();
m_client.handleTooltipEvent(event, VTopologyComponent.this, t);
event.stopPropagation();
event.preventDefault();
}
}
};
}
private Handler<GWTEdge> edgeToolTipHandler(){
return new Handler<GWTEdge>() {
public void call(GWTEdge edge, int index) {
if(m_client != null) {
Event event = D3.getEvent().cast();
m_client.handleTooltipEvent(event, VTopologyComponent.this, edge);
event.stopPropagation();
event.preventDefault();
}
}
};
}
private final ActionOwner getActionOwner() {
return this;
}
private Handler<GWTVertex> vertexClickHandler() {
return new D3Events.Handler<GWTVertex>(){
public void call(GWTVertex vertex, int index) {
m_client.updateVariable(m_paintableId, "clickedVertex", vertex.getId(), false);
m_client.updateVariable(m_paintableId, "shiftKeyPressed", D3.getEvent().getShiftKey(), false);
m_client.sendPendingVariableChanges();
}
};
}
private Handler<GWTVertex> vertexDragEndHandler() {
return new Handler<GWTVertex>() {
public void call(GWTVertex vertex, int index) {
m_client.updateVariable(m_paintableId, "updatedVertex", "id," + vertex.getId() + "|x," + vertex.getX() + "|y," + vertex.getY() + "|selected,"+ vertex.isSelected(), true);
D3.getEvent().preventDefault();
D3.getEvent().stopPropagation();
}
};
}
private Handler<GWTVertex> vertexDragStartHandler() {
return new Handler<GWTVertex>() {
public void call(GWTVertex vertex, int index) {
NativeEvent event = D3.getEvent();
Element draggableElement = Element.as(event.getEventTarget()).getParentElement();
m_dragObject = new DragObject(VTopologyComponent.this, draggableElement, m_svgViewPort);
D3.getEvent().preventDefault();
D3.getEvent().stopPropagation();
}
};
}
public static final native void eval(JavaScriptObject elem) /*-{
$wnd.console.log($wnd.eval(elem));
}-*/;
public static final native void typeof(Element elem) /*-{
$wnd.console.log("typeof: " + typeof(elem));
}-*/;
private static final native void consoleLog(String message) /*-{
$wnd.console.log(message);
}-*/;
private Handler<GWTVertex> vertexDragHandler() {
return new Handler<GWTVertex>() {
public void call(GWTVertex vertex, int index) {
vertex.setX( m_dragObject.getCurrentX() );
vertex.setY( m_dragObject.getCurrentY() );
m_dragObject.move();
D3.getEvent().preventDefault();
D3.getEvent().stopPropagation();
}
};
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
if(client.updateComponent(this, uidl, true)) {
return;
}
m_client = client;
m_paintableId = uidl.getId();
setScale(uidl.getDoubleAttribute("scale"), uidl.getIntAttribute("clientX"), uidl.getIntAttribute("clientY"));
setSemanticZoomLevel(uidl.getIntAttribute("semanticZoomLevel"));
setActionKeys(uidl.getStringArrayAttribute("backgroundActions"));
UIDL graph = uidl.getChildByTagName("graph");
Iterator<?> children = graph.getChildIterator();
GWTGraph graphConverted = GWTGraph.create();
while(children.hasNext()) {
UIDL child = (UIDL) children.next();
if(child.getTag().equals("group")) {
GWTGroup group = GWTGroup.create(child.getStringAttribute("key"), child.getIntAttribute("x"), child.getIntAttribute("y"));
boolean booleanAttribute = child.getBooleanAttribute("selected");
String[] actionKeys = child.getStringArrayAttribute("actionKeys");
group.setActionKeys(actionKeys);
group.setSelected(booleanAttribute);
group.setIcon(child.getStringAttribute("iconUrl"));
group.setSemanticZoomLevel(child.getIntAttribute("semanticZoomLevel"));
if (child.hasAttribute("label")) {
group.setLabel(child.getStringAttribute("label"));
}
graphConverted.addGroup(group);
if(m_client != null) {
TooltipInfo ttInfo = new TooltipInfo(group.getTooltipText());
m_client.registerTooltip(this, group, ttInfo);
}
}else if(child.getTag().equals("vertex")) {
GWTVertex vertex = GWTVertex.create(child.getStringAttribute("key"), child.getIntAttribute("x"), child.getIntAttribute("y"));
boolean booleanAttribute = child.getBooleanAttribute("selected");
String[] actionKeys = child.getStringArrayAttribute("actionKeys");
vertex.setSemanticZoomLevel(child.getIntAttribute("semanticZoomLevel"));
vertex.setActionKeys(actionKeys);
if(child.hasAttribute("groupKey")) {
String groupKey = child.getStringAttribute("groupKey");
GWTGroup group = graphConverted.getGroup(groupKey);
vertex.setParent(group);
}
vertex.setSelected(booleanAttribute);
vertex.setIcon(client.translateVaadinUri(child.getStringAttribute("iconUrl")));
if (child.hasAttribute("label")) {
vertex.setLabel(child.getStringAttribute("label"));
}
graphConverted.addVertex(vertex);
if(m_client != null) {
TooltipInfo ttInfo = new TooltipInfo(vertex.getTooltipText());
m_client.registerTooltip(this, vertex, ttInfo);
}
}else if(child.getTag().equals("edge")) {
GWTVertex source = graphConverted.findVertexById(child.getStringAttribute("source"));
GWTEdge edge = GWTEdge.create(child.getStringAttribute("key"), source, graphConverted.findVertexById( child.getStringAttribute("target") ));
String[] actionKeys = child.getStringArrayAttribute("actionKeys");
edge.setActionKeys(actionKeys);
graphConverted.addEdge(edge);
if(m_client != null) {
TooltipInfo edgeInfo = new TooltipInfo("Edge: " + edge.getId());
m_client.registerTooltip(this, edge, edgeInfo);
}
}else if(child.getTag().equals("groupParent")) {
String groupKey = child.getStringAttribute("key");
String parentKey = child.getStringAttribute("parentKey");
GWTGroup group = graphConverted.getGroup(groupKey);
GWTGroup parentGroup = graphConverted.getGroup(parentKey);
group.setParent(parentGroup);
}
}
UIDL actions = uidl.getChildByTagName("actions");
if (actions != null) {
updateActionMap(actions);
}
setGraph(graphConverted);
}
private void setSemanticZoomLevel(int level) {
m_oldSemanticZoomLevel = m_semanticZoomLevel;
m_semanticZoomLevel = level;
}
private void updateActionMap(UIDL c) {
final Iterator<?> it = c.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
m_actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
m_actionMap.put(key + "_i", m_client.translateVaadinUri(action
.getStringAttribute("icon")));
} else {
m_actionMap.remove(key + "_i");
}
}
}
private void setActionKeys(String[] actions) {
m_actionKeys = actions;
}
private void setScale(double scale, int clientX, int clientY) {
if(m_scale != scale) {
double oldScale = m_scale;
m_scale = scale;
repaintScale(oldScale, clientX, clientY);
}
}
private void repaintScale(double oldScale, int clientX, int clientY) {
updateScale(oldScale, m_scale, getSVGElement(), clientX, clientY);
}
private void setGraph(GWTGraph graph) {
m_graph = graph;
repaintGraph();
}
private void repaintGraph() {
drawGraph(m_graph, false);
}
public void repaintGraphNow() {
drawGraph(m_graph, true);
}
@Override
public void repaintNow() {
repaintGraphNow();
}
private void updateScale(double oldScale, double newScale) {
SVGElement svg = getSVGElement();
int cx = svg.getClientWidth()/2;
int cy = svg.getClientWidth()/2;
updateScale(oldScale, newScale, svg, cx, cy);
}
private void updateScale(double oldScale, double newScale, SVGElement svg,int cx, int cy) {
double zoomFactor = newScale/oldScale;
// (x in new coord system - x in old coord system)/x coordinate
SVGGElement g = m_svgViewPort.cast();
if(cx == 0 ) {
cx = (int) (Math.ceil(svg.getOffsetWidth() / 2.0) - 1);
}
if(cy == 0) {
cy = (int) (Math.ceil(svg.getOffsetHeight() / 2.0) -1);
}
SVGPoint p = svg.createSVGPoint();
p.setX(cx);
p.setY(cy);
p = p.matrixTransform(g.getCTM().inverse());
SVGMatrix m = svg.createSVGMatrix()
.translate(p.getX(),p.getY())
.scale(zoomFactor)
.translate(-p.getX(), -p.getY());
SVGMatrix ctm = g.getCTM().multiply(m);
consoleLog("zoomFactor: " + zoomFactor + " oldScale: " + oldScale + " newScale:" + newScale);
D3.d3().select(m_svgViewPort).transition().duration(1000).attr("transform", matrixTransform(ctm));
}
private SVGPoint getPoint(int x, int y) {
SVGPoint p = getSVGElement().createSVGPoint();
p.setX(x);
p.setY(y);
return p;
}
@Override
public SVGElement getSVGElement() {
return m_svg.cast();
}
private void setCTM(SVGGElement elem, SVGMatrix matrix) {
elem.setAttribute("transform", matrixTransform(matrix));
}
private String matrixTransform(SVGMatrix matrix) {
return "matrix(" + matrix.getA() +
", " + matrix.getB() +
", " + matrix.getC() +
", " + matrix.getD() +
", " + matrix.getE() +
", " + matrix.getF() + ")";
}
public String[] getActionKeys() {
return m_actionKeys;
}
public Action[] getActions() {
return getActions(null, getActionKeys());
}
public Action[] getActions(String target, String[] actionKeys) {
if(actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for(int i = 0; i < actions.length; i++) {
String actionKey = actionKeys[i];
GraphAction a = new GraphAction(this, target, actionKey);
a.setCaption(m_actionMap.get(actionKey + "_c"));
if (m_actionMap.containsKey(actionKey+"_i")) {
a.setIconUrl(m_actionMap.get(actionKey+"_i"));
}
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return m_client;
}
public String getPaintableId() {
return m_paintableId;
}
public VDropHandler getDropHandler() {
return null;
}
public void showContextMenu(Object target, int x, int y, String type) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("target", target);
map.put("x", x);
map.put("y", y);
map.put("type", type);
m_client.updateVariable(getPaintableId(), "contextMenu", map, true);
}
@Override
public Element getVertexGroup() {
return m_vertexGroup;
}
@Override
public Element getReferenceViewPort() {
return m_referenceMapViewport;
}
@Override
public Element getSVGViewPort() {
return m_svgViewPort;
}
@Override
public void setVertexSelection(List<String> vertIds) {
m_client.updateVariable(getPaintableId(), "marqueeSelection", vertIds.toArray(new String[]{}), false);
m_client.updateVariable(m_paintableId, "shiftKeyPressed", D3.getEvent().getShiftKey(), false);
m_client.sendPendingVariableChanges();
}
@Override
public Element getMarqueeElement() {
return m_marquee;
}
/**
* Returns the D3 selection for all Vertex svg elements
*/
@Override
public D3 selectAllVertexElements() {
return D3.d3().selectAll(GWTVertex.VERTEX_CLASS_NAME);
}
}
|
package io.hawkcd.core.security;
import com.google.common.collect.Lists;
import io.hawkcd.model.User;
import io.hawkcd.model.UserGroup;
import io.hawkcd.services.UserGroupService;
import io.hawkcd.services.UserService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class AuthorizationGrantService {
private static UserGroupService userGroupService = new UserGroupService();
private static UserService userService = new UserService();
public static List<AuthorizationGrant> getUpdatedGrants(String userGroupId, List<AuthorizationGrant> grants) {
List<AuthorizationGrant> updatedGrants = new ArrayList<>();
for (AuthorizationGrant grant : grants) {
if (!grant.isInherited()) {
updatedGrants.add(grant);
}
}
// updatedGrants.addAll(grants);
UserGroup userGroup = null;
if (userGroupId != null) {
userGroup = (UserGroup) userGroupService.getById(userGroupId).getEntity();
}
if (userGroup != null) {
updatedGrants.addAll(userGroup.getPermissions());
}
updatedGrants = filterAuthorizationGrantsForDuplicates(updatedGrants);
updatedGrants = sortAuthorizationGrants(updatedGrants);
return updatedGrants;
}
// public static List<AuthorizationGrant> getUpdatedGrants(String userId) {
// User user = (User) userService.getById(userId).getEntity();
// if (user == null) {
// return null;
// List<AuthorizationGrant> updatedGrants = new ArrayList<>();
// UserGroup userGroup = (UserGroup) userGroupService.getById(user.getUserGroupId()).getEntity();
// if (userGroup != null) {
// updatedGrants = filterAuthorizationGrantsForDuplicates(updatedGrants);
// updatedGrants = sortAuthorizationGrants(updatedGrants);
// return updatedGrants;
public static void refreshUserGrants(Collection<String> userIds) {
for (String userId : userIds) {
User user = (User) userService.getById(userId).getEntity();
if (user == null) {
continue;
}
List<AuthorizationGrant> newGrants = new ArrayList<>();
List<AuthorizationGrant> userGrants = user.getPermissions();
for (AuthorizationGrant grant : userGrants) {
if (!grant.isInherited()) {
newGrants.add(grant);
}
}
if (user.getUserGroupId() != null) {
UserGroup userGroup = (UserGroup) userGroupService.getById(user.getUserGroupId()).getEntity();
if (userGroup != null) {
newGrants.addAll(userGroup.getPermissions());
}
}
newGrants = filterAuthorizationGrantsForDuplicates(newGrants);
newGrants = sortAuthorizationGrants(newGrants);
user.setPermissions(newGrants);
userService.update(user);
}
}
public static List<AuthorizationGrant> sortAuthorizationGrants(List<AuthorizationGrant> grants) {
List<AuthorizationGrant> sortedGrants = grants
.stream()
.sorted(Comparator.comparingInt(g -> g.getPermissionEntity().getPriorityLevel()))
.collect(Collectors.toList());
sortedGrants = Lists.reverse(sortedGrants);
return sortedGrants;
}
public static List<AuthorizationGrant> filterAuthorizationGrantsForDuplicates(List<AuthorizationGrant> grants) {
List<AuthorizationGrant> filteredGrants = new ArrayList<>();
for (AuthorizationGrant grant : grants) {
boolean foundDuplicate = false;
for (AuthorizationGrant filteredGrant : filteredGrants) {
foundDuplicate = grant.isDuplicateWith(filteredGrant);
if (foundDuplicate) {
break;
}
}
if (!foundDuplicate) {
filteredGrants.add(grant);
}
}
return filteredGrants;
}
}
|
package org.eclipse.che.ide.ext.java.client.newsourcefile;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.api.promises.client.Operation;
import org.eclipse.che.api.promises.client.OperationException;
import org.eclipse.che.ide.api.event.FileEvent;
import org.eclipse.che.ide.api.resources.Container;
import org.eclipse.che.ide.api.resources.File;
import org.eclipse.che.ide.api.resources.Folder;
import org.eclipse.che.ide.api.resources.Resource;
import org.eclipse.che.ide.ext.java.client.resource.SourceFolderMarker;
import org.eclipse.che.ide.resource.Path;
import org.eclipse.che.ide.resources.reveal.RevealResourceEvent;
import java.util.Arrays;
import java.util.List;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.eclipse.che.ide.api.event.FileEvent.FileOperation.OPEN;
import static org.eclipse.che.ide.ext.java.client.JavaUtils.checkCompilationUnitName;
import static org.eclipse.che.ide.ext.java.client.JavaUtils.checkPackageName;
import static org.eclipse.che.ide.ext.java.client.JavaUtils.isValidCompilationUnitName;
import static org.eclipse.che.ide.ext.java.client.JavaUtils.isValidPackageName;
import static org.eclipse.che.ide.ext.java.client.newsourcefile.JavaSourceFileType.ANNOTATION;
import static org.eclipse.che.ide.ext.java.client.newsourcefile.JavaSourceFileType.CLASS;
import static org.eclipse.che.ide.ext.java.client.newsourcefile.JavaSourceFileType.ENUM;
import static org.eclipse.che.ide.ext.java.client.newsourcefile.JavaSourceFileType.INTERFACE;
/**
* Presenter for creating Java source file.
*
* @author Artem Zatsarynnyi
*/
@Singleton
public class NewJavaSourceFilePresenter implements NewJavaSourceFileView.ActionDelegate {
private static final String DEFAULT_CONTENT = " {\n}\n";
private final NewJavaSourceFileView view;
private final List<JavaSourceFileType> sourceFileTypes;
private final EventBus eventBus;
private Container parent;
@Inject
public NewJavaSourceFilePresenter(NewJavaSourceFileView view, EventBus eventBus) {
this.eventBus = eventBus;
sourceFileTypes = Arrays.asList(CLASS, INTERFACE, ENUM, ANNOTATION);
this.view = view;
this.view.setDelegate(this);
}
public void showDialog(Container parent) {
this.parent = parent;
view.setTypes(sourceFileTypes); //todo why we need this there?
view.showDialog();
}
@Override
public void onCancelClicked() {
view.close();
}
@Override
public void onNameChanged() {
try {
final String fileNameWithExtension = getFileNameWithExtension(view.getName());
if (!fileNameWithExtension.trim().isEmpty()) {
checkCompilationUnitName(fileNameWithExtension);
}
final String packageName = getPackageFragment(view.getName());
if (!packageName.trim().isEmpty()) {
checkPackageName(packageName);
}
view.hideErrorHint();
} catch (IllegalStateException e) {
view.showErrorHint(e.getMessage());
}
}
@Override
public void onOkClicked() {
final String fileNameWithExtension = getFileNameWithExtension(view.getName());
final String fileNameWithoutExtension = fileNameWithExtension.substring(0, fileNameWithExtension.lastIndexOf(".java"));
final String packageFragment = getPackageFragment(view.getName());
if (!packageFragment.isEmpty() && !isValidPackageName(packageFragment)) {
return;
}
if (isValidCompilationUnitName(fileNameWithExtension)) {
view.close();
switch (view.getSelectedType()) {
case CLASS:
createClass(fileNameWithoutExtension, packageFragment);
break;
case INTERFACE:
createInterface(fileNameWithoutExtension, packageFragment);
break;
case ENUM:
createEnum(fileNameWithoutExtension, packageFragment);
break;
case ANNOTATION:
createAnnotation(fileNameWithoutExtension, packageFragment);
break;
}
}
}
private String getFileNameWithExtension(String name) {
if (name.endsWith(".java")) {
name = name.substring(0, name.lastIndexOf(".java"));
}
final int lastDotPos = name.lastIndexOf('.');
name = name.substring(lastDotPos + 1);
return name + ".java";
}
private String getPackageFragment(String name) {
if (name.endsWith(".java")) {
name = name.substring(0, name.lastIndexOf(".java"));
}
final int lastDotPos = name.lastIndexOf('.');
if (lastDotPos >= 0) {
return name.substring(0, lastDotPos);
}
return "";
}
private void createClass(String name, String packageFragment) {
String content = getPackageQualifier(packageFragment) +
"public class " + name + DEFAULT_CONTENT;
createSourceFile(name, packageFragment, content);
}
private void createInterface(String name, String packageFragment) {
String content = getPackageQualifier(packageFragment) +
"public interface " + name + DEFAULT_CONTENT;
createSourceFile(name, packageFragment, content);
}
private void createEnum(String name, String packageFragment) {
String content = getPackageQualifier(packageFragment) +
"public enum " + name + DEFAULT_CONTENT;
createSourceFile(name, packageFragment, content);
}
private void createAnnotation(String name, String packageFragment) {
String content = getPackageQualifier(packageFragment) +
"public @interface " + name + DEFAULT_CONTENT;
createSourceFile(name, packageFragment, content);
}
private String getPackageQualifier(String packageFragment) {
final Optional<Resource> srcFolder = parent.getParentWithMarker(SourceFolderMarker.ID);
if (!srcFolder.isPresent() && isNullOrEmpty(packageFragment)) {
return "\n";
}
final Path path = parent.getLocation().removeFirstSegments(srcFolder.get().getLocation().segmentCount());
String packageFQN = path.toString().replace('/', '.');
if (!packageFragment.isEmpty()) {
packageFQN = packageFQN.isEmpty() ? packageFragment : packageFQN + '.' + packageFragment;
}
if (!packageFQN.isEmpty()) {
return "package " + packageFQN + ";\n\n";
} else {
return "\n";
}
}
private void createSourceFile(final String nameWithoutExtension, String packageFragment, final String content) {
if (!isNullOrEmpty(packageFragment)) {
parent.newFolder(packageFragment.replace('.', '/')).then(new Operation<Folder>() {
@Override
public void apply(Folder pkg) throws OperationException {
pkg.newFile(nameWithoutExtension + ".java", content).then(new Operation<File>() {
@Override
public void apply(File file) throws OperationException {
eventBus.fireEvent(new FileEvent(file, OPEN));
eventBus.fireEvent(new RevealResourceEvent(file));
}
});
}
});
} else {
parent.newFile(nameWithoutExtension + ".java", content).then(new Operation<File>() {
@Override
public void apply(File file) throws OperationException {
eventBus.fireEvent(new FileEvent(file, OPEN));
eventBus.fireEvent(new RevealResourceEvent(file));
}
});
}
}
}
|
package caris.framework.utilities;
import java.util.ArrayList;
public class TokenUtilities {
public static char[] punctuation = new char[] {
'.',
',',
'!',
'?',
';',
'@',
};
public static ArrayList<String> parseTokens(String line) {
ArrayList<String> tokens = new ArrayList<String>();
while( line.contains(" ") ) {
line = line.replace(" ", " ");
}
while( line.contains("") ) {
line = line.replace("", "\"");
}
while( line.contains("") ) {
line = line.replace("", "\"");
}
line += " ";
char[] charArray = line.toCharArray();
String temp = "";
boolean openQuote = false;
boolean border = false;
for( char c : charArray ) {
if( c == ' ' && !openQuote && temp.length() > 0 || c == '\n' && !openQuote && temp.length() > 0 ) {
tokens.add(temp);
temp = "";
border = false;
} else if( c == '"' ) {
if( openQuote ) {
openQuote = false;
if( temp.length() > 0 ) {
tokens.add(temp);
}
temp = "";
border = true;
} else {
openQuote = true;
}
} else {
if( !border ) {
boolean valid = true;
for( char p : punctuation ) {
if( c == p ) {
valid = false;
break;
}
}
if( valid || openQuote ) {
temp += c;
}
}
border = false;
}
}
return tokens;
}
public static ArrayList<String> parseTokens(String line, char[] punctList) {
ArrayList<String> tokens = new ArrayList<String>();
line += " ";
while( line.contains(" ") ) {
line = line.replace(" ", " ");
}
char[] charArray = line.toCharArray();
String temp = "";
boolean openQuote = false;
boolean border = false;
for( char c : charArray ) {
if( c == ' ' && !openQuote && temp.length() > 0 ) {
tokens.add(temp);
temp = "";
border = false;
} else if( c == '"' ) {
if( openQuote ) {
openQuote = false;
if( temp.length() > 0 ) {
tokens.add(temp);
}
temp = "";
border = true;
} else {
openQuote = true;
}
} else {
if( !border ) {
boolean valid = true;
for( char p : punctList ) {
if( c == p ) {
valid = false;
break;
}
}
if( valid || openQuote ) {
temp += c;
}
}
border = false;
}
}
return tokens;
}
public static ArrayList<String> parseQuoted(String line) {
ArrayList<String> tokens = new ArrayList<String>();
line += " ";
while( line.contains("") ) {
line = line.replace("", "\"");
}
while( line.contains("") ) {
line = line.replace("", "\"");
}
while( line.contains("\"") ) {
int indexA = line.indexOf('\"');
line = line.substring(indexA+1);
int indexB = line.indexOf('\"');
if( indexB != -1 && indexB != 0 ) {
String token = line.substring(0, indexB);
tokens.add(token);
line = line.substring(indexB+1);
} else {
break;
}
}
return tokens;
}
public static ArrayList<Integer> parseNumbers(String line) {
ArrayList<Integer> tokens = new ArrayList<Integer>();
ArrayList<String> stringTokens = parseTokens(line);
for( String s : stringTokens ) {
try {
tokens.add(Integer.parseInt(s));
} catch(NumberFormatException e) {}
}
return tokens;
}
}
|
package cc.hughes.droidchatty;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
public class ThreadListFragment extends ListFragment
{
private boolean _dualPane;
ThreadLoadingAdapter _adapter;
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
_adapter = new ThreadLoadingAdapter(getActivity(), new ArrayList<Thread>());
setListAdapter(_adapter);
View singleThread = getActivity().findViewById(R.id.singleThread);
_dualPane = singleThread != null && singleThread.getVisibility() == View.VISIBLE;
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setHasOptionsMenu(true);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id)
{
showDetails(position);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.main_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.refresh:
refreshThreads();
return true;
case R.id.add:
post();
return true;
case R.id.settings:
showSettings();
return true;
case R.id.search:
showSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void refreshThreads()
{
getListView().clearChoices();
_adapter.clear();
}
private static final int POST_THREAD = 0;
private void post()
{
Intent i = new Intent(getActivity(), ComposePostView.class);
startActivityForResult(i, POST_THREAD);
}
private void showSettings()
{
Intent i = new Intent(getActivity(), PreferenceView.class);
startActivity(i);
}
private void showSearch()
{
Intent i = new Intent(getActivity(), SearchView.class);
startActivity(i);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case POST_THREAD:
if (resultCode == Activity.RESULT_OK)
{
// read the resulting thread id from the post
int postId = data.getExtras().getInt("postId");
// hey, thats the same thing I just wrote!
Intent i = new Intent(getActivity(), SingleThreadView.class);
i.putExtra("postId", postId);
startActivity(i);
}
break;
default:
break;
}
}
void showDetails(int index)
{
Thread thread = _adapter.getItem(index);
getListView().setItemChecked(index, true);
if (_dualPane)
{
ThreadViewFragment view = (ThreadViewFragment)getFragmentManager().findFragmentById(R.id.singleThread);
if (view == null || view.getPostId() != thread.getThreadId())
{
view = ThreadViewFragment.newInstance(thread.getThreadId(), thread.getUserName(), thread.getPosted(), thread.getContent(), thread.getModeration());
getFragmentManager().beginTransaction().replace(R.id.singleThread, view).commit();
}
}
else
{
Intent intent = new Intent();
intent.setClass(getActivity(), SingleThreadView.class);
intent.putExtra("postId", thread.getThreadId());
intent.putExtra("userName", thread.getUserName());
intent.putExtra("posted", thread.getPosted());
intent.putExtra("content", thread.getContent());
intent.putExtra("moderation", thread.getModeration());
startActivity(intent);
}
}
private void updatePostCounts(ArrayList<Thread> threads)
{
// set the number of replies that are new
Hashtable<Integer, Integer> counts = getPostCounts();
for (Thread t : threads)
{
if (counts.containsKey(t.getThreadId()))
t.setReplyCountPrevious(counts.get(t.getThreadId()));
}
try
{
storePostCounts(counts, threads);
} catch (IOException e)
{
// yeah, who cares
Log.e("ThreadView", "Error storing post counts.", e);
}
}
private Hashtable<Integer, Integer> getPostCounts()
{
Hashtable<Integer, Integer> counts = new Hashtable<Integer, Integer>();
if (getActivity().getFileStreamPath("post_count.cache").exists())
{
// look at that, we got a file
try {
FileInputStream input = getActivity().openFileInput("post_count.cache");
try
{
DataInputStream in = new DataInputStream(input);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
while (line != null)
{
if (line.length() > 0)
{
String[] parts = line.split("=");
counts.put(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
}
line = reader.readLine();
}
}
finally
{
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return counts;
}
final static int POST_CACHE_HISTORY = 1000;
private void storePostCounts(Hashtable<Integer, Integer> counts, ArrayList<Thread> threads) throws IOException
{
// update post counts for threads viewing right now
for (Thread t : threads)
counts.put(t.getThreadId(), t.getReplyCount());
List<Integer> postIds = Collections.list(counts.keys());
Collections.sort(postIds);
// trim to last 1000 posts
if (postIds.size() > POST_CACHE_HISTORY)
postIds.subList(postIds.size() - POST_CACHE_HISTORY, postIds.size() - 1);
FileOutputStream output = getActivity().openFileOutput("post_count.cache", Activity.MODE_PRIVATE);
try
{
DataOutputStream out = new DataOutputStream(output);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
for (Integer postId : postIds)
{
writer.write(postId + "=" + counts.get(postId));
writer.newLine();
}
writer.flush();
}
finally
{
output.close();
}
}
private class ThreadLoadingAdapter extends LoadingAdapter<Thread>
{
private int _pageNumber = 0;
public ThreadLoadingAdapter(Context context, ArrayList<Thread> items)
{
super(context, R.layout.row, R.layout.row_loading, items);
}
@Override
public void clear()
{
_pageNumber = 0;
super.clear();
}
@Override
protected View createView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = (ViewHolder)convertView.getTag();
if (holder == null)
{
holder = new ViewHolder();
holder.moderation = (View)convertView.findViewById(R.id.threadModeration);
holder.userName = (TextView)convertView.findViewById(R.id.textUserName);
holder.content = (TextView)convertView.findViewById(R.id.textContent);
holder.posted = (TextView)convertView.findViewById(R.id.textPostedTime);
holder.replyCount = (TextView)convertView.findViewById(R.id.textReplyCount);
holder.defaultTimeColor = holder.posted.getTextColors().getDefaultColor();
convertView.setTag(holder);
}
// get the thread to display and populate all the data into the layout
Thread t = getItem(position);
holder.userName.setText(t.getUserName());
holder.content.setText(t.getPreview());
holder.posted.setText(t.getPosted());
holder.replyCount.setText(formatReplyCount(t));
// special highlight for shacknews posts, hopefully the thread_selector color thing will
// reset the background to transparent when scrolling
if (t.getUserName().equalsIgnoreCase("Shacknews"))
convertView.setBackgroundColor(getResources().getColor(R.color.news_post_background));
else
convertView.setBackgroundResource(R.color.thread_selector);
if (t.getModeration().equalsIgnoreCase("nws"))
holder.moderation.setBackgroundColor(Color.RED);
else
holder.moderation.setBackgroundColor(Color.TRANSPARENT);
if (t.getReplied())
holder.posted.setTextColor(getResources().getColor(R.color.user_paricipated));
else
holder.posted.setTextColor(holder.defaultTimeColor);
// special highlight for employee and mod names
holder.userName.setTextColor(User.getColor(t.getUserName()));
return convertView;
}
private Spanned formatReplyCount(Thread thread)
{
String first = "(" + thread.getReplyCount();
String second = "";
String third = ")";
if (thread.getReplyCount() > thread.getReplyCountPrevious())
{
int new_replies = thread.getReplyCount() - thread.getReplyCountPrevious();
second = " +" + new_replies;
}
SpannableString formatted = new SpannableString(first + second + third);
if (second.length() > 0)
formatted.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.new_post_count)), first.length(), first.length() + second.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return formatted;
}
@Override
protected ArrayList<Thread> loadData() throws Exception
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ThreadListFragment.this.getActivity());
String userName = prefs.getString("userName", "");
// grab threads from the api
ArrayList<Thread> new_threads = ShackApi.getThreads(_pageNumber + 1, userName);
_pageNumber++;
// update the "new" post counts
updatePostCounts(new_threads);
return new_threads;
}
private class ViewHolder
{
View moderation;
TextView userName;
TextView content;
TextView posted;
TextView replyCount;
int defaultTimeColor;
}
}
}
|
package ch.unizh.ini.tobi.rccar;
import ch.unizh.ini.caviar.chip.*;
import ch.unizh.ini.caviar.event.*;
import ch.unizh.ini.caviar.eventprocessing.EventFilter2D;
import ch.unizh.ini.caviar.graphics.FrameAnnotater;
import java.awt.Graphics2D;
import java.util.*;
import java.util.prefs.*;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.*;
/**
* @author chbraen
*/
public class PerspecTransform extends EventFilter2D implements FrameAnnotater, Observer {
public boolean isGeneratingFilter(){ return false;}
private int horizon=getPrefs().getInt("PerspecTransform.horizon",90);
{setPropertyTooltip("horizon","the height of the horizon (in pixles)");}
private float horizonFactor=getPrefs().getFloat("PerspecTransform.horizonFactor",0);
{setPropertyTooltip("horizonFactor","the curvature of the horizon");}
private float ratio=getPrefs().getFloat("PerspecTransform.ratio",0.5f);
{setPropertyTooltip("ratio","The ratio of the horizon to the with at the lower end of the picture");}
private boolean lensEnabled=getPrefs().getBoolean("PerspecTransform.lensEnabled",false);
{setPropertyTooltip("lenseEnabled","should the distortion of the lens be respected");}
private float k1=getPrefs().getFloat("PerspecTransform.k1",0.001f);
{setPropertyTooltip("k1","lense distortion coefficent 1");}
private int[][] dx;
private int[][] dy;
private boolean[][] pass;
private int sx;
private float horizonFactorB;
private int mx;
private int sy;
private int my;
private float factor;
private float alpha;
private float r;
private float ro;
public PerspecTransform(AEChip chip){
super(chip);
resetFilter();
chip.getCanvas().addAnnotator(this);
}
synchronized public EventPacket filterPacket(EventPacket in) {
if(in==null) return null;
if(!filterEnabled) return in;
if(dx == null) {
resetFilter();
return in;
}
if(enclosedFilter!=null) in=enclosedFilter.filterPacket(in);
// filter
int n=in.getSize();
if(n==0) return in;
checkOutputPacketEventType(in);
OutputEventIterator outItr=out.outputIterator();
// for each event only write it to the tmp buffers if it matches
for(Object obj:in){
TypedEvent e=(TypedEvent)obj;
TypedEvent o=(TypedEvent)outItr.nextOutput();
if(pass[e.x][e.y]){
o.copyFrom(e);
o.setX((short)(e.x+dx[e.x][e.y]));
o.setY((short)(e.y+dy[e.x][e.y]));
}
}
return out;
}
public Object getFilterState() {
return null;
}
synchronized public void resetFilter() {
if(chip == null) return;
sx = chip.getSizeX();
mx = sx/2;
sy = chip.getSizeY();
my = sy/2;
dx = new int[sx][sy];
dy = new int[sx][sy];
pass = new boolean[sx][sy];
buildMatrix();
}
public void initFilter() {
resetFilter();
}
private void buildMatrix(){
//the pass matrix has to be set up
//the horizon is described by a hyperbole with y=horizonFactorB*x^2 + horizonFactor
horizonFactorB=-horizonFactor/(mx*mx);
for(int y=0; y<sy; y++){
for(int x=0; x<sx; x++){
if(y<horizon || ((y-horizon)<horizonFactorB*(x-mx)*(x-mx)+horizonFactor)) pass[x][y] = true;
else pass[x][y] = false;
}
}
//the transformation matrix has to be calculated
for(int y=0; y<sy; y++){
factor = (1-ratio)*((float)horizon - (float)y)/(float)horizon;
for(int x=0; x<sx; x++){
if(x!=mx){
alpha = (float)Math.atan(Math.abs(((float)my-(float)y)/((float)mx-(float)x)));
} else {
alpha = (float)(Math.signum(x)*Math.PI/2);
}
ro = (float)Math.sqrt((mx-x)*(mx-x)+(my-y)*(my-y));
if(lensEnabled){
r = lenseTransform(ro);
dx[x][y] = (int)((r/ro)*Math.cos(alpha)*Math.signum(mx-x));
dy[x][y] = (int)((r/ro)*Math.sin(alpha)*Math.signum(my-y));
} else {
dx[x][y]=0;
dy[x][y]=0;
}
dx[x][y] = dx[x][y] + (short)((float)(mx-x)*factor);
}
}
//-->uncomment to see the transformation matrix
/*for(int y=horizon-1; y>=0; y--){
for(int x=0; x<sx; x++){
System.out.print(dx[x][y] + " ");
}
System.out.println();
}*/
}
private float lenseTransform(float r){
return (float)(r*(1+(k1*(r*r))));
}
public int getHorizon() {
return horizon;
}
public void setHorizon(int horizon) {
this.horizon = horizon;
getPrefs().putInt("PerspecTransform.horizon",horizon);
resetFilter();
}
public float getRatio() {
return ratio;
}
public void setRatio(float ratio) {
this.ratio = ratio;
getPrefs().putFloat("PerspecTransform.ratio",ratio);
resetFilter();
}
public float getHorizonFactor() {
return horizonFactor;
}
public void setHorizonFactor(float horizonFactor) {
this.horizonFactor = horizonFactor;
getPrefs().putFloat("PerspecTransform.horizonFactor",horizonFactor);
resetFilter();
}
public boolean isLensEnabled() {
return lensEnabled;
}
public void setLensEnabled(boolean lensEnabled) {
this.lensEnabled = lensEnabled;
getPrefs().putBoolean("PerspecTransform.lensEnabled",lensEnabled);
resetFilter();
}
public float getK1() {
return k1;
}
public void setK1(float k1) {
this.k1 = k1;
getPrefs().putFloat("PerspecTransform.k1",k1);
resetFilter();
}
public void annotate(float[][][] frame) {
}
public void annotate(Graphics2D g) {
}
public void annotate(GLAutoDrawable drawable) {
if(!isAnnotationEnabled() || !isFilterEnabled()) return;
if(!isFilterEnabled()) return;
GL gl=drawable.getGL();
gl.glPushMatrix();
{
}
gl.glPopMatrix();
}
public void update(Observable o, Object arg) {
chip.getCanvas().addAnnotator(this);
}
}
|
package integratedtoolkit.scheduler.loadBalancingScheduler;
import integratedtoolkit.scheduler.readyScheduler.ReadyResourceScheduler;
import integratedtoolkit.scheduler.types.AllocatableAction;
import integratedtoolkit.scheduler.types.LoadBalancingScore;
import integratedtoolkit.scheduler.types.Profile;
import integratedtoolkit.scheduler.types.Score;
import integratedtoolkit.types.TaskDescription;
import integratedtoolkit.types.resources.Worker;
import integratedtoolkit.types.resources.WorkerResourceDescription;
import integratedtoolkit.types.implementations.Implementation;
public class LoadBalancingResourceScheduler<P extends Profile, T extends WorkerResourceDescription, I extends Implementation<T>>
extends ReadyResourceScheduler<P, T, I> {
/**
* New ready resource scheduler instance
*
* @param w
*/
public LoadBalancingResourceScheduler(Worker<T, I> w) {
super(w);
}
@Override
public Score generateBlockedScore(AllocatableAction<P, T, I> action) {
// LOGGER.debug("[ResourceEmptyScheduler] Generate blocked score for action " + action);
double actionPriority = action.getPriority();
double waitingScore = 2.0;
if (this.blocked.size() > 0) {
waitingScore = (double) (1.0 / (double) this.blocked.size());
}
double resourceScore = 0;
double implementationScore = 0;
return new LoadBalancingScore(actionPriority, waitingScore, resourceScore, implementationScore);
}
@Override
public Score generateResourceScore(AllocatableAction<P, T, I> action, TaskDescription params, Score actionScore) {
// LOGGER.debug("[ResourceEmptyScheduler] Generate resource score for action " + action);
// Gets the action priority
double actionPriority = actionScore.getActionScore();
// Computes the resource waiting score
double waitingScore = 2.0;
if (this.blocked.size() > 0) {
waitingScore = (double) (1.0 / (double) this.blocked.size());
}
// Computes the priority of the resource
double resourceScore = LoadBalancingScore.calculateScore(params, this.myWorker);
// Computes the priority of the implementation (should not be computed)
double implementationScore = 0;
LoadBalancingScore score = new LoadBalancingScore(actionPriority, waitingScore, resourceScore, implementationScore);
// LOGGER.debug(score);
return score;
}
@Override
public Score generateImplementationScore(AllocatableAction<P, T, I> action, TaskDescription params, I impl, Score resourceScore) {
// LOGGER.debug("[ResourceScheduler] Generate implementation score for action " + action);
if (myWorker.canRunNow(impl.getRequirements())) {
double actionPriority = resourceScore.getActionScore();
double waitingScore = resourceScore.getWaitingScore();
double resourcePriority = resourceScore.getResourceScore();
double implScore = 1.0 / ((double) this.getProfile(impl).getAverageExecutionTime());
LoadBalancingScore score = new LoadBalancingScore(actionPriority, waitingScore, resourcePriority, implScore);
// LOGGER.debug(score);
return score;
} else {
// Implementation cannot be run
// LOGGER.debug("ResourceEmtpyScore evaluated to null");
return null;
}
}
@Override
public String toString() {
return "ResourceEmptyResourceScheduler@" + getName();
}
}
|
package com.arcologydesigns.io_operations;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileIO {
private String fileName;
private String path;
private boolean appendToFile;
public FileIO(String filePath) {
path = filePath;
}
public FileIO(String filePath, boolean appendValue) {
path = filePath;
appendToFile = appendValue;
}
public void WriteOperation(String textLine) throws IOException {
FileWriter writer = new FileWriter(path, appendToFile);
PrintWriter printWriter = new PrintWriter(writer);
printWriter.printf("%s" + "%n", textLine);
printWriter.close();
}
public String ReadOneLine() throws IOException {
FileReader fileReader = new FileReader(path);
BufferedReader lineReader = new BufferedReader(fileReader);
String fileData;
lineReader.readLine(); // temporary code to skip first line containing headers
fileData = lineReader.readLine();
System.out.print("1st line: " + fileData + "\n");
lineReader.close();
return fileData;
}
public String ReadAll() throws IOException {
return "";
}
}
|
package com.braintreegateway;
/**
* An Enum representing all of the validation errors from the gateway.
*/
public enum ValidationErrorCode {
ADDRESS_CANNOT_BE_BLANK("81801"),
ADDRESS_COMPANY_IS_TOO_LONG("81802"),
ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED("91814"),
ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED("91816"),
ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED("91817"),
ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED("91803"),
ADDRESS_EXTENDED_ADDRESS_IS_TOO_LONG("81804"),
ADDRESS_FIRST_NAME_IS_TOO_LONG("81805"),
ADDRESS_INCONSISTENT_COUNTRY("91815"),
ADDRESS_LAST_NAME_IS_TOO_LONG("81806"),
ADDRESS_LOCALITY_IS_TOO_LONG("81807"),
ADDRESS_POSTAL_CODE_INVALID_CHARACTERS("81813"),
ADDRESS_POSTAL_CODE_IS_REQUIRED("81808"),
ADDRESS_POSTAL_CODE_IS_TOO_LONG("81809"),
ADDRESS_REGION_IS_TOO_LONG("81810"),
ADDRESS_STREET_ADDRESS_IS_REQUIRED("81811"),
ADDRESS_STREET_ADDRESS_IS_TOO_LONG("81812"),
CREDIT_CARD_BILLING_ADDRESS_CONFLICT("91701"),
CREDIT_CARD_BILLING_ADDRESS_ID_IS_INVALID("91702"),
CREDIT_CARD_CARDHOLDER_NAME_IS_TOO_LONG("81723"),
CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED("81703"),
CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED_BY_SUBSCRIPTION_MERCHANT_ACCOUNT("81718"),
CREDIT_CARD_CUSTOMER_ID_IS_INVALID("91705"),
CREDIT_CARD_CUSTOMER_ID_IS_REQUIRED("91704"),
CREDIT_CARD_CVV_IS_INVALID("81707"),
CREDIT_CARD_CVV_IS_REQUIRED("81706"),
CREDIT_CARD_EXPIRATION_DATE_CONFLICT("91708"),
CREDIT_CARD_EXPIRATION_DATE_IS_INVALID("81710"),
CREDIT_CARD_EXPIRATION_DATE_IS_REQUIRED("81709"),
CREDIT_CARD_EXPIRATION_DATE_YEAR_IS_INVALID("81711"),
CREDIT_CARD_EXPIRATION_MONTH_IS_INVALID("81712"),
CREDIT_CARD_EXPIRATION_YEAR_IS_INVALID("81713"),
CREDIT_CARD_NUMBER_HAS_INVALID_LENGTH("81716"),
CREDIT_CARD_NUMBER_IS_INVALID("81715"),
CREDIT_CARD_NUMBER_IS_REQUIRED("81714"),
CREDIT_CARD_NUMBER_MUST_BE_TEST_NUMBER("81717"),
CREDIT_CARD_OPTIONS_UPDATE_EXISTING_TOKEN_IS_INVALID("91723"),
CREDIT_CARD_TOKEN_INVALID("91718"),
CREDIT_CARD_TOKEN_IS_IN_USE("91719"),
CREDIT_CARD_TOKEN_IS_NOT_ALLOWED("91721"),
CREDIT_CARD_TOKEN_IS_REQUIRED("91722"),
CREDIT_CARD_TOKEN_IS_TOO_LONG("91720"),
CUSTOMER_COMPANY_IS_TOO_LONG("81601"),
CUSTOMER_CUSTOM_FIELD_IS_INVALID("91602"),
CUSTOMER_CUSTOM_FIELD_IS_TOO_LONG("81603"),
CUSTOMER_EMAIL_IS_INVALID("81604"),
CUSTOMER_EMAIL_IS_REQUIRED("81606"),
CUSTOMER_EMAIL_IS_TOO_LONG("81605"),
CUSTOMER_FAX_IS_TOO_LONG("81607"),
CUSTOMER_FIRST_NAME_IS_TOO_LONG("81608"),
CUSTOMER_ID_IS_INVAILD("91610"),
CUSTOMER_ID_IS_IN_USE("91609"),
CUSTOMER_ID_IS_NOT_ALLOWED("91611"),
CUSTOMER_ID_IS_REQUIRED("91613"),
CUSTOMER_ID_IS_TOO_LONG("91612"),
CUSTOMER_LAST_NAME_IS_TOO_LONG("81613"),
CUSTOMER_PHONE_IS_TOO_LONG("81614"),
CUSTOMER_WEBSITE_IS_INVALID("81616"),
CUSTOMER_WEBSITE_IS_TOO_LONG("81615"),
SUBSCRIPTION_CANNOT_ADD_DUPLICATE_ADDON_OR_DISCOUNT("91911"),
SUBSCRIPTION_CANNOT_EDIT_CANCELED_SUBSCRIPTION("81901"),
SUBSCRIPTION_CANNOT_EDIT_EXPIRED_SUBSCRIPTION("81910"),
SUBSCRIPTION_ID_IS_IN_USE("81902"),
SUBSCRIPTION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES("91908"),
SUBSCRIPTION_MERCHANT_ACCOUNT_ID_IS_INVALID("91901"),
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK("91912"),
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_IS_TOO_SMALL("91909"),
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO("91907"),
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_NUMERIC("91906"),
SUBSCRIPTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED("91902"),
SUBSCRIPTION_PAYMENT_METHOD_TOKEN_IS_INVALID("91903"),
SUBSCRIPTION_PAYMENT_METHOD_TOKEN_NOT_ASSOCIATED_WITH_CUSTOMER("91905"),
SUBSCRIPTION_PLAN_ID_IS_INVALID("91904"),
SUBSCRIPTION_PRICE_CANNOT_BE_BLANK("81903"),
SUBSCRIPTION_PRICE_FORMAT_IS_INVALID("81904"),
SUBSCRIPTION_STATUS_IS_CANCELED("81905"),
SUBSCRIPTION_TOKEN_FORMAT_IS_INVALID("81906"),
SUBSCRIPTION_TRIAL_DURATION_FORMAT_IS_INVALID("81907"),
SUBSCRIPTION_TRIAL_DURATION_IS_REQUIRED("81908"),
SUBSCRIPTION_TRIAL_DURATION_UNIT_IS_INVALID("81909"),
SUBSCRIPTION_MODIFICATION_AMOUNT_CANNOT_BE_BLANK("92003"),
SUBSCRIPTION_MODIFICATION_AMOUNT_IS_INVALID("92002"),
SUBSCRIPTION_MODIFICATION_CANNOT_UPDATE_AND_REMOVE("92015"),
SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INCORRECT_KIND("92020"),
SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INVALID("92011"),
SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_REQUIRED("92012"),
SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_INCORRECT_KIND("92021"),
SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_NOT_PRESENT("92016"),
SUBSCRIPTION_MODIFICATION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES("92018"),
SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_INVALID("92013"),
SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_REQUIRED("92014"),
SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK("92017"),
SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_IS_INVALID("92005"),
SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO("92019"),
SUBSCRIPTION_MODIFICATION_QUANTITY_CANNOT_BE_BLANK("92004"),
SUBSCRIPTION_MODIFICATION_QUANTITY_IS_INVALID("92001"),
SUBSCRIPTION_MODIFICATION_QUANTITY_MUST_BE_GREATER_THAN_ZERO("92010"),
TRANSACTION_AMOUNT_CANNOT_BE_NEGATIVE("81501"),
TRANSACTION_AMOUNT_IS_REQUIRED("81502"),
TRANSACTION_AMOUNT_IS_INVALID("81503"),
TRANSACTION_AMOUNT_IS_TOO_LARGE("81528"),
TRANSACTION_AMOUNT_MUST_BE_GREATER_THAN_ZERO("81531"),
TRANSACTION_BILLING_ADDRESS_CONFLICT("91530"),
TRANSACTION_CANNOT_BE_VOIDED("91504"),
TRANSACTION_CANNOT_REFUND_CREDIT("91505"),
TRANSACTION_CANNOT_REFUND_UNLESS_SETTLED("91506"),
TRANSACTION_CANNOT_SUBMIT_FOR_SETTLEMENT("91507"),
TRANSACTION_CREDIT_CARD_IS_REQUIRED("91508"),
TRANSACTION_CUSTOM_FIELD_IS_INVALID("91526"),
TRANSACTION_CUSTOM_FIELD_IS_TOO_LONG("81527"),
TRANSACTION_CUSTOMER_DEFAULT_PAYMENT_METHOD_CARD_TYPE_IS_NOT_ACCEPTED("81509"),
TRANSACTION_CUSTOMER_ID_IS_INVALID("91510"),
TRANSACTION_CUSTOMER_DOES_NOT_HAVE_CREDIT_CARD("91511"),
TRANSACTION_HAS_ALREADY_BEEN_REFUNDED("91512"),
TRANSACTION_MERCHANT_ACCOUNT_NAME_IS_INVALID("91513"),
TRANSACTION_MERCHANT_ACCOUNT_IS_SUSPENDED("91514"),
TRANSACTION_ORDER_ID_IS_TOO_LONG("91501"),
TRANSACTION_PAYMENT_METHOD_CONFLICT("91515"),
TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_CUSTOMER("91516"),
TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_SUBSCRIPTION("91527"),
TRANSACTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED("91517"),
TRANSACTION_PAYMENT_METHOD_TOKEN_IS_INVALID("91518"),
TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_CANNOT_BE_SET("91519"),
TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_IS_INVALID("81520"),
TRANSACTION_REFUND_AMOUNT_IS_TOO_LARGE("91521"),
TRANSACTION_SETTLEMENT_AMOUNT_IS_TOO_LARGE("91522"),
TRANSACTION_SUBSCRIPTION_DOES_NOT_BELONG_TO_CUSTOMER("91529"),
TRANSACTION_SUBSCRIPTION_ID_IS_INVALID("91528"),
TRANSACTION_TYPE_IS_INVALID("91523"),
TRANSACTION_TYPE_IS_REQUIRED("91524"),
TRANSACTION_OPTIONS_VAULT_IS_DISABLED("91525"),
UNKOWN_VALIDATION_ERROR("");
public String code;
private ValidationErrorCode(String code) {
this.code = code;
}
public static ValidationErrorCode findByCode(String code) {
for (ValidationErrorCode validationErrorCode : values()) {
if (validationErrorCode.code.equals(code)) {
return validationErrorCode;
}
}
return UNKOWN_VALIDATION_ERROR;
}
}
|
package com.esotericsoftware.clippy;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import com.esotericsoftware.clippy.Win.LASTINPUTINFO;
import com.esotericsoftware.clippy.util.Util;
public class BreakWarning {
final Clippy clippy = Clippy.instance;
final LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
long lastBreakTime = System.currentTimeMillis();
volatile ProgressBar progressBar;
public BreakWarning () {
if (clippy.config.breakWarningMinutes <= 0) return;
new Timer("BreakWarning Timer", true).schedule(new TimerTask() {
public void run () {
if (progressBar != null) return;
long inactiveMinutes = getInactiveMillis() / 1000 / 60;
if (inactiveMinutes >= clippy.config.breakResetMinutes) lastBreakTime = System.currentTimeMillis();
long activeMinutes = (System.currentTimeMillis() - lastBreakTime) / 1000 / 60;
if (activeMinutes >= clippy.config.breakWarningMinutes) showBreakDialog();
}
}, clippy.config.breakWarningMinutes * 60 * 1000, 60 * 1000);
}
void showBreakDialog () {
EventQueue.invokeLater(new Runnable() {
public void run () {
progressBar = new ProgressBar("");
progressBar.clickToDispose = false;
progressBar.progressBar.setForeground(new Color(0xff341c));
new Thread("BreakWarning Dialog") {
{
setDaemon(true);
}
public void run () {
float indeterminateMillis = 5000;
while (true) {
long inactiveMillis = getInactiveMillis();
long inactiveMinutes = inactiveMillis / 1000 / 60;
if (inactiveMinutes >= clippy.config.breakResetMinutes) break;
long activeMinutes = (System.currentTimeMillis() - lastBreakTime) / 1000 / 60;
long hours = activeMinutes / 60, minutes = activeMinutes - hours * 60;
String minutesMessage = minutes + " minute" + (minutes == 1 ? "" : "s");
String hoursMessage = hours + " hour" + (hours == 1 ? "" : "s");
String message;
if (hours == 0)
message = "Active: " + minutesMessage;
else if (minutes == 0)
message = "Active: " + hoursMessage;
else
message = "Active: " + hoursMessage + ", " + minutesMessage;
progressBar.progressBar.setString(message);
indeterminateMillis -= 16;
if (indeterminateMillis > 0) {
if (!progressBar.progressBar.isIndeterminate()) progressBar.progressBar.setIndeterminate(true);
} else {
if (indeterminateMillis < -5 * 60 * 1000) indeterminateMillis = 5000;
progressBar.setProgress(1 - inactiveMillis / (float)(clippy.config.breakResetMinutes * 60 * 1000));
}
Util.sleep(16);
}
lastBreakTime = System.currentTimeMillis();
progressBar.done("Break complete!");
progressBar = null;
}
}.start();
}
});
}
long getInactiveMillis () {
Win.User32.GetLastInputInfo(lastInputInfo);
return Win.Kernel32.GetTickCount() - lastInputInfo.dwTime;
}
}
|
package com.flat502.rox.processing;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.BlockingQueue;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLException;
import com.flat502.rox.http.HttpMessageBuffer;
import com.flat502.rox.log.Log;
import com.flat502.rox.log.LogFactory;
import com.flat502.rox.server.SSLSessionPolicy;
import com.flat502.rox.utils.Profiler;
import com.flat502.rox.utils.ProfilerCollection;
import com.flat502.rox.utils.Utils;
/**
* This abstract base class encapsulates all of the generic logic common to both client and server side
* communication over HTTP.
* <p>
* This particular implementation uses a single {@link java.lang.Thread} (this class) to manage all I/O on the
* underlying collection of sockets. I/O is managed using a {@link java.nio.channels.Selector} instance. This thread
* may be shared with other instances by means of a {@link com.flat502.rox.processing.ResourcePool}.
* <p>
* I/O writes are queued and written whenever the target socket becomes available for writing. I/O reads are
* buffered in an instance of {@link com.flat502.rox.http.HttpMessageBuffer} until a complete message is available
* (as determined by the {@link com.flat502.rox.http.HttpMessageBuffer#isComplete()} method.
* <p>
* When a complete message has been received it is placed on a shared queue serviced by a pool of
* {@link #addWorker() worker} threads, themselves instances of
* {@link com.flat502.rox.processing.HttpMessageHandler} created through calls to the
* {@link com.flat502.rox.processing.ResourcePool#newWorker()} factory method on the underlying
* {@link com.flat502.rox.processing.ResourcePool}. A worker pool may be provided when an instance of this class is
* created. This allows multiple instances to share an underlying worker pool.
* <p>
* All I/O and any state changes on the underlying {@link java.nio.channels.Selector} (like updates to interest
* operations on channels, or new channel registrations) are handled directly by the thread backing this instance to
* avoid unexpected blocking due to platform inconsistencies in the underlying NIO implementation.
*/
public abstract class HttpProcessor {
private static Log log = LogFactory.getLog(HttpProcessor.class);
private static final String CLOSE_AFTER_WRITE = "CloseAfterWrite";
// Implementation note: Win32 NIO implementations have had
// problems in the past if OP_READ and OP_WRITE are set at
// the same time. Interleaving them solves the problem.
private static final Integer OP_WRITE = new Integer(SelectionKey.OP_WRITE);
private static final Integer OP_READ = new Integer(SelectionKey.OP_READ);
// A local buffer for all non-blocking I/O read operations.
private ByteBuffer nonBlockingReadBuf = ByteBuffer.allocate(8192);
// A local buffer for all blocking I/O read operations.
// private byte[] blockingReadBuf = new byte[8192];
// An empty buffer used as the source buffer for wrap() operations during
// SSL handshakes.
private ByteBuffer BLANK = ByteBuffer.allocate(0);
// The worker pool for this instance. null until one is
// configured or addWorker is called (in which case a default
// is used).
private Object workerPoolMutex = new Object();
private boolean sharedWorkerPool;
private ResourcePool resourcePool;
private ChannelSelector channelSelector;
private SSLSessionPolicy sslSessionPolicy;
private ProfilerCollection profilers = new ProfilerCollection();
// The shared queue events should be delivered via.
private BlockingQueue<Object> queue;
// The Selector worker threads wait on for
// socket events.
private Selector socketSelector;
// Maps Socket to OP_WRITE or OP_READ.
private Map<Socket, Integer> pendingInterestOps = new LinkedHashMap<>();
private Set<SocketChannel> pendingRegistrations = new HashSet<>();
private Set<AbstractSelectableChannel> pendingCancellations = new HashSet<>();
private Map<Socket, SSLSessionMetadata> sslEngineMap = new HashMap<>();
private SSLContext sslContext;
// true if we're using SSL
private boolean useHttps;
// Non-null if we're using SSL
private SSLConfiguration sslConfig;
private boolean started;
private boolean shouldShutdown;
/**
* Initializes a new instance of this class.
*
* @param useHttps
* A flag indicating whether or not the underlying transport should use HTTPS (HTTP over SSL).
* @see #setCipherSuitePattern(String)
*/
// TODO: Document extra param
protected HttpProcessor(boolean useHttps, ResourcePool workerPool) throws IOException {
this(useHttps, null, workerPool);
}
protected HttpProcessor(SSLConfiguration sslConfig, ResourcePool workerPool) throws IOException {
this(/* useHttps = */sslConfig != null, sslConfig, workerPool);
}
protected HttpProcessor(boolean useHttps, SSLConfiguration sslConfig, ResourcePool workerPool)
throws IOException {
this.useHttps = useHttps;
this.sslConfig = sslConfig;
if (this.useHttps && this.sslConfig == null) {
// Use a default configuration
try {
this.sslConfig = new SSLConfiguration(System.getProperties());
} catch (SSLException e) {
throw (SSLException) new SSLException("Default SSL initialization failed").initCause(e);
} catch (GeneralSecurityException e) {
throw (SSLException) new SSLException("Default SSL initialization failed").initCause(e);
}
}
if (log.logDebug()) {
log.debug("Initializing SSL:\n" + this.sslConfig);
}
try {
this.sslContext = this.sslConfig.createContext();
} catch (Exception e) {
throw (SSLException) new SSLException("Failed to initialize SSL context").initCause(e);
}
if (workerPool == null) {
this.resourcePool = this.newWorkerPool();
this.sharedWorkerPool = false;
} else {
this.resourcePool = workerPool;
this.sharedWorkerPool = true;
}
this.queue = this.resourcePool.getQueue();
}
/**
* Create a new worker instance and add it to the underlying thread pool.
* <p>
* Worker threads are responsible for handling complete HTTP messages. All I/O is handled by this thread
* instance alone.
* <p>
* If an instance of this class is constructed and started without this method having been invoked it will be
* invoked before processing begins.
*
* @return The number of worker threads backing this instance.
*/
public int addWorker() {
synchronized (this.workerPoolMutex) {
return this.resourcePool.addWorker();
}
}
/**
* A convenience method for adding multiple worker threads in a single call.
*
* @param count
* The number of worker threads to add.
* @return The number of worker threads backing this instance.
*/
public int addWorkers(int count) {
synchronized (this.workerPoolMutex) {
return this.resourcePool.addWorkers(count);
}
}
/**
* Get the number of worker threads currently responsible for this instance.
*
* @return The number of worker threads backing this instance.
*/
public int getWorkerCount() {
synchronized (this.workerPoolMutex) {
return this.resourcePool.getWorkerCount();
}
}
public int removeWorker() {
synchronized (this.workerPoolMutex) {
return this.resourcePool.removeWorker();
}
}
public void setCipherSuitePattern(String cipherSuitePattern) {
if (!this.useHttps) {
throw new IllegalStateException("This instance is not configured to use HTTPS");
}
this.sslConfig.setCipherSuitePattern(cipherSuitePattern);
}
public void setSSLHandshakeTimeout(int timeout) {
if (!this.useHttps) {
throw new IllegalStateException("This instance is not configured to use HTTPS");
}
this.sslConfig.setHandshakeTimeout(timeout);
}
public SSLConfiguration getSSLConfiguration() {
return this.sslConfig;
}
protected SSLSession newSSLSession(Socket socket) {
javax.net.ssl.SSLSession session = this.getSSLSession(socket);
if (session == null) {
return null;
}
return new SSLSession(session);
}
protected javax.net.ssl.SSLSession getSSLSession(Socket socket) {
SSLSessionMetadata sessionMetadata = this.sslEngineMap.get(socket);
if (sessionMetadata == null) {
return null;
}
return sessionMetadata.engine.getSession();
}
protected boolean isStarted() {
synchronized (this.workerPoolMutex) {
return this.started;
}
}
public void start() {
synchronized (this.workerPoolMutex) {
if (this.started) {
throw new IllegalStateException("Already started");
}
// Always make sure there's at least one worker. The
// WorkerPool class will "swallow" the first addWorker()
// to provide the "at least one but however many you said
// if you said any" semantics.
if (this.getWorkerCount() == 0) {
this.addWorker();
}
this.resourcePool.startProcessingThread();
this.started = true;
}
}
// TODO: Document delayed resource release:
// There is a small delay between stopping the server and the listening socket
// actually being released to the OS. It only happens when the selecting thread
// performs it's next select() operation, which is almost immediately but asynchronous.
public void stop() throws IOException {
synchronized (this.workerPoolMutex) {
if (!this.sharedWorkerPool) {
this.resourcePool.shutdown();
}
// This will call channelSelector.deregister() for client instances
// (indirectly, as part of detaching from the resource pool).
this.stopImpl();
this.shouldShutdown = true;
// But this is still requires for server instances
// TODO: Move into stopImpl on the server?
this.channelSelector.deregister(this);
// Wake up the selecting thread so it notices this channel should
// be deregistered.
this.socketSelector.wakeup();
}
}
protected abstract void stopImpl() throws IOException;
protected boolean shouldUseHTTPS() {
return this.useHttps;
}
void processPendingSelectorChanges() throws IOException {
// Process any queued channel registrations
synchronized (this.pendingRegistrations) {
if (this.pendingRegistrations.size() > 0) {
Iterator<SocketChannel> channels = this.pendingRegistrations.iterator();
while (channels.hasNext()) {
SocketChannel channel = channels.next();
boolean wq = isWriteQueued(channel.socket());
if (log.logTrace()) {
log.trace("Registering channel (wq=" + wq + ") for " + Utils.toString(channel.socket()));
}
if (channel.isConnected()) {
// A registration is re-queued after an SSL I/O
// operation to avoid a CancelledKeyException.
// In that case we are interested in reads, not
// connections.
if (log.logTrace()) {
log.trace("Interest ops change to OP_READ for " + Utils.toString(channel.socket()));
}
channel.register(this.getSocketSelector(), SelectionKey.OP_READ);
} else {
if (log.logTrace()) {
log.trace("Interest ops change to OP_CONNECT for " + Utils.toString(channel.socket()));
}
channel.register(this.getSocketSelector(), SelectionKey.OP_CONNECT);
}
}
this.pendingRegistrations.clear();
}
}
// Process any queued interestOps updates.
synchronized (this.pendingInterestOps) {
if (this.pendingInterestOps.size() > 0) {
Iterator<Entry<Socket, Integer>> entries = this.pendingInterestOps.entrySet().iterator();
while (entries.hasNext()) {
Entry<Socket, Integer> entry = entries.next();
Socket socket = entry.getKey();
SelectionKey sk = socket.getChannel().keyFor(this.getSocketSelector());
if (socket.getChannel().isConnected()) {
// Only update the interest ops set if we're not
// waiting to complete the connection (otherwise we
// disable the OP_CONNECT interest op and never see
// the connection complete).
if (sk != null && sk.isValid()) {
int ops = entry.getValue().intValue();
if (log.logTrace()) {
log.trace("Interest ops change for " + Utils.toString(socket) + ": "
+ (ops == OP_READ ? "OP_READ" : "OP_WRITE"));
}
sk.interestOps(ops);
}
}
}
this.pendingInterestOps.clear();
}
}
// Process any queued channel cancellations
synchronized (this.pendingCancellations) {
if (this.pendingCancellations.size() > 0) {
Iterator<AbstractSelectableChannel> channels = this.pendingCancellations.iterator();
while (channels.hasNext()) {
SelectableChannel channel = channels.next();
boolean client = channel instanceof SocketChannel;
boolean connected = (client && ((SocketChannel) channel).isConnected());
if (!client || connected) {
channel.close();
SelectionKey key = channel.keyFor(this.getSocketSelector());
if (key != null) {
key.cancel();
}
}
if (log.logTrace()) {
if (client) {
log.trace("Cancellation on socket "
+ Utils.toString(((SocketChannel) channel).socket()));
} else {
log.trace("Cancellation on serverSocket "
+ Utils.toString(((ServerSocketChannel) channel).socket()));
}
}
}
this.pendingCancellations.clear();
}
}
}
void processSelectionKey(SelectionKey key) throws IOException {
try {
this.handleSelectionKeyOperation(key);
} catch (IOException e) {
SocketChannel socketChannel = (SocketChannel) key.channel();
this.deregisterSocket(socketChannel.socket());
// this.queueCancellation(socketChannel);
key.cancel();
socketChannel.close();
this.handleProcessingException(socketChannel.socket(), e);
}
}
// TODO: Better name to differentiate from overloaded method?
void handleProcessingException(Exception e) {
if (e instanceof ClosedSelectorException) {
if (!this.shouldShutdown) {
this.handleProcessingException(null, e);
}
} else {
this.handleProcessingException(null, e);
}
}
/**
* Initializes this implementation.
* <p>
* Sub-classes <i>must</i> invoke this method after their constructor has completed it's initialization.
* <p>
* This implementation invokes {@link #initSelector(Selector)} to initialize the underlying {@link Selector}.
*
* @throws IOException
* if an error occurs during initialization.
*/
protected void initialize() throws IOException {
this.channelSelector = this.resourcePool.getChannelSelector();
this.channelSelector.register(this);
this.socketSelector = this.channelSelector.getSocketSelector();
this.initSelector(this.socketSelector);
}
/**
* Queue's a new {@link SocketChannel} for registration with the underlying {@link Selector}.
* <p>
* The update is queued internally and the selecting thread is awoken to apply the change. This removes any risk
* of platform specific NIO implementation discrepancies from blocking indefinitely.
*
* @param channel
* The {@link SocketChannel} to register.
*/
protected void queueRegistration(SocketChannel channel) {
synchronized (this.pendingRegistrations) {
this.pendingRegistrations.add(channel);
}
this.getSocketSelector().wakeup();
}
protected void queueCancellation(AbstractSelectableChannel channel) {
synchronized (this.pendingCancellations) {
this.pendingCancellations.add(channel);
}
this.getSocketSelector().wakeup();
}
protected Timer getTimer() {
synchronized (this.workerPoolMutex) {
return this.resourcePool.getTimer();
}
}
/**
* Returns a handle to the shared queue used by worker threads.
*
* @return A handle to the shared queue.
*/
protected BlockingQueue<Object> getQueue() {
return this.queue;
}
/**
* Returns a handle to the {@link Selector} this thread is using for all I/O.
*
* @return A handle to the {@link Selector}.
*/
protected Selector getSocketSelector() {
return this.socketSelector;
}
/**
* Central dispatch routine for handling I/O events on the underlying {@link Selector}.
* <p>
* This implementation defers to the {@link #read(SelectionKey)} or {@link #write(SelectionKey)} method
* appropriately.
* <p>
* If a sub-class overrides this method it should defer to it if it is not interested in the
* {@link SelectionKey} presented.
*
* @param key
* The {@link SelectionKey} for the socket on which an I/O operation is pending.
* @throws IOException
* if an error occurs while processing the pending event.
*/
protected void handleSelectionKeyOperation(SelectionKey key) throws IOException {
if (key.isValid() && key.isReadable()) {
this.read(key);
} else if (key.isValid() && key.isWritable()) {
this.write(key);
}
}
/**
* Writes any pending data to the socket indicated by the given {@link SelectionKey}.
* <p>
* This implementation checks for data using the {@link #getWriteBuffer(Socket)} method. If data is available as
* much as possible is written to the socket.
*
* @param key
* The {@link SelectionKey} indicating the socket available for writing.
* @throws IOException
* If an error occurs while attempting to write to the indicated socket.
*/
protected void write(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
Socket socket = socketChannel.socket();
ByteBuffer buf = null;
// If we're using HTTPS and handshaking is still happening then we need to call
// SSLEngine.wrap() which will write the next chunk of handshake data.
if (this.useHttps && this.isHandshaking(socket)) {
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": write(): still handshaking for "
+ Utils.toString(socket));
}
try {
this.progressSSLHandshake(key);
} catch (SSLException e) {
safeClose(key, socketChannel, "SSL handshake error during write()", e);
this.handleSSLHandshakeFailed(socket);
handleProcessingException(socket, e);
}
return;
}
// Get the next chunk of application data to write, if we're using
// HTTPS we'll encrypt it a little further down.
while (true) {
buf = this.getWriteBuffer(socket);
if (buf == null) {
// A second OP_WRITE was queued at some point. This happens
// because multiple threads (the selector and the caller's
// original "write" thread) can both request an OP_WRITE
// interest op change. Rather than trying to coordinate their
// efforts we gracefully handle the case where this happens
// and just ignore the fact that there's nothing to write.
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName()
+ ": Ignoring write() call with no write buffer queued on [" + Utils.toString(socket)
+ "]");
}
key.interestOps(SelectionKey.OP_READ);
return;
}
if (this.useHttps) {
buf = this.encryptWriteBuffer(socket, buf);
}
try {
if (writeBuffer(key, socketChannel, buf)) {
// All data was successsfully written
this.processDataWritten(key, socket);
}
} catch (IOException e) {
// An error occurred
safeClose(key, socketChannel, "write() failed", e);
}
}
}
private boolean writeBuffer(SelectionKey key, SocketChannel socketChannel, ByteBuffer buf) throws IOException {
Socket socket = socketChannel.socket();
if (log.logTrace()) {
byte[] d = buf.array();
log.trace(this.getClass().getSimpleName() + ": Writing " + buf.remaining() + " byte(s) on "
+ Utils.toString(socket) + ":\n" + Utils.toHexDump(d, buf.position(), buf.remaining()));
}
int numWritten = socketChannel.write(buf);
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": Wrote " + numWritten + " byte(s) on "
+ Utils.toString(socket) + ", " + buf.remaining() + " remaining");
}
return (buf.remaining() == 0);
}
/**
* Reads any pending data from the socket indicated by the given {@link SelectionKey}.
* <p>
* This implementation retrieves an {@link HttpMessageBuffer} instance for the indicated socket using the
* {@link #getReadBuffer(Socket)} method. Data present on the socket is added to this buffer and if a complete
* HTTP message has been received it is enqueued on the {@link #getQueue() shared queue}.
*
* @param key
* The {@link SelectionKey} indicating the socket available for writing.
* @throws IOException
* If an error occurs while attempting to read from the indicated socket.
*/
protected void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
Socket socket = socketChannel.socket();
if (this.useHttps && this.isHandshaking(socket)) {
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": read(): still handshaking for "
+ Utils.toString(socket));
}
try {
this.progressSSLHandshake(key);
} catch (SSLException e) {
safeClose(key, socketChannel, "SSL handshake error during read()", e);
handleProcessingException(socket, e);
}
return;
}
HttpMessageBuffer httpMsg = this.getReadBuffer(socket);
ByteBuffer readBuf = this.nonBlockingReadBuf;
int numRead;
try {
numRead = readBuffer(key, socketChannel, readBuf);
} catch (Exception e) {
readBuf.clear();
this.handleMessageException(httpMsg, e);
return;
}
if (numRead == 0) {
readBuf.clear();
return;
}
if (this.useHttps) {
ByteBuffer decryptedBuf = null;
try {
while (readBuf.hasRemaining()) {
// unwrap() (decrypt) the message
decryptedBuf = this.decryptReadBuffer(socket, readBuf);
this.processReadData(httpMsg, decryptedBuf.array(), decryptedBuf.remaining());
}
} catch (SSLException e) {
if (decryptedBuf != null) {
decryptedBuf.clear();
}
// The remote entity probably forcibly closed the connection.
// Nothing to see here. Move on.
safeClose(key, socketChannel, "SSL decryption failed", e);
this.handleMessageException(httpMsg, e);
return;
}
} else {
this.processReadData(httpMsg, readBuf.array(), readBuf.remaining());
}
// Clear our read buffer after we've handled the data instead of before
// we read so that during the SSL handshake we can deal with the BUFFER_UNDERFLOW
// case by simple waiting for more data (which will be appended into this buffer).
readBuf.clear();
}
private int readBuffer(SelectionKey key, SocketChannel socketChannel, ByteBuffer readBuf) throws IOException {
Socket socket = socketChannel.socket();
int numRead;
try {
log.trace(this.getClass().getSimpleName() + ": ENTERING read(): " + readBuf + ": "
+ socketChannel.isBlocking());
numRead = socketChannel.read(readBuf);
log.trace(this.getClass().getSimpleName() + ": EXITING read() = " + numRead);
} catch (IOException e) {
// The remote entity probably forcibly closed the connection.
// Nothing to see here. Move on.
safeClose(key, socketChannel, "SocketChannel.read() exception cancels connection", e);
throw e;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
safeClose(key, socketChannel, "SocketChannel.read() returned EOF", null);
// The caller needs to be notifed. Although this is
// a "clean" close from the caller's perspective this
// is unexpected. So we manufacture an exception.
throw new RemoteSocketClosedException("Remote entity closed connection");
}
readBuf.flip();
// Make sure the limit on the buffer reflects what we read off the wire.
// It's not enough to simply flip the buffer, since if the position was at x > 0
// and we read nothing off the wire we end up with pos = 0 and limit = x
readBuf.limit(numRead);
if (log.logTrace()) {
byte[] d = readBuf.array();
log.trace(this.getClass().getSimpleName() + ": Read " + numRead + " byte(s) on "
+ Utils.toString(socket) + ":\n" + Utils.toHexDump(d, readBuf.position(), readBuf.remaining()));
}
return numRead;
}
private void safeClose(SelectionKey key, SocketChannel socketChannel, String traceMsg, Exception cause) {
if (log.logTrace()) {
log.trace(traceMsg, cause);
}
//this.queueCancellation(socketChannel);
key.cancel();
try {
socketChannel.close();
} catch (IOException e2) {
log.trace(traceMsg + ": close() failed", e2);
}
// This will clean up associated buffers and SSL engines too
this.deregisterSocket(socketChannel.socket());
}
private ByteBuffer encryptWriteBuffer(Socket socket, ByteBuffer buffer) throws SSLException {
if (log.logTrace()) {
log.trace("Encrypting " + buffer.remaining() + " byte(s) for " + Utils.toString(socket));
}
SSLSessionMetadata sessionMetadata = this.sslEngineMap.get(socket);
sessionMetadata.netBuffer.clear();
SSLEngineResult result = sessionMetadata.engine.wrap(buffer, sessionMetadata.netBuffer);
sessionMetadata.netBuffer.flip();
if (log.logTrace()) {
log.trace("Encryption produced " + sessionMetadata.netBuffer.remaining() + " byte(s) for "
+ Utils.toString(socket) + ": " + result);
}
return sessionMetadata.netBuffer;
}
private ByteBuffer decryptReadBuffer(Socket socket, ByteBuffer buffer) throws SSLException {
if (log.logTrace()) {
log.trace("Decrypting " + buffer.remaining() + " byte(s) for " + Utils.toString(socket));
}
SSLSessionMetadata sessionMetadata = this.sslEngineMap.get(socket);
sessionMetadata.appBuffer.clear();
SSLEngineResult result = sessionMetadata.engine.unwrap(buffer, sessionMetadata.appBuffer);
sessionMetadata.appBuffer.flip();
if (log.logTrace()) {
log.trace("Decryption produced " + sessionMetadata.appBuffer.remaining() + " byte(s) for "
+ Utils.toString(socket) + ": " + result + "(read buffer has " + buffer.remaining()
+ " byte(s) remaining)");
}
return sessionMetadata.appBuffer;
}
/**
* Queue's data to be written on the indicated {@link Socket}.
* <p>
* The data is queued internally and the interest operations set on the associated {@link SocketChannel} is
* updated to indicate that a write operation is desired.
*
* @param socket
* The socket to which the data should be written.
* @param data
* The data to be written
* @param close
* The socket should be closed after the write completes
*/
protected void queueWrite(Socket socket, byte[] data, boolean close) {
SelectionKey key = socket.getChannel().keyFor(this.getSocketSelector());
if (log.logTrace()) {
boolean pendReg = this.pendingRegistrations.contains(socket.getChannel());
log.trace("Queuing " + data.length + " byte(s) (close=" + close + ", socket=" + Utils.toString(socket)
+ ", key=" + key + ", pr=" + pendReg + "):\n" + Utils.toHexDump(data, 0, data.length));
}
ByteBuffer buf = ByteBuffer.wrap(data);
this.putWriteBuffer(socket, buf);
if (key == null) {
// This channel isn't registered yet. We've queued the
// write. When the channel is connected the selector
// thread will notice and set the interest Ops to OP_WRITE
if (log.logTrace()) {
log.trace("Queued write for unregistered channel on " + Utils.toString(socket));
}
} else {
if (close) {
// Signal that we want a close after the write completes.
// This should never be required on an unregistered
// SelectionKey since it's really only used to shut down
// a socket in the event of bad data or to shut down
// a socket after responding to a pre-1.1 client.
key.attach(CLOSE_AFTER_WRITE);
}
}
// Indicate that we're interested in writing on this socket. The socket
// itself may not be connected (or even registered) at this point, but at
// the very least a registration has been queued (otherwise there would
// be no socket to begin with). If so then the registration will be
// processed and this OP_WRITE will be ignored (if the socket is not
// yet connected) or applied (if it is).
// We have to do this because the connection operation may finish on this
// socket before this method is called, in which case this write would
// never happen.
this.queueInterestOpsUpdate(socket, OP_WRITE);
}
/**
* Create and initialize a {@link Selector} for all I/O operations.
*
* @param selector
* @throws IOException
* If an error occurs while attempting to create the {@link Selector}.
*/
protected void initSelector(Selector selector) throws IOException {
}
/**
* Factory method for new worker pools.
* <p>
* This is invoked from the constructor to create a new worker pool when one is not provided.
*
* @return A new {@link ResourcePool}.
*/
protected abstract ResourcePool newWorkerPool();
protected boolean isSharedWorkerPool() {
return this.sharedWorkerPool;
}
/**
* An error handler invoked when an attempt to determine if an HTTP message buffer constitutes a complete HTTP
* message.
*
* @param msg
* The message buffer the exception is associated with.
* @param e
* The exception that was raised.
* @throws IOException
* Implementations may raise an IOException, since there may be a requirement to notify the remote
* party of the error (which in turn will require network I/O).
*/
protected abstract void handleMessageException(HttpMessageBuffer msg, Exception e) throws IOException;
/**
* An error handler invoked when an error occurs within the main processing loop.
*
* @param socket
* The socket the exception is associated with. This may be <code>null</code> if the exception is not
* specific to a particular socket.
* @param e
* The exception that was raised.
*/
protected abstract void handleProcessingException(Socket socket, Exception e);
protected abstract void handleTimeout(Socket socket, Exception cause);
/**
* Called when a complete HTTP message has been identified.
*
* @param socket
* The socket on which a complete message has been received.
*/
protected abstract void removeReadBuffer(Socket socket);
/**
* Called when a a socket is deregistered and any buffers associated with it should be released.
*
* @param socket
* The socket on which a complete message has been received.
*/
protected abstract void removeReadBuffers(Socket socket);
/**
* Called when data is available on a socket.
* <p>
* Implementations must return a buffer, even if this means creating a new instance. The same buffer should be
* returned for a given socket until the {@link #removeReadBuffer(Socket)} method is invoked, ensuring that
* message fragmentation is correctly handled.
*
* @param socket
* The socket on which data has arrived.
* @return A message buffer for the given socket.
*/
protected abstract HttpMessageBuffer getReadBuffer(Socket socket);
/**
* Called when data is available to be written to a socket.
*
* @param socket
* The socket on which the data should be sent.
* @param data
* The data to be written.
*/
protected abstract void putWriteBuffer(Socket socket, ByteBuffer data);
/**
* Called to find out if data is queued to be written to a socket.
*
* @param socket
* The socket on which the data should be sent.
* @return <code>true</code> if there is a buffer waiting to be written on the given socket
*/
protected abstract boolean isWriteQueued(Socket socket);
/**
* Called when a all of the data in a pending write buffer has been written to a socket.
*
* @param socket
* The socket the buffer was associated with.
*/
protected abstract void removeWriteBuffer(Socket socket);
/**
* Called when a a socket is deregistered and any buffers associated with it should be released.
*
* @param socket
* The socket the buffer was associated with.
*/
protected abstract void removeWriteBuffers(Socket socket);
/**
* Called when a socket becomes available for writing.
* <p>
* Implementations should return a buffer only if one has been added using
* {@link #putWriteBuffer(Socket, ByteBuffer)}. The same buffer should be returned for a given socket until the
* {@link #removeWriteBuffer(Socket)} method is invoked, ensuring that large messages that must be written in
* multiple fragments are correctly handled.
*
* @param socket
* The socket that is available for writing.
* @return A data buffer for the given socket.
*/
protected abstract ByteBuffer getWriteBuffer(Socket socket);
/**
* Request an update to a given {@link Socket}'s interest operation set.
* <p>
* The update is queued internally and the selecting thread is awoken to apply the change. This removes any risk
* of platform specific NIO implementation discrepancies from blocking indefinitely.
*
* @param socket
* The {@link Socket} the change is intended for.
* @param interestOp
* The new interest operation.
*/
private void queueInterestOpsUpdate(Socket socket, Integer interestOp) {
synchronized (this.pendingInterestOps) {
this.pendingInterestOps.put(socket, interestOp);
}
this.getSocketSelector().wakeup();
}
protected void queueRead(Socket socket) {
this.queueInterestOpsUpdate(socket, OP_READ);
}
protected void queueWrite(Socket socket) {
this.queueInterestOpsUpdate(socket, OP_WRITE);
}
public void registerSSLSessionPolicy(SSLSessionPolicy policy) {
this.sslSessionPolicy = policy;
}
public void registerProfiler(Profiler p) {
synchronized (this.profilers) {
this.profilers.addProfiler(p);
}
synchronized (this.workerPoolMutex) {
this.resourcePool.registerProfiler(p);
}
}
// TODO: Comment to describe why this differes to registerSocket
protected void registerChannel(SelectableChannel channel) {
this.channelSelector.addChannel(this, channel);
}
protected void deregisterChannel(SelectableChannel channel) {
this.channelSelector.removeChannel(channel);
}
protected void registerSocket(Socket socket, String host, int port, boolean client) throws IOException {
}
protected void deregisterSocket(Socket socket) {
this.removeReadBuffers(socket);
this.removeWriteBuffers(socket);
this.deregisterChannel(socket.getChannel());
}
private SSLSessionMetadata initSocketSSLHandshake(Socket socket) throws SSLException {
// Create the engine
SSLEngine engine = this.initSocketSSLEngine(socket);
// Create SSL metadata container (this will initialize relevant buffers too)
SSLSessionMetadata metadata = new SSLSessionMetadata(this, engine, socket);
// Kick off the SSL handshake
engine.beginHandshake();
int timeout = this.sslConfig.getHandshakeTimeout();
if (timeout != 0) {
if (log.logTrace()) {
log.trace("Starting " + timeout + "ms timer for SSL handshake on " + Utils.toString(socket));
}
resourcePool.getTimer().schedule(metadata.newHandshakeTimerTask(), timeout);
}
// Record the new engine so it get's closed when the socket is shut down.
this.sslEngineMap.put(socket, metadata);
return metadata;
}
protected SSLEngine initSocketSSLEngine(Socket socket) throws SSLException {
SSLEngine engine = this.sslContext.createSSLEngine();
engine.setEnabledCipherSuites(this.sslConfig.selectCiphersuites(engine.getSupportedCipherSuites()));
engine.setEnabledProtocols(this.sslConfig.selectProtocols(engine.getSupportedProtocols()));
return engine;
}
private boolean isHandshaking(Socket socket) {
SSLSessionMetadata sessionMetadata = this.sslEngineMap.get(socket);
return (sessionMetadata == null)
|| (sessionMetadata.engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING);
}
private void progressSSLHandshake(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
Socket socket = socketChannel.socket();
// Make sure an engine is initialized for this socket
SSLSessionMetadata sessionMetadata = this.sslEngineMap.get(socket);
if (sessionMetadata == null) {
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": Initializing SSL engine for "
+ this.getClass().getSimpleName() + " on " + Utils.toString(socket));
}
sessionMetadata = this.initSocketSSLHandshake(socket);
this.handleSSLHandshakeStarted(socket, sessionMetadata);
}
SSLEngine engine = sessionMetadata.engine;
if (engine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) {
// This is an error condition since we never call this method
// after we finish handshaking.
throw new SSLException("SSLEngine is not handshaking for " + Utils.toString(socket));
}
SSLEngineResult result;
while (true) {
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": SSL handshake status for " + Utils.toString(socket)
+ ": " + engine.getHandshakeStatus());
}
switch (engine.getHandshakeStatus()) {
case FINISHED:
case NOT_HANDSHAKING:
this.handleSSLHandshakeFinished(socket, sessionMetadata);
return;
case NEED_TASK:
this.delegateSSLEngineTasks(socket, engine);
break;
case NEED_UNWRAP:
// Since the handshake needs an unwrap() and we're only in here because of either
// a read and a write, we assume(!) we're in here because of a read and that
// data is available.
int numRead;
try {
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": NEED_UNWRAP for " + Utils.toString(socket)
+ ": calling readBuffer()");
}
numRead = this.readBuffer(key, socketChannel, this.nonBlockingReadBuf);
} catch (RemoteSocketClosedException e) {
// The remote guy shut us out during the handshak
throw new SSLException("Handshake aborted by remote entity (socket closed)", e);
} catch (IOException e) {
if (sessionMetadata.handshakeTimeout()) {
throw new SSLException("Handshake aborted (timeout)", e);
}
throw new SSLException("Handshake aborted by remote entity (read error)", e);
}
if (numRead == 0 && engine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
// Bail so we go back to blocking the selector
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": NEED_UNWRAP for " + Utils.toString(socket)
+ ": readBuffer() returned 0, unwrap() pending, returning");
}
// Since we're in here the channel is already registered for OP_READ.
// Don't requeue it since that will needlessly wake up the selecting
// thread.
this.nonBlockingReadBuf.clear();
return;
}
while (this.nonBlockingReadBuf.hasRemaining()) {
sessionMetadata.appBuffer.clear();
result = engine.unwrap(this.nonBlockingReadBuf, sessionMetadata.appBuffer);
sessionMetadata.appBuffer.flip();
// A handshake never produces data for us to consume.
if (sessionMetadata.appBuffer.hasRemaining()) {
throw new SSLException("Handshake produced application data (unexpected)");
}
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": unwrap() result for "
+ Utils.toString(socket) + ": " + result);
}
if (result.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
// Need more data
this.queueInterestOpsUpdate(socket, OP_READ);
break;
}
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
this.delegateSSLEngineTasks(socket, engine);
}
}
this.nonBlockingReadBuf.clear();
break;
case NEED_WRAP:
// The engine wants to give us data to send to the remote party to advance
// the handshake. Let it :-)
// ByteBuffer sslBuf;
if (sessionMetadata.netBuffer.position() == 0) {
// We have no outstanding data to write for the handshake (from a previous wrap())
// so ask the engine for more.
result = engine.wrap(BLANK, sessionMetadata.netBuffer);
sessionMetadata.netBuffer.flip();
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName()
+ ": wrap() result for "
+ Utils.toString(socket)
+ ": "
+ result
+ ": produced data\n"
+ Utils.toHexDump(sessionMetadata.netBuffer.array(),
sessionMetadata.netBuffer.position(), sessionMetadata.netBuffer.remaining()));
}
} else {
// There's data remaining from the last wrap() call, fall through and try to write it
}
// Write the data away
try {
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": NEED_WRAP for " + Utils.toString(socket)
+ ": calling writeBuffer()");
}
if (!this.writeBuffer(key, socketChannel, sessionMetadata.netBuffer)) {
// Only some of the data was written Still have data to write, make sure we are alerted to write availability on the socket
this.queueInterestOpsUpdate(socket, OP_WRITE);
// And return since we have to wait for the socket to become available.
return;
}
} catch (IOException e) {
if (sessionMetadata.handshakeTimeout()) {
throw new SSLException("Handshake aborted (timeout)", e);
}
// FIXME: what do we do here?
log.error("SSL write failed: ARRRRGH", e);
throw e;
}
// All the data was written away, clear the buffer out
sessionMetadata.netBuffer.clear();
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName()
+ ": After wrap() SSL handshake expects unwrap for " + Utils.toString(socket));
}
// We need more data (to pass to unwrap(), signal we're interested
// in reading on the socket
this.queueInterestOpsUpdate(socket, OP_READ);
// And return since we have to wait for the socket to become available.
return;
}
// For all other cases fall through so we can check what the next step is.
// This ensures we handle delegated tasks, and handshake completion neatly.
break;
}
}
}
private void delegateSSLEngineTasks(Socket socket, SSLEngine engine) {
Runnable task;
while ((task = engine.getDelegatedTask()) != null) {
// TODO: We could use a thread pool and hand these out. Later.
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": Delegating SSL task " + task);
}
task.run();
}
if (log.logTrace()) {
log.trace(this.getClass().getSimpleName() + ": All SSL delegated tasks complete: "
+ engine.getHandshakeStatus());
}
}
private void handleSSLHandshakeStarted(Socket socket, SSLSessionMetadata sessionMetadata) {
synchronized (this.profilers) {
this.profilers.begin(sessionMetadata.hashCode(), "ssl.handshake");
}
}
private void handleSSLHandshakeFailed(Socket socket) {
SSLSessionMetadata metadata = this.sslEngineMap.get(socket);
if (metadata == null) {
log.warn("SSL handshake meta-data not found for " + Utils.toString(socket));
return;
}
synchronized (this.profilers) {
this.profilers.count(metadata.hashCode(), "ssl.handshake.failed");
this.profilers.end(metadata.hashCode(), "ssl.handshake");
}
}
private void handleSSLHandshakeFinished(Socket socket, SSLSessionMetadata metadata) throws SSLException {
SSLEngine engine = metadata.engine;
if (log.logDebug()) {
log.debug(this.getClass().getSimpleName() + ": SSL handshake finished for " + Utils.toString(socket)
+ ": " + Utils.toString(engine.getSession()));
}
metadata.cancelHandshakeTimer();
// Assign to a local so we don't have to synchronize access to this
// guy.
SSLSessionPolicy policy = this.sslSessionPolicy;
SSLSession session = new SSLSession(engine.getSession());
if (policy != null && !policy.shouldRetain(socket.getChannel(), session)) {
throw new SSLException("SSL Session rejected by installed policy: " + policy);
}
synchronized (this.profilers) {
this.profilers.count(metadata.hashCode(), "ssl.handshake.complete");
this.profilers.end(metadata.hashCode(), "ssl.handshake");
}
this.handleSSLHandshakeFinished(socket, engine);
}
protected abstract void handleSSLHandshakeFinished(Socket socket, SSLEngine engine);
private void processReadData(HttpMessageBuffer httpMsg, byte[] data, int numRead) throws IOException {
if (log.logTrace()) {
log.trace("Read " + numRead + " byte(s):\n" + Utils.toHexDump(data, 0, numRead));
}
try {
Socket socket = httpMsg.getSocket();
int excess = httpMsg.addBytes(data, 0, numRead);
// FIXME: To really support pipelining we need to guarantee
// response order. The way I see it this means "pipelining" only
// really means "all requests received in a single read". If we
// assume that then we could collect them all together here
// before dispatching them and have the handler threads know how
// to deal with a single "batch" call.
while (excess >= 0) {
// Clear this socket's request buffer
this.removeReadBuffer(socket);
this.getQueue().add(httpMsg);
if (excess > 0) {
// There's still data, start a new message
httpMsg = this.getReadBuffer(socket);
excess = httpMsg.addBytes(data, excess, numRead - excess);
} else {
// We have a complete message and no more data
// break out of the loop
break;
}
}
} catch (Exception e) {
this.handleMessageException(httpMsg, e);
}
}
private boolean processDataWritten(SelectionKey key, Socket socket) throws IOException {
this.removeWriteBuffer(socket);
if (key.attachment() == CLOSE_AFTER_WRITE) {
key.cancel();
socket.getChannel().close();
this.deregisterSocket(socket);
return false;
} else {
key.interestOps(SelectionKey.OP_READ);
return true;
}
}
}
|
package org.hswebframework.web.workflow.service.imp;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.hswebframework.ezorm.rdb.RDBTable;
import org.hswebframework.ezorm.rdb.meta.RDBColumnMetaData;
import org.hswebframework.ezorm.rdb.meta.RDBTableMetaData;
import org.hswebframework.ezorm.rdb.meta.converter.DateTimeConverter;
import org.hswebframework.ezorm.rdb.render.dialect.Dialect;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.service.form.DynamicFormOperationService;
import org.hswebframework.web.service.form.initialize.ColumnInitializeContext;
import org.hswebframework.web.service.form.initialize.DynamicFormInitializeCustomer;
import org.hswebframework.web.service.form.initialize.TableInitializeContext;
import org.hswebframework.web.workflow.service.config.ProcessConfigurationService;
import org.hswebframework.web.workflow.service.WorkFlowFormService;
import org.hswebframework.web.workflow.service.config.ActivityConfiguration;
import org.hswebframework.web.workflow.service.config.ProcessConfiguration;
import org.hswebframework.web.workflow.service.request.SaveFormRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.sql.JDBCType;
import java.util.Date;
import java.util.Map;
/**
* @author zhouhao
* @since 3.0.0-RC
*/
@Service
public class WorkFlowFormServiceImpl extends AbstractFlowableService implements WorkFlowFormService, DynamicFormInitializeCustomer {
@Autowired
private ProcessConfigurationService processConfigurationService;
@Autowired
private DynamicFormOperationService dynamicFormOperationService;
@Override
public void saveProcessForm(ProcessInstance instance, SaveFormRequest request) {
request.tryValidate();
ProcessConfiguration configuration = processConfigurationService
.getProcessConfiguration(instance.getProcessDefinitionId());
if (configuration == null || StringUtils.isEmpty(configuration.getFormId())) {
return;
}
Map<String, Object> formData = request.getFormData();
acceptStartProcessFormData(instance, formData);
dynamicFormOperationService.saveOrUpdate(configuration.getFormId(), formData);
}
@Override
public void saveTaskForm(Task task, SaveFormRequest request) {
request.tryValidate();
ActivityConfiguration configuration = processConfigurationService
.getActivityConfiguration(request.getUserId()
, task.getProcessDefinitionId()
, task.getTaskDefinitionKey());
if (configuration == null || StringUtils.isEmpty(configuration.getFormId())) {
return;
}
Map<String, Object> formData = request.getFormData();
acceptTaskFormData(task, formData);
dynamicFormOperationService.saveOrUpdate(configuration.getFormId(), formData);
}
protected void acceptTaskFormData(Task task,
Map<String, Object> formData) {
ProcessInstance instance = runtimeService.createProcessInstanceQuery()
.processInstanceId(task.getProcessInstanceId())
.singleResult();
acceptStartProcessFormData(instance, formData);
formData.put("processTaskId", task.getId());
formData.put("processTaskDefineKey", task.getTaskDefinitionKey());
formData.put("processTaskName",task.getName());
}
protected void acceptStartProcessFormData(ProcessInstance instance,
Map<String, Object> formData) {
formData.put("id", instance.getBusinessKey());
formData.put("processDefineId", instance.getProcessDefinitionId());
formData.put("processDefineKey", instance.getProcessDefinitionKey());
formData.put("processDefineName", instance.getProcessDefinitionName());
formData.put("processDefineVersion", instance.getProcessDefinitionVersion());
formData.put("processInstanceId", instance.getProcessInstanceId());
}
@Override
public void customTableSetting(TableInitializeContext context) {
RDBTableMetaData table = context.getTable();
Dialect dialect = context.getDatabase().getMeta().getDialect();
if(!table.getProperty("enable-workflow",true).isTrue()){
return;
}
{
RDBColumnMetaData processTaskId = new RDBColumnMetaData();
processTaskId.setJavaType(String.class);
processTaskId.setJdbcType(JDBCType.VARCHAR);
processTaskId.setLength(32);
processTaskId.setName("proc_task_id");
processTaskId.setAlias("processTaskId");
processTaskId.setDataType(dialect.buildDataType(processTaskId));
processTaskId.setComment("ID");
table.addColumn(processTaskId);
}
{
RDBColumnMetaData taskDefineKey = new RDBColumnMetaData();
taskDefineKey.setJavaType(String.class);
taskDefineKey.setJdbcType(JDBCType.VARCHAR);
taskDefineKey.setLength(128);
taskDefineKey.setName("proc_task_key");
taskDefineKey.setAlias("processTaskDefineKey");
taskDefineKey.setDataType(dialect.buildDataType(taskDefineKey));
taskDefineKey.setComment("KEY");
table.addColumn(taskDefineKey);
}
{
RDBColumnMetaData processTaskName = new RDBColumnMetaData();
processTaskName.setJavaType(String.class);
processTaskName.setJdbcType(JDBCType.VARCHAR);
processTaskName.setLength(128);
processTaskName.setName("proc_task_name");
processTaskName.setAlias("processTaskName");
processTaskName.setDataType(dialect.buildDataType(processTaskName));
processTaskName.setComment("");
table.addColumn(processTaskName);
}
{
RDBColumnMetaData processDefineId = new RDBColumnMetaData();
processDefineId.setJavaType(String.class);
processDefineId.setJdbcType(JDBCType.VARCHAR);
processDefineId.setLength(32);
processDefineId.setName("proc_def_id");
processDefineId.setAlias("processDefineId");
processDefineId.setDataType(dialect.buildDataType(processDefineId));
processDefineId.setProperty("read-only", true);
processDefineId.setComment("ID");
table.addColumn(processDefineId);
}
{
RDBColumnMetaData processDefineKey = new RDBColumnMetaData();
processDefineKey.setJavaType(String.class);
processDefineKey.setJdbcType(JDBCType.VARCHAR);
processDefineKey.setLength(32);
processDefineKey.setName("proc_def_key");
processDefineKey.setAlias("processDefineKey");
processDefineKey.setDataType(dialect.buildDataType(processDefineKey));
processDefineKey.setProperty("read-only", true);
processDefineKey.setComment("KEY");
table.addColumn(processDefineKey);
}
{
RDBColumnMetaData processDefineName = new RDBColumnMetaData();
processDefineName.setJavaType(String.class);
processDefineName.setJdbcType(JDBCType.VARCHAR);
processDefineName.setLength(128);
processDefineName.setName("proc_def_name");
processDefineName.setAlias("processDefineName");
processDefineName.setDataType(dialect.buildDataType(processDefineName));
processDefineName.setProperty("read-only", true);
processDefineName.setComment("Name");
table.addColumn(processDefineName);
}
{
RDBColumnMetaData processDefineVersion = new RDBColumnMetaData();
processDefineVersion.setJavaType(Integer.class);
processDefineVersion.setJdbcType(JDBCType.INTEGER);
processDefineVersion.setLength(32);
processDefineVersion.setPrecision(32);
processDefineVersion.setScale(0);
processDefineVersion.setName("proc_def_ver");
processDefineVersion.setAlias("processDefineVersion");
processDefineVersion.setDataType(dialect.buildDataType(processDefineVersion));
processDefineVersion.setProperty("read-only", true);
processDefineVersion.setComment("");
table.addColumn(processDefineVersion);
}
{
RDBColumnMetaData processInstanceId = new RDBColumnMetaData();
processInstanceId.setJavaType(String.class);
processInstanceId.setJdbcType(JDBCType.VARCHAR);
processInstanceId.setLength(32);
processInstanceId.setName("proc_ins_id");
processInstanceId.setAlias("processInstanceId");
processInstanceId.setDataType(dialect.buildDataType(processInstanceId));
processInstanceId.setProperty("read-only", true);
processInstanceId.setComment("ID");
table.addColumn(processInstanceId);
}
{
RDBColumnMetaData creatorUserId = new RDBColumnMetaData();
creatorUserId.setJavaType(String.class);
creatorUserId.setJdbcType(JDBCType.VARCHAR);
creatorUserId.setLength(32);
creatorUserId.setName("creator_id");
creatorUserId.setAlias("creatorId");
creatorUserId.setDataType(dialect.buildDataType(creatorUserId));
creatorUserId.setProperty("read-only", true);
creatorUserId.setComment("ID");
creatorUserId.setDefaultValue(() -> Authentication.current().map(autz -> autz.getUser().getId()).orElse(null));
table.addColumn(creatorUserId);
}
{
RDBColumnMetaData creatorName = new RDBColumnMetaData();
creatorName.setJavaType(String.class);
creatorName.setJdbcType(JDBCType.VARCHAR);
creatorName.setLength(32);
creatorName.setName("creator_name");
creatorName.setAlias("creatorName");
creatorName.setDataType(dialect.buildDataType(creatorName));
creatorName.setProperty("read-only", true);
creatorName.setComment("");
creatorName.setDefaultValue(() -> Authentication.current().map(autz -> autz.getUser().getName()).orElse(null));
table.addColumn(creatorName);
}
{
RDBColumnMetaData createTime = new RDBColumnMetaData();
createTime.setJavaType(Date.class);
createTime.setJdbcType(JDBCType.TIMESTAMP);
createTime.setName("create_time");
createTime.setAlias("createTime");
createTime.setDataType(dialect.buildDataType(createTime));
createTime.setProperty("read-only", true);
createTime.setComment("");
createTime.setNotNull(true);
createTime.setValueConverter(new DateTimeConverter("yyyy-MM-dd HH:mm:ss",Date.class));
createTime.setDefaultValue(Date::new);
table.addColumn(createTime);
}
{
RDBColumnMetaData lastUpdateTime = new RDBColumnMetaData();
lastUpdateTime.setJavaType(Date.class);
lastUpdateTime.setJdbcType(JDBCType.TIMESTAMP);
lastUpdateTime.setName("last_update_time");
lastUpdateTime.setAlias("lastUpdateTime");
lastUpdateTime.setDataType(dialect.buildDataType(lastUpdateTime));
lastUpdateTime.setComment("");
lastUpdateTime.setNotNull(true);
lastUpdateTime.setValueConverter(new DateTimeConverter("yyyy-MM-dd HH:mm:ss",Date.class));
lastUpdateTime.setDefaultValue(Date::new);
table.addColumn(lastUpdateTime);
}
}
@Override
public void customTableColumnSetting(ColumnInitializeContext context) {
}
}
|
package fr.openwide.core.test.jpa.more.business;
import java.util.Date;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import fr.openwide.core.jpa.exception.SecurityServiceException;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkErrorType;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkStatus;
import fr.openwide.core.jpa.more.business.link.model.ExternalLinkWrapper;
import fr.openwide.core.jpa.more.business.link.service.IExternalLinkCheckerService;
import fr.openwide.core.jpa.util.EntityManagerUtils;
import fr.openwide.core.test.jpa.more.config.spring.ExternalLinkCheckerTestConfig;
@ContextConfiguration(classes = ExternalLinkCheckerTestConfig.class)
public class TestExternalLinkCheckerService extends AbstractJpaMoreTestCase {
@Autowired
private IExternalLinkCheckerService externalLinkCheckerService;
@Autowired
private EntityManagerUtils entityManagerUtils;
@Test
public void testExternalLinkCheckerService() throws Exception {
Long id1 = null;
Long id2 = null;
Long id3 = null;
Long id4 = null;
Long id5 = null;
Long id6 = null;
Long id7 = null;
Long id8 = null;
Long id9 = null;
Long id10 = null;
Long id11 = null;
Long id12 = null;
Long id13 = null;
Long id14 = null;
{
id1 = createLink("http:
id2 = createLink("http://zzz.totototototo.zzz/totoz/");
id3 = createLink("http:
id4 = createLink("http://zzz.totototototo.zzz/totoz/");
id5 = createLink("http:
id6 = createLink("http: http://example.com/");
id7 = createLink("http://62.210.184.140/V2/Partenaires/00043/Images/Chalet 95/dheilly003.JPG");
id8 = createLink("http://hotel.reservit.com/reservit/avail-info.php?hotelid=104461&userid=4340d8abb651c8ca20e6cd57a844f5708354&__utma=1.804870725.1361370840.1361370840.1361370840.1&__utmc=1&__utmz=1.1361370840.1.1.utmcsr=%28direct%29|utmccn=%28direct%29|utmcmd=%28none%29");
id9 = createLink("http:
id10 = createLink("http://drome-hotel.for-system.com/index.aspx?Globales/ListeIdFournisseur=20716");
id11 = createLink("http://cyclosyennois.free.fr/");
id12 = createLink("http://lacroisee26.com/");
id13 = createLink("http://ledauphine.com/");
id14 = createLink("https:
}
Date beforeFirstBatchDate = new Date();
Thread.sleep(1000); // Make sure the checkDate will not be exactly the same
{
externalLinkCheckerService.checkBatch();
}
entityManagerUtils.getEntityManager().clear();
{
checkStatusOK(id1, beforeFirstBatchDate);
ExternalLinkWrapper externalLink2 = externalLinkWrapperService.getById(id2);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink2.getStatus());
Assert.assertEquals(1, externalLink2.getConsecutiveFailures());
Assert.assertNull(externalLink2.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.IO, externalLink2.getLastErrorType());
Assert.assertTrue(externalLink2.getLastCheckDate().after(beforeFirstBatchDate));
ExternalLinkWrapper externalLink3 = externalLinkWrapperService.getById(id3);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink3.getStatus());
Assert.assertEquals(1, externalLink3.getConsecutiveFailures());
Assert.assertEquals(Integer.valueOf(HttpStatus.SC_NOT_FOUND), externalLink3.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.HTTP, externalLink3.getLastErrorType());
Assert.assertTrue(externalLink3.getLastCheckDate().after(beforeFirstBatchDate));
// Same URL as externalLink2, so this link should carry the same data
ExternalLinkWrapper externalLink4 = externalLinkWrapperService.getById(id4);
Assert.assertEquals(externalLink2.getStatus(), externalLink4.getStatus());
Assert.assertEquals(externalLink2.getConsecutiveFailures(), externalLink4.getConsecutiveFailures());
Assert.assertEquals(externalLink2.getLastStatusCode(), externalLink4.getLastStatusCode());
Assert.assertEquals(externalLink2.getLastErrorType(), externalLink4.getLastErrorType());
Assert.assertEquals(externalLink2.getLastCheckDate(), externalLink2.getLastCheckDate());
checkStatusOK(id5, beforeFirstBatchDate);
// Invalid URL
ExternalLinkWrapper externalLink6 = externalLinkWrapperService.getById(id6);
Assert.assertEquals(ExternalLinkStatus.DEAD_LINK, externalLink6.getStatus());
Assert.assertEquals(0, externalLink6.getConsecutiveFailures());
Assert.assertNull(externalLink6.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.URI_SYNTAX, externalLink6.getLastErrorType());
Assert.assertTrue(externalLink6.getLastCheckDate().after(beforeFirstBatchDate));
checkStatusOK(id7, beforeFirstBatchDate);
checkStatusOK(id8, beforeFirstBatchDate);
checkStatusOK(id9, beforeFirstBatchDate);
checkStatusOK(id10, beforeFirstBatchDate);
checkStatusOK(id11, beforeFirstBatchDate);
checkStatusOK(id12, beforeFirstBatchDate);
checkStatusOK(id13, beforeFirstBatchDate);
checkStatusOK(id14, beforeFirstBatchDate);
}
Date beforeSecondBatchDate = new Date();
Thread.sleep(1000); // Make sure the checkDate will not be exactly the same
{
externalLinkCheckerService.checkBatch();
}
entityManagerUtils.getEntityManager().clear();
{
checkStatusOK(id1, beforeSecondBatchDate);
ExternalLinkWrapper externalLink2 = externalLinkWrapperService.getById(id2);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink2.getStatus());
Assert.assertEquals(2, externalLink2.getConsecutiveFailures());
Assert.assertNull(externalLink2.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.IO, externalLink2.getLastErrorType());
Assert.assertTrue(externalLink2.getLastCheckDate().after(beforeSecondBatchDate));
ExternalLinkWrapper externalLink3 = externalLinkWrapperService.getById(id3);
Assert.assertEquals(ExternalLinkStatus.OFFLINE, externalLink3.getStatus());
Assert.assertEquals(2, externalLink3.getConsecutiveFailures());
Assert.assertEquals(Integer.valueOf(HttpStatus.SC_NOT_FOUND), externalLink3.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.HTTP, externalLink3.getLastErrorType());
Assert.assertTrue(externalLink3.getLastCheckDate().after(beforeSecondBatchDate));
// Same URL as externalLink2, so this link should carry the same data
ExternalLinkWrapper externalLink4 = externalLinkWrapperService.getById(id4);
Assert.assertEquals(externalLink2.getStatus(), externalLink4.getStatus());
Assert.assertEquals(externalLink2.getConsecutiveFailures(), externalLink4.getConsecutiveFailures());
Assert.assertEquals(externalLink2.getLastStatusCode(), externalLink4.getLastStatusCode());
Assert.assertEquals(externalLink2.getLastErrorType(), externalLink4.getLastErrorType());
Assert.assertEquals(externalLink2.getLastCheckDate(), externalLink2.getLastCheckDate());
checkStatusOK(id5, beforeSecondBatchDate);
// Invalid URL
ExternalLinkWrapper externalLink6 = externalLinkWrapperService.getById(id6);
Assert.assertEquals(ExternalLinkStatus.DEAD_LINK, externalLink6.getStatus());
Assert.assertEquals(0, externalLink6.getConsecutiveFailures());
Assert.assertNull(externalLink6.getLastStatusCode());
Assert.assertEquals(ExternalLinkErrorType.URI_SYNTAX, externalLink6.getLastErrorType());
Assert.assertTrue(externalLink6.getLastCheckDate().after(beforeFirstBatchDate));
checkStatusOK(id7, beforeSecondBatchDate);
}
}
private Long createLink(String url) throws ServiceException, SecurityServiceException {
ExternalLinkWrapper externalLink = new ExternalLinkWrapper(url);
externalLinkWrapperService.create(externalLink);
return externalLink.getId();
}
private void checkStatusOK(Long id, Date beforeFirstBatchDate) {
checkStatus(id, beforeFirstBatchDate,
ExternalLinkStatus.ONLINE, 0, Integer.valueOf(HttpStatus.SC_OK), null);
}
private void checkStatus(Long id, Date beforeFirstBatchDate,
ExternalLinkStatus externalLinkStatus,
int consecutiveFailures,
Integer httpStatus,
ExternalLinkErrorType errorType) {
ExternalLinkWrapper externalLink = externalLinkWrapperService.getById(id);
Assert.assertEquals(externalLinkStatus, externalLink.getStatus());
Assert.assertEquals(consecutiveFailures, externalLink.getConsecutiveFailures());
Assert.assertEquals(httpStatus, externalLink.getLastStatusCode());
Assert.assertEquals(errorType, externalLink.getLastErrorType());
Assert.assertTrue(externalLink.getLastCheckDate().after(beforeFirstBatchDate));
}
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileEditor.impl.EditorTabbedContainer;
import com.intellij.openapi.fileEditor.impl.EditorWindow;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.maddyhome.idea.vim.EventFacade;
import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.action.motion.MotionEditorAction;
import com.maddyhome.idea.vim.action.motion.TextObjectAction;
import com.maddyhome.idea.vim.command.*;
import com.maddyhome.idea.vim.common.Jump;
import com.maddyhome.idea.vim.common.Mark;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.ex.ExOutputModel;
import com.maddyhome.idea.vim.handler.ExecuteMethodNotOverriddenException;
import com.maddyhome.idea.vim.helper.CaretData;
import com.maddyhome.idea.vim.helper.EditorData;
import com.maddyhome.idea.vim.helper.EditorHelper;
import com.maddyhome.idea.vim.helper.SearchHelper;
import com.maddyhome.idea.vim.option.BoundStringOption;
import com.maddyhome.idea.vim.option.NumberOption;
import com.maddyhome.idea.vim.option.Options;
import com.maddyhome.idea.vim.ui.ExEntryPanel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.event.MouseEvent;
import java.io.File;
/**
* This handles all motion related commands and marks
*/
public class MotionGroup {
public static final int LAST_F = 1;
public static final int LAST_f = 2;
public static final int LAST_T = 3;
public static final int LAST_t = 4;
public static final int LAST_COLUMN = 9999;
/**
* Create the group
*/
public MotionGroup() {
EventFacade.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {
public void editorCreated(@NotNull EditorFactoryEvent event) {
final Editor editor = event.getEditor();
// This ridiculous code ensures that a lot of events are processed BEFORE we finally start listening
// to visible area changes. The primary reason for this change is to fix the cursor position bug
// using the gd and gD commands (Goto Declaration). This bug has been around since Idea 6.0.4?
// Prior to this change the visible area code was moving the cursor around during file load and messing
// with the cursor position of the Goto Declaration processing.
ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().invokeLater(
() -> ApplicationManager.getApplication().invokeLater(() -> {
addEditorListener(editor);
EditorData.setMotionGroup(editor, true);
})));
}
public void editorReleased(@NotNull EditorFactoryEvent event) {
Editor editor = event.getEditor();
if (EditorData.getMotionGroup(editor)) {
removeEditorListener(editor);
EditorData.setMotionGroup(editor, false);
}
}
}, ApplicationManager.getApplication());
}
public void turnOn() {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
if (!EditorData.getMotionGroup(editor)) {
addEditorListener(editor);
EditorData.setMotionGroup(editor, true);
}
}
}
public void turnOff() {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
if (EditorData.getMotionGroup(editor)) {
removeEditorListener(editor);
EditorData.setMotionGroup(editor, false);
}
}
}
private void addEditorListener(@NotNull Editor editor) {
final EventFacade eventFacade = EventFacade.getInstance();
eventFacade.addEditorMouseListener(editor, mouseHandler);
eventFacade.addEditorMouseMotionListener(editor, mouseHandler);
eventFacade.addEditorSelectionListener(editor, selectionHandler);
}
private void removeEditorListener(@NotNull Editor editor) {
final EventFacade eventFacade = EventFacade.getInstance();
eventFacade.removeEditorMouseListener(editor, mouseHandler);
eventFacade.removeEditorMouseMotionListener(editor, mouseHandler);
eventFacade.removeEditorSelectionListener(editor, selectionHandler);
}
/**
* Process mouse clicks by setting/resetting visual mode. There are some strange scenarios to handle.
*
* @param editor The editor
* @param event The mouse event
*/
private void processMouseClick(@NotNull Editor editor, @NotNull MouseEvent event) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
ExOutputModel.getInstance(editor).clear();
CommandState.SubMode visualMode = CommandState.SubMode.NONE;
switch (event.getClickCount()) {
case 2:
visualMode = CommandState.SubMode.VISUAL_CHARACTER;
break;
case 3:
visualMode = CommandState.SubMode.VISUAL_LINE;
// Pop state of being in Visual Char mode
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
CommandState.getInstance(editor).popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
editor.getSelectionModel().setSelection(start, Math.max(start, end - 1));
break;
}
setVisualMode(editor, visualMode);
final CaretModel caretModel = editor.getCaretModel();
if (CommandState.getInstance(editor).getSubMode() != CommandState.SubMode.NONE) {
caretModel.removeSecondaryCarets();
}
switch (CommandState.getInstance(editor).getSubMode()) {
case NONE:
VisualPosition vp = caretModel.getVisualPosition();
int col = EditorHelper.normalizeVisualColumn(editor, vp.line, vp.column,
CommandState.getInstance(editor).getMode() ==
CommandState.Mode.INSERT ||
CommandState.getInstance(editor).getMode() ==
CommandState.Mode.REPLACE);
if (col != vp.column) {
caretModel.moveToVisualPosition(new VisualPosition(vp.line, col));
}
MotionGroup.scrollCaretIntoView(editor);
break;
case VISUAL_CHARACTER:
caretModel.moveToOffset(CaretData.getVisualEnd(caretModel.getPrimaryCaret()));
break;
case VISUAL_LINE:
caretModel.moveToLogicalPosition(editor.xyToLogicalPosition(event.getPoint()));
break;
}
CaretData.setVisualOffset(caretModel.getPrimaryCaret(), caretModel.getOffset());
CaretData.setLastColumn(editor, caretModel.getPrimaryCaret(), caretModel.getVisualPosition().column);
}
/**
* Handles mouse drags by properly setting up visual mode based on the new selection.
*
* @param editor The editor the mouse drag occurred in.
* @param update True if update, false if not.
*/
private void processLineSelection(@NotNull Editor editor, boolean update) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
ExOutputModel.getInstance(editor).clear();
if (update) {
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
for (@NotNull Caret caret : editor.getCaretModel().getAllCarets()) {
updateSelection(editor, caret, caret.getOffset());
}
}
}
else {
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
CommandState.getInstance(editor).popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
editor.getSelectionModel().setSelection(start, Math.max(start, end - 1));
setVisualMode(editor, CommandState.SubMode.VISUAL_LINE);
VisualChange range = getVisualOperatorRange(editor, Command.FLAG_MOT_LINEWISE);
if (range.getLines() > 1) {
MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(),
moveCaretVertical(editor, editor.getCaretModel().getPrimaryCaret(), -1));
}
}
}
private void processMouseReleased(@NotNull Editor editor, @NotNull CommandState.SubMode mode, int startOff,
int endOff) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
ExOutputModel.getInstance(editor).clear();
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
CommandState.getInstance(editor).popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
if (start == end) return;
if (mode == CommandState.SubMode.VISUAL_LINE) {
end
endOff
}
if (end == startOff || end == endOff) {
int t = start;
start = end;
end = t;
if (mode == CommandState.SubMode.VISUAL_CHARACTER) {
start
}
}
MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), start);
toggleVisual(editor, 1, 0, mode);
MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), end);
KeyHandler.getInstance().reset(editor);
}
@NotNull
public TextRange getWordRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter,
boolean isBig) {
int dir = 1;
boolean selection = false;
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
if (CaretData.getVisualEnd(caret) < CaretData.getVisualStart(caret)) {
dir = -1;
}
if (CaretData.getVisualStart(caret) != CaretData.getVisualEnd(caret)) {
selection = true;
}
}
return SearchHelper.findWordUnderCursor(editor, caret, count, dir, isOuter, isBig, selection);
}
@Nullable
public TextRange getBlockQuoteRange(@NotNull Editor editor, @NotNull Caret caret, char quote, boolean isOuter) {
return SearchHelper.findBlockQuoteInLineRange(editor, caret, quote, isOuter);
}
@Nullable
public TextRange getBlockRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter, char type) {
return SearchHelper.findBlockRange(editor, caret, type, count, isOuter);
}
@Nullable
public TextRange getBlockTagRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) {
return SearchHelper.findBlockTagRange(editor, caret, count, isOuter);
}
@NotNull
public TextRange getSentenceRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) {
return SearchHelper.findSentenceRange(editor, caret, count, isOuter);
}
@Nullable
public TextRange getParagraphRange(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isOuter) {
return SearchHelper.findParagraphRange(editor, caret, count, isOuter);
}
/**
* This helper method calculates the complete range a motion will move over taking into account whether
* the motion is FLAG_MOT_LINEWISE or FLAG_MOT_CHARACTERWISE (FLAG_MOT_INCLUSIVE or FLAG_MOT_EXCLUSIVE).
*
* @param editor The editor the motion takes place in
* @param caret The caret the motion takes place on
* @param context The data context
* @param count The count applied to the motion
* @param rawCount The actual count entered by the user
* @param argument Any argument needed by the motion
* @param incNewline True if to include newline
* @return The motion's range
*/
@Nullable
public static TextRange getMotionRange(@NotNull Editor editor, @NotNull Caret caret, DataContext context, int count,
int rawCount, @NotNull Argument argument, boolean incNewline) {
final Command cmd = argument.getMotion();
if (cmd == null) {
return null;
}
// Normalize the counts between the command and the motion argument
int cnt = cmd.getCount() * count;
int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt;
int start = 0;
int end = 0;
if (cmd.getAction() instanceof MotionEditorAction) {
MotionEditorAction action = (MotionEditorAction) cmd.getAction();
// This is where we are now
start = caret.getOffset();
// Execute the motion (without moving the cursor) and get where we end
try {
end = action.getOffset(editor, caret, context, cnt, raw, cmd.getArgument());
} catch (ExecuteMethodNotOverriddenException e) {
// This actually should have fallen even earlier.
end = -1;
VimPlugin.indicateError();
}
// Invalid motion
if (end == -1) {
return null;
}
}
else if (cmd.getAction() instanceof TextObjectAction) {
TextObjectAction action = (TextObjectAction) cmd.getAction();
TextRange range = action.getRange(editor, caret, context, cnt, raw, cmd.getArgument());
if (range == null) {
return null;
}
start = range.getStartOffset();
end = range.getEndOffset();
}
// If we are a linewise motion we need to normalize the start and stop then move the start to the beginning
// of the line and move the end to the end of the line.
int flags = cmd.getFlags();
if ((flags & Command.FLAG_MOT_LINEWISE) != 0) {
if (start > end) {
int t = start;
start = end;
end = t;
}
start = EditorHelper.getLineStartForOffset(editor, start);
end = Math
.min(EditorHelper.getLineEndForOffset(editor, end) + (incNewline ? 1 : 0), EditorHelper.getFileSize(editor));
}
// If characterwise and inclusive, add the last character to the range
else if ((flags & Command.FLAG_MOT_INCLUSIVE) != 0) {
end++;
}
// Normalize the range
if (start > end) {
int t = start;
start = end;
end = t;
}
return new TextRange(start, end);
}
public int moveCaretToNthCharacter(@NotNull Editor editor, int count) {
return Math.max(0, Math.min(count, EditorHelper.getFileSize(editor) - 1));
}
public int moveCaretToFileMark(@NotNull Editor editor, char ch, boolean toLineStart) {
final Mark mark = VimPlugin.getMark().getFileMark(editor, ch);
if (mark == null) return -1;
final int line = mark.getLogicalLine();
return toLineStart ? moveCaretToLineStartSkipLeading(editor, line)
: editor.logicalPositionToOffset(new LogicalPosition(line, mark.getCol()));
}
public int moveCaretToMark(@NotNull Editor editor, char ch, boolean toLineStart) {
final Mark mark = VimPlugin.getMark().getMark(editor, ch);
if (mark == null) return -1;
final VirtualFile vf = EditorData.getVirtualFile(editor);
if (vf == null) return -1;
final int line = mark.getLogicalLine();
if (vf.getPath().equals(mark.getFilename())) {
return toLineStart ? moveCaretToLineStartSkipLeading(editor, line)
: editor.logicalPositionToOffset(new LogicalPosition(line, mark.getCol()));
}
final Editor selectedEditor = selectEditor(editor, mark);
if (selectedEditor != null) {
moveCaret(selectedEditor, selectedEditor.getCaretModel().getPrimaryCaret(),
toLineStart ? moveCaretToLineStartSkipLeading(selectedEditor, line)
: selectedEditor.logicalPositionToOffset(new LogicalPosition(line, mark.getCol())));
}
return -2;
}
public int moveCaretToJump(@NotNull Editor editor, @NotNull Caret caret, int count) {
final int spot = VimPlugin.getMark().getJumpSpot();
final Jump jump = VimPlugin.getMark().getJump(count);
if (jump == null) {
return -1;
}
final VirtualFile vf = EditorData.getVirtualFile(editor);
if (vf == null) {
return -1;
}
final LogicalPosition lp = new LogicalPosition(jump.getLogicalLine(), jump.getCol());
final String fileName = jump.getFilename();
if (!vf.getPath().equals(fileName) && fileName != null) {
final VirtualFile newFile = LocalFileSystem.getInstance().findFileByPath(fileName.replace(File.separatorChar, '/'));
if (newFile == null) {
return -2;
}
final Editor newEditor = selectEditor(editor, newFile);
if (newEditor != null) {
if (spot == -1) {
VimPlugin.getMark().addJump(editor, false);
}
moveCaret(newEditor, caret, EditorHelper.normalizeOffset(newEditor, newEditor.logicalPositionToOffset(lp), false));
}
return -2;
}
else {
if (spot == -1) {
VimPlugin.getMark().addJump(editor, false);
}
return editor.logicalPositionToOffset(lp);
}
}
@Nullable
private Editor selectEditor(@NotNull Editor editor, @NotNull Mark mark) {
final VirtualFile virtualFile = markToVirtualFile(mark);
if (virtualFile != null) {
return selectEditor(editor, virtualFile);
}
else {
return null;
}
}
@Nullable
private VirtualFile markToVirtualFile(@NotNull Mark mark) {
String protocol = mark.getProtocol();
VirtualFileSystem fileSystem = VirtualFileManager.getInstance().getFileSystem(protocol);
if (mark.getFilename() == null) {
return null;
}
return fileSystem.findFileByPath(mark.getFilename());
}
@Nullable
private Editor selectEditor(@NotNull Editor editor, @NotNull VirtualFile file) {
return VimPlugin.getFile().selectEditor(editor.getProject(), file);
}
public int moveCaretToMatchingPair(@NotNull Editor editor, @NotNull Caret caret) {
int pos = SearchHelper.findMatchingPairOnCurrentLine(editor, caret);
if (pos >= 0) {
return pos;
}
else {
return -1;
}
}
/**
* This moves the caret to the start of the next/previous camel word.
*
* @param editor The editor to move in
* @param caret The caret to be moved
* @param count The number of words to skip
* @return position
*/
public int moveCaretToNextCamel(@NotNull Editor editor, @NotNull Caret caret, int count) {
if ((caret.getOffset() == 0 && count < 0) ||
(caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
return SearchHelper.findNextCamelStart(editor, caret, count);
}
}
/**
* This moves the caret to the start of the next/previous camel word.
*
* @param editor The editor to move in
* @param caret The caret to be moved
* @param count The number of words to skip
* @return position
*/
public int moveCaretToNextCamelEnd(@NotNull Editor editor, @NotNull Caret caret, int count) {
if ((caret.getOffset() == 0 && count < 0) ||
(caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
return SearchHelper.findNextCamelEnd(editor, caret, count);
}
}
/**
* This moves the caret to the start of the next/previous word/WORD.
*
* @param editor The editor to move in
* @param caret The caret to be moved
* @param count The number of words to skip
* @param bigWord If true then find WORD, if false then find word
* @return position
*/
public int moveCaretToNextWord(@NotNull Editor editor, @NotNull Caret caret, int count, boolean bigWord) {
final int offset = caret.getOffset();
final int size = EditorHelper.getFileSize(editor);
if ((offset == 0 && count < 0) || (offset >= size - 1 && count > 0)) {
return -1;
}
return SearchHelper.findNextWord(editor, caret, count, bigWord);
}
/**
* This moves the caret to the end of the next/previous word/WORD.
*
* @param editor The editor to move in
* @param caret The caret to be moved
* @param count The number of words to skip
* @param bigWord If true then find WORD, if false then find word
* @return position
*/
public int moveCaretToNextWordEnd(@NotNull Editor editor, @NotNull Caret caret, int count, boolean bigWord) {
if ((caret.getOffset() == 0 && count < 0) ||
(caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
// If we are doing this move as part of a change command (e.q. cw), we need to count the current end of
// word if the cursor happens to be on the end of a word already. If this is a normal move, we don't count
// the current word.
int pos = SearchHelper.findNextWordEnd(editor, caret, count, bigWord);
if (pos == -1) {
if (count < 0) {
return moveCaretToLineStart(editor, 0);
}
else {
return moveCaretToLineEnd(editor, EditorHelper.getLineCount(editor) - 1, false);
}
}
else {
return pos;
}
}
/**
* This moves the caret to the start of the next/previous paragraph.
*
* @param editor The editor to move in
* @param caret The caret to be moved
* @param count The number of paragraphs to skip
* @return position
*/
public int moveCaretToNextParagraph(@NotNull Editor editor, @NotNull Caret caret, int count) {
int res = SearchHelper.findNextParagraph(editor, caret, count, false);
if (res >= 0) {
res = EditorHelper.normalizeOffset(editor, res, true);
}
else {
res = -1;
}
return res;
}
public int moveCaretToNextSentenceStart(@NotNull Editor editor, @NotNull Caret caret, int count) {
int res = SearchHelper.findNextSentenceStart(editor, caret, count, false, true);
if (res >= 0) {
res = EditorHelper.normalizeOffset(editor, res, true);
}
else {
res = -1;
}
return res;
}
public int moveCaretToNextSentenceEnd(@NotNull Editor editor, @NotNull Caret caret, int count) {
int res = SearchHelper.findNextSentenceEnd(editor, caret, count, false, true);
if (res >= 0) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
else {
res = -1;
}
return res;
}
public int moveCaretToUnmatchedBlock(@NotNull Editor editor, @NotNull Caret caret, int count, char type) {
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
int res = SearchHelper.findUnmatchedBlock(editor, caret, type, count);
if (res != -1) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
return res;
}
}
public int moveCaretToSection(@NotNull Editor editor, @NotNull Caret caret, char type, int dir, int count) {
if ((caret.getOffset() == 0 && count < 0) ||
(caret.getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
int res = SearchHelper.findSection(editor, caret, type, dir, count);
if (res != -1) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
return res;
}
}
public int moveCaretToMethodStart(@NotNull Editor editor, @NotNull Caret caret, int count) {
return SearchHelper.findMethodStart(editor, caret, count);
}
public int moveCaretToMethodEnd(@NotNull Editor editor, @NotNull Caret caret, int count) {
return SearchHelper.findMethodEnd(editor, caret, count);
}
public void setLastFTCmd(int lastFTCmd, char lastChar) {
this.lastFTCmd = lastFTCmd;
this.lastFTChar = lastChar;
}
public int repeatLastMatchChar(@NotNull Editor editor, @NotNull Caret caret, int count) {
int res = -1;
int startPos = editor.getCaretModel().getOffset();
switch (lastFTCmd) {
case LAST_F:
res = moveCaretToNextCharacterOnLine(editor, caret, -count, lastFTChar);
break;
case LAST_f:
res = moveCaretToNextCharacterOnLine(editor, caret, count, lastFTChar);
break;
case LAST_T:
res = moveCaretToBeforeNextCharacterOnLine(editor, caret, -count, lastFTChar);
if (res == startPos && Math.abs(count) == 1) {
res = moveCaretToBeforeNextCharacterOnLine(editor, caret, 2 * count, lastFTChar);
}
break;
case LAST_t:
res = moveCaretToBeforeNextCharacterOnLine(editor, caret, count, lastFTChar);
if (res == startPos && Math.abs(count) == 1) {
res = moveCaretToBeforeNextCharacterOnLine(editor, caret, 2 * count, lastFTChar);
}
break;
}
return res;
}
/**
* This moves the caret to the next/previous matching character on the current line
*
* @param caret The caret to be moved
* @param count The number of occurrences to move to
* @param ch The character to search for
* @param editor The editor to search in
* @return True if [count] character matches were found, false if not
*/
public int moveCaretToNextCharacterOnLine(@NotNull Editor editor, @NotNull Caret caret, int count, char ch) {
int pos = SearchHelper.findNextCharacterOnLine(editor, caret, count, ch);
if (pos >= 0) {
return pos;
}
else {
return -1;
}
}
/**
* This moves the caret next to the next/previous matching character on the current line
*
* @param caret The caret to be moved
* @param count The number of occurrences to move to
* @param ch The character to search for
* @param editor The editor to search in
* @return True if [count] character matches were found, false if not
*/
public int moveCaretToBeforeNextCharacterOnLine(@NotNull Editor editor, @NotNull Caret caret, int count, char ch) {
int pos = SearchHelper.findNextCharacterOnLine(editor, caret, count, ch);
if (pos >= 0) {
int step = count >= 0 ? 1 : -1;
return pos - step;
}
else {
return -1;
}
}
public boolean scrollLineToFirstScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) {
scrollLineToScreenLine(editor, 1, rawCount, count, start);
return true;
}
public boolean scrollLineToMiddleScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) {
scrollLineToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2 + 1, rawCount, count, start);
return true;
}
public boolean scrollLineToLastScreenLine(@NotNull Editor editor, int rawCount, int count, boolean start) {
scrollLineToScreenLine(editor, EditorHelper.getScreenHeight(editor), rawCount, count, start);
return true;
}
public boolean scrollColumnToFirstScreenColumn(@NotNull Editor editor) {
scrollColumnToScreenColumn(editor, 0);
return true;
}
public boolean scrollColumnToLastScreenColumn(@NotNull Editor editor) {
scrollColumnToScreenColumn(editor, EditorHelper.getScreenWidth(editor));
return true;
}
private void scrollColumnToScreenColumn(@NotNull Editor editor, int column) {
int scrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value();
int width = EditorHelper.getScreenWidth(editor);
if (scrollOffset > width / 2) {
scrollOffset = width / 2;
}
if (column <= width / 2) {
if (column < scrollOffset + 1) {
column = scrollOffset + 1;
}
}
else {
if (column > width - scrollOffset) {
column = width - scrollOffset;
}
}
int visualColumn = editor.getCaretModel().getVisualPosition().column;
scrollColumnToLeftOfScreen(editor, EditorHelper
.normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn - column + 1,
false));
}
private void scrollLineToScreenLine(@NotNull Editor editor, int line, int rawCount, int count, boolean start) {
int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value();
int height = EditorHelper.getScreenHeight(editor);
if (scrollOffset > height / 2) {
scrollOffset = height / 2;
}
if (line <= height / 2) {
if (line < scrollOffset + 1) {
line = scrollOffset + 1;
}
}
else {
if (line > height - scrollOffset) {
line = height - scrollOffset;
}
}
int visualLine = rawCount == 0
? editor.getCaretModel().getVisualPosition().line
: EditorHelper.logicalLineToVisualLine(editor, count - 1);
scrollLineToTopOfScreen(editor, EditorHelper.normalizeVisualLine(editor, visualLine - line + 1));
if (visualLine != editor.getCaretModel().getVisualPosition().line || start) {
int offset;
if (start) {
offset = moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, visualLine));
}
else {
offset = moveCaretVertical(editor, editor.getCaretModel().getPrimaryCaret(),
EditorHelper.visualLineToLogicalLine(editor, visualLine) -
editor.getCaretModel().getLogicalPosition().line);
}
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset);
}
}
public int moveCaretToFirstScreenLine(@NotNull Editor editor, int count) {
return moveCaretToScreenLine(editor, count);
}
public int moveCaretToLastScreenLine(@NotNull Editor editor, int count) {
return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) - count + 1);
}
public int moveCaretToMiddleScreenLine(@NotNull Editor editor) {
return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2 + 1);
}
private int moveCaretToScreenLine(@NotNull Editor editor, int line) {
//saveJumpLocation(editor, context);
int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value();
int height = EditorHelper.getScreenHeight(editor);
if (scrollOffset > height / 2) {
scrollOffset = height / 2;
}
int top = EditorHelper.getVisualLineAtTopOfScreen(editor);
if (line > height - scrollOffset && top < EditorHelper.getLineCount(editor) - height) {
line = height - scrollOffset;
}
else if (line <= scrollOffset && top > 0) {
line = scrollOffset + 1;
}
return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, top + line - 1));
}
public boolean scrollHalfPage(@NotNull Editor editor, int dir, int count) {
NumberOption scroll = (NumberOption) Options.getInstance().getOption("scroll");
int height = EditorHelper.getScreenHeight(editor) / 2;
if (count == 0) {
count = scroll.value();
if (count == 0) {
count = height;
}
}
else {
scroll.set(count);
}
return scrollPage(editor, dir, count, EditorHelper.getCurrentVisualScreenLine(editor), true);
}
public boolean scrollColumn(@NotNull Editor editor, int columns) {
int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
visualColumn = EditorHelper
.normalizeVisualColumn(editor, editor.getCaretModel().getVisualPosition().line, visualColumn + columns, false);
scrollColumnToLeftOfScreen(editor, visualColumn);
moveCaretToView(editor);
return true;
}
public boolean scrollLine(@NotNull Editor editor, int lines) {
int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor);
visualLine = EditorHelper.normalizeVisualLine(editor, visualLine + lines);
scrollLineToTopOfScreen(editor, visualLine);
moveCaretToView(editor);
return true;
}
public static void moveCaretToView(@NotNull Editor editor) {
int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value();
int sideScrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value();
int height = EditorHelper.getScreenHeight(editor);
int width = EditorHelper.getScreenWidth(editor);
if (scrollOffset > height / 2) {
scrollOffset = height / 2;
}
if (sideScrollOffset > width / 2) {
sideScrollOffset = width / 2;
}
int visualLine = EditorHelper.getVisualLineAtTopOfScreen(editor);
int cline = editor.getCaretModel().getVisualPosition().line;
int newline = cline;
if (cline < visualLine + scrollOffset) {
newline = EditorHelper.normalizeVisualLine(editor, visualLine + scrollOffset);
}
else if (cline >= visualLine + height - scrollOffset) {
newline = EditorHelper.normalizeVisualLine(editor, visualLine + height - scrollOffset - 1);
}
int col = editor.getCaretModel().getVisualPosition().column;
int oldColumn = col;
if (col >= EditorHelper.getLineLength(editor) - 1) {
col = CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret());
}
int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
int caretColumn = col;
int newColumn = caretColumn;
if (caretColumn < visualColumn + sideScrollOffset) {
newColumn = visualColumn + sideScrollOffset;
}
else if (caretColumn >= visualColumn + width - sideScrollOffset) {
newColumn = visualColumn + width - sideScrollOffset - 1;
}
if (newline == cline && newColumn != caretColumn) {
col = newColumn;
}
newColumn = EditorHelper.normalizeVisualColumn(editor, newline, newColumn, CommandState.inInsertMode(editor));
if (newline != cline || newColumn != oldColumn) {
int offset = EditorHelper.visualPositionToOffset(editor, new VisualPosition(newline, newColumn));
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset);
CaretData.setLastColumn(editor, editor.getCaretModel().getPrimaryCaret(), col);
}
}
public boolean scrollFullPage(@NotNull Editor editor, int pages) {
int height = EditorHelper.getScreenHeight(editor);
int line = pages > 0 ? 1 : height;
return scrollPage(editor, pages, height - 2, line, false);
}
public boolean scrollPage(@NotNull Editor editor, int pages, int height, int line, boolean partial) {
int visualTopLine = EditorHelper.getVisualLineAtTopOfScreen(editor);
int newLine = visualTopLine + pages * height;
int topLine = EditorHelper.normalizeVisualLine(editor, newLine);
boolean moved = scrollLineToTopOfScreen(editor, topLine);
visualTopLine = EditorHelper.getVisualLineAtTopOfScreen(editor);
if (moved && topLine == newLine && topLine == visualTopLine) {
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretToScreenLine(editor, line));
return true;
}
else if (moved && !partial) {
int visualLine = Math.abs(visualTopLine - newLine) % height + 1;
if (pages < 0) {
visualLine = height - visualLine + 3;
}
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretToScreenLine(editor, visualLine));
return true;
}
else if (partial) {
int cline = editor.getCaretModel().getVisualPosition().line;
int visualLine = cline + pages * height;
visualLine = EditorHelper.normalizeVisualLine(editor, visualLine);
if (cline == visualLine) {
return false;
}
int logicalLine = editor.visualToLogicalPosition(new VisualPosition(visualLine, 0)).line;
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), moveCaretToLineStartSkipLeading(editor, logicalLine));
return true;
}
else {
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(),
moveCaretToLineStartSkipLeading(editor, editor.getCaretModel().getPrimaryCaret()));
return false;
}
}
private static boolean scrollLineToTopOfScreen(@NotNull Editor editor, int line) {
int pos = line * editor.getLineHeight();
int verticalPos = editor.getScrollingModel().getVerticalScrollOffset();
editor.getScrollingModel().scrollVertically(pos);
return verticalPos != editor.getScrollingModel().getVerticalScrollOffset();
}
private static void scrollColumnToLeftOfScreen(@NotNull Editor editor, int column) {
editor.getScrollingModel().scrollHorizontally(column * EditorHelper.getColumnWidth(editor));
}
public int moveCaretToMiddleColumn(@NotNull Editor editor, @NotNull Caret caret) {
final int width = EditorHelper.getScreenWidth(editor) / 2;
final int len = EditorHelper.getLineLength(editor);
return moveCaretToColumn(editor, caret, Math.max(0, Math.min(len - 1, width)), false);
}
public int moveCaretToColumn(@NotNull Editor editor, @NotNull Caret caret, int count, boolean allowEnd) {
int line = caret.getLogicalPosition().line;
int pos = EditorHelper.normalizeColumn(editor, line, count, allowEnd);
return editor.logicalPositionToOffset(new LogicalPosition(line, pos));
}
/**
* @deprecated To move the caret, use {@link #moveCaretToColumn(Editor, Caret, int, boolean)}
*/
public int moveCaretToColumn(@NotNull Editor editor, int count, boolean allowEnd) {
return moveCaretToColumn(editor, editor.getCaretModel().getPrimaryCaret(), count, allowEnd);
}
public int moveCaretToLineStartSkipLeading(@NotNull Editor editor, @NotNull Caret caret) {
int logicalLine = caret.getLogicalPosition().line;
return moveCaretToLineStartSkipLeading(editor, logicalLine);
}
public int moveCaretToLineStartSkipLeading(@NotNull Editor editor, int line) {
return EditorHelper.getLeadingCharacterOffset(editor, line);
}
/**
* @deprecated To move the caret, use {@link #moveCaretToLineStartSkipLeading(Editor, Caret)}
*/
public int moveCaretToLineStartSkipLeading(@NotNull Editor editor) {
return moveCaretToLineStartSkipLeading(editor, editor.getCaretModel().getPrimaryCaret());
}
public int moveCaretToLineStartSkipLeadingOffset(@NotNull Editor editor, @NotNull Caret caret, int linesOffset) {
int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + linesOffset);
return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
/**
* @deprecated To move the caret, use {@link #moveCaretToLineStartSkipLeadingOffset(Editor, Caret, int)}
*/
public int moveCaretToLineStartSkipLeadingOffset(@NotNull Editor editor, int linesOffset) {
return moveCaretToLineStartSkipLeadingOffset(editor, editor.getCaretModel().getPrimaryCaret(), linesOffset);
}
public int moveCaretToLineEndSkipLeadingOffset(@NotNull Editor editor, @NotNull Caret caret, int linesOffset) {
int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + linesOffset);
return moveCaretToLineEndSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
public int moveCaretToLineEndSkipLeading(@NotNull Editor editor, int line) {
int start = EditorHelper.getLineStartOffset(editor, line);
int end = EditorHelper.getLineEndOffset(editor, line, true);
CharSequence chars = editor.getDocument().getCharsSequence();
int pos = start;
for (int offset = end; offset > start; offset
if (offset >= chars.length()) {
break;
}
if (!Character.isWhitespace(chars.charAt(offset))) {
pos = offset;
break;
}
}
return pos;
}
/**
* @deprecated Use {@link #moveCaretToLineEnd(Editor, Caret)}
*/
public int moveCaretToLineEnd(@NotNull Editor editor) {
return moveCaretToLineEnd(editor, editor.getCaretModel().getPrimaryCaret());
}
public int moveCaretToLineEnd(@NotNull Editor editor, @NotNull Caret caret) {
final VisualPosition visualPosition = caret.getVisualPosition();
final int lastVisualLineColumn = EditorUtil.getLastVisualLineColumnNumber(editor, visualPosition.line);
final VisualPosition visualEndOfLine = new VisualPosition(visualPosition.line, lastVisualLineColumn, true);
return moveCaretToLineEnd(editor, editor.visualToLogicalPosition(visualEndOfLine).line, true);
}
public int moveCaretToLineEnd(@NotNull Editor editor, int line, boolean allowPastEnd) {
return EditorHelper
.normalizeOffset(editor, line, EditorHelper.getLineEndOffset(editor, line, allowPastEnd), allowPastEnd);
}
public int moveCaretToLineEndOffset(@NotNull Editor editor, @NotNull Caret caret, int cntForward,
boolean allowPastEnd) {
int line = EditorHelper.normalizeVisualLine(editor, caret.getVisualPosition().line + cntForward);
if (line < 0) {
return 0;
}
else {
return moveCaretToLineEnd(editor, EditorHelper.visualLineToLogicalLine(editor, line), allowPastEnd);
}
}
/**
* @deprecated To move the caret, use {@link #moveCaretToLineEndOffset(Editor, Caret, int, boolean)}
*/
public int moveCaretToLineEndOffset(@NotNull Editor editor, int cntForward, boolean allowPastEnd) {
return moveCaretToLineEndOffset(editor, editor.getCaretModel().getPrimaryCaret(), cntForward, allowPastEnd);
}
public int moveCaretToLineStart(@NotNull Editor editor, @NotNull Caret caret) {
int logicalLine = caret.getLogicalPosition().line;
return moveCaretToLineStart(editor, logicalLine);
}
/**
* @deprecated To move the caret, use {@link #moveCaretToLineStart(Editor, Caret)}
*/
public int moveCaretToLineStart(@NotNull Editor editor) {
return moveCaretToLineStart(editor, editor.getCaretModel().getPrimaryCaret());
}
public int moveCaretToLineStart(@NotNull Editor editor, int line) {
if (line >= EditorHelper.getLineCount(editor)) {
return EditorHelper.getFileSize(editor);
}
return EditorHelper.getLineStartOffset(editor, line);
}
public int moveCaretToLineScreenStart(@NotNull Editor editor, @NotNull Caret caret) {
final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
return moveCaretToColumn(editor, caret, col, false);
}
public int moveCaretToLineScreenStartSkipLeading(@NotNull Editor editor, @NotNull Caret caret) {
final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
final int logicalLine = caret.getLogicalPosition().line;
return EditorHelper.getLeadingCharacterOffset(editor, logicalLine, col);
}
public int moveCaretToLineScreenEnd(@NotNull Editor editor, @NotNull Caret caret, boolean allowEnd) {
final int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor) + EditorHelper.getScreenWidth(editor) - 1;
return moveCaretToColumn(editor, caret, col, allowEnd);
}
public int moveCaretHorizontalWrap(@NotNull Editor editor, @NotNull Caret caret, int count) {
// FIX - allows cursor over newlines
int oldOffset = caret.getOffset();
int offset = Math.min(Math.max(0, caret.getOffset() + count), EditorHelper.getFileSize(editor));
if (offset == oldOffset) {
return -1;
}
else {
return offset;
}
}
public int moveCaretHorizontal(@NotNull Editor editor, @NotNull Caret caret, int count, boolean allowPastEnd) {
int oldOffset = caret.getOffset();
int offset = EditorHelper.normalizeOffset(editor, caret.getLogicalPosition().line, oldOffset + count, allowPastEnd);
if (offset == oldOffset) {
return -1;
}
else {
return offset;
}
}
public int moveCaretVertical(@NotNull Editor editor, @NotNull Caret caret, int count) {
VisualPosition pos = caret.getVisualPosition();
if ((pos.line == 0 && count < 0) || (pos.line >= EditorHelper.getVisualLineCount(editor) - 1 && count > 0)) {
return -1;
}
else {
int col = CaretData.getLastColumn(caret);
int line = EditorHelper.normalizeVisualLine(editor, pos.line + count);
VisualPosition newPos = new VisualPosition(line, EditorHelper
.normalizeVisualColumn(editor, line, col, CommandState.inInsertMode(editor)));
return EditorHelper.visualPositionToOffset(editor, newPos);
}
}
public int moveCaretToLine(@NotNull Editor editor, int logicalLine) {
int col = CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret());
int line = logicalLine;
if (logicalLine < 0) {
line = 0;
col = 0;
}
else if (logicalLine >= EditorHelper.getLineCount(editor)) {
line = EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1);
col = EditorHelper.getLineLength(editor, line);
}
LogicalPosition newPos = new LogicalPosition(line, EditorHelper.normalizeColumn(editor, line, col, false));
return editor.logicalPositionToOffset(newPos);
}
public int moveCaretToLinePercent(@NotNull Editor editor, int count) {
if (count > 100) count = 100;
return moveCaretToLineStartSkipLeading(editor, EditorHelper
.normalizeLine(editor, (EditorHelper.getLineCount(editor) * count + 99) / 100 - 1));
}
public int moveCaretGotoLineLast(@NotNull Editor editor, int rawCount) {
final int line = rawCount == 0 ?
EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) :
rawCount - 1;
return moveCaretToLineStartSkipLeading(editor, line);
}
public int moveCaretGotoLineLastEnd(@NotNull Editor editor, int rawCount, int line, boolean pastEnd) {
return moveCaretToLineEnd(editor, rawCount == 0
? EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1)
: line, pastEnd);
}
public int moveCaretGotoLineFirst(@NotNull Editor editor, int line) {
return moveCaretToLineStartSkipLeading(editor, line);
}
public static void moveCaret(@NotNull Editor editor, @NotNull Caret caret, int offset) {
moveCaret(editor, caret, offset, false);
}
/**
* @deprecated Use the {@link #moveCaret(Editor, Caret, int) multi-caret version} of this function.
*/
public static void moveCaret(@NotNull Editor editor, int offset) {
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), offset);
}
public static void moveCaret(@NotNull Editor editor, @NotNull Caret caret, int offset, boolean forceKeepVisual) {
if (offset >= 0 && offset <= editor.getDocument().getTextLength()) {
final boolean keepVisual = forceKeepVisual || keepVisual(editor);
if (caret.getOffset() != offset) {
caret.moveToOffset(offset);
CaretData.setLastColumn(editor, caret, caret.getVisualPosition().column);
if (caret == editor.getCaretModel().getPrimaryCaret()) {
scrollCaretIntoView(editor);
}
}
if (keepVisual) {
VimPlugin.getMotion().updateSelection(editor, caret, offset);
}
else {
editor.getSelectionModel().removeSelection();
}
}
}
private static boolean keepVisual(Editor editor) {
final CommandState commandState = CommandState.getInstance(editor);
if (commandState.getMode() == CommandState.Mode.VISUAL) {
final Command command = commandState.getCommand();
return command == null || (command.getFlags() & Command.FLAG_EXIT_VISUAL) == 0;
}
return false;
}
/**
* If 'absolute' is true, then set tab index to 'value', otherwise add 'value' to tab index with wraparound.
*/
private void switchEditorTab(@Nullable EditorWindow editorWindow, int value, boolean absolute) {
if (editorWindow != null) {
final EditorTabbedContainer tabbedPane = editorWindow.getTabbedPane();
if (tabbedPane != null) {
if (absolute) {
tabbedPane.setSelectedIndex(value);
}
else {
int tabIndex = (value + tabbedPane.getSelectedIndex()) % tabbedPane.getTabCount();
tabbedPane.setSelectedIndex(tabIndex < 0 ? tabIndex + tabbedPane.getTabCount() : tabIndex);
}
}
}
}
public int moveCaretGotoPreviousTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) {
switchEditorTab(EditorWindow.DATA_KEY.getData(context), rawCount >= 1 ? -rawCount : -1, false);
return editor.getCaretModel().getOffset();
}
public int moveCaretGotoNextTab(@NotNull Editor editor, @NotNull DataContext context, int rawCount) {
final boolean absolute = rawCount >= 1;
switchEditorTab(EditorWindow.DATA_KEY.getData(context), absolute ? rawCount - 1 : 1, absolute);
return editor.getCaretModel().getOffset();
}
public static void scrollCaretIntoView(@NotNull Editor editor) {
final boolean scrollJump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SCROLL_JUMP) == 0;
scrollPositionIntoView(editor, editor.getCaretModel().getVisualPosition(), scrollJump);
}
public static void scrollPositionIntoView(@NotNull Editor editor, @NotNull VisualPosition position,
boolean scrollJump) {
final int line = position.line;
final int column = position.column;
final int topLine = EditorHelper.getVisualLineAtTopOfScreen(editor);
int scrollOffset = ((NumberOption) Options.getInstance().getOption("scrolloff")).value();
int scrollJumpSize = 0;
if (scrollJump) {
scrollJumpSize = Math.max(0, ((NumberOption) Options.getInstance().getOption("scrolljump")).value() - 1);
}
int height = EditorHelper.getScreenHeight(editor);
int visualTop = topLine + scrollOffset;
int visualBottom = topLine + height - scrollOffset;
if (scrollOffset >= height / 2) {
scrollOffset = height / 2;
visualTop = topLine + scrollOffset;
visualBottom = topLine + height - scrollOffset;
if (visualTop == visualBottom) {
visualBottom++;
}
}
int diff;
if (line < visualTop) {
diff = line - visualTop;
scrollJumpSize = -scrollJumpSize;
}
else {
diff = line - visualBottom + 1;
if (diff < 0) {
diff = 0;
}
}
if (diff != 0) {
int resLine;
// If we need to move the top line more than a half screen worth then we just center the cursor line
if (Math.abs(diff) > height / 2) {
resLine = line - height / 2 - 1;
}
// Otherwise put the new cursor line "scrolljump" lines from the top/bottom
else {
resLine = topLine + diff + scrollJumpSize;
}
resLine = Math.min(resLine, EditorHelper.getVisualLineCount(editor) - height);
resLine = Math.max(0, resLine);
scrollLineToTopOfScreen(editor, resLine);
}
int visualColumn = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
int width = EditorHelper.getScreenWidth(editor);
scrollJump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SIDE_SCROLL_JUMP) == 0;
scrollOffset = ((NumberOption) Options.getInstance().getOption("sidescrolloff")).value();
scrollJumpSize = 0;
if (scrollJump) {
scrollJumpSize = Math.max(0, ((NumberOption) Options.getInstance().getOption("sidescroll")).value() - 1);
if (scrollJumpSize == 0) {
scrollJumpSize = width / 2;
}
}
int visualLeft = visualColumn + scrollOffset;
int visualRight = visualColumn + width - scrollOffset;
if (scrollOffset >= width / 2) {
scrollOffset = width / 2;
visualLeft = visualColumn + scrollOffset;
visualRight = visualColumn + width - scrollOffset;
if (visualLeft == visualRight) {
visualRight++;
}
}
scrollJumpSize = Math.min(scrollJumpSize, width / 2 - scrollOffset);
if (column < visualLeft) {
diff = column - visualLeft + 1;
scrollJumpSize = -scrollJumpSize;
}
else {
diff = column - visualRight + 1;
if (diff < 0) {
diff = 0;
}
}
if (diff != 0) {
int col;
if (Math.abs(diff) > width / 2) {
col = column - width / 2 - 1;
}
else {
col = visualColumn + diff + scrollJumpSize;
}
col = Math.max(0, col);
scrollColumnToLeftOfScreen(editor, col);
}
}
public boolean selectPreviousVisualMode(@NotNull Editor editor) {
final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor);
if (lastSelectionType == null) {
return false;
}
final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor);
if (visualMarks == null) {
return false;
}
editor.getCaretModel().removeSecondaryCarets();
CommandState.getInstance(editor)
.pushState(CommandState.Mode.VISUAL, lastSelectionType.toSubMode(), MappingMode.VISUAL);
Caret primaryCaret = editor.getCaretModel().getPrimaryCaret();
CaretData.setVisualStart(primaryCaret, visualMarks.getStartOffset());
CaretData.setVisualEnd(primaryCaret, visualMarks.getEndOffset());
CaretData.setVisualOffset(primaryCaret, visualMarks.getEndOffset());
updateSelection(editor, primaryCaret, visualMarks.getEndOffset());
primaryCaret.moveToOffset(visualMarks.getEndOffset());
editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
return true;
}
public boolean swapVisualSelections(@NotNull Editor editor) {
final SelectionType lastSelectionType = EditorData.getLastSelectionType(editor);
final TextRange lastVisualRange = EditorData.getLastVisualRange(editor);
if (lastSelectionType == null || lastVisualRange == null) {
return false;
}
final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode());
EditorData.setLastSelectionType(editor, selectionType);
editor.getCaretModel().removeSecondaryCarets();
Caret primaryCaret = editor.getCaretModel().getPrimaryCaret();
CaretData.setVisualStart(primaryCaret, lastVisualRange.getStartOffset());
CaretData.setVisualEnd(primaryCaret, lastVisualRange.getEndOffset());
CaretData.setVisualOffset(primaryCaret, lastVisualRange.getEndOffset());
CommandState.getInstance(editor).setSubMode(lastSelectionType.toSubMode());
updateSelection(editor, primaryCaret, lastVisualRange.getEndOffset());
primaryCaret.moveToOffset(lastVisualRange.getEndOffset());
editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
return true;
}
public void setVisualMode(@NotNull Editor editor, @NotNull CommandState.SubMode mode) {
CommandState.SubMode oldMode = CommandState.getInstance(editor).getSubMode();
if (mode == CommandState.SubMode.NONE) {
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
if (start != end) {
int line = editor.offsetToLogicalPosition(start).line;
int logicalStart = EditorHelper.getLineStartOffset(editor, line);
int lend = EditorHelper.getLineEndOffset(editor, line, true);
if (logicalStart == start && lend + 1 == end) {
mode = CommandState.SubMode.VISUAL_LINE;
}
else {
mode = CommandState.SubMode.VISUAL_CHARACTER;
}
}
}
if (oldMode == CommandState.SubMode.NONE && mode == CommandState.SubMode.NONE) {
editor.getSelectionModel().removeSelection();
return;
}
if (mode == CommandState.SubMode.NONE) {
exitVisual(editor);
}
else {
CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL);
}
KeyHandler.getInstance().reset(editor);
for (Caret caret : editor.getCaretModel().getAllCarets()) {
CaretData.setVisualStart(caret, caret.getSelectionStart());
int visualEnd = caret.getSelectionEnd();
if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) {
BoundStringOption opt = (BoundStringOption) Options.getInstance().getOption("selection");
int adj = 1;
if (opt.getValue().equals("exclusive")) {
adj = 0;
}
visualEnd -= adj;
}
CaretData.setVisualEnd(caret, visualEnd);
CaretData.setVisualOffset(caret, caret.getOffset());
}
VimPlugin.getMark().setVisualSelectionMarks(editor, getRawVisualRange(editor));
}
public boolean toggleVisual(@NotNull Editor editor, int count, int rawCount, @NotNull CommandState.SubMode mode) {
CommandState.SubMode currentMode = CommandState.getInstance(editor).getSubMode();
if (CommandState.getInstance(editor).getMode() != CommandState.Mode.VISUAL) {
if (rawCount > 0) {
if (editor.getCaretModel().getCaretCount() > 1) {
return false;
}
VisualChange range = CaretData.getLastVisualOperatorRange(editor.getCaretModel().getPrimaryCaret());
if (range == null) {
return false;
}
mode = range.getType().toSubMode();
int start = editor.getCaretModel().getOffset();
int end = calculateVisualRange(editor, range, count);
Caret primaryCaret = editor.getCaretModel().getPrimaryCaret();
CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL);
CaretData.setVisualStart(primaryCaret, start);
updateSelection(editor, primaryCaret, end);
MotionGroup.moveCaret(editor, primaryCaret, CaretData.getVisualEnd(primaryCaret), true);
}
else {
CommandState.getInstance(editor).pushState(CommandState.Mode.VISUAL, mode, MappingMode.VISUAL);
if (mode == CommandState.SubMode.VISUAL_BLOCK) {
EditorData.setVisualBlockStart(editor, editor.getSelectionModel().getSelectionStart());
updateBlockSelection(editor, editor.getSelectionModel().getSelectionEnd());
MotionGroup
.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), EditorData.getVisualBlockEnd(editor), true);
}
else {
for (Caret caret : editor.getCaretModel().getAllCarets()) {
CaretData.setVisualStart(caret, caret.getSelectionStart());
updateSelection(editor, caret, caret.getSelectionEnd());
MotionGroup.moveCaret(editor, caret, CaretData.getVisualEnd(caret), true);
}
}
}
}
else if (mode == currentMode) {
exitVisual(editor);
}
else if (mode == CommandState.SubMode.VISUAL_BLOCK) {
CommandState.getInstance(editor).setSubMode(mode);
updateBlockSelection(editor, EditorData.getVisualBlockEnd(editor));
}
else {
CommandState.getInstance(editor).setSubMode(mode);
for (Caret caret : editor.getCaretModel().getAllCarets()) {
updateSelection(editor, caret, CaretData.getVisualEnd(caret));
}
}
return true;
}
private int calculateVisualRange(@NotNull Editor editor, @NotNull VisualChange range, int count) {
int lines = range.getLines();
int chars = range.getColumns();
if (range.getType() == SelectionType.LINE_WISE || range.getType() == SelectionType.BLOCK_WISE || lines > 1) {
lines *= count;
}
if ((range.getType() == SelectionType.CHARACTER_WISE && lines == 1) ||
range.getType() == SelectionType.BLOCK_WISE) {
chars *= count;
}
int start = editor.getCaretModel().getOffset();
LogicalPosition sp = editor.offsetToLogicalPosition(start);
int endLine = sp.line + lines - 1;
int res;
if (range.getType() == SelectionType.LINE_WISE) {
res = moveCaretToLine(editor, endLine);
}
else if (range.getType() == SelectionType.CHARACTER_WISE) {
if (lines > 1) {
res = moveCaretToLineStart(editor, endLine) + Math.min(EditorHelper.getLineLength(editor, endLine), chars);
}
else {
res = EditorHelper.normalizeOffset(editor, sp.line, start + chars - 1, false);
}
}
else {
int endColumn = Math.min(EditorHelper.getLineLength(editor, endLine), sp.column + chars - 1);
res = editor.logicalPositionToOffset(new LogicalPosition(endLine, endColumn));
}
return res;
}
public void exitVisual(@NotNull final Editor editor) {
resetVisual(editor, true);
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
CommandState.getInstance(editor).popState();
}
}
public void resetVisual(@NotNull final Editor editor, final boolean removeSelection) {
final boolean wasVisualBlock = CommandState.inVisualBlockMode(editor);
final SelectionType selectionType = SelectionType.fromSubMode(CommandState.getInstance(editor).getSubMode());
EditorData.setLastSelectionType(editor, selectionType);
final TextRange visualMarks = VimPlugin.getMark().getVisualSelectionMarks(editor);
if (visualMarks != null) {
EditorData.setLastVisualRange(editor, visualMarks);
}
if (removeSelection) {
if (!EditorData.isKeepingVisualOperatorAction(editor)) {
for (Caret caret : editor.getCaretModel().getAllCarets()) {
caret.removeSelection();
}
}
if (wasVisualBlock) {
editor.getCaretModel().removeSecondaryCarets();
}
}
CommandState.getInstance(editor).setSubMode(CommandState.SubMode.NONE);
}
@NotNull
public VisualChange getVisualOperatorRange(@NotNull Editor editor, @NotNull Caret caret, int cmdFlags) {
int start = CaretData.getVisualStart(caret);
int end = CaretData.getVisualEnd(caret);
if (CommandState.inVisualBlockMode(editor)) {
start = EditorData.getVisualBlockStart(editor);
end = EditorData.getVisualBlockEnd(editor);
}
if (start > end) {
int t = start;
start = end;
end = t;
}
start = EditorHelper.normalizeOffset(editor, start, false);
end = EditorHelper.normalizeOffset(editor, end, false);
LogicalPosition sp = editor.offsetToLogicalPosition(start);
LogicalPosition ep = editor.offsetToLogicalPosition(end);
int lines = ep.line - sp.line + 1;
int chars;
SelectionType type;
if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_LINE ||
(cmdFlags & Command.FLAG_MOT_LINEWISE) != 0) {
chars = ep.column;
type = SelectionType.LINE_WISE;
}
else if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_CHARACTER) {
type = SelectionType.CHARACTER_WISE;
if (lines > 1) {
chars = ep.column;
}
else {
chars = ep.column - sp.column + 1;
}
}
else {
chars = ep.column - sp.column + 1;
if (CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()) == MotionGroup.LAST_COLUMN) {
chars = MotionGroup.LAST_COLUMN;
}
type = SelectionType.BLOCK_WISE;
}
return new VisualChange(lines, chars, type);
}
@NotNull
public VisualChange getVisualOperatorRange(@NotNull Editor editor, int cmdFlags) {
return getVisualOperatorRange(editor, editor.getCaretModel().getPrimaryCaret(), cmdFlags);
}
@NotNull
public TextRange getVisualRange(@NotNull Editor editor) {
return new TextRange(editor.getSelectionModel().getBlockSelectionStarts(),
editor.getSelectionModel().getBlockSelectionEnds());
}
@NotNull
public TextRange getVisualRange(@NotNull Caret caret) {
return new TextRange(caret.getSelectionStart(), caret.getSelectionEnd());
}
@NotNull
public TextRange getRawVisualRange(@NotNull Editor editor) {
return getRawVisualRange(editor.getCaretModel().getPrimaryCaret());
}
@NotNull
public TextRange getRawVisualRange(@NotNull Caret caret) {
return new TextRange(CaretData.getVisualStart(caret), CaretData.getVisualEnd(caret));
}
public void updateBlockSelection(@NotNull Editor editor) {
updateBlockSelection(editor, EditorData.getVisualBlockEnd(editor));
}
private void updateBlockSelection(@NotNull Editor editor, int offset) {
EditorData.setVisualBlockEnd(editor, offset);
EditorData.setVisualBlockOffset(editor, offset);
int start = EditorData.getVisualBlockStart(editor);
int end = EditorData.getVisualBlockEnd(editor);
LogicalPosition blockStart = editor.offsetToLogicalPosition(start);
LogicalPosition blockEnd = editor.offsetToLogicalPosition(end);
if (blockStart.column < blockEnd.column) {
blockEnd = new LogicalPosition(blockEnd.line, blockEnd.column + 1);
}
else {
blockStart = new LogicalPosition(blockStart.line, blockStart.column + 1);
}
editor.getSelectionModel().setBlockSelection(blockStart, blockEnd);
for (Caret caret : editor.getCaretModel().getAllCarets()) {
int line = caret.getLogicalPosition().line;
int lineEndOffset = EditorHelper.getLineEndOffset(editor, line, true);
if (CaretData.getLastColumn(editor.getCaretModel().getPrimaryCaret()) >= MotionGroup.LAST_COLUMN) {
caret.setSelection(caret.getSelectionStart(), lineEndOffset);
}
if (!EditorHelper.isLineEmpty(editor, line, false)) {
caret.moveToOffset(caret.getSelectionEnd() - 1);
}
}
editor.getCaretModel().getPrimaryCaret().moveToOffset(end);
VimPlugin.getMark().setVisualSelectionMarks(editor, new TextRange(start, end));
}
private void updateSelection(@NotNull Editor editor, @NotNull Caret caret, int offset) {
if (CommandState.getInstance(editor).getSubMode() == CommandState.SubMode.VISUAL_BLOCK) {
updateBlockSelection(editor, offset);
}
else {
CaretData.setVisualEnd(caret, offset);
CaretData.setVisualOffset(caret, offset);
int start = CaretData.getVisualStart(caret);
int end = offset;
final CommandState.SubMode subMode = CommandState.getInstance(editor).getSubMode();
if (subMode == CommandState.SubMode.VISUAL_CHARACTER) {
if (start > end) {
int t = start;
start = end;
end = t;
}
final BoundStringOption opt = (BoundStringOption) Options.getInstance().getOption("selection");
int lineEnd = EditorHelper.getLineEndForOffset(editor, end);
final int adj = opt.getValue().equals("exclusive") || end == lineEnd ? 0 : 1;
final int adjEnd = Math.min(EditorHelper.getFileSize(editor), end + adj);
caret.setSelection(start, adjEnd);
}
else if (subMode == CommandState.SubMode.VISUAL_LINE) {
if (start > end) {
int t = start;
start = end;
end = t;
}
start = EditorHelper.getLineStartForOffset(editor, start);
end = EditorHelper.getLineEndForOffset(editor, end);
caret.setSelection(start, end);
}
VimPlugin.getMark().setVisualSelectionMarks(editor, new TextRange(start, end));
}
}
public boolean swapVisualBlockEnds(@NotNull Editor editor) {
if (!CommandState.inVisualBlockMode(editor)) return false;
int t = EditorData.getVisualBlockEnd(editor);
EditorData.setVisualBlockEnd(editor, EditorData.getVisualBlockStart(editor));
EditorData.setVisualBlockStart(editor, t);
moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), EditorData.getVisualBlockEnd(editor));
return true;
}
public boolean swapVisualEnds(@NotNull Editor editor, @NotNull Caret caret) {
int t = CaretData.getVisualEnd(caret);
CaretData.setVisualEnd(caret, CaretData.getVisualStart(caret));
CaretData.setVisualStart(caret, t);
moveCaret(editor, caret, CaretData.getVisualEnd(caret));
return true;
}
public void moveVisualStart(@NotNull Caret caret, int startOffset) {
CaretData.setVisualStart(caret, startOffset);
}
public void processEscape(@NotNull Editor editor) {
exitVisual(editor);
}
public static class MotionEditorChange implements FileEditorManagerListener {
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
final FileEditor fileEditor = event.getOldEditor();
if (fileEditor instanceof TextEditor) {
final Editor editor = ((TextEditor) fileEditor).getEditor();
ExOutputModel.getInstance(editor).clear();
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
VimPlugin.getMotion().exitVisual(editor);
}
}
}
}
private static class EditorSelectionHandler implements SelectionListener {
private boolean myMakingChanges = false;
public void selectionChanged(@NotNull SelectionEvent selectionEvent) {
final Editor editor = selectionEvent.getEditor();
final Document document = editor.getDocument();
if (myMakingChanges || (document instanceof DocumentEx && ((DocumentEx) document).isInEventsHandling())) {
return;
}
myMakingChanges = true;
try {
final com.intellij.openapi.util.TextRange newRange = selectionEvent.getNewRange();
for (Editor e : EditorFactory.getInstance().getEditors(document)) {
if (!e.equals(editor)) {
e.getSelectionModel().setSelection(newRange.getStartOffset(), newRange.getEndOffset());
}
}
} finally {
myMakingChanges = false;
}
}
}
private static class EditorMouseHandler implements EditorMouseListener, EditorMouseMotionListener {
public void mouseMoved(EditorMouseEvent event) {
}
public void mouseDragged(@NotNull EditorMouseEvent event) {
if (!VimPlugin.isEnabled()) return;
if (event.getArea() == EditorMouseEventArea.EDITING_AREA ||
event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) {
if (dragEditor == null) {
if (event.getArea() == EditorMouseEventArea.EDITING_AREA) {
mode = CommandState.SubMode.VISUAL_CHARACTER;
}
else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) {
mode = CommandState.SubMode.VISUAL_LINE;
}
startOff = event.getEditor().getSelectionModel().getSelectionStart();
endOff = event.getEditor().getSelectionModel().getSelectionEnd();
}
dragEditor = event.getEditor();
}
}
public void mousePressed(EditorMouseEvent event) {
}
public void mouseClicked(@NotNull EditorMouseEvent event) {
if (!VimPlugin.isEnabled()) return;
if (event.getArea() == EditorMouseEventArea.EDITING_AREA) {
VimPlugin.getMotion().processMouseClick(event.getEditor(), event.getMouseEvent());
}
else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA &&
event.getArea() != EditorMouseEventArea.FOLDING_OUTLINE_AREA) {
VimPlugin.getMotion()
.processLineSelection(event.getEditor(), event.getMouseEvent().getButton() == MouseEvent.BUTTON3);
}
}
public void mouseReleased(@NotNull EditorMouseEvent event) {
if (!VimPlugin.isEnabled()) return;
if (event.getEditor().equals(dragEditor)) {
VimPlugin.getMotion().processMouseReleased(event.getEditor(), mode, startOff, endOff);
dragEditor = null;
}
}
public void mouseEntered(EditorMouseEvent event) {
}
public void mouseExited(EditorMouseEvent event) {
}
@Nullable
private Editor dragEditor = null;
@NotNull
private CommandState.SubMode mode = CommandState.SubMode.NONE;
private int startOff;
private int endOff;
}
public int getLastFTCmd() {
return lastFTCmd;
}
public char getLastFTChar() {
return lastFTChar;
}
private int lastFTCmd = 0;
private char lastFTChar;
@NotNull
private final EditorMouseHandler mouseHandler = new EditorMouseHandler();
@NotNull
private final EditorSelectionHandler selectionHandler = new EditorSelectionHandler();
}
|
package org.innovateuk.ifs.application.common.populator;
import org.innovateuk.ifs.application.common.viewmodel.ApplicationFinanceSummaryViewModel;
import org.innovateuk.ifs.application.finance.service.FinanceService;
import org.innovateuk.ifs.application.finance.view.OrganisationApplicationFinanceOverviewImpl;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.service.ApplicationService;
import org.innovateuk.ifs.application.service.SectionService;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.file.service.FileEntryRestService;
import org.innovateuk.ifs.finance.resource.BaseFinanceResource;
import org.innovateuk.ifs.form.resource.SectionResource;
import org.innovateuk.ifs.form.resource.SectionType;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.innovateuk.ifs.user.resource.ProcessRoleResource;
import org.innovateuk.ifs.user.resource.Role;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.service.OrganisationRestService;
import org.innovateuk.ifs.user.service.UserRestService;
import org.innovateuk.ifs.user.service.UserService;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.Optional.ofNullable;
import static org.innovateuk.ifs.user.resource.Role.*;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
@Component
public class ApplicationFinanceSummaryViewModelPopulator {
private FinanceService financeService;
private FileEntryRestService fileEntryRestService;
private OrganisationRestService organisationRestService;
private ApplicationService applicationService;
private SectionService sectionService;
private UserRestService userRestService;
private UserService userService;
private CompetitionRestService competitionRestService;
public ApplicationFinanceSummaryViewModelPopulator(ApplicationService applicationService,
SectionService sectionService,
FinanceService financeService,
FileEntryRestService fileEntryRestService,
OrganisationRestService organisationRestService,
UserRestService userRestService,
UserService userService,
CompetitionRestService competitionRestService) {
this.applicationService = applicationService;
this.sectionService = sectionService;
this.financeService = financeService;
this.fileEntryRestService = fileEntryRestService;
this.organisationRestService = organisationRestService;
this.userRestService = userRestService;
this.userService = userService;
this.competitionRestService = competitionRestService;
}
public ApplicationFinanceSummaryViewModel populate(long applicationId, UserResource user) {
ApplicationResource application = applicationService.getById(applicationId);
CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess();
OrganisationApplicationFinanceOverviewImpl organisationFinanceOverview = new OrganisationApplicationFinanceOverviewImpl(
financeService,
fileEntryRestService,
applicationId
);
SectionResource financeSection = sectionService.getFinanceSection(application.getCompetition());
final boolean hasFinanceSection = financeSection != null;
Long financeSectionId = null;
if (hasFinanceSection) {
financeSectionId = financeSection.getId();
}
Map<Long, Set<Long>> completedSectionsByOrganisation = sectionService.getCompletedSectionsByOrganisation(application.getId());
ProcessRoleResource leadApplicantUser = userService.getLeadApplicantProcessRoleOrNull(applicationId);
OrganisationResource leadOrganisation = organisationRestService.getOrganisationById(leadApplicantUser.getOrganisationId()).getSuccess();
Set<Long> sectionsMarkedAsComplete = getCompletedSectionsForUserOrganisation(completedSectionsByOrganisation, leadOrganisation);
List<SectionResource> eachOrganisationFinanceSections = sectionService.getSectionsForCompetitionByType(application.getCompetition(), SectionType.FINANCE);
Long eachCollaboratorFinanceSectionId = getEachCollaboratorFinanceSectionId(eachOrganisationFinanceSections);
Map<Long, BaseFinanceResource> organisationFinances = organisationFinanceOverview.getFinancesByOrganisation();
final List<OrganisationResource> applicationOrganisations = getApplicationOrganisations(applicationId);
final List<OrganisationResource> academicOrganisations = getAcademicOrganisations(applicationOrganisations);
final List<Long> academicOrganisationIds = simpleMap(academicOrganisations, OrganisationResource::getId);
Map<Long, Boolean> applicantOrganisationsAreAcademic = simpleToMap
(applicationOrganisations, OrganisationResource::getId, o -> academicOrganisationIds.contains(o.getId
()));
Map<Long, Boolean> showDetailedFinanceLink = simpleToMap(applicationOrganisations, OrganisationResource::getId,
organisation -> {
boolean orgFinancesExist = ofNullable(organisationFinances)
.map(finances -> organisationFinances.get(organisation.getId()))
.map(BaseFinanceResource::getOrganisationSize)
.isPresent();
boolean academicFinancesExist = applicantOrganisationsAreAcademic.get(organisation.getId());
boolean financesExist = orgFinancesExist || academicFinancesExist;
return isApplicationVisibleToUser(application, user) && financesExist;
});
boolean yourFinancesCompleteForAllOrganisations = getYourFinancesCompleteForAllOrganisations(
completedSectionsByOrganisation, financeSectionId);
return new ApplicationFinanceSummaryViewModel(
application,
hasFinanceSection,
organisationFinanceOverview.getTotalPerType(),
applicationOrganisations,
sectionsMarkedAsComplete,
financeSectionId,
leadOrganisation,
competition,
getUserOrganisation(user, applicationId),
organisationFinanceOverview.getFinancesByOrganisation(),
organisationFinanceOverview.getTotalFundingSought(),
organisationFinanceOverview.getTotalOtherFunding(),
organisationFinanceOverview.getTotalContribution(),
organisationFinanceOverview.getTotal(),
completedSectionsByOrganisation,
eachCollaboratorFinanceSectionId,
showDetailedFinanceLink,
yourFinancesCompleteForAllOrganisations
);
}
private List<OrganisationResource> getApplicationOrganisations(final Long applicationId) {
return organisationRestService.getOrganisationsByApplicationId(applicationId).getSuccess();
}
private Set<Long> getCompletedSectionsForUserOrganisation(Map<Long, Set<Long>> completedSectionsByOrganisation,
OrganisationResource userOrganisation) {
return completedSectionsByOrganisation.getOrDefault(
userOrganisation.getId(),
new HashSet<>()
);
}
private boolean getYourFinancesCompleteForAllOrganisations(Map<Long, Set<Long>> completedSectionsByOrganisation,
Long financeSectionId) {
if (financeSectionId == null) {
return false;
}
return completedSectionsByOrganisation.keySet()
.stream()
.noneMatch(id -> !completedSectionsByOrganisation.get(id).contains(financeSectionId));
}
private Long getEachCollaboratorFinanceSectionId(List<SectionResource> eachOrganisationFinanceSections) {
if (!eachOrganisationFinanceSections.isEmpty()) {
return eachOrganisationFinanceSections.get(0).getId();
}
return null;
}
private boolean isApplicationVisibleToUser(ApplicationResource application, UserResource user) {
boolean canSeeUnsubmitted = user.hasRole(IFS_ADMINISTRATOR) || user.hasRole(SUPPORT);
boolean canSeeSubmitted = user.hasRole(PROJECT_FINANCE) || user.hasRole(COMP_ADMIN) || user.hasRole(INNOVATION_LEAD) || user.hasRole(STAKEHOLDER);
boolean isSubmitted = application.getApplicationState() != ApplicationState.OPEN && application.getApplicationState() != ApplicationState.CREATED;
return canSeeUnsubmitted || (canSeeSubmitted && isSubmitted);
}
private List<OrganisationResource> getAcademicOrganisations(final List<OrganisationResource> organisations) {
return simpleFilter(organisations, o -> OrganisationTypeEnum.RESEARCH.getId() == o.getOrganisationType());
}
private OrganisationResource getUserOrganisation(UserResource user, Long applicationId) {
OrganisationResource userOrganisation = null;
if (!user.isInternalUser() && !user.hasAnyRoles(Role.ASSESSOR, Role.INTERVIEW_ASSESSOR)) {
ProcessRoleResource userProcessRole = userRestService.findProcessRole(user.getId(), applicationId).getSuccess();
userOrganisation = organisationRestService.getOrganisationById(userProcessRole.getOrganisationId()).getSuccess();
}
return userOrganisation;
}
}
|
package com.maddyhome.idea.vim.group;
import com.google.common.collect.Lists;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Ref;
import com.intellij.util.Processor;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.Command;
import com.maddyhome.idea.vim.command.CommandState;
import com.maddyhome.idea.vim.command.SelectionType;
import com.maddyhome.idea.vim.common.CharacterPosition;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.ex.LineRange;
import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.option.ListOption;
import com.maddyhome.idea.vim.option.Options;
import com.maddyhome.idea.vim.regexp.CharHelper;
import com.maddyhome.idea.vim.regexp.CharPointer;
import com.maddyhome.idea.vim.regexp.CharacterClasses;
import com.maddyhome.idea.vim.regexp.RegExp;
import com.maddyhome.idea.vim.ui.ExEntryPanel;
import com.maddyhome.idea.vim.ui.ModalEntry;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.*;
public class SearchGroup {
@Nullable
public String getLastSearch() {
return lastSearch;
}
@Nullable
public String getLastPattern() {
return lastPattern;
}
private void setLastPattern(@NotNull Editor editor, @NotNull String lastPattern) {
this.lastPattern = lastPattern;
VimPlugin.getRegister().storeTextInternal(editor, new TextRange(-1, -1),
lastPattern, SelectionType.CHARACTER_WISE, '/', false);
VimPlugin.getHistory().addEntry(HistoryGroup.SEARCH, lastPattern);
}
public boolean searchAndReplace(@NotNull Editor editor, @NotNull LineRange range, @NotNull String excmd, String exarg) {
boolean res = true;
// Explicitly exit visual mode here, so that visual mode marks don't change when we move the cursor to a match.
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.VISUAL) {
VimPlugin.getMotion().exitVisual(editor);
}
CharPointer cmd = new CharPointer(new StringBuffer(exarg));
//sub_nsubs = 0;
//sub_nlines = 0;
int which_pat;
if (excmd.equals("~")) {
which_pat = RE_LAST; /* use last used regexp */
}
else {
which_pat = RE_SUBST; /* use last substitute regexp */
}
CharPointer pat;
CharPointer sub;
char delimiter;
/* new pattern and substitution */
if (excmd.charAt(0) == 's' && !cmd.isNul() && !Character.isWhitespace(cmd.charAt()) &&
"0123456789cegriIp|\"".indexOf(cmd.charAt()) == -1) {
/* don't accept alphanumeric for separator */
if (CharacterClasses.isAlpha(cmd.charAt())) {
VimPlugin.showMessage(MessageHelper.message(Msg.E146));
return false;
}
/*
* undocumented vi feature:
* "\/sub/" and "\?sub?" use last used search pattern (almost like
* //sub/r). "\&sub&" use last substitute pattern (like //sub/).
*/
if (cmd.charAt() == '\\') {
cmd.inc();
if ("/?&".indexOf(cmd.charAt()) == -1) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_backslash));
return false;
}
if (cmd.charAt() != '&') {
which_pat = RE_SEARCH; /* use last '/' pattern */
}
pat = new CharPointer(""); /* empty search pattern */
delimiter = cmd.charAt(); /* remember delimiter character */
cmd.inc();
}
else /* find the end of the regexp */ {
which_pat = RE_LAST; /* use last used regexp */
delimiter = cmd.charAt(); /* remember delimiter character */
cmd.inc();
pat = cmd.ref(0); /* remember start of search pat */
cmd = RegExp.skip_regexp(cmd, delimiter, true);
if (cmd.charAt() == delimiter) /* end delimiter found */ {
cmd.set('\u0000').inc(); /* replace it with a NUL */
}
}
/*
* Small incompatibility: vi sees '\n' as end of the command, but in
* Vim we want to use '\n' to find/substitute a NUL.
*/
sub = cmd.ref(0); /* remember the start of the substitution */
while (!cmd.isNul()) {
if (cmd.charAt() == delimiter) /* end delimiter found */ {
cmd.set('\u0000').inc(); /* replace it with a NUL */
break;
}
if (cmd.charAt(0) == '\\' && cmd.charAt(1) != 0) /* skip escaped characters */ {
cmd.inc();
}
cmd.inc();
}
}
else /* use previous pattern and substitution */ {
if (lastReplace == null) /* there is no previous command */ {
VimPlugin.showMessage(MessageHelper.message(Msg.e_nopresub));
return false;
}
pat = null; /* search_regcomp() will use previous pattern */
sub = new CharPointer(lastReplace);
}
/*
* Find trailing options. When '&' is used, keep old options.
*/
if (cmd.charAt() == '&') {
cmd.inc();
}
else {
do_all = Options.getInstance().isSet("gdefault");
do_ask = false;
do_error = true;
//do_print = false;
do_ic = 0;
}
while (!cmd.isNul()) {
/*
* Note that 'g' and 'c' are always inverted, also when p_ed is off.
* 'r' is never inverted.
*/
if (cmd.charAt() == 'g') {
do_all = !do_all;
}
else if (cmd.charAt() == 'c') {
do_ask = !do_ask;
}
else if (cmd.charAt() == 'e') {
do_error = !do_error;
}
else if (cmd.charAt() == 'r') /* use last used regexp */ {
which_pat = RE_LAST;
}
else if (cmd.charAt() == 'i') /* ignore case */ {
do_ic = 'i';
}
else if (cmd.charAt() == 'I') /* don't ignore case */ {
do_ic = 'I';
}
else if (cmd.charAt() != 'p') {
break;
}
cmd.inc();
}
int line1 = range.getStartLine();
int line2 = range.getEndLine();
if (line1 < 0 || line2 < 0) {
return false;
}
/*
* check for a trailing count
*/
cmd = CharHelper.skipwhite(cmd);
if (CharacterClasses.isDigit(cmd.charAt())) {
int i = CharHelper.getdigits(cmd);
if (i <= 0 && do_error) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_zerocount));
return false;
}
line1 = line2;
line2 = EditorHelper.normalizeLine(editor, line1 + i - 1);
}
/*
* check for trailing command or garbage
*/
cmd = CharHelper.skipwhite(cmd);
if (!cmd.isNul() && cmd.charAt() != '"') /* if not end-of-line or comment */ {
VimPlugin.showMessage(MessageHelper.message(Msg.e_trailing));
return false;
}
String pattern = "";
if (pat == null || pat.isNul()) {
switch (which_pat) {
case RE_LAST:
pattern = lastPattern;
break;
case RE_SEARCH:
pattern = lastSearch;
break;
case RE_SUBST:
pattern = lastSubstitute;
break;
}
}
else {
pattern = pat.toString();
}
lastSubstitute = pattern;
lastSearch = pattern;
if (pattern != null) {
setLastPattern(editor, pattern);
}
//int start = editor.logicalPositionToOffset(new LogicalPosition(line1, 0));
//int end = editor.logicalPositionToOffset(new LogicalPosition(line2, EditorHelper.getLineLength(editor, line2)));
int start = editor.getDocument().getLineStartOffset(line1);
int end = editor.getDocument().getLineEndOffset(line2);
RegExp sp;
RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T();
sp = new RegExp();
regmatch.regprog = sp.vim_regcomp(pattern, 1);
if (regmatch.regprog == null) {
if (do_error) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_invcmd));
}
return false;
}
/* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
if (do_ic == 'i') {
regmatch.rmm_ic = true;
}
else if (do_ic == 'I') {
regmatch.rmm_ic = false;
}
/*
* ~ in the substitute pattern is replaced with the old pattern.
* We do it here once to avoid it to be replaced over and over again.
* But don't do it when it starts with "\=", then it's an expression.
*/
if (!(sub.charAt(0) == '\\' && sub.charAt(1) == '=') && lastReplace != null) {
StringBuffer tmp = new StringBuffer(sub.toString());
int pos = 0;
while ((pos = tmp.indexOf("~", pos)) != -1) {
if (pos == 0 || tmp.charAt(pos - 1) != '\\') {
tmp.replace(pos, pos + 1, lastReplace);
pos += lastReplace.length();
}
pos++;
}
sub = new CharPointer(tmp);
}
lastReplace = sub.toString();
searchHighlight(false);
if (logger.isDebugEnabled()) {
logger.debug("search range=[" + start + "," + end + "]");
logger.debug("pattern=" + pattern + ", replace=" + sub);
}
int lastMatch = -1;
int lastLine = -1;
int searchcol = 0;
boolean firstMatch = true;
boolean got_quit = false;
int lcount = EditorHelper.getLineCount(editor);
for (int lnum = line1; lnum <= line2 && !got_quit; ) {
CharacterPosition newpos = null;
int nmatch = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, searchcol);
if (nmatch > 0) {
if (firstMatch) {
VimPlugin.getMark().saveJumpLocation(editor);
firstMatch = false;
}
String match = sp.vim_regsub_multi(regmatch, lnum, sub, 1, false);
//logger.debug("found match[" + spos + "," + epos + "] - replace " + match);
int line = lnum + regmatch.startpos[0].lnum;
CharacterPosition startpos = new CharacterPosition(lnum + regmatch.startpos[0].lnum,
regmatch.startpos[0].col);
CharacterPosition endpos = new CharacterPosition(lnum + regmatch.endpos[0].lnum,
regmatch.endpos[0].col);
int startoff = EditorHelper.characterPositionToOffset(editor, startpos);
int endoff = EditorHelper.characterPositionToOffset(editor, endpos);
int newend = startoff + match.length();
if (do_all || line != lastLine) {
boolean doReplace = true;
if (do_ask) {
RangeHighlighter hl = highlightConfirm(editor, startoff, endoff);
MotionGroup.scrollPositionIntoView(editor, editor.offsetToVisualPosition(startoff), true);
MotionGroup.moveCaret(editor, startoff);
final ReplaceConfirmationChoice choice = confirmChoice(editor, match);
editor.getMarkupModel().removeHighlighter(hl);
switch (choice) {
case SUBSTITUTE_THIS:
doReplace = true;
break;
case SKIP:
doReplace = false;
break;
case SUBSTITUTE_ALL:
do_ask = false;
break;
case QUIT:
doReplace = false;
got_quit = true;
break;
case SUBSTITUTE_LAST:
do_all = false;
line2 = lnum;
doReplace = true;
break;
}
}
if (doReplace) {
editor.getDocument().replaceString(startoff, endoff, match);
lastMatch = startoff;
newpos = EditorHelper.offsetToCharacterPosition(editor, newend);
lnum += newpos.line - endpos.line;
line2 += newpos.line - endpos.line;
}
}
lastLine = line;
lnum += nmatch - 1;
if (do_all && startoff != endoff) {
if (newpos != null) {
lnum = newpos.line;
searchcol = newpos.column;
}
else {
searchcol = endpos.column;
}
}
else {
searchcol = 0;
lnum++;
}
}
else {
lnum++;
searchcol = 0;
}
}
if (lastMatch != -1) {
MotionGroup.moveCaret(editor, VimPlugin.getMotion()
.moveCaretToLineStartSkipLeading(editor, editor.offsetToLogicalPosition(lastMatch).line
));
}
else {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
}
return res;
}
@NotNull
private static ReplaceConfirmationChoice confirmChoice(@NotNull Editor editor, @NotNull String match) {
final Ref<ReplaceConfirmationChoice> result = Ref.create(ReplaceConfirmationChoice.QUIT);
// XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for this method
final ExEntryPanel exEntryPanel = ExEntryPanel.getInstance();
exEntryPanel.activate(editor, new EditorDataContext(editor), "Replace with " + match + " (y/n/a/q/l)?", "", 1);
ModalEntry.activate(new Processor<KeyStroke>() {
@Override
public boolean process(KeyStroke key) {
final ReplaceConfirmationChoice choice;
final char c = key.getKeyChar();
if (StringHelper.isCloseKeyStroke(key) || c == 'q') {
choice = ReplaceConfirmationChoice.QUIT;
}
else if (c == 'y') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_THIS;
}
else if (c == 'l') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_LAST;
}
else if (c == 'n') {
choice = ReplaceConfirmationChoice.SKIP;
}
else if (c == 'a') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_ALL;
}
else {
return true;
}
result.set(choice);
exEntryPanel.deactivate(true);
return false;
}
});
return result.get();
}
private static boolean shouldIgnoreCase(@NotNull String pattern, boolean noSmartCase) {
boolean sc = !noSmartCase && Options.getInstance().isSet("smartcase");
boolean ic = Options.getInstance().isSet("ignorecase");
return ic && !(sc && StringHelper.containsUpperCase(pattern));
}
public int search(@NotNull Editor editor, @NotNull String command, int count, int flags, boolean moveCursor) {
int res = search(editor, command, editor.getCaretModel().getOffset(), count, flags);
if (res != -1 && moveCursor) {
VimPlugin.getMark().saveJumpLocation(editor);
MotionGroup.moveCaret(editor, res);
}
return res;
}
public int search(@NotNull Editor editor, @NotNull String command, int startOffset, int count, int flags) {
int dir = 1;
char type = '/';
String pattern = lastSearch;
String offset = lastOffset;
if ((flags & Command.FLAG_SEARCH_REV) != 0) {
dir = -1;
type = '?';
}
if (command.length() > 0) {
if (command.charAt(0) != type) {
CharPointer p = new CharPointer(command);
CharPointer end = RegExp.skip_regexp(p.ref(0), type, true);
pattern = p.substring(end.pointer() - p.pointer());
if (logger.isDebugEnabled()) logger.debug("pattern=" + pattern);
if (p.charAt() != type) {
logger.debug("no offset");
offset = "";
}
else {
p.inc();
offset = p.toString();
if (logger.isDebugEnabled()) logger.debug("offset=" + offset);
}
}
else if (command.length() == 1) {
offset = "";
}
else {
offset = command.substring(1);
if (logger.isDebugEnabled()) logger.debug("offset=" + offset);
}
}
lastSearch = pattern;
if (pattern != null) {
setLastPattern(editor, pattern);
}
lastOffset = offset;
lastDir = dir;
if (logger.isDebugEnabled()) {
logger.debug("lastSearch=" + lastSearch);
logger.debug("lastOffset=" + lastOffset);
logger.debug("lastDir=" + lastDir);
}
searchHighlight(false);
return findItOffset(editor, startOffset, count, lastDir, false);
}
public int searchWord(@NotNull Editor editor, int count, boolean whole, int dir) {
TextRange range = SearchHelper.findWordUnderCursor(editor);
if (range == null) {
return -1;
}
StringBuilder pattern = new StringBuilder();
if (whole) {
pattern.append("\\<");
}
pattern.append(EditorHelper.getText(editor, range.getStartOffset(), range.getEndOffset()));
if (whole) {
pattern.append("\\>");
}
MotionGroup.moveCaret(editor, range.getStartOffset());
lastSearch = pattern.toString();
setLastPattern(editor, lastSearch);
lastOffset = "";
lastDir = dir;
searchHighlight(true);
return findItOffset(editor, editor.getCaretModel().getOffset(), count, lastDir, true);
}
public int searchNext(@NotNull Editor editor, int count) {
searchHighlight(false);
return findItOffset(editor, editor.getCaretModel().getOffset(), count, lastDir, false);
}
public int searchPrevious(@NotNull Editor editor, int count) {
searchHighlight(false);
return findItOffset(editor, editor.getCaretModel().getOffset(), count, -lastDir, false);
}
public void updateHighlight() {
highlightSearch(false);
}
private void searchHighlight(boolean noSmartCase) {
showSearchHighlight = Options.getInstance().isSet("hlsearch");
highlightSearch(noSmartCase);
}
private void highlightSearch(final boolean noSmartCase) {
Project[] projects = ProjectManager.getInstance().getOpenProjects();
for (Project project : projects) {
Editor current = FileEditorManager.getInstance(project).getSelectedTextEditor();
Editor[] editors =
current == null ? null : EditorFactory.getInstance().getEditors(current.getDocument(), project);
if (editors == null) {
continue;
}
for (final Editor editor : editors) {
String els = EditorData.getLastSearch(editor);
if (!showSearchHighlight) {
removeSearchHighlight(editor);
continue;
}
else if (lastSearch != null && lastSearch.equals(els)) {
continue;
}
else if (lastSearch == null) {
continue;
}
removeSearchHighlight(editor);
highlightSearchLines(editor, lastSearch, 0, -1, shouldIgnoreCase(lastSearch, noSmartCase));
EditorData.setLastSearch(editor, lastSearch);
}
}
}
private void highlightSearchLines(@NotNull Editor editor, boolean noSmartCase, int startLine, int endLine) {
if (lastSearch != null) {
highlightSearchLines(editor, lastSearch, startLine, endLine, shouldIgnoreCase(lastSearch, noSmartCase));
}
}
@Nullable
public static TextRange findNext(@NotNull Editor editor, @NotNull String pattern, final int offset, boolean ignoreCase,
final boolean forwards) {
final List<TextRange> results = findAll(editor, pattern, 0, -1, shouldIgnoreCase(pattern, ignoreCase));
if (results.isEmpty()) {
return null;
}
final int size = EditorHelper.getFileSize(editor);
final TextRange max = Collections.max(results, new Comparator<TextRange>() {
@Override
public int compare(TextRange r1, TextRange r2) {
final int d1 = distance(r1, offset, forwards, size);
final int d2 = distance(r2, offset, forwards, size);
if (d1 < 0 && d2 >= 0) {
return Integer.MAX_VALUE;
}
return d2 - d1;
}
});
if (!Options.getInstance().isSet("wrapscan")) {
final int start = max.getStartOffset();
if (forwards && start < offset || start >= offset) {
return null;
}
}
return max;
}
private static int distance(@NotNull TextRange range, int pos, boolean forwards, int size) {
final int start = range.getStartOffset();
if (start <= pos) {
return forwards ? size - pos + start : pos - start;
}
else {
return forwards ? start - pos : pos + size - start;
}
}
@NotNull
public static List<TextRange> findAll(@NotNull Editor editor, @NotNull String pattern, int startLine, int endLine,
boolean ignoreCase) {
final List<TextRange> results = Lists.newArrayList();
final int lineCount = EditorHelper.getLineCount(editor);
final int actualEndLine = endLine == -1 ? lineCount : endLine;
final RegExp.regmmatch_T regMatch = new RegExp.regmmatch_T();
final RegExp regExp = new RegExp();
regMatch.regprog = regExp.vim_regcomp(pattern, 1);
if (regMatch.regprog == null) {
return results;
}
regMatch.rmm_ic = ignoreCase;
int col = 0;
for (int line = startLine; line <= actualEndLine; ) {
int matchedLines = regExp.vim_regexec_multi(regMatch, editor, lineCount, line, col);
if (matchedLines > 0) {
final CharacterPosition startPos = new CharacterPosition(line + regMatch.startpos[0].lnum,
regMatch.startpos[0].col);
final CharacterPosition endPos = new CharacterPosition(line + regMatch.endpos[0].lnum,
regMatch.endpos[0].col);
int start = EditorHelper.characterPositionToOffset(editor, startPos);
int end = EditorHelper.characterPositionToOffset(editor, endPos);
results.add(new TextRange(start, end));
if (start != end) {
line += matchedLines - 1;
col = endPos.column;
}
else {
line += matchedLines;
col = 0;
}
}
else {
line++;
col = 0;
}
}
return results;
}
private static void highlightSearchLines(@NotNull Editor editor, @NotNull String pattern, int startLine, int endLine,
boolean ignoreCase) {
final TextAttributes color = editor.getColorsScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
Collection<RangeHighlighter> highlighters = EditorData.getLastHighlights(editor);
if (highlighters == null) {
highlighters = new ArrayList<RangeHighlighter>();
EditorData.setLastHighlights(editor, highlighters);
}
for (TextRange range : findAll(editor, pattern, startLine, endLine, ignoreCase)) {
final RangeHighlighter highlighter = highlightMatch(editor, range.getStartOffset(), range.getEndOffset());
highlighter.setErrorStripeMarkColor(color.getBackgroundColor());
highlighter.setErrorStripeTooltip(pattern);
highlighters.add(highlighter);
}
}
private int findItOffset(@NotNull Editor editor, int startOffset, int count, int dir,
boolean noSmartCase) {
boolean wrap = Options.getInstance().isSet("wrapscan");
TextRange range = findIt(editor, startOffset, count, dir, noSmartCase, wrap, true, true);
if (range == null) {
return -1;
}
//highlightMatch(editor, range.getStartOffset(), range.getEndOffset());
ParsePosition pp = new ParsePosition(0);
int res = range.getStartOffset();
if (lastOffset == null) {
return -1;
}
if (lastOffset.length() == 0) {
return range.getStartOffset();
}
else if (Character.isDigit(lastOffset.charAt(0)) || lastOffset.charAt(0) == '+' || lastOffset.charAt(0) == '-') {
int lineOffset = 0;
if (lastOffset.equals("+")) {
lineOffset = 1;
}
else if (lastOffset.equals("-")) {
lineOffset = -1;
}
else {
if (lastOffset.charAt(0) == '+') {
lastOffset = lastOffset.substring(1);
}
NumberFormat nf = NumberFormat.getIntegerInstance();
pp = new ParsePosition(0);
Number num = nf.parse(lastOffset, pp);
if (num != null) {
lineOffset = num.intValue();
}
}
int line = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int newLine = EditorHelper.normalizeLine(editor, line + lineOffset);
res = VimPlugin.getMotion().moveCaretToLineStart(editor, newLine);
}
else if ("ebs".indexOf(lastOffset.charAt(0)) != -1) {
int charOffset = 0;
if (lastOffset.length() >= 2) {
if ("+-".indexOf(lastOffset.charAt(1)) != -1) {
charOffset = 1;
}
NumberFormat nf = NumberFormat.getIntegerInstance();
pp = new ParsePosition(lastOffset.charAt(1) == '+' ? 2 : 1);
Number num = nf.parse(lastOffset, pp);
if (num != null) {
charOffset = num.intValue();
}
}
int base = range.getStartOffset();
if (lastOffset.charAt(0) == 'e') {
base = range.getEndOffset() - 1;
}
res = Math.max(0, Math.min(base + charOffset, EditorHelper.getFileSize(editor) - 1));
}
int ppos = pp.getIndex();
if (ppos < lastOffset.length() - 1 && lastOffset.charAt(ppos) == ';') {
int flags;
if (lastOffset.charAt(ppos + 1) == '/') {
flags = Command.FLAG_SEARCH_FWD;
}
else if (lastOffset.charAt(ppos + 1) == '?') {
flags = Command.FLAG_SEARCH_REV;
}
else {
return res;
}
if (lastOffset.length() - ppos > 2) {
ppos++;
}
res = search(editor, lastOffset.substring(ppos + 1), res, 1, flags);
return res;
}
else {
return res;
}
}
@Nullable
private TextRange findIt(@NotNull Editor editor, int startOffset, int count, int dir,
boolean noSmartCase, boolean wrap, boolean showMessages, boolean wholeFile) {
TextRange res = null;
if (lastSearch == null || lastSearch.length() == 0) {
return res;
}
/*
int pflags = RE.REG_MULTILINE;
if (shouldIgnoreCase(lastSearch, noSmartCase))
{
pflags |= RE.REG_ICASE;
}
*/
//RE sp;
RegExp sp;
RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T();
regmatch.rmm_ic = shouldIgnoreCase(lastSearch, noSmartCase);
sp = new RegExp();
regmatch.regprog = sp.vim_regcomp(lastSearch, 1);
if (regmatch == null) {
if (logger.isDebugEnabled()) logger.debug("bad pattern: " + lastSearch);
return res;
}
/*
int extra_col = 1;
int startcol = -1;
boolean found = false;
boolean match_ok = true;
LogicalPosition pos = editor.offsetToLogicalPosition(startOffset);
LogicalPosition endpos = null;
//REMatch match = null;
*/
CharacterPosition lpos = EditorHelper.offsetToCharacterPosition(editor, startOffset);
RegExp.lpos_T pos = new RegExp.lpos_T();
pos.lnum = lpos.line;
pos.col = lpos.column;
int found;
int lnum; /* no init to shut up Apollo cc */
//RegExp.regmmatch_T regmatch;
CharPointer ptr;
int matchcol;
int startcol;
RegExp.lpos_T endpos = new RegExp.lpos_T();
int loop;
RegExp.lpos_T start_pos;
boolean at_first_line;
int extra_col = 1;
boolean match_ok;
long nmatched;
//int submatch = 0;
int first_lnum;
int lineCount = EditorHelper.getLineCount(editor);
int startLine = 0;
int endLine = lineCount;
do /* loop for count */ {
start_pos = new RegExp.lpos_T(pos); /* remember start pos for detecting no match */
found = 0; /* default: not found */
at_first_line = true; /* default: start in first line */
if (pos.lnum == -1) /* correct lnum for when starting in line 0 */ {
pos.lnum = 0;
pos.col = 0;
at_first_line = false; /* not in first line now */
}
/*
* Start searching in current line, unless searching backwards and
* we're in column 0.
*/
if (dir == -1 && start_pos.col == 0) {
lnum = pos.lnum - 1;
at_first_line = false;
}
else {
lnum = pos.lnum;
}
int lcount = EditorHelper.getLineCount(editor);
for (loop = 0; loop <= 1; ++loop) /* loop twice if 'wrapscan' set */ {
if (!wholeFile) {
startLine = lnum;
endLine = lnum + 1;
}
for (; lnum >= startLine && lnum < endLine; lnum += dir, at_first_line = false) {
/*
* Look for a match somewhere in the line.
*/
first_lnum = lnum;
nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, 0);
if (nmatched > 0) {
/* match may actually be in another line when using \zs */
lnum += regmatch.startpos[0].lnum;
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum));
startcol = regmatch.startpos[0].col;
endpos = regmatch.endpos[0];
/*
* Forward search in the first line: match should be after
* the start position. If not, continue at the end of the
* match (this is vi compatible) or on the next char.
*/
if (dir == 1 && at_first_line) {
match_ok = true;
/*
* When match lands on a NUL the cursor will be put
* one back afterwards, compare with that position,
* otherwise "/$" will get stuck on end of line.
*/
while ((startcol - (startcol == ptr.strlen() ? 1 : 0)) < (start_pos.col + extra_col)) {
if (nmatched > 1) {
/* end is in next line, thus no match in
* this line */
match_ok = false;
break;
}
matchcol = endpos.col;
/* for empty match: advance one char */
if (matchcol == startcol && ptr.charAt(matchcol) != '\u0000') {
++matchcol;
}
if (ptr.charAt(matchcol) == '\u0000' ||
(nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, matchcol)) == 0) {
match_ok = false;
break;
}
startcol = regmatch.startpos[0].col;
endpos = regmatch.endpos[0];
/* Need to get the line pointer again, a
* multi-line search may have made it invalid. */
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum));
}
if (!match_ok) {
continue;
}
}
if (dir == -1) {
/*
* Now, if there are multiple matches on this line,
* we have to get the last one. Or the last one before
* the cursor, if we're on that line.
* When putting the new cursor at the end, compare
* relative to the end of the match.
*/
match_ok = false;
for (; ; ) {
if (!at_first_line || (regmatch.startpos[0].col + extra_col <= start_pos.col)) {
/* Remember this position, we use it if it's
* the last match in the line. */
match_ok = true;
startcol = regmatch.startpos[0].col;
endpos = regmatch.endpos[0];
}
else {
break;
}
/*
* We found a valid match, now check if there is
* another one after it.
* If vi-compatible searching, continue at the end
* of the match, otherwise continue one position
* forward.
*/
if (nmatched > 1) {
break;
}
matchcol = endpos.col;
/* for empty match: advance one char */
if (matchcol == startcol && ptr.charAt(matchcol) != '\u0000') {
++matchcol;
}
if (ptr.charAt(matchcol) == '\u0000' ||
(nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, matchcol)) == 0) {
break;
}
/* Need to get the line pointer again, a
* multi-line search may have made it invalid. */
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum));
}
/*
* If there is only a match after the cursor, skip
* this match.
*/
if (!match_ok) {
continue;
}
}
pos.lnum = lnum;
pos.col = startcol;
endpos.lnum += first_lnum;
found = 1;
/* Set variables used for 'incsearch' highlighting. */
//search_match_lines = endpos.lnum - (lnum - first_lnum);
//search_match_endcol = endpos.col;
break;
}
//line_breakcheck(); /* stop if ctrl-C typed */
//if (got_int)
// break;
if (loop != 0 && lnum == start_pos.lnum) {
break; /* if second loop, stop where started */
}
}
at_first_line = false;
/*
* stop the search if wrapscan isn't set, after an interrupt and
* after a match
*/
if (!wrap || found != 0) {
break;
}
/*
* If 'wrapscan' is set we continue at the other end of the file.
* If 'shortmess' does not contain 's', we give a message.
* This message is also remembered in keep_msg for when the screen
* is redrawn. The keep_msg is cleared whenever another message is
* written.
*/
if (dir == -1) /* start second loop at the other end */ {
lnum = lineCount - 1;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(top_bot_msg), TRUE);
}
else {
lnum = 0;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(bot_top_msg), TRUE);
}
}
//if (got_int || called_emsg || break_loop)
// break;
}
while (--count > 0 && found != 0); /* stop after count matches or no match */
if (found == 0) /* did not find it */ {
//if ((options & SEARCH_MSG) == SEARCH_MSG)
if (showMessages) {
if (wrap) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, lastSearch));
}
else if (lnum <= 0) {
VimPlugin.showMessage(MessageHelper.message(Msg.E384, lastSearch));
}
else {
VimPlugin.showMessage(MessageHelper.message(Msg.E385, lastSearch));
}
}
return null;
}
//return new TextRange(editor.logicalPositionToOffset(new LogicalPosition(pos.lnum, pos.col)),
// editor.logicalPositionToOffset(new LogicalPosition(endpos.lnum, endpos.col)));
//return new TextRange(editor.logicalPositionToOffset(new LogicalPosition(pos.lnum, 0)) + pos.col,
// editor.logicalPositionToOffset(new LogicalPosition(endpos.lnum, 0)) + endpos.col);
return new TextRange(EditorHelper.characterPositionToOffset(editor, new CharacterPosition(pos.lnum, pos.col)),
EditorHelper.characterPositionToOffset(editor, new CharacterPosition(endpos.lnum, endpos.col)));
}
@NotNull
private RangeHighlighter highlightConfirm(@NotNull Editor editor, int start, int end) {
TextAttributes color = new TextAttributes(
editor.getColorsScheme().getColor(EditorColors.SELECTION_FOREGROUND_COLOR),
editor.getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR),
null, null, 0
);
return editor.getMarkupModel().addRangeHighlighter(start, end, HighlighterLayer.ADDITIONAL_SYNTAX + 2,
color, HighlighterTargetArea.EXACT_RANGE);
}
@NotNull
public static RangeHighlighter highlightMatch(@NotNull Editor editor, int start, int end) {
TextAttributes color = editor.getColorsScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
return editor.getMarkupModel().addRangeHighlighter(start, end, HighlighterLayer.ADDITIONAL_SYNTAX + 1,
color, HighlighterTargetArea.EXACT_RANGE);
}
public void clearSearchHighlight() {
showSearchHighlight = false;
updateHighlight();
}
private static void removeSearchHighlight(@NotNull Editor editor) {
Collection<RangeHighlighter> ehl = EditorData.getLastHighlights(editor);
if (ehl == null) {
return;
}
for (RangeHighlighter rh : ehl) {
editor.getMarkupModel().removeHighlighter(rh);
}
ehl.clear();
EditorData.setLastHighlights(editor, null);
EditorData.setLastSearch(editor, null);
}
public void saveData(@NotNull Element element) {
logger.debug("saveData");
Element search = new Element("search");
if (lastSearch != null) {
search.addContent(createElementWithText("last-search", lastSearch));
}
if (lastOffset != null) {
search.addContent(createElementWithText("last-offset", lastOffset));
}
if (lastPattern != null) {
search.addContent(createElementWithText("last-pattern", lastPattern));
}
if (lastReplace != null) {
search.addContent(createElementWithText("last-replace", lastReplace));
}
if (lastSubstitute != null) {
search.addContent(createElementWithText("last-substitute", lastSubstitute));
}
Element text = new Element("last-dir");
text.addContent(Integer.toString(lastDir));
search.addContent(text);
text = new Element("show-last");
text.addContent(Boolean.toString(showSearchHighlight));
if (logger.isDebugEnabled()) logger.debug("text=" + text);
search.addContent(text);
element.addContent(search);
}
@NotNull
private static Element createElementWithText(@NotNull String name, @NotNull String text) {
return StringHelper.setSafeXmlText(new Element(name), text);
}
public void readData(@NotNull Element element) {
logger.debug("readData");
Element search = element.getChild("search");
if (search == null) {
return;
}
lastSearch = getSafeChildText(search, "last-search");
lastOffset = getSafeChildText(search, "last-offset");
lastPattern = getSafeChildText(search, "last-pattern");
lastReplace = getSafeChildText(search, "last-replace");
lastSubstitute = getSafeChildText(search, "last-substitute");
Element dir = search.getChild("last-dir");
lastDir = Integer.parseInt(dir.getText());
Element show = search.getChild("show-last");
final ListOption vimInfo = Options.getInstance().getListOption(Options.VIMINFO);
final boolean disableHighlight = vimInfo != null && vimInfo.contains("h");
showSearchHighlight = !disableHighlight && Boolean.valueOf(show.getText());
if (logger.isDebugEnabled()) {
logger.debug("show=" + show + "(" + show.getText() + ")");
logger.debug("showSearchHighlight=" + showSearchHighlight);
}
}
@Nullable
private static String getSafeChildText(@NotNull Element element, @NotNull String name) {
final Element child = element.getChild(name);
return child != null ? StringHelper.getSafeXmlText(child) : null;
}
public static class EditorSelectionCheck extends FileEditorManagerAdapter {
/*
public void fileOpened(FileEditorManager fileEditorManager, VirtualFile virtualFile)
{
FileDocumentManager.getInstance().getDocument(virtualFile).addDocumentListener(listener);
}
public void fileClosed(FileEditorManager fileEditorManager, VirtualFile virtualFile)
{
FileDocumentManager.getInstance().getDocument(virtualFile).removeDocumentListener(listener);
}
*/
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
VimPlugin.getSearch().updateHighlight();
}
}
public static class DocumentSearchListener extends DocumentAdapter {
public void documentChanged(@NotNull DocumentEvent event) {
if (!VimPlugin.isEnabled()) {
return;
}
Project[] projs = ProjectManager.getInstance().getOpenProjects();
for (Project proj : projs) {
Editor[] editors = EditorFactory.getInstance().getEditors(event.getDocument(), proj);
for (Editor editor : editors) {
Collection hls = EditorData.getLastHighlights(editor);
if (hls == null) {
continue;
}
int soff = event.getOffset();
int eoff = soff + event.getNewLength();
if (logger.isDebugEnabled()) {
logger.debug("hls=" + hls);
logger.debug("event=" + event);
}
Iterator iter = hls.iterator();
while (iter.hasNext()) {
RangeHighlighter rh = (RangeHighlighter)iter.next();
if (!rh.isValid() || (eoff >= rh.getStartOffset() && soff <= rh.getEndOffset())) {
iter.remove();
editor.getMarkupModel().removeHighlighter(rh);
}
}
int sl = editor.offsetToLogicalPosition(soff).line;
int el = editor.offsetToLogicalPosition(eoff).line;
VimPlugin.getSearch().highlightSearchLines(editor, false, sl, el);
hls = EditorData.getLastHighlights(editor);
if (logger.isDebugEnabled()) {
logger.debug("sl=" + sl + ", el=" + el);
logger.debug("hls=" + hls);
}
}
}
}
}
private enum ReplaceConfirmationChoice {
SUBSTITUTE_THIS,
SUBSTITUTE_LAST,
SKIP,
QUIT,
SUBSTITUTE_ALL,
}
@Nullable private String lastSearch;
@Nullable private String lastPattern;
@Nullable private String lastSubstitute;
@Nullable private String lastReplace;
@Nullable private String lastOffset;
private int lastDir;
private boolean showSearchHighlight = Options.getInstance().isSet("hlsearch");
private boolean do_all = false; /* do multiple substitutions per line */
private boolean do_ask = false; /* ask for confirmation */
private boolean do_error = true; /* if false, ignore errors */
//private boolean do_print = false; /* print last line with subs. */
private char do_ic = 0; /* ignore case flag */
private static final int RE_LAST = 1;
private static final int RE_SEARCH = 2;
private static final int RE_SUBST = 3;
private static final Logger logger = Logger.getInstance(SearchGroup.class.getName());
}
|
package org.innovateuk.ifs.management.controller;
import com.google.common.net.InetAddresses;
import org.innovateuk.ifs.application.service.CompetitionService;
import org.innovateuk.ifs.assessment.service.CompetitionInviteRestService;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.invite.resource.CompetitionInviteResource;
import org.innovateuk.ifs.invite.resource.ExistingUserStagedInviteResource;
import org.innovateuk.ifs.invite.resource.NewUserStagedInviteListResource;
import org.innovateuk.ifs.invite.resource.NewUserStagedInviteResource;
import org.innovateuk.ifs.management.controller.CompetitionManagementAssessorProfileController.AssessorProfileOrigin;
import org.innovateuk.ifs.management.form.FindAssessorsFilterForm;
import org.innovateuk.ifs.management.form.InviteNewAssessorsForm;
import org.innovateuk.ifs.management.form.InviteNewAssessorsRowForm;
import org.innovateuk.ifs.management.model.InviteAssessorsFindModelPopulator;
import org.innovateuk.ifs.management.model.InviteAssessorsInviteModelPopulator;
import org.innovateuk.ifs.management.model.InviteAssessorsOverviewModelPopulator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static org.innovateuk.ifs.util.BackLinkUtil.buildOriginQueryString;
import static org.innovateuk.ifs.util.MapFunctions.asMap;
/**
* This controller will handle all Competition Management requests related to inviting assessors to a Competition.
*/
@Controller
@RequestMapping("/competition/{competitionId}/assessors")
@PreAuthorize("hasAnyAuthority('comp_admin','project_finance')")
public class CompetitionManagementInviteAssessorsController {
private static final String FILTER_FORM_ATTR_NAME = "filterForm";
private static final String FORM_ATTR_NAME = "form";
@Autowired
private CompetitionService competitionService;
@Autowired
private CompetitionInviteRestService competitionInviteRestService;
@Autowired
private InviteAssessorsFindModelPopulator inviteAssessorsFindModelPopulator;
@Autowired
private InviteAssessorsInviteModelPopulator inviteAssessorsInviteModelPopulator;
@Autowired
private InviteAssessorsOverviewModelPopulator inviteAssessorsOverviewModelPopulator;
@RequestMapping(method = RequestMethod.GET)
public String assessors(@PathVariable("competitionId") long competitionId) {
return format("redirect:/competition/%s/assessors/find", competitionId);
}
@RequestMapping(value = "/find", method = RequestMethod.GET)
public String find(Model model,
@Valid @ModelAttribute(FILTER_FORM_ATTR_NAME) FindAssessorsFilterForm filterForm,
@SuppressWarnings("unused") BindingResult bindingResult,
@PathVariable("competitionId") long competitionId,
@RequestParam(defaultValue = "0") int page,
@RequestParam MultiValueMap<String, String> queryParams) {
return doViewFind(model, competitionId, page, filterForm.getInnovationArea(), queryParams);
}
@RequestMapping(value = "/find", params = {"add"}, method = RequestMethod.POST)
public String addInviteFromFindView(Model model,
@PathVariable("competitionId") long competitionId,
@RequestParam("add") String email,
@RequestParam(defaultValue = "0") int page,
@RequestParam Optional<Long> innovationArea) {
inviteUser(email, competitionId).getSuccessObjectOrThrowException();
return redirectToFind(competitionId, page, innovationArea);
}
@RequestMapping(value = "/find", params = {"remove"}, method = RequestMethod.POST)
public String removeInviteFromFindView(Model model,
@PathVariable("competitionId") long competitionId,
@RequestParam("remove") String email,
@RequestParam(defaultValue = "0") int page,
@RequestParam Optional<Long> innovationArea) {
deleteInvite(email, competitionId).getSuccessObjectOrThrowException();
return redirectToFind(competitionId, page, innovationArea);
}
private String redirectToFind(long competitionId, int page, Optional<Long> innovationArea) {
UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/competition/{competitionId}/assessors/find")
.queryParam("page", page);
innovationArea.ifPresent(innovationAreaId -> builder.queryParam("innovationArea", innovationAreaId));
return "redirect:" + builder.buildAndExpand(asMap("competitionId", competitionId))
.toUriString();
}
@RequestMapping(value = "/invite", method = RequestMethod.GET)
public String invite(Model model,
@PathVariable("competitionId") long competitionId,
@ModelAttribute(FORM_ATTR_NAME) InviteNewAssessorsForm form,
@RequestParam MultiValueMap<String, String> queryParams
) {
if (form.getInvites().isEmpty()) {
form.getInvites().add(new InviteNewAssessorsRowForm());
}
return doViewInvite(model, competitionId, queryParams);
}
@RequestMapping(value = "/invite", params = {"remove"}, method = RequestMethod.POST)
public String removeInviteFromInviteView(Model model,
@PathVariable("competitionId") long competitionId,
@RequestParam(name = "remove") String email,
@RequestParam MultiValueMap<String, String> queryParams,
@ModelAttribute(FORM_ATTR_NAME) InviteNewAssessorsForm form) {
deleteInvite(email, competitionId);
return invite(model, competitionId, form, queryParams);
}
@RequestMapping(value = "/invite", params = {"addNewUser"}, method = RequestMethod.POST)
public String addNewUserToInviteView(Model model,
@PathVariable("competitionId") long competitionId,
@RequestParam MultiValueMap<String, String> queryParams,
@ModelAttribute(FORM_ATTR_NAME) InviteNewAssessorsForm form) {
form.getInvites().add(new InviteNewAssessorsRowForm());
form.setVisible(true);
return invite(model, competitionId, form, queryParams);
}
@RequestMapping(value = "/invite", params = {"removeNewUser"}, method = RequestMethod.POST)
public String removeNewUserFromInviteView(Model model,
@PathVariable("competitionId") long competitionId,
@ModelAttribute(FORM_ATTR_NAME) InviteNewAssessorsForm form,
@RequestParam(name = "removeNewUser") int position,
@RequestParam MultiValueMap<String, String> queryParams) {
form.getInvites().remove(position);
form.setVisible(true);
return invite(model, competitionId, form, queryParams);
}
@RequestMapping(value = "/invite", params = {"inviteNewUsers"}, method = RequestMethod.POST)
public String inviteNewsUsersFromInviteView(Model model,
@PathVariable("competitionId") long competitionId,
@RequestParam MultiValueMap<String, String> queryParams,
@Valid @ModelAttribute(FORM_ATTR_NAME) InviteNewAssessorsForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler) {
form.setVisible(true);
return validationHandler.failNowOrSucceedWith(
() -> invite(model, competitionId, form, queryParams),
() -> {
RestResult<Void> restResult = competitionInviteRestService.inviteNewUsers(
newInviteFormToResource(form, competitionId), competitionId
);
return validationHandler.addAnyErrors(restResult)
.failNowOrSucceedWith(
() -> invite(model, competitionId, form, queryParams),
() -> format("redirect:/competition/%s/assessors/invite", competitionId)
);
}
);
}
@RequestMapping(value = "/overview", method = RequestMethod.GET)
public String overview(Model model,
@PathVariable("competitionId") long competitionId,
@RequestParam MultiValueMap<String, String> queryParams) {
CompetitionResource competition = competitionService.getById(competitionId);
model.addAttribute("model", inviteAssessorsOverviewModelPopulator.populateModel(competition));
model.addAttribute("originQuery", buildOriginQueryString(AssessorProfileOrigin.ASSESSOR_OVERVIEW, queryParams));
return "assessors/overview";
}
private ServiceResult<CompetitionInviteResource> inviteUser(String email, long competitionId) {
return competitionInviteRestService.inviteUser(new ExistingUserStagedInviteResource(email, competitionId)).toServiceResult();
}
private ServiceResult<Void> deleteInvite(String email, long competitionId) {
return competitionInviteRestService.deleteInvite(email, competitionId).toServiceResult();
}
private String doViewFind(Model model,
long competitionId,
int page,
Optional<Long> innovationArea,
MultiValueMap<String, String> queryParams) {
CompetitionResource competition = competitionService.getById(competitionId);
String originQuery = buildOriginQueryString(AssessorProfileOrigin.ASSESSOR_FIND, queryParams);
model.addAttribute("model", inviteAssessorsFindModelPopulator.populateModel(competition, page, innovationArea, originQuery));
model.addAttribute("originQuery", originQuery);
return "assessors/find";
}
private String doViewInvite(Model model, long competitionId, MultiValueMap<String, String> queryParams) {
CompetitionResource competition = competitionService.getById(competitionId);
model.addAttribute("model", inviteAssessorsInviteModelPopulator.populateModel(competition));
model.addAttribute("originQuery", buildOriginQueryString(AssessorProfileOrigin.ASSESSOR_INVITE, queryParams));
return "assessors/invite";
}
private NewUserStagedInviteListResource newInviteFormToResource(InviteNewAssessorsForm form, long competitionId) {
List<NewUserStagedInviteResource> invites = form.getInvites().stream()
.map(newUserInvite -> new NewUserStagedInviteResource(
newUserInvite.getEmail(),
competitionId,
newUserInvite.getName(),
form.getSelectedInnovationArea()
))
.collect(Collectors.toList());
return new NewUserStagedInviteListResource(invites);
}
}
|
package com.pcache.DO.timeseries;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import com.pcache.exceptions.PCacheException;
/**
* The FixedTimeseries class allows another take on handling timeseries data.
* This is modelled on Arrays and hence inserts are a bit costlier but then
* selects are super fast.
*
* The only downside to having something like an array based representation is
* the fact that one has to deal with gaps in the data and doing "between"
* operations takes up a lot of understanding. The current implementation will
* "try" to solve this problem by asking for the "ticks" from the user itself.
* This will allow us to pre-fill the array with nulls so that the gaps are
* handled in a better fashion. This approach however isn't tested. There ought
* to be places that i'm overlooking.
*
* The storing of ticks gives us an advantage that we don't need to store the
* timeseries data in itself. Storing the starting timestamp along with the
* ticks should be enough since seeking to a point would be a simple offset
* operation.
*
* This also however means that for every kind of data, the NULL values might
* differ. We require a value that we prefill that will indicate to you that
* a particular data point is a NULL point.
*
* @param <T> the Type of data to store
*/
public class FixedTimeseries<T>
{
private long _startingTimestamp;
private long _endingTimestamp;
private long _tick;
private T _null;
private ArrayList<T> _dataPoints;
public FixedTimeseries(ArrayList<String> timestamps, ArrayList<T> dataPoints,
String tickStr, T nullValue) throws PCacheException {
if (timestamps.size() != dataPoints.size()) {
throw new PCacheException("Timestamps and datapoints should be of" +
"the same length");
}
String startingTimestamp = timestamps.get(0);
String endingTimestamp = timestamps.get(timestamps.size()-1);
this._startingTimestamp = ISO8601toMilis(startingTimestamp);
this._endingTimestamp = ISO8601toMilis(endingTimestamp);
this._dataPoints = new ArrayList<>();
this._tick = parseTickString(tickStr);
this._null = nullValue;
fillNULLs(this._startingTimestamp, this._endingTimestamp, this._null);
fillPoints(timestamps, dataPoints);
}
private long ISO8601toMilis(String timestamp) {
DateTimeFormatter ISO8601Formatter = ISODateTimeFormat.dateTime();
return ISO8601Formatter.parseDateTime(timestamp).getMillis();
}
private void fillPoints(ArrayList<String> timestamps, ArrayList<T> dataPoints) {
for (int i=0;i<timestamps.size();i++) {
String timestamp = timestamps.get(i);
T dataPoint = dataPoints.get(i);
long timestampInMilis = ISO8601toMilis(timestamp);
int index = (int)((timestampInMilis - this._startingTimestamp)
/this._tick);
this._dataPoints.set(index, dataPoint);
}
}
private void fillNULLs(long from, long to, T nullValue) {
long currentTimestamp = from;
while (currentTimestamp <= to) {
this._dataPoints.add(nullValue);
currentTimestamp = currentTimestamp + this._tick;
}
}
/**
* Parse a tick string and return the no. of miliseconds in that tick.
* Eg: 1D is 1 Day. 1 Day contains 86400000 miliseconds.
*
* @param tickStr the string representing the no. of ticks between timestamps
* in the array.
*
* The following units are acceptable:
* d: Day,
* m: Month,
* y: Year,
* h: Hour,
* M: Minute,
* s: Second.
*
* @return no. of miliseconds in the tick string.
* @throws PCacheException
*/
private long parseTickString(String tickStr) throws PCacheException {
Pattern pattern = Pattern.compile("([0-9]+)([dmyHMs])$");
Matcher matcher = pattern.matcher(tickStr);
int tickDuration = 1;
String tickUnit = "d";
if (matcher.groupCount() != 2) {
throw new PCacheException("Invalid format for tick");
}
if (matcher.matches()) {
tickDuration = Integer.parseInt(matcher.group(1));
tickUnit = matcher.group(2);
}
if (tickUnit.equals("m") || tickUnit.equals("y")) {
throw new PCacheException("Tick value in months or years not " +
"supported yet");
}
long milisInSecond = 1000;
long milisInMinute = milisInSecond * 60;
long milisInHour = milisInMinute * 60;
long milisInDay = milisInHour * 24;
switch(tickUnit) {
case "s":
return (tickDuration * milisInSecond);
case "M":
return (tickDuration * milisInMinute);
case "h":
return (tickDuration * milisInHour);
case "d":
return (tickDuration * milisInDay);
default:
throw new PCacheException("Tick format not supported");
}
}
}
|
package com.speakingfish.common.function;
public interface Creator<R, P> extends Mapper<R, P>{
//R create(P params);
}
|
package im.actor.crypto.box;
import im.actor.crypto.IntegrityException;
import im.actor.crypto.primitives.aes.AESFastEngine;
import im.actor.crypto.primitives.digest.SHA256;
import im.actor.crypto.primitives.kuznechik.KuznechikFastEngine;
import im.actor.crypto.primitives.padding.PKCS7Padding;
import im.actor.crypto.primitives.streebog.Streebog256;
import im.actor.crypto.primitives.util.ByteStrings;
/**
* Encrypted Actor Box. Encrypted and HMACed with AES-128-CBC-HMAC-SHA256 and then again
* with Kuznechik-128-CBC-HMAC-Streebog256. Cipher Text is padded with PKCS#7.
*
* @author Steve Kite (steve@actor.im)
*/
public class ActorBox {
/**
* Opening Encrypted box
*
* @param header plain-text header of a box
* @param cipherText encrypted content
* @param key Box key
* @return plain-text content
* @throws IntegrityException
*/
public static byte[] openBox(byte[] header, byte[] cipherText, ActorBoxKey key) throws IntegrityException {
CBCHmacBox aesCipher =
new CBCHmacBox(new AESFastEngine(key.getKeyAES()), new SHA256(), key.getMacAES());
CBCHmacBox kuzCipher =
new CBCHmacBox(new KuznechikFastEngine(key.getKeyKuz()), new Streebog256(), key.getMacKuz());
byte[] kuzPackage = aesCipher.decryptPackage(header,
ByteStrings.substring(cipherText, 0, 16),
ByteStrings.substring(cipherText, 16, cipherText.length - 16));
byte[] plainText = kuzCipher.decryptPackage(header,
ByteStrings.substring(kuzPackage, 0, 16),
ByteStrings.substring(kuzPackage, 16, kuzPackage.length - 16));
// Validating padding
int paddingSize = plainText[plainText.length - 1] & 0xFF;
if (paddingSize < 0 || paddingSize >= 16) {
throw new IntegrityException("Incorrect padding!");
}
PKCS7Padding padding = new PKCS7Padding();
if (!padding.validate(plainText, plainText.length - 1 - paddingSize, paddingSize)) {
throw new IntegrityException("Padding does not match!");
}
return ByteStrings.substring(plainText, 0, plainText.length - 1 - paddingSize);
}
/**
* Closing encrypted box
*
* @param header plain-text header of a box
* @param plainText plain-text content
* @param random32 32 random bytes
* @param key Box key
* @return encrypted context
* @throws IntegrityException
*/
public static byte[] closeBox(byte[] header, byte[] plainText, byte[] random32, ActorBoxKey key) throws IntegrityException {
CBCHmacBox aesCipher = new CBCHmacBox(new AESFastEngine(key.getKeyAES()), new SHA256(), key.getMacAES());
CBCHmacBox kuzCipher = new CBCHmacBox(new KuznechikFastEngine(key.getKeyKuz()), new Streebog256(), key.getMacKuz());
// Calculating padding
int paddingSize = (plainText.length + 1) % 16;
byte[] paddedPlainText = new byte[plainText.length + 1 + paddingSize];
ByteStrings.write(paddedPlainText, 0, plainText, 0, plainText.length);
paddedPlainText[paddedPlainText.length - 1] = (byte) paddingSize;
PKCS7Padding padding = new PKCS7Padding();
padding.padding(paddedPlainText, plainText.length, paddingSize);
byte[] kuzIv = ByteStrings.substring(random32, 0, 16);
byte[] aesIv = ByteStrings.substring(random32, 16, 16);
byte[] kuzPackage = ByteStrings.merge(kuzIv, kuzCipher.encryptPackage(header, kuzIv, paddedPlainText));
return ByteStrings.merge(aesIv, aesCipher.encryptPackage(header, aesIv, kuzPackage));
}
}
|
package sg.ncl.adapter.deterlab;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import sg.ncl.adapter.deterlab.data.jpa.DeterLabUserRepository;
import sg.ncl.adapter.deterlab.dtos.entities.DeterLabUserEntity;
import sg.ncl.adapter.deterlab.exceptions.*;
import javax.inject.Inject;
@Component
public class AdapterDeterLab {
private DeterLabUserRepository deterLabUserRepository;
private ConnectionProperties properties;
private static final Logger logger = LoggerFactory.getLogger(AdapterDeterLab.class);
@Inject
private RestTemplate restTemplate;
@Inject
public AdapterDeterLab(DeterLabUserRepository repository, ConnectionProperties connectionProperties) {
this.deterLabUserRepository = repository;
this.properties = connectionProperties;
}
/**
* Creates a join project request to Deterlab
* Also creates a new user
* @param jsonString
* @return The Deter userid (randomly generated)
*/
public String joinProjectNewUsers(String jsonString) {
logger.info("Joining project as new user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getJoinProjectNewUsers(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
logger.info("Join project request (new user) submitted to deterlab");
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("join project request new users fail".equals(jsonResult) || !"user is created".equals(jsonResult)) {
throw new JoinProjectException();
}
// Will return the following JSON:
// msg: join project request new users fail
// msg: no user created, uid: xxx
// msg: user is created, uid: xxx
// msg: user not found, uid: xxx
return response.getBody().toString();
}
/**
* Creates a apply project request to Deterlab
* Also creates a new user
* @param jsonString
* @return The Deter userid (randomly generated)
*/
public String applyProjectNewUsers(String jsonString) {
logger.info("Applying new project as new user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApplyProjectNewUsers(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
logger.info("Apply project request (new user) submitted to deterlab");
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("apply project request new users fail".equals(jsonResult) || !"user is created".equals(jsonResult)) {
throw new ApplyNewProjectException();
}
// Will return the following JSON:
// msg: apply project request new users fail
// msg: no user created, uid: xxx
// msg: user is created, uid: xxx
// msg: user not found, uid: xxx
return response.getBody().toString();
}
/**
* Creates a apply project request to Deterlab
* Does not create a new user
* @param jsonString Contains uid, project name, pid, project goals, project web, project organisation, project visibility
*/
public void applyProject(String jsonString) {
logger.info("Applying project as logged on user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApplyProject(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
logger.info("Apply new project request existing users submitted to deterlab: {}", jsonResult);
if (!"apply project request existing users success".equals(jsonResult)) {
throw new ApplyNewProjectException();
}
}
/**
* Creates a join project request to Deterlab
* Does not create a new user
* @param jsonString Contains uid, pid
*/
public void joinProject(String jsonString) {
logger.info("Joining project as logged on user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getJoinProject(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
logger.info("Join project request submitted to deterlab");
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if (!"join project request existing users success".equals(jsonResult)) {
throw new JoinProjectException();
}
}
/**
* Creates a edit user profile request to Deterlab
* @param jsonString Contains uid, password, confirm password
*/
public void updateCredentials(String jsonString) {
logger.info("Updating credentials to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUpdateCredentials(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("password change fail".equals(jsonResult)) {
throw new CredentialsUpdateException();
}
}
@Transactional
public void saveDeterUserIdMapping(String deterUserId, String nclUserId) {
DeterLabUserEntity deterLabUserEntity = new DeterLabUserEntity();
deterLabUserEntity.setNclUserId(nclUserId);
deterLabUserEntity.setDeterUserId(deterUserId);
deterLabUserRepository.save(deterLabUserEntity);
}
@Transactional
public String getDeterUserIdByNclUserId(String nclUserId) {
DeterLabUserEntity deterLabUserEntity = deterLabUserRepository.findByNclUserId(nclUserId);
if (deterLabUserEntity == null) {
throw new UserNotFoundException();
}
return deterLabUserEntity.getDeterUserId();
}
public void createExperiment(String jsonString) {
logger.info("Creating experiment to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getCreateExperiment(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("experiment create fail ns file error".equals(jsonResult)) {
throw new NSFileParseException();
} else if ("experiment create fail exp name already in use".equals(jsonResult)) {
throw new ExpNameAlreadyExistsException();
} else if (!"experiment create success".equals(jsonResult)) {
throw new AdapterDeterlabConnectException();
}
}
/**
* Creates a start experiment request to Deterlab
* @implNote must return the entire response body as realization service needs to store the experiment report to transmit back to UI
* @param jsonString Contains pid, eid, and deterlab userId
* @return a experiment report if the experiment is started successfully and active, otherwise a "experiment start fail" is return
*/
public String startExperiment(String jsonString) {
logger.info("Start experiment - {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.startExperiment(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException(e.getMessage());
}
logger.info("Start experiment request submitted to deterlab");
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("experiment start fail".equals(jsonResult)) {
logger.warn("Fail to start experiment at deterlab {}", jsonString);
throw new ExpStartException();
} else if (!"experiment start success".equals(jsonResult)) {
logger.warn("Start experiment connection error {}", jsonString);
throw new AdapterDeterlabConnectException();
}
logger.info("Start experiment request success at deterlab", response.getBody().toString());
return response.getBody().toString();
}
public String stopExperiment(String jsonString) {
logger.info("Stop experiment - {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.stopExperiment(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String deleteExperiment(String jsonString) {
logger.info("Delete experiment - {} at {} : {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.deleteExperiment(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
/**
* Retrieves the experiment status from Deterlab
* @param jsonString Contains eid and pid
* @return the status of the experiment, a "no experiment found" if the request fails
*/
public String getExperimentStatus(String jsonString) {
logger.info("Get experiment status - {} at {} : {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getExpStatus(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException(e.getMessage());
}
logger.info("Get experiment status request submitted to deterlab");
return response.getBody().toString();
}
public String approveJoinRequest(String jsonString) {
// for team leaders to accept join request
logger.info("Approving join request to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getApproveJoinRequest(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String rejectJoinRequest(String jsonString) {
// for team leaders to reject join request
logger.info("Rejecting join request to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getRejectJoinRequest(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String approveProject(String jsonString) {
// for ncl admins to approve teams
logger.info("Approving team to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getApproveProject(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String rejectProject(String jsonString) {
// for ncl admins to reject teams
logger.info("Rejecting team to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getRejectProject(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
}
|
package com.brentvatne.exoplayer;
import android.annotation.TargetApi;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.TextRenderer;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.SubtitleView;
import java.util.List;
@TargetApi(16)
public final class ExoPlayerView extends FrameLayout {
private final View surfaceView;
private final View shutterView;
private final SubtitleView subtitleLayout;
private final AspectRatioFrameLayout layout;
private final ComponentListener componentListener;
private SimpleExoPlayer player;
public ExoPlayerView(Context context) {
this(context, null);
}
public ExoPlayerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ExoPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
boolean useTextureView = false;
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
componentListener = new ComponentListener();
FrameLayout.LayoutParams aspectRatioParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
aspectRatioParams.gravity = Gravity.CENTER;
layout = new AspectRatioFrameLayout(context);
layout.setLayoutParams(aspectRatioParams);
shutterView = new View(getContext());
shutterView.setLayoutParams(params);
shutterView.setBackgroundColor(ContextCompat.getColor(context, android.R.color.black));
subtitleLayout = new SubtitleView(context);
subtitleLayout.setLayoutParams(params);
subtitleLayout.setUserDefaultStyle();
subtitleLayout.setUserDefaultTextSize();
View view = useTextureView ? new TextureView(context) : new SurfaceView(context);
view.setLayoutParams(params);
surfaceView = view;
layout.addView(surfaceView, 0, params);
layout.addView(shutterView, 1, params);
layout.addView(subtitleLayout, 2, params);
addViewInLayout(layout, 0, aspectRatioParams);
}
/**
* Set the {@link SimpleExoPlayer} to use. The {@link SimpleExoPlayer#setTextOutput} and
* {@link SimpleExoPlayer#setVideoListener} method of the player will be called and previous
* assignments are overridden.
*
* @param player The {@link SimpleExoPlayer} to use.
*/
public void setPlayer(SimpleExoPlayer player) {
if (this.player == player) {
return;
}
if (this.player != null) {
this.player.setTextOutput(null);
this.player.setVideoListener(null);
this.player.removeListener(componentListener);
this.player.setVideoSurface(null);
}
this.player = player;
shutterView.setVisibility(VISIBLE);
if (player != null) {
if (surfaceView instanceof TextureView) {
player.setVideoTextureView((TextureView) surfaceView);
} else if (surfaceView instanceof SurfaceView) {
player.setVideoSurfaceView((SurfaceView) surfaceView);
}
player.setVideoListener(componentListener);
player.addListener(componentListener);
player.setTextOutput(componentListener);
}
}
/**
* Sets the resize mode which can be of value {@link ResizeMode.Mode}
*
* @param resizeMode The resize mode.
*/
public void setResizeMode(@ResizeMode.Mode int resizeMode) {
if (layout.getResizeMode() != resizeMode) {
layout.setResizeMode(resizeMode);
post(measureAndLayout);
}
}
/**
* Get the view onto which video is rendered. This is either a {@link SurfaceView} (default)
* or a {@link TextureView} if the {@code use_texture_view} view attribute has been set to true.
*
* @return either a {@link SurfaceView} or a {@link TextureView}.
*/
public View getVideoSurfaceView() {
return surfaceView;
}
private final Runnable measureAndLayout = new Runnable() {
@Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
private void updateForCurrentTrackSelections() {
if (player == null) {
return;
}
TrackSelectionArray selections = player.getCurrentTrackSelections();
for (int i = 0; i < selections.length; i++) {
if (player.getRendererType(i) == C.TRACK_TYPE_VIDEO && selections.get(i) != null) {
// Video enabled so artwork must be hidden. If the shutter is closed, it will be opened in
// onRenderedFirstFrame().
return;
}
}
// Video disabled so the shutter must be closed.
shutterView.setVisibility(VISIBLE);
}
private final class ComponentListener implements SimpleExoPlayer.VideoListener,
TextRenderer.Output, ExoPlayer.EventListener {
// TextRenderer.Output implementation
@Override
public void onCues(List<Cue> cues) {
subtitleLayout.onCues(cues);
}
// SimpleExoPlayer.VideoListener implementation
@Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
boolean isInitialRatio = layout.getAspectRatio() == 0;
layout.setAspectRatio(height == 0 ? 1 : (width * pixelWidthHeightRatio) / height);
// React native workaround for measuring and layout on initial load.
if (isInitialRatio) {
post(measureAndLayout);
}
}
@Override
public void onRenderedFirstFrame() {
shutterView.setVisibility(INVISIBLE);
}
// ExoPlayer.EventListener implementation
@Override
public void onLoadingChanged(boolean isLoading) {
// Do nothing.
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
// Do nothing.
}
@Override
public void onPlayerError(ExoPlaybackException e) {
// Do nothing.
}
@Override
public void onPositionDiscontinuity() {
// Do nothing.
}
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
// Do nothing.
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
updateForCurrentTrackSelections();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.