Example usage for com.google.common.base CaseFormat UPPER_CAMEL

List of usage examples for com.google.common.base CaseFormat UPPER_CAMEL

Introduction

In this page you can find the example usage for com.google.common.base CaseFormat UPPER_CAMEL.

Prototype

CaseFormat UPPER_CAMEL

To view the source code for com.google.common.base CaseFormat UPPER_CAMEL.

Click Source Link

Document

Java and C++ class naming convention, e.g., "UpperCamel".

Usage

From source file:org.jooby.Renderer.java

/**
 * @return Renderer's name./*from   w w w  .j av  a  2  s.  c o  m*/
 */
default String name() {
    String name = getClass().getSimpleName().replace("renderer", "").replace("render", "");
    return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);
}

From source file:org.ballerinalang.composer.service.ballerina.parser.service.BallerinaParserService.java

public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs)
        throws InvocationTargetException, IllegalAccessException {
    if (node == null) {
        return JsonNull.INSTANCE;
    }/* ww  w . j  av  a  2  s .c om*/
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream()
            .flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();

    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }

    /* Virtual props */

    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }

    for (Method m : methods) {
        String name = m.getName();

        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }

        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }

        Object prop = m.invoke(node);

        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if (node.getKind() == NodeKind.LITERAL && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }

        if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) {
            JsonArray attachmentPoints = new JsonArray();
            ((BLangAnnotation) node).getAttachPoints().stream().map(AttachPoint::getValue)
                    .map(JsonPrimitive::new).forEach(attachmentPoints::add);
            nodeJson.add("attachmentPoints", attachmentPoints);
        }
        // TODO: revisit logic for user defined types
        //            if (node.getKind() == NodeKind.USER_DEFINED_TYPE && jsonName.equals("typeName")) {
        //                IdentifierNode typeNode = (IdentifierNode) prop;
        //                Node structNode;
        //                if (typeNode.getValue().startsWith("$anonStruct$") &&
        //                        (structNode = anonStructs.remove(typeNode.getValue())) != null) {
        //                    JsonObject anonStruct = generateJSON(structNode, anonStructs).getAsJsonObject();
        //                    anonStruct.addProperty("anonStruct", true);
        //                    nodeJson.add("anonStruct", anonStruct);
        //                    continue;
        //                }
        //            }

        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }

        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangFunction
                                && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs));
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }

            /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());

            /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop instanceof int[]) {
            int[] intArray = ((int[]) prop);
            JsonArray intArrayPropJson = new JsonArray();
            nodeJson.add(jsonName, intArrayPropJson);
            for (int intProp : intArray) {
                intArrayPropJson.add(intProp);
            }
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
            String message = "Node " + node.getClass().getSimpleName() + " contains unknown type prop: "
                    + jsonName + " of type " + prop.getClass();
            logger.error(message);
        }
    }
    return nodeJson;
}

From source file:org.roda.core.plugins.plugins.ingest.DefaultIngestPlugin.java

