scala.util.Either Java Examples
The following examples show how to use
scala.util.Either.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SMRecordWriter.java From spliceengine with GNU Affero General Public License v3.0 | 7 votes |
@Override public void write(RowLocation rowLocation, Either<Exception, ExecRow> value) throws IOException, InterruptedException { if (value.isLeft()) { Exception e = value.left().get(); // failure failure = true; SpliceLogUtils.error(LOG,"Error Reading",e); throw new IOException(e); } assert value.isRight(); ExecRow execRow = value.right().get(); try { if (!initialized) { initialized = true; tableWriter.open(); } tableWriter.write(execRow); } catch (Exception se) { SpliceLogUtils.error(LOG,"Error Writing",se); failure = true; throw new IOException(se); } }
Example #2
Source File: LimitRateByRejection.java From ditto with Eclipse Public License 2.0 | 7 votes |
@Override public Iterable<Either<E, A>> apply(final A element) { final long currentTime = System.currentTimeMillis(); if (currentTime - previousWindow >= windowSizeMillis) { previousWindow = currentTime; counter = 1; } else { counter++; } final Either<E, A> result; if (counter <= maxElements) { result = Right.apply(element); } else { result = Left.apply(errorReporter.apply(element)); } return Collections.singletonList(result); }
Example #3
Source File: HaskellRunConfigurationBase.java From intellij-haskforce with Apache License 2.0 | 6 votes |
protected void requireCabalVersionMinimum(double minimumVersion, @NotNull String errorMessage) throws RuntimeConfigurationException { final HaskellBuildSettings buildSettings = HaskellBuildSettings.getInstance(getProject()); final String cabalPath = buildSettings.getCabalPath(); if (cabalPath.isEmpty()) { throw new RuntimeConfigurationError("Path to cabal is not set."); } GeneralCommandLine cabalCmdLine = new GeneralCommandLine(cabalPath, "--numeric-version"); Either<ExecUtil.ExecError, String> result = ExecUtil.readCommandLine(cabalCmdLine); if (result.isLeft()) { //noinspection ThrowableResultOfMethodCallIgnored ExecUtil.ExecError e = EitherUtil.unsafeGetLeft(result); NotificationUtil.displaySimpleNotification( NotificationType.ERROR, getProject(), "cabal", e.getMessage() ); throw new RuntimeConfigurationError("Failed executing cabal to check its version: " + e.getMessage()); } final String out = EitherUtil.unsafeGetRight(result); final Matcher m = EXTRACT_CABAL_VERSION_REGEX.matcher(out); if (!m.find()) { throw new RuntimeConfigurationError("Could not parse cabal version: '" + out + "'"); } final Double actualVersion = Double.parseDouble(m.group(1)); if (actualVersion < minimumVersion) { throw new RuntimeConfigurationError(errorMessage); } }
Example #4
Source File: SparkUpdateDataSetWriter.java From spliceengine with GNU Affero General Public License v3.0 | 6 votes |
public SparkUpdateDataSetWriter(JavaPairRDD<K, Either<Exception, V>> rdd, OperationContext operationContext, Configuration conf, long heapConglom, int[] formatIds, int[] columnOrdering, int[] pkCols, FormatableBitSet pkColumns, String tableVersion, ExecRow execRowDefinition, FormatableBitSet heapList, int[] updateCounts){ this.rdd=rdd; this.operationContext=operationContext; this.conf=conf; this.heapConglom=heapConglom; this.formatIds=formatIds; this.columnOrdering=columnOrdering; this.pkCols=pkCols; this.pkColumns=pkColumns; this.tableVersion=tableVersion; this.execRowDefinition=execRowDefinition; this.heapList=heapList; this.updateCounts=updateCounts; }
Example #5
Source File: EntityDiscoveryService.java From incubator-atlas with Apache License 2.0 | 6 votes |
private GremlinQuery toGremlinQuery(String query, int limit, int offset) throws AtlasBaseException { QueryParams params = validateSearchParams(limit, offset); Either<NoSuccess, Expression> either = QueryParser.apply(query, params); if (either.isLeft()) { throw new AtlasBaseException(DISCOVERY_QUERY_FAILED, query); } Expression expression = either.right().get(); Expression validExpression = QueryProcessor.validate(expression); GremlinQuery gremlinQuery = new GremlinTranslator(validExpression, graphPersistenceStrategy).translate(); if (LOG.isDebugEnabled()) { LOG.debug("Translated Gremlin Query: {}", gremlinQuery.queryStr()); } return gremlinQuery; }
Example #6
Source File: MessageMappingProcessorActor.java From ditto with Eclipse Public License 2.0 | 6 votes |
private static Either<RuntimeException, AuthorizationContext> getAuthorizationContextAsEither( final ExternalMessage externalMessage) { return externalMessage.getAuthorizationContext() .filter(authorizationContext -> !authorizationContext.isEmpty()) .<Either<RuntimeException, AuthorizationContext>>map(authorizationContext -> { try { return new Right<>(PlaceholderFilter.applyHeadersPlaceholderToAuthContext(authorizationContext, externalMessage.getHeaders())); } catch (final RuntimeException e) { return new Left<>(e); } }) .orElseGet(() -> new Left<>(new IllegalArgumentException("No nonempty authorization context is available"))); }
Example #7
Source File: QueryProcessorTest.java From incubator-atlas with Apache License 2.0 | 6 votes |
private ValidatingTypeCache findTypeLookupsDuringQueryParsing(String query) throws AtlasException { TypeSystem typeSystem = TypeSystem.getInstance(); ValidatingTypeCache result = new ValidatingTypeCache(); typeSystem.setTypeCache(result); typeSystem.reset(); HierarchicalTypeDefinition<ClassType> hiveTypeDef = createClassTypeDef("hive_db", "", ImmutableSet.<String>of(), createRequiredAttrDef("name", DataTypes.STRING_TYPE), createRequiredAttrDef("tableCount", DataTypes.INT_TYPE) ); typeSystem.defineClassType(hiveTypeDef); Either<Parsers.NoSuccess, Expressions.Expression> either = QueryParser.apply(query, null); Expressions.Expression expression = either.right().get(); QueryProcessor.validate(expression); return result; }
Example #8
Source File: HTableRecordWriter.java From spliceengine with GNU Affero General Public License v3.0 | 6 votes |
@Override public void write(byte[] rowKey, Either<Exception, KVPair> value) throws IOException, InterruptedException { if (value.isLeft()) { Exception e = value.left().get(); // failure failure = true; SpliceLogUtils.error(LOG,"Error Reading",e); throw new IOException(e); } assert value.isRight(); KVPair kvPair = value.right().get(); try { if (!initialized) { initialized = true; tableWriter.open(); } tableWriter.write(kvPair); } catch (Exception se) { SpliceLogUtils.error(LOG,"Error Writing",se); failure = true; throw new IOException(se); } }
Example #9
Source File: HLint.java From intellij-haskforce with Apache License 2.0 | 6 votes |
@NotNull public static Either<ExecError, Problems> parseProblems(final HaskellToolsConsole.Curried toolConsole, final @NotNull String workingDirectory, final @NotNull String path, final @NotNull String flags, final @NotNull HaskellFile haskellFile) { return getVersion(toolConsole, workingDirectory, path).flatMap(version -> { final boolean useJson = version.$greater$eq(HLINT_MIN_VERSION_WITH_JSON_SUPPORT); final String[] params = getParams(haskellFile, useJson); final String fileContents = ApplicationManager.getApplication().runReadAction( (Computable<String>) haskellFile::getText ); return runHlint(toolConsole, workingDirectory, path, flags, fileContents, params).map(stdout -> { toolConsole.writeOutput(stdout); if (useJson) return parseProblemsJson(toolConsole, stdout); return parseProblemsFallback(stdout); }); }); }
Example #10
Source File: HLint.java From intellij-haskforce with Apache License 2.0 | 6 votes |
@NotNull public static Either<Throwable, Problems> parseProblemsJson(@NotNull String stdout) { final Problem[] problems; try { problems = gson.fromJson(stdout, Problem[].class); } catch (JsonSyntaxException e) { return EitherUtil.left( new IllegalStateException( "Unable to decode problem from HLint json output:\n" + e.getMessage() + "\nJSON was: " + stdout, e ) ); } if (problems == null) { return EitherUtil.left( new IllegalStateException( "Unable to decode problem from HLint json output, decoded as null; json was: " + stdout ) ); } return EitherUtil.right(new Problems(problems)); }
Example #11
Source File: SMOutputFormatTest.java From spliceengine with GNU Affero General Public License v3.0 | 6 votes |
@Test public void readExceptionsCauseAbort() throws StandardException, IOException { SparkPairDataSet<ExecRow, ExecRow> dataset = new SparkPairDataSet<>(SpliceSpark.getContextUnsafe().parallelizePairs(tenRows).mapToPair(new FailFunction())); JavaPairRDD<ExecRow, Either<Exception, ExecRow>> rdd = dataset.wrapExceptions(); final Configuration conf=new Configuration(HConfiguration.unwrapDelegate()); TableWriterUtils.serializeInsertTableWriterBuilder(conf, new FakeTableWriterBuilder(false)); conf.setClass(JobContext.OUTPUT_FORMAT_CLASS_ATTR,FakeOutputFormat.class,FakeOutputFormat.class); // workaround for SPARK-21549 on spark-2.2.0 conf.set("mapreduce.output.fileoutputformat.outputdir","/tmp"); File file = File.createTempFile(SMOutputFormatTest.class.getName(), "exception"); file.delete(); file.mkdir(); conf.set("abort.directory", file.getAbsolutePath()); try { rdd.saveAsNewAPIHadoopDataset(conf); Assert.fail("Expected exception"); } catch (Exception se) { Assert.assertTrue("Unexpected exception", se instanceof SparkException); } File[] files = file.listFiles(); Assert.assertTrue("Abort() not called", files.length > 0); }
Example #12
Source File: SMOutputFormatTest.java From spliceengine with GNU Affero General Public License v3.0 | 6 votes |
@Test public void writeExceptionsCauseAbort() throws StandardException, IOException { SparkPairDataSet<RowLocation, ExecRow> dataset = new SparkPairDataSet<>(SpliceSpark.getContextUnsafe().parallelizePairs(tenRows).mapToPair(new ToRowLocationFunction())); JavaPairRDD<RowLocation, Either<Exception, ExecRow>> rdd = dataset.wrapExceptions(); final Configuration conf=new Configuration(HConfiguration.unwrapDelegate()); TableWriterUtils.serializeInsertTableWriterBuilder(conf, new FakeTableWriterBuilder(true)); conf.setClass(JobContext.OUTPUT_FORMAT_CLASS_ATTR, FakeOutputFormat.class, FakeOutputFormat.class); // workaround for SPARK-21549 on spark-2.2.0 conf.set("mapreduce.output.fileoutputformat.outputdir","/tmp"); File file = File.createTempFile(SMOutputFormatTest.class.getName(), "exception"); file.delete(); file.mkdir(); conf.set("abort.directory", file.getAbsolutePath()); try { rdd.saveAsNewAPIHadoopDataset(conf); Assert.fail("Expected exception"); } catch (Exception se) { Assert.assertTrue("Unexpected exception", se instanceof SparkException); } File[] files = file.listFiles(); Assert.assertTrue("Abort() not called", files.length > 0); }
Example #13
Source File: SMOutputFormatTest.java From spliceengine with GNU Affero General Public License v3.0 | 6 votes |
@Test public void abortNotCalled() throws StandardException, IOException { SparkPairDataSet<RowLocation, ExecRow> dataset = new SparkPairDataSet<>(SpliceSpark.getContextUnsafe().parallelizePairs(tenRows).mapToPair(new ToRowLocationFunction())); JavaPairRDD<RowLocation, Either<Exception, ExecRow>> rdd = dataset.wrapExceptions(); final Configuration conf=new Configuration(HConfiguration.unwrapDelegate()); TableWriterUtils.serializeInsertTableWriterBuilder(conf, new FakeTableWriterBuilder(false)); conf.setClass(JobContext.OUTPUT_FORMAT_CLASS_ATTR,FakeOutputFormat.class,FakeOutputFormat.class); // workaround for SPARK-21549 on spark-2.2.0 conf.set("mapreduce.output.fileoutputformat.outputdir","/tmp"); File file = File.createTempFile(SMOutputFormatTest.class.getName(), "noException"); file.delete(); file.mkdir(); conf.set("abort.directory", file.getAbsolutePath()); rdd.saveAsNewAPIHadoopDataset(conf); File[] files = file.listFiles(); Assert.assertEquals("Abort() was called", 0, files.length); }
Example #14
Source File: HLint.java From intellij-haskforce with Apache License 2.0 | 6 votes |
/** * Runs hlintProg with parameters if hlintProg can be executed. */ @NotNull public static Either<ExecError, String> runHlint(HaskellToolsConsole.Curried toolConsole, @NotNull String workingDirectory, @NotNull String hlintProg, @NotNull String hlintFlags, @Nullable String fileContents, @NotNull String... params) { GeneralCommandLine commandLine = new GeneralCommandLine(); commandLine.setWorkDirectory(workingDirectory); commandLine.setExePath(hlintProg); ParametersList parametersList = commandLine.getParametersList(); // Required so that hlint won't report a non-zero exit status for lint issues. // Otherwise, ExecUtil.readCommandLine will return an error. parametersList.add("--no-exit-code"); parametersList.addParametersString(hlintFlags); parametersList.addAll(params); toolConsole.writeInput("Using working directory: " + workingDirectory); toolConsole.writeInput(commandLine.getCommandLineString()); return ExecUtil.readCommandLine(commandLine, fileContents); }
Example #15
Source File: ResumeSource.java From ditto with Eclipse Public License 2.0 | 6 votes |
/** * Create a flow from seeds to either elements or failure with reason and the previous N elements that passed * through the stream before the failure. For maximum information, even elements emitted 2 or more failures ago * are kept in the look-behind queue. * <ul> * <li>Emits when: stream created by {@code resume} emits or fails.</li> * <li>Completes when: a stream created by {@code resume} completes.</li> * <li>Cancels when: downstream cancels.</li> * <li>Fails when: never.</li> * </ul> * * @param resume Creator of a stream of elements from a resumption seed. * @param lookBehind How many elements to keep in memory to create the next seed on failure. * @param <S> Type of seeds. * @param <E> Type of elements. * @return A never-failing flow. */ private static <S, E> Flow<S, Either<FailureWithLookBehind<E>, E>, NotUsed> resumeWithFailuresAppended( final Function<S, Source<E, ?>> resume, final int lookBehind, final Function<Throwable, Optional<Throwable>> resumeOrMapError) { return Flow.<S>create() .flatMapConcat(seed -> resume.apply(seed) .<Envelope<E>>map(Element::new) .concat(Source.single(new EndOfStream<>())) .recoverWithRetries(1, new PFBuilder<Throwable, Graph<SourceShape<Envelope<E>>, NotUsed>>() .matchAny(error -> resumeOrMapError.apply(error) .<Source<Envelope<E>, NotUsed>>map(Source::failed) .orElseGet(() -> Source.single(new Error<>(error))) ) .build()) ) .via(new EndStreamOnEOS<>()) .buffer(1, OverflowStrategy.backpressure()) .statefulMapConcat(() -> new StatefulLookBehindFunction<>(lookBehind)); }
Example #16
Source File: HTableOutputFormat.java From spliceengine with GNU Affero General Public License v3.0 | 6 votes |
@Override public RecordWriter<byte[],Either<Exception, KVPair>> getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { try { assert taskAttemptContext != null && taskAttemptContext.getConfiguration() != null:"configuration passed in is null"; if (outputCommitter == null) getOutputCommitter(taskAttemptContext); DataSetWriterBuilder tableWriter =TableWriterUtils.deserializeTableWriter(taskAttemptContext.getConfiguration()); TxnView childTxn = outputCommitter.getChildTransaction(taskAttemptContext.getTaskAttemptID()); if (childTxn == null) throw new IOException("child transaction lookup failed"); tableWriter.txn(childTxn); return new HTableRecordWriter(tableWriter.buildTableWriter(), outputCommitter); } catch (Exception e) { throw new IOException(e); } }
Example #17
Source File: ScalaFeelEngine.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
public <T> T evaluateSimpleExpression(String expression, VariableContext variableContext) { CustomContext context = new CustomContext() { public VariableProvider variableProvider() { return new ContextVariableWrapper(variableContext); } }; Either either = feelEngine.evalExpression(expression, context); if (either instanceof Right) { Right right = (Right) either; return (T) right.value(); } else { Left left = (Left) either; Failure failure = (Failure) left.value(); String message = failure.message(); throw LOGGER.evaluationException(message); } }
Example #18
Source File: DecisionByMetricStage.java From ditto with Eclipse Public License 2.0 | 6 votes |
private static Either<CreditDecision, Long> getMaxTimerNanosFromStatusInfo(final StatusInfo statusInfo) { if (statusInfo.getDetails().size() != 1) { return left("StatusInfo has non-singleton detail: " + statusInfo); } final JsonValue detail = statusInfo.getDetails().get(0).getMessage(); if (!detail.isObject()) { return left("StatusDetailMessage is not an object: " + statusInfo); } final List<Long> maxTimerNanos = MongoMetrics.fromJson(detail.asObject()).getMaxTimerNanos(); // extract max long value final Optional<Long> max = maxTimerNanos.stream().max(Long::compareTo); if (!max.isPresent()) { return left("Field maxTimerNanos not found or empty in status detail: " + statusInfo); } return new Right<>(max.get()); }
Example #19
Source File: WebSocketRoute.java From ditto with Eclipse Public License 2.0 | 5 votes |
private Graph<FanOutShape2<String, Either<StreamControlMessage, Signal>, DittoRuntimeException>, NotUsed> selectStreamControlOrSignal( final JsonSchemaVersion version, final CharSequence connectionCorrelationId, final AuthorizationContext connectionAuthContext, final DittoHeaders additionalHeaders, final ProtocolAdapter adapter) { final ProtocolMessageExtractor protocolMessageExtractor = new ProtocolMessageExtractor(connectionAuthContext, connectionCorrelationId); return Filter.multiplexByEither(cmdString -> { final Optional<StreamControlMessage> streamControlMessage = protocolMessageExtractor.apply(cmdString); if (streamControlMessage.isPresent()) { return Right.apply(Left.apply(streamControlMessage.get())); } else { try { final Signal<?> signal = buildSignal(cmdString, version, connectionCorrelationId, connectionAuthContext, additionalHeaders, adapter, headerTranslator); return Right.apply(Right.apply(signal)); } catch (final DittoRuntimeException dre) { // This is a client error usually; log at level DEBUG without stack trace. LOGGER.withCorrelationId(dre) .debug("DittoRuntimeException building signal from <{}>: <{}>", cmdString, dre); return Left.apply(dre); } catch (final Exception throwable) { LOGGER.warn("Error building signal from <{}>: {}: <{}>", cmdString, throwable.getClass().getSimpleName(), throwable.getMessage()); final DittoRuntimeException dittoRuntimeException = GatewayInternalErrorException.newBuilder() .cause(throwable) .build(); return Left.apply(dittoRuntimeException); } } }); }
Example #20
Source File: DecisionByMetricStage.java From ditto with Eclipse Public License 2.0 | 5 votes |
private static Either<CreditDecision, Long> getMaxTimerNanos(final List<StatusInfo> statusInfos) { long maxTimerNanos = 0L; for (final StatusInfo statusInfo : statusInfos) { final Either<CreditDecision, Long> statusTimerValue = getMaxTimerNanosFromStatusInfo(statusInfo); if (statusTimerValue.isLeft()) { return statusTimerValue; } else { maxTimerNanos = Math.max(maxTimerNanos, statusTimerValue.right().get()); } } return new Right<>(maxTimerNanos); }
Example #21
Source File: Filter.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Multiplex messages by an Either flow. * * @param eitherFlow the filter implemented as a flow from messages to Either of accepted or rejected messages. * @param <A> type of all messages. * @param <B> type of accepted messages. * @param <C> type of rejected messages. * @return graph with 1 inlet for messages and 2 outlets, the first outlet for messages mapped to the right * and the second outlet for messages mapped to the left. */ public static <A, B, C> Graph<FanOutShape2<A, B, C>, NotUsed> multiplexByEitherFlow( final Graph<FlowShape<A, Either<C, B>>, ?> eitherFlow) { return GraphDSL.create(builder -> { final FlowShape<A, Either<C, B>> testPredicate = builder.add(eitherFlow); final UniformFanOutShape<Either<C, B>, Either<C, B>> broadcast = builder.add(Broadcast.create(2, true)); final FlowShape<Either<C, B>, B> filterTrue = builder.add(Flow.<Either<C, B>>create() .filter(Either::isRight) .map(either -> either.right().get())); final FlowShape<Either<C, B>, C> filterFalse = builder.add(Flow.<Either<C, B>>create() .filter(Either::isLeft) .map(either -> either.left().get())); builder.from(testPredicate.out()).toInlet(broadcast.in()); builder.from(broadcast.out(0)).toInlet(filterTrue.in()); builder.from(broadcast.out(1)).toInlet(filterFalse.in()); return new FanOutShape2<>(testPredicate.in(), filterTrue.out(), filterFalse.out()); }); }
Example #22
Source File: ResumeSource.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Override public Iterable<Either<FailureWithLookBehind<E>, E>> apply(final Envelope<E> param) { if (param instanceof Element) { final E element = ((Element<E>) param).element; enqueue(element); return Collections.singletonList(new Right<>(element)); } else if (param instanceof Error) { final List<E> finalElementsCopy = new ArrayList<>(finalElements); final Throwable error = ((Error<E>) param).error; return Collections.singletonList(new Left<>(new FailureWithLookBehind<>(finalElementsCopy, error))); } else { // param is EOS; this is not supposed to happen. throw new IllegalStateException("End-of-stream encountered; stream should be complete already!"); } }
Example #23
Source File: WebSocketRoute.java From ditto with Eclipse Public License 2.0 | 5 votes |
private Graph<SinkShape<Either<StreamControlMessage, Signal>>, ?> getStreamControlOrSignalSink() { return Sink.foreach(either -> { final Object streamControlMessageOrSignal = either.isLeft() ? either.left().get() : either.right().get(); streamingActor.tell(streamControlMessageOrSignal, ActorRef.noSender()); }); }
Example #24
Source File: PathCommand.java From rug-cli with GNU General Public License v3.0 | 5 votes |
@Command public void run(@Argument(index = 1, defaultValue = "") String expression, @Option("change-dir") String rootName, @Option("values") boolean values) { Collection<GraphNode> treeNodes = new ProgressReportingOperationRunner<Collection<GraphNode>>( "Evaluating path expression against project").run((indicator) -> { PathExpression pathExpression = PathExpressionParser$.MODULE$ .parseString(expression); File root = FileUtils.createProjectRoot(rootName); ArtifactSource source = ArtifactSourceUtils.createArtifactSource(root); ExpressionEngine pxe = new PathExpressionEngine(); TreeNode pmv = new ProjectMutableView(new EmptyArtifactSource(""), source); Either<String, Seq<GraphNode>> result = pxe.evaluate(pmv, pathExpression, DefaultExecutionContext$.MODULE$, Option$.MODULE$.apply(null)); if (result.isLeft()) { throw new CommandException( String.format("Evaluating path expression failed:\n\n%s", result.left().get()), "path"); } return JavaConverters.asJavaCollectionConverter(result.right().get()) .asJavaCollection(); }); printResult(expression, values, treeNodes); }
Example #25
Source File: CucumberReportAdapterTest.java From openCypher with Apache License 2.0 | 5 votes |
@Override public Either<ExecutionFailed, CypherValueRecords> cypher(String query, Map<String, CypherValue> params, QueryType meta) { if (query.contains("foo()")) { return new Left<>(new ExecutionFailed("SyntaxError", "compile time", "UnknownFunction", null)); } else if (query.startsWith("RETURN ")) { String result = query.replace("RETURN ", ""); System.out.println("Producing some output " + result); List<String> header = new Set.Set1<>(result).toList(); Map<String, String> row = new Map.Map1<>(result, result); List<Map<String, String>> rows = new Set.Set1<>(row).toList(); return new Right<>(new StringRecords(header, rows).asValueRecords()); } else { return new Right<>(CypherValueRecords.empty()); } }
Example #26
Source File: SMOutputFormat.java From spliceengine with GNU Affero General Public License v3.0 | 5 votes |
@Override public RecordWriter<RowLocation,Either<Exception, ExecRow>> getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { try { if (outputCommitter == null) getOutputCommitter(taskAttemptContext); DataSetWriterBuilder dsWriter = TableWriterUtils.deserializeTableWriter(taskAttemptContext.getConfiguration()); TxnView childTxn = outputCommitter.getChildTransaction(taskAttemptContext.getTaskAttemptID()); if (childTxn == null) throw new IOException("child transaction lookup failed"); dsWriter.txn(outputCommitter.getChildTransaction(taskAttemptContext.getTaskAttemptID())); return new SMRecordWriter(dsWriter.buildTableWriter(), outputCommitter); } catch (Exception e) { throw new IOException(e); } }
Example #27
Source File: ExecUtil.java From intellij-haskforce with Apache License 2.0 | 5 votes |
@NotNull public static Either<ExecError, String> readCommandLine(@Nullable String workingDirectory, @NotNull String command, @NotNull String[] params, @Nullable String input) { GeneralCommandLine commandLine = new GeneralCommandLine(command); if (workingDirectory != null) { commandLine.setWorkDirectory(workingDirectory); } commandLine.addParameters(params); return readCommandLine(commandLine, input); }
Example #28
Source File: GraphBackedDiscoveryService.java From incubator-atlas with Apache License 2.0 | 5 votes |
private Expressions.Expression parseQuery(String dslQuery, QueryParams queryParams) throws DiscoveryException { Either<Parsers.NoSuccess, Expressions.Expression> either = QueryParser.apply(dslQuery, queryParams); if (either.isRight()) { Expressions.Expression expression = either.right().get(); Expressions.Expression validatedExpression = QueryProcessor.validate(expression); return validatedExpression; } else { throw new DiscoveryException("Invalid expression : " + dslQuery + ". " + either.left()); } }
Example #29
Source File: ExceptionWrapperFunction.java From spliceengine with GNU Affero General Public License v3.0 | 5 votes |
@Override public Tuple2<K, ? extends Either<Exception, V>> next() { if (caught != null) { consumed = true; return new Tuple2<>(null, new Left<Exception, V>(caught)); } try { Tuple2<K, V> result = delegate.next(); return new Tuple2<>(result._1(), new Right<Exception, V>(result._2())); } catch (Exception e) { consumed = true; return new Tuple2<>(null, new Left<Exception, V>(e)); } }
Example #30
Source File: GhcMod.java From intellij-haskforce with Apache License 2.0 | 5 votes |
@Nullable public static String exec(@NotNull Project project, @NotNull String workingDirectory, @NotNull String ghcModPath, @NotNull String command, @NotNull String ghcModFlags, String... params) { if (!validateGhcVersion(project, ghcModPath, ghcModFlags)) return null; GeneralCommandLine commandLine = new GeneralCommandLine(ghcModPath); GhcModUtil.updateEnvironment(project, commandLine.getEnvironment()); ParametersList parametersList = commandLine.getParametersList(); parametersList.addParametersString(ghcModFlags); parametersList.add(command); parametersList.addAll(params); // setWorkDirectory is deprecated but is needed to work with IntelliJ 13 which does not have withWorkDirectory. commandLine.setWorkDirectory(workingDirectory); // Make sure we can actually see the errors. commandLine.setRedirectErrorStream(true); HaskellToolsConsole toolConsole = HaskellToolsConsole.get(project); toolConsole.writeInput(ToolKey.GHC_MOD_KEY, "Using working directory: " + workingDirectory); toolConsole.writeInput(ToolKey.GHC_MOD_KEY, commandLine.getCommandLineString()); Either<ExecUtil.ExecError, String> result = ExecUtil.readCommandLine(commandLine); if (result.isLeft()) { //noinspection ThrowableResultOfMethodCallIgnored ExecUtil.ExecError e = EitherUtil.unsafeGetLeft(result); toolConsole.writeError(ToolKey.GHC_MOD_KEY, e.getMessage()); NotificationUtil.displayToolsNotification( NotificationType.ERROR, project, "ghc-mod", e.getMessage() ); return null; } String out = EitherUtil.unsafeGetRight(result); toolConsole.writeOutput(ToolKey.GHC_MOD_KEY, out); return out; }