use of au.gov.asd.tac.constellation.plugins.PluginException in project constellation by constellation-app.
the class LayerByTimePlugin method read.
@Override
public void read(final GraphReadMethods rg, final PluginInteraction interaction, final PluginParameters parameters) throws PluginException, InterruptedException {
// We have the dtAttr from the original wg: we should have been passed the label, but never mind.
// We need to get the label from the original, so we can get the dtAttr for the copy.
final String dtAttrOrig = parameters.getParameters().get(DATETIME_ATTRIBUTE_PARAMETER_ID).getStringValue();
if (dtAttrOrig == null) {
interaction.notify(PluginNotificationLevel.ERROR, "A date-time attribute must be specified.");
return;
}
final int dtAttrOrigId = rg.getAttribute(GraphElementType.TRANSACTION, dtAttrOrig);
if (dtAttrOrigId == Graph.NOT_FOUND) {
interaction.notify(PluginNotificationLevel.ERROR, "A valid date-time attribute must be specified.");
return;
}
Graph copy;
try {
final Plugin copyGraphPlugin = PluginRegistry.get(InteractiveGraphPluginRegistry.COPY_TO_NEW_GRAPH);
final PluginParameters copyParams = copyGraphPlugin.createParameters();
copyParams.getParameters().get(CopyToNewGraphPlugin.NEW_SCHEMA_NAME_PARAMETER_ID).setStringValue(rg.getSchema().getFactory().getName());
copyParams.getParameters().get(CopyToNewGraphPlugin.COPY_ALL_PARAMETER_ID).setBooleanValue(true);
copyParams.getParameters().get(CopyToNewGraphPlugin.COPY_KEYS_PARAMETER_ID).setBooleanValue(false);
PluginExecution.withPlugin(copyGraphPlugin).withParameters(copyParams).executeNow(rg);
copy = (Graph) copyParams.getParameters().get(CopyToNewGraphPlugin.NEW_GRAPH_OUTPUT_PARAMETER_ID).getObjectValue();
} catch (final PluginException ex) {
copy = null;
LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
}
if (copy == null) {
// The copy failed, drop out now.
return;
}
final Attribute dt = new GraphAttribute(rg, dtAttrOrigId);
final WritableGraph wgcopy = copy.getWritableGraph("Layer by time", true);
try {
final int dtAttr = wgcopy.getAttribute(GraphElementType.TRANSACTION, dt.getName());
final boolean useIntervals = parameters.getParameters().get(LAYER_BY_PARAMETER_ID).getStringValue().equals(INTERVAL_METHOD);
final ZonedDateTime[] startEnd = parameters.getParameters().get(DATE_RANGE_PARAMETER_ID).getDateTimeRangeValue().getZonedStartEnd();
final ZonedDateTime start = startEnd[0];
final ZonedDateTime end = startEnd[1];
final boolean isTransactionLayers = parameters.getParameters().get(TRANSACTION_AS_LAYER_PARAMETER_ID).getBooleanValue();
// Establish new attributes.
// Create and store graph attributes.
final LayerName defaultName = new LayerName(Graph.NOT_FOUND, "Default");
final int timeLayerAttr = wgcopy.addAttribute(GraphElementType.TRANSACTION, LayerNameAttributeDescription.ATTRIBUTE_NAME, LAYER_NAME, "time layer", defaultName, null);
wgcopy.addAttribute(GraphElementType.GRAPH, IntegerAttributeDescription.ATTRIBUTE_NAME, NLAYERS, "The number of layers to layer by time", 1, null);
final int txColorAttr = wgcopy.getAttribute(GraphElementType.TRANSACTION, "color");
final int txGuideline = wgcopy.addAttribute(GraphElementType.TRANSACTION, BooleanAttributeDescription.ATTRIBUTE_NAME, "layer_guideline", "This transaction is a layer guideline", false, null);
final ConstellationColor guidelineColor = ConstellationColor.getColorValue(0.25F, 0.25F, 0.25F, 1F);
wgcopy.addAttribute(GraphElementType.VERTEX, IntegerAttributeDescription.ATTRIBUTE_NAME, ORIGINAL_ID_LABEL, "Original Node Id", -1, null);
final List<Float> values = new ArrayList<>();
final Map<Integer, List<Float>> remappedLayers = new HashMap<>();
final Map<Integer, String> displayNames = new HashMap<>();
if (useIntervals) {
final int intervalUnit = LAYER_INTERVALS.get(parameters.getParameters().get(UNIT_PARAMETER_ID).getStringValue());
final int intervalAmount = parameters.getParameters().get(AMOUNT_PARAMETER_ID).getIntegerValue();
buildIntervals(wgcopy, values, remappedLayers, displayNames, dtAttr, start.toInstant(), end.toInstant(), intervalUnit, intervalAmount);
} else {
final int calendarUnit = BIN_CALENDAR_UNITS.get(parameters.getParameters().get(UNIT_PARAMETER_ID).getStringValue());
final int binAmount = parameters.getParameters().get(AMOUNT_PARAMETER_ID).getIntegerValue();
buildBins(wgcopy, values, remappedLayers, displayNames, dtAttr, start.toInstant(), end.toInstant(), calendarUnit, binAmount);
}
final boolean keepTxColors = parameters.getParameters().get(KEEP_TX_COLORS_PARAMETER_ID).getBooleanValue();
final boolean drawTxGuides = parameters.getParameters().get(DRAW_TX_GUIDES_PARAMETER_ID).getBooleanValue();
// Modify the copied graph to show our layers.
int z = 0;
float step = getWidth(wgcopy) / values.size();
for (final Entry<Integer, List<Float>> entry : remappedLayers.entrySet()) {
for (final Entry<Float, List<Integer>> currentLayer : transactionLayers.entrySet()) {
if (entry.getValue().contains(currentLayer.getKey())) {
for (final int txId : currentLayer.getValue()) {
final float origLayer = currentLayer.getKey();
int newLayer = 0;
if (entry.getValue().contains(origLayer)) {
// Overwrite value
newLayer = entry.getKey();
}
final LayerName dn = new LayerName(newLayer, displayNames.get(newLayer));
wgcopy.setObjectValue(timeLayerAttr, txId, dn);
final float normLayer = newLayer / (remappedLayers.keySet().size() * 1F);
if (!keepTxColors) {
final Color heatmap = new Color(Color.HSBtoRGB((1 - normLayer) * 2F / 3F, 0.5F, 1));
final ConstellationColor color = ConstellationColor.getColorValue(heatmap.getRed() / 255F, heatmap.getGreen() / 255F, heatmap.getBlue() / 255F, 1F);
wgcopy.setObjectValue(txColorAttr, txId, color);
}
if (isTransactionLayers) {
transactionsAsLayers(wgcopy, txId, z, step);
} else {
nodesAsLayers(wgcopy, txId, newLayer);
}
}
}
}
if (isTransactionLayers) {
srcVxMap = dstVxMap;
dstVxMap = new HashMap<>();
z += step;
}
}
// Remove any outstanding transactions flagged for deletion
for (int txId = txToDelete.nextSetBit(0); txId >= 0; txId = txToDelete.nextSetBit(txId + 1)) {
wgcopy.removeTransaction(txId);
}
// Get rid of all of the nodes that don't have any transactions.
// By definition, the duplicates will have transactions between them, including the original layer
// (because we just deleted transactions that belong in different layers, leaving only the transactions
// that belong in the original layer).
final List<Integer> vertices = new ArrayList<>();
for (int position = 0; position < wgcopy.getVertexCount(); position++) {
final int vertexId = wgcopy.getVertex(position);
final int nTx = wgcopy.getVertexTransactionCount(vertexId);
if (nTx == 0) {
vertices.add(vertexId);
}
}
vertices.stream().forEach(wgcopy::removeVertex);
if (drawTxGuides) {
interaction.setProgress(5, 6, "Draw guide lines", false);
// We have to do this after the "remove node without transactions" step because we're adding more transactions.
if (!isTransactionLayers && remappedLayers.keySet().size() > 1) {
nodeIdToLayers.keySet().stream().forEach(origNodeId -> {
int prevNodeId = -1;
final BitSet layers = nodeIdToLayers.get(origNodeId);
for (int layer = layers.nextSetBit(0); layer >= 0; layer = layers.nextSetBit(layer + 1)) {
final int nodeId = layer == 0 ? origNodeId : nodeDups.get(String.format("%s/%s", origNodeId, layer));
if (prevNodeId != -1) {
final int sTxId = wgcopy.addTransaction(prevNodeId, nodeId, false);
wgcopy.setBooleanValue(txGuideline, sTxId, true);
wgcopy.setObjectValue(txColorAttr, sTxId, guidelineColor);
final LayerName dn = new LayerName(1107, "Guideline");
wgcopy.setObjectValue(timeLayerAttr, sTxId, dn);
}
prevNodeId = nodeId;
}
});
}
}
} finally {
wgcopy.commit();
}
}
use of au.gov.asd.tac.constellation.plugins.PluginException in project constellation by constellation-app.
the class TestParametersPlugin method query.
@Override
protected RecordStore query(final RecordStore query, final PluginInteraction interaction, final PluginParameters parameters) throws PluginException {
final int sleep = parameters.getParameters().get(SLEEP_PARAMETER_ID).getIntegerValue();
for (int i = 0; i < sleep; i++) {
LOGGER.log(Level.INFO, "sleep {0}/{1}", new Object[] { i, sleep });
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
Thread.currentThread().interrupt();
}
}
LOGGER.log(Level.INFO, "slept for {0} seconds", sleep);
LOGGER.log(Level.INFO, "parameters: {0}", parameters);
LOGGER.log(Level.INFO, "GraphElementType: {0}", parameters.getSingleChoice(ELEMENT_TYPE_PARAMETER_ID));
final LocalDate localDate = parameters.getLocalDateValue(LOCAL_DATE_PARAMETER_ID);
LOGGER.log(Level.INFO, "localdate: {0} ", localDate);
if (localDate != null) {
final Calendar cal = LocalDateParameterType.toCalendar(localDate);
LOGGER.log(Level.INFO, String.format("toDate: [%s] [%04d-%02d-%02d]", cal, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)));
LOGGER.log(Level.INFO, String.format("fields: [%04d-%02d-%02d]", localDate.get(ChronoField.YEAR), localDate.get(ChronoField.MONTH_OF_YEAR), localDate.get(ChronoField.DAY_OF_MONTH)));
}
final MultiChoiceParameterValue planets = parameters.getMultiChoiceValue(PLANETS_PARAMETER_ID);
planets.getChoices().stream().forEach(planet -> LOGGER.log(Level.INFO, "Planet: {0}", planet));
LOGGER.log(Level.INFO, "==== begin string values");
parameters.getParameters().values().stream().forEach(param -> LOGGER.log(Level.INFO, "String {0}: \"{1}\"", new Object[] { param.getName(), param.getStringValue() }));
LOGGER.log(Level.INFO, "==== end string values");
final File outputDir = DataAccessPreferenceUtilities.getDataAccessResultsDir();
if (outputDir != null) {
final String fnam = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss")) + "-testChainer.txt";
final File fout = new File(outputDir, fnam);
try (final PrintWriter writer = new PrintWriter(fout, StandardCharsets.UTF_8.name())) {
parameters.getParameters().values().stream().forEach(param -> writer.printf("%s: '%s'", param.getName(), param.getStringValue()));
} catch (final FileNotFoundException | UnsupportedEncodingException ex) {
Exceptions.printStackTrace(ex);
}
}
final List<String> keys = query.keys();
while (query.next()) {
keys.stream().forEach(key -> LOGGER.log(Level.INFO, String.format("%-20s: %s", key, query.get(key))));
LOGGER.log(Level.INFO, "--");
}
final boolean crash = parameters.getBooleanValue(CRASH_PARAMETER_ID);
if (crash) {
throw new RuntimeException("Simulated plugin failure");
}
try {
interaction.setProgress(1, 0, String.format("Pretended to add %d node(s), modify %d node(s)", r.nextInt(100) + 1, r.nextInt(100) + 1), false);
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
Thread.currentThread().interrupt();
}
final String queryName = parameters.getStringValue(CoreGlobalParameters.QUERY_NAME_PARAMETER_ID);
LOGGER.log(Level.INFO, "query name: {0}", queryName);
final DateTimeRange dtr = parameters.getDateTimeRangeValue(CoreGlobalParameters.DATETIME_RANGE_PARAMETER_ID);
final ZonedDateTime[] dtrStartEnd = dtr.getZonedStartEnd();
LOGGER.log(Level.INFO, "range: (zdt) {0} .. {1}", new Object[] { dtrStartEnd[0], dtrStartEnd[1] });
LOGGER.log(Level.INFO, "range: (zdt) {0} .. {1}", new Object[] { DateTimeFormatter.ISO_INSTANT.format(dtrStartEnd[0]), DateTimeFormatter.ISO_INSTANT.format(dtrStartEnd[1]) });
final String interactionLevel = parameters.getParameters().get(INTERACTION_PARAMETER_ID).getStringValue();
final PluginNotificationLevel pnInteractionLevel;
if (interactionLevel != null) {
switch(interactionLevel) {
case DEBUG:
pnInteractionLevel = PluginNotificationLevel.DEBUG;
break;
case INFO:
pnInteractionLevel = PluginNotificationLevel.INFO;
break;
case WARNING:
pnInteractionLevel = PluginNotificationLevel.WARNING;
break;
case ERROR:
pnInteractionLevel = PluginNotificationLevel.ERROR;
break;
case FATAL:
pnInteractionLevel = PluginNotificationLevel.FATAL;
break;
default:
pnInteractionLevel = null;
break;
}
if (pnInteractionLevel != null) {
interaction.notify(pnInteractionLevel, "Interaction from plugin");
}
}
final String exceptionLevel = parameters.getParameters().get(LEVEL_PARAMETER_ID).getStringValue();
final PluginNotificationLevel pnExceptionLevel;
if (exceptionLevel != null) {
switch(exceptionLevel) {
case DEBUG:
pnExceptionLevel = PluginNotificationLevel.DEBUG;
break;
case INFO:
pnExceptionLevel = PluginNotificationLevel.INFO;
break;
case WARNING:
pnExceptionLevel = PluginNotificationLevel.WARNING;
break;
case ERROR:
pnExceptionLevel = PluginNotificationLevel.ERROR;
break;
case FATAL:
pnExceptionLevel = PluginNotificationLevel.FATAL;
break;
default:
pnExceptionLevel = null;
break;
}
if (pnExceptionLevel != null) {
throw new PluginException(pnExceptionLevel, "Exception thrown from plugin");
}
}
// Add nodes containing global query parameters
final RecordStore results = new GraphRecordStore();
results.add();
results.set(GraphRecordStoreUtilities.SOURCE + AnalyticConcept.VertexAttribute.RAW, "name1@domain1.com");
results.set(GraphRecordStoreUtilities.SOURCE + AnalyticConcept.VertexAttribute.TYPE, "Email");
results.set(GraphRecordStoreUtilities.SOURCE + AnalyticConcept.VertexAttribute.COMMENT, queryName);
results.set(GraphRecordStoreUtilities.SOURCE + TemporalConcept.VertexAttribute.LAST_SEEN, DateTimeFormatter.ISO_INSTANT.format(dtrStartEnd[0]).replace("Z", ".000Z"));
results.set(GraphRecordStoreUtilities.DESTINATION + AnalyticConcept.VertexAttribute.RAW, "name2@domain2.com");
results.set(GraphRecordStoreUtilities.DESTINATION + AnalyticConcept.VertexAttribute.TYPE, "Email");
results.set(GraphRecordStoreUtilities.DESTINATION + AnalyticConcept.VertexAttribute.COMMENT, queryName);
results.set(GraphRecordStoreUtilities.DESTINATION + TemporalConcept.VertexAttribute.LAST_SEEN, DateTimeFormatter.ISO_INSTANT.format(dtrStartEnd[1]).replace("Z", ".000Z"));
results.set(GraphRecordStoreUtilities.TRANSACTION + AnalyticConcept.TransactionAttribute.COMMENT, parameters.toString());
return results;
}
use of au.gov.asd.tac.constellation.plugins.PluginException in project constellation by constellation-app.
the class TestParametersPluginNGTest method testQueryException5.
/**
* Test of query method, of class TestParametersPlugin. Tests throwing of
* fatal pluginException
*/
@Test(expectedExceptions = PluginException.class)
public void testQueryException5() throws Exception {
System.out.println("throw pluginexception5");
final TestParametersPlugin instance = new TestParametersPlugin();
final PluginParameters result = instance.createParameters();
final GraphRecordStore recordStore = new GraphRecordStore();
final DefaultPluginInteraction interaction = new DefaultPluginInteraction(null, null);
// Set plugin query name here before execution
result.getParameters().get(CoreGlobalParameters.QUERY_NAME_PARAMETER_ID).setStringValue("TESTPARAMETERSPLUGIN");
// Set plugin parameters here before execution
result.getParameters().get(TestParametersPlugin.LEVEL_PARAMETER_ID).setStringValue("Fatal");
try {
instance.query(recordStore, interaction, result);
} catch (final PluginException ex) {
assertEquals(ex.getNotificationLevel(), PluginNotificationLevel.FATAL);
throw ex;
}
}
use of au.gov.asd.tac.constellation.plugins.PluginException in project constellation by constellation-app.
the class TestParametersPluginNGTest method testQueryException4.
/**
* Test of query method, of class TestParametersPlugin. Tests throwing of
* error pluginException
*/
@Test(expectedExceptions = PluginException.class)
public void testQueryException4() throws Exception {
System.out.println("throw pluginexception4");
final TestParametersPlugin instance = new TestParametersPlugin();
final PluginParameters result = instance.createParameters();
final GraphRecordStore recordStore = new GraphRecordStore();
final DefaultPluginInteraction interaction = new DefaultPluginInteraction(null, null);
// Set plugin query name here before execution
result.getParameters().get(CoreGlobalParameters.QUERY_NAME_PARAMETER_ID).setStringValue("TESTPARAMETERSPLUGIN");
// Set plugin parameters here before execution
result.getParameters().get(TestParametersPlugin.LEVEL_PARAMETER_ID).setStringValue("Error");
try {
instance.query(recordStore, interaction, result);
} catch (final PluginException ex) {
assertEquals(ex.getNotificationLevel(), PluginNotificationLevel.ERROR);
throw ex;
}
}
use of au.gov.asd.tac.constellation.plugins.PluginException in project constellation by constellation-app.
the class SaveResultsFileWriterNGTest method testWriteRecordStoreInvalidDataAccessResultsDir.
/**
* Test of writeRecordStore method for case when
* DataAccessPreferenceKeys.getDataAccessResultsDir() returns an invalid
* directory. Because directory (and hence generated file path) is invalid,
* and exception will be thrown and
* ConstellationLoggerHelper.exportPropertyBuilder called with appropriate
* ERROR status.
*/
@Test
public void testWriteRecordStoreInvalidDataAccessResultsDir() {
Plugin plugin = new ExampleClass();
TabularRecordStore tabularRecordStore = new TabularRecordStore();
mockedDataAccessPreferenceKeys.when(() -> DataAccessPreferenceUtilities.getDataAccessResultsDir()).thenReturn(new File("/BADDIR/"));
mockedConstellationLoggerHelper.when(() -> ConstellationLoggerHelper.exportPropertyBuilder(any(), any(), any(), any())).thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
File passedFile = (File) args[2];
constellationLoggerHelperStatus = (String) args[3];
// Ensure the file was not created
fileCreated = passedFile.exists();
if (fileCreated) {
passedFile.delete();
}
// Return properties (which are ignored)
Properties properties = new Properties();
return properties;
});
try {
SaveResultsFileWriter.writeRecordStore(plugin, tabularRecordStore);
// Execution should not make it this far, an invalid file should result in an exception.
Assert.fail("PluginException is expected.");
} catch (Exception ex) {
mockedRecordStoreUtilities.verify(times(0), () -> RecordStoreUtilities.toCsv(Mockito.any(), Mockito.any()));
Assert.assertFalse(fileCreated, "Record store file was not created.");
Assert.assertEquals(constellationLoggerHelperStatus, ConstellationLoggerHelper.FAILURE, "ConstellationLoggerHelper passed status = FAILURE.");
}
}
Aggregations