private void sendNotification(ModelService model)
        throws GenericException, RequestNotValidException, NotFoundException, AuthorizationDeniedException {
    Job job = PluginHelper.getJob(this, model);
    JobStats jobStats = job.getJobStats();

    String emails = PluginHelper.getStringFromParameters(this,
            getPluginParameter(RodaConstants.PLUGIN_PARAMS_EMAIL_NOTIFICATION));

    if (StringUtils.isNotBlank(emails)) {
        List<String> emailList = new ArrayList<>(Arrays.asList(emails.split("\\s*,\\s*")));
        Notification notification = new Notification();
        String outcome = PluginState.SUCCESS.toString();

        if (jobStats.getSourceObjectsProcessedWithFailure() > 0) {
            outcome = PluginState.FAILURE.toString();
        }//from   ww w  .j  ava  2s.  c o m

        String subject = RodaCoreFactory.getRodaConfigurationAsString("core", "notification", "ingest_subject");
        if (StringUtils.isNotBlank(subject)) {
            subject += outcome;
        } else {
            subject = outcome;
        }

        notification.setSubject(subject);
        notification.setFromUser(this.getClass().getSimpleName());
        notification.setRecipientUsers(emailList);

        Map<String, Object> scopes = new HashMap<>();
        scopes.put("outcome", outcome);
        scopes.put("type",
                CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, job.getPluginType().toString()));
        scopes.put("sips", jobStats.getSourceObjectsCount());
        scopes.put("success", jobStats.getSourceObjectsProcessedWithSuccess());
        scopes.put("failed", jobStats.getSourceObjectsProcessedWithFailure());
        scopes.put("name", job.getName());
        scopes.put("creator", job.getUsername());

        SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        scopes.put("start", parser.format(job.getStartDate()));

        long duration = (new Date().getTime() - job.getStartDate().getTime()) / 1000;
        scopes.put("duration", duration + " seconds");
        model.createNotification(notification,
                new EmailNotificationProcessor(RodaConstants.INGEST_EMAIL_TEMPLATE, scopes));
    }

    String httpNotifications = RodaCoreFactory.getRodaConfiguration()
            .getString(RodaConstants.NOTIFICATION_HTTP_ENDPOINT, "");
    if (StringUtils.isNotBlank(httpNotifications)) {
        Notification notification = new Notification();
        String outcome = PluginState.SUCCESS.toString();

        if (jobStats.getSourceObjectsProcessedWithFailure() > 0) {
            outcome = PluginState.FAILURE.toString();
        }

        notification.setSubject("RODA ingest process finished - " + outcome);
        notification.setFromUser(this.getClass().getSimpleName());
        notification.setRecipientUsers(Arrays.asList(httpNotifications));
        Map<String, Object> scope = new HashMap<>();
        scope.put(HTTPNotificationProcessor.JOB_KEY, job);
        model.createNotification(notification, new HTTPNotificationProcessor(httpNotifications, scope));
    }

}

From source file:gobblin.runtime.AbstractJobLauncher.java

