All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.chutneytesting.action.domain.ActionTemplateParserV2 Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
/*
 * Copyright 2017-2023 Enedis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.chutneytesting.action.domain;

import com.chutneytesting.action.domain.parameter.Parameter;
import com.chutneytesting.action.spi.Action;
import com.google.common.base.CaseFormat;
import com.google.common.base.Converter;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ActionTemplateParserV2 implements ActionTemplateParser {
    private static final String CLASS_NAME_ACTION_SUFFIX = "Action";
    private static final Converter CAMEL_TO_HYPHEN_CONVERTER = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_HYPHEN);

    @Override
    public ResultOrError parse(Class taskClass) {
        if (taskClass.getDeclaredConstructors().length > 1) {
            return ResultOrError.error(new ParsingError(taskClass, "More than one constructor"));
        }
        String taskName = computeActionName(taskClass);
        Constructor constructor = (Constructor) taskClass.getDeclaredConstructors()[0];
        List parameters = extractParameters(constructor);
        return ResultOrError.result(new ActionTemplateV2(taskName, taskClass, constructor, parameters));
    }

    private List extractParameters(Constructor constructor) {
        return Arrays.stream(constructor.getParameters())
            .map(Parameter::fromJavaParameter)
            .collect(Collectors.toList());
    }

    private String computeActionName(Class taskClass) {
        // TODO extract @taskIdentifier if present
        String taskName = taskClass.getSimpleName();
        if (taskName.endsWith(CLASS_NAME_ACTION_SUFFIX)) {
            taskName = taskName.substring(0, taskName.length() - CLASS_NAME_ACTION_SUFFIX.length());
        }
        taskName = CAMEL_TO_HYPHEN_CONVERTER.convert(taskName);
        return taskName;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy