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:com.android.utils.SdkUtils.java

/**
 * Translates an XML name (e.g. xml-name) into a Java / C++ constant name (e.g. XML_NAME)
 * @param xmlName the hyphen separated lower case xml name.
 * @return the equivalent constant name.
 *//*from  w w  w  .  ja va 2 s  .  com*/
public static String xmlNameToConstantName(String xmlName) {
    return CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, xmlName);
}

From source file:com.android.utils.SdkUtils.java

/**
 * Translates a camel case name (e.g. xmlName) into a Java / C++ constant name (e.g. XML_NAME)
 * @param camelCaseName the camel case name.
 * @return the equivalent constant name.
 *//*from  w  ww  .  ja  va  2  s  .  c  o m*/
public static String camelCaseToConstantName(String camelCaseName) {
    return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, camelCaseName);
}

From source file:com.android.utils.SdkUtils.java

/**
 * Translates a Java / C++ constant name (e.g. XML_NAME) into camel case name (e.g. xmlName)
 * @param constantName the constant name.
 * @return the equivalent camel case name.
 */// ww  w.java 2  s.c  om
public static String constantNameToCamelCase(String constantName) {
    return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, constantName);
}

From source file:com.android.utils.SdkUtils.java

/**
 * Translates a Java / C++ constant name (e.g. XML_NAME) into a XML case name (e.g. xml-name)
 * @param constantName the constant name.
 * @return the equivalent XML name./*from www.  j a v  a  2s.c o  m*/
 */
public static String constantNameToXmlName(String constantName) {
    return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, constantName);
}

From source file:net.phonex.intellij.android.dbmodel.CodeGenerator.java

private String getFieldName(String varName) {
    return "FIELD_" + CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, varName);
}

From source file:org.metaservice.core.OntologyToJavaConverter.java

/**
 * for conflict resolution it must be called from generate
 * @param uri uri to encode/* w  w w. j a  v a 2 s. co  m*/
 * @param conflictString String to append when there is a nameconflict
 * @return Upper case, underscore separated java identifier of localname of uri
 */
String toJavaName(URI uri, String conflictString) {
    String s = uri.getLocalName();
    boolean upper = false;
    StringBuilder builder = new StringBuilder();
    for (char c : s.toCharArray()) {
        if (Character.isUpperCase(c)) {
            if (upper) {
                c = Character.toLowerCase(c);
            }
            upper = true;
        } else {
            upper = false;
        }
        builder.append(c);
    }
    s = caseFormat.to(CaseFormat.UPPER_UNDERSCORE, builder.toString());
    s = s.replaceAll("[^A-Z0-9]", "_");
    while (nameMap.values().contains(s)) {
        s = s + conflictString;
    }
    nameMap.put(uri, s);
    return s;
}

From source file:bio.gcat.Utilities.java

public static String camelCase(String text) {
    return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, text);
}

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;
    }//  w ww  .j a  v  a2 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();
        }/* ww w  .j  a v  a2 s  .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   w  ww . j av  a2  s. com*/
        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);
    }
}