@Override
public void launchJob(JobListener jobListener) throws JobException {
    String jobId = this.jobContext.getJobId();
    final JobState jobState = this.jobContext.getJobState();

    try {/*from ww  w  .j  a  v a2  s . c o m*/
        MDC.put(ConfigurationKeys.JOB_NAME_KEY, this.jobContext.getJobName());
        MDC.put(ConfigurationKeys.JOB_KEY_KEY, this.jobContext.getJobKey());
        TimingEvent launchJobTimer = this.eventSubmitter
                .getTimingEvent(TimingEvent.LauncherTimings.FULL_JOB_EXECUTION);

        try (Closer closer = Closer.create()) {
            notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_PREPARE,
                    new JobListenerAction() {
                        @Override
                        public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                            jobListener.onJobPrepare(jobContext);
                        }
                    });

            if (this.jobContext.getSemantics() == DeliverySemantics.EXACTLY_ONCE) {

                // If exactly-once is used, commit sequences of the previous run must be successfully compelted
                // before this run can make progress.
                executeUnfinishedCommitSequences(jobState.getJobName());
            }

            TimingEvent workUnitsCreationTimer = this.eventSubmitter
                    .getTimingEvent(TimingEvent.LauncherTimings.WORK_UNITS_CREATION);
            Source<?, ?> source = this.jobContext.getSource();
            WorkUnitStream workUnitStream;
            if (source instanceof WorkUnitStreamSource) {
                workUnitStream = ((WorkUnitStreamSource) source).getWorkunitStream(jobState);
            } else {
                workUnitStream = new BasicWorkUnitStream.Builder(source.getWorkunits(jobState)).build();
            }
            workUnitsCreationTimer.stop();

            // The absence means there is something wrong getting the work units
            if (workUnitStream == null || workUnitStream.getWorkUnits() == null) {
                this.eventSubmitter.submit(JobEvent.WORK_UNITS_MISSING);
                jobState.setState(JobState.RunningState.FAILED);
                throw new JobException("Failed to get work units for job " + jobId);
            }

            // No work unit to run
            if (!workUnitStream.getWorkUnits().hasNext()) {
                this.eventSubmitter.submit(JobEvent.WORK_UNITS_EMPTY);
                LOG.warn("No work units have been created for job " + jobId);
                jobState.setState(JobState.RunningState.COMMITTED);
                notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_COMPLETE,
                        new JobListenerAction() {
                            @Override
                            public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                                jobListener.onJobCompletion(jobContext);
                            }
                        });
                return;
            }

            //Initialize writer and converter(s)
            closer.register(WriterInitializerFactory.newInstace(jobState, workUnitStream)).initialize();
            closer.register(ConverterInitializerFactory.newInstance(jobState, workUnitStream)).initialize();

            TimingEvent stagingDataCleanTimer = this.eventSubmitter
                    .getTimingEvent(TimingEvent.RunJobTimings.MR_STAGING_DATA_CLEAN);
            // Cleanup left-over staging data possibly from the previous run. This is particularly
            // important if the current batch of WorkUnits include failed WorkUnits from the previous
            // run which may still have left-over staging data not cleaned up yet.
            cleanLeftoverStagingData(workUnitStream, jobState);
            stagingDataCleanTimer.stop();

            long startTime = System.currentTimeMillis();
            jobState.setStartTime(startTime);
            jobState.setState(JobState.RunningState.RUNNING);

            try {
                LOG.info("Starting job " + jobId);

                notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_START,
                        new JobListenerAction() {
                            @Override
                            public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                                jobListener.onJobStart(jobContext);
                            }
                        });

                TimingEvent workUnitsPreparationTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.WORK_UNITS_PREPARATION);
                // Add task ids
                workUnitStream = prepareWorkUnits(workUnitStream, jobState);
                // Remove skipped workUnits from the list of work units to execute.
                workUnitStream = workUnitStream.filter(new SkippedWorkUnitsFilter(jobState));
                // Add surviving tasks to jobState
                workUnitStream = workUnitStream.transform(new MultiWorkUnitForEach() {
                    @Override
                    public void forWorkUnit(WorkUnit workUnit) {
                        jobState.incrementTaskCount();
                        jobState.addTaskState(new TaskState(new WorkUnitState(workUnit, jobState)));
                    }
                });
                workUnitsPreparationTimer.stop();

                // Write job execution info to the job history store before the job starts to run
                this.jobContext.storeJobExecutionInfo();

                TimingEvent jobRunTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.JOB_RUN);
                // Start the job and wait for it to finish
                runWorkUnitStream(workUnitStream);
                jobRunTimer.stop();

                this.eventSubmitter.submit(
                        CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "JOB_" + jobState.getState()));

                // Check and set final job jobPropsState upon job completion
                if (jobState.getState() == JobState.RunningState.CANCELLED) {
                    LOG.info(String.format("Job %s has been cancelled, aborting now", jobId));
                    return;
                }

                TimingEvent jobCommitTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.JOB_COMMIT);
                this.jobContext.finalizeJobStateBeforeCommit();
                this.jobContext.commit();
                postProcessJobState(jobState);
                jobCommitTimer.stop();
            } finally {
                long endTime = System.currentTimeMillis();
                jobState.setEndTime(endTime);
                jobState.setDuration(endTime - jobState.getStartTime());
            }
        } catch (Throwable t) {
            jobState.setState(JobState.RunningState.FAILED);
            String errMsg = "Failed to launch and run job " + jobId;
            LOG.error(errMsg + ": " + t, t);
        } finally {
            try {
                TimingEvent jobCleanupTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.JOB_CLEANUP);
                cleanupStagingData(jobState);
                jobCleanupTimer.stop();

                // Write job execution info to the job history store upon job termination
                this.jobContext.storeJobExecutionInfo();
            } finally {
                launchJobTimer.stop();
            }
        }

        for (JobState.DatasetState datasetState : this.jobContext.getDatasetStatesByUrns().values()) {
            // Set the overall job state to FAILED if the job failed to process any dataset
            if (datasetState.getState() == JobState.RunningState.FAILED) {
                jobState.setState(JobState.RunningState.FAILED);
                break;
            }
        }

        notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_COMPLETE,
                new JobListenerAction() {
                    @Override
                    public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                        jobListener.onJobCompletion(jobContext);
                    }
                });

        if (jobState.getState() == JobState.RunningState.FAILED) {
            notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_FAILED,
                    new JobListenerAction() {
                        @Override
                        public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                            jobListener.onJobFailure(jobContext);
                        }
                    });
            throw new JobException(String.format("Job %s failed", jobId));
        }
    } finally {
        // Stop metrics reporting
        if (this.jobContext.getJobMetricsOptional().isPresent()) {
            JobMetrics.remove(jobState);
        }
        MDC.remove(ConfigurationKeys.JOB_NAME_KEY);
        MDC.remove(ConfigurationKeys.JOB_KEY_KEY);
    }
}

