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

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

Introduction

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

Prototype

CaseFormat UPPER_UNDERSCORE

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

Click Source Link

Document

Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE".

Usage

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 {/* www  . j  a  v  a  2 s  . co  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: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;// ww w.  j av a2 s. c  o  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);
}

From source file:com.google.template.soy.jssrc.internal.GenJsCodeVisitorAssistantForMsgs.java

/**
 * Private helper for visitGoogMsgDefNode().
 * Converts a Soy placeholder name (in upper underscore format) into a JS variable name (in lower
 * camel case format) used by goog.getMsg(). If the original name has a numeric suffix, it will
 * be preserved with an underscore.//from  w ww  .ja  v  a2 s.  com
 *
 * For example, the following transformations happen:
 * <li> N : n
 * <li> NUM_PEOPLE : numPeople
 * <li> PERSON_2 : person_2
 * <li>GENDER_OF_THE_MAIN_PERSON_3 : genderOfTheMainPerson_3
 *
 * @param placeholderName The placeholder name to convert.
 * @return The generated goog.getMsg name for the given (standard) Soy name.
 */
private static String genGoogMsgPlaceholderName(String placeholderName) {

    Matcher suffixMatcher = UNDERSCORE_NUMBER_SUFFIX.matcher(placeholderName);
    if (suffixMatcher.find()) {
        String base = placeholderName.substring(0, suffixMatcher.start());
        String suffix = suffixMatcher.group();
        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, base) + suffix;
    } else {
        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, placeholderName);
    }
}

From source file:org.eclipse.xtext.xtext.ui.editor.quickfix.XtextGrammarQuickfixProvider.java

@Fix(INVALID_TERMINALRULE_NAME)
public void fixTerminalRuleName(final Issue issue, IssueResolutionAcceptor acceptor) {
    if (issue.getData().length == 1) {
        final String upperCase = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, issue.getData()[0])
                .toString();// www .j a v  a2  s  .c  o m
        acceptor.accept(issue, "Change name to " + upperCase, "Change name to " + upperCase, "upcase.png",
                new IModification() {

                    @Override
                    public void apply(IModificationContext context) throws Exception {
                        final IXtextDocument xtextDocument = context.getXtextDocument();
                        xtextDocument.replace(issue.getOffset(), issue.getLength(), upperCase);
                        xtextDocument.modify(new IUnitOfWork.Void<XtextResource>() {
                            @Override
                            public void process(XtextResource state) throws Exception {
                                final EObject terminalRule = state
                                        .getEObject(issue.getUriToProblem().fragment());
                                Iterable<RuleCall> candidates = Iterables.filter(Iterables
                                        .filter(Lists.newArrayList(state.getAllContents()), RuleCall.class),
                                        new Predicate<RuleCall>() {
                                            @Override
                                            public boolean apply(RuleCall ruleCall) {
                                                return ruleCall.getRule() == terminalRule;
                                            }
                                        });
                                for (RuleCall ruleCall : candidates) {
                                    List<INode> nodes = NodeModelUtils.findNodesForFeature(ruleCall,
                                            XtextPackage.eINSTANCE.getRuleCall_Rule());
                                    for (INode node : nodes) {
                                        ITextRegion textRegion = node.getTextRegion();
                                        xtextDocument.replace(textRegion.getOffset(), textRegion.getLength(),
                                                upperCase);
                                    }
                                }
                            }
                        });
                    }
                });
    }
}

From source file:com.android.build.gradle.internal2.incremental.InstantRunBuildContext.java

private Element toXml(Document document, PersistenceMode persistenceMode) {
    Element instantRun = document.createElement(TAG_INSTANT_RUN);
    document.appendChild(instantRun);/*from w  w w. j av a  2 s  .c  o  m*/

    for (TaskType taskType : TaskType.values()) {
        Element taskTypeNode = document.createElement(TAG_TASK);
        taskTypeNode.setAttribute(ATTR_NAME,
                CaseFormat.UPPER_UNDERSCORE.converterTo(CaseFormat.LOWER_HYPHEN).convert(taskType.name()));
        taskTypeNode.setAttribute(ATTR_DURATION, String.valueOf(taskDurationInMs[taskType.ordinal()]));
        instantRun.appendChild(taskTypeNode);
    }

    currentBuild.toXml(document, instantRun);
    instantRun.setAttribute(ATTR_API_LEVEL, String.valueOf(getFeatureLevel()));
    if (density != null) {
        instantRun.setAttribute(ATTR_DENSITY, density);
    }
    if (abi != null) {
        instantRun.setAttribute(ATTR_ABI, abi);
    }
    if (token != null) {
        instantRun.setAttribute(ATTR_TOKEN, token.toString());
    }
    instantRun.setAttribute(ATTR_FORMAT, CURRENT_FORMAT);
    instantRun.setAttribute(ATTR_PLUGIN_VERSION, Version.ANDROID_GRADLE_PLUGIN_VERSION);

    switch (persistenceMode) {
    case FULL_BUILD:
        // only include the last build.
        if (!previousBuilds.isEmpty()) {
            instantRun.appendChild(previousBuilds.lastEntry().getValue().toXml(document));
        }
        break;
    case INCREMENTAL_BUILD:
        for (Build build : previousBuilds.values()) {
            instantRun.appendChild(build.toXml(document));
        }
        break;
    case TEMP_BUILD:
        break;
    default:
        throw new RuntimeException("PersistenceMode not handled" + persistenceMode);
    }
    return instantRun;
}

From source file:com.google.javascript.jscomp.JsMessageVisitor.java

/**
 * Converts the given string from upper-underscore case to lower-camel case,
 * preserving numeric suffixes. For example: "NAME" -> "name" "A4_LETTER" ->
 * "a4Letter" "START_SPAN_1_23" -> "startSpan_1_23".
 *//*from  www . ja  va2  s  . c  o m*/
static String toLowerCamelCaseWithNumericSuffixes(String input) {
    // Determine where the numeric suffixes begin
    int suffixStart = input.length();
    while (suffixStart > 0) {
        char ch = '\0';
        int numberStart = suffixStart;
        while (numberStart > 0) {
            ch = input.charAt(numberStart - 1);
            if (Character.isDigit(ch)) {
                numberStart--;
            } else {
                break;
            }
        }
        if ((numberStart > 0) && (numberStart < suffixStart) && (ch == '_')) {
            suffixStart = numberStart - 1;
        } else {
            break;
        }
    }

    if (suffixStart == input.length()) {
        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, input);
    } else {
        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, input.substring(0, suffixStart))
                + input.substring(suffixStart);
    }
}

From source file:com.google.gwt.resources.rg.GssResourceGenerator.java

/**
 * Transform a camel case string to upper case. Each word is separated by a '_'
 *
 * @param camelCase/* ww w. j a  va2 s .  c  o m*/
 * @return
 */
private String toUpperCase(String camelCase) {
    return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, camelCase);
}

From source file:pt.ist.fenixedu.integration.api.FenixAPIv1.java

private FenixCourseEvaluation.GenericTest getGenericTestJSON(Evaluation evaluation) {
    String type = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, evaluation.getClass().getSimpleName());
    return new FenixCourseEvaluation.GenericTest(evaluation.getPresentationName(), type);
}