From source file:org.abstractmeta.reflectify.plugin.ReflectifyGenerator.java

protected void generateAccessors(JavaTypeBuilder typeBuilder, List<JavaMethod> methods, Type reflectifyType) {
    JavaMethodBuilder methodBuilder = new JavaMethodBuilder();
    methodBuilder.addModifier("protected").setName("registerAccessors").setResultType(void.class);
    methodBuilder.addParameter("accessors", new ParameterizedTypeImpl(null, Map.class, String.class,
            new ParameterizedTypeImpl(null, Accessor.class, reflectifyType, Object.class)));
    methodBuilder.addBody("\n");
    for (JavaMethod method : methods) {
        if (!method.getModifiers().contains("public")) {
            continue;
        }//from   w  w  w  . j a v  a2  s  .c  o  m
        String methodName = method.getName();
        if (!((methodName.startsWith("get") || methodName.startsWith("is"))
                && method.getParameterTypes().size() == 0)) {
            continue;
        }
        String fieldName = ReflectUtil.extractFieldNameFromMethodName(method.getName());
        Type fieldType = ReflectUtil.getObjectType(method.getResultType());
        Class fieldRawClass = ReflectUtil.getRawClass(fieldType);
        JavaTypeBuilder nestedClassBuilder = methodBuilder.addNestedJavaType();
        String accessorClassName = StringUtil.format(CaseFormat.UPPER_CAMEL, fieldName, "accessor",
                CaseFormat.LOWER_CAMEL);
        nestedClassBuilder.setName(accessorClassName);
        nestedClassBuilder
                .addSuperInterface(new ParameterizedTypeImpl(null, Accessor.class, reflectifyType, fieldType));
        JavaMethodBuilder accessorBuilder = new JavaMethodBuilder();
        accessorBuilder.addModifier("public").setName("get").setResultType(fieldType);
        accessorBuilder.addParameter("instance", reflectifyType);
        accessorBuilder.addBody("return instance." + methodName + "();");
        String fieldSimpleName;
        if (fieldRawClass.isArray()) {
            fieldSimpleName = JavaTypeUtil.getSimpleClassName(fieldRawClass.getComponentType().getName(), true)
                    + " []";
        } else {
            fieldSimpleName = JavaTypeUtil.getSimpleClassName(fieldRawClass.getName(), true);
        }

        nestedClassBuilder.addMethod(accessorBuilder.build());
        methodBuilder.addBody("register(accessors, \"" + fieldName + "\", " + fieldSimpleName + ".class , new "
                + accessorClassName + "());");
    }

    typeBuilder.addMethod(methodBuilder.build());
}

From source file:org.jooby.camel.Camel.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> T configure(final T source, final Config config) {
    List<Method> methods = Lists.newArrayList(source.getClass().getMethods());
    config.entrySet().forEach(o -> {//from w  ww .  ja v  a 2  s .co  m
        String key = o.getKey();
        String setter = "set" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, key);
        Object raw = o.getValue().unwrapped();
        Optional<Method> result = methods.stream().filter(m -> m.getName().equals(setter)).findFirst();
        if (result.isPresent()) {
            Method method = result.get();
            Class type = method.getParameterTypes()[0];
            Object value = cast(type, raw);
            Try.run(() -> method.invoke(source, value)).onFailure(ex -> {
                throw new IllegalArgumentException("Bad option: <" + raw + "> for: " + method, ex);
            });
        } else {
            log.error("Unknown option camel.{} = {}", key, raw);
        }
    });
    return source;
}

From source file:org.apache.gobblin.runtime.AbstractJobLauncher.java

@Override
public void launchJob(JobListener jobListener) throws JobException {
    String jobId = this.jobContext.getJobId();
    final JobState jobState = this.jobContext.getJobState();

    try {//from w ww.jav  a 2  s . c  o  m
        MDC.put(ConfigurationKeys.JOB_NAME_KEY, this.jobContext.getJobName());
        MDC.put(ConfigurationKeys.JOB_KEY_KEY, this.jobContext.getJobKey());
        TimingEvent launchJobTimer = this.eventSubmitter
                .getTimingEvent(TimingEvent.LauncherTimings.FULL_JOB_EXECUTION);

        try (Closer closer = Closer.create()) {
            closer.register(this.jobContext);
            notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_PREPARE,
                    new JobListenerAction() {
                        @Override
                        public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                            jobListener.onJobPrepare(jobContext);
                        }
                    });

            if (this.jobContext.getSemantics() == DeliverySemantics.EXACTLY_ONCE) {

                // If exactly-once is used, commit sequences of the previous run must be successfully compelted
                // before this run can make progress.
                executeUnfinishedCommitSequences(jobState.getJobName());
            }

            TimingEvent workUnitsCreationTimer = this.eventSubmitter
                    .getTimingEvent(TimingEvent.LauncherTimings.WORK_UNITS_CREATION);
            Source<?, ?> source = this.jobContext.getSource();
            WorkUnitStream workUnitStream;
            if (source instanceof WorkUnitStreamSource) {
                workUnitStream = ((WorkUnitStreamSource) source).getWorkunitStream(jobState);
            } else {
                workUnitStream = new BasicWorkUnitStream.Builder(source.getWorkunits(jobState)).build();
            }
            workUnitsCreationTimer.stop(
                    this.eventMetadataGenerator.getMetadata(this.jobContext, EventName.WORK_UNITS_CREATION));

            // The absence means there is something wrong getting the work units
            if (workUnitStream == null || workUnitStream.getWorkUnits() == null) {
                this.eventSubmitter.submit(JobEvent.WORK_UNITS_MISSING);
                jobState.setState(JobState.RunningState.FAILED);
                throw new JobException("Failed to get work units for job " + jobId);
            }

            // No work unit to run
            if (!workUnitStream.getWorkUnits().hasNext()) {
                this.eventSubmitter.submit(JobEvent.WORK_UNITS_EMPTY);
                LOG.warn("No work units have been created for job " + jobId);
                jobState.setState(JobState.RunningState.COMMITTED);
                notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_COMPLETE,
                        new JobListenerAction() {
                            @Override
                            public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                                jobListener.onJobCompletion(jobContext);
                            }
                        });
                return;
            }

            //Initialize writer and converter(s)
            closer.register(WriterInitializerFactory.newInstace(jobState, workUnitStream)).initialize();
            closer.register(ConverterInitializerFactory.newInstance(jobState, workUnitStream)).initialize();

            TimingEvent stagingDataCleanTimer = this.eventSubmitter
                    .getTimingEvent(TimingEvent.RunJobTimings.MR_STAGING_DATA_CLEAN);
            // Cleanup left-over staging data possibly from the previous run. This is particularly
            // important if the current batch of WorkUnits include failed WorkUnits from the previous
            // run which may still have left-over staging data not cleaned up yet.
            cleanLeftoverStagingData(workUnitStream, jobState);
            stagingDataCleanTimer.stop(
                    this.eventMetadataGenerator.getMetadata(this.jobContext, EventName.MR_STAGING_DATA_CLEAN));

            long startTime = System.currentTimeMillis();
            jobState.setStartTime(startTime);
            jobState.setState(JobState.RunningState.RUNNING);

            try {
                LOG.info("Starting job " + jobId);

                notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_START,
                        new JobListenerAction() {
                            @Override
                            public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                                jobListener.onJobStart(jobContext);
                            }
                        });

                TimingEvent workUnitsPreparationTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.WORK_UNITS_PREPARATION);
                // Add task ids
                workUnitStream = prepareWorkUnits(workUnitStream, jobState);
                // Remove skipped workUnits from the list of work units to execute.
                workUnitStream = workUnitStream.filter(new SkippedWorkUnitsFilter(jobState));
                // Add surviving tasks to jobState
                workUnitStream = workUnitStream.transform(new MultiWorkUnitForEach() {
                    @Override
                    public void forWorkUnit(WorkUnit workUnit) {
                        jobState.incrementTaskCount();
                        jobState.addTaskState(new TaskState(new WorkUnitState(workUnit, jobState)));
                    }
                });

                // dump the work unit if tracking logs are enabled
                if (jobState.getPropAsBoolean(ConfigurationKeys.WORK_UNIT_ENABLE_TRACKING_LOGS)) {
                    workUnitStream = workUnitStream.transform(new Function<WorkUnit, WorkUnit>() {
                        @Nullable
                        @Override
                        public WorkUnit apply(@Nullable WorkUnit input) {
                            LOG.info("Work unit tracking log: {}", input);
                            return input;
                        }
                    });
                }

                workUnitsPreparationTimer.stop(this.eventMetadataGenerator.getMetadata(this.jobContext,
                        EventName.WORK_UNITS_PREPARATION));

                // Write job execution info to the job history store before the job starts to run
                this.jobContext.storeJobExecutionInfo();

                TimingEvent jobRunTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.JOB_RUN);
                // Start the job and wait for it to finish
                runWorkUnitStream(workUnitStream);
                jobRunTimer.stop(this.eventMetadataGenerator.getMetadata(this.jobContext, EventName.JOB_RUN));

                this.eventSubmitter.submit(
                        CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "JOB_" + jobState.getState()));

                // Check and set final job jobPropsState upon job completion
                if (jobState.getState() == JobState.RunningState.CANCELLED) {
                    LOG.info(String.format("Job %s has been cancelled, aborting now", jobId));
                    return;
                }

                TimingEvent jobCommitTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.JOB_COMMIT);
                this.jobContext.finalizeJobStateBeforeCommit();
                this.jobContext.commit();
                postProcessJobState(jobState);
                jobCommitTimer
                        .stop(this.eventMetadataGenerator.getMetadata(this.jobContext, EventName.JOB_COMMIT));
            } finally {
                long endTime = System.currentTimeMillis();
                jobState.setEndTime(endTime);
                jobState.setDuration(endTime - jobState.getStartTime());
            }
        } catch (Throwable t) {
            jobState.setState(JobState.RunningState.FAILED);
            String errMsg = "Failed to launch and run job " + jobId;
            LOG.error(errMsg + ": " + t, t);
        } finally {
            try {
                TimingEvent jobCleanupTimer = this.eventSubmitter
                        .getTimingEvent(TimingEvent.LauncherTimings.JOB_CLEANUP);
                cleanupStagingData(jobState);
                jobCleanupTimer
                        .stop(this.eventMetadataGenerator.getMetadata(this.jobContext, EventName.JOB_CLEANUP));

                // Write job execution info to the job history store upon job termination
                this.jobContext.storeJobExecutionInfo();
            } finally {
                launchJobTimer.stop(
                        this.eventMetadataGenerator.getMetadata(this.jobContext, EventName.FULL_JOB_EXECUTION));
            }
        }

        for (JobState.DatasetState datasetState : this.jobContext.getDatasetStatesByUrns().values()) {
            // Set the overall job state to FAILED if the job failed to process any dataset
            if (datasetState.getState() == JobState.RunningState.FAILED) {
                jobState.setState(JobState.RunningState.FAILED);
                LOG.warn("At least one dataset state is FAILED. Setting job state to FAILED.");
                break;
            }
        }

        notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_COMPLETE,
                new JobListenerAction() {
                    @Override
                    public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                        jobListener.onJobCompletion(jobContext);
                    }
                });

        if (jobState.getState() == JobState.RunningState.FAILED) {
            notifyListeners(this.jobContext, jobListener, TimingEvent.LauncherTimings.JOB_FAILED,
                    new JobListenerAction() {
                        @Override
                        public void apply(JobListener jobListener, JobContext jobContext) throws Exception {
                            jobListener.onJobFailure(jobContext);
                        }
                    });
            throw new JobException(String.format("Job %s failed", jobId));
        }
    } finally {
        // Stop metrics reporting
        if (this.jobContext.getJobMetricsOptional().isPresent()) {
            JobMetrics.remove(jobState);
        }
        MDC.remove(ConfigurationKeys.JOB_NAME_KEY);
        MDC.remove(ConfigurationKeys.JOB_KEY_KEY);
    }
}

From source file:iterator.Explorer.java

/** @see Subscriber#updated(IFS) */
@Override//w  w  w  . java  2s  .c o m
@Subscribe
public void updated(IFS updated) {
    ifs = updated;
    System.err.println("Updated: " + ifs);
    String name = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
            Optional.fromNullable(ifs.getName()).or(IFS.UNTITLED));
    setTitle(name);
    if (!ifs.isEmpty()) {
        save.setEnabled(true);
        saveAs.setEnabled(true);
    }
    repaint();
}

From source file:org.abstractmeta.reflectify.plugin.ReflectifyGenerator.java

protected void generateMutators(JavaTypeBuilder typeBuilder, List<JavaMethod> methods, Type reflectifyType) {
    JavaMethodBuilder methodBuilder = new JavaMethodBuilder();
    methodBuilder.addModifier("protected").setName("registerMutators").setResultType(void.class);
    methodBuilder.addParameter("mutators", new ParameterizedTypeImpl(null, Map.class, String.class,
            new ParameterizedTypeImpl(null, Mutator.class, reflectifyType, Object.class)));
    methodBuilder.addBody("\n");
    for (JavaMethod method : methods) {
        if (!method.getModifiers().contains("public")) {
            continue;
        }//w w w .  j  a  v a  2 s.c  o m
        String methodName = method.getName();
        if (!methodName.startsWith("set") || method.getParameterTypes().size() != 1) {
            continue;
        }
        String fieldName = ReflectUtil.extractFieldNameFromMethodName(method.getName());
        Type fieldType = ReflectUtil.getObjectType(method.getParameterTypes().get(0));
        JavaTypeBuilder nestedClassBuilder = methodBuilder.addNestedJavaType();
        String accessorClassName = StringUtil.format(CaseFormat.UPPER_CAMEL, fieldName, "mutator",
                CaseFormat.LOWER_CAMEL);
        nestedClassBuilder.setName(accessorClassName);
        nestedClassBuilder
                .addSuperInterface(new ParameterizedTypeImpl(null, Mutator.class, reflectifyType, fieldType));
        JavaMethodBuilder accessorBuilder = new JavaMethodBuilder();
        accessorBuilder.addModifier("public").setName("set").setResultType(void.class);
        accessorBuilder.addParameter("instance", reflectifyType).addParameter("value", fieldType);
        accessorBuilder.addBody("instance." + methodName + "(value);");

        nestedClassBuilder.addMethod(accessorBuilder.build());
        methodBuilder.addBody("register(mutators, \"" + fieldName + "\", new " + accessorClassName + "());");
    }
    typeBuilder.addMethod(methodBuilder.build());
}

From source file:com.google.template.soy.parseinfo.passes.GenerateParseInfoVisitor.java

@Override
protected void visitTemplateNode(TemplateNode node) {
    // Don't generate anything for private or delegate templates.
    if (node.getVisibility() == Visibility.LEGACY_PRIVATE || node instanceof TemplateDelegateNode) {
        return;// w w  w  .j a va  2  s .co  m
    }

    // First build list of all transitive params (direct and indirect).
    LinkedHashMap<String, TemplateParam> transitiveParamMap = Maps.newLinkedHashMap();
    // Direct params.
    for (TemplateParam param : node.getParams()) {
        transitiveParamMap.put(param.name(), param);
    }

    // Indirect params.
    IndirectParamsInfo indirectParamsInfo = new FindIndirectParamsVisitor(templateRegistry, errorReporter)
            .exec(node);
    for (TemplateParam param : indirectParamsInfo.indirectParams.values()) {
        TemplateParam existingParam = transitiveParamMap.get(param.name());
        if (existingParam == null) {
            // Note: We don't list the description for indirect params.
            transitiveParamMap.put(param.name(), param.copyEssential());
        }
    }

    // Get info on injected params.
    IjParamsInfo ijParamsInfo = new FindIjParamsVisitor(templateRegistry, errorReporter).exec(node);

    @SuppressWarnings("ConstantConditions") // for IntelliJ
    String upperUnderscoreName = convertToUpperUnderscore(node.getPartialTemplateName().substring(1));
    String templateInfoClassName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, upperUnderscoreName)
            + "SoyTemplateInfo";

    // ------ *SoyTemplateInfo class start. ------
    ilb.appendLine();
    ilb.appendLine();
    appendJavadoc(ilb, node.getSoyDocDesc(), true, false);
    ilb.appendLine("public static final class ", templateInfoClassName, " extends SoyTemplateInfo {");
    ilb.increaseIndent();

    // ------ Constants for template name. ------
    ilb.appendLine();
    ilb.appendLine("/** This template's full name. */");
    ilb.appendLine("public static final String __NAME__ = \"", node.getTemplateName(), "\";");
    ilb.appendLine("/** This template's partial name. */");
    ilb.appendLine("public static final String __PARTIAL_NAME__ = \"", node.getPartialTemplateName(), "\";");

    // ------ Param constants. ------
    boolean hasSeenFirstDirectParam = false;
    boolean hasSwitchedToIndirectParams = false;
    for (TemplateParam param : transitiveParamMap.values()) {

        if (param.desc() != null) {
            // Direct param.
            if (!hasSeenFirstDirectParam) {
                ilb.appendLine();
                hasSeenFirstDirectParam = true;
            }
            appendJavadoc(ilb, param.desc(), false, false);

        } else {
            // Indirect param.
            if (!hasSwitchedToIndirectParams) {
                ilb.appendLine();
                ilb.appendLine("// Indirect params.");
                hasSwitchedToIndirectParams = true;
            }

            // Get the list of all transitive callee names as they will appear in the generated
            // Javadoc (possibly containing both partial and full names) and sort them before
            // generating the Javadoc.
            SortedSet<String> sortedJavadocCalleeNames = Sets.newTreeSet();
            for (TemplateNode transitiveCallee : indirectParamsInfo.paramKeyToCalleesMultimap
                    .get(param.name())) {
                String javadocCalleeName = buildTemplateNameForJavadoc(node.getParent(), transitiveCallee);
                sortedJavadocCalleeNames.add(javadocCalleeName);
            }

            // Generate the Javadoc.
            StringBuilder javadocSb = new StringBuilder();
            javadocSb.append("Listed by ");
            boolean isFirst = true;
            for (String javadocCalleeName : sortedJavadocCalleeNames) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    javadocSb.append(", ");
                }
                javadocSb.append(javadocCalleeName);
            }
            javadocSb.append('.');
            appendJavadoc(ilb, javadocSb.toString(), false, true);
        }

        // The actual param field.
        ilb.appendLine("public static final String ", convertToUpperUnderscore(param.name()), " = \"",
                param.name(), "\";");
    }

    // ------ Constructor. ------
    ilb.appendLine();
    ilb.appendLine("private ", templateInfoClassName, "() {");
    ilb.increaseIndent();

    ilb.appendLine("super(");
    ilb.increaseIndent(2);
    ilb.appendLine("\"", node.getTemplateName(), "\",");

    if (!transitiveParamMap.isEmpty()) {
        List<Pair<String, String>> entrySnippetPairs = Lists.newArrayList();
        for (TemplateParam param : transitiveParamMap.values()) {
            entrySnippetPairs.add(Pair.of("\"" + param.name() + "\"",
                    param.isRequired() ? "ParamRequisiteness.REQUIRED" : "ParamRequisiteness.OPTIONAL"));
        }
        appendImmutableMap(ilb, "<String, ParamRequisiteness>", entrySnippetPairs);
        ilb.appendLineEnd(",");
    } else {
        ilb.appendLine("ImmutableMap.<String, ParamRequisiteness>of(),");
    }

    appendIjParamSet(ilb, ijParamsInfo);
    ilb.appendLineEnd(");");
    ilb.decreaseIndent(2);

    ilb.decreaseIndent();
    ilb.appendLine("}");

    // ------ Singleton instance and its getter. ------
    ilb.appendLine();
    ilb.appendLine("private static final ", templateInfoClassName, " __INSTANCE__ =");
    ilb.increaseIndent(2);
    ilb.appendLine("new ", templateInfoClassName, "();");
    ilb.decreaseIndent(2);
    ilb.appendLine();
    ilb.appendLine("public static ", templateInfoClassName, " getInstance() {");
    ilb.increaseIndent();
    ilb.appendLine("return __INSTANCE__;");
    ilb.decreaseIndent();
    ilb.appendLine("}");

    // ------ *SoyTemplateInfo class end. ------
    ilb.decreaseIndent();
    ilb.appendLine("}");

    // ------ Static field with instance of *SoyTemplateInfo class. ------
    ilb.appendLine();
    ilb.appendLine("/** Same as ", templateInfoClassName, ".getInstance(). */");
    ilb.appendLine("public static final ", templateInfoClassName, " ", upperUnderscoreName, " =");
    ilb.increaseIndent(2);
    ilb.appendLine(templateInfoClassName, ".getInstance();");
    ilb.decreaseIndent(2);
}