hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0d8aa29e2bf30ac8905a6012965970b293a9d3 | 5,915 | java | Java | bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/expression/BOJudgmentLink.java | color-coding/ibas | e050bbf323002c7c0f4b31e58e8e9c4cc7627c5a | [
"MIT"
] | 14 | 2016-06-03T02:50:22.000Z | 2018-04-02T03:44:17.000Z | bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/expression/BOJudgmentLink.java | color-coding/ibas | e050bbf323002c7c0f4b31e58e8e9c4cc7627c5a | [
"MIT"
] | 4 | 2017-01-13T01:14:42.000Z | 2022-02-28T03:37:41.000Z | bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/expression/BOJudgmentLink.java | color-coding/ibas | e050bbf323002c7c0f4b31e58e8e9c4cc7627c5a | [
"MIT"
] | 119 | 2016-07-14T03:30:20.000Z | 2021-11-09T09:53:53.000Z | 32.679558 | 101 | 0.709721 | 5,726 | package org.colorcoding.ibas.bobas.expression;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.colorcoding.ibas.bobas.MyConfiguration;
import org.colorcoding.ibas.bobas.bo.IBusinessObject;
import org.colorcoding.ibas.bobas.bo.IBusinessObjects;
import org.colorcoding.ibas.bobas.core.fields.IFieldData;
import org.colorcoding.ibas.bobas.core.fields.IManagedFields;
import org.colorcoding.ibas.bobas.data.ArrayList;
import org.colorcoding.ibas.bobas.data.DataConvert;
import org.colorcoding.ibas.bobas.message.Logger;
import org.colorcoding.ibas.bobas.message.MessageLevel;
/**
* 业务对象的判断链
*
* @author Niuren.Zhu
*
*/
public class BOJudgmentLink extends JudgmentLink {
/**
* 创建属性操作者
*
* @return
*/
protected IPropertyValueOperator createPropertyValueOperator() {
return new FieldValueOperator();
}
/**
* 判断
*
* @param bo 待判断的对象
* @return true,满足条件;false,不满足
* @throws JudmentOperationException
*/
public boolean judge(IBusinessObject bo) throws JudmentOperationException {
// 无条件
if (this.getJudgmentItems() == null) {
return true;
}
ArrayList<JudgmentLinkItem> jItems = new ArrayList<>();
// 设置所以条件的比较值
for (JudgmentLinkItem item : this.getJudgmentItems()) {
// 左值
if (item.getLeftOperter() instanceof IPropertyValueOperator) {
IPropertyValueOperator propertyOperator = (IPropertyValueOperator) item.getLeftOperter();
propertyOperator.setValue(bo);
if (!DataConvert.isNullOrEmpty(propertyOperator.getPropertyName())
&& propertyOperator.getPropertyName().indexOf(".") > 0
&& item.getLeftOperter() instanceof FieldValueOperator) {
// 存在子属性的判断
if (MyConfiguration.isDebugMode()) {
Logger.log(MessageLevel.DEBUG, MSG_JUDGMENT_ENTRY_SUB_JUDGMENT, item.toString());
}
try {
// 比较子判断
boolean result = this.judge(bo, item);
// 子判断结果并入父项
JudgmentLinkItem jItem = new JudgmentLinkItem();
jItem.setRelationship(item.getRelationship());
jItem.setOpenBracket(item.getOpenBracket());
jItem.setLeftOperter(this.createValueOperator());
jItem.getLeftOperter().setValue(true);
jItem.setOperation(JudmentOperation.EQUAL);
jItem.setRightOperter(this.createValueOperator());
jItem.getRightOperter().setValue(result);
jItem.setCloseBracket(item.getCloseBracket());
jItems.add(jItem);
// 处理下一个
continue;
} catch (JudmentOperationException e) {
throw e;
} catch (Exception e) {
throw new JudmentOperationException(e);
}
}
}
// 右值
if (item.getRightOperter() instanceof IPropertyValueOperator) {
IPropertyValueOperator propertyOperator = (IPropertyValueOperator) item.getRightOperter();
propertyOperator.setValue(bo);
}
jItems.add(item);
}
return this.judge(0, jItems.toArray(new JudgmentLinkItem[] {}));
}
private List<IBusinessObject> getValues(IBusinessObject bo, String path) {
return this.getValues(bo, path.split("\\."));
}
private List<IBusinessObject> getValues(IBusinessObject bo, String[] propertys) {
ArrayList<IBusinessObject> values = new ArrayList<>();
if (!(bo instanceof IManagedFields)) {
// 不能识别的对象
return values;
}
if (propertys.length == 1) {
// 最后一个属性
String property = propertys[0];
IFieldData fieldData = ((IManagedFields) bo).getField(property);
if (fieldData == null) {
// 未找到属性
Logger.log(MessageLevel.WARN, MSG_JUDGMENT_NOT_FOUND_PROPERTY, bo, property);
} else {
values.add(bo);
}
return values;
}
// 获取属性路径的值
String property = null;
for (int i = 0; i < propertys.length - 1; i++) {
property = propertys[i];
IFieldData fieldData = ((IManagedFields) bo).getField(property);
if (fieldData == null) {
// 未找到属性
Logger.log(MessageLevel.WARN, MSG_JUDGMENT_NOT_FOUND_PROPERTY, bo, property);
break;
}
String[] lasts = new String[propertys.length - i - 1];
for (int j = 0; j < lasts.length; j++) {
lasts[j] = propertys[i + j + 1];
}
if (fieldData.getValue() instanceof IBusinessObjects<?, ?>) {
// 值是业务对象列表
IBusinessObjects<?, ?> boList = (IBusinessObjects<?, ?>) fieldData.getValue();
for (IBusinessObject item : boList) {
values.addAll(this.getValues(item, lasts));
}
} else if (fieldData.getValue() instanceof IBusinessObject) {
// 值是对象
values.add((IBusinessObject) fieldData.getValue());
}
}
return values;
}
protected boolean judge(IBusinessObject bo, JudgmentLinkItem parent)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, JudmentOperationException {
String path = ((IPropertyValueOperator) parent.getLeftOperter()).getPropertyName();
if (path == null || path.isEmpty()) {
// 无属性
return false;
}
List<IBusinessObject> values = this.getValues(bo, path);
if (values.isEmpty()) {
// 没有待比较的值
return false;
}
String property = path.substring(path.lastIndexOf(".") + 1);
ArrayList<JudgmentLinkItem> jItems = new ArrayList<>();
for (Object item : values) {
JudgmentLinkItem jItem = new JudgmentLinkItem();
jItem.setRelationship(JudmentOperation.OR);
// 左值
IPropertyValueOperator propertyValueOperator = this.createPropertyValueOperator();
propertyValueOperator.setPropertyName(property);
propertyValueOperator.setValue(item);
jItem.setLeftOperter(propertyValueOperator);
// 比较类型
jItem.setOperation(parent.getOperation());
// 获取右值,使用父项的运算结果避免藏数据
IValueOperator valueOperator = this.createValueOperator();
if (parent.getRightOperter() instanceof FieldValueOperator) {
parent.getRightOperter().setValue(item);
}
valueOperator.setValue(parent.getRightOperter().getValue());
// 设置右值
jItem.setRightOperter(valueOperator);
jItems.add(jItem);
}
return this.judge(0, jItems.toArray(new JudgmentLinkItem[] {}));
}
}
|
3e0d8aa593191926ea0a614196021f7402ae1503 | 2,182 | java | Java | Excalibur/src/main/java/Tetrahydrocannabinol/Excalibur/api/EndpointsApiProfile.java | Linkbit-gif/KhufusCloud | 8c153f056b037f05b8f41d69b08717e4c39646e8 | [
"Apache-2.0"
] | 1 | 2021-04-29T06:13:09.000Z | 2021-04-29T06:13:09.000Z | Excalibur/src/main/java/Tetrahydrocannabinol/Excalibur/api/EndpointsApiProfile.java | Linkbit-gif/KhufusCloud | 8c153f056b037f05b8f41d69b08717e4c39646e8 | [
"Apache-2.0"
] | null | null | null | Excalibur/src/main/java/Tetrahydrocannabinol/Excalibur/api/EndpointsApiProfile.java | Linkbit-gif/KhufusCloud | 8c153f056b037f05b8f41d69b08717e4c39646e8 | [
"Apache-2.0"
] | null | null | null | 43.519231 | 138 | 0.667698 | 5,727 | package Tetrahydrocannabinol.Excalibur.api;
import com.google.api.server.spi.auth.EspAuthenticator;
import com.google.api.server.spi.auth.GoogleOAuth2Authenticator;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiIssuer;
import com.google.api.server.spi.config.ApiIssuerAudience;
import com.google.api.server.spi.config.ApiNamespace;
import static Tetrahydrocannabinol.Excalibur.api.EndpointsApiProfile.PROJECT_ID;
/**
* The endpoint profile, the base class as a configuration of the REST API and generated client.
* <p>
* <strong>Preconfigured for Firebase Authentication (OAuth 2.0)</strong>
* <p>
* It provides backend services, easy-to-use SDKs, and ready-made libraries to authenticate
* users to your app.
*
* @author <a href="mailto:envkt@example.com">Aurel Medvegy</a>
* @see <a href="https://cloud.google.com/endpoints/docs/frameworks/java/authenticating-users">Authenticating Users</a>
* @see <a href="https://cloud.google.com/endpoints/docs/openapi/when-why-api-key">Why and When to Use API Keys</a>
*/
@Api( name = "Navi",
canonicalName = "Khufu's Cloud",
title = "khufuscloud.com Ecosystem Example REST API",
version = "v1",
description = "Example REST API",
documentationLink = "khufuscloud.atlassian.net",
namespace = @ApiNamespace( ownerDomain = "turnonline.biz", ownerName = "TurnOnline.biz, Ltd." ),
authenticators = {EspAuthenticator.class, GoogleOAuth2Authenticator.class},
issuers = {
@ApiIssuer(
name = "firebase",
issuer = "https://securetoken.google.com/" + PROJECT_ID,
jwksUri = "https:ychag@example.com" )
},
issuerAudiences = {
@ApiIssuerAudience( name = "firebase", audiences = PROJECT_ID )
}
)
public class EndpointsApiProfile
{
/**
* The API short and stable name, might be used publicly.
* Keep same as in {@code @Api( name = "Navi" )}
*/
public static final String API_NAME = "Navi";
static final String PROJECT_ID = "42";
}
|
3e0d8aea6b340d16f593cd63ae6278bea4e739ee | 378 | java | Java | src/LibExceptions/addLibrarianExceptionGui.java | idorom/Library-Project | 18659993b5623efeff36011e0e73681eb28a5b0b | [
"MIT"
] | null | null | null | src/LibExceptions/addLibrarianExceptionGui.java | idorom/Library-Project | 18659993b5623efeff36011e0e73681eb28a5b0b | [
"MIT"
] | null | null | null | src/LibExceptions/addLibrarianExceptionGui.java | idorom/Library-Project | 18659993b5623efeff36011e0e73681eb28a5b0b | [
"MIT"
] | null | null | null | 25.2 | 87 | 0.756614 | 5,728 | package LibExceptions;
import javax.swing.JOptionPane;
public class addLibrarianExceptionGui extends Exception {
private String ErrMsg;
public addLibrarianExceptionGui(String ErrMsg) {
this.ErrMsg="Missing or invalid data in the following field(s): " +ErrMsg ;
JOptionPane.showMessageDialog(null,this.ErrMsg ,"Error", JOptionPane.ERROR_MESSAGE);
}
}
|
3e0d8b56327d9f232a0ff67ee8e4d5a7a785b7c4 | 3,933 | java | Java | nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParser.java | JayUpadhyay-8/nacos-spring-project | 12883bbd2a5f26f51e711481eb79bac5b6c9fd85 | [
"Apache-2.0"
] | 690 | 2018-07-26T03:35:14.000Z | 2022-03-25T06:29:01.000Z | nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParser.java | JayUpadhyay-8/nacos-spring-project | 12883bbd2a5f26f51e711481eb79bac5b6c9fd85 | [
"Apache-2.0"
] | 164 | 2018-07-26T05:01:05.000Z | 2022-01-26T06:02:56.000Z | nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParser.java | JayUpadhyay-8/nacos-spring-project | 12883bbd2a5f26f51e711481eb79bac5b6c9fd85 | [
"Apache-2.0"
] | 255 | 2018-07-30T12:45:19.000Z | 2022-03-29T04:41:17.000Z | 44.224719 | 93 | 0.814278 | 5,729 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.alibaba.nacos.spring.context.config.xml;
import java.util.Properties;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.util.NacosBeanUtils;
import org.w3c.dom.Element;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.env.Environment;
import static com.alibaba.nacos.api.annotation.NacosProperties.ACCESS_KEY;
import static com.alibaba.nacos.api.annotation.NacosProperties.CLUSTER_NAME;
import static com.alibaba.nacos.api.annotation.NacosProperties.ENCODE;
import static com.alibaba.nacos.api.annotation.NacosProperties.ENDPOINT;
import static com.alibaba.nacos.api.annotation.NacosProperties.NAMESPACE;
import static com.alibaba.nacos.api.annotation.NacosProperties.PASSWORD;
import static com.alibaba.nacos.api.annotation.NacosProperties.SECRET_KEY;
import static com.alibaba.nacos.api.annotation.NacosProperties.SERVER_ADDR;
import static com.alibaba.nacos.api.annotation.NacosProperties.USERNAME;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.registerGlobalNacosProperties;
/**
* Nacos Global {@link Properties} {@link BeanDefinitionParser} for
* <nacos:global-properties ...>
*
* @author <a href="mailto:envkt@example.com">Mercy</a>
* @see NacosBeanUtils#GLOBAL_NACOS_PROPERTIES_BEAN_NAME
* @see NacosProperties
* @see PropertyKeyConst
* @since 0.1.0
*/
public class GlobalNacosPropertiesBeanDefinitionParser implements BeanDefinitionParser {
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
Properties properties = new Properties();
Environment environment = parserContext.getDelegate().getReaderContext()
.getReader().getEnvironment();
properties.setProperty(PropertyKeyConst.ENDPOINT, element.getAttribute(ENDPOINT));
properties.setProperty(PropertyKeyConst.NAMESPACE,
element.getAttribute(NAMESPACE));
properties.setProperty(PropertyKeyConst.ACCESS_KEY,
element.getAttribute(ACCESS_KEY));
properties.setProperty(PropertyKeyConst.SECRET_KEY,
element.getAttribute(SECRET_KEY));
properties.setProperty(PropertyKeyConst.SERVER_ADDR,
element.getAttribute(SERVER_ADDR));
properties.setProperty(PropertyKeyConst.CLUSTER_NAME,
element.getAttribute(CLUSTER_NAME));
properties.setProperty(PropertyKeyConst.ENCODE, element.getAttribute(ENCODE));
properties.setProperty(PropertyKeyConst.USERNAME, element.getAttribute(USERNAME));
properties.setProperty(PropertyKeyConst.PASSWORD, element.getAttribute(PASSWORD));
BeanDefinitionRegistry registry = parserContext.getRegistry();
// Register Global Nacos Properties as Spring singleton bean
registerGlobalNacosProperties(properties, registry, environment,
GLOBAL_NACOS_PROPERTIES_BEAN_NAME);
return null;
}
}
|
3e0d8bde0669c4c408316e97ca2f9f9aeb3311b3 | 3,833 | java | Java | src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.aarch64/src/jdk/vm/ci/aarch64/AArch64Kind.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.aarch64/src/jdk/vm/ci/aarch64/AArch64Kind.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | src/jdk.internal.vm.ci/share/classes/jdk.vm.ci.aarch64/src/jdk/vm/ci/aarch64/AArch64Kind.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | 25.553333 | 76 | 0.557527 | 5,730 | /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.vm.ci.aarch64;
import jdk.vm.ci.meta.PlatformKind;
public enum AArch64Kind implements PlatformKind {
// scalar
BYTE(1),
WORD(2),
DWORD(4),
QWORD(8),
SINGLE(4),
DOUBLE(8),
// SIMD
V32_BYTE(4, BYTE),
V32_WORD(4, WORD),
V64_BYTE(8, BYTE),
V64_WORD(8, WORD),
V64_DWORD(8, DWORD),
V128_BYTE(16, BYTE),
V128_WORD(16, WORD),
V128_DWORD(16, DWORD),
V128_QWORD(16, QWORD),
V128_SINGLE(16, SINGLE),
V128_DOUBLE(16, DOUBLE);
private final int size;
private final int vectorLength;
private final AArch64Kind scalar;
private final EnumKey<AArch64Kind> key = new EnumKey<>(this);
AArch64Kind(int size) {
this.size = size;
this.scalar = this;
this.vectorLength = 1;
}
AArch64Kind(int size, AArch64Kind scalar) {
this.size = size;
this.scalar = scalar;
assert size % scalar.size == 0;
this.vectorLength = size / scalar.size;
}
public AArch64Kind getScalar() {
return scalar;
}
public int getSizeInBytes() {
return size;
}
public int getVectorLength() {
return vectorLength;
}
public Key getKey() {
return key;
}
public boolean isInteger() {
switch (this) {
case BYTE:
case WORD:
case DWORD:
case QWORD:
return true;
default:
return false;
}
}
public boolean isSIMD() {
switch (this) {
case SINGLE:
case DOUBLE:
case V32_BYTE:
case V32_WORD:
case V64_BYTE:
case V64_WORD:
case V64_DWORD:
case V128_BYTE:
case V128_WORD:
case V128_DWORD:
case V128_QWORD:
case V128_SINGLE:
case V128_DOUBLE:
return true;
default:
return false;
}
}
public char getTypeChar() {
switch (this) {
case BYTE:
return 'b';
case WORD:
return 'w';
case DWORD:
return 'd';
case QWORD:
return 'q';
case SINGLE:
return 'S';
case DOUBLE:
return 'D';
case V32_BYTE:
case V32_WORD:
case V64_BYTE:
case V64_WORD:
case V64_DWORD:
case V128_BYTE:
case V128_WORD:
case V128_DWORD:
case V128_QWORD:
case V128_SINGLE:
case V128_DOUBLE:
return 'v';
default:
return '-';
}
}
}
|
3e0d8d1052566499331448ad02c3399e6c34d40b | 1,284 | java | Java | src/msg/version/UrlReader.java | afkvido/MessageEngine_alphatest | 3b46346f6b5733be943f1a379c1bc47e73a4b7ae | [
"Unlicense"
] | 4 | 2021-12-23T00:06:35.000Z | 2022-03-14T22:26:34.000Z | src/msg/version/UrlReader.java | afkvido/MessageEngine_alphatest | 3b46346f6b5733be943f1a379c1bc47e73a4b7ae | [
"Unlicense"
] | 3 | 2022-02-02T07:26:28.000Z | 2022-03-31T18:13:13.000Z | src/msg/version/UrlReader.java | afkvido/MessageEngine | 3b46346f6b5733be943f1a379c1bc47e73a4b7ae | [
"Unlicense"
] | 1 | 2022-03-07T19:39:03.000Z | 2022-03-07T19:39:03.000Z | 24.692308 | 87 | 0.591121 | 5,731 | package msg.version;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
/** This is used to read URLs. Improved by gemsvido, original from [idk]. <p></p>
* @author gemsvido
* @since 0.1.4 */
public interface UrlReader {
/** This String will determine if the URLreader failed or not*/
String fail = "URLreader failed";
/** Read a URL. <p></p>
* @author gemsvidø
* @since 0.2.0 */
static @NotNull String check (@NotNull String url) {
String r;
try {
r = read(url);
} catch (Exception ignored) {
r = fail;
}
return r;
}
/** Read a URL, if it couldn't return a String then it throws an Exception. <p></p>
* @author gemsvidø
* @since 0.2.0 */
static @NotNull String read (@NotNull String url) throws Exception {
URL oracle = new URL(url);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
StringBuilder r = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
r.append(inputLine).append("\n");
in.close();
return r.toString();
}
} |
3e0d8df84c3f03218bb7e8e1f1a59fa10decf8cd | 311 | java | Java | library/src/main/java/de/jochen_schweizer/stackedStickyHeaders/StackedStickyHeadersAdapter.java | github-jsts/StackedStickyHeaders | 99d3da95f7b8d8bcaa4f8a791778a28c43d97f9e | [
"MIT"
] | 3 | 2016-05-05T12:13:24.000Z | 2016-07-26T20:40:35.000Z | library/src/main/java/de/jochen_schweizer/stackedStickyHeaders/StackedStickyHeadersAdapter.java | jochen-schweizer/StackedStickyHeaders | 99d3da95f7b8d8bcaa4f8a791778a28c43d97f9e | [
"MIT"
] | null | null | null | library/src/main/java/de/jochen_schweizer/stackedStickyHeaders/StackedStickyHeadersAdapter.java | jochen-schweizer/StackedStickyHeaders | 99d3da95f7b8d8bcaa4f8a791778a28c43d97f9e | [
"MIT"
] | null | null | null | 20.733333 | 71 | 0.77492 | 5,732 | package de.jochen_schweizer.stackedStickyHeaders;
import android.widget.BaseAdapter;
/**
* Created by ganevlyu on 20/07/16.
*/
public abstract class StackedStickyHeadersAdapter extends BaseAdapter {
public abstract int[] getHeadersViewTypeIds();
public abstract int[] getHeadersViewsHeights();
}
|
3e0d8e8d55f1611fc649ffafb7a0fdb10cfa0fa7 | 549 | java | Java | paascloud-common/paascloud-security-core/src/main/java/com/paascloud/security/core/validate/code/email/EmailCodeSender.java | xueyuyang/miniServerSecond | bda8def83a478b7789b6ca30759f2fb64116577b | [
"Apache-2.0"
] | 10,031 | 2018-03-17T07:40:56.000Z | 2022-03-31T06:22:56.000Z | paascloud-common/paascloud-security-core/src/main/java/com/paascloud/security/core/validate/code/email/EmailCodeSender.java | 1105748319/paascloud-master | 781281a9503332ed3cef44ea618349d14230a127 | [
"Apache-2.0"
] | 139 | 2018-03-19T06:34:23.000Z | 2021-12-09T19:48:33.000Z | paascloud-common/paascloud-security-core/src/main/java/com/paascloud/security/core/validate/code/email/EmailCodeSender.java | 1105748319/paascloud-master | 781281a9503332ed3cef44ea618349d14230a127 | [
"Apache-2.0"
] | 4,495 | 2017-12-01T06:37:15.000Z | 2022-03-31T15:08:05.000Z | 18.866667 | 57 | 0.689046 | 5,733 | /*
* Copyright (c) 2018. paascloud.net All Rights Reserved.
* 项目名称:paascloud快速搭建企业级分布式微服务平台
* 类名称:EmailCodeSender.java
* 创建人:刘兆明
* ychag@example.com
* 开源地址: https://github.com/paascloud
* 博客地址: http://blog.paascloud.net
* 项目官网: http://paascloud.net
*/
package com.paascloud.security.core.validate.code.email;
/**
* The interface Sms code sender.
*
* @author upchh@example.com
*/
public interface EmailCodeSender {
/**
* Send.
*
* @param email the email
* @param code the code
*/
void send(String email, String code);
}
|
3e0d8f44ba3fc7f085bebabfa5fc1b09edf36e40 | 25,180 | java | Java | config/config-api/src/test/java/com/thoughtworks/go/config/BasicEnvironmentConfigTest.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,865 | 2015-01-02T04:24:52.000Z | 2022-03-31T11:00:46.000Z | config/config-api/src/test/java/com/thoughtworks/go/config/BasicEnvironmentConfigTest.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,972 | 2015-01-02T10:20:42.000Z | 2022-03-31T20:17:09.000Z | config/config-api/src/test/java/com/thoughtworks/go/config/BasicEnvironmentConfigTest.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 998 | 2015-01-01T18:02:09.000Z | 2022-03-28T21:20:50.000Z | 44.253076 | 145 | 0.723233 | 5,734 | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* 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.thoughtworks.go.config;
import com.thoughtworks.go.config.remote.ConfigOrigin;
import com.thoughtworks.go.config.remote.FileConfigOrigin;
import com.thoughtworks.go.config.remote.RepoConfigOrigin;
import com.thoughtworks.go.config.remote.UIConfigOrigin;
import com.thoughtworks.go.domain.ConfigErrors;
import com.thoughtworks.go.domain.EnvironmentPipelineMatcher;
import com.thoughtworks.go.helper.GoConfigMother;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import static com.thoughtworks.go.config.ConfigSaveValidationContext.forChain;
import static com.thoughtworks.go.helper.EnvironmentConfigMother.environment;
import static com.thoughtworks.go.helper.EnvironmentConfigMother.remote;
import static com.thoughtworks.go.util.command.EnvironmentVariableContext.GO_ENVIRONMENT_NAME;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.jupiter.api.Assertions.*;
class BasicEnvironmentConfigTest extends EnvironmentConfigTestBase {
@BeforeEach
void setUp() throws Exception {
environmentConfig = new BasicEnvironmentConfig(new CaseInsensitiveString("UAT"));
}
@Test
void shouldReturnEmptyForRemotePipelinesWhenIsLocal() {
environmentConfig.addPipeline(new CaseInsensitiveString("pipe"));
assertThat(environmentConfig.getRemotePipelines().isEmpty()).isTrue();
}
@Test
void shouldReturnAllPipelinesForRemotePipelinesWhenIsRemote() {
environmentConfig.setOrigins(new RepoConfigOrigin());
environmentConfig.addPipeline(new CaseInsensitiveString("pipe"));
assertThat(environmentConfig.getRemotePipelines().isEmpty()).isFalse();
}
@Test
void shouldReturnTrueThatLocalWhenOriginIsNotSet() {
environmentConfig.setOrigins(null);
assertThat(environmentConfig.isLocal()).isTrue();
}
@Test
void shouldSetOriginSetOriginForEnvConfigAndEnvVariables(){
environmentConfig.addEnvironmentVariable("var1", "value1");
environmentConfig.addEnvironmentVariable("var2", "value2");
FileConfigOrigin fileOrigin = new FileConfigOrigin();
environmentConfig.setOrigins(fileOrigin);
assertThat(environmentConfig.getOrigin()).isEqualTo(fileOrigin);
assertThat(environmentConfig.getVariables().size() == 2);
environmentConfig.getVariables().forEach(var -> assertThat(var.getOrigin()).isEqualTo(fileOrigin));
}
@Test
void shouldSetOriginSetOriginToNullForEnvConfigAndEnvVariables(){
environmentConfig.addEnvironmentVariable("var1", "value1");
environmentConfig.addEnvironmentVariable("var2", "value2");
environmentConfig.setOrigins(null);
assertThat(environmentConfig.getOrigin()).isNull();
assertThat(environmentConfig.getVariables().size() == 2);
environmentConfig.getVariables().forEach(var -> assertThat(var.getOrigin()).isNull());
}
@Test
void shouldReturnTrueThatLocalWhenOriginIsFile() {
environmentConfig.setOrigins(new FileConfigOrigin());
assertThat(environmentConfig.isLocal()).isTrue();
}
@Test
void shouldReturnFalseThatLocalWhenOriginIsConfigRepo() {
environmentConfig.setOrigins(new RepoConfigOrigin());
assertThat(environmentConfig.isLocal()).isFalse();
}
@Test
void shouldReturnSelfAsLocalPartWhenOriginIsFile() {
environmentConfig.setOrigins(new FileConfigOrigin());
assertThat(environmentConfig.getLocal()).isSameAs(environmentConfig);
}
@Test
void shouldReturnSelfAsLocalPartWhenOriginIsUI() {
environmentConfig.setOrigins(new UIConfigOrigin());
assertThat(environmentConfig.getLocal()).isSameAs(environmentConfig);
}
@Test
void shouldReturnNullAsLocalPartWhenOriginIsConfigRepo() {
environmentConfig.setOrigins(new RepoConfigOrigin());
assertThat(environmentConfig.getLocal()).isNull();
}
@Test
void shouldUpdateName() {
environmentConfig.setConfigAttributes(Collections.singletonMap(BasicEnvironmentConfig.NAME_FIELD, "PROD"));
assertThat(environmentConfig.name()).isEqualTo(new CaseInsensitiveString("PROD"));
}
@Nested
class Validate {
@Test
void shouldReturnTrueIfAssociatedAgentUUIDsAreFromSpecifiedSetOfUUIDs(){
environmentConfig.addAgent("uuid1");
environmentConfig.addAgent("uuid2");
environmentConfig.addAgent("uuid3");
boolean result = environmentConfig.validateContainsAgentUUIDsFrom(new HashSet<>(asList("uuid1", "uuid2", "uuid3", "uuid4")));
assertThat(result).isTrue();
}
@Test
void shouldReturnFalseIfAssociatedAgentUUIDsAreNotFromSpecifiedSetOfUUIDs(){
environmentConfig.addAgent("uuid1");
environmentConfig.addAgent("uuid2");
environmentConfig.addAgent("uuid3");
boolean result = environmentConfig.validateContainsAgentUUIDsFrom(new HashSet<>(asList("uuid1", "uuid2", "uuid4")));
assertThat(result).isFalse();
}
@Test
void shouldReturnFalseIfAssociatedAgentUUIDsAreNotFromSpecifiedSetOfUUIDsBecauseSpecifiedSetIsEmpty(){
environmentConfig.addAgent("uuid1");
environmentConfig.addAgent("uuid2");
environmentConfig.addAgent("uuid3");
boolean result = environmentConfig.validateContainsAgentUUIDsFrom(new HashSet<>(emptyList()));
assertThat(result).isFalse();
}
@Test
void shouldNotAllowToReferencePipelineDefinedInConfigRepo_WhenEnvironmentDefinedInFile() {
ConfigOrigin pipelineOrigin = new RepoConfigOrigin();
ConfigOrigin envOrigin = new FileConfigOrigin();
BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipe1");
cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("pipe1")).setOrigin(pipelineOrigin);
BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) BasicEnvironmentConfigTest.this.environmentConfig;
environmentConfig.setOrigins(envOrigin);
environmentConfig.addPipeline(new CaseInsensitiveString("pipe1"));
cruiseConfig.addEnvironment(environmentConfig);
environmentConfig.validate(forChain(cruiseConfig, environmentConfig));
EnvironmentPipelineConfig reference = environmentConfig.getPipelines().first();
assertThat(reference.errors()).isNotEmpty();
assertThat(reference.errors().on(EnvironmentPipelineConfig.ORIGIN)).startsWith("Environment defined in");
}
@Test
void shouldAllowToReferencePipelineDefinedInConfigRepo_WhenEnvironmentDefinedInConfigRepo() {
ConfigOrigin pipelineOrigin = new RepoConfigOrigin();
ConfigOrigin envOrigin = new RepoConfigOrigin();
passReferenceValidationHelper(pipelineOrigin, envOrigin);
}
@Test
void shouldAllowToReferencePipelineDefinedInFile_WhenEnvironmentDefinedInFile() {
ConfigOrigin pipelineOrigin = new FileConfigOrigin();
ConfigOrigin envOrigin = new FileConfigOrigin();
passReferenceValidationHelper(pipelineOrigin, envOrigin);
}
@Test
void shouldAllowToReferencePipelineDefinedInFile_WhenEnvironmentDefinedInConfigRepo() {
ConfigOrigin pipelineOrigin = new FileConfigOrigin();
ConfigOrigin envOrigin = new RepoConfigOrigin();
passReferenceValidationHelper(pipelineOrigin, envOrigin);
}
}
@Test
void shouldReturnPipelineNames() {
CaseInsensitiveString pipeline1 = new CaseInsensitiveString("Pipeline1");
CaseInsensitiveString pipeline2 = new CaseInsensitiveString("Pipeline2");
environmentConfig.addPipeline(pipeline1);
environmentConfig.addPipeline(pipeline2);
assertThat(environmentConfig.getPipelineNames()).isEqualTo(asList(pipeline1, pipeline2));
}
@Test
void shouldReturnEmptyListAsPipelineNamesWhenThereAreNoPipelinesAssociated() {
assertThat(environmentConfig.getPipelineNames()).isEqualTo(emptyList());
}
@Test
void shouldValidateWhenPipelineNotFound() {
ConfigOrigin pipelineOrigin = new RepoConfigOrigin();
ConfigOrigin envOrigin = new FileConfigOrigin();
BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipe1");
cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("pipe1")).setOrigin(pipelineOrigin);
BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) this.environmentConfig;
environmentConfig.setOrigins(envOrigin);
environmentConfig.addPipeline(new CaseInsensitiveString("unknown"));
cruiseConfig.addEnvironment(environmentConfig);
environmentConfig.validate(forChain(cruiseConfig, environmentConfig));
EnvironmentPipelineConfig reference = environmentConfig.getPipelines().first();
assertThat(reference.errors().isEmpty()).isTrue();
}
@Nested
class ValidateTree {
@Test
void shouldNotAllowToReferencePipelineDefinedInConfigRepo_WhenEnvironmentDefinedInFile() {
ConfigOrigin pipelineOrigin = new RepoConfigOrigin();
ConfigOrigin envOrigin = new FileConfigOrigin();
BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipe1");
cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("pipe1")).setOrigin(pipelineOrigin);
BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) BasicEnvironmentConfigTest.this.environmentConfig;
environmentConfig.setOrigins(envOrigin);
environmentConfig.addPipeline(new CaseInsensitiveString("pipe1"));
cruiseConfig.addEnvironment(environmentConfig);
environmentConfig.validateTree(forChain(cruiseConfig, environmentConfig), cruiseConfig);
EnvironmentPipelineConfig reference = environmentConfig.getPipelines().first();
assertThat(reference.errors()).isNotEmpty();
assertThat(reference.errors().on(EnvironmentPipelineConfig.ORIGIN)).startsWith("Environment defined in");
}
@Test
void shouldAllowToReferencePipelineDefinedInConfigRepo_WhenEnvironmentDefinedInConfigRepo() {
ConfigOrigin pipelineOrigin = new RepoConfigOrigin();
ConfigOrigin envOrigin = new RepoConfigOrigin();
passReferenceValidationHelperForValidateTree(pipelineOrigin, envOrigin);
}
@Test
void shouldAllowToReferencePipelineDefinedInFile_WhenEnvironmentDefinedInFile() {
ConfigOrigin pipelineOrigin = new FileConfigOrigin();
ConfigOrigin envOrigin = new FileConfigOrigin();
passReferenceValidationHelperForValidateTree(pipelineOrigin, envOrigin);
}
@Test
void shouldAllowToReferencePipelineDefinedInFile_WhenEnvironmentDefinedInConfigRepo() {
ConfigOrigin pipelineOrigin = new FileConfigOrigin();
ConfigOrigin envOrigin = new RepoConfigOrigin();
passReferenceValidationHelperForValidateTree(pipelineOrigin, envOrigin);
}
@Test
void shouldValidateEnvVariables() {
ConfigOrigin repoConfigOrigin = new RepoConfigOrigin();
BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipe1");
cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("pipe1")).setOrigin(repoConfigOrigin);
BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) BasicEnvironmentConfigTest.this.environmentConfig;
environmentConfig.setOrigins(repoConfigOrigin);
environmentConfig.addPipeline(new CaseInsensitiveString("pipe1"));
environmentConfig.addEnvironmentVariable(" ", "bar");
cruiseConfig.addEnvironment(environmentConfig);
boolean validate = environmentConfig.validateTree(forChain(cruiseConfig, environmentConfig), cruiseConfig);
List<ConfigErrors> configErrors = environmentConfig.getAllErrors();
assertThat(validate).isFalse();
assertThat(configErrors).isNotEmpty();
assertThat(configErrors.get(0).on("name")).isEqualTo("Environment Variable cannot have an empty name for environment 'UAT'.");
}
@Test
void shouldValidateViaValidateTreeWhenPipelineNotFound() {
ConfigOrigin pipelineOrigin = new RepoConfigOrigin();
ConfigOrigin envOrigin = new FileConfigOrigin();
BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipe1");
cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("pipe1")).setOrigin(pipelineOrigin);
BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) BasicEnvironmentConfigTest.this.environmentConfig;
environmentConfig.setOrigins(envOrigin);
environmentConfig.addPipeline(new CaseInsensitiveString("unknown"));
cruiseConfig.addEnvironment(environmentConfig);
environmentConfig.validate(forChain(cruiseConfig, environmentConfig));
EnvironmentPipelineConfig reference = environmentConfig.getPipelines().first();
assertThat(reference.errors().isEmpty()).isTrue();
}
}
@Test
void shouldReturnEnvironmentContextWithGO_ENVIRONMENT_NAMEVariableWhenNoEnvironmentVariablesAreDefined() {
EnvironmentVariableContext environmentContext = environmentConfig.createEnvironmentContext();
assertThat(environmentContext.getProperties()).hasSize(1);
assertThat(environmentContext.getProperty(GO_ENVIRONMENT_NAME)).isEqualTo(environmentConfig.name().toString());
}
@Test
void shouldReturnEnvironmentContextWithGO_ENVIRONMENT_NAMEVariableWhenEnvironmentVariablesAreDefined() {
environmentConfig.addEnvironmentVariable("foo", "bar");
EnvironmentVariableContext environmentContext = environmentConfig.createEnvironmentContext();
assertThat(environmentContext.getProperties()).hasSize(2);
assertThat(environmentContext.getProperty(GO_ENVIRONMENT_NAME)).isEqualTo(environmentConfig.name().toString());
assertThat(environmentContext.getProperty("foo")).isEqualTo("bar");
}
@Test
void shouldAddErrorToTheConfig() {
assertTrue(environmentConfig.errors().isEmpty());
environmentConfig.addError("field-name", "some error message.");
assertThat(environmentConfig.errors().size()).isEqualTo(1);
assertThat(environmentConfig.errors().on("field-name")).isEqualTo("some error message.");
}
@Test
void shouldReturnMatchersWithTheProperties() {
environmentConfig.addPipeline(new CaseInsensitiveString("pipeline-1"));
environmentConfig.addAgent("agent-1");
EnvironmentPipelineMatcher matcher = environmentConfig.createMatcher();
assertNotNull(matcher);
assertThat(matcher.name()).isEqualTo(environmentConfig.name());
assertTrue(matcher.hasPipeline("pipeline-1"));
assertTrue(matcher.match("pipeline-1", "agent-1"));
assertFalse(matcher.hasPipeline("non-existent-pipeline"));
}
@Test
void shouldNotThrowExceptionIfAllThePipelinesArePresent() {
CaseInsensitiveString p1 = new CaseInsensitiveString("pipeline-1");
CaseInsensitiveString p2 = new CaseInsensitiveString("pipeline-2");
environmentConfig.addPipeline(p1);
environmentConfig.addPipeline(p2);
assertThatCode(() -> environmentConfig.validateContainsOnlyPipelines(asList(p1, p2)))
.doesNotThrowAnyException();
}
@Test
void shouldThrowExceptionIfOneOfThePipelinesAreNotPassed() {
CaseInsensitiveString p1 = new CaseInsensitiveString("pipeline-1");
CaseInsensitiveString p2 = new CaseInsensitiveString("pipeline-2");
CaseInsensitiveString p3 = new CaseInsensitiveString("pipeline-3");
environmentConfig.addPipeline(p1);
environmentConfig.addPipeline(p2);
assertThatCode(() -> environmentConfig.validateContainsOnlyPipelines(asList(p1, p3)))
.isInstanceOf(RuntimeException.class)
.hasMessage("Environment 'UAT' refers to an unknown pipeline 'pipeline-2'.");
}
@Test
void shouldReturnTrueIsChildConfigContainsNoPipelineAgentsAndVariables() {
assertTrue(environmentConfig.isEnvironmentEmpty());
}
@Test
void shouldReturnFalseIfNotEmpty() {
environmentConfig.addPipeline(new CaseInsensitiveString("pipeline1"));
assertFalse(environmentConfig.isEnvironmentEmpty());
}
@Nested
class ContainsAgentRemotely {
@Test
void shouldReturnTrueIfTheEnvAgentAssociationIsFromConfigRepo() {
BasicEnvironmentConfig environmentConfig = remote("env1");
String uuid = "uuid";
environmentConfig.addAgent(uuid);
assertThat(environmentConfig.containsAgentRemotely(uuid)).isTrue();
}
@Test
void shouldReturnFalseIfTheAgentIsNotPresentInTheEnvFromConfigRepo() {
BasicEnvironmentConfig environmentConfig = remote("env1");
String uuid = "uuid";
assertThat(environmentConfig.containsAgentRemotely(uuid)).isFalse();
}
@Test
void shouldReturnFalseIfTheEnvAgentAssociationIsFromConfigXml() {
BasicEnvironmentConfig environmentConfig = environment("env1");
String uuid = "uuid";
environmentConfig.addAgent(uuid);
assertThat(environmentConfig.containsAgentRemotely(uuid)).isFalse();
}
@Test
void shouldReturnFalseIfTheOriginIsNull() {
BasicEnvironmentConfig environmentConfig = new BasicEnvironmentConfig(new CaseInsensitiveString("env1"));
String uuid = "uuid";
environmentConfig.addAgent(uuid);
assertThat(environmentConfig.getOrigin()).isNull();
assertThat(environmentConfig.containsAgentRemotely(uuid)).isFalse();
}
}
@Nested
class ContainsPipelineRemotely {
@Test
void shouldReturnTrueIfTheEnvPipelineAssociationIsFromConfigRepo() {
BasicEnvironmentConfig environmentConfig = remote("env1");
CaseInsensitiveString pipeline = new CaseInsensitiveString("Pipeline");
environmentConfig.addPipeline(pipeline);
assertThat(environmentConfig.containsPipelineRemotely(pipeline)).isTrue();
}
@Test
void shouldReturnFalseIfThePipelineIsNotPresentInTheEnvFromConfigRepo() {
BasicEnvironmentConfig environmentConfig = remote("env1");
CaseInsensitiveString pipeline = new CaseInsensitiveString("Pipeline");
assertThat(environmentConfig.containsPipelineRemotely(pipeline)).isFalse();
}
@Test
void shouldReturnFalseIfTheEnvPipelineAssociationIsFromConfigXml() {
BasicEnvironmentConfig environmentConfig = environment("env1");
assertThat(environmentConfig.getRemotePipelines()).isEqualTo(emptyList());
assertThat(environmentConfig.getPipelines()).size().isEqualTo(1);
environmentConfig.getPipelineNames().forEach(pipeline -> assertThat(environmentConfig.containsPipelineRemotely(pipeline)).isFalse());
}
@Test
void shouldReturnFalseIfTheOriginIsNull() {
BasicEnvironmentConfig environmentConfig = new BasicEnvironmentConfig(new CaseInsensitiveString("env1"));
CaseInsensitiveString pipeline = new CaseInsensitiveString("Pipeline");
environmentConfig.addPipeline(pipeline);
assertThat(environmentConfig.getOrigin()).isNull();
assertThat(environmentConfig.containsPipelineRemotely(pipeline)).isFalse();
}
}
@Nested
class ContainsEnvironmentVariablesRemotely {
@Test
void shouldReturnTrueIfTheEnvVarAssociationIsFromConfigRepo() {
BasicEnvironmentConfig environmentConfig = remote("env1");
environmentConfig.addEnvironmentVariable("var1", "value1");
assertThat(environmentConfig.containsEnvironmentVariableRemotely("var1")).isTrue();
}
@Test
void shouldReturnFalseIfTheVarIsNotPresentInTheEnvFromConfigRepo() {
BasicEnvironmentConfig environmentConfig = remote("env1");
assertThat(environmentConfig.containsEnvironmentVariableRemotely("var1")).isFalse();
}
@Test
void shouldReturnFalseIfTheEnvVarAssociationIsFromConfigXml() {
BasicEnvironmentConfig environmentConfig = environment("env1");
environmentConfig.addEnvironmentVariable("var1", "value1");
environmentConfig.getVariables().forEach(var -> assertThat(environmentConfig.containsEnvironmentVariableRemotely("var1")).isFalse());
}
@Test
void shouldReturnFalseIfTheOriginIsNull() {
BasicEnvironmentConfig environmentConfig = new BasicEnvironmentConfig(new CaseInsensitiveString("env1"));
environmentConfig.addEnvironmentVariable("var1", "value1");
assertThat(environmentConfig.getOrigin()).isNull();
assertThat(environmentConfig.containsEnvironmentVariableRemotely("var1")).isFalse();
}
}
@Test
void shouldReturnEmptyOptionalIfEnvDoesNotContainTheAgent() {
Optional<ConfigOrigin> originForAgent = this.environmentConfig.originForAgent("uuid");
assertThat(originForAgent.isPresent()).isFalse();
}
@Test
void shouldReturnOriginIfEnvContainsTheAgent() {
String uuid = "uuid";
this.environmentConfig.addAgent(uuid);
this.environmentConfig.setOrigins(new FileConfigOrigin());
Optional<ConfigOrigin> originForAgent = this.environmentConfig.originForAgent(uuid);
assertThat(originForAgent.isPresent()).isTrue();
assertThat(originForAgent.get().displayName()).isEqualTo("cruise-config.xml");
}
@Test
void shouldReturnFalseIfEnvDoesNotContainTheSpecifiedAgentUuid() {
assertThat(this.environmentConfig.hasAgent("uuid")).isFalse();
}
@Test
void shouldReturnTrueIfEnvContainsTheSpecifiedAgentUuid() {
this.environmentConfig.addAgent("uuid");
assertThat(this.environmentConfig.hasAgent("uuid")).isTrue();
}
private void passReferenceValidationHelper(ConfigOrigin pipelineOrigin, ConfigOrigin envOrigin) {
BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipe1");
cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("pipe1")).setOrigin(pipelineOrigin);
BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) this.environmentConfig;
environmentConfig.setOrigins(envOrigin);
environmentConfig.addPipeline(new CaseInsensitiveString("pipe1"));
cruiseConfig.addEnvironment(environmentConfig);
environmentConfig.validate(forChain(cruiseConfig, environmentConfig));
EnvironmentPipelineConfig reference = environmentConfig.getPipelines().first();
assertThat(reference.errors().isEmpty()).isTrue();
}
private void passReferenceValidationHelperForValidateTree(ConfigOrigin pipelineOrigin, ConfigOrigin envOrigin) {
BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("pipe1");
cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("pipe1")).setOrigin(pipelineOrigin);
BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) this.environmentConfig;
environmentConfig.setOrigins(envOrigin);
environmentConfig.addPipeline(new CaseInsensitiveString("pipe1"));
cruiseConfig.addEnvironment(environmentConfig);
environmentConfig.validateTree(forChain(cruiseConfig, environmentConfig), cruiseConfig);
EnvironmentPipelineConfig reference = environmentConfig.getPipelines().first();
assertThat(reference.errors().isEmpty()).isTrue();
}
}
|
3e0d922a08255825da178c9407d99eba80e6d12a | 1,522 | java | Java | spring-webscripts/spring-webscripts/src/main/java/org/springframework/extensions/webscripts/annotation/ScriptParameter.java | LMRob/surf-webscripts | 085a93a78ab8aa90ece5a926fbf27f6325182633 | [
"Apache-2.0"
] | 4 | 2019-02-08T14:08:38.000Z | 2021-05-25T13:08:25.000Z | spring-webscripts/spring-webscripts/src/main/java/org/springframework/extensions/webscripts/annotation/ScriptParameter.java | LMRob/surf-webscripts | 085a93a78ab8aa90ece5a926fbf27f6325182633 | [
"Apache-2.0"
] | 88 | 2018-04-30T09:47:33.000Z | 2021-12-15T08:17:48.000Z | spring-webscripts/spring-webscripts/src/main/java/org/springframework/extensions/webscripts/annotation/ScriptParameter.java | LMRob/surf-webscripts | 085a93a78ab8aa90ece5a926fbf27f6325182633 | [
"Apache-2.0"
] | 9 | 2018-05-16T14:48:54.000Z | 2021-05-25T13:08:27.000Z | 29.843137 | 115 | 0.717477 | 5,735 | /**
* Copyright (C) 2005-2009 Alfresco Software Limited.
*
* This file is part of the Spring Surf Extension project.
*
* 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 org.springframework.extensions.webscripts.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Custom annotation type for method parameters.
*
* @author drq
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ScriptParameter
{
/**
* @return a user friendly display name for the parameter
*/
String name() default "";
/**
* @return a help message for this parameter (the default is a blank String, which means there is no help)
*/
String help() default "";
/**
* @return code snippet for this parameter (the default is a blank String, which means there is no sample code)
*/
String code() default "";
}
|
3e0d94ab33b7a6bdf539015deda2d4b70fb0cc56 | 687 | java | Java | src/main/java/com/wxmp/core/domain/ajax/BaseAjaxResult.java | SethMessenger/wechat-manage | e5f4f480f6e3c87de004eaa04237862e417a3e6f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/wxmp/core/domain/ajax/BaseAjaxResult.java | SethMessenger/wechat-manage | e5f4f480f6e3c87de004eaa04237862e417a3e6f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/wxmp/core/domain/ajax/BaseAjaxResult.java | SethMessenger/wechat-manage | e5f4f480f6e3c87de004eaa04237862e417a3e6f | [
"Apache-2.0"
] | null | null | null | 16.756098 | 46 | 0.572052 | 5,736 | package com.wxmp.core.domain.ajax;
/**
* @author xunbo.xu
* @desc 用于进行ajax返回值的传递的基类
* @date 18/3/27
*/
public class BaseAjaxResult {
/** 返回消息 */
private String msg;
/** 服务器时间戳 */
private long timestamp;
/** 服务器返回编码 */
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
|
3e0d962399cf54e4079528f97246b70f468d5916 | 29,892 | java | Java | modules/spring-mock-mvc/src/main/java/io/restassured/module/mockmvc/internal/MockMvcRequestSenderImpl.java | richardfearn/rest-assured | 4eeb3d82b1d4672787b57ca45167a63085c8c1f1 | [
"Apache-2.0"
] | 5,038 | 2016-05-20T09:22:37.000Z | 2022-03-31T12:39:54.000Z | modules/spring-mock-mvc/src/main/java/io/restassured/module/mockmvc/internal/MockMvcRequestSenderImpl.java | richardfearn/rest-assured | 4eeb3d82b1d4672787b57ca45167a63085c8c1f1 | [
"Apache-2.0"
] | 899 | 2016-05-21T06:09:57.000Z | 2022-03-31T05:33:52.000Z | modules/spring-mock-mvc/src/main/java/io/restassured/module/mockmvc/internal/MockMvcRequestSenderImpl.java | richardfearn/rest-assured | 4eeb3d82b1d4672787b57ca45167a63085c8c1f1 | [
"Apache-2.0"
] | 1,601 | 2016-05-23T03:43:21.000Z | 2022-03-31T13:59:33.000Z | 43.637956 | 216 | 0.673759 | 5,737 | /*
* Copyright 2019 the original author or authors.
*
* 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 io.restassured.module.mockmvc.internal;
import io.restassured.RestAssured;
import io.restassured.authentication.NoAuthScheme;
import io.restassured.builder.MultiPartSpecBuilder;
import io.restassured.filter.Filter;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.time.TimingFilter;
import io.restassured.http.*;
import io.restassured.internal.RequestSpecificationImpl;
import io.restassured.internal.ResponseParserRegistrar;
import io.restassured.internal.ResponseSpecificationImpl;
import io.restassured.internal.filter.FilterContextImpl;
import io.restassured.internal.log.LogRepository;
import io.restassured.internal.support.PathSupport;
import io.restassured.internal.util.SafeExceptionRethrower;
import io.restassured.module.mockmvc.config.RestAssuredMockMvcConfig;
import io.restassured.module.mockmvc.intercept.MockHttpServletRequestBuilderInterceptor;
import io.restassured.module.mockmvc.response.MockMvcResponse;
import io.restassured.module.mockmvc.specification.MockMvcRequestAsyncConfigurer;
import io.restassured.module.mockmvc.specification.MockMvcRequestAsyncSender;
import io.restassured.module.mockmvc.specification.MockMvcRequestSender;
import io.restassured.module.spring.commons.BodyHelper;
import io.restassured.module.spring.commons.HeaderHelper;
import io.restassured.module.spring.commons.ParamApplier;
import io.restassured.module.spring.commons.config.AsyncConfig;
import io.restassured.module.spring.commons.config.ConfigConverter;
import io.restassured.specification.ResponseSpecification;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.security.Principal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static io.restassured.internal.common.assertion.AssertParameter.notNull;
import static io.restassured.internal.support.PathSupport.mergeAndRemoveDoubleSlash;
import static io.restassured.module.mockmvc.internal.SpringSecurityClassPathChecker.isSpringSecurityInClasspath;
import static io.restassured.module.spring.commons.HeaderHelper.mapToArray;
import static io.restassured.module.spring.commons.RequestLogger.logParamsAndHeaders;
import static io.restassured.module.spring.commons.RequestLogger.logRequestBody;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import static org.springframework.http.HttpMethod.*;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
class MockMvcRequestSenderImpl implements MockMvcRequestSender, MockMvcRequestAsyncConfigurer, MockMvcRequestAsyncSender {
private static final String ATTRIBUTE_NAME_URL_TEMPLATE = "org.springframework.restdocs.urlTemplate";
private static final String CONTENT_TYPE = "Content-Type";
private static final String CHARSET = "charset";
private final MockMvc mockMvc;
private final Map<String, Object> params;
private final Map<String, Object> queryParams;
private final Map<String, Object> formParams;
private final Map<String, Object> attributes;
private final RestAssuredMockMvcConfig config;
private final Object requestBody;
private Headers headers;
private final Cookies cookies;
private final List<MockMvcMultiPart> multiParts;
private final RequestLoggingFilter requestLoggingFilter;
private final List<ResultHandler> resultHandlers;
private final List<RequestPostProcessor> requestPostProcessors;
private final MockHttpServletRequestBuilderInterceptor interceptor;
private final String basePath;
private final ResponseSpecification responseSpecification;
private final Object authentication;
private final LogRepository logRepository;
private final boolean isAsyncRequest;
private final Map<String, Object> sessionAttributes;
MockMvcRequestSenderImpl(MockMvc mockMvc, Map<String, Object> params, Map<String, Object> queryParams, Map<String, Object> formParams, Map<String, Object> attributes,
RestAssuredMockMvcConfig config, Object requestBody, Headers headers, Cookies cookies, Map<String, Object> sessionAttributes,
List<MockMvcMultiPart> multiParts, RequestLoggingFilter requestLoggingFilter, List<ResultHandler> resultHandlers,
List<RequestPostProcessor> requestPostProcessors, MockHttpServletRequestBuilderInterceptor interceptor, String basePath, ResponseSpecification responseSpecification,
Object authentication, LogRepository logRepository) {
this(mockMvc, params, queryParams, formParams, attributes, config, requestBody, headers, cookies, sessionAttributes, multiParts, requestLoggingFilter, resultHandlers, requestPostProcessors, interceptor,
basePath, responseSpecification, authentication, logRepository, false);
}
private MockMvcRequestSenderImpl(MockMvc mockMvc, Map<String, Object> params, Map<String, Object> queryParams, Map<String, Object> formParams, Map<String, Object> attributes,
RestAssuredMockMvcConfig config, Object requestBody, Headers headers, Cookies cookies, Map<String, Object> sessionAttributes,
List<MockMvcMultiPart> multiParts, RequestLoggingFilter requestLoggingFilter, List<ResultHandler> resultHandlers,
List<RequestPostProcessor> requestPostProcessors, MockHttpServletRequestBuilderInterceptor interceptor, String basePath, ResponseSpecification responseSpecification,
Object authentication, LogRepository logRepository, boolean isAsyncRequest) {
this.mockMvc = mockMvc;
this.params = params;
this.queryParams = queryParams;
this.formParams = formParams;
this.attributes = attributes;
this.config = config;
this.requestBody = requestBody;
this.headers = headers;
this.cookies = cookies;
this.sessionAttributes = sessionAttributes;
this.multiParts = multiParts;
this.requestLoggingFilter = requestLoggingFilter;
this.resultHandlers = resultHandlers;
this.requestPostProcessors = requestPostProcessors;
this.interceptor = interceptor;
this.basePath = basePath;
this.responseSpecification = responseSpecification;
this.authentication = authentication;
this.logRepository = logRepository;
this.isAsyncRequest = isAsyncRequest;
}
private Object assembleHeaders(MockHttpServletResponse response) {
Collection<String> headerNames = response.getHeaderNames();
List<Header> headers = new ArrayList<>();
for (String headerName : headerNames) {
List<String> headerValues = response.getHeaders(headerName);
for (String headerValue : headerValues) {
headers.add(new Header(headerName, headerValue));
}
}
return new Headers(headers);
}
private Cookies convertCookies(javax.servlet.http.Cookie[] servletCookies) {
List<Cookie> cookies = new ArrayList<>();
for (javax.servlet.http.Cookie servletCookie : servletCookies) {
Cookie.Builder cookieBuilder = new Cookie.Builder(servletCookie.getName(), servletCookie.getValue());
if (servletCookie.getComment() != null) {
cookieBuilder.setComment(servletCookie.getComment());
}
if (servletCookie.getDomain() != null) {
cookieBuilder.setDomain(servletCookie.getDomain());
}
if (servletCookie.getPath() != null) {
cookieBuilder.setPath(servletCookie.getPath());
}
cookieBuilder.setMaxAge(servletCookie.getMaxAge());
cookieBuilder.setVersion(servletCookie.getVersion());
cookieBuilder.setSecured(servletCookie.getSecure());
cookies.add(cookieBuilder.build());
}
return new Cookies(cookies);
}
@SuppressWarnings("unchecked")
private MockMvcResponse performRequest(MockHttpServletRequestBuilder requestBuilder) {
MockHttpServletResponse response;
if (interceptor != null) {
interceptor.intercept(requestBuilder);
}
if (isSpringSecurityInClasspath() && authentication instanceof org.springframework.security.core.Authentication) {
org.springframework.security.core.context.SecurityContextHolder.getContext().setAuthentication((org.springframework.security.core.Authentication) authentication);
}
if (authentication instanceof Principal) {
requestBuilder.principal((Principal) authentication);
}
for (RequestPostProcessor requestPostProcessor : requestPostProcessors) {
requestBuilder.with(requestPostProcessor);
}
MockMvcRestAssuredResponseImpl restAssuredResponse;
try {
final long start = System.currentTimeMillis();
ResultActions perform = mockMvc.perform(requestBuilder);
final long responseTime = System.currentTimeMillis() - start;
if (!resultHandlers.isEmpty()) {
for (ResultHandler resultHandler : resultHandlers) {
perform.andDo(resultHandler);
}
}
MvcResult mvcResult = getMvcResult(perform, isAsyncRequest);
response = mvcResult.getResponse();
restAssuredResponse = new MockMvcRestAssuredResponseImpl(perform, logRepository);
restAssuredResponse.setConfig(ConfigConverter.convertToRestAssuredConfig(config));
restAssuredResponse.setDecoderConfig(config.getDecoderConfig());
restAssuredResponse.setContent(response.getContentAsByteArray());
restAssuredResponse.setContentType(response.getContentType());
restAssuredResponse.setHasExpectations(false);
restAssuredResponse.setStatusCode(response.getStatus());
restAssuredResponse.setResponseHeaders(assembleHeaders(response));
restAssuredResponse.setRpr(getRpr());
restAssuredResponse.setStatusLine(assembleStatusLine(response, mvcResult.getResolvedException()));
restAssuredResponse.setFilterContextProperties(new HashMap() {{
put(TimingFilter.RESPONSE_TIME_MILLISECONDS, responseTime);
}});
restAssuredResponse.setCookies(convertCookies(response.getCookies()));
if (responseSpecification != null) {
responseSpecification.validate(ResponseConverter.toStandardResponse(restAssuredResponse));
}
} catch (Exception e) {
return SafeExceptionRethrower.safeRethrow(e);
} finally {
if (isSpringSecurityInClasspath()) {
org.springframework.security.core.context.SecurityContextHolder.clearContext();
}
}
return restAssuredResponse;
}
private MvcResult getMvcResult(ResultActions perform, boolean isAsyncRequest) throws Exception {
MvcResult mvcResult;
if (isAsyncRequest) {
MvcResult startedAsyncRequestProcessing = perform.andExpect(MockMvcResultMatchers.request().asyncStarted()).andReturn();
startedAsyncRequestProcessing.getAsyncResult(config.getAsyncConfig().timeoutInMs());
mvcResult = mockMvc.perform(asyncDispatch(startedAsyncRequestProcessing)).andReturn();
} else {
mvcResult = perform.andReturn();
}
return mvcResult;
}
private ResponseParserRegistrar getRpr() {
if (responseSpecification instanceof ResponseSpecificationImpl) {
return ((ResponseSpecificationImpl) responseSpecification).getRpr();
}
return new ResponseParserRegistrar();
}
private String assembleStatusLine(MockHttpServletResponse response, Exception resolvedException) {
StringBuilder builder = new StringBuilder();
builder.append(response.getStatus());
if (isNotBlank(response.getErrorMessage())) {
builder.append(" ").append(response.getErrorMessage());
} else if (resolvedException != null) {
builder.append(" ").append(resolvedException.getMessage());
}
return builder.toString();
}
private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) {
notNull(path, "Path");
if (requestBody != null && !multiParts.isEmpty()) {
throw new IllegalStateException("You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?");
}
String baseUri;
if (isNotBlank(basePath)) {
baseUri = mergeAndRemoveDoubleSlash(basePath, path);
} else {
baseUri = path;
}
final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
if (!queryParams.isEmpty()) {
new ParamApplier(queryParams) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
uriComponentsBuilder.queryParam(paramName, paramValues);
}
}.applyParams();
}
String uri = uriComponentsBuilder.build().toUriString();
final MockHttpServletRequestBuilder request;
if (multiParts.isEmpty()) {
request = MockMvcRequestBuilders.request(method, uri, pathParams);
} else if (method == POST || method == PUT) {
request = MockMvcRequestBuilders.fileUpload(uri, pathParams);
request.with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.setMethod(method.name());
return request;
}
});
} else {
throw new IllegalArgumentException("Currently multi-part file data uploading only works for POST and PUT methods");
}
String requestContentType = HeaderHelper.findContentType(headers, (List<Object>) (List<?>) multiParts, config);
if (!params.isEmpty()) {
new ParamApplier(params) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
request.param(paramName, paramValues);
}
}.applyParams();
if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) {
setContentTypeToApplicationFormUrlEncoded(request);
}
}
if (!formParams.isEmpty()) {
if (method == GET) {
throw new IllegalArgumentException("Cannot use form parameters in a GET request");
}
new ParamApplier(formParams) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
request.param(paramName, paramValues);
}
}.applyParams();
boolean isInMultiPartMode = isInMultiPartMode(request);
if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) {
setContentTypeToApplicationFormUrlEncoded(request);
}
}
if (!attributes.isEmpty()) {
new ParamApplier(attributes) {
@Override
protected void applyParam(String paramName, String[] paramValues) {
request.requestAttr(paramName, paramValues[0]);
}
}.applyParams();
}
if (RestDocsClassPathChecker.isSpringRestDocsInClasspath() && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) {
request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri));
}
if (headers.exist()) {
for (Header header : headers) {
request.header(header.getName(), header.getValue());
}
}
if (StringUtils.isNotBlank(requestContentType)) {
request.contentType(MediaType.parseMediaType(requestContentType));
}
if (cookies.exist()) {
for (Cookie cookie : cookies) {
javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
if (cookie.hasComment()) {
servletCookie.setComment(cookie.getComment());
}
if (cookie.hasDomain()) {
servletCookie.setDomain(cookie.getDomain());
}
if (cookie.hasMaxAge()) {
servletCookie.setMaxAge(cookie.getMaxAge());
}
if (cookie.hasPath()) {
servletCookie.setPath(cookie.getPath());
}
if (cookie.hasVersion()) {
servletCookie.setVersion(cookie.getVersion());
}
servletCookie.setSecure(cookie.isSecured());
request.cookie(servletCookie);
}
}
if (!sessionAttributes.isEmpty()) {
request.sessionAttrs(sessionAttributes);
}
if (!multiParts.isEmpty()) {
MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request;
for (MockMvcMultiPart multiPart : multiParts) {
MockMultipartFile multipartFile;
String fileName = multiPart.getFileName();
String controlName = multiPart.getControlName();
String mimeType = multiPart.getMimeType();
if (multiPart.isByteArray()) {
multipartFile = new MockMultipartFile(controlName, fileName, mimeType, (byte[]) multiPart.getContent());
} else if (multiPart.isFile() || multiPart.isInputStream()) {
InputStream inputStream;
if (multiPart.isFile()) {
try {
inputStream = new FileInputStream((File) multiPart.getContent());
} catch (FileNotFoundException e) {
return SafeExceptionRethrower.safeRethrow(e);
}
} else {
inputStream = (InputStream) multiPart.getContent();
}
try {
multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream);
} catch (IOException e) {
return SafeExceptionRethrower.safeRethrow(e);
}
} else { // String
multipartFile = new MockMultipartFile(controlName, fileName, mimeType, ((String) multiPart.getContent()).getBytes());
}
multiPartRequest.file(multipartFile);
}
}
if (requestBody != null) {
if (requestBody instanceof byte[]) {
request.content((byte[]) requestBody);
} else if (requestBody instanceof File) {
byte[] bytes = BodyHelper.toByteArray((File) requestBody);
request.content(bytes);
} else {
request.content(requestBody.toString());
}
}
logRequestIfApplicable(method, baseUri, path, pathParams);
return performRequest(request);
}
private void setContentTypeToApplicationFormUrlEncoded(MockHttpServletRequestBuilder request) {
MediaType mediaType = MediaType.parseMediaType(HeaderHelper.buildApplicationFormEncodedContentType(config, APPLICATION_FORM_URLENCODED_VALUE));
request.contentType(mediaType);
List<Header> newHeaders = new ArrayList<>(headers.asList());
newHeaders.add(new Header(CONTENT_TYPE, mediaType.toString()));
headers = new Headers(newHeaders);
}
private boolean isInMultiPartMode(MockHttpServletRequestBuilder request) {
return request instanceof MockMultipartHttpServletRequestBuilder;
}
private void logRequestIfApplicable(HttpMethod method, String uri, String originalPath, Object[] unnamedPathParams) {
if (requestLoggingFilter == null) {
return;
}
final RequestSpecificationImpl reqSpec = new RequestSpecificationImpl("http://localhost", RestAssured.UNDEFINED_PORT, "", new NoAuthScheme(), Collections.<Filter>emptyList(),
null, true, ConfigConverter.convertToRestAssuredConfig(config), logRepository, null);
logParamsAndHeaders(reqSpec, method.toString(), uri, unnamedPathParams, params, queryParams, formParams, headers, cookies);
logRequestBody(reqSpec, requestBody, headers, (List<Object>) (List<?>) multiParts, config);
if (multiParts != null) {
for (MockMvcMultiPart multiPart : multiParts) {
reqSpec.multiPart(new MultiPartSpecBuilder(multiPart.getContent()).
controlName(multiPart.getControlName()).
fileName(multiPart.getFileName()).
mimeType(multiPart.getMimeType()).
build());
}
}
String uriPath = PathSupport.getPath(uri);
String originalUriPath = PathSupport.getPath(originalPath);
requestLoggingFilter.filter(reqSpec, null, new FilterContextImpl(uri, originalUriPath, uriPath, uri, uri, new Object[0], method.toString(), null, Collections.<Filter>emptyList().iterator(), new HashMap<>()));
}
public MockMvcResponse get(String path, Object... pathParams) {
return sendRequest(GET, path, pathParams);
}
public MockMvcResponse get(String path, Map<String, ?> pathParams) {
return get(path, mapToArray(pathParams));
}
public MockMvcResponse post(String path, Object... pathParams) {
return sendRequest(POST, path, pathParams);
}
public MockMvcResponse post(String path, Map<String, ?> pathParams) {
return post(path, mapToArray(pathParams));
}
public MockMvcResponse put(String path, Object... pathParams) {
return sendRequest(PUT, path, pathParams);
}
public MockMvcResponse put(String path, Map<String, ?> pathParams) {
return put(path, mapToArray(pathParams));
}
public MockMvcResponse delete(String path, Object... pathParams) {
return sendRequest(DELETE, path, pathParams);
}
public MockMvcResponse delete(String path, Map<String, ?> pathParams) {
return delete(path, mapToArray(pathParams));
}
public MockMvcResponse head(String path, Object... pathParams) {
return sendRequest(HEAD, path, pathParams);
}
public MockMvcResponse head(String path, Map<String, ?> pathParams) {
return head(path, mapToArray(pathParams));
}
public MockMvcResponse patch(String path, Object... pathParams) {
return sendRequest(PATCH, path, pathParams);
}
public MockMvcResponse patch(String path, Map<String, ?> pathParams) {
return patch(path, mapToArray(pathParams));
}
public MockMvcResponse options(String path, Object... pathParams) {
return sendRequest(OPTIONS, path, pathParams);
}
public MockMvcResponse options(String path, Map<String, ?> pathParams) {
return options(path, mapToArray(pathParams));
}
public MockMvcResponse get(URI uri) {
return get(uri.toString());
}
public MockMvcResponse post(URI uri) {
return post(uri.toString());
}
public MockMvcResponse put(URI uri) {
return put(uri.toString());
}
public MockMvcResponse delete(URI uri) {
return delete(uri.toString());
}
public MockMvcResponse head(URI uri) {
return head(uri.toString());
}
public MockMvcResponse patch(URI uri) {
return patch(uri.toString());
}
public MockMvcResponse options(URI uri) {
return options(uri.toString());
}
public MockMvcResponse get(URL url) {
return get(url.toString());
}
public MockMvcResponse post(URL url) {
return post(url.toString());
}
public MockMvcResponse put(URL url) {
return put(url.toString());
}
public MockMvcResponse delete(URL url) {
return delete(url.toString());
}
public MockMvcResponse head(URL url) {
return head(url.toString());
}
public MockMvcResponse patch(URL url) {
return patch(url.toString());
}
public MockMvcResponse options(URL url) {
return options(url.toString());
}
public MockMvcResponse get() {
return get("");
}
public MockMvcResponse post() {
return post("");
}
public MockMvcResponse put() {
return put("");
}
public MockMvcResponse delete() {
return delete("");
}
public MockMvcResponse head() {
return head("");
}
public MockMvcResponse patch() {
return patch("");
}
public MockMvcResponse options() {
return options("");
}
public MockMvcResponse request(Method method) {
return request(method, "");
}
public MockMvcResponse request(String method) {
return request(method, "");
}
public MockMvcResponse request(Method method, String path, Object... pathParams) {
return request(notNull(method, Method.class).name(), path, pathParams);
}
public MockMvcResponse request(String method, String path, Object... pathParams) {
return sendRequest(toValidHttpMethod(method), path, pathParams);
}
public MockMvcResponse request(Method method, URI uri) {
return request(method, notNull(uri, URI.class).toString());
}
public MockMvcResponse request(Method method, URL url) {
return request(method, notNull(url, URL.class).toString());
}
public MockMvcResponse request(String method, URI uri) {
return request(method, notNull(uri, URI.class).toString());
}
public MockMvcResponse request(String method, URL url) {
return request(method, notNull(url, URL.class).toString());
}
public MockMvcRequestAsyncConfigurer with() {
return this;
}
public MockMvcRequestAsyncConfigurer and() {
return this;
}
public MockMvcRequestAsyncConfigurer timeout(long duration, TimeUnit timeUnit) {
RestAssuredMockMvcConfig newConfig = config.asyncConfig(new AsyncConfig(duration, timeUnit));
return new MockMvcRequestSenderImpl(mockMvc, params, queryParams, formParams,
attributes, newConfig, requestBody, headers, cookies, sessionAttributes, multiParts, requestLoggingFilter, resultHandlers, requestPostProcessors, interceptor,
basePath, responseSpecification, authentication, logRepository, isAsyncRequest);
}
public MockMvcRequestAsyncConfigurer timeout(long durationInMs) {
return timeout(durationInMs, TimeUnit.MILLISECONDS);
}
public MockMvcRequestSender then() {
return this;
}
public MockMvcRequestAsyncConfigurer async() {
return new MockMvcRequestSenderImpl(mockMvc, params, queryParams, formParams,
attributes, config, requestBody, headers, cookies, sessionAttributes, multiParts, requestLoggingFilter, resultHandlers, requestPostProcessors, interceptor,
basePath, responseSpecification, authentication, logRepository, true);
}
private HttpMethod toValidHttpMethod(String method) {
String httpMethodAsString = notNull(trimToNull(method), "HTTP Method");
HttpMethod httpMethod = HttpMethod.resolve(httpMethodAsString.toUpperCase());
if (httpMethod == null) {
throw new IllegalArgumentException("HTTP method '" + method + "' is not supported by MockMvc");
}
return httpMethod;
}
}
|
3e0d9781166eac414f2eeb1d962dc24a09f570b7 | 767 | java | Java | ipl-tournament/src/com/tarktech/training/ipl/Main.java | kathanLunagariya/training-oops | 28164f6af3d334c42a9f4e111155b3a95e300df8 | [
"MIT"
] | null | null | null | ipl-tournament/src/com/tarktech/training/ipl/Main.java | kathanLunagariya/training-oops | 28164f6af3d334c42a9f4e111155b3a95e300df8 | [
"MIT"
] | null | null | null | ipl-tournament/src/com/tarktech/training/ipl/Main.java | kathanLunagariya/training-oops | 28164f6af3d334c42a9f4e111155b3a95e300df8 | [
"MIT"
] | null | null | null | 29.5 | 79 | 0.741851 | 5,738 | package com.tarktech.training.ipl;
import com.tarktech.training.ipl.domain.*;
import com.tarktech.training.ipl.util.PrettyPrinter;
import com.tarktech.training.ipl.util.TeamRepository;
import java.time.LocalDate;
import java.util.List;
public class Main {
public static void main(String[] args) {
TeamRepository teamRepository = new TeamRepository();
List<Team> teams = teamRepository.findAllTeams();
PrettyPrinter.printTeamDetails(teams);
LocalDate tournamentStartDate = LocalDate.of(2022, 3, 15);
Tournament tournament = new Tournament(teams, tournamentStartDate);
List<CricketMatch> scheduledMatches = tournament.scheduleLeagueRound();
PrettyPrinter.printMatchSchedule(scheduledMatches);
}
}
|
3e0d98215f2226f7c56ff009fad0d4028b0d1759 | 3,915 | java | Java | clients/google-api-services-monitoring/v1/1.29.2/com/google/api/services/monitoring/v1/model/SparkChartView.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 372 | 2018-09-05T21:06:51.000Z | 2022-03-31T09:22:03.000Z | clients/google-api-services-monitoring/v1/1.29.2/com/google/api/services/monitoring/v1/model/SparkChartView.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 1,351 | 2018-10-12T23:07:12.000Z | 2022-03-05T09:25:29.000Z | clients/google-api-services-monitoring/v1/1.29.2/com/google/api/services/monitoring/v1/model/SparkChartView.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 307 | 2018-09-04T20:15:31.000Z | 2022-03-31T09:42:39.000Z | 38.009709 | 182 | 0.732312 | 5,739 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.monitoring.v1.model;
/**
* A sparkChart is a small chart suitable for inclusion in a table-cell or inline in text. This
* message contains the configuration for a sparkChart to show up on a Scorecard, showing recent
* trends of the scorecard's timeseries.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Stackdriver Monitoring API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class SparkChartView extends com.google.api.client.json.GenericJson {
/**
* The lower bound on data point frequency in the chart implemented by specifying the minimum
* alignment period to use in a time series query. For example, if the data is published once
* every 10 minutes it would not make sense to fetch and align data at one minute intervals. This
* field is optional and exists only as a hint.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String minAlignmentPeriod;
/**
* The type of sparkchart to show in this chartView.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sparkChartType;
/**
* The lower bound on data point frequency in the chart implemented by specifying the minimum
* alignment period to use in a time series query. For example, if the data is published once
* every 10 minutes it would not make sense to fetch and align data at one minute intervals. This
* field is optional and exists only as a hint.
* @return value or {@code null} for none
*/
public String getMinAlignmentPeriod() {
return minAlignmentPeriod;
}
/**
* The lower bound on data point frequency in the chart implemented by specifying the minimum
* alignment period to use in a time series query. For example, if the data is published once
* every 10 minutes it would not make sense to fetch and align data at one minute intervals. This
* field is optional and exists only as a hint.
* @param minAlignmentPeriod minAlignmentPeriod or {@code null} for none
*/
public SparkChartView setMinAlignmentPeriod(String minAlignmentPeriod) {
this.minAlignmentPeriod = minAlignmentPeriod;
return this;
}
/**
* The type of sparkchart to show in this chartView.
* @return value or {@code null} for none
*/
public java.lang.String getSparkChartType() {
return sparkChartType;
}
/**
* The type of sparkchart to show in this chartView.
* @param sparkChartType sparkChartType or {@code null} for none
*/
public SparkChartView setSparkChartType(java.lang.String sparkChartType) {
this.sparkChartType = sparkChartType;
return this;
}
@Override
public SparkChartView set(String fieldName, Object value) {
return (SparkChartView) super.set(fieldName, value);
}
@Override
public SparkChartView clone() {
return (SparkChartView) super.clone();
}
}
|
3e0d98445c47f872a124bb27a3805a02581ae020 | 4,816 | java | Java | harvesting-infraestructure/infraestructure/src/main/java/com/backend/demo/batch/reader/EuropeReader.java | AlexGuti14/harvesting-tfg | 1577e42b468a8b56c2b3178218d3d356bfd32ae4 | [
"MIT"
] | 1 | 2020-07-05T11:28:15.000Z | 2020-07-05T11:28:15.000Z | harvesting-infraestructure/infraestructure/src/main/java/com/backend/demo/batch/reader/EuropeReader.java | AlexGuti14/Harvesting-TFG | 1577e42b468a8b56c2b3178218d3d356bfd32ae4 | [
"MIT"
] | 7 | 2021-03-10T22:30:43.000Z | 2022-02-27T06:48:20.000Z | harvesting-infraestructure/infraestructure/src/main/java/com/backend/demo/batch/reader/EuropeReader.java | AlexGuti14/harvesting-tfg | 1577e42b468a8b56c2b3178218d3d356bfd32ae4 | [
"MIT"
] | null | null | null | 27.20904 | 132 | 0.738164 | 5,740 | package com.backend.demo.batch.reader;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.LocalDate;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.AfterStep;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.UnexpectedInputException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.backend.demo.batch.util.CellUtility;
import com.backend.demo.batch.model.DateJson;
import com.backend.demo.batch.model.EuropePork;
public class EuropeReader implements ItemReader<EuropePork>, Reader {
private static final Logger log = LoggerFactory.getLogger(EuropeReader.class);
private XSSFWorkbook workbook;
private HSSFWorkbook workbookHSSF;
private FileInputStream file;
private List<String> files;
private String urlFiles;
private int index;
private Sheet sheet;
private int numSheet;
private Row row;
private int initial;
private int initialRow;
private int finalRow;
private int finalColum;
private int filaMercado;
private int columMercadosI;
// PARAMETROS
private String tipo;
private String clase;
private int fecha;
private int price;
Vector<String> mercados;
public EuropeReader(){}
public EuropeReader(int initialRow, int finalRow, int numSheet, String urlFiles, String tipo, String clase, int fecha, int price,
int filaMercado ,int columMercadosI, int columMercados) throws IOException {
this.urlFiles = urlFiles;
this.initial = initialRow;
this.initialRow=initialRow;
this.finalRow=finalRow;
this.filaMercado=filaMercado;
this.columMercadosI=columMercadosI;
this.finalColum=columMercados;
this.tipo = tipo;
this.clase = clase;
this.fecha = fecha;
this.price = price;
this.numSheet = numSheet;
this.index = 0;
}
@BeforeStep
public void beforeStep(StepExecution stepExecution) throws IOException {
openFile(urlFiles + files.get(index));
mercados = mercados(filaMercado, columMercadosI, finalColum);
}
@AfterStep
public void afterStep(StepExecution stepExecution) throws IOException {
index = 0;
}
/**
* @return Porcino
* @throws Exception
* @throws UnexpectedInputException
* @throws NonTransientResourceException
* @throws ParseException
*/
@Override
public EuropePork read() throws Exception, UnexpectedInputException, NonTransientResourceException, ParseException {
EuropePork next = null;
try {
if (initialRow <= sheet.getLastRowNum()) {
row = sheet.getRow(initialRow);
next = createEuropePork();
initialRow++;
}
else{
initialRow=initial;
file.close();
}
} catch (Exception e) {
initialRow++;
}
return next;
}
//PRIVATE OPERATIONS
/**
* @param numSheet
* @param namefile
* @throws IOException
*/
private void openFile(String namefile) throws IOException {
file = new FileInputStream(new File(namefile));
String[] tipo = namefile.split("\\.");
if(tipo[1].equals("xls")){
// Create Workbook instance holding reference to .xls file
workbookHSSF = new HSSFWorkbook(file);
// Get first/desired sheet from the workbook
sheet = workbookHSSF.getSheetAt(numSheet);
}
else{
// Create Workbook instance holding reference to .xlsx file
workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
sheet = workbook.getSheetAt(numSheet);
}
log.info("Open file: " + namefile);
}
/**
* @return Cereal
*/
EuropePork createEuropePork(){
LocalDateTime d = row.getCell(fecha).getLocalDateTimeCellValue();
LocalDate date = new LocalDate(d.getYear(), d.getMonthValue(), d.getDayOfMonth());
EuropePork eu = new EuropePork(new DateJson(date, new LocalDate()), tipo, clase);
int m = 0;
int i = price;
while(i<finalColum){
if(!CellUtility.isCellEmpty(row.getCell(i)) && CellUtility.isNumber(row.getCell(i))){
String priceS = row.getCell(i).toString();
eu.setMercado(priceS, mercados.get(m));
}
i++;
m++;
}
return eu;
}
/**
* @return List of markets
*/
Vector<String> mercados(int filaMercado, int i, int j){
Vector<String> mercados = new Vector<String>();
Row merca = row = sheet.getRow(filaMercado);
while(i<=j){
mercados.add(merca.getCell(i).toString());
i++;
}
return mercados;
}
public void filesToRead(List<String> files){
this.files = files;
}
} |
3e0d98565ce80eedb1a9210316bd38b9b12ef92b | 320 | java | Java | Library/src/main/java/com/sunzn/swipe/library/OnRefreshListenerAdapter.java | ShortStickBoy/swipe | 046ad1a5e8cb47ed3f45769c286875428337d65a | [
"Apache-2.0"
] | null | null | null | Library/src/main/java/com/sunzn/swipe/library/OnRefreshListenerAdapter.java | ShortStickBoy/swipe | 046ad1a5e8cb47ed3f45769c286875428337d65a | [
"Apache-2.0"
] | null | null | null | Library/src/main/java/com/sunzn/swipe/library/OnRefreshListenerAdapter.java | ShortStickBoy/swipe | 046ad1a5e8cb47ed3f45769c286875428337d65a | [
"Apache-2.0"
] | null | null | null | 12.307692 | 77 | 0.63125 | 5,741 | package com.sunzn.swipe.library;
public abstract class OnRefreshListenerAdapter implements OnRefreshListener {
@Override
public void onPrepare() {
}
@Override
public void onRefresh() {
}
@Override
public void onReset() {
}
@Override
public void onCancel() {
}
}
|
3e0d98c5e93cc2f6448c31149c05807f631d1931 | 1,816 | java | Java | app/src/main/java/com/gimbal/hello_gimbal_android/GimbalPermissionsManager.java | mcculloh213/hello-gimbal-android | bec9c7a1900a2e09b6ef5da9e6a54f8dcf5020d4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/gimbal/hello_gimbal_android/GimbalPermissionsManager.java | mcculloh213/hello-gimbal-android | bec9c7a1900a2e09b6ef5da9e6a54f8dcf5020d4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/gimbal/hello_gimbal_android/GimbalPermissionsManager.java | mcculloh213/hello-gimbal-android | bec9c7a1900a2e09b6ef5da9e6a54f8dcf5020d4 | [
"Apache-2.0"
] | null | null | null | 40.355556 | 119 | 0.720264 | 5,742 | package com.gimbal.hello_gimbal_android;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.gimbal.android.Gimbal;
class GimbalPermissionsManager {
static final int REQUEST_COARSE_LOCATION_CODE = 0b100;
static final int REQUEST_FINE_LOCATION_CODE = 0b010;
static final int REQUEST_BLUETOOTH_CODE = 0b001;
static final int REQUEST_PERMISSIONS_MASK = REQUEST_COARSE_LOCATION_CODE
| REQUEST_FINE_LOCATION_CODE
| REQUEST_BLUETOOTH_CODE;
static int checkRequiredPermissions(Context context) {
int mask = PackageManager.PERMISSION_GRANTED;
mask |= mapPermissionToMask(context, Manifest.permission.ACCESS_COARSE_LOCATION, REQUEST_COARSE_LOCATION_CODE);
mask |= mapPermissionToMask(context, Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_FINE_LOCATION_CODE);
mask |= mapPermissionToMask(context, Manifest.permission.BLUETOOTH, REQUEST_BLUETOOTH_CODE);
return mask;
}
static void requestPermissions(Activity activity, int code) {
ActivityCompat.requestPermissions(activity,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH
}, code);
}
private static int mapPermissionToMask(Context context, String permission, int code) {
int mask = 0;
if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) {
mask |= code;
}
return mask;
}
}
|
3e0d9a1e955d47d5b56ce3cf5784d3acc02ab94c | 4,253 | java | Java | set-structure/src/main/java/com/ktz/sh/array/Array.java | kaituozhesh/data-structure | 28820f820f252c6632cee1cdb8a981a5be128aba | [
"Apache-2.0"
] | 1 | 2020-06-29T00:26:39.000Z | 2020-06-29T00:26:39.000Z | set-structure/src/main/java/com/ktz/sh/array/Array.java | kaituozhesh/data-structure | 28820f820f252c6632cee1cdb8a981a5be128aba | [
"Apache-2.0"
] | null | null | null | set-structure/src/main/java/com/ktz/sh/array/Array.java | kaituozhesh/data-structure | 28820f820f252c6632cee1cdb8a981a5be128aba | [
"Apache-2.0"
] | null | null | null | 17.869748 | 99 | 0.419233 | 5,743 | package com.ktz.sh.array;
/**
* @ClassName : Array
* @Description : 动态数组实现
* @Author : kaituozhesh
* @Date: 2020-05-10 20:26
* @Version: 1.0.0
*/
public class Array<E> {
/**
* 数组数据
*/
private E[] data;
/**
* 有效数据
*/
private int size;
/**
* 默认初始化数组容量10
*/
public Array() {
this(10);
}
/**
* 自定义初始化数组容量
*
* @param capacity
*/
public Array(int capacity) {
data = (E[]) new Object[capacity];
}
/**
* 获取有效数据个数
*
* @return
*/
public int getSize() {
return size;
}
/**
* 获取数组容量
*
* @return
*/
public int getCapacity() {
return data.length;
}
/**
* 数组是否为空
*
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 添加元素到开头
*
* @param e
*/
public void addFirst(E e) {
add(0, e);
}
/**
* 添加元素到最后
*
* @param e
*/
public void addLast(E e) {
add(size, e);
}
/**
* 指定位置插入元素
*
* @param index
* @param e
*/
public void add(int index, E e) {
if (index < 0 || index > size) {
throw new IllegalArgumentException("Add faild. Require index >= 0 && index < size");
}
if (size == data.length) {
reSize(2 * data.length);
}
// size - 1指向最后一个有效元素的下标
for (int i = size - 1; i >= index; i--) {
// index及之后的元素后移
data[i + 1] = data[i];
}
data[index] = e;
size++;
}
/**
* 删除首个元素
*
* @return
*/
public E removeFirst() {
return remove(0);
}
/**
* 删除最后一个元素
*
* @return
*/
public E removeLast() {
return remove(size - 1);
}
/**
* 删除指定下标元素
*
* @param index
* @return
*/
public E remove(int index) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("remove faild. Require index >= 0 && index < size");
}
E result = data[index];
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
data[size] = null;
if (size == data.length / 4 && data.length / 2 != 0) {
reSize(data.length / 2);
}
return result;
}
/**
* 删除首个元素e
*
* @param e
*/
public void removeElement(E e) {
int index = find(e);
if (index != -1) {
remove(index);
}
}
/**
* 删除数组中所有的元素e
*
* @param e
*/
public void removeAllElement(E e) {
int index = find(e);
while (index != -1) {
remove(index);
index = find(e);
}
}
/**
* 修改下标index的元素为e
*
* @param index
* @param e
*/
public void set(int index, E e) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("Set failed. Index is Illegal.");
}
data[index] = e;
}
/**
* 判断元素e是否存在
*
* @param e
* @return
*/
public boolean contains(E e) {
return find(e) != -1;
}
/**
* 查询元素下标
*
* @param e
* @return
*/
public int find(E e) {
for (int i = 0; i < size; i++) {
if (data[i].equals(e)) {
return i;
}
}
return -1;
}
/**
* 重置数组容量
*
* @param newCapacity
*/
private void reSize(int newCapacity) {
E[] newData = (E[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
data = newData;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(String.format("Array: size = %d, capacity = %d", size, getCapacity()));
builder.append("[");
for (int i = 0; i < size; i++) {
builder.append(data[i]);
if (i != size - 1) {
builder.append(",");
}
}
return builder.append("]").toString();
}
}
|
3e0d9a2e5cc6ac571a17d5a3d5e7e9b5200fa4e1 | 4,260 | java | Java | cascading-hadoop/src/main/shared-io/cascading/scheme/hadoop/SequenceFile.java | Schmed/cascading | 2b7346e43b5e5fef6dd88e07e90ac056386c51f0 | [
"Apache-2.0"
] | 170 | 2015-01-16T17:17:10.000Z | 2022-01-03T12:13:24.000Z | cascading-hadoop/src/main/shared-io/cascading/scheme/hadoop/SequenceFile.java | Schmed/cascading | 2b7346e43b5e5fef6dd88e07e90ac056386c51f0 | [
"Apache-2.0"
] | 9 | 2015-02-24T04:36:18.000Z | 2018-12-05T21:03:45.000Z | cascading-hadoop/src/main/shared-io/cascading/scheme/hadoop/SequenceFile.java | Schmed/cascading | 2b7346e43b5e5fef6dd88e07e90ac056386c51f0 | [
"Apache-2.0"
] | 56 | 2015-02-11T16:22:02.000Z | 2020-09-17T23:35:18.000Z | 34.354839 | 155 | 0.732394 | 5,744 | /*
* Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* 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 cascading.scheme.hadoop;
import java.beans.ConstructorProperties;
import java.io.IOException;
import cascading.flow.FlowProcess;
import cascading.scheme.Scheme;
import cascading.scheme.SinkCall;
import cascading.scheme.SourceCall;
import cascading.tap.Tap;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.OutputFormat;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hadoop.mapred.SequenceFileOutputFormat;
/**
* A SequenceFile is a type of {@link cascading.scheme.Scheme}, which is a flat file consisting of
* binary key/value pairs. This is a space and time efficient means to store data.
*/
public class SequenceFile extends Scheme<Configuration, RecordReader, OutputCollector, Object[], Void>
{
/** Protected for use by TempDfs and other subclasses. Not for general consumption. */
protected SequenceFile()
{
super( null );
}
/**
* Creates a new SequenceFile instance that stores the given field names.
*
* @param fields
*/
@ConstructorProperties({"fields"})
public SequenceFile( Fields fields )
{
super( fields, fields );
}
@Override
public void sourceConfInit( FlowProcess<? extends Configuration> flowProcess, Tap<Configuration, RecordReader, OutputCollector> tap, Configuration conf )
{
conf.setBoolean( "mapred.mapper.new-api", false );
conf.setClass( "mapred.input.format.class", SequenceFileInputFormat.class, InputFormat.class );
}
@Override
public void sinkConfInit( FlowProcess<? extends Configuration> flowProcess, Tap<Configuration, RecordReader, OutputCollector> tap, Configuration conf )
{
conf.setBoolean( "mapred.mapper.new-api", false );
conf.setClass( "mapred.output.key.class", Tuple.class, Object.class );
conf.setClass( "mapred.output.value.class", Tuple.class, Object.class );
conf.setClass( "mapred.output.format.class", SequenceFileOutputFormat.class, OutputFormat.class );
}
@Override
public void sourcePrepare( FlowProcess<? extends Configuration> flowProcess, SourceCall<Object[], RecordReader> sourceCall )
{
Object[] pair = new Object[]{
sourceCall.getInput().createKey(),
sourceCall.getInput().createValue()
};
sourceCall.setContext( pair );
}
@Override
public boolean source( FlowProcess<? extends Configuration> flowProcess, SourceCall<Object[], RecordReader> sourceCall ) throws IOException
{
Tuple key = (Tuple) sourceCall.getContext()[ 0 ];
Tuple value = (Tuple) sourceCall.getContext()[ 1 ];
boolean result = sourceCall.getInput().next( key, value );
if( !result )
return false;
TupleEntry entry = sourceCall.getIncomingEntry();
if( entry.hasTypes() )
entry.setCanonicalTuple( value );
else
entry.setTuple( value );
return true;
}
@Override
public void sourceCleanup( FlowProcess<? extends Configuration> flowProcess, SourceCall<Object[], RecordReader> sourceCall )
{
sourceCall.setContext( null );
}
@Override
public void sink( FlowProcess<? extends Configuration> flowProcess, SinkCall<Void, OutputCollector> sinkCall ) throws IOException
{
sinkCall.getOutput().collect( Tuple.NULL, sinkCall.getOutgoingEntry().getTuple() );
}
}
|
3e0d9bd18cc7885d3d31499d6ce002204f6130f1 | 3,829 | java | Java | modules/core/general/tax/src/com/geecommerce/tax/model/DefaultTaxRate.java | geetools/geeCommerce-Java-Shop-Software | 48823ccf012d7a1f11a5bf7b99619a67805984f4 | [
"Apache-2.0"
] | 9 | 2016-11-24T11:41:02.000Z | 2020-04-22T02:43:51.000Z | modules/core/general/tax/src/com/geecommerce/tax/model/DefaultTaxRate.java | geetools/geeCommerce-Java-Shop-Software | 48823ccf012d7a1f11a5bf7b99619a67805984f4 | [
"Apache-2.0"
] | null | null | null | modules/core/general/tax/src/com/geecommerce/tax/model/DefaultTaxRate.java | geetools/geeCommerce-Java-Shop-Software | 48823ccf012d7a1f11a5bf7b99619a67805984f4 | [
"Apache-2.0"
] | 2 | 2020-03-28T09:23:32.000Z | 2020-10-02T13:58:57.000Z | 23.635802 | 95 | 0.636981 | 5,745 | package com.geecommerce.tax.model;
import java.util.Map;
import com.geecommerce.core.service.AbstractMultiContextModel;
import com.geecommerce.core.service.annotation.Cacheable;
import com.geecommerce.core.service.annotation.Model;
import com.geecommerce.core.type.ContextObject;
import com.geecommerce.core.type.Id;
import com.geecommerce.tax.TaxClassType;
import com.geecommerce.tax.repository.TaxClasses;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
@Cacheable
@Model("tax_rates")
public class DefaultTaxRate extends AbstractMultiContextModel implements TaxRate {
private static final long serialVersionUID = -4897010166894675659L;
private Id id = null;
private String country = null;
private String state = null;
private String zip = null;
private String productTaxClassCode = null;
private Double rate = null;
private ContextObject<String> label = null;
// Loaded lazily
private TaxClass productTaxClass = null;
// Repository
private TaxClasses taxClasses = null;
@Inject
public DefaultTaxRate(TaxClasses taxClasses) {
this.taxClasses = taxClasses;
}
@Override
public Id getId() {
return id;
}
@Override
public TaxRate setId(Id id) {
this.id = id;
return this;
}
@Override
public String getCountry() {
return country;
}
@Override
public TaxRate setCountry(String country) {
this.country = country;
return this;
}
@Override
public String getState() {
return state;
}
@Override
public TaxRate setState(String state) {
this.state = state;
return this;
}
@Override
public String getZip() {
return zip;
}
@Override
public TaxRate setZip(String zip) {
this.zip = zip;
return this;
}
@Override
public TaxClass getProductTaxClass() {
if (productTaxClass == null) {
productTaxClass = taxClasses.havingCode(productTaxClassCode, TaxClassType.PRODUCT);
}
return productTaxClass;
}
@Override
public TaxRate setProductTaxClass(TaxClass productTaxClass) {
this.productTaxClass = productTaxClass;
this.productTaxClassCode = productTaxClass.getCode();
return this;
}
@Override
public Double getRate() {
return rate;
}
@Override
public TaxRate setRate(Double rate) {
this.rate = rate;
return this;
}
@Override
public ContextObject<String> getLabel() {
return label;
}
@Override
public TaxRate setLabel(ContextObject<String> label) {
this.label = label;
return this;
}
@Override
public void fromMap(Map<String, Object> map) {
super.fromMap(map);
this.id = id_(map.get(Column.ID));
this.country = str_(map.get(Column.COUNTRY));
this.state = str_(map.get(Column.STATE));
this.zip = str_(map.get(Column.ZIP));
this.productTaxClassCode = str_(map.get(Column.PRODUCT_TAX_CLASS_CODE));
this.rate = double_(map.get(Column.RATE));
this.label = ctxObj_(map.get(Column.LABEL));
}
@Override
public Map<String, Object> toMap() {
Map<String, Object> map = Maps.newLinkedHashMap(super.toMap());
map.put(Column.ID, getId());
if (getCountry() != null)
map.put(Column.COUNTRY, getCountry());
if (getState() != null)
map.put(Column.STATE, getState());
if (getZip() != null)
map.put(Column.ZIP, getZip());
map.put(Column.PRODUCT_TAX_CLASS_CODE, getProductTaxClass().getCode());
map.put(Column.RATE, getRate());
map.put(Column.LABEL, getLabel());
return map;
}
}
|
3e0d9beac0a5554062c584add2e2ca84f7f82982 | 3,398 | java | Java | examples/src/main/java/xyz/troublor/crawljax/experiments/ClientSideCoverageCollectorPlugin.java | KristenLawrence/darcher-crawljax | 50145fc4d3256e4068d3d25072a287868e6ed93c | [
"Apache-2.0"
] | null | null | null | examples/src/main/java/xyz/troublor/crawljax/experiments/ClientSideCoverageCollectorPlugin.java | KristenLawrence/darcher-crawljax | 50145fc4d3256e4068d3d25072a287868e6ed93c | [
"Apache-2.0"
] | null | null | null | examples/src/main/java/xyz/troublor/crawljax/experiments/ClientSideCoverageCollectorPlugin.java | KristenLawrence/darcher-crawljax | 50145fc4d3256e4068d3d25072a287868e6ed93c | [
"Apache-2.0"
] | null | null | null | 34.673469 | 122 | 0.652148 | 5,746 | package xyz.troublor.crawljax.experiments;
import com.crawljax.browser.EmbeddedBrowser;
import com.crawljax.core.CrawlSession;
import com.crawljax.core.CrawlerContext;
import com.crawljax.core.ExitNotifier;
import com.crawljax.core.plugin.OnFireEventSucceededPlugin;
import com.crawljax.core.plugin.PostCrawlingPlugin;
import com.crawljax.core.plugin.PreResetPlugin;
import com.crawljax.core.state.Eventable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class ClientSideCoverageCollectorPlugin implements PreResetPlugin, OnFireEventSucceededPlugin, PostCrawlingPlugin {
Path covSaveDir;
String lastCovJson = null;
Timer periodicallySaveCoverageTimer;
public ClientSideCoverageCollectorPlugin(Path covSaveDir) {
this.covSaveDir = covSaveDir;
}
private String fetchCovJson(EmbeddedBrowser browser) {
return (String) browser.executeJavaScript("return JSON.stringify(window.__coverage__)");
}
private void saveCovJson(String covJson, String filename) {
if (!Files.exists(this.covSaveDir)) {
try {
Files.createDirectories(this.covSaveDir);
} catch (IOException e) {
System.err.println("Create coverage save dir failed: " + e.getMessage());
}
}
try {
Path file;
if (filename != null) {
file = Paths.get(filename);
} else {
file = Files.createTempFile(this.covSaveDir, "cov-", ".json");
}
FileWriter myWriter = new FileWriter(file.toString());
myWriter.write(covJson);
myWriter.close();
} catch (IOException e) {
System.err.println("Save coverage failed: " + e.getMessage());
}
}
@Override
public void preReset(CrawlerContext context) {
String covJson = fetchCovJson(context.getBrowser());
saveCovJson(covJson, null);
// save coverage every 1 minute
if (this.periodicallySaveCoverageTimer == null) {
TimerTask task = new TimerTask() {
@Override
public void run() {
String json = fetchCovJson(context.getBrowser());
DateFormat dateFormat = new SimpleDateFormat("HH-mm-ss");
Date now = new Date();
saveCovJson(json, covSaveDir + File.separator + "cov-" + dateFormat.format(now) + ".json");
}
};
this.periodicallySaveCoverageTimer = new Timer(true);
this.periodicallySaveCoverageTimer.schedule(task, 60 * 1000, 60 * 1000);
}
}
@Override
public void onFireEventSucceeded(CrawlerContext context, Eventable eventable, List<Eventable> pathToFailure) {
lastCovJson = fetchCovJson(context.getBrowser());
}
@Override
public void postCrawling(CrawlSession session, ExitNotifier.ExitStatus exitReason) {
saveCovJson(lastCovJson, null);
if (this.periodicallySaveCoverageTimer != null) {
this.periodicallySaveCoverageTimer.cancel();
}
}
}
|
3e0d9cd8226214ea1f2008a04300a7ad8447fdb3 | 1,235 | java | Java | spring-boot-project/boot-logging/src/main/java/icu/easyj/spring/boot/logging/logback/EasyjExtendedWhitespaceThrowableProxyConverter.java | easyj-projects/easyj | 0875670df161e7b91c257cce79d586467e062170 | [
"Apache-2.0"
] | 5 | 2021-07-07T03:43:16.000Z | 2021-12-14T12:36:50.000Z | spring-boot-project/boot-logging/src/main/java/icu/easyj/spring/boot/logging/logback/EasyjExtendedWhitespaceThrowableProxyConverter.java | easyj-projects/easyj | 0875670df161e7b91c257cce79d586467e062170 | [
"Apache-2.0"
] | 2 | 2022-01-11T07:52:30.000Z | 2022-01-14T07:38:04.000Z | spring-boot-project/boot-logging/src/main/java/icu/easyj/spring/boot/logging/logback/EasyjExtendedWhitespaceThrowableProxyConverter.java | easyj-projects/easyj | 0875670df161e7b91c257cce79d586467e062170 | [
"Apache-2.0"
] | 1 | 2022-02-19T08:07:50.000Z | 2022-02-19T08:07:50.000Z | 35.285714 | 101 | 0.77166 | 5,747 | /*
* Copyright 2021-2022 the original author or authors.
*
* 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
*
* https://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 icu.easyj.spring.boot.logging.logback;
import ch.qos.logback.classic.pattern.ExtendedThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.CoreConstants;
/**
* 在堆栈信息前后加一个标记行,更加方便观察
*
* @author wangliang181230
*/
public class EasyjExtendedWhitespaceThrowableProxyConverter extends ExtendedThrowableProxyConverter {
@Override
protected String throwableProxyToString(IThrowableProxy tp) {
return "==>" + CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp)
+ "<==" + CoreConstants.LINE_SEPARATOR + CoreConstants.LINE_SEPARATOR;
}
}
|
3e0d9ce2c067c82f864a513bc5712383e9e87e6c | 2,905 | java | Java | monolith/dukesbank-war/src/main/java/com/sun/tutorial/javaee/dukesbank/web/CustomerBean.java | kwkoo/fsi-workshop-v2m1-labs | 3fcbf17d8c6c38f6777de0882bce83d11981f654 | [
"Apache-2.0"
] | 2 | 2020-12-02T17:43:19.000Z | 2021-03-02T21:01:01.000Z | monolith/dukesbank-war/src/main/java/com/sun/tutorial/javaee/dukesbank/web/CustomerBean.java | kwkoo/fsi-workshop-v2m1-labs | 3fcbf17d8c6c38f6777de0882bce83d11981f654 | [
"Apache-2.0"
] | 1 | 2020-11-23T18:11:55.000Z | 2020-11-23T18:11:55.000Z | monolith/dukesbank-war/src/main/java/com/sun/tutorial/javaee/dukesbank/web/CustomerBean.java | kwkoo/fsi-workshop-v2m1-labs | 3fcbf17d8c6c38f6777de0882bce83d11981f654 | [
"Apache-2.0"
] | 1 | 2020-11-19T01:14:47.000Z | 2020-11-19T01:14:47.000Z | 27.666667 | 105 | 0.650602 | 5,748 | /*
* Copyright 2007 Sun Microsystems, Inc.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developer.sun.com/berkeley_license.html
*/
package com.sun.tutorial.javaee.dukesbank.web;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import java.util.List;
import com.sun.tutorial.javaee.dukesbank.exception.AccountNotFoundException;
import com.sun.tutorial.javaee.dukesbank.exception.CustomerNotFoundException;
import com.sun.tutorial.javaee.dukesbank.exception.InvalidParameterException;
import com.sun.tutorial.javaee.dukesbank.request.AccountController;
import com.sun.tutorial.javaee.dukesbank.request.TxController;
import com.sun.tutorial.javaee.dukesbank.util.AccountDetails;
import com.sun.tutorial.javaee.dukesbank.util.Debug;
import com.sun.tutorial.javaee.dukesbank.web.Util.Navigation;
public class CustomerBean {
@EJB
private AccountController accountController;
private Long account;
private Long customerId;
@EJB
private TxController txController;
public CustomerBean() {
customerId = Long.parseLong(
FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName());
}
public TxController getTxController() {
return txController;
}
public Long getCustomerId() {
return customerId;
}
public void setActiveAccount(Long account) {
this.account = account;
}
public Long getActiveAccount() {
return this.account;
}
public AccountDetails getAccountDetails() {
AccountDetails ad = null;
try {
ad = accountController.getDetails(this.account);
} catch (InvalidParameterException e) {
Debug.print(e.getMessage());
// Not possible
} catch (AccountNotFoundException e) {
Debug.print(e.getMessage());
// Not possible
}
if (ad != null) {
Debug.print(
"account ID: ",
ad.getAccountId());
}
return ad;
}
public List<AccountDetails> getAccounts() {
List<AccountDetails> accounts = null;
try {
accounts = accountController.getAccountsOfCustomer(customerId);
} catch (InvalidParameterException e) {
Debug.print(e.getMessage());
// Not possible
} catch (CustomerNotFoundException e) {
Debug.print(e.getMessage());
// Not possible
}
return accounts;
}
public Object logout() {
HttpSession session = (HttpSession) Util.getExternalContext()
.getSession(true);
session.invalidate();
return Navigation.main;
}
}
|
3e0d9da785ccfc19d80e985b5e937198563e2841 | 897 | java | Java | src/main/java/br/com/clinicamed/api/modules/medico/MedicoDTO.java | douglasouza/clinicaMed | 08024c1996ff8f19385555ba8980bcda2be609a5 | [
"MIT"
] | null | null | null | src/main/java/br/com/clinicamed/api/modules/medico/MedicoDTO.java | douglasouza/clinicaMed | 08024c1996ff8f19385555ba8980bcda2be609a5 | [
"MIT"
] | null | null | null | src/main/java/br/com/clinicamed/api/modules/medico/MedicoDTO.java | douglasouza/clinicaMed | 08024c1996ff8f19385555ba8980bcda2be609a5 | [
"MIT"
] | null | null | null | 16.309091 | 56 | 0.586399 | 5,749 | package br.com.clinicamed.api.modules.medico;
public class MedicoDTO {
private Long id;
private String nome;
private String especialidade;
private String crm;
private String login;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEspecialidade() {
return especialidade;
}
public void setEspecialidade(String especialidade) {
this.especialidade = especialidade;
}
public String getCrm() {
return crm;
}
public void setCrm(String crm) {
this.crm = crm;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
|
3e0d9e9498fbc819a859d0cf447bb49c4fd0360f | 31,948 | java | Java | src/org/opengts/dbtools/DBFieldValues.java | earyabh/GTS | 01bec7cdc0524390207139dd0c08db35f33ca569 | [
"Apache-2.0"
] | null | null | null | src/org/opengts/dbtools/DBFieldValues.java | earyabh/GTS | 01bec7cdc0524390207139dd0c08db35f33ca569 | [
"Apache-2.0"
] | null | null | null | src/org/opengts/dbtools/DBFieldValues.java | earyabh/GTS | 01bec7cdc0524390207139dd0c08db35f33ca569 | [
"Apache-2.0"
] | 15 | 2017-01-12T11:18:30.000Z | 2019-04-19T10:10:35.000Z | 36.891455 | 117 | 0.552523 | 5,750 | // ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2006/03/26 Martin D. Flynn
// -Initial release
// 2006/04/11 Martin D. Flynn
// -'toString(<FieldName>)' now returns a default value consistent with the
// field type if the field has not yet been assigned an actual value.
// 2006/04/23 Martin D. Flynn
// -Integrated logging changes made to Print
// 2007/01/25 Martin D. Flynn
// -Integrated with "OpenGTS"
// 2007/09/16 Martin D. Flynn
// -Fixed case where default Boolean valus were not properly converted to a
// String value in "toString(fldName)".
// 2008/02/04 Martin D. Flynn
// -Fixed 'setChanged' method to properly pass the old field value.
// 2009/05/01 Martin D. Flynn
// -Added DateTime datatype
// 2009/05/24 Martin D. Flynn
// -Made "_setFieldValue(DBField fld, Object newVal)" public to allow direct
// access to other modules.
// 2011/05/13 Martin D. Flynn
// -Modified "setAllFieldValues" to accept a list of specific fields to set.
// ----------------------------------------------------------------------------
package org.opengts.dbtools;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.text.*;
import java.sql.*;
import org.opengts.util.*;
/**
*** <code>DBFieldValues</code> is a container class for field/column values for
*** a DBRecord.
**/
public class DBFieldValues
{
// ------------------------------------------------------------------------
/* validate field values */
private static boolean VALIDATE_FIELD_VALUES = false;
/**
*** Sets the global state for validating field values
*** @param validate True to validate, false otherwise
**/
public static void setValidateFieldValues(boolean validate)
{
VALIDATE_FIELD_VALUES = validate;
}
// ------------------------------------------------------------------------
private DBRecordKey recordKey = null;
private OrderedMap<String,Object> valueMap = null;
private OrderedMap<String,DBField> fieldMap = null;
private Map<String,String> caseMap = null; // order is not important
private boolean mustExist = true;
/**
*** Constructor
**/
private DBFieldValues()
{
this.valueMap = new OrderedMap<String,Object>();
this.fieldMap = new OrderedMap<String,DBField>();
this.caseMap = new HashMap<String,String>();
}
/**
*** Constructor
*** @param rcdKey The DBRecordKey associated with this field value container
**/
public DBFieldValues(DBRecordKey rcdKey)
{
this();
this.recordKey = rcdKey;
DBField fld[] = rcdKey.getFields();
for (int i = 0; i < fld.length; i++) {
String fldName = DBProvider.translateColumnName(fld[i].getName());
this.fieldMap.put(fldName, fld[i]);
this.caseMap.put(fldName.toLowerCase(),fldName);
}
}
// ------------------------------------------------------------------------
/**
*** Sets the state for ignoring invalid field names. True to ignore errors when
*** setting/getting a field name that does not exist, False to emit any invalid
*** field errors.
*** @param state True to ignore invalid field names, false to emit errors.
**/
public void setIgnoreInvalidFields(boolean state)
{
this.mustExist = !state;
}
/**
*** Gets the state of reporting invalid field names.
*** @return False to report invalid field names, true to suppress/ignore errors.
**/
public boolean getIgnoreInvalidFields()
{
return !this.mustExist;
}
// ------------------------------------------------------------------------
/**
*** Gets the table name for this DBFieldValue instance
*** @return The table name
**/
public String getUntranslatedTableName()
{
if (this.recordKey != null) {
return this.recordKey.getUntranslatedTableName();
} else {
return "";
}
}
// ------------------------------------------------------------------------
/**
*** Clears all field values
**/
public void clearFieldValues()
{
this.clearFieldValues(null);
}
/**
*** Clears field values
**/
public void clearFieldValues(DBField fldList[])
{
if (this.recordKey != null) {
DBField fld[] = (fldList != null)? fldList : this.recordKey.getFields();
for (int i = 0; i < fld.length; i++) {
if (!fld[i].isPrimaryKey()) {
this._setFieldValue(fld[i], (Object)null);
}
}
} else {
Print.logStackTrace("DBRecordKey has not been set!");
}
}
/**
*** Gets the DBField for the specified field name
*** @param fldName The field name of the DBField to return
*** @return The returned DBField
**/
public DBField getField(String fldName)
{
if (this.recordKey != null) {
return this.recordKey.getField(fldName);
} else {
Print.logStackTrace("DBRecordKey has not been set!");
return null;
}
}
// ------------------------------------------------------------------------
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param requiredField True to indicate that this field is required (warnings displayed if field is not found)
*** @param newVal The 'Object' value to set for the field
*** @return True if the field exists, false otherwise
**/
protected boolean _setFieldValue(String fldName, boolean requiredField, Object newVal)
{
/* get/validate field */
DBField fld = this.getField(fldName);
if (fld == null) {
if (requiredField && !this.getIgnoreInvalidFields()) {
String tn = this.getUntranslatedTableName();
Print.logError("Field does not exist: " + tn + "." + fldName);
}
return false;
}
/* set field value */
return this._setFieldValue(fld, newVal);
}
/**
*** Sets the value for the specified field name
*** @param fld The DBField to set
*** @param newVal The 'Object' value to set for the field
*** @return True if 'newVal' is proper field type, false otherwise
**/
public boolean _setFieldValue(DBField fld, Object newVal)
{
/* validate Java type */
if (newVal != null) {
/* check Java types */
if (newVal.getClass() == fld.getTypeClass()) {
// ok
} else
if ((newVal instanceof Boolean) && fld.isTypeBoolean()) {
// ok
} else
if ((newVal instanceof Integer) && fld.isTypeInteger()) {
// ok
} else
if ((newVal instanceof Long) && fld.isTypeLong()) {
// ok
} else
if ((newVal instanceof Float) && fld.isTypeFloat()) {
// ok
} else
if ((newVal instanceof Double) && fld.isTypeDouble()) {
// ok
} else
if ((newVal instanceof byte[]) && fld.isTypeBLOB()) {
// ok
} else
if ((newVal instanceof DateTime) && fld.isTypeDateTime()) {
// ok
} else {
Print.logStackTrace("Invalid type["+fld.getName()+"]:" +
" found '" + StringTools.className(newVal) + "'" +
", expected '"+StringTools.className(fld.getTypeClass())+"'");
return false;
}
}
/* store value */
String fldName = fld.getName();
Object oldVal = this._getFieldValue(fldName, true);
this.valueMap.put(fldName, newVal);
DBRecord rcd = (this.recordKey != null)? this.recordKey._getDBRecord() : null;
if (rcd != null) {
rcd.setChanged(fldName, oldVal, newVal);
} else
if (!fld.isKeyField()) {
// should not be setting a non-key field if there is no associated DBRecord
Print.logStackTrace("DBRecordKey does not point to a DBRecord! ...");
}
/* ok */
return true;
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param newVal The 'Object' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, Object newVal)
{
return this._setFieldValue(fldName, false, newVal);
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param newVal The 'Object' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, Object newVal)
{
return this._setFieldValue(fldName, true, newVal);
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'String' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, String val)
{
return this._setFieldValue(fldName, false, (Object)StringTools.trim(val));
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'String' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, String val)
{
return this._setFieldValue(fldName, true, (Object)StringTools.trim(val));
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'int' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, int val)
{
return this._setFieldValue(fldName, false, (Object)(new Integer(val)));
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'int' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, int val)
{
return this._setFieldValue(fldName, true, (Object)(new Integer(val)));
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'long' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, long val)
{
return this._setFieldValue(fldName, false, (Object)(new Long(val)));
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'long' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, long val)
{
return this._setFieldValue(fldName, true, (Object)(new Long(val)));
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'float' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, float val)
{
return this._setFieldValue(fldName, false, (Object)(new Float(val)));
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'float' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, float val)
{
return this._setFieldValue(fldName, true, (Object)(new Float(val)));
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'double' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, double val)
{
return this._setFieldValue(fldName, false, (Object)(new Double(val)));
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'double' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, double val)
{
return this._setFieldValue(fldName, true, (Object)(new Double(val)));
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'boolean' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, boolean val)
{
return this._setFieldValue(fldName, false, (Object)(new Boolean(val)));
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'boolean' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, boolean val)
{
return this._setFieldValue(fldName, true, (Object)(new Boolean(val)));
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'byte[]' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, byte val[])
{
return this._setFieldValue(fldName, false, (Object)((val != null)? val : new byte[0]));
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'byte[]' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, byte val[])
{
return this._setFieldValue(fldName, true, (Object)((val != null)? val : new byte[0]));
}
/**
*** Sets the value for the specified optional field name
*** @param fldName The field name to set
*** @param val The 'DateTime' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setOptionalFieldValue(String fldName, DateTime val)
{
return this._setFieldValue(fldName, false, (Object)val);
}
/**
*** Sets the value for the specified field name
*** @param fldName The field name to set
*** @param val The 'boolean' value to set for the field
*** @return True if the field exists, false otherwise
**/
public boolean setFieldValue(String fldName, DateTime val)
{
return this._setFieldValue(fldName, true, (Object)val);
}
// ------------------------------------------------------------------------
/**
*** Sets all field values from the specified ResultSet
*** @param rs The ResultSet from which field values are retrieved
*** @throws SQLException If field does not exist
**/
public void setAllFieldValues(ResultSet rs)
throws SQLException
{
this.setAllFieldValues(rs, true, null);
}
/**
*** Sets all field values from the specified ResultSet
*** @param rs The ResultSet from which field values are retrieved
*** @param setPrimaryKey True to set primay key fields
*** @throws SQLException If field does not exist
**/
public void setAllFieldValues(ResultSet rs, boolean setPrimaryKey)
throws SQLException
{
this.setAllFieldValues(rs, setPrimaryKey, null);
}
/**
*** Sets all field values from the specified ResultSet
*** @param rs The ResultSet from which field values are retrieved
*** @param setPrimaryKey True to set primay key fields
*** @throws SQLException If field does not exist
**/
public void setAllFieldValues(ResultSet rs, boolean setPrimaryKey, DBField fldList[])
throws SQLException
{
if (rs == null) {
// quietly ignore
} else
if (this.recordKey != null) {
String utableName = this.getUntranslatedTableName();
DBField fld[] = (fldList != null)? fldList : this.recordKey.getFields();
for (int i = 0; i < fld.length; i++) {
if (setPrimaryKey || !fld[i].isPrimaryKey()) {
try {
Object val = fld[i].getResultSetValue(rs); // may throw exception if field does not exist
this._setFieldValue(fld[i], val);
} catch (SQLException sqe) {
// we want to ignore "Column 'xxxx' not found" errors [found: SQLState:S0022;ErrorCode:0]
int errCode = sqe.getErrorCode(); // in the test we performed, this was '0' (thus useless)
if (errCode == DBFactory.SQLERR_UNKNOWN_COLUMN) {
// this is the errorCode that is supposed to be returned
Print.logException("Unknown Column: '" + utableName + "." + fld[i].getName() + "'", sqe);
} else
if (sqe.getMessage().indexOf("Column") >= 0) {
// if it says anything about the "Column"
if (RTConfig.isDebugMode()) {
Print.logException("Column '" + utableName + "." + fld[i].getName() + "'?", sqe);
} else {
Print.logError("Column '" + utableName + "." + fld[i].getName() + "'? " + sqe);
}
} else {
throw sqe;
}
}
}
}
} else {
Print.logStackTrace("DBRecordKey has not been set!");
}
}
/**
*** Sets all field values from the specified value map (all fields required)
*** @param valMap The Field==>Value map
*** @throws DBException If field does not exist
**/
public void setAllFieldValues(Map<String,String> valMap)
throws DBException
{
this.setAllFieldValues(valMap, true/*setPrimaryKey*/);
}
/**
*** Sets all field values from the specified value map (all fields required)
*** @param valMap The Field==>Value map
*** @param setPrimaryKey True if key fields should also be set
*** @throws DBException If field does not exist
**/
public void setAllFieldValues(Map<String,String> valMap, boolean setPrimaryKey)
throws DBException
{
this.setFieldValues(valMap, setPrimaryKey, true/*requireAllFields*/);
}
/**
*** Sets the specified field values from the specified ResultSet.
*** (NOTE: field names specified in the value map, which do not exist in the
*** actual field list, are quietly ignored).
*** @param valMap The Field==>Value map
*** @param setPrimaryKey True if key fields should also be set
*** @throws DBException If field does not exist
**/
public void setFieldValues(Map<String,String> valMap, boolean setPrimaryKey, boolean requireAllFields)
throws DBException
{
if (this.recordKey != null) {
String utableName = this.getUntranslatedTableName();
DBField fld[] = this.recordKey.getFields();
for (int i = 0; i < fld.length; i++) {
String name = fld[i].getName();
String val = valMap.get(name); // may be defined, but null
if (fld[i].isPrimaryKey()) {
if (setPrimaryKey) {
if (val != null) {
//Print.logInfo("Setting Key Field: " + name + " ==> " + val);
Object v = fld[i].parseStringValue(val);
this._setFieldValue(fld[i], v);
} else {
throw new DBException("Setting Key Field Values: value not defined for field - " + name);
}
}
} else {
if (val != null) {
//Print.logInfo("Setting Field: " + name + " ==> " + val);
Object v = fld[i].parseStringValue(val);
this._setFieldValue(fld[i], v);
} else
if (requireAllFields) {
//throw new DBException("Setting Field Values: value not defined for field - " + name);
Print.logError("Column '" + utableName + "." + name + "' value not specified.");
}
}
}
} else {
Print.logStackTrace("DBRecordKey has not been set!");
}
}
/**
*** Sets the specified field values from the specified ResultSet.
*** (NOTE: field names specified in the value map, which do not exist in the
*** actual field list, are quietly ignored).
*** @param fldVals The Field==>Value map
*** @param setPrimaryKey True if primary key fields should also be set
*** @throws DBException If field does not exist
**/
public void setFieldValues(DBFieldValues fldVals, boolean setPrimaryKey, boolean requireAllFields)
throws DBException
{
if ((this.recordKey != null) && (fldVals != null)) {
String utableName = this.getUntranslatedTableName();
DBField fld[] = this.recordKey.getFields();
for (int i = 0; i < fld.length; i++) {
String name = fld[i].getName();
Object val = fldVals.getOptionalFieldValue(name);
if (fld[i].isPrimaryKey()) {
if (setPrimaryKey) {
if (val != null) {
//Print.logInfo("Setting Key Field: " + name + " ==> " + val);
this._setFieldValue(fld[i], val);
} else {
throw new DBException("Setting Key Field Values: value not defined for field - " + name);
}
}
} else {
if (val != null) {
//Print.logInfo("Setting Field: " + name + " ==> " + val);
this._setFieldValue(fld[i], val);
} else
if (requireAllFields) {
//throw new DBException("Setting Field Values: value not defined for field - " + name);
Print.logError("Column '" + utableName + "." + name + "' value not specified.");
}
}
}
} else {
Print.logStackTrace("DBRecordKey has not been set!");
}
}
// ------------------------------------------------------------------------
/**
*** Converts the field name to the proper case
*** @param fldName The case-insensitive field name
*** @return The field name in proper case.
**/
public String getFieldName(String fldName)
{
if (fldName != null) {
return this.caseMap.get(fldName.toLowerCase());
} else {
return null;
}
}
// ------------------------------------------------------------------------
/**
*** Returns true if the specified field name exists in this DBFieldValues instance
*** @param fldName The field name to test
*** @return True if the specified field name exists in this DBFieldValues instance
**/
public boolean hasField(String fldName)
{
// if true, the field is defined
if (fldName == null) {
return false;
} else {
String fn = DBProvider.translateColumnName(fldName);
return this.fieldMap.containsKey(fn);
}
}
/**
*** Returns true if a value has been set for the specified field name
*** @param fldName The field name to test for a set value
*** @return True if ta value has been set for the specified field name
**/
public boolean hasFieldValue(String fldName)
{
// if true, the field, and its value, are defined
return (fldName != null)? this.valueMap.containsKey(fldName) : false;
}
// ------------------------------------------------------------------------
/**
*** Gets the value for the specified field name
*** @param fldName The field name for the value retrieved
*** @param requiredField True to indicate that this field is required (warnings displayed if field is not found)
*** @return The field value
**/
protected Object _getFieldValue(String fldName, boolean requiredField)
{
Object val = (fldName != null)? this.valueMap.get(fldName) : null;
if (val != null) {
// field value found (or undefined)
return val;
} else
if (this.hasField(fldName)) {
// field name found, but value is null (which may be the case if the value was undefined)
//Print.logError("Field value is null: " + fldName);
return null;
} else
if (requiredField && !this.getIgnoreInvalidFields()) {
Print.logStackTrace("Field not found: " + fldName);
return null;
} else {
return null;
}
}
/**
*** Gets the value for the specified field name
*** @param fldName The field name for the value retrieved
*** @param requiredField True to indicate that this field is required (warnings displayed if field is not found)
*** @param rtnDft True to return a default value if a value has not been set
*** @return The field value
**/
protected Object _getFieldValue(String fldName, boolean requiredField, boolean rtnDft)
{
/* get field value */
Object obj = this._getFieldValue(fldName, requiredField);
/* create default? */
if ((obj == null) && rtnDft) {
// return a default value consistent with the field type
DBField fld = this.getField(fldName);
if (fld != null) {
obj = fld.getDefaultValue();
if (obj == null) {
// Implementation error, this should never occur
Print.logStackTrace("Field doesn't support a default value: " + fldName);
return null;
}
} else {
// Implementation error, this should never occur
// If we're here, the field doesn't exist.
return null;
}
}
/* return object */
return obj;
}
/**
*** Gets the value for the specified optional field name
*** @param fldName The field name for the value retrieved
*** @return The optional field value, or null if the field has not been set, or does not exist
**/
public Object getOptionalFieldValue(String fldName)
{
return this._getFieldValue(fldName, false, false);
}
/**
*** Gets the value for the specified optional field name
*** @param fldName The field name for the value retrieved
*** @return The optional field value, or null if the field has not been set, or does not exist
**/
public Object getOptionalFieldValue(String fldName, boolean rtnDft)
{
return this._getFieldValue(fldName, false, rtnDft);
}
/**
*** Gets the value for the specified field name
*** @param fldName The field name for the value retrieved
*** @return The field value
**/
public Object getFieldValue(String fldName)
{
return this._getFieldValue(fldName, true, false);
}
/**
*** Gets the value for the specified field name
*** @param fldName The field name for the value retrieved
*** @param rtnDft True to return a default value if a value has not been set
*** @return The field value
**/
public Object getFieldValue(String fldName, boolean rtnDft)
{
return this._getFieldValue(fldName, true, rtnDft);
}
/**
*** Gets the String representation of the field value
*** @param fldName The field name for the value retrieved
*** @return The String representation of the field value
**/
public String getFieldValueAsString(String fldName)
{
Object val = this.getFieldValue(fldName, true);
if (val instanceof Number) {
DBField fld = this.getField(fldName);
if (fld != null) {
String fmt = fld.getFormat();
if ((fmt != null) && fmt.startsWith("X")) { // hex
return fld.formatValue(val);
}
}
}
return DBFieldValues.toStringValue(val);
}
// ------------------------------------------------------------------------
/**
*** Converts the specified object to a String representation
*** @param obj The Object to converts to a String representation
*** @return The String representation of the specified object
**/
public static String toStringValue(Object obj)
{
/* null? */
if (obj == null) {
return "";
}
/* DBFieldType? */
if (obj instanceof DBFieldType) {
obj = ((DBFieldType)obj).getObject();
}
/* convert to String */
if (obj instanceof String) {
return ((String)obj).trim();
} else
if (obj instanceof Number) {
return obj.toString();
} else
if (obj instanceof Boolean) {
return ((Boolean)obj).booleanValue()? "1" : "0";
} else
if (obj instanceof byte[]) {
String hex = StringTools.toHexString((byte[])obj);
return "0x" + hex;
} else
if (obj instanceof DateTime) {
DateTime dt = (DateTime)obj;
return dt.format("yyyy-MM-dd HH:mm:ss", DateTime.getGMTTimeZone());
} else {
Print.logWarn("Converting object to string: " + StringTools.className(obj));
return obj.toString();
}
}
}
|
3e0d9ebed43baa0acff795626c41651240b709b6 | 16,829 | java | Java | consent-management/consent-xs2a-api/src/main/java/de/adorsys/psd2/consent/api/PisCommonPaymentApi.java | dberadze/xs2a | 71334ba664c6f87719ffa8fa48b486b9d726ce7c | [
"Apache-2.0"
] | null | null | null | consent-management/consent-xs2a-api/src/main/java/de/adorsys/psd2/consent/api/PisCommonPaymentApi.java | dberadze/xs2a | 71334ba664c6f87719ffa8fa48b486b9d726ce7c | [
"Apache-2.0"
] | null | null | null | consent-management/consent-xs2a-api/src/main/java/de/adorsys/psd2/consent/api/PisCommonPaymentApi.java | dberadze/xs2a | 71334ba664c6f87719ffa8fa48b486b9d726ce7c | [
"Apache-2.0"
] | null | null | null | 52.64486 | 320 | 0.68075 | 5,751 | /*
* Copyright 2018-2020 adorsys GmbH & Co KG
*
* 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 de.adorsys.psd2.consent.api;
import de.adorsys.psd2.consent.api.authorisation.CreateAuthorisationRequest;
import de.adorsys.psd2.consent.api.authorisation.CreateAuthorisationResponse;
import de.adorsys.psd2.consent.api.authorisation.UpdateAuthorisationRequest;
import de.adorsys.psd2.consent.api.config.InternalCmsXs2aApiTagName;
import de.adorsys.psd2.consent.api.pis.CreatePisCommonPaymentResponse;
import de.adorsys.psd2.consent.api.pis.PisCommonPaymentDataStatusResponse;
import de.adorsys.psd2.consent.api.pis.PisCommonPaymentResponse;
import de.adorsys.psd2.consent.api.pis.proto.PisPaymentInfo;
import de.adorsys.psd2.xs2a.core.authorisation.Authorisation;
import de.adorsys.psd2.xs2a.core.profile.ScaApproach;
import de.adorsys.psd2.xs2a.core.sca.AuthorisationScaApproachResponse;
import de.adorsys.psd2.xs2a.core.sca.ScaStatus;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping(path = "api/v1/pis/common-payments")
@Api(value = "api/v1/pis/common-payments", tags = InternalCmsXs2aApiTagName.PIS_COMMON_PAYMENT)
public interface PisCommonPaymentApi {
@PostMapping(path = "/")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = CreatePisCommonPaymentResponse.class),
@ApiResponse(code = 400, message = "Bad request")})
ResponseEntity<CreatePisCommonPaymentResponse> createCommonPayment(@RequestBody PisPaymentInfo request);
@GetMapping(path = "/{payment-id}/status")
@ApiOperation(value = "")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = PisCommonPaymentDataStatusResponse.class),
@ApiResponse(code = 400, message = "Bad request")})
ResponseEntity<PisCommonPaymentDataStatusResponse> getPisCommonPaymentStatusById(
@ApiParam(name = "payment-id",
value = "The payment identification assigned to the created payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId);
@GetMapping(path = "/{payment-id}")
@ApiOperation(value = "")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = PisCommonPaymentResponse.class),
@ApiResponse(code = 400, message = "Bad request")})
ResponseEntity<PisCommonPaymentResponse> getCommonPaymentById(
@ApiParam(name = "payment-id",
value = "The payment identification assigned to the created payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId);
@PutMapping(path = "/{payment-id}/status/{status}")
@ApiOperation(value = "")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 400, message = "Bad request")})
ResponseEntity<Void> updateCommonPaymentStatus(
@ApiParam(name = "payment-id",
value = "The payment identification assigned to the created payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId,
@ApiParam(value = "The following code values are permitted 'ACCC', 'ACCP', 'ACSC', 'ACSP', 'ACTC', 'ACWC', 'ACWP', 'PDNG', 'RJCT', 'RCVD', 'CANC', 'ACFC', 'PATC'. These values might be extended by ASPSP by more values.",
allowableValues = "AcceptedSettlementCompletedCreditor, AcceptedCustomerProfile, AcceptedSettlementCompleted, AcceptedSettlementInProcess, AcceptedTechnicalValidation, AcceptedWithChange, AcceptedWithoutPosting, Received, Pending, Rejected, Canceled, AcceptedFundsChecked, PartiallyAcceptedTechnicalCorrect",
required = true)
@PathVariable("status") String status);
@PostMapping(path = "/{payment-id}/authorisations")
@ApiOperation(value = "Create authorisation for given id.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<CreateAuthorisationResponse> createAuthorisation(
@ApiParam(name = "payment-id",
value = "The payment identification assigned to the created authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId,
@RequestBody CreateAuthorisationRequest request);
@PostMapping(path = "/{payment-id}/cancellation-authorisations")
@ApiOperation(value = "Create payment authorisation cancellation for given payment id.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<CreateAuthorisationResponse> createAuthorisationCancellation(
@ApiParam(name = "payment-id",
value = "The payment identification of the related payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId,
@RequestBody CreateAuthorisationRequest request);
@PutMapping(path = "/authorisations/{authorisation-id}")
@ApiOperation(value = "Update pis authorisation.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<Authorisation> updateAuthorisation(
@ApiParam(name = "authorisation-id",
value = "The authorisation identification assigned to the created authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId,
@RequestBody UpdateAuthorisationRequest request);
@PutMapping(path = "authorisations/{authorisation-id}/status/{status}")
@ApiOperation(value = "Update status for PIS authorisation.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<Void> updateAuthorisationStatus(
@ApiParam(name = "authorisation-id",
value = "The authorisation identification assigned to the created authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId,
@ApiParam(name = "status",
value = "The authorisation status.",
example = "ScaStatus.FAILED",
required = true)
@PathVariable("status") String authorisationStatus);
@GetMapping(path = "/authorisations/{authorisation-id}")
@ApiOperation(value = "Getting pis authorisation.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<Authorisation> getAuthorisation(
@ApiParam(name = "authorisation-id",
value = "The authorisation identification assigned to the created authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId);
@GetMapping(path = "/{payment-id}/authorisations/{authorisation-id}/status")
@ApiOperation(value = "Gets SCA status of pis consent authorisation.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<ScaStatus> getAuthorisationScaStatus(
@ApiParam(name = "payment-id",
value = "Identification of the payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId,
@ApiParam(name = "authorisation-id",
value = "The consent authorisation identification",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId);
@PutMapping(path = "/cancellation-authorisations/{authorisation-id}")
@ApiOperation(value = "Update pis cancellation authorisation.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<Authorisation> updateCancellationAuthorisation(
@ApiParam(name = "cancellation-id",
value = "The cancellation authorisation identification assigned to the created cancellation authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId,
@RequestBody UpdateAuthorisationRequest request);
@GetMapping(path = "/cancellation-authorisations/{authorisation-id}")
@ApiOperation(value = "Getting pis cancellation authorisation.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<List<String>> getAuthorisationCancellation(
@ApiParam(name = "cancellation-id",
value = "The cancellation authorisation identification assigned to the created cancellation authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId);
@GetMapping(path = "/{payment-id}/cancellation-authorisations")
@ApiOperation(value = "Gets list of payment cancellation authorisation IDs by payment ID")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<List<String>> getAuthorisationsCancellation(
@ApiParam(name = "payment-id",
value = "The payment identification of the related payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId);
@GetMapping(path = "/{payment-id}/cancellation-authorisations/{authorisation-id}/status")
@ApiOperation(value = "Gets SCA status of pis consent cancellation authorisation.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<ScaStatus> getCancellationAuthorisationScaStatus(
@ApiParam(name = "payment-id",
value = "Identification of the payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("payment-id") String paymentId,
@ApiParam(name = "cancellation-id",
value = "Identification of the consent cancellation authorisation",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId);
@GetMapping(path = "/{payment-id}/authorisations")
@ApiOperation(value = "Gets list of payment authorisation IDs by payment ID")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<List<String>> getAuthorisations(
@ApiParam(name = "payment-id",
value = "The payment identification of the related payment.",
example = "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7",
required = true)
@PathVariable("payment-id") String paymentId);
@GetMapping(path = "/authorisations/{authorisation-id}/authentication-methods/{authentication-method-id}")
@ApiOperation(value = "Checks if requested authentication method is decoupled")
@ApiResponse(code = 200, message = "OK")
ResponseEntity<Boolean> isAuthenticationMethodDecoupled(
@ApiParam(name = "authorisation-id",
value = "Common payment authorisation identification",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId,
@ApiParam(name = "authentication-method-id",
value = "Authentication method identification",
example = "sms",
required = true)
@PathVariable("authentication-method-id") String authenticationMethodId);
@PostMapping(path = "/authorisations/{authorisation-id}/authentication-methods")
@ApiOperation(value = "Saves authentication methods in authorisation")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "No Content"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<Void> saveAuthenticationMethods(
@ApiParam(name = "authorisation-id",
value = "The common payment authorisation identification.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId,
@RequestBody List<CmsScaMethod> methods);
@PutMapping(path = "/authorisations/{authorisation-id}/sca-approach/{sca-approach}")
@ApiOperation(value = "Updates pis sca approach.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<Boolean> updateScaApproach(
@ApiParam(name = "authorisation-id",
value = "The authorisation identification assigned to the created authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId,
@ApiParam(name = "sca-approach",
value = "Chosen SCA approach.",
example = "REDIRECT",
required = true)
@PathVariable("sca-approach") ScaApproach scaApproach);
@GetMapping(path = "/authorisations/{authorisation-id}/sca-approach")
@ApiOperation(value = "Gets SCA approach of the payment initiation authorisation by its ID")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<AuthorisationScaApproachResponse> getAuthorisationScaApproach(
@ApiParam(name = "authorisation-id",
value = "Identification of the payment initiation authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId);
@GetMapping(path = "/cancellation-authorisations/{authorisation-id}/sca-approach")
@ApiOperation(value = "Gets SCA approach of the payment cancellation authorisation by its ID")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found")})
ResponseEntity<AuthorisationScaApproachResponse> getCancellationAuthorisationScaApproach(
@ApiParam(name = "authorisation-id",
value = "Identification of the payment cancellation authorisation.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable("authorisation-id") String authorisationId);
@PutMapping(path = "/{payment-id}/multilevel-sca")
@ApiOperation(value = "Updates multilevel sca required by payment ID")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Bad Request")})
ResponseEntity<Boolean> updateMultilevelScaRequired(
@ApiParam(name = "payment-id",
value = "The payment identification of the related payment.",
example = "bf489af6-a2cb-4b75-b71d-d66d58b934d7",
required = true)
@PathVariable(name = "payment-id") String paymentId,
@ApiParam(name = "multilevel-sca", value = "Multilevel SCA.", example = "false")
@RequestParam(value = "multilevel-sca", defaultValue = "false") boolean multilevelSca);
}
|
3e0d9ecc03ec670941deb2ee29c6891b7d9fdf54 | 6,846 | java | Java | webapps/src/main/java/org/camunda/bpm/cockpit/impl/plugin/base/dto/IncidentDto.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 2,577 | 2015-01-02T07:43:55.000Z | 2022-03-31T22:31:45.000Z | webapps/src/main/java/org/camunda/bpm/cockpit/impl/plugin/base/dto/IncidentDto.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 839 | 2015-01-12T22:06:28.000Z | 2022-03-24T13:26:29.000Z | webapps/src/main/java/org/camunda/bpm/cockpit/impl/plugin/base/dto/IncidentDto.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 1,270 | 2015-01-02T03:39:25.000Z | 2022-03-31T06:04:37.000Z | 28.886076 | 100 | 0.790389 | 5,752 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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 org.camunda.bpm.cockpit.impl.plugin.base.dto;
import java.util.Date;
/**
* @author roman.smirnov
*/
public class IncidentDto {
protected String id;
protected Date incidentTimestamp;
protected String incidentMessage;
protected String incidentType;
protected String executionId;
protected String activityId;
protected String failedActivityId;
protected String processInstanceId;
protected String processDefinitionId;
protected String causeIncidentId;
protected String rootCauseIncidentId;
protected String configuration;
protected String annotation;
// additional properties
protected String causeIncidentProcessInstanceId;
protected String causeIncidentProcessDefinitionId;
protected String causeIncidentActivityId;
protected String causeIncidentFailedActivityId;
protected String rootCauseIncidentProcessInstanceId;
protected String rootCauseIncidentProcessDefinitionId;
protected String rootCauseIncidentActivityId;
protected String rootCauseIncidentFailedActivityId;
protected String rootCauseIncidentConfiguration;
protected String rootCauseIncidentMessage;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getIncidentTimestamp() {
return incidentTimestamp;
}
public void setIncidentTimestamp(Date incidentTimestamp) {
this.incidentTimestamp = incidentTimestamp;
}
public String getIncidentMessage() {
return incidentMessage;
}
public void setIncidentMessage(String incidentMessage) {
this.incidentMessage = incidentMessage;
}
public String getIncidentType() {
return incidentType;
}
public void setIncidentType(String incidentType) {
this.incidentType = incidentType;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getCauseIncidentId() {
return causeIncidentId;
}
public void setCauseIncidentId(String causeIncidentId) {
this.causeIncidentId = causeIncidentId;
}
public String getRootCauseIncidentId() {
return rootCauseIncidentId;
}
public void setRootCauseIncidentId(String rootCauseIncidentId) {
this.rootCauseIncidentId = rootCauseIncidentId;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getCauseIncidentProcessInstanceId() {
return causeIncidentProcessInstanceId;
}
public void setCauseIncidentProcessInstanceId(String causeIncidentProcessInstanceId) {
this.causeIncidentProcessInstanceId = causeIncidentProcessInstanceId;
}
public String getCauseIncidentProcessDefinitionId() {
return causeIncidentProcessDefinitionId;
}
public String getCauseIncidentActivityId() {
return causeIncidentActivityId;
}
public void setCauseIncidentActivityId(String causeIncidentActivityId) {
this.causeIncidentActivityId = causeIncidentActivityId;
}
public String getCauseIncidentFailedActivityId() {
return causeIncidentFailedActivityId;
}
public void setCauseIncidentFailedActivityId(String causeIncidentFailedActivityId) {
this.causeIncidentFailedActivityId = causeIncidentFailedActivityId;
}
public void setCauseIncidentProcessDefinitionId(String causeIncidentProcessDefinitionId) {
this.causeIncidentProcessDefinitionId = causeIncidentProcessDefinitionId;
}
public String getRootCauseIncidentProcessInstanceId() {
return rootCauseIncidentProcessInstanceId;
}
public void setRootCauseIncidentProcessInstanceId(String rootCauseIncidentProcessInstanceId) {
this.rootCauseIncidentProcessInstanceId = rootCauseIncidentProcessInstanceId;
}
public String getRootCauseIncidentProcessDefinitionId() {
return rootCauseIncidentProcessDefinitionId;
}
public void setRootCauseIncidentProcessDefinitionId(String rootCauseIncidentProcessDefinitionId) {
this.rootCauseIncidentProcessDefinitionId = rootCauseIncidentProcessDefinitionId;
}
public String getRootCauseIncidentActivityId() {
return rootCauseIncidentActivityId;
}
public void setRootCauseIncidentActivityId(String rootCauseIncidentActivityId) {
this.rootCauseIncidentActivityId = rootCauseIncidentActivityId;
}
public String getRootCauseIncidentFailedActivityId() {
return rootCauseIncidentFailedActivityId;
}
public void setRootCauseIncidentFailedActivityId(String rootCauseIncidentFailedActivityId) {
this.rootCauseIncidentFailedActivityId = rootCauseIncidentFailedActivityId;
}
public String getRootCauseIncidentConfiguration() {
return rootCauseIncidentConfiguration;
}
public void setRootCauseIncidentConfiguration(String rootCauseIncidentConfiguration) {
this.rootCauseIncidentConfiguration = rootCauseIncidentConfiguration;
}
public String getRootCauseIncidentMessage() {
return rootCauseIncidentMessage;
}
public void setRootCauseIncidentMessage(String rootCauseIncidentMessage) {
this.rootCauseIncidentMessage = rootCauseIncidentMessage;
}
}
|
3e0d9f15f05e105e2e6111b3c29885392dea6205 | 1,942 | java | Java | src/test/java/de/jensd/addon/registry/PayloadConverterRegistryTest.java | Jerady/mqttfx-payload-decoder | 821a2a922e75cd7a6ddbd25bc5cd5c7c2440a54c | [
"Apache-2.0"
] | 6 | 2018-07-20T01:32:41.000Z | 2022-01-14T15:33:41.000Z | src/test/java/de/jensd/addon/registry/PayloadConverterRegistryTest.java | Jerady/mqttfx-payload-decoder | 821a2a922e75cd7a6ddbd25bc5cd5c7c2440a54c | [
"Apache-2.0"
] | 2 | 2019-01-18T14:46:20.000Z | 2022-03-09T06:19:16.000Z | src/test/java/de/jensd/addon/registry/PayloadConverterRegistryTest.java | Jerady/mqttfx-payload-decoder | 821a2a922e75cd7a6ddbd25bc5cd5c7c2440a54c | [
"Apache-2.0"
] | 6 | 2017-05-20T22:41:00.000Z | 2020-12-25T06:27:35.000Z | 36.641509 | 130 | 0.721421 | 5,753 | /**
* Copyright (c) 2017 Jens Deters http://www.jensd.de
*
* 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 de.jensd.addon.registry;
import de.jensd.addon.AddOnRegistryServiceLoader;
import java.util.List;
import de.jensd.addon.decoder.PayloadDecoder;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author Jens Deters
*/
class PayloadConverterRegistryTest {
public PayloadConverterRegistryTest() {
}
@Test
void testLoadExtensions() {
AddOnRegistryServiceLoader extensionRegistry = new AddOnRegistryServiceLoader();
List<PayloadDecoder> converters = extensionRegistry.getAddOns(PayloadDecoder.class);
assertEquals(converters.size() == 5, "Expected to find 5 payload decoders");
}
@Test
void testLoadExtensionsFromJar() {
String lookupPath = "build/libs/";
System.setProperty(AddOnRegistryServiceLoader.ADDON_LOOKUP_PATH_PROPERTY_NAME, lookupPath);
AddOnRegistryServiceLoader extensionRegistry = new AddOnRegistryServiceLoader();
List<PayloadDecoder> converters = extensionRegistry.getAddOns(PayloadDecoder.class);
converters.forEach(c -> {
System.out.println(String.format("%-30s %-30s %-10s %s", c.getId(), c.getName(), c.getVersion(), c.getDescription()));
});
assertEquals( "Expected to find 5 payload decoders", converters.size() == 5);
}
}
|
3e0d9f4db14a3eeb27e0681be47990a2b65f85e1 | 2,841 | java | Java | python/experiments/projects/Angel-ML-angel/real_error_dataset/1/151/MFUpdateFunc.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | python/experiments/projects/Angel-ML-angel/real_error_dataset/1/151/MFUpdateFunc.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | python/experiments/projects/Angel-ML-angel/real_error_dataset/1/151/MFUpdateFunc.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | 36.423077 | 101 | 0.710313 | 5,754 | /*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.angel.ml.matrix.psf.updater.base;
import com.tencent.angel.common.Serialize;
import com.tencent.angel.ps.impl.PSContext;
import com.tencent.angel.ps.impl.matrix.ServerDenseDoubleRow;
import com.tencent.angel.ps.impl.matrix.ServerPartition;
import com.tencent.angel.ps.impl.matrix.ServerRow;
/**
* `MFUpdateFunc` is a POF updater for multi rows in matrix with a user-defined function.
* Constructor's Parameters include int[] `rowIds` and Serialize `func`, which correspond to
* ServerDenseDoubleRow[] `rows` and Serialize `func` in `doUpdate` interface respectively.
*
* That is the length of `rowIds` and `rows` is exactly the same, rows[i] is the content of
* rowIds[i] row in matrix.
*/
public abstract class MFUpdateFunc extends UpdateFunc {
public MFUpdateFunc(int matrixId, int[] rowIds, Serialize func) {
super(new MFUpdaterParam(matrixId, rowIds, func));
}
public MFUpdateFunc() {
super(null);
}
@Override
public void partitionUpdate(PartitionUpdaterParam partParam) {
ServerPartition part = PSContext.get()
.getMatrixPartitionManager()
.getPartition(partParam.getMatrixId(), partParam.getPartKey().getPartitionId());
if (part != null) {
MFUpdaterParam.MFPartitionUpdaterParam mf = (MFUpdaterParam.MFPartitionUpdaterParam) partParam;
int[] rowIds = mf.getRowIds();
ServerRow[] rows = new ServerRow[rowIds.length];
for (int i = 0; i < rowIds.length; i++) {
rows[i] = part.getRow(rowIds[i]);
}
update(rows, mf.getFunc());
}
}
private void update(ServerRow[] rows, Serialize func) {
switch (rows[0].getRowType()) {
case T_DOUBLE_DENSE:
ServerDenseDoubleRow[] denseRows = new ServerDenseDoubleRow[rows.length];
for (int i = 0; i < rows.length; i++) {
denseRows[i] = (ServerDenseDoubleRow) rows[i];
}
doUpdate(denseRows, func);
return;
default:
throw new RuntimeException("currently only supports Double Dense Row");
}
}
protected abstract void doUpdate(ServerDenseDoubleRow[] rows, Serialize func);
}
|
3e0d9f54f857e407b5c5d4a00a96f35429f545d9 | 1,158 | java | Java | webapps/legacyjson/src/main/java/uk/ac/ebi/biosamples/legacy/json/domain/LegacyExternalReference.java | FuqiX/biosamples-v4 | b1d28fdf356243f95c791a2cd14fbbce994ea08f | [
"Apache-2.0"
] | null | null | null | webapps/legacyjson/src/main/java/uk/ac/ebi/biosamples/legacy/json/domain/LegacyExternalReference.java | FuqiX/biosamples-v4 | b1d28fdf356243f95c791a2cd14fbbce994ea08f | [
"Apache-2.0"
] | null | null | null | webapps/legacyjson/src/main/java/uk/ac/ebi/biosamples/legacy/json/domain/LegacyExternalReference.java | FuqiX/biosamples-v4 | b1d28fdf356243f95c791a2cd14fbbce994ea08f | [
"Apache-2.0"
] | null | null | null | 27.571429 | 73 | 0.728843 | 5,755 | package uk.ac.ebi.biosamples.legacy.json.domain;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import uk.ac.ebi.biosamples.model.ExternalReference;
import uk.ac.ebi.biosamples.service.ExternalReferenceService;
@JsonPropertyOrder(value = {"name", "acc", "url"})
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class LegacyExternalReference {
private String name;
private String url;
private String accession;
public LegacyExternalReference() {}
public LegacyExternalReference(ExternalReference externalReference) {
ExternalReferenceService service = new ExternalReferenceService();
this.name = service.getNickname(externalReference);
this.accession = service.getDataId(externalReference).orElse("");
this.url = externalReference.getUrl();
}
@JsonGetter
public String getName() {
return name;
}
@JsonGetter
public String getUrl() {
return url;
}
@JsonGetter("acc")
public String getAccession() {
return accession;
}
}
|
3e0da1023cd5c866d5e33d3ff099b691d1319295 | 7,184 | java | Java | opencga-core/src/main/java/org/opencb/opencga/core/models/study/configuration/ClinicalAnalysisStudyConfiguration.java | lauralopezreal/opencga-laura | bdce25d11abc43789d7bdebbaa832d3144d961fe | [
"Apache-2.0"
] | 146 | 2015-03-05T19:14:22.000Z | 2022-03-30T03:46:48.000Z | opencga-core/src/main/java/org/opencb/opencga/core/models/study/configuration/ClinicalAnalysisStudyConfiguration.java | lauralopezreal/opencga-laura | bdce25d11abc43789d7bdebbaa832d3144d961fe | [
"Apache-2.0"
] | 1,623 | 2015-01-27T00:30:36.000Z | 2022-03-31T14:42:33.000Z | opencga-core/src/main/java/org/opencb/opencga/core/models/study/configuration/ClinicalAnalysisStudyConfiguration.java | lauralopezreal/opencga-laura | bdce25d11abc43789d7bdebbaa832d3144d961fe | [
"Apache-2.0"
] | 93 | 2015-01-28T17:13:01.000Z | 2022-03-09T20:46:47.000Z | 49.205479 | 136 | 0.717288 | 5,756 | package org.opencb.opencga.core.models.study.configuration;
import org.opencb.opencga.core.models.clinical.ClinicalAnalysis;
import org.opencb.opencga.core.models.common.FlagValue;
import org.opencb.opencga.core.models.common.StatusValue;
import java.util.*;
public class ClinicalAnalysisStudyConfiguration {
private Map<ClinicalAnalysis.Type, List<StatusValue>> status;
private InterpretationStudyConfiguration interpretation;
private List<ClinicalPriorityValue> priorities;
private Map<ClinicalAnalysis.Type, List<FlagValue>> flags;
private ClinicalConsentConfiguration consent;
public ClinicalAnalysisStudyConfiguration() {
}
public ClinicalAnalysisStudyConfiguration(Map<ClinicalAnalysis.Type, List<StatusValue>> status,
InterpretationStudyConfiguration interpretation, List<ClinicalPriorityValue> priorities,
Map<ClinicalAnalysis.Type, List<FlagValue>> flags, ClinicalConsentConfiguration consent) {
this.status = status;
this.interpretation = interpretation;
this.priorities = priorities;
this.flags = flags;
this.consent = consent;
}
public static ClinicalAnalysisStudyConfiguration defaultConfiguration() {
Map<ClinicalAnalysis.Type, List<StatusValue>> status = new HashMap<>();
Map<ClinicalAnalysis.Type, List<StatusValue>> interpretationStatus = new HashMap<>();
List<ClinicalPriorityValue> priorities = new ArrayList<>(5);
Map<ClinicalAnalysis.Type, List<FlagValue>> flags = new HashMap<>();
List<ClinicalConsent> clinicalConsentList = new ArrayList<>();
List<StatusValue> statusValueList = new ArrayList<>(4);
statusValueList.add(new StatusValue("READY_FOR_INTERPRETATION", "The Clinical Analysis is ready for interpretations"));
statusValueList.add(new StatusValue("READY_FOR_REPORT", "The Interpretation is finished and it is to create the report"));
statusValueList.add(new StatusValue("CLOSED", "The Clinical Analysis is closed"));
statusValueList.add(new StatusValue("REJECTED", "The Clinical Analysis is rejected"));
status.put(ClinicalAnalysis.Type.FAMILY, statusValueList);
status.put(ClinicalAnalysis.Type.AUTOCOMPARATIVE, statusValueList);
status.put(ClinicalAnalysis.Type.CANCER, statusValueList);
status.put(ClinicalAnalysis.Type.COHORT, statusValueList);
status.put(ClinicalAnalysis.Type.SINGLE, statusValueList);
List<StatusValue> interpretationStatusList = new ArrayList<>(3);
interpretationStatusList.add(new StatusValue("IN_PROGRESS", "Interpretation in progress"));
interpretationStatusList.add(new StatusValue("READY", "Interpretation ready"));
interpretationStatusList.add(new StatusValue("REJECTED", "Interpretation rejected"));
interpretationStatus.put(ClinicalAnalysis.Type.FAMILY, interpretationStatusList);
interpretationStatus.put(ClinicalAnalysis.Type.AUTOCOMPARATIVE, interpretationStatusList);
interpretationStatus.put(ClinicalAnalysis.Type.CANCER, interpretationStatusList);
interpretationStatus.put(ClinicalAnalysis.Type.COHORT, interpretationStatusList);
interpretationStatus.put(ClinicalAnalysis.Type.SINGLE, interpretationStatusList);
priorities.add(new ClinicalPriorityValue("URGENT", "Highest priority of all", 1, false));
priorities.add(new ClinicalPriorityValue("HIGH", "Second highest priority of all", 2, false));
priorities.add(new ClinicalPriorityValue("MEDIUM", "Intermediate priority", 3, false));
priorities.add(new ClinicalPriorityValue("LOW", "Low priority", 4, false));
priorities.add(new ClinicalPriorityValue("UNKNOWN", "Unknown priority. Treated as the lowest priority of all.", 5, true));
List<FlagValue> flagValueList = new ArrayList<>(7);
flagValueList.add(new FlagValue("MIXED_CHEMISTRIES", ""));
flagValueList.add(new FlagValue("LOW_TUMOUR_PURITY", ""));
flagValueList.add(new FlagValue("UNIPARENTAL_ISODISOMY", ""));
flagValueList.add(new FlagValue("UNIPARENTAL_HETERODISOMY", ""));
flagValueList.add(new FlagValue("UNUSUAL_KARYOTYPE", ""));
flagValueList.add(new FlagValue("SUSPECTED_MOSAICISM", ""));
flagValueList.add(new FlagValue("LOW_QUALITY_SAMPLE", ""));
flags.put(ClinicalAnalysis.Type.FAMILY, flagValueList);
flags.put(ClinicalAnalysis.Type.AUTOCOMPARATIVE, flagValueList);
flags.put(ClinicalAnalysis.Type.CANCER, flagValueList);
flags.put(ClinicalAnalysis.Type.COHORT, flagValueList);
flags.put(ClinicalAnalysis.Type.SINGLE, flagValueList);
clinicalConsentList.add(new ClinicalConsent("PRIMARY_FINDINGS", "Primary findings", ""));
clinicalConsentList.add(new ClinicalConsent("SECONDARY_FINDINGS", "Secondary findings", ""));
clinicalConsentList.add(new ClinicalConsent("CARRIER_FINDINGS", "Carrier findings", ""));
clinicalConsentList.add(new ClinicalConsent("RESEARCH_FINDINGS", "Research findings", ""));
return new ClinicalAnalysisStudyConfiguration(status,
new InterpretationStudyConfiguration(interpretationStatus, Collections.emptyList()), priorities, flags,
new ClinicalConsentConfiguration(clinicalConsentList));
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ClinicalAnalysisStudyConfiguration{");
sb.append("status=").append(status);
sb.append(", interpretation=").append(interpretation);
sb.append(", priorities=").append(priorities);
sb.append(", flags=").append(flags);
sb.append(", consent=").append(consent);
sb.append('}');
return sb.toString();
}
public Map<ClinicalAnalysis.Type, List<StatusValue>> getStatus() {
return status;
}
public ClinicalAnalysisStudyConfiguration setStatus(Map<ClinicalAnalysis.Type, List<StatusValue>> status) {
this.status = status;
return this;
}
public InterpretationStudyConfiguration getInterpretation() {
return interpretation;
}
public ClinicalAnalysisStudyConfiguration setInterpretation(InterpretationStudyConfiguration interpretation) {
this.interpretation = interpretation;
return this;
}
public List<ClinicalPriorityValue> getPriorities() {
return priorities;
}
public ClinicalAnalysisStudyConfiguration setPriorities(List<ClinicalPriorityValue> priorities) {
this.priorities = priorities;
return this;
}
public Map<ClinicalAnalysis.Type, List<FlagValue>> getFlags() {
return flags;
}
public ClinicalAnalysisStudyConfiguration setFlags(Map<ClinicalAnalysis.Type, List<FlagValue>> flags) {
this.flags = flags;
return this;
}
public ClinicalConsentConfiguration getConsent() {
return consent;
}
public ClinicalAnalysisStudyConfiguration setConsent(ClinicalConsentConfiguration consent) {
this.consent = consent;
return this;
}
}
|
3e0da1902ac9bc2bd18e082b8c8faf65a8e4a672 | 2,829 | java | Java | examples/realisticearth/src/nl/esciencecenter/neon/examples/realisticearth/RealisticEarthInterfaceWindow.java | NLeSC/Neon | 6db8155800bc5cf3ac2825fe1de29ad217ccfc84 | [
"Apache-2.0"
] | 2 | 2016-06-20T17:05:46.000Z | 2022-01-25T04:17:57.000Z | examples/realisticearth/src/nl/esciencecenter/neon/examples/realisticearth/RealisticEarthInterfaceWindow.java | NLeSC/Neon | 6db8155800bc5cf3ac2825fe1de29ad217ccfc84 | [
"Apache-2.0"
] | null | null | null | examples/realisticearth/src/nl/esciencecenter/neon/examples/realisticearth/RealisticEarthInterfaceWindow.java | NLeSC/Neon | 6db8155800bc5cf3ac2825fe1de29ad217ccfc84 | [
"Apache-2.0"
] | 2 | 2019-04-23T03:53:33.000Z | 2022-01-25T04:18:00.000Z | 36.974026 | 116 | 0.698981 | 5,757 | package nl.esciencecenter.neon.examples.realisticearth;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import nl.esciencecenter.neon.NeonInterfacePanel;
import nl.esciencecenter.neon.swing.GoggleSwing;
/* Copyright 2013 Netherlands eScience Center
*
* 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.
*/
/**
* Example {@link NeonInterfacePanel} implementation. Currently holds no more
* than a logo, but could be used for all kinds of swing interface elements.
*
* @author Maarten van Meersbergen <envkt@example.com>
*
*/
public class RealisticEarthInterfaceWindow extends JPanel {
private final static RealisticEarthSettings settings = RealisticEarthSettings.getInstance();
// A serialVersionUID is 'needed' because we extend JPanel.
private static final long serialVersionUID = 1L;
/**
* Basic constructor for NeonExampleInterfaceWindow.
*/
public RealisticEarthInterfaceWindow() {
// Set the swing layout type for this JPanel.
setLayout(new BorderLayout(0, 0));
// Make a menu bar
final JMenuBar menuBar = new JMenuBar();
// Create a swing-enabled image.
ImageIcon nlescIcon = GoggleSwing.createResizedImageIcon("images/ESCIENCE_logo.jpg", "eScienceCenter Logo",
200, 20);
JLabel nlesclogo = new JLabel(nlescIcon);
// Add the image to the menu bar, but create some glue around it so it
// doesn't automatically resize the window to minimum size.
menuBar.add(Box.createHorizontalGlue());
menuBar.add(nlesclogo);
menuBar.add(Box.createHorizontalGlue());
// Add the menubar to a container, so we can apply a boxlayout. (not
// strictly necessary, but a demonstration of what swing could do)
Container menuContainer = new Container();
menuContainer.setLayout(new BoxLayout(menuContainer, BoxLayout.Y_AXIS));
menuContainer.add(menuBar);
// Add the menu container to the JPanel
add(menuContainer, BorderLayout.NORTH);
setVisible(true);
}
}
|
3e0da2434eb4773871a2b83c0c27346aee958a7a | 3,321 | java | Java | kayenta-opentsdb/src/main/java/com/netflix/kayenta/opentsdb/config/OpentsdbResponseConverter.java | lixmgl/kayenta | c78d53c943394e867156bfc9a8c954428a88ecda | [
"Apache-2.0"
] | null | null | null | kayenta-opentsdb/src/main/java/com/netflix/kayenta/opentsdb/config/OpentsdbResponseConverter.java | lixmgl/kayenta | c78d53c943394e867156bfc9a8c954428a88ecda | [
"Apache-2.0"
] | null | null | null | kayenta-opentsdb/src/main/java/com/netflix/kayenta/opentsdb/config/OpentsdbResponseConverter.java | lixmgl/kayenta | c78d53c943394e867156bfc9a8c954428a88ecda | [
"Apache-2.0"
] | null | null | null | 33.887755 | 95 | 0.744956 | 5,758 | package com.netflix.kayenta.opentsdb.config;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.kayenta.opentsdb.model.OpentsdbMetricDescriptorsResponse;
import com.netflix.kayenta.opentsdb.model.OpentsdbResults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.converter.JacksonConverter;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class OpentsdbResponseConverter implements Converter {
private static final int DEFAULT_STEP_SIZE = 0;
private final ObjectMapper kayentaObjectMapper;
@Autowired
public OpentsdbResponseConverter(ObjectMapper kayentaObjectMapper) {
this.kayentaObjectMapper = kayentaObjectMapper;
}
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
// Metric suggest
//if (type == OpentsdbMetricDescriptorsResponse.class) {
// return new JacksonConverter(kayentaObjectMapper).fromBody(body, type);
//}
// Metric query
try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) {
String json = reader.readLine();
log.info("Converting response from opentsdb: {}", json);
if (type != OpentsdbResults.class) {
return this.getMetadataResultObject(json);
}
Map result = getResultObject(json);
List<List> seriesValues = (List<List>) result.get("dps");
if (CollectionUtils.isEmpty(seriesValues)) {
log.warn("Received no data from Opentsdb.");
return null;
}
OpentsdbResults opentsdbResults = new OpentsdbResults((String) result.get("metric"),
(Map<String, String>) result.get("tags"), (List<List>) result.get("dps"));
log.info("Converted response: {} ", opentsdbResults);
return opentsdbResults;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private List<String> getMetadataResultObject(String json)
throws IOException, JsonParseException, JsonMappingException, ConversionException {
return kayentaObjectMapper.readValue(json, new TypeReference<List<String>>() {});
}
private Map getResultObject(String json)
throws IOException, JsonParseException, JsonMappingException, ConversionException {
List<Map> results = kayentaObjectMapper.readValue(json, new TypeReference<List<Map>>() {});
if (CollectionUtils.isEmpty(results)) {
throw new ConversionException("Unexpected response from opentsdb");
}
if (results.size() > 1) {
throw new ConversionException("Received too many series to deserialize");
}
return results.get(0);
}
@Override
public TypedOutput toBody(Object object) {
return null;
}
} |
3e0da24dbca23297b22cdf2e30a3af1d9f16a946 | 2,701 | java | Java | lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/an/SampleWSTokenizerAnnotator.java | elyograg/solr-6733 | c30e6e72b3a402dc9c14c355380dd1cbe391af89 | [
"Apache-2.0"
] | 5 | 2017-03-17T04:35:39.000Z | 2021-04-06T07:20:04.000Z | lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/an/SampleWSTokenizerAnnotator.java | elyograg/solr-6733 | c30e6e72b3a402dc9c14c355380dd1cbe391af89 | [
"Apache-2.0"
] | 5 | 2020-03-04T22:26:23.000Z | 2021-12-09T21:50:04.000Z | lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/an/SampleWSTokenizerAnnotator.java | elyograg/solr-6733 | c30e6e72b3a402dc9c14c355380dd1cbe391af89 | [
"Apache-2.0"
] | 2 | 2019-09-05T09:55:45.000Z | 2020-11-14T18:32:19.000Z | 40.313433 | 113 | 0.757127 | 5,759 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.lucene.analysis.uima.an;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
/**
* Dummy implementation of a UIMA based whitespace tokenizer
*/
public class SampleWSTokenizerAnnotator extends JCasAnnotator_ImplBase {
private final static String TOKEN_TYPE = "org.apache.lucene.uima.ts.TokenAnnotation";
private final static String SENTENCE_TYPE = "org.apache.lucene.uima.ts.SentenceAnnotation";
private String lineEnd;
private static final String WHITESPACE = " ";
@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
super.initialize(aContext);
lineEnd = String.valueOf(aContext.getConfigParameterValue("line-end"));
}
@Override
public void process(JCas jCas) throws AnalysisEngineProcessException {
Type sentenceType = jCas.getCas().getTypeSystem().getType(SENTENCE_TYPE);
Type tokenType = jCas.getCas().getTypeSystem().getType(TOKEN_TYPE);
int i = 0;
for (String sentenceString : jCas.getDocumentText().split(lineEnd)) {
// add the sentence
AnnotationFS sentenceAnnotation = jCas.getCas().createAnnotation(sentenceType, i, sentenceString.length());
jCas.addFsToIndexes(sentenceAnnotation);
i += sentenceString.length();
}
// get tokens
int j = 0;
for (String tokenString : jCas.getDocumentText().split(WHITESPACE)) {
int tokenLength = tokenString.length();
AnnotationFS tokenAnnotation = jCas.getCas().createAnnotation(tokenType, j, j + tokenLength);
jCas.addFsToIndexes(tokenAnnotation);
j += tokenLength;
}
}
}
|
3e0da35b1eac0a3e0c4d6fbc0caeef88aec4326f | 543 | java | Java | src/main/java/jonrabone/junit/InSuite.java | jonrabone/junit-dynamic-suites | a6b070b6d5c01b6a429b241a34fffd82ae478abf | [
"BSD-2-Clause"
] | null | null | null | src/main/java/jonrabone/junit/InSuite.java | jonrabone/junit-dynamic-suites | a6b070b6d5c01b6a429b241a34fffd82ae478abf | [
"BSD-2-Clause"
] | 1 | 2019-03-30T13:10:41.000Z | 2019-03-30T13:10:41.000Z | src/main/java/jonrabone/junit/InSuite.java | jonrabone/junit-dynamic-suites | a6b070b6d5c01b6a429b241a34fffd82ae478abf | [
"BSD-2-Clause"
] | null | null | null | 30.166667 | 107 | 0.780847 | 5,760 | package jonrabone.junit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks entire test classes or individual methods as belonging to a specific test suite.
* The {@link jonrabone.junit.InSuite} annotation can be used on both methods and classes, but methods take
* priority.
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface InSuite {
String[] value();
}
|
3e0da3cdccf5ea8d6b0c674d7f570945d6e72b9d | 1,531 | java | Java | javafx-sdk-11.0.2/lib/src/javafx.base/com/sun/javafx/reflect/FieldUtil.java | carlcastillo9818/JavaFXBankApp | 38a785e97dadcad1c9851b70680704a6d58cf875 | [
"MIT"
] | 3 | 2021-04-11T16:24:41.000Z | 2021-06-16T09:09:28.000Z | javafx-sdk-11.0.2/lib/src/javafx.base/com/sun/javafx/reflect/FieldUtil.java | carlcastillo9818/JavaFXBankApp | 38a785e97dadcad1c9851b70680704a6d58cf875 | [
"MIT"
] | null | null | null | javafx-sdk-11.0.2/lib/src/javafx.base/com/sun/javafx/reflect/FieldUtil.java | carlcastillo9818/JavaFXBankApp | 38a785e97dadcad1c9851b70680704a6d58cf875 | [
"MIT"
] | 1 | 2021-07-22T19:45:22.000Z | 2021-07-22T19:45:22.000Z | 37.341463 | 79 | 0.737427 | 5,761 | /*
* Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.javafx.reflect;
import java.lang.reflect.Field;
public final class FieldUtil {
private FieldUtil() {
}
public static Field getField(Class<?> cls, String name)
throws NoSuchFieldException {
ReflectUtil.checkPackageAccess(cls);
return cls.getField(name);
}
}
|
3e0da4bbe96a33c774aa1edc4f3a8c877764b3ea | 4,887 | java | Java | src/main/java/com/zl/way/shop/model/WayShop.java | SimonOsaka/way-api | d3f1f6cd6557d95ede209aa55dbcb38e942a6791 | [
"MIT"
] | null | null | null | src/main/java/com/zl/way/shop/model/WayShop.java | SimonOsaka/way-api | d3f1f6cd6557d95ede209aa55dbcb38e942a6791 | [
"MIT"
] | null | null | null | src/main/java/com/zl/way/shop/model/WayShop.java | SimonOsaka/way-api | d3f1f6cd6557d95ede209aa55dbcb38e942a6791 | [
"MIT"
] | null | null | null | 17.835766 | 93 | 0.643544 | 5,762 | package com.zl.way.shop.model;
import com.zl.way.commodity.model.WayCommodity;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
public class WayShop {
private Long id;
private String shopName;
private String shopAddress;
private String shopTel;
private String shopBusinessTime1;
private String shopBusinessTime2;
private Integer shopCateLeafId;
private WayShopCateLeaf wayShopCateLeaf;
private String shopInfo;
private Date createTime;
private Date updateTime;
private Byte isDeleted;
private BigDecimal shopLat;
private BigDecimal shopLng;
private String shopLogoUrl;
private List<WayCommodity> commodityList;
private String commodityName;
private String adCode;
private String cityCode;
private String shopPinyin;
private String shopPy;
private WayShopFollow follow;
public String getCommodityName() {
return commodityName;
}
public void setCommodityName(String commodityName) {
this.commodityName = commodityName;
}
public List<WayCommodity> getCommodityList() {
return commodityList;
}
public void setCommodityList(List<WayCommodity> commodityList) {
this.commodityList = commodityList;
}
public String getShopPinyin() {
return shopPinyin;
}
public void setShopPinyin(String shopPinyin) {
this.shopPinyin = shopPinyin;
}
public String getShopPy() {
return shopPy;
}
public void setShopPy(String shopPy) {
this.shopPy = shopPy;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName == null ? null : shopName.trim();
}
public String getShopAddress() {
return shopAddress;
}
public void setShopAddress(String shopAddress) {
this.shopAddress = shopAddress == null ? null : shopAddress.trim();
}
public String getShopTel() {
return shopTel;
}
public void setShopTel(String shopTel) {
this.shopTel = shopTel == null ? null : shopTel.trim();
}
public String getShopBusinessTime1() {
return shopBusinessTime1;
}
public void setShopBusinessTime1(String shopBusinessTime1) {
this.shopBusinessTime1 = shopBusinessTime1 == null ? null : shopBusinessTime1.trim();
}
public String getShopBusinessTime2() {
return shopBusinessTime2;
}
public void setShopBusinessTime2(String shopBusinessTime2) {
this.shopBusinessTime2 = shopBusinessTime2 == null ? null : shopBusinessTime2.trim();
}
public WayShopCateLeaf getWayShopCateLeaf() {
return wayShopCateLeaf;
}
public void setWayShopCateLeaf(WayShopCateLeaf wayShopCateLeaf) {
this.wayShopCateLeaf = wayShopCateLeaf;
}
public String getShopInfo() {
return shopInfo;
}
public void setShopInfo(String shopInfo) {
this.shopInfo = shopInfo == null ? null : shopInfo.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Byte getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Integer getShopCateLeafId() {
return shopCateLeafId;
}
public void setShopCateLeafId(Integer shopCateLeafId) {
this.shopCateLeafId = shopCateLeafId;
}
public BigDecimal getShopLat() {
return shopLat;
}
public void setShopLat(BigDecimal shopLat) {
this.shopLat = shopLat;
}
public BigDecimal getShopLng() {
return shopLng;
}
public void setShopLng(BigDecimal shopLng) {
this.shopLng = shopLng;
}
public String getShopLogoUrl() {
return shopLogoUrl;
}
public void setShopLogoUrl(String shopLogoUrl) {
this.shopLogoUrl = shopLogoUrl == null ? null : shopLogoUrl.trim();
}
public String getAdCode() {
return adCode;
}
public void setAdCode(String adCode) {
this.adCode = adCode;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public WayShopFollow getFollow() {
return follow;
}
public void setFollow(WayShopFollow follow) {
this.follow = follow;
}
} |
3e0da5dcea05aa11be99364d3ece53192db7b0b2 | 233 | java | Java | src/me/koply/saniye/util/Util.java | kingOf0/saniye | 0076cfc7f4d51084c19df35aded107dd3e2f78f4 | [
"Apache-2.0"
] | null | null | null | src/me/koply/saniye/util/Util.java | kingOf0/saniye | 0076cfc7f4d51084c19df35aded107dd3e2f78f4 | [
"Apache-2.0"
] | 1 | 2022-03-11T18:45:07.000Z | 2022-03-12T13:32:26.000Z | src/me/koply/saniye/util/Util.java | kingOf0/saniye | 0076cfc7f4d51084c19df35aded107dd3e2f78f4 | [
"Apache-2.0"
] | 2 | 2022-03-11T18:26:03.000Z | 2022-03-12T08:17:22.000Z | 17.923077 | 48 | 0.549356 | 5,763 | package me.koply.saniye.util;
public class Util {
public static Integer parseInt(String str) {
try {
return Integer.parseInt(str);
} catch (Exception ex) {
return null;
}
}
} |
3e0da65fb79963a311af95cff17023111d1fd290 | 747 | java | Java | service/src/test/java/com/networknt/service/Processor.java | KalevGonvick/light-4j | 7083f925d1f15f647df939b5eec763656b680089 | [
"Apache-2.0"
] | 3,383 | 2017-05-07T07:43:27.000Z | 2022-03-26T10:11:27.000Z | service/src/test/java/com/networknt/service/Processor.java | KalevGonvick/light-4j | 7083f925d1f15f647df939b5eec763656b680089 | [
"Apache-2.0"
] | 857 | 2017-05-05T18:29:15.000Z | 2022-03-30T22:08:27.000Z | service/src/test/java/com/networknt/service/Processor.java | KalevGonvick/light-4j | 7083f925d1f15f647df939b5eec763656b680089 | [
"Apache-2.0"
] | 596 | 2017-05-08T13:43:35.000Z | 2022-03-26T10:11:11.000Z | 29.88 | 75 | 0.725569 | 5,764 | /*
* Copyright (c) 2016 Network New Technologies Inc.
*
* 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.networknt.service;
/**
* Created by steve on 2016-11-27.
*/
public interface Processor {
String process();
}
|
3e0da6c87ff1388732f85414212aab28fe4ed85c | 333 | java | Java | rut/src/main/java/io/norberg/rut/CharSequences.java | danielnorberg/rut | 6cd99e0d464da934d446b554ab5bbecaf294fcdc | [
"Apache-2.0"
] | 23 | 2015-03-09T12:23:54.000Z | 2020-12-23T20:42:24.000Z | rut/src/main/java/io/norberg/rut/CharSequences.java | danielnorberg/rut | 6cd99e0d464da934d446b554ab5bbecaf294fcdc | [
"Apache-2.0"
] | 18 | 2015-04-21T06:50:10.000Z | 2020-02-06T19:27:50.000Z | rut/src/main/java/io/norberg/rut/CharSequences.java | danielnorberg/rut | 6cd99e0d464da934d446b554ab5bbecaf294fcdc | [
"Apache-2.0"
] | 6 | 2015-03-09T12:23:56.000Z | 2019-05-27T17:32:32.000Z | 18.5 | 90 | 0.582583 | 5,765 | package io.norberg.rut;
final class CharSequences {
private CharSequences() {
throw new AssertionError();
}
static int indexOf(final CharSequence s, final char c, final int start, final int end) {
for (int i = start; i < end; i++) {
if (s.charAt(i) == c) {
return i;
}
}
return -1;
}
}
|
3e0da6e3fdd8693ada0c6b417f2c2b64b16432d4 | 4,704 | java | Java | app/src/main/java/com/example/android/miwok/PharassFragment.java | wenzhifeifeidetutu/miwok | 0fe9b75d232f12446ced9544c69cf25577648e5f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/miwok/PharassFragment.java | wenzhifeifeidetutu/miwok | 0fe9b75d232f12446ced9544c69cf25577648e5f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/miwok/PharassFragment.java | wenzhifeifeidetutu/miwok | 0fe9b75d232f12446ced9544c69cf25577648e5f | [
"Apache-2.0"
] | null | null | null | 40.205128 | 155 | 0.65625 | 5,766 | package com.example.android.miwok;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class PharassFragment extends Fragment {
private ListView pharassListView ;
private MediaPlayer mediaPlayer;
private AudioManager audioManager;
AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK||focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ) {
mediaPlayer.pause();
mediaPlayer.seekTo(0);
}else if (focusChange == AudioManager.AUDIOFOCUS_LOSS){
mediaPlayRelease();
}else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mediaPlayer.start();
}
}
};
public PharassFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_pharass, container, false);
audioManager = (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);
final ArrayList<Pharass> pharassArrayList =new ArrayList<Pharass>();
//clear this imageId is -1;
pharassArrayList.add(new Pharass("Where are you going","minto wuksus",-1, R.raw.phrase_where_are_you_going ));
//pharassArrayList.add(new Pharass("What is your name?","tinnə oyaase'nə",R.drawable.color_black ));
pharassArrayList.add(new Pharass("What is your name?","tinnə oyaase'nə",-1, R.raw.phrase_what_is_your_name ));
pharassArrayList.add(new Pharass("My name is...","oyaaset...",-1, R.raw.phrase_my_name_is ));
pharassArrayList.add(new Pharass("How are you feeling?","michəksəs?",-1, R.raw.phrase_how_are_you_feeling ));
pharassArrayList.add(new Pharass("I’m feeling good.","kuchi achit",-1, R.raw.phrase_im_feeling_good ));
pharassArrayList.add(new Pharass("Are you coming?","əənəs'aa?",-1, R.raw.phrase_are_you_coming ));
pharassArrayList.add(new Pharass("Yes, I’m coming.","həə’ əənəm",-1,R.raw.phrase_yes_im_coming ));
pharassArrayList.add(new Pharass("I’m coming.","əənəm",-1, R.raw.phrase_im_coming ));
pharassArrayList.add(new Pharass("Let’s go.","yoowutis",-1, R.raw.phrase_lets_go ));
pharassArrayList.add(new Pharass("Come here","ənni'nem", -1, R.raw.phrase_come_here ));
pharassListView = (ListView) rootView.findViewById(R.id.pharass_list);
PharassAdapter pharassAdapter =new PharassAdapter(getActivity(), pharassArrayList);
pharassListView.setAdapter(pharassAdapter);
pharassListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Pharass pharass = pharassArrayList.get(position);
mediaPlayRelease();
int result = audioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mediaPlayRelease();
mediaPlayer = MediaPlayer.create(getActivity(), pharass.getPharassVoiceId() );
mediaPlayer.start();
//如果播放完就release掉
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mediaPlayRelease();
}
});
}
}
});
return rootView;
}
public void mediaPlayRelease(){
if (mediaPlayer != null){
mediaPlayer.release();
}
mediaPlayer = null;
//这里要把adudiofocus给释放掉
audioManager.abandonAudioFocus(onAudioFocusChangeListener);
}
@Override
public void onStop(){
super.onStop();
mediaPlayRelease();
}
}
|
3e0da7a863a5827274b188151d276d65f72daf75 | 4,063 | java | Java | src/main/java/com/jonpereiradev/jfile/reader/file/ColumnValue.java | jonpereiradev/jfilereader | 2869675e0d1ffb43ac54ce227b6b07aa80721202 | [
"MIT"
] | 6 | 2019-03-29T21:34:28.000Z | 2020-09-17T05:09:41.000Z | src/main/java/com/jonpereiradev/jfile/reader/file/ColumnValue.java | jonpereiradev/jfilereader | 2869675e0d1ffb43ac54ce227b6b07aa80721202 | [
"MIT"
] | null | null | null | src/main/java/com/jonpereiradev/jfile/reader/file/ColumnValue.java | jonpereiradev/jfilereader | 2869675e0d1ffb43ac54ce227b6b07aa80721202 | [
"MIT"
] | 1 | 2020-07-07T05:54:51.000Z | 2020-07-07T05:54:51.000Z | 26.907285 | 107 | 0.749446 | 5,767 | /*
* MIT License
*
* Copyright (c) 2020 Jonathan de Almeida Pereira
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jonpereiradev.jfile.reader.file;
import com.jonpereiradev.jfile.reader.JFilePatternConfig;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.regex.Pattern;
/**
* @author jonpereiradev
* @since 0.1.0
*/
public interface ColumnValue extends Comparable<ColumnValue> {
static ColumnValue newColumnValue(JFilePatternConfig patternConfig, int columnNumber, String content) {
return new ColumnValueImpl(patternConfig, columnNumber, content);
}
int getColumnNumber();
<T> T getContent(Class<T> clazz);
String getText();
String[] getTextArray();
String[] getTextArray(Pattern splitPattern);
Character getCharacter();
Character[] getCharacterArray();
Character[] getCharacterArray(Pattern splitPattern);
Short getShort();
Short[] getShortArray();
Short[] getShortArray(Pattern splitPattern);
Integer getInt();
Integer[] getIntArray();
Integer[] getIntArray(Pattern splitPattern);
Long getLong();
Long[] getLongArray();
Long[] getLongArray(Pattern splitPattern);
Float getFloat();
Float[] getFloatArray();
Float[] getFloatArray(Pattern splitPattern);
Double getDouble();
Double[] getDoubleArray();
Double[] getDoubleArray(Pattern splitPattern);
Boolean getBoolean();
Boolean[] getBooleanArray();
Boolean[] getBooleanArray(Pattern splitPattern);
BigInteger getBigInteger();
BigInteger[] getBigIntegerArray();
BigInteger[] getBigIntegerArray(Pattern splitPattern);
BigDecimal getBigDecimal();
BigDecimal getBigDecimal(DecimalFormat bigDecimalFormatter);
BigDecimal[] getBigDecimalArray();
BigDecimal[] getBigDecimalArray(Pattern splitPattern);
BigDecimal[] getBigDecimalArray(Pattern splitPattern, DecimalFormat bigDecimalFormatter);
Date getDate();
Date getDate(DateFormat dateFormat);
Date[] getDateArray();
Date[] getDateArray(Pattern splitPattern);
Date[] getDateArray(Pattern splitPattern, DateFormat dateFormat);
LocalDate getLocalDate();
LocalDate getLocalDate(DateTimeFormatter dateTimeFormatter);
LocalDate[] getLocalDateArray();
LocalDate[] getLocalDateArray(Pattern splitPattern);
LocalDate[] getLocalDateArray(Pattern splitPattern, DateTimeFormatter dateTimeFormatter);
LocalDateTime getLocalDateTime();
LocalDateTime getLocalDateTime(DateTimeFormatter dateTimeFormatter);
LocalDateTime[] getLocalDateTimeArray();
LocalDateTime[] getLocalDateTimeArray(Pattern splitPattern);
LocalDateTime[] getLocalDateTimeArray(Pattern splitPattern, DateTimeFormatter dateTimeFormatter);
JFilePatternConfig getPatternConfig();
}
|
3e0da84e99eebf882f184dbc8b7ed5d3731484c7 | 3,826 | java | Java | src/main/java/org/azkfw/log/StdoutLogger.java | azuki-framework/azuki-base | 1e48d6432c34a3989c5b666b6c3cf525bec63ce7 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/azkfw/log/StdoutLogger.java | azuki-framework/azuki-base | 1e48d6432c34a3989c5b666b6c3cf525bec63ce7 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/azkfw/log/StdoutLogger.java | azuki-framework/azuki-base | 1e48d6432c34a3989c5b666b6c3cf525bec63ce7 | [
"Apache-2.0"
] | null | null | null | 21.988506 | 118 | 0.702823 | 5,768 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.azkfw.log;
import java.util.Calendar;
import java.util.Date;
/**
* このクラスは、標準出力を行うロガークラスです。
*
* @since 1.0.0
* @version 1.0.0 2013/01/04
* @author Kawakicchi
*/
public final class StdoutLogger extends AbstractLogger {
/**
* Debug
*/
private static String LEVEL_DEBUG = "DEBUG";
/**
* Information
*/
private static String LEVEL_INFO = "INFO";
/**
* Warning
*/
private static String LEVEL_WARN = "WARN";
/**
* Error
*/
private static String LEVEL_ERROR = "ERROR";
/**
* Fatal
*/
private static String LEVEL_FATAL = "FATAL";
/**
* 名前
*/
private String name;
/**
* コンストラクタ
*
* @param aName 名前
*/
public StdoutLogger(final String aName) {
name = aName;
}
/**
* コンストラクタ
*
* @param aClass クラス
*/
public StdoutLogger(final Class<?> aClass) {
name = aClass.getName();
}
@Override
public void debug(final String message) {
log(LEVEL_DEBUG, message);
}
@Override
public void debug(final Throwable throwable) {
log(LEVEL_DEBUG, throwable.toString());
}
@Override
public void debug(final String message, final Throwable throwable) {
log(LEVEL_DEBUG, message);
log(LEVEL_DEBUG, throwable.toString());
}
@Override
public void info(final String message) {
log(LEVEL_INFO, message);
}
@Override
public void info(final Throwable throwable) {
log(LEVEL_INFO, throwable.toString());
}
@Override
public void info(final String message, final Throwable throwable) {
log(LEVEL_INFO, message);
log(LEVEL_INFO, throwable.toString());
}
@Override
public void warn(final String message) {
log(LEVEL_WARN, message);
}
@Override
public void warn(final Throwable throwable) {
log(LEVEL_WARN, throwable.toString());
}
@Override
public void warn(final String message, final Throwable throwable) {
log(LEVEL_WARN, message);
log(LEVEL_WARN, throwable.toString());
}
@Override
public void error(final String message) {
log(LEVEL_ERROR, message);
}
@Override
public void error(final Throwable throwable) {
log(LEVEL_ERROR, throwable.toString());
}
@Override
public void error(final String message, final Throwable throwable) {
log(LEVEL_ERROR, message);
log(LEVEL_ERROR, throwable.toString());
}
@Override
public void fatal(final String message) {
log(LEVEL_FATAL, message);
}
@Override
public void fatal(final Throwable throwable) {
log(LEVEL_FATAL, throwable.toString());
}
@Override
public void fatal(final String message, final Throwable throwable) {
log(LEVEL_FATAL, message);
log(LEVEL_FATAL, throwable.toString());
}
/**
* ログを出力する。
*
* @param level レベル
* @param message メッセージ
*/
private void log(final String level, final String message) {
Calendar cln = Calendar.getInstance();
cln.setTime(new Date());
String msg = String.format("%02d:%02d:%02d.%03d %5s %s %s", cln.get(Calendar.HOUR_OF_DAY), cln.get(Calendar.MINUTE),
cln.get(Calendar.SECOND), cln.get(Calendar.MILLISECOND), level, name, message);
System.out.println(msg);
}
}
|
3e0da87ff75dbbd3b75c0c75bc983cf1f72657aa | 3,633 | java | Java | app/src/main/java/org/tensorflow/demo/Introduccion/tutorial_primer_uso.java | Jairo22Enrique/ultima_version_hw_agosto_17 | ccfd9914fd7ec67cefa68e8dbfd8cd74d7eea5f0 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/tensorflow/demo/Introduccion/tutorial_primer_uso.java | Jairo22Enrique/ultima_version_hw_agosto_17 | ccfd9914fd7ec67cefa68e8dbfd8cd74d7eea5f0 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/tensorflow/demo/Introduccion/tutorial_primer_uso.java | Jairo22Enrique/ultima_version_hw_agosto_17 | ccfd9914fd7ec67cefa68e8dbfd8cd74d7eea5f0 | [
"Apache-2.0"
] | null | null | null | 41.758621 | 120 | 0.636939 | 5,769 | package org.tensorflow.demo.Introduccion;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import org.tensorflow.demo.Datos_Usuario;
import org.tensorflow.demo.Inicio_Comunicativo;
import org.tensorflow.demo.R;
import static org.tensorflow.demo.Clases.VariablesYDatos.Num_apartado;
import static org.tensorflow.demo.Clases.VariablesYDatos.Num_columna;
import static org.tensorflow.demo.Clases.VariablesYDatos.Tutorial_Primer_uso;
public class tutorial_primer_uso extends AppCompatActivity {
TextView txtTitulo,txtSubTitulo;
TextView txtDescripcion;
Button btnSiguiente;
VideoView vv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bienvenida_auditivo_1);
txtDescripcion=findViewById(R.id.txtDescripcion_);
txtTitulo=findViewById(R.id.txtTitulo_);
vv=findViewById(R.id.video_tuto);
txtSubTitulo=findViewById(R.id.txtSubTitulo_);
btnSiguiente=findViewById(R.id.btn_tuto_sig);
btnSiguiente.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(Num_columna==(Tutorial_Primer_uso[1].length-1)){
try {
Datos_Usuario conex_primera = new Datos_Usuario(getApplicationContext(), "DBUsuarios", null, 3);
SQLiteDatabase db_pri = conex_primera.getReadableDatabase();
db_pri.execSQL("UPDATE Primeravezen SET Auditivo='1' WHERE Auditivo='0'");
db_pri.execSQL("UPDATE Primeravezen SET Comunicativo='1' WHERE Comunicativo ='0'");
}catch (Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
startActivity(new Intent(getApplication(), Inicio_Comunicativo.class));
}else {
Num_columna++;
if(Num_columna==2||Num_columna==4||Num_columna==6){
Num_apartado++;
}
startActivity(new Intent(getApplication(), tutorial_primer_uso.class));
}
}
});
settearDatos();
}
private void settearDatos() {
btnSiguiente.setText("Siguiente "+(Num_columna+1)+"/9");
txtTitulo.setText( Tutorial_Primer_uso [0] [Num_apartado]+"");
txtSubTitulo.setText( Tutorial_Primer_uso [1] [Num_columna]+"");
txtDescripcion.setText( Tutorial_Primer_uso [2] [Num_columna]+"");
// gf.setImageResource(Integer.parseInt(Tutorial_Primer_uso [3] [Num_columna]+""));
SettearVideo();
}
void SettearVideo(){
try {
String path = "android.resource://org.tensorflow.tensorflowdemo/" +
Integer.parseInt(Tutorial_Primer_uso [3] [Num_columna]+"");
Uri uri = Uri.parse(path);
vv.setVideoURI(uri);
vv.setMediaController(new MediaController(this));
vv.start();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
|
3e0da8f23cad4bff666e873752b62d48cb9d5c7c | 309 | java | Java | Accedo/app/src/main/java/com/freakybyte/accedo/controller/score/constructors/ScoreView.java | xkokushox/AccedoTest | 30074ac95a8897c30c2ae7e07190ac492b663425 | [
"Apache-2.0"
] | null | null | null | Accedo/app/src/main/java/com/freakybyte/accedo/controller/score/constructors/ScoreView.java | xkokushox/AccedoTest | 30074ac95a8897c30c2ae7e07190ac492b663425 | [
"Apache-2.0"
] | null | null | null | Accedo/app/src/main/java/com/freakybyte/accedo/controller/score/constructors/ScoreView.java | xkokushox/AccedoTest | 30074ac95a8897c30c2ae7e07190ac492b663425 | [
"Apache-2.0"
] | null | null | null | 18.176471 | 60 | 0.754045 | 5,770 | package com.freakybyte.accedo.controller.score.constructors;
import com.freakybyte.accedo.model.ScoreModel;
import java.util.List;
/**
* Created by Jose Torres in FreakyByte on 26/06/16.
*/
public interface ScoreView {
void setItemsToAdapter(List<ScoreModel> scores);
void refreshAdapter();
}
|
3e0da9597d20a8f072c7553338381f513c91743c | 1,533 | java | Java | core/src/main/java/org/atomnuke/atom/xml/AtomNamespaceContext.java | zinic/atom-nuke | e586b07809692d5a8d10b4e908423b3aa2c504e2 | [
"Apache-2.0"
] | 1 | 2017-10-28T19:06:55.000Z | 2017-10-28T19:06:55.000Z | core/src/main/java/org/atomnuke/atom/xml/AtomNamespaceContext.java | zinic/atom-nuke | e586b07809692d5a8d10b4e908423b3aa2c504e2 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/org/atomnuke/atom/xml/AtomNamespaceContext.java | zinic/atom-nuke | e586b07809692d5a8d10b4e908423b3aa2c504e2 | [
"Apache-2.0"
] | null | null | null | 27.872727 | 85 | 0.733855 | 5,771 | package org.atomnuke.atom.xml;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
/**
*
* @author zinic
*/
public final class AtomNamespaceContext implements NamespaceContext {
public static final String XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
public static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
public static final String XML_PREFIX = "xml";
public static final String ATOM_PREFIX = "atom";
private static final AtomNamespaceContext INSTANCE = new AtomNamespaceContext();
public static NamespaceContext instance() {
return INSTANCE;
}
private final Map<String, String> uriToPrefixMap;
private final Map<String, String> prefixToUriMap;
private AtomNamespaceContext() {
uriToPrefixMap = new HashMap<String, String>();
prefixToUriMap = new HashMap<String, String>();
uriToPrefixMap.put(ATOM_NAMESPACE, ATOM_PREFIX);
prefixToUriMap.put(ATOM_PREFIX, ATOM_NAMESPACE);
uriToPrefixMap.put(XML_NAMESPACE, XML_PREFIX);
prefixToUriMap.put(XML_PREFIX, XML_NAMESPACE);
}
@Override
public String getNamespaceURI(String prefix) {
return prefixToUriMap.get(prefix);
}
@Override
public String getPrefix(String namespaceURI) {
return uriToPrefixMap.get(namespaceURI);
}
@Override
public Iterator getPrefixes(String namespaceURI) {
return Collections.EMPTY_LIST.iterator();
}
}
|
3e0daa2537f88f958b8bf80ab3f0fae8d0e19763 | 21,231 | java | Java | app/src/main/java/com/dhaval/note/MainActivity.java | dhvl5/note-taking-app | 46bd6d62a90d69cf70a3f9ed17ff6ee6a30c85d6 | [
"MIT"
] | null | null | null | app/src/main/java/com/dhaval/note/MainActivity.java | dhvl5/note-taking-app | 46bd6d62a90d69cf70a3f9ed17ff6ee6a30c85d6 | [
"MIT"
] | null | null | null | app/src/main/java/com/dhaval/note/MainActivity.java | dhvl5/note-taking-app | 46bd6d62a90d69cf70a3f9ed17ff6ee6a30c85d6 | [
"MIT"
] | null | null | null | 42.125 | 146 | 0.63737 | 5,772 | package com.dhaval.note;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.util.Pair;
import androidx.core.view.ViewCompat;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.transition.Fade;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
static long backPressed;
EditText titleEditText, descEditText, searchEditText;
FloatingActionButton floatingActionButton;
RelativeLayout bottomSheet;
BottomSheetBehavior bottomSheetBehavior;
MaterialButton createNoteBtn;
RecyclerView recyclerView;
NoteAdapter noteAdapter;
ArrayList<Note> noteList;
ArrayList<Note> filteredList;
ImageButton searchImageButton, searchCloseImageButton, themeModeImageButton;
MaterialToolbar searchToolbar;
View dimBackgroundView;
LottieAnimationView lottieAnimationView;
@Override
public void recreate() {
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
startActivity(getIntent());
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
String themeName = pref.getString("themeList", "Auto");
if (themeName.equals("Dark"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
else if (themeName.equals("Light"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
else
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fade fade = new Fade();
View decor = getWindow().getDecorView();
fade.excludeTarget(decor.findViewById(R.id.action_bar_container),true);
fade.excludeTarget(android.R.id.statusBarBackground,true);
fade.excludeTarget(android.R.id.navigationBarBackground,true);
getWindow().setEnterTransition(fade);
getWindow().setExitTransition(fade);
final InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
assert inputMethodManager != null;
dimBackgroundView = findViewById(R.id.dimBackground);
recyclerView = findViewById(R.id.rv);
lottieAnimationView = findViewById(R.id.lottie);
bottomSheet = findViewById(R.id.bottom_sheet);
createNoteBtn = findViewById(R.id.createNoteBtn);
titleEditText = findViewById(R.id.titleNoteEditText);
descEditText = findViewById(R.id.descNoteEditText);
floatingActionButton = findViewById(R.id.floating_btn);
searchImageButton = findViewById(R.id.searchImageButton);
searchCloseImageButton = findViewById(R.id.searchCloseImageButton);
searchToolbar = findViewById(R.id.searchToolbar);
searchEditText = findViewById(R.id.searchEditText);
themeModeImageButton = findViewById(R.id.themeModeImageButton);
dimBackgroundView.setVisibility(View.GONE);
searchToolbar.setVisibility(View.INVISIBLE);
noteList = new ArrayList<>();
filteredList = new ArrayList<>();
noteAdapter = new NoteAdapter(noteList);
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
/*StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, RecyclerView.VERTICAL);
staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(noteAdapter);*/
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(noteAdapter);
floatingActionButton.setImageResource(R.drawable.ic_add_black);
if(inputMethodManager.hideSoftInputFromWindow(titleEditText.getWindowToken(), 0))
titleEditText.clearFocus();
if(inputMethodManager.hideSoftInputFromWindow(descEditText.getWindowToken(), 0))
descEditText.clearFocus();
ClearFocus(titleEditText, inputMethodManager);
ClearFocus(descEditText, inputMethodManager);
themeModeImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
});
//region floatingActionButton click listener
floatingActionButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(noteAdapter.getSelected().size() > 0)
{
for(Note n : noteAdapter.getSelected())
{
noteList.remove(n);
noteAdapter.notifyItemRemoved(noteList.size());
noteAdapter.notifyDataSetChanged();
}
floatingActionButton.setRippleColor(ColorStateList.valueOf(Color.BLACK));
floatingActionButton.setBackgroundTintList(getColorStateList(R.color.colorAccent));
floatingActionButton.setImageResource(R.drawable.ic_add_black);
floatingActionButton.setColorFilter(Color.TRANSPARENT, PorterDuff.Mode.LIGHTEN);
if(noteAdapter.getSelected().size() == noteList.size())
RevealAnimation(lottieAnimationView, 1000);
return;
}
HideAnimation(floatingActionButton, 500);
dimBackgroundView.setVisibility(View.VISIBLE);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(dimBackgroundView, "Alpha", .7f);
objectAnimator.setDuration(500);
objectAnimator.start();
objectAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
});
}
});
//endregion
//region createNoteBtn click listener
createNoteBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(titleEditText.getText().toString().matches("") && descEditText.getText().toString().matches(""))
{
ShowToast("Empty note discarded!");
inputMethodManager.hideSoftInputFromWindow(titleEditText.getWindowToken(), 0);
titleEditText.clearFocus();
titleEditText.getText().clear();
inputMethodManager.hideSoftInputFromWindow(descEditText.getWindowToken(), 0);
descEditText.clearFocus();
descEditText.getText().clear();
}
else
{
Note a = new Note(titleEditText.getText().toString(), descEditText.getText().toString());
noteList.add(a);
noteAdapter.notifyDataSetChanged();
HideAnimation(lottieAnimationView, 1000);
inputMethodManager.hideSoftInputFromWindow(titleEditText.getWindowToken(), 0);
titleEditText.clearFocus();
titleEditText.getText().clear();
inputMethodManager.hideSoftInputFromWindow(descEditText.getWindowToken(), 0);
descEditText.clearFocus();
descEditText.getText().clear();
}
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
RevealAnimation(floatingActionButton, 500);
}
});
//endregion
//region noteAdapter single click listener
noteAdapter.setOnItemClickListener(new NoteAdapter.OnItemClickListener()
{
@Override
public void OnItemClick(int position, View view, View v, NoteAdapter.MyViewHolder holder)
{
if(noteAdapter.getSelected().size() > 0)
{
noteList.get(position).setChecked(!noteList.get(position).isChecked());
if(noteList.get(position).isChecked())
{
holder.noteCard.setCardBackgroundColor(R.attr.textColor);
holder.noteCard.setBackgroundTintList(ColorStateList.valueOf(R.attr.textColor));
holder.noteCard.setStrokeWidth(15);
}
else
{
holder.noteCard.setCardBackgroundColor(Color.TRANSPARENT);
holder.noteCard.setBackgroundTintList(ColorStateList.valueOf(Color.TRANSPARENT));
holder.noteCard.setStrokeWidth(5);
}
if(noteAdapter.getSelected().size() == 0)
{
floatingActionButton.setRippleColor(ColorStateList.valueOf(Color.BLACK));
floatingActionButton.setBackgroundTintList(getColorStateList(R.color.colorAccent));
floatingActionButton.setImageResource(R.drawable.ic_add_black);
floatingActionButton.setColorFilter(Color.TRANSPARENT, PorterDuff.Mode.LIGHTEN);
}
return;
}
Intent intent = new Intent(getApplicationContext(), EditNote.class);
intent.putExtra("edit_note", noteList.get(position).getNote());
intent.putExtra("edit_title", noteList.get(position).getNoteTitle());
Pair<View, String> pair1 = new Pair<>(view, ViewCompat.getTransitionName(view));
Pair<View, String> pair2 = new Pair<>(v, ViewCompat.getTransitionName(v));
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, pair1, pair2);
startActivity(intent, options.toBundle());
}
});
//endregion
//region noteAdapter long click listener
noteAdapter.setOnItemLongClickListener(new NoteAdapter.OnItemLongClickListener()
{
@Override
public void OnLongClick(int position, NoteAdapter.MyViewHolder holder)
{
floatingActionButton.setRippleColor(ColorStateList.valueOf(Color.TRANSPARENT));
floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(Color.RED));
floatingActionButton.setImageResource(R.drawable.ic_delete_white);
floatingActionButton.setColorFilter(Color.RED, PorterDuff.Mode.LIGHTEN);
noteList.get(position).setChecked(!noteList.get(position).isChecked());
if(noteList.get(position).isChecked())
{
holder.noteCard.setCardBackgroundColor(R.attr.textColor);
holder.noteCard.setBackgroundTintList(ColorStateList.valueOf(R.attr.textColor));
holder.noteCard.setStrokeWidth(15);
}
else
{
holder.noteCard.setCardBackgroundColor(Color.TRANSPARENT);
holder.noteCard.setBackgroundTintList(ColorStateList.valueOf(Color.TRANSPARENT));
holder.noteCard.setStrokeWidth(5);
}
if(noteAdapter.getSelected().size() == 0)
{
floatingActionButton.setRippleColor(ColorStateList.valueOf(Color.BLACK));
floatingActionButton.setBackgroundTintList(getColorStateList(R.color.colorAccent));
floatingActionButton.setImageResource(R.drawable.ic_add_black);
floatingActionButton.setColorFilter(Color.TRANSPARENT, PorterDuff.Mode.LIGHTEN);
}
}
});
//endregion
//region dimBackgroundView click listener
dimBackgroundView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
inputMethodManager.hideSoftInputFromWindow(titleEditText.getWindowToken(), 0);
titleEditText.clearFocus();
inputMethodManager.hideSoftInputFromWindow(descEditText.getWindowToken(), 0);
descEditText.clearFocus();
}
});
//endregion
//region bottomSheetBehavior callback
bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback()
{
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState)
{
if(newState == BottomSheetBehavior.STATE_HIDDEN)
{
if(floatingActionButton.getVisibility() != View.VISIBLE)
RevealAnimation(floatingActionButton, 500);
dimBackgroundView.setVisibility(View.GONE);
dimBackgroundView.setAlpha(0);
ClearFocus(titleEditText, inputMethodManager);
ClearFocus(descEditText, inputMethodManager);
}
else if( newState == BottomSheetBehavior.STATE_DRAGGING)
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset)
{
}
});
//endregion
//region searchImageButton click listener
searchImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SearchBarReveal(searchToolbar, 300, .3f, true, true);
HideAnimation(floatingActionButton, 500);
searchEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT);
}
});
//endregion
//region searchCloseImageButton click listener
searchCloseImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RevealAnimation(floatingActionButton, 500);
SearchBarReveal(searchToolbar, 300, .3f, true, false);
ClearFocus(searchEditText, inputMethodManager);
searchEditText.getText().clear();
}
});
//endregion
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override
public void afterTextChanged(Editable s) {
noteAdapter.getFilter().filter(s);
}
});
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void SearchBarReveal(final View view, long duration, float posFromRight, boolean containsOverflow, final boolean isShow)
{
int width = view.getWidth();
if(posFromRight > 0)
width -= (posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)) -
(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material) / 2);
if(containsOverflow)
width -= getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int centerX = width;
int centerY = view.getHeight() / 2;
Animator animator;
if(isShow)
animator = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, 0, (float) width);
else
animator = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, (float) width, 0);
animator.setDuration(duration);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
view.setVisibility(View.INVISIBLE);
}
}
});
if(isShow)
view.setVisibility(View.VISIBLE);
animator.start();
}
private void RevealAnimation(View view, long duration)
{
int centerX = view.getWidth() / 2;
int centerY = view.getHeight() / 2;
float radius = (float) Math.hypot(centerX, centerY);
Animator animator = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, 0, radius);
animator.setDuration(duration);
view.setVisibility(View.VISIBLE);
animator.start();
}
private void HideAnimation(final View view, long duration)
{
int centerX = view.getWidth() / 2;
int centerY = view.getHeight() / 2;
float radius = (float) Math.hypot(centerX, centerY);
Animator animator = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, radius, 0);
animator.setDuration(duration);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
view.setVisibility(View.INVISIBLE);
}
});
animator.start();
}
private void ClearFocus(final EditText editText, final InputMethodManager inputMethodManager)
{
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
editText.clearFocus();
}
}
});
}
private void ShowToast(String msg)
{
Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
View view = toast.getView();
view.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN);
TextView text = view.findViewById(android.R.id.message);
text.setTextColor(Color.WHITE);
toast.show();
}
@Override
public void onBackPressed()
{
if(bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED)
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
else if(bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN)
{
if(backPressed + 2000 > System.currentTimeMillis())
super.onBackPressed();
else
{
ShowToast("Press again to exit!!!");
backPressed = System.currentTimeMillis();
}
}
}
} |
3e0daaa092d941a4b25923730366aa096344f8a6 | 2,533 | java | Java | platform/testFramework/src/com/intellij/testFramework/TestLogger.java | erdi/intellij-community | dda25a8a4e6375c6d964cb0197e5c387d585ea9e | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | platform/testFramework/src/com/intellij/testFramework/TestLogger.java | tnorbye/intellij-community | f01cf262fc196bf4dbb99e20cd937dee3705a7b6 | [
"Apache-2.0"
] | null | null | null | platform/testFramework/src/com/intellij/testFramework/TestLogger.java | tnorbye/intellij-community | f01cf262fc196bf4dbb99e20cd937dee3705a7b6 | [
"Apache-2.0"
] | 1 | 2019-07-18T16:50:52.000Z | 2019-07-18T16:50:52.000Z | 29.114943 | 88 | 0.716936 | 5,773 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.testFramework;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.diagnostic.Log4jBasedLogger;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TestLogger extends Log4jBasedLogger {
TestLogger(@NotNull Logger logger) {
super(logger);
}
@Override
public void warn(String message, @Nullable Throwable t) {
t = checkException(t);
LoggedErrorProcessor.getInstance().processWarn(message, t, myLogger);
}
@Override
public void error(String message, @Nullable Throwable t, @NotNull String... details) {
t = checkException(t);
LoggedErrorProcessor.getInstance().processError(message, t, details, myLogger);
}
@Override
public void debug(@NonNls String message) {
if (isDebugEnabled()) {
super.debug(message);
TestLoggerFactory.log(myLogger, Level.DEBUG, message, null);
}
}
@Override
public void debug(@Nullable Throwable t) {
if (isDebugEnabled()) {
super.debug(t);
TestLoggerFactory.log(myLogger, Level.DEBUG, null, t);
}
}
@Override
public void debug(@NonNls String message, @Nullable Throwable t) {
if (isDebugEnabled()) {
super.debug(message, t);
TestLoggerFactory.log(myLogger, Level.DEBUG, message, t);
}
}
@Override
public void info(@NonNls String message) {
super.info(message);
TestLoggerFactory.log(myLogger, Level.INFO, message, null);
}
@Override
public void info(@NonNls String message, @Nullable Throwable t) {
super.info(message, t);
TestLoggerFactory.log(myLogger, Level.INFO, message, t);
}
@Override
public boolean isDebugEnabled() {
if (ApplicationInfoImpl.isInStressTest()) {
return super.isDebugEnabled();
}
return true;
}
}
|
3e0daaa8b049bf0facdb7e90b4395577359c9195 | 5,107 | java | Java | aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/DestinationSchema.java | pgoranss/aws-sdk-java | 041ffc4197309c98c4be534b43ca2bda146e4f7c | [
"Apache-2.0"
] | 1 | 2019-04-21T21:56:44.000Z | 2019-04-21T21:56:44.000Z | aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/DestinationSchema.java | pgoranss/aws-sdk-java | 041ffc4197309c98c4be534b43ca2bda146e4f7c | [
"Apache-2.0"
] | 110 | 2019-11-11T19:37:58.000Z | 2021-07-16T18:23:58.000Z | aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/DestinationSchema.java | pgoranss/aws-sdk-java | 041ffc4197309c98c4be534b43ca2bda146e4f7c | [
"Apache-2.0"
] | 1 | 2019-07-22T16:24:05.000Z | 2019-07-22T16:24:05.000Z | 32.528662 | 143 | 0.656941 | 5,774 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.kinesisanalyticsv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes the data format when records are written to the destination in an SQL-based Amazon Kinesis Data Analytics
* application.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/DestinationSchema"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DestinationSchema implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Specifies the format of the records on the output stream.
* </p>
*/
private String recordFormatType;
/**
* <p>
* Specifies the format of the records on the output stream.
* </p>
*
* @param recordFormatType
* Specifies the format of the records on the output stream.
* @see RecordFormatType
*/
public void setRecordFormatType(String recordFormatType) {
this.recordFormatType = recordFormatType;
}
/**
* <p>
* Specifies the format of the records on the output stream.
* </p>
*
* @return Specifies the format of the records on the output stream.
* @see RecordFormatType
*/
public String getRecordFormatType() {
return this.recordFormatType;
}
/**
* <p>
* Specifies the format of the records on the output stream.
* </p>
*
* @param recordFormatType
* Specifies the format of the records on the output stream.
* @return Returns a reference to this object so that method calls can be chained together.
* @see RecordFormatType
*/
public DestinationSchema withRecordFormatType(String recordFormatType) {
setRecordFormatType(recordFormatType);
return this;
}
/**
* <p>
* Specifies the format of the records on the output stream.
* </p>
*
* @param recordFormatType
* Specifies the format of the records on the output stream.
* @return Returns a reference to this object so that method calls can be chained together.
* @see RecordFormatType
*/
public DestinationSchema withRecordFormatType(RecordFormatType recordFormatType) {
this.recordFormatType = recordFormatType.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRecordFormatType() != null)
sb.append("RecordFormatType: ").append(getRecordFormatType());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DestinationSchema == false)
return false;
DestinationSchema other = (DestinationSchema) obj;
if (other.getRecordFormatType() == null ^ this.getRecordFormatType() == null)
return false;
if (other.getRecordFormatType() != null && other.getRecordFormatType().equals(this.getRecordFormatType()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRecordFormatType() == null) ? 0 : getRecordFormatType().hashCode());
return hashCode;
}
@Override
public DestinationSchema clone() {
try {
return (DestinationSchema) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.kinesisanalyticsv2.model.transform.DestinationSchemaMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
3e0dabbedf8d0e1cedc9f70aaa4058701ef409be | 2,751 | java | Java | src/main/java/xf/xfvrp/report/ErrorSummary.java | hschneid/xfvrp | 496b8eec6ebb753ffb457f7e3daad43b02467253 | [
"MIT"
] | 6 | 2016-08-28T19:07:29.000Z | 2021-11-10T05:30:48.000Z | src/main/java/xf/xfvrp/report/ErrorSummary.java | hschneid/xfvrp | 496b8eec6ebb753ffb457f7e3daad43b02467253 | [
"MIT"
] | 27 | 2017-12-10T20:35:59.000Z | 2021-11-26T21:40:59.000Z | src/main/java/xf/xfvrp/report/ErrorSummary.java | hschneid/xfvrp | 496b8eec6ebb753ffb457f7e3daad43b02467253 | [
"MIT"
] | 1 | 2021-05-19T14:55:55.000Z | 2021-05-19T14:55:55.000Z | 27.51 | 86 | 0.703017 | 5,775 | package xf.xfvrp.report;
import xf.xfvrp.base.InvalidReason;
import xf.xfvrp.base.Node;
import xf.xfvrp.opt.Solution;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Copyright (c) 2012-2021 Holger Schneider
* All rights reserved.
*
* This source code is licensed under the MIT License (MIT) found in the
* LICENSE file in the root directory of this source tree.
*
*
* This summary lists all errors in the route plan. Invalid nodes
* are in the route plan on individual routes with an invalid vehicle type.
*
* Each invalid node has an reason, which is detected in the XFVRP init method. So
* for each invalid node with an invalid description, this is listed in the error
* descriptions. In the statistics for each invalid reason the number of invalid nodes
* is counted.
*
* @author hschneid
*
*/
public class ErrorSummary {
private final List<String> errorDescriptions = new ArrayList<>();
private final Map<String, Integer> statistics = new HashMap<>();
/**
* Adds the errors in an evaluated giant route. Evaluated route means,
* that the route is build up by the init routine in the XFVRPInit class.
*/
public void add(Solution solution) {
for (Node[] route : solution) {
for (Node node : route) {
if (node != null && node.getInvalidReason() != InvalidReason.NONE) {
// Description
if (node.getInvalidArguments().length() > 0)
errorDescriptions.add(node.getInvalidArguments());
// Statistics
String invalidReason = node.getInvalidReason().toString();
if (!statistics.containsKey(invalidReason))
statistics.put(invalidReason, 0);
statistics.put(
invalidReason,
statistics.get(invalidReason) + 1
);
}
}
}
}
/**
* If multiple reports are joined, the ErrorSummary objects must be joined too.
*
* This is done in this method. The given ErrorSummary will be added to this object.
*
* @param errors ErrorSummary of foreign Report
*/
public void importErrors(ErrorSummary errors) {
errorDescriptions.addAll(errors.getErrorDescriptions());
for (String invalidReason : errors.getStatistics().keySet()) {
if(!statistics.containsKey(invalidReason))
statistics.put(invalidReason, 0);
statistics.put(
invalidReason,
statistics.get(invalidReason) + errors.getStatistics().get(invalidReason)
);
}
}
/**
*
* @return Counted invalid customers for each invalid reason
*/
public Map<String, Integer> getStatistics() {
return statistics;
}
/**
*
* @return List of error descriptions, if the invalid reason allows a description.
*/
public List<String> getErrorDescriptions() {
return errorDescriptions;
}
}
|
3e0dac243ffa9dc759d8be6a28be87179a251ed8 | 1,155 | java | Java | MAS/src/logic/agents/recommenderAgent/RecommenderAgent.java | FRYoussef/multi-agent-store | 78c8f270f8ae1fd5e7b92ff35e24045c3c6c8560 | [
"MIT"
] | null | null | null | MAS/src/logic/agents/recommenderAgent/RecommenderAgent.java | FRYoussef/multi-agent-store | 78c8f270f8ae1fd5e7b92ff35e24045c3c6c8560 | [
"MIT"
] | 1 | 2021-04-30T21:15:23.000Z | 2021-04-30T21:15:23.000Z | MAS/src/logic/agents/recommenderAgent/RecommenderAgent.java | FRYoussef/multi-agent-store | 78c8f270f8ae1fd5e7b92ff35e24045c3c6c8560 | [
"MIT"
] | null | null | null | 27.5 | 77 | 0.625108 | 5,776 | package logic.agents.recommenderAgent;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.domain.FIPAException;
public class RecommenderAgent extends Agent {
public static final String NAME = "RecommenderAgent";
@Override
protected void setup() {
System.out.println(NAME + "(" + getAID().getName() + ") is running");
DFAgentDescription dfd = new DFAgentDescription();
ServiceDescription sd = new ServiceDescription();
sd.setType(NAME);
sd.setName(getName());
sd.setOwnership("UCM");
dfd.setName(getAID());
dfd.addServices(sd);
try {
DFService.register(this, dfd);
addBehaviour(new RecommenderBehaviour(this));
} catch (FIPAException e) {
doDelete();
}
}
@Override
protected void takeDown() {
try {
DFService.deregister(this);
}
catch (FIPAException fe) {
fe.printStackTrace();
}
super.takeDown();
}
}
|
3e0dac97530e1d07e92e3833ac91536de9bc9a9a | 1,768 | java | Java | android/app/src/main/java/com/sugardaddy/citascasualesconocergentenuevacercadeti/modules/autoimageslider/IndicatorView/draw/drawer/type/DropDrawer.java | yanaderevianko726/Dating-App-Android | 5a09f72b0e5e70a7245564703d42adade12917b3 | [
"ADSL"
] | 3 | 2021-04-14T10:09:31.000Z | 2021-08-03T14:16:48.000Z | android/app/src/main/java/com/sugardaddy/citascasualesconocergentenuevacercadeti/modules/autoimageslider/IndicatorView/draw/drawer/type/DropDrawer.java | borysHozh77/SugarDaddy | 5a09f72b0e5e70a7245564703d42adade12917b3 | [
"ADSL"
] | 1 | 2022-03-28T13:06:53.000Z | 2022-03-28T14:34:14.000Z | android/app/src/main/java/com/sugardaddy/citascasualesconocergentenuevacercadeti/modules/autoimageslider/IndicatorView/draw/drawer/type/DropDrawer.java | borysHozh77/SugarDaddy | 5a09f72b0e5e70a7245564703d42adade12917b3 | [
"ADSL"
] | 3 | 2021-04-18T09:16:23.000Z | 2021-08-03T14:16:50.000Z | 41.116279 | 139 | 0.733597 | 5,777 | package com.sugardaddy.citascasualesconocergentenuevacercadeti.modules.autoimageslider.IndicatorView.draw.drawer.type;
import android.graphics.Canvas;
import android.graphics.Paint;
import androidx.annotation.NonNull;
import com.sugardaddy.citascasualesconocergentenuevacercadeti.modules.autoimageslider.IndicatorView.animation.data.Value;
import com.sugardaddy.citascasualesconocergentenuevacercadeti.modules.autoimageslider.IndicatorView.animation.data.type.DropAnimationValue;
import com.sugardaddy.citascasualesconocergentenuevacercadeti.modules.autoimageslider.IndicatorView.draw.data.Indicator;
import com.sugardaddy.citascasualesconocergentenuevacercadeti.modules.autoimageslider.IndicatorView.draw.data.Orientation;
public class DropDrawer extends BaseDrawer {
public DropDrawer(@NonNull Paint paint, @NonNull Indicator indicator) {
super(paint, indicator);
}
public void draw(
@NonNull Canvas canvas,
@NonNull Value value,
int coordinateX,
int coordinateY) {
if (!(value instanceof DropAnimationValue)) {
return;
}
DropAnimationValue v = (DropAnimationValue) value;
int unselectedColor = indicator.getUnselectedColor();
int selectedColor = indicator.getSelectedColor();
float radius = indicator.getRadius();
paint.setColor(unselectedColor);
canvas.drawCircle(coordinateX, coordinateY, radius, paint);
paint.setColor(selectedColor);
if (indicator.getOrientation() == Orientation.HORIZONTAL) {
canvas.drawCircle(v.getWidth(), v.getHeight(), v.getRadius(), paint);
} else {
canvas.drawCircle(v.getHeight(), v.getWidth(), v.getRadius(), paint);
}
}
}
|
3e0daca1a6cb506a05f86d4cdba6196357231869 | 13,030 | java | Java | examples/src/main/java/boofcv/examples/stereo/ExampleStereoTwoViewsOneCamera.java | waicool20/BoofCV | 2869761da4cfccf33aa5409e35e26817992c2d42 | [
"Apache-2.0"
] | null | null | null | examples/src/main/java/boofcv/examples/stereo/ExampleStereoTwoViewsOneCamera.java | waicool20/BoofCV | 2869761da4cfccf33aa5409e35e26817992c2d42 | [
"Apache-2.0"
] | null | null | null | examples/src/main/java/boofcv/examples/stereo/ExampleStereoTwoViewsOneCamera.java | waicool20/BoofCV | 2869761da4cfccf33aa5409e35e26817992c2d42 | [
"Apache-2.0"
] | null | null | null | 41.234177 | 136 | 0.781274 | 5,778 | /*
* Copyright (c) 2011-2019, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.examples.stereo;
import boofcv.abst.feature.disparity.StereoDisparity;
import boofcv.alg.distort.ImageDistort;
import boofcv.alg.filter.derivative.GImageDerivativeOps;
import boofcv.alg.geo.PerspectiveOps;
import boofcv.alg.geo.RectifyImageOps;
import boofcv.alg.geo.rectify.RectifyCalibrated;
import boofcv.alg.geo.robust.ModelMatcherMultiview;
import boofcv.factory.distort.LensDistortionFactory;
import boofcv.factory.feature.disparity.ConfigDisparityBMBest5;
import boofcv.factory.feature.disparity.DisparityError;
import boofcv.factory.feature.disparity.FactoryStereoDisparity;
import boofcv.factory.geo.ConfigEssential;
import boofcv.factory.geo.ConfigRansac;
import boofcv.factory.geo.FactoryMultiViewRobust;
import boofcv.gui.d3.DisparityToColorPointCloud;
import boofcv.gui.feature.AssociationPanel;
import boofcv.gui.image.ShowImages;
import boofcv.gui.image.VisualizeImageData;
import boofcv.gui.stereo.RectifiedPairPanel;
import boofcv.io.UtilIO;
import boofcv.io.calibration.CalibrationIO;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.io.image.UtilImageIO;
import boofcv.struct.border.BorderType;
import boofcv.struct.calib.CameraPinhole;
import boofcv.struct.calib.CameraPinholeBrown;
import boofcv.struct.distort.DoNothing2Transform2_F64;
import boofcv.struct.distort.Point2Transform2_F64;
import boofcv.struct.geo.AssociatedPair;
import boofcv.struct.image.*;
import boofcv.visualize.PointCloudViewer;
import boofcv.visualize.VisualizeData;
import georegression.struct.se.Se3_F64;
import georegression.struct.se.SpecialEuclideanOps_F64;
import org.ejml.data.DMatrixRMaj;
import org.ejml.data.FMatrixRMaj;
import org.ejml.ops.ConvertMatrixData;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Example demonstrating how to use to images taken from a single calibrated camera to create a stereo disparity image,
* from which a dense 3D point cloud of the scene can be computed. For this technique to work the camera's motion
* needs to be approximately tangential to the direction the camera is pointing. The code below assumes that the first
* image is to the left of the second image.
*
* @author Peter Abeles
*/
public class ExampleStereoTwoViewsOneCamera {
// Disparity calculation parameters
private static final int minDisparity = 15;
private static final int rangeDisparity = 85;
public static void main(String args[]) {
// specify location of images and calibration
String calibDir = UtilIO.pathExample("calibration/mono/Sony_DSC-HX5V_Chess/");
String imageDir = UtilIO.pathExample("stereo/");
// Camera parameters
CameraPinholeBrown intrinsic = CalibrationIO.load(new File(calibDir , "intrinsic.yaml"));
// Input images from the camera moving left to right
BufferedImage origLeft = UtilImageIO.loadImage(imageDir , "mono_wall_01.jpg");
BufferedImage origRight = UtilImageIO.loadImage(imageDir, "mono_wall_02.jpg");
// Input images with lens distortion
GrayU8 distortedLeft = ConvertBufferedImage.convertFrom(origLeft, (GrayU8) null);
GrayU8 distortedRight = ConvertBufferedImage.convertFrom(origRight, (GrayU8) null);
// matched features between the two images
List<AssociatedPair> matchedFeatures = ExampleFundamentalMatrix.computeMatches(origLeft, origRight);
// convert from pixel coordinates into normalized image coordinates
List<AssociatedPair> matchedCalibrated = convertToNormalizedCoordinates(matchedFeatures, intrinsic);
// Robustly estimate camera motion
List<AssociatedPair> inliers = new ArrayList<>();
Se3_F64 leftToRight = estimateCameraMotion(intrinsic, matchedCalibrated, inliers);
drawInliers(origLeft, origRight, intrinsic, inliers);
// Rectify and remove lens distortion for stereo processing
DMatrixRMaj rectifiedK = new DMatrixRMaj(3, 3);
DMatrixRMaj rectifiedR = new DMatrixRMaj(3, 3);
GrayU8 rectifiedLeft = distortedLeft.createSameShape();
GrayU8 rectifiedRight = distortedRight.createSameShape();
GrayU8 rectifiedMask = distortedLeft.createSameShape();
rectifyImages(distortedLeft, distortedRight, leftToRight, intrinsic,intrinsic,
rectifiedLeft, rectifiedRight,rectifiedMask, rectifiedK,rectifiedR);
// compute disparity
ConfigDisparityBMBest5 config = new ConfigDisparityBMBest5();
config.errorType = DisparityError.SAD;
config.minDisparity = minDisparity;
config.rangeDisparity = rangeDisparity;
config.subpixel = true;
config.regionRadiusX = config.regionRadiusY = 5;
config.maxPerPixelError = 20;
config.validateRtoL = 1;
config.texture = 0.1;
StereoDisparity<GrayS16, GrayF32> disparityAlg =
FactoryStereoDisparity.blockMatchBest5(config, GrayS16.class, GrayF32.class);
// Apply the Laplacian across the image to add extra resistance to changes in lighting or camera gain
GrayS16 derivLeft = new GrayS16(rectifiedLeft.width,rectifiedLeft.height);
GrayS16 derivRight = new GrayS16(rectifiedLeft.width,rectifiedLeft.height);
GImageDerivativeOps.laplace(rectifiedLeft, derivLeft,BorderType.EXTENDED);
GImageDerivativeOps.laplace(rectifiedRight,derivRight,BorderType.EXTENDED);
// process and return the results
disparityAlg.process(derivLeft, derivRight);
GrayF32 disparity = disparityAlg.getDisparity();
RectifyImageOps.applyMask(disparity,rectifiedMask,0);
// show results
BufferedImage visualized = VisualizeImageData.disparity(disparity, null, rangeDisparity, 0);
BufferedImage outLeft = ConvertBufferedImage.convertTo(rectifiedLeft, null);
BufferedImage outRight = ConvertBufferedImage.convertTo(rectifiedRight, null);
ShowImages.showWindow(new RectifiedPairPanel(true, outLeft, outRight), "Rectification",true);
ShowImages.showWindow(visualized, "Disparity",true);
showPointCloud(disparity, outLeft, leftToRight, rectifiedK,rectifiedR, minDisparity, rangeDisparity);
System.out.println("Total found " + matchedCalibrated.size());
System.out.println("Total Inliers " + inliers.size());
}
/**
* Estimates the camera motion robustly using RANSAC and a set of associated points.
*
* @param intrinsic Intrinsic camera parameters
* @param matchedNorm set of matched point features in normalized image coordinates
* @param inliers OUTPUT: Set of inlier features from RANSAC
* @return Found camera motion. Note translation has an arbitrary scale
*/
public static Se3_F64 estimateCameraMotion(CameraPinholeBrown intrinsic,
List<AssociatedPair> matchedNorm, List<AssociatedPair> inliers)
{
ModelMatcherMultiview<Se3_F64, AssociatedPair> epipolarMotion =
FactoryMultiViewRobust.baselineRansac(new ConfigEssential(),new ConfigRansac(200,0.5));
epipolarMotion.setIntrinsic(0,intrinsic);
epipolarMotion.setIntrinsic(1,intrinsic);
if (!epipolarMotion.process(matchedNorm))
throw new RuntimeException("Motion estimation failed");
// save inlier set for debugging purposes
inliers.addAll(epipolarMotion.getMatchSet());
return epipolarMotion.getModelParameters();
}
/**
* Convert a set of associated point features from pixel coordinates into normalized image coordinates.
*/
public static List<AssociatedPair> convertToNormalizedCoordinates(List<AssociatedPair> matchedFeatures, CameraPinholeBrown intrinsic) {
Point2Transform2_F64 p_to_n = LensDistortionFactory.narrow(intrinsic).undistort_F64(true, false);
List<AssociatedPair> calibratedFeatures = new ArrayList<>();
for (AssociatedPair p : matchedFeatures) {
AssociatedPair c = new AssociatedPair();
p_to_n.compute(p.p1.x, p.p1.y, c.p1);
p_to_n.compute(p.p2.x, p.p2.y, c.p2);
calibratedFeatures.add(c);
}
return calibratedFeatures;
}
/**
* Remove lens distortion and rectify stereo images
*
* @param distortedLeft Input distorted image from left camera.
* @param distortedRight Input distorted image from right camera.
* @param leftToRight Camera motion from left to right
* @param intrinsicLeft Intrinsic camera parameters
* @param rectifiedLeft Output rectified image for left camera.
* @param rectifiedRight Output rectified image for right camera.
* @param rectifiedMask Mask that indicates invalid pixels in rectified image. 1 = valid, 0 = invalid
* @param rectifiedK Output camera calibration matrix for rectified camera
*/
public static <T extends ImageBase<T>>
void rectifyImages(T distortedLeft,
T distortedRight,
Se3_F64 leftToRight,
CameraPinholeBrown intrinsicLeft,
CameraPinholeBrown intrinsicRight,
T rectifiedLeft,
T rectifiedRight,
GrayU8 rectifiedMask,
DMatrixRMaj rectifiedK,
DMatrixRMaj rectifiedR) {
RectifyCalibrated rectifyAlg = RectifyImageOps.createCalibrated();
// original camera calibration matrices
DMatrixRMaj K1 = PerspectiveOps.pinholeToMatrix(intrinsicLeft, (DMatrixRMaj)null);
DMatrixRMaj K2 = PerspectiveOps.pinholeToMatrix(intrinsicRight, (DMatrixRMaj)null);
rectifyAlg.process(K1, new Se3_F64(), K2, leftToRight);
// rectification matrix for each image
DMatrixRMaj rect1 = rectifyAlg.getRect1();
DMatrixRMaj rect2 = rectifyAlg.getRect2();
rectifiedR.set(rectifyAlg.getRectifiedRotation());
// New calibration matrix,
rectifiedK.set(rectifyAlg.getCalibrationMatrix());
// Adjust the rectification to make the view area more useful
RectifyImageOps.fullViewLeft(intrinsicLeft, rect1, rect2, rectifiedK);
// undistorted and rectify images
FMatrixRMaj rect1_F32 = new FMatrixRMaj(3,3);
FMatrixRMaj rect2_F32 = new FMatrixRMaj(3,3);
ConvertMatrixData.convert(rect1, rect1_F32);
ConvertMatrixData.convert(rect2, rect2_F32);
// Extending the image prevents a harsh edge reducing false matches at the image border
// SKIP is another option, possibly a tinny bit faster, but has a harsh edge which will need to be filtered
ImageDistort<T,T> distortLeft =
RectifyImageOps.rectifyImage(intrinsicLeft, rect1_F32, BorderType.EXTENDED, distortedLeft.getImageType());
ImageDistort<T,T> distortRight =
RectifyImageOps.rectifyImage(intrinsicRight, rect2_F32, BorderType.EXTENDED, distortedRight.getImageType());
distortLeft.apply(distortedLeft, rectifiedLeft,rectifiedMask);
distortRight.apply(distortedRight, rectifiedRight);
}
/**
* Draw inliers for debugging purposes. Need to convert from normalized to pixel coordinates.
*/
public static void drawInliers(BufferedImage left, BufferedImage right, CameraPinholeBrown intrinsic,
List<AssociatedPair> normalized) {
Point2Transform2_F64 n_to_p = LensDistortionFactory.narrow(intrinsic).distort_F64(false,true);
List<AssociatedPair> pixels = new ArrayList<>();
for (AssociatedPair n : normalized) {
AssociatedPair p = new AssociatedPair();
n_to_p.compute(n.p1.x, n.p1.y, p.p1);
n_to_p.compute(n.p2.x, n.p2.y, p.p2);
pixels.add(p);
}
// display the results
AssociationPanel panel = new AssociationPanel(20);
panel.setAssociation(pixels);
panel.setImages(left, right);
ShowImages.showWindow(panel, "Inlier Features", true);
}
/**
* Show results as a point cloud
*/
public static void showPointCloud(ImageGray disparity, BufferedImage left,
Se3_F64 motion, DMatrixRMaj rectifiedK , DMatrixRMaj rectifiedR,
int minDisparity, int rangeDisparity)
{
DisparityToColorPointCloud d2c = new DisparityToColorPointCloud();
double baseline = motion.getT().norm();
d2c.configure(baseline, rectifiedK, rectifiedR, new DoNothing2Transform2_F64(), minDisparity, minDisparity+rangeDisparity);
d2c.process(disparity,left);
CameraPinhole rectifiedPinhole = PerspectiveOps.matrixToPinhole(rectifiedK,disparity.width,disparity.height,null);
// skew the view to make the structure easier to see
Se3_F64 cameraToWorld = SpecialEuclideanOps_F64.eulerXyz(-baseline*5,0,0,0,0.2,0,null);
PointCloudViewer pcv = VisualizeData.createPointCloudViewer();
pcv.setCameraHFov(PerspectiveOps.computeHFov(rectifiedPinhole));
pcv.setCameraToWorld(cameraToWorld);
pcv.setTranslationStep(baseline/3);
pcv.addCloud(d2c.getCloud(),d2c.getCloudColor());
pcv.setDotSize(1);
pcv.setTranslationStep(baseline/10);
pcv.getComponent().setPreferredSize(new Dimension(left.getWidth(), left.getHeight()));
ShowImages.showWindow(pcv.getComponent(), "Point Cloud", true);
}
}
|
3e0dad247bbd93d5232b121e84c4cf43f5ff5f3a | 3,286 | java | Java | app/src/main/java/com/example/user/century/GuestLoginActivity/PilihPetaGuestAdapter.java | yacob21/Century | 9924f34ed218c0dda88b9d0a8323bffcb7fa4a5d | [
"MIT"
] | null | null | null | app/src/main/java/com/example/user/century/GuestLoginActivity/PilihPetaGuestAdapter.java | yacob21/Century | 9924f34ed218c0dda88b9d0a8323bffcb7fa4a5d | [
"MIT"
] | null | null | null | app/src/main/java/com/example/user/century/GuestLoginActivity/PilihPetaGuestAdapter.java | yacob21/Century | 9924f34ed218c0dda88b9d0a8323bffcb7fa4a5d | [
"MIT"
] | null | null | null | 36.511111 | 129 | 0.702982 | 5,780 | package com.example.user.century.GuestLoginActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.user.century.R;
import com.example.user.century.Register.LokasiPertama;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 27/07/2017.
*/
public class PilihPetaGuestAdapter extends RecyclerView.Adapter<PilihPetaGuestAdapter.PetaGuestViewHolder> {
public List<LokasiPertama> lokasiGuestList;
Context context;
ArrayList<String> tempNama = new ArrayList<>();
ArrayList<Integer> tempId = new ArrayList<>();
public PilihPetaGuestAdapter(Context c,List<LokasiPertama> lokasiGuestList) {
this.lokasiGuestList=lokasiGuestList;
this.context=c;
}
@Override
public void onBindViewHolder(final PetaGuestViewHolder petaGuestViewHolder, final int i) {
final LokasiPertama lp = lokasiGuestList.get(i);
petaGuestViewHolder.tvNamaLokasiPertama.setText(lp.Nama);
petaGuestViewHolder.tvAlamatLokasiPertama.setText(lp.Alamat);
petaGuestViewHolder.tvJarakLokasiPertama.setText(String.valueOf(String.format( "%.2f km", lp.Jarak )));
petaGuestViewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), String.valueOf(lp.Id), Toast.LENGTH_SHORT).show();
Intent i = new Intent(v.getContext(),PetaGuest.class);
i.putExtra("panduanNama",lp.Nama);
i.putExtra("panduanAlamat",lp.Alamat);
i.putExtra("panduanLongitude2",lp.Longitude);
i.putExtra("panduanLatitude2",lp.Latitude);
i.putExtra("panduanJarak",petaGuestViewHolder.tvJarakLokasiPertama.getText().toString());
i.putExtra("panduanId",String.valueOf(lp.Id));
v.getContext().startActivity(i);
}
});
}
@Override
public int getItemCount() {
return lokasiGuestList.size();
}
@Override
public PilihPetaGuestAdapter.PetaGuestViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_lokasi_pertama, viewGroup, false);
return new PilihPetaGuestAdapter.PetaGuestViewHolder(itemView);
}
public static class PetaGuestViewHolder extends RecyclerView.ViewHolder {
protected TextView tvJarakLokasiPertama;
protected TextView tvNamaLokasiPertama;
protected TextView tvAlamatLokasiPertama;
protected LinearLayout btnDetail;
public PetaGuestViewHolder(View v) {
super(v);
btnDetail = (LinearLayout) v.findViewById(R.id.btnDetail);
tvAlamatLokasiPertama = (TextView) v.findViewById(R.id.tvAlamatLokasiPertama);
tvNamaLokasiPertama = (TextView) v.findViewById(R.id.tvNamaLokasiPertama);
tvJarakLokasiPertama = (TextView) v.findViewById(R.id.tvJarakLokasiPertama);
}
}
} |
3e0dad7b2a220f12f6e315c3043f948026538f9f | 2,821 | java | Java | src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/transittaxes/entities/TaxEntity.java | helderhernandez/apaw-practice | 38fbe250f5ff21f2503ab129e243c2cbecf312d9 | [
"MIT"
] | null | null | null | src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/transittaxes/entities/TaxEntity.java | helderhernandez/apaw-practice | 38fbe250f5ff21f2503ab129e243c2cbecf312d9 | [
"MIT"
] | null | null | null | src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/transittaxes/entities/TaxEntity.java | helderhernandez/apaw-practice | 38fbe250f5ff21f2503ab129e243c2cbecf312d9 | [
"MIT"
] | null | null | null | 23.122951 | 124 | 0.613612 | 5,781 | package es.upm.miw.apaw_practice.adapters.mongodb.transittaxes.entities;
import es.upm.miw.apaw_practice.domain.models.transittaxes.Tax;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.math.BigDecimal;
import java.util.UUID;
@Document
public class TaxEntity {
@Id
private String id;
@Indexed(unique = true)
private String refTax;
private String description;
private BigDecimal price;
private Boolean paid;
public TaxEntity() {
//empty from framework
}
public TaxEntity(Tax tax) {
BeanUtils.copyProperties(tax, this);
this.id = UUID.randomUUID().toString();
}
public static TaxBuilders.IdTax builder() {
return new Builder();
}
public String getId() {
return id;
}
public String getRefTax() {
return refTax;
}
public void setRefTax(String refTax) {
this.refTax = refTax;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Boolean getPaid() {
return paid;
}
public void setPaid(Boolean paid) {
this.paid = paid;
}
public Tax toTax() {
Tax tax = new Tax();
BeanUtils.copyProperties(this, tax);
return tax;
}
public static class Builder implements TaxBuilders.IdTax, TaxBuilders.RefTax, TaxBuilders.Price, TaxBuilders.Optatives {
private TaxEntity taxEntity;
public Builder() {
this.taxEntity = new TaxEntity();
}
@Override
public TaxBuilders.RefTax idTax() {
this.taxEntity.id = UUID.randomUUID().toString();
return this;
}
@Override
public TaxBuilders.Price refTax(String refTax) {
this.taxEntity.refTax = refTax;
return this;
}
@Override
public TaxBuilders.Optatives price(BigDecimal price) {
this.taxEntity.price = price;
return this;
}
@Override
public TaxBuilders.Optatives description(String description) {
this.taxEntity.description = description;
return this;
}
@Override
public TaxBuilders.Optatives paid(Boolean paid) {
this.taxEntity.paid = paid;
return this;
}
@Override
public TaxEntity build() {
return taxEntity;
}
}
}
|
3e0dad8e281504db3eded1c3bd445f3d92f2299d | 3,150 | java | Java | v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/options/PubsubToJdbcOptions.java | Cherepushko/DataflowTemplates | 327a84ec27dc174af75ef86d43e8d06670f8c1c1 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-10-11T04:07:05.000Z | 2021-10-11T04:07:05.000Z | v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/options/PubsubToJdbcOptions.java | Cherepushko/DataflowTemplates | 327a84ec27dc174af75ef86d43e8d06670f8c1c1 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2021-12-18T20:28:20.000Z | 2022-02-16T01:21:37.000Z | v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/options/PubsubToJdbcOptions.java | Cherepushko/DataflowTemplates | 327a84ec27dc174af75ef86d43e8d06670f8c1c1 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2019-06-24T18:25:37.000Z | 2019-09-09T16:57:49.000Z | 33.157895 | 107 | 0.726032 | 5,782 | /*
* Copyright (C) 2021 Google LLC
*
* 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.google.cloud.teleport.v2.options;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.Validation;
/**
* The {@link PubsubToJdbcOptions} interface provides the custom execution options passed by the
* executor at the command-line.
*/
public interface PubsubToJdbcOptions extends PipelineOptions {
@Description(
"The Cloud Pub/Sub subscription to read from. "
+ "The name should be in the format of "
+ "projects/<project-id>/subscriptions/<subscription-name>.")
@Validation.Required
String getInputSubscription();
void setInputSubscription(String inputSubscription);
@Description("The JDBC driver class name. " + "For example: com.mysql.jdbc.Driver")
String getDriverClassName();
void setDriverClassName(String driverClassName);
@Description(
"The JDBC connection URL string. " + "For example: jdbc:mysql://some-host:3306/sampledb")
String getConnectionUrl();
void setConnectionUrl(String connectionUrl);
@Description("JDBC connection user name. ")
String getUsername();
void setUsername(String username);
@Description("JDBC connection password. ")
String getPassword();
void setPassword(String password);
@Description(
"Comma separate list of driver class/dependency jar file GCS paths "
+ "for example "
+ "gs://<some-bucket>/driver_jar1.jar,gs://<some_bucket>/driver_jar2.jar")
String getDriverJars();
void setDriverJars(String driverJar);
@Description(
"JDBC connection property string. " + "For example: unicode=true&characterEncoding=UTF-8")
String getConnectionProperties();
void setConnectionProperties(String connectionProperties);
@Description(
"SQL statement which will be executed to write to the database. For example:"
+ " INSERT INTO tableName VALUES (?,?)")
String getStatement();
void setStatement(String statement);
@Description(
"The Cloud Pub/Sub topic to publish deadletter records to. "
+ "The name should be in the format of "
+ "projects/<project-id>/topics/<topic-name>.")
@Validation.Required
String getOutputDeadletterTopic();
void setOutputDeadletterTopic(String deadletterTopic);
@Description(
"KMS Encryption Key. The key should be in the format"
+ " projects/{gcp_project}/locations/{key_region}/keyRings/{key_ring}/cryptoKeys/{kms_key_name}")
String getKMSEncryptionKey();
void setKMSEncryptionKey(String keyName);
}
|
3e0dae8c348cf3924c55d4dffc03b835cc7b4b16 | 1,956 | java | Java | eventuate/todo-list/hybrid-query/src/test/java/com/networknt/todolist/query/handler/GetAllTodosTest.java | morganseznec/light-example-4j | 85a364b060ba2270625a37da3deef9c16168dff8 | [
"Apache-2.0"
] | null | null | null | eventuate/todo-list/hybrid-query/src/test/java/com/networknt/todolist/query/handler/GetAllTodosTest.java | morganseznec/light-example-4j | 85a364b060ba2270625a37da3deef9c16168dff8 | [
"Apache-2.0"
] | 3 | 2022-01-21T23:54:27.000Z | 2022-02-16T01:18:37.000Z | eventuate/todo-list/hybrid-query/src/test/java/com/networknt/todolist/query/handler/GetAllTodosTest.java | morganseznec/light-example-4j | 85a364b060ba2270625a37da3deef9c16168dff8 | [
"Apache-2.0"
] | null | null | null | 36.222222 | 79 | 0.707055 | 5,783 |
package com.networknt.todolist.query.handler;
import com.networknt.client.Client;
import com.networknt.server.Server;
import com.networknt.exception.ClientException;
import com.networknt.exception.ApiException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jose4j.json.internal.json_simple.JSONObject;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class GetAllTodosTest {
@ClassRule
public static TestServer server = TestServer.getInstance();
static final Logger logger = LoggerFactory.getLogger(GetAllTodos.class);
@Test
public void testGetAllTodos() throws ClientException, ApiException {
CloseableHttpClient client = Client.getInstance().getSyncClient();
HttpPost httpPost = new HttpPost("http://localhost:8080/api/json");
Map<String, Object> map = new HashMap<String, Object>();
map.put("host", "lightapi.net");
map.put("service", "todo");
map.put("action", "gettodos");
map.put("version", "0.1.0");
JSONObject json = new JSONObject();
json.putAll( map );
System.out.printf( "JSON: %s", json.toString() );
//Client.getInstance().addAuthorization(httpPost);
try {
httpPost.setEntity(new StringEntity(json.toString()));
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
} |
3e0daea5fa3097218b264cd19800b7258c5ac63b | 354 | java | Java | HW05 - Simple Hash Table/src/hr/fer/zemris/java/tecaj/hw5/db/comparison/EqualsCondition.java | tiendung690/JavaCourse | fff7d3077029344a8319c8da2bf09753475c8b0d | [
"MIT"
] | null | null | null | HW05 - Simple Hash Table/src/hr/fer/zemris/java/tecaj/hw5/db/comparison/EqualsCondition.java | tiendung690/JavaCourse | fff7d3077029344a8319c8da2bf09753475c8b0d | [
"MIT"
] | null | null | null | HW05 - Simple Hash Table/src/hr/fer/zemris/java/tecaj/hw5/db/comparison/EqualsCondition.java | tiendung690/JavaCourse | fff7d3077029344a8319c8da2bf09753475c8b0d | [
"MIT"
] | 1 | 2017-07-20T11:05:19.000Z | 2017-07-20T11:05:19.000Z | 20.823529 | 71 | 0.745763 | 5,784 | package hr.fer.zemris.java.tecaj.hw5.db.comparison;
/**
* A comparison operator that checks if the two given string are equal.
*
* @author Kristijan Vulinovic
* @version 1.0
*/
public class EqualsCondition implements IComparisonOperator {
@Override
public boolean satisfied(String value1, String value2) {
return value1.equals(value2);
}
}
|
3e0daec71edfe28f73da96499ef9ec2bc741316d | 2,577 | java | Java | special-membership-service/src/test/java/specialmembershipservice/it/IntegrationTestBase.java | rahulagalcha97/microservices-testing-examples | c56cbf4a954387839df981a8a2c24825315a7a2e | [
"MIT"
] | 103 | 2016-11-03T18:24:35.000Z | 2022-02-08T05:25:52.000Z | special-membership-service/src/test/java/specialmembershipservice/it/IntegrationTestBase.java | rahulagalcha97/microservices-testing-examples | c56cbf4a954387839df981a8a2c24825315a7a2e | [
"MIT"
] | 138 | 2016-12-07T20:00:07.000Z | 2022-03-21T22:56:59.000Z | special-membership-service/src/test/java/specialmembershipservice/it/IntegrationTestBase.java | dinhluongzalora/microservices-testing-examples | 812af0df12c7eab456328ee19e245af6fcae6a71 | [
"MIT"
] | 35 | 2017-01-31T20:41:49.000Z | 2022-01-30T20:31:20.000Z | 37.897059 | 99 | 0.803648 | 5,785 | package specialmembershipservice.it;
import static io.dropwizard.testing.ResourceHelpers.resourceFilePath;
import static java.util.Collections.singletonMap;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.github.charithe.kafka.EphemeralKafkaBroker;
import com.github.charithe.kafka.KafkaJunitRule;
import io.dropwizard.testing.junit.DropwizardAppRule;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.RuleChain;
import specialmembershipservice.bootstrap.SpecialMembershipServiceApplication;
import specialmembershipservice.bootstrap.SpecialMembershipServiceConfiguration;
import specialmembershipservice.it.client.ResourcesClient;
public abstract class IntegrationTestBase {
protected static final String CREDIT_SCORE_SERVICE_HOST = "localhost";
protected static final int CREDIT_SCORE_SERVICE_PORT = 8088;
private static final String INTEGRATION_YML = resourceFilePath("integration.yml");
private static final int KAFKA_PORT = 9092;
private static final String SPECIAL_MEMBERSHIP_TOPIC = "special-membership-topic";
private static final EphemeralKafkaBroker KAFKA_BROKER = EphemeralKafkaBroker.create(KAFKA_PORT);
private static final KafkaJunitRule KAFKA_RULE = new KafkaJunitRule(KAFKA_BROKER);
private static final DropwizardAppRule<SpecialMembershipServiceConfiguration> SERVICE_RULE =
new DropwizardAppRule<>(SpecialMembershipServiceApplication.class, INTEGRATION_YML);
@ClassRule
public static final RuleChain RULES = RuleChain
.outerRule(KAFKA_RULE)
.around(SERVICE_RULE);
protected static ResourcesClient resourcesClient;
@BeforeClass
public static void setUpClass() throws Exception {
resourcesClient = new ResourcesClient(SERVICE_RULE.getEnvironment(),
SERVICE_RULE.getLocalPort());
}
protected String readPublishedMessage()
throws InterruptedException, ExecutionException, TimeoutException {
return readOneMessage(SPECIAL_MEMBERSHIP_TOPIC);
}
protected String readOneMessage(String topic)
throws InterruptedException, ExecutionException, TimeoutException {
return KAFKA_RULE.helper()
.consumeStrings(topic, 1)
.get(5, SECONDS)
.get(0);
}
protected Map<String, Object> specialMembershipDto(String email) {
return singletonMap("email", email);
}
protected String creditScoreDto(Integer creditScore) {
return String.format("{\"creditScore\":%d}", creditScore);
}
}
|
3e0daf4197bad6e7d88afe64eb4349f55745f469 | 1,888 | java | Java | swf/src/main/java/com/venky/swf/plugins/attachment/controller/AttachmentsController.java | venkatramanm/swf-all | a9a13f494335772d14df7f8c6c7914da6a082696 | [
"MIT"
] | 2 | 2019-09-04T19:08:00.000Z | 2022-02-04T19:41:20.000Z | swf/src/main/java/com/venky/swf/plugins/attachment/controller/AttachmentsController.java | venkatramanm/swf-all | a9a13f494335772d14df7f8c6c7914da6a082696 | [
"MIT"
] | 9 | 2021-07-24T17:34:24.000Z | 2022-01-16T18:06:31.000Z | swf/src/main/java/com/venky/swf/plugins/attachment/controller/AttachmentsController.java | venkatramanm/swf-all | a9a13f494335772d14df7f8c6c7914da6a082696 | [
"MIT"
] | 1 | 2021-09-04T10:56:42.000Z | 2021-09-04T10:56:42.000Z | 28.179104 | 182 | 0.722987 | 5,786 | package com.venky.swf.plugins.attachment.controller;
import java.util.List;
import com.venky.core.date.DateUtils;
import com.venky.core.util.ObjectUtil;
import com.venky.swf.controller.ModelController;
import com.venky.swf.controller.annotations.RequireLogin;
import com.venky.swf.db.Database;
import com.venky.swf.exceptions.AccessDeniedException;
import com.venky.swf.path.Path;
import com.venky.swf.plugins.attachment.db.model.Attachment;
import com.venky.swf.sql.Expression;
import com.venky.swf.sql.Operator;
import com.venky.swf.sql.Select;
import com.venky.swf.views.View;
public class AttachmentsController extends ModelController<Attachment>{
public AttachmentsController(Path path) {
super(path);
}
@RequireLogin(false)
public View view(String contentFileName){
Attachment attachment = null;
if (contentFileName.matches("^[0-9]+\\.[^\\.]+$")){
String[] parts = contentFileName.split("\\.");
attachment = Database.getTable(Attachment.class).get(Long.valueOf(parts[0]));
}
if (attachment == null){
List<Attachment> attachments = new Select().from(Attachment.class).where(new Expression(getReflector().getPool(),"ATTACHMENT_CONTENT_NAME",Operator.EQ,contentFileName)).execute();
if (attachments.size() == 1){
attachment = attachments.get(0);
}
}
if (attachment != null) {
return view(attachment,null);
}
throw new AccessDeniedException();
}
@Override
@RequireLogin(false)
public View view(long id) {
return super.view(id);
}
@Override
public View save() {
if (getIntegrationAdaptor() == null){
String id = (String)getPath().getFormFields().get("ID");
if (!ObjectUtil.isVoid(id)){
Attachment attachment = Database.getTable(getModelClass()).get(Long.valueOf(id));
if (attachment != null){
attachment.destroy();
getPath().getFormFields().remove("ID");
}
}
}
return super.save();
}
}
|
3e0db081ea2b07cbb3c70caa655f72659d35650b | 635 | java | Java | src/main/java/dp/_14_chains_of_responsibility_pattern/AbstractLogger.java | ivalue2333/centaur | f579356ea4eaaf289d45305816975f6a6c6bf555 | [
"Apache-2.0"
] | null | null | null | src/main/java/dp/_14_chains_of_responsibility_pattern/AbstractLogger.java | ivalue2333/centaur | f579356ea4eaaf289d45305816975f6a6c6bf555 | [
"Apache-2.0"
] | null | null | null | src/main/java/dp/_14_chains_of_responsibility_pattern/AbstractLogger.java | ivalue2333/centaur | f579356ea4eaaf289d45305816975f6a6c6bf555 | [
"Apache-2.0"
] | null | null | null | 22.678571 | 56 | 0.672441 | 5,787 | package dp._14_chains_of_responsibility_pattern;
public abstract class AbstractLogger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
protected int level;
//责任链中的下一个元素
protected AbstractLogger nextLogger;
public void setNextLogger(AbstractLogger nextLogger){
this.nextLogger = nextLogger;
}
public void logMessage(int level, String message){
if(this.level <= level){
write(message);
}
if(nextLogger !=null){
nextLogger.logMessage(level, message);
}
}
abstract protected void write(String message);
} |
3e0db1221b140c20a2d513af175b01ae11972956 | 1,651 | java | Java | app/src/main/java/com/adil/android/Hyderabadi/NumbersActivity.java | Sugooi/Hyderabadi | 204cbe4ca89a4311cdc4b076fd1dfd7da84db080 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/adil/android/Hyderabadi/NumbersActivity.java | Sugooi/Hyderabadi | 204cbe4ca89a4311cdc4b076fd1dfd7da84db080 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/adil/android/Hyderabadi/NumbersActivity.java | Sugooi/Hyderabadi | 204cbe4ca89a4311cdc4b076fd1dfd7da84db080 | [
"Apache-2.0"
] | null | null | null | 33.02 | 79 | 0.682617 | 5,788 | package com.adil.android.Hyderabadi;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class NumbersActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.words_list);
// LinearLayout linearLayout=(LinearLayout) findViewById(R.id.lay2);
// linearLayout.setBackgroundColor(Color.parseColor("#FFF76d"));
ArrayList<Word> words= new ArrayList<Word>();
words.add(new Word("One","Aek",R.drawable.number_one,"#b99bc7"));
words.add(new Word("Two","Do",R.drawable.number_two,"#b99bc7"));
words.add(new Word("Three","Theen",R.drawable.number_three,"#b99bc7"));
words.add(new Word("Four","Chaar",R.drawable.number_four,"#b99bc7"));
words.add(new Word("Five","Panch",R.drawable.number_five,"#b99bc7"));
words.add(new Word("Six","Che",R.drawable.number_six,"#b99bc7"));
words.add(new Word("Seven","Saath",R.drawable.number_seven,"#b99bc7"));
words.add(new Word("Eight","Aath",R.drawable.number_eight,"#b99bc7"));
words.add(new Word("Nine","Naw",R.drawable.number_nine,"#b99bc7"));
words.add(new Word("Ten","Dus",R.drawable.number_ten,"#b99bc7"));
WordAdapter itemsAdapter = new WordAdapter(this,words);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(itemsAdapter);
listView.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
}
|
3e0db1a6be140bfa16448b9aa16990cb0cbea9e6 | 768 | java | Java | src/pl/altkom/ogoreczek/model/JednostkaMiary.java | alapierre/altkom_2014_07_22 | e0ade3eccdbbdd677e8d91ab07cc826c26955e74 | [
"Apache-2.0"
] | null | null | null | src/pl/altkom/ogoreczek/model/JednostkaMiary.java | alapierre/altkom_2014_07_22 | e0ade3eccdbbdd677e8d91ab07cc826c26955e74 | [
"Apache-2.0"
] | null | null | null | src/pl/altkom/ogoreczek/model/JednostkaMiary.java | alapierre/altkom_2014_07_22 | e0ade3eccdbbdd677e8d91ab07cc826c26955e74 | [
"Apache-2.0"
] | null | null | null | 29.538462 | 76 | 0.696615 | 5,789 | /*
* Copyright 2014 Your Name <Ewa Milewska>.
*
* 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 pl.altkom.ogoreczek.model;
/**
*
* @author Your Name <Ewa Milewska>
*/
public enum JednostkaMiary {
szt, kg, litr
}
|
3e0db1c8d99e600e2b58e27dad3ece646d75faba | 169 | java | Java | spring-study/src/main/java/com/guo/UserBean.java | guojunjiechen/spring | 4894e1880129eece0fa38d9e3579f641021ba9f0 | [
"Apache-2.0"
] | 1 | 2019-12-20T05:52:52.000Z | 2019-12-20T05:52:52.000Z | spring-study/src/main/java/com/guo/UserBean.java | guojunjiechen/spring | 4894e1880129eece0fa38d9e3579f641021ba9f0 | [
"Apache-2.0"
] | null | null | null | spring-study/src/main/java/com/guo/UserBean.java | guojunjiechen/spring | 4894e1880129eece0fa38d9e3579f641021ba9f0 | [
"Apache-2.0"
] | null | null | null | 12.071429 | 40 | 0.674556 | 5,790 | package com.guo;
public class UserBean {
private String name;
private int age;
public UserBean(String name, int age) {
this.name = name;
this.age = age;
}
}
|
3e0db2515e2552c99d8993db7f355d7e6b25ba55 | 8,228 | java | Java | OpenRobertaRobot/src/main/java/de/fhg/iais/roberta/visitor/hardware/sensor/ISensorVisitor.java | MatthiasSchmickler/openroberta-lab | e1d2306945ad60670d7dd619b38edd933e4d299d | [
"Apache-2.0"
] | 1 | 2019-06-04T05:01:35.000Z | 2019-06-04T05:01:35.000Z | OpenRobertaRobot/src/main/java/de/fhg/iais/roberta/visitor/hardware/sensor/ISensorVisitor.java | sebastiankmilo/openroberta-lab | bf7ca882137cff3a065e75a28fce833578841e1c | [
"Apache-2.0"
] | null | null | null | OpenRobertaRobot/src/main/java/de/fhg/iais/roberta/visitor/hardware/sensor/ISensorVisitor.java | sebastiankmilo/openroberta-lab | bf7ca882137cff3a065e75a28fce833578841e1c | [
"Apache-2.0"
] | null | null | null | 30.139194 | 78 | 0.67404 | 5,791 | package de.fhg.iais.roberta.visitor.hardware.sensor;
import de.fhg.iais.roberta.syntax.sensor.generic.AccelerometerSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.ColorSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.CompassSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.DropSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.EncoderSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.GestureSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.GetSampleSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.GyroSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.HumiditySensor;
import de.fhg.iais.roberta.syntax.sensor.generic.IRSeekerSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.InfraredSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.KeysSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.LightSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.MoistureSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.MotionSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.PinGetValueSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.PinTouchSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.PulseSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.RfidSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.SoundSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.TemperatureSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.TimerSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.TouchSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.UltrasonicSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.VemlLightSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.VoltageSensor;
import de.fhg.iais.roberta.util.dbc.DbcException;
import de.fhg.iais.roberta.visitor.hardware.IHardwareVisitor;
public interface ISensorVisitor<V> extends IHardwareVisitor<V> {
/**
* visit a {@link KeysSensor}.
*
* @param keysSensor to be visited
*/
default V visitKeysSensor(KeysSensor<V> keysSensor) {
throw new DbcException("KeysSensor not implemented!");
}
/**
* visit a {@link ColorSensor}.
*
* @param colorSensor to be visited
*/
default V visitColorSensor(ColorSensor<V> colorSensor) {
throw new DbcException("ColorSensor not implemented!");
}
/**
* visit a {@link LightSensor}.
*
* @param colorSensor to be visited
*/
default V visitLightSensor(LightSensor<V> lightSensor) {
throw new DbcException("LightSensor not implemented!");
}
/**
* visit a {@link SoundSensor}.
*
* @param colorSensor to be visited
*/
default V visitSoundSensor(SoundSensor<V> soundSensor) {
throw new DbcException("SoundSensor not implemented!");
}
/**
* visit a {@link EncoderSensor}.
*
* @param encoderSensor to be visited
*/
default V visitEncoderSensor(EncoderSensor<V> encoderSensor) {
throw new DbcException("EncoderSensor not implemented!");
}
/**
* visit a {@link GyroSensor}.
*
* @param gyroSensor to be visited
*/
default V visitGyroSensor(GyroSensor<V> gyroSensor) {
throw new DbcException("GyroSensor not implemented!");
}
/**
* visit a {@link InfraredSensor}.
*
* @param infraredSensor to be visited
*/
default V visitInfraredSensor(InfraredSensor<V> infraredSensor) {
throw new DbcException("InfraredSensor not implemented!");
}
/**
* visit a {@link TimerSensor}.
*
* @param timerSensor to be visited
*/
default V visitTimerSensor(TimerSensor<V> timerSensor) {
throw new DbcException("TimerSensor not implemented!");
}
/**
* visit a {@link TouchSensor}.
*
* @param touchSensor to be visited
*/
default V visitTouchSensor(TouchSensor<V> touchSensor) {
throw new DbcException("TouchSensor not implemented!");
}
/**
* visit a {@link UltrasonicSensor}.
*
* @param ultrasonicSensor to be visited
*/
default V visitUltrasonicSensor(UltrasonicSensor<V> ultrasonicSensor) {
throw new DbcException("UltrasonicSensor not implemented!");
}
/**
* visit a {@link CompassSensor}.
*
* @param compassSensor to be visited
*/
default V visitCompassSensor(CompassSensor<V> compassSensor) {
throw new DbcException("CompassSensor not implemented!");
}
/**
* visit a {@link TemperatureSensor}.
*
* @param temperatureSensor to be visited
*/
default V visitTemperatureSensor(TemperatureSensor<V> temperatureSensor) {
throw new DbcException("TemperatureSensor not implemented!");
}
/**
* visit a {@link VoltageSensor}.
*
* @param voltageSensor to be visited
*/
default V visitVoltageSensor(VoltageSensor<V> voltageSensor) {
throw new DbcException("VoltageSensor not implemented!");
}
/**
* visit a {@link AccelerometerSensor}.
*
* @param accelerometerSensor to be visited
*/
default V visitAccelerometer(AccelerometerSensor<V> accelerometerSensor) {
throw new DbcException("AccelerometerSensor not implemented!");
}
/**
* visit a {@link PinTouchSensor}.
*
* @param pinTouchSensor to be visited
*/
default V visitPinTouchSensor(PinTouchSensor<V> sensorGetSample) {
throw new DbcException("PinTouchSensor not implemented!");
}
/**
* visit a {@link GestureSensor}.
*
* @param GestureSensor to be visited
*/
default V visitGestureSensor(GestureSensor<V> sensorGetSample) {
throw new DbcException("GestureSensor not implemented!");
}
/**
* visit a {@link PinGetValueSensor}.
*
* @param PinGetValueSensor to be visited
*/
default V visitPinGetValueSensor(PinGetValueSensor<V> pinGetValueSensor) {
throw new DbcException("PinGetValueSensor not implemented!");
}
/**
* visit a {@link GetSampleSensor}.
*
* @param sensorGetSample to be visited
*/
default V visitGetSampleSensor(GetSampleSensor<V> sensorGetSample) {
sensorGetSample.getSensor().visit(this);
return null;
}
/**
* visit a {@link InfraredSensor}.
*
* @param infraredSensor to be visited
*/
default V visitIRSeekerSensor(IRSeekerSensor<V> irSeekerSensor) {
throw new DbcException("IRSeekerSensor not implemented!");
}
/**
* visit a {@link MoistureSensor}.
*
* @param MoistureSensor to be visited
*/
default V visitMoistureSensor(MoistureSensor<V> moistureSensor) {
throw new DbcException("MoistureSensor not implemented!");
}
/**
* visit a {@link HumiditySensor}.
*
* @param HumiditySensor to be visited
*/
default V visitHumiditySensor(HumiditySensor<V> humiditySensor) {
throw new DbcException("HumiditySensor not implemented!");
}
/**
* visit a {@link MotionSensor}.
*
* @param MotionSensor to be visited
*/
default V visitMotionSensor(MotionSensor<V> motionSensor) {
throw new DbcException("MotionSensor not implemented!");
}
/**
* visit a {@link DropSensor}.
*
* @param DropSensor to be visited
*/
default V visitDropSensor(DropSensor<V> dropSensor) {
throw new DbcException("DropSensor not implemented!");
}
/**
* visit a {@link PulseSensor}.
*
* @param PulseSensor to be visited
*/
default V visitPulseSensor(PulseSensor<V> pulseSensor) {
throw new DbcException("PulseSensor not implemented!");
}
/**
* visit a {@link RfidSensor}.
*
* @param RfidSensor to be visited
*/
default V visitRfidSensor(RfidSensor<V> rfidSensor) {
throw new DbcException("RfidSensor not implemented!");
}
/**
* visit a {@link VemlLightSensor}.
*
* @param vemlLightSensor to be visited
*/
default V visitVemlLightSensor(VemlLightSensor<V> vemlLightSensor) {
throw new DbcException("VEML light sensor not implemented!");
}
}
|
3e0db254331024bb3f5d53215da0aabc88956093 | 92,272 | java | Java | Plugins/Instantiation/de.uni_hildesheim.sse.vil.buildlang/src-gen/de/uni_hildesheim/sse/services/VilBuildLanguageGrammarAccess.java | SSEHUB/EASyProducer | 769ebe97f9f83963ea814f5e811a562ded7db5d5 | [
"Apache-2.0"
] | 10 | 2016-02-09T14:55:59.000Z | 2019-06-06T00:23:38.000Z | Plugins/Instantiation/de.uni_hildesheim.sse.vil.buildlang/src-gen/de/uni_hildesheim/sse/services/VilBuildLanguageGrammarAccess.java | SSEHUB/EASyProducer | 769ebe97f9f83963ea814f5e811a562ded7db5d5 | [
"Apache-2.0"
] | 88 | 2015-09-03T16:06:12.000Z | 2021-05-26T12:10:12.000Z | Plugins/Instantiation/de.uni_hildesheim.sse.vil.buildlang/src-gen/de/uni_hildesheim/sse/services/VilBuildLanguageGrammarAccess.java | SSEHUB/EASyProducer | 769ebe97f9f83963ea814f5e811a562ded7db5d5 | [
"Apache-2.0"
] | 1 | 2016-03-21T16:12:51.000Z | 2016-03-21T16:12:51.000Z | 40.434706 | 152 | 0.755614 | 5,792 | /*
* generated by Xtext
*/
package de.uni_hildesheim.sse.services;
import com.google.inject.Singleton;
import com.google.inject.Inject;
import java.util.List;
import org.eclipse.xtext.*;
import org.eclipse.xtext.service.GrammarProvider;
import org.eclipse.xtext.service.AbstractElementFinder.*;
import de.uni_hildesheim.sse.vil.expressions.services.ExpressionDslGrammarAccess;
@Singleton
public class VilBuildLanguageGrammarAccess extends AbstractGrammarElementFinder {
public class ImplementationUnitElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.ImplementationUnit");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Action cImplementationUnitAction_0 = (Action)cGroup.eContents().get(0);
private final Assignment cImportsAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cImportsImportParserRuleCall_1_0 = (RuleCall)cImportsAssignment_1.eContents().get(0);
private final Assignment cRequiresAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cRequiresRequireParserRuleCall_2_0 = (RuleCall)cRequiresAssignment_2.eContents().get(0);
private final Assignment cScriptsAssignment_3 = (Assignment)cGroup.eContents().get(3);
private final RuleCall cScriptsLanguageUnitParserRuleCall_3_0 = (RuleCall)cScriptsAssignment_3.eContents().get(0);
//ImplementationUnit:
// {ImplementationUnit} imports+=Import*
// requires+=Require*
// scripts+=LanguageUnit*;
@Override public ParserRule getRule() { return rule; }
//{ImplementationUnit} imports+=Import*
//requires+=Require*
//scripts+=LanguageUnit*
public Group getGroup() { return cGroup; }
//{ImplementationUnit}
public Action getImplementationUnitAction_0() { return cImplementationUnitAction_0; }
//imports+=Import*
public Assignment getImportsAssignment_1() { return cImportsAssignment_1; }
//Import
public RuleCall getImportsImportParserRuleCall_1_0() { return cImportsImportParserRuleCall_1_0; }
//requires+=Require*
public Assignment getRequiresAssignment_2() { return cRequiresAssignment_2; }
//Require
public RuleCall getRequiresRequireParserRuleCall_2_0() { return cRequiresRequireParserRuleCall_2_0; }
//scripts+=LanguageUnit*
public Assignment getScriptsAssignment_3() { return cScriptsAssignment_3; }
//LanguageUnit
public RuleCall getScriptsLanguageUnitParserRuleCall_3_0() { return cScriptsLanguageUnitParserRuleCall_3_0; }
}
public class RequireElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.Require");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cRequireVTLKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Assignment cNameAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cNameSTRINGTerminalRuleCall_1_0 = (RuleCall)cNameAssignment_1.eContents().get(0);
private final Assignment cVersionSpecAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cVersionSpecVersionSpecParserRuleCall_2_0 = (RuleCall)cVersionSpecAssignment_2.eContents().get(0);
private final Keyword cSemicolonKeyword_3 = (Keyword)cGroup.eContents().get(3);
//Require:
// // here fqn because this may reference a specific project (of an external project)
// 'requireVTL' name=STRING versionSpec=VersionSpec
// ';';
@Override public ParserRule getRule() { return rule; }
//// here fqn because this may reference a specific project (of an external project)
//'requireVTL' name=STRING versionSpec=VersionSpec
//';'
public Group getGroup() { return cGroup; }
//// here fqn because this may reference a specific project (of an external project)
//'requireVTL'
public Keyword getRequireVTLKeyword_0() { return cRequireVTLKeyword_0; }
//name=STRING
public Assignment getNameAssignment_1() { return cNameAssignment_1; }
//STRING
public RuleCall getNameSTRINGTerminalRuleCall_1_0() { return cNameSTRINGTerminalRuleCall_1_0; }
//versionSpec=VersionSpec
public Assignment getVersionSpecAssignment_2() { return cVersionSpecAssignment_2; }
//VersionSpec
public RuleCall getVersionSpecVersionSpecParserRuleCall_2_0() { return cVersionSpecVersionSpecParserRuleCall_2_0; }
//';'
public Keyword getSemicolonKeyword_3() { return cSemicolonKeyword_3; }
}
public class LanguageUnitElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.LanguageUnit");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cAdvicesAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final RuleCall cAdvicesAdviceParserRuleCall_0_0 = (RuleCall)cAdvicesAssignment_0.eContents().get(0);
private final Keyword cVilScriptKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cNameAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cNameIdentifierParserRuleCall_2_0 = (RuleCall)cNameAssignment_2.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Assignment cParamAssignment_4 = (Assignment)cGroup.eContents().get(4);
private final RuleCall cParamParameterListParserRuleCall_4_0 = (RuleCall)cParamAssignment_4.eContents().get(0);
private final Keyword cRightParenthesisKeyword_5 = (Keyword)cGroup.eContents().get(5);
private final Assignment cParentAssignment_6 = (Assignment)cGroup.eContents().get(6);
private final RuleCall cParentScriptParentDeclParserRuleCall_6_0 = (RuleCall)cParentAssignment_6.eContents().get(0);
private final Keyword cLeftCurlyBracketKeyword_7 = (Keyword)cGroup.eContents().get(7);
private final Assignment cVersionAssignment_8 = (Assignment)cGroup.eContents().get(8);
private final RuleCall cVersionVersionStmtParserRuleCall_8_0 = (RuleCall)cVersionAssignment_8.eContents().get(0);
private final Assignment cLoadPropertiesAssignment_9 = (Assignment)cGroup.eContents().get(9);
private final RuleCall cLoadPropertiesLoadPropertiesParserRuleCall_9_0 = (RuleCall)cLoadPropertiesAssignment_9.eContents().get(0);
private final Assignment cContentsAssignment_10 = (Assignment)cGroup.eContents().get(10);
private final RuleCall cContentsScriptContentsParserRuleCall_10_0 = (RuleCall)cContentsAssignment_10.eContents().get(0);
private final Keyword cRightCurlyBracketKeyword_11 = (Keyword)cGroup.eContents().get(11);
private final Keyword cSemicolonKeyword_12 = (Keyword)cGroup.eContents().get(12);
//// ---------------- project header
//LanguageUnit:
// advices+=Advice*
// 'vilScript' name=Identifier
// '(' param=ParameterList? ')'
// parent=ScriptParentDecl?
// '{'
// version=VersionStmt?
// loadProperties+=LoadProperties*
// contents=ScriptContents
// '}' ';'?;
@Override public ParserRule getRule() { return rule; }
//// do not rename - required for reuse
// advices+=Advice*
//'vilScript' name=Identifier
//'(' param=ParameterList? ')'
//parent=ScriptParentDecl?
//'{'
//version=VersionStmt?
//loadProperties+=LoadProperties*
//contents=ScriptContents
//'}' ';'?
public Group getGroup() { return cGroup; }
//// do not rename - required for reuse
// advices+=Advice*
public Assignment getAdvicesAssignment_0() { return cAdvicesAssignment_0; }
//Advice
public RuleCall getAdvicesAdviceParserRuleCall_0_0() { return cAdvicesAdviceParserRuleCall_0_0; }
//'vilScript'
public Keyword getVilScriptKeyword_1() { return cVilScriptKeyword_1; }
//name=Identifier
public Assignment getNameAssignment_2() { return cNameAssignment_2; }
//Identifier
public RuleCall getNameIdentifierParserRuleCall_2_0() { return cNameIdentifierParserRuleCall_2_0; }
//'('
public Keyword getLeftParenthesisKeyword_3() { return cLeftParenthesisKeyword_3; }
//param=ParameterList?
public Assignment getParamAssignment_4() { return cParamAssignment_4; }
//ParameterList
public RuleCall getParamParameterListParserRuleCall_4_0() { return cParamParameterListParserRuleCall_4_0; }
//')'
public Keyword getRightParenthesisKeyword_5() { return cRightParenthesisKeyword_5; }
//parent=ScriptParentDecl?
public Assignment getParentAssignment_6() { return cParentAssignment_6; }
//ScriptParentDecl
public RuleCall getParentScriptParentDeclParserRuleCall_6_0() { return cParentScriptParentDeclParserRuleCall_6_0; }
//'{'
public Keyword getLeftCurlyBracketKeyword_7() { return cLeftCurlyBracketKeyword_7; }
//version=VersionStmt?
public Assignment getVersionAssignment_8() { return cVersionAssignment_8; }
//VersionStmt
public RuleCall getVersionVersionStmtParserRuleCall_8_0() { return cVersionVersionStmtParserRuleCall_8_0; }
//loadProperties+=LoadProperties*
public Assignment getLoadPropertiesAssignment_9() { return cLoadPropertiesAssignment_9; }
//LoadProperties
public RuleCall getLoadPropertiesLoadPropertiesParserRuleCall_9_0() { return cLoadPropertiesLoadPropertiesParserRuleCall_9_0; }
//contents=ScriptContents
public Assignment getContentsAssignment_10() { return cContentsAssignment_10; }
//ScriptContents
public RuleCall getContentsScriptContentsParserRuleCall_10_0() { return cContentsScriptContentsParserRuleCall_10_0; }
//'}'
public Keyword getRightCurlyBracketKeyword_11() { return cRightCurlyBracketKeyword_11; }
//';'?
public Keyword getSemicolonKeyword_12() { return cSemicolonKeyword_12; }
}
public class ScriptParentDeclElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.ScriptParentDecl");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cExtendsKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Assignment cNameAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cNameIdentifierParserRuleCall_1_0 = (RuleCall)cNameAssignment_1.eContents().get(0);
//ScriptParentDecl:
// 'extends' name=Identifier // here identifier because this references a complete project
//;
@Override public ParserRule getRule() { return rule; }
//'extends' name=Identifier
public Group getGroup() { return cGroup; }
//'extends'
public Keyword getExtendsKeyword_0() { return cExtendsKeyword_0; }
//name=Identifier
public Assignment getNameAssignment_1() { return cNameAssignment_1; }
//Identifier
public RuleCall getNameIdentifierParserRuleCall_1_0() { return cNameIdentifierParserRuleCall_1_0; }
}
public class LoadPropertiesElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.LoadProperties");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cLoadKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Keyword cPropertiesKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cPathAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cPathSTRINGTerminalRuleCall_2_0 = (RuleCall)cPathAssignment_2.eContents().get(0);
private final Keyword cSemicolonKeyword_3 = (Keyword)cGroup.eContents().get(3);
//LoadProperties:
// 'load' 'properties' path=STRING // here string because this references a file
// ';';
@Override public ParserRule getRule() { return rule; }
//'load' 'properties' path=STRING // here string because this references a file
//';'
public Group getGroup() { return cGroup; }
//'load'
public Keyword getLoadKeyword_0() { return cLoadKeyword_0; }
//'properties'
public Keyword getPropertiesKeyword_1() { return cPropertiesKeyword_1; }
//path=STRING
public Assignment getPathAssignment_2() { return cPathAssignment_2; }
//STRING
public RuleCall getPathSTRINGTerminalRuleCall_2_0() { return cPathSTRINGTerminalRuleCall_2_0; }
//// here string because this references a file
//';'
public Keyword getSemicolonKeyword_3() { return cSemicolonKeyword_3; }
}
public class ScriptContentsElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.ScriptContents");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Action cScriptContentsAction_0 = (Action)cGroup.eContents().get(0);
private final Alternatives cAlternatives_1 = (Alternatives)cGroup.eContents().get(1);
private final Assignment cElementsAssignment_1_0 = (Assignment)cAlternatives_1.eContents().get(0);
private final RuleCall cElementsVariableDeclarationParserRuleCall_1_0_0 = (RuleCall)cElementsAssignment_1_0.eContents().get(0);
private final Assignment cElementsAssignment_1_1 = (Assignment)cAlternatives_1.eContents().get(1);
private final RuleCall cElementsCompoundParserRuleCall_1_1_0 = (RuleCall)cElementsAssignment_1_1.eContents().get(0);
private final Assignment cElementsAssignment_1_2 = (Assignment)cAlternatives_1.eContents().get(2);
private final RuleCall cElementsTypeDefParserRuleCall_1_2_0 = (RuleCall)cElementsAssignment_1_2.eContents().get(0);
private final Assignment cElementsAssignment_1_3 = (Assignment)cAlternatives_1.eContents().get(3);
private final RuleCall cElementsRuleDeclarationParserRuleCall_1_3_0 = (RuleCall)cElementsAssignment_1_3.eContents().get(0);
//ScriptContents:
// {ScriptContents} (elements+=VariableDeclaration
// | elements+=Compound
// | elements+=TypeDef
// | elements+=RuleDeclaration)*;
@Override public ParserRule getRule() { return rule; }
//{ScriptContents} (elements+=VariableDeclaration
//| elements+=Compound
//| elements+=TypeDef
//| elements+=RuleDeclaration)*
public Group getGroup() { return cGroup; }
//{ScriptContents}
public Action getScriptContentsAction_0() { return cScriptContentsAction_0; }
//(elements+=VariableDeclaration
//| elements+=Compound
//| elements+=TypeDef
//| elements+=RuleDeclaration)*
public Alternatives getAlternatives_1() { return cAlternatives_1; }
//elements+=VariableDeclaration
public Assignment getElementsAssignment_1_0() { return cElementsAssignment_1_0; }
//VariableDeclaration
public RuleCall getElementsVariableDeclarationParserRuleCall_1_0_0() { return cElementsVariableDeclarationParserRuleCall_1_0_0; }
//elements+=Compound
public Assignment getElementsAssignment_1_1() { return cElementsAssignment_1_1; }
//Compound
public RuleCall getElementsCompoundParserRuleCall_1_1_0() { return cElementsCompoundParserRuleCall_1_1_0; }
//elements+=TypeDef
public Assignment getElementsAssignment_1_2() { return cElementsAssignment_1_2; }
//TypeDef
public RuleCall getElementsTypeDefParserRuleCall_1_2_0() { return cElementsTypeDefParserRuleCall_1_2_0; }
//elements+=RuleDeclaration
public Assignment getElementsAssignment_1_3() { return cElementsAssignment_1_3; }
//RuleDeclaration
public RuleCall getElementsRuleDeclarationParserRuleCall_1_3_0() { return cElementsRuleDeclarationParserRuleCall_1_3_0; }
}
public class RuleDeclarationElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.RuleDeclaration");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Action cRuleDeclarationAction_0 = (Action)cGroup.eContents().get(0);
private final Group cGroup_1 = (Group)cGroup.eContents().get(1);
private final Assignment cModifierAssignment_1_0 = (Assignment)cGroup_1.eContents().get(0);
private final RuleCall cModifierRuleModifierParserRuleCall_1_0_0 = (RuleCall)cModifierAssignment_1_0.eContents().get(0);
private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1);
private final RuleCall cTypeTypeParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0);
private final Assignment cNameAssignment_1_2 = (Assignment)cGroup_1.eContents().get(2);
private final RuleCall cNameIdentifierParserRuleCall_1_2_0 = (RuleCall)cNameAssignment_1_2.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_1_3 = (Keyword)cGroup_1.eContents().get(3);
private final Assignment cParamListAssignment_1_4 = (Assignment)cGroup_1.eContents().get(4);
private final RuleCall cParamListParameterListParserRuleCall_1_4_0 = (RuleCall)cParamListAssignment_1_4.eContents().get(0);
private final Keyword cRightParenthesisKeyword_1_5 = (Keyword)cGroup_1.eContents().get(5);
private final Keyword cEqualsSignKeyword_1_6 = (Keyword)cGroup_1.eContents().get(6);
private final Assignment cConditionsAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cConditionsRuleConditionsParserRuleCall_2_0 = (RuleCall)cConditionsAssignment_2.eContents().get(0);
private final Assignment cBlockAssignment_3 = (Assignment)cGroup.eContents().get(3);
private final RuleCall cBlockRuleElementBlockParserRuleCall_3_0 = (RuleCall)cBlockAssignment_3.eContents().get(0);
private final Keyword cSemicolonKeyword_4 = (Keyword)cGroup.eContents().get(4);
//// ---------------- rules
//RuleDeclaration:
// {RuleDeclaration} (modifier=RuleModifier?
// type=Type?
// name=Identifier
// '(' paramList=ParameterList? ')'
// '=')?
// conditions=RuleConditions?
// block=RuleElementBlock
// ';'?;
@Override public ParserRule getRule() { return rule; }
//{RuleDeclaration} (modifier=RuleModifier?
//type=Type?
//name=Identifier
//'(' paramList=ParameterList? ')'
//'=')?
//conditions=RuleConditions?
//block=RuleElementBlock
//';'?
public Group getGroup() { return cGroup; }
//{RuleDeclaration}
public Action getRuleDeclarationAction_0() { return cRuleDeclarationAction_0; }
//(modifier=RuleModifier?
//type=Type?
//name=Identifier
//'(' paramList=ParameterList? ')'
//'=')?
public Group getGroup_1() { return cGroup_1; }
//modifier=RuleModifier?
public Assignment getModifierAssignment_1_0() { return cModifierAssignment_1_0; }
//RuleModifier
public RuleCall getModifierRuleModifierParserRuleCall_1_0_0() { return cModifierRuleModifierParserRuleCall_1_0_0; }
//type=Type?
public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; }
//Type
public RuleCall getTypeTypeParserRuleCall_1_1_0() { return cTypeTypeParserRuleCall_1_1_0; }
//name=Identifier
public Assignment getNameAssignment_1_2() { return cNameAssignment_1_2; }
//Identifier
public RuleCall getNameIdentifierParserRuleCall_1_2_0() { return cNameIdentifierParserRuleCall_1_2_0; }
//'('
public Keyword getLeftParenthesisKeyword_1_3() { return cLeftParenthesisKeyword_1_3; }
//paramList=ParameterList?
public Assignment getParamListAssignment_1_4() { return cParamListAssignment_1_4; }
//ParameterList
public RuleCall getParamListParameterListParserRuleCall_1_4_0() { return cParamListParameterListParserRuleCall_1_4_0; }
//')'
public Keyword getRightParenthesisKeyword_1_5() { return cRightParenthesisKeyword_1_5; }
//'='
public Keyword getEqualsSignKeyword_1_6() { return cEqualsSignKeyword_1_6; }
//conditions=RuleConditions?
public Assignment getConditionsAssignment_2() { return cConditionsAssignment_2; }
//RuleConditions
public RuleCall getConditionsRuleConditionsParserRuleCall_2_0() { return cConditionsRuleConditionsParserRuleCall_2_0; }
//block=RuleElementBlock
public Assignment getBlockAssignment_3() { return cBlockAssignment_3; }
//RuleElementBlock
public RuleCall getBlockRuleElementBlockParserRuleCall_3_0() { return cBlockRuleElementBlockParserRuleCall_3_0; }
//';'?
public Keyword getSemicolonKeyword_4() { return cSemicolonKeyword_4; }
}
public class RuleConditionsElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.RuleConditions");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Action cRuleConditionsAction_0 = (Action)cGroup.eContents().get(0);
private final Assignment cPostconditionAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cPostconditionLogicalExpressionParserRuleCall_1_0 = (RuleCall)cPostconditionAssignment_1.eContents().get(0);
private final Keyword cColonKeyword_2 = (Keyword)cGroup.eContents().get(2);
private final Group cGroup_3 = (Group)cGroup.eContents().get(3);
private final Assignment cPreconditionsAssignment_3_0 = (Assignment)cGroup_3.eContents().get(0);
private final RuleCall cPreconditionsLogicalExpressionParserRuleCall_3_0_0 = (RuleCall)cPreconditionsAssignment_3_0.eContents().get(0);
private final Group cGroup_3_1 = (Group)cGroup_3.eContents().get(1);
private final Keyword cCommaKeyword_3_1_0 = (Keyword)cGroup_3_1.eContents().get(0);
private final Assignment cPreconditionsAssignment_3_1_1 = (Assignment)cGroup_3_1.eContents().get(1);
private final RuleCall cPreconditionsLogicalExpressionParserRuleCall_3_1_1_0 = (RuleCall)cPreconditionsAssignment_3_1_1.eContents().get(0);
//RuleConditions:
// {RuleConditions} postcondition+=LogicalExpression?
// ':' (preconditions+=LogicalExpression (',' preconditions+=LogicalExpression)*)?;
@Override public ParserRule getRule() { return rule; }
//{RuleConditions} postcondition+=LogicalExpression?
//':' (preconditions+=LogicalExpression (',' preconditions+=LogicalExpression)*)?
public Group getGroup() { return cGroup; }
//{RuleConditions}
public Action getRuleConditionsAction_0() { return cRuleConditionsAction_0; }
//postcondition+=LogicalExpression?
public Assignment getPostconditionAssignment_1() { return cPostconditionAssignment_1; }
//LogicalExpression
public RuleCall getPostconditionLogicalExpressionParserRuleCall_1_0() { return cPostconditionLogicalExpressionParserRuleCall_1_0; }
//':'
public Keyword getColonKeyword_2() { return cColonKeyword_2; }
//(preconditions+=LogicalExpression (',' preconditions+=LogicalExpression)*)?
public Group getGroup_3() { return cGroup_3; }
//preconditions+=LogicalExpression
public Assignment getPreconditionsAssignment_3_0() { return cPreconditionsAssignment_3_0; }
//LogicalExpression
public RuleCall getPreconditionsLogicalExpressionParserRuleCall_3_0_0() { return cPreconditionsLogicalExpressionParserRuleCall_3_0_0; }
//(',' preconditions+=LogicalExpression)*
public Group getGroup_3_1() { return cGroup_3_1; }
//','
public Keyword getCommaKeyword_3_1_0() { return cCommaKeyword_3_1_0; }
//preconditions+=LogicalExpression
public Assignment getPreconditionsAssignment_3_1_1() { return cPreconditionsAssignment_3_1_1; }
//LogicalExpression
public RuleCall getPreconditionsLogicalExpressionParserRuleCall_3_1_1_0() { return cPreconditionsLogicalExpressionParserRuleCall_3_1_1_0; }
}
public class RuleElementBlockElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.RuleElementBlock");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Action cRuleElementBlockAction_0 = (Action)cGroup.eContents().get(0);
private final Keyword cLeftCurlyBracketKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cElementsAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cElementsRuleElementParserRuleCall_2_0 = (RuleCall)cElementsAssignment_2.eContents().get(0);
private final Keyword cRightCurlyBracketKeyword_3 = (Keyword)cGroup.eContents().get(3);
//RuleElementBlock:
// {RuleElementBlock}
// '{'
// elements+=RuleElement*
// '}';
@Override public ParserRule getRule() { return rule; }
//{RuleElementBlock}
//'{'
//elements+=RuleElement*
//'}'
public Group getGroup() { return cGroup; }
//{RuleElementBlock}
public Action getRuleElementBlockAction_0() { return cRuleElementBlockAction_0; }
//'{'
public Keyword getLeftCurlyBracketKeyword_1() { return cLeftCurlyBracketKeyword_1; }
//elements+=RuleElement*
public Assignment getElementsAssignment_2() { return cElementsAssignment_2; }
//RuleElement
public RuleCall getElementsRuleElementParserRuleCall_2_0() { return cElementsRuleElementParserRuleCall_2_0; }
//'}'
public Keyword getRightCurlyBracketKeyword_3() { return cRightCurlyBracketKeyword_3; }
}
public class RuleElementElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.RuleElement");
private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1);
private final Assignment cVarDeclAssignment_0 = (Assignment)cAlternatives.eContents().get(0);
private final RuleCall cVarDeclVariableDeclarationParserRuleCall_0_0 = (RuleCall)cVarDeclAssignment_0.eContents().get(0);
private final Assignment cExprStmtAssignment_1 = (Assignment)cAlternatives.eContents().get(1);
private final RuleCall cExprStmtExpressionStatementParserRuleCall_1_0 = (RuleCall)cExprStmtAssignment_1.eContents().get(0);
private final Group cGroup_2 = (Group)cAlternatives.eContents().get(2);
private final Assignment cWhileAssignment_2_0 = (Assignment)cGroup_2.eContents().get(0);
private final RuleCall cWhileWhileParserRuleCall_2_0_0 = (RuleCall)cWhileAssignment_2_0.eContents().get(0);
private final Keyword cSemicolonKeyword_2_1 = (Keyword)cGroup_2.eContents().get(1);
private final Group cGroup_3 = (Group)cAlternatives.eContents().get(3);
private final Assignment cForAssignment_3_0 = (Assignment)cGroup_3.eContents().get(0);
private final RuleCall cForForParserRuleCall_3_0_0 = (RuleCall)cForAssignment_3_0.eContents().get(0);
private final Keyword cSemicolonKeyword_3_1 = (Keyword)cGroup_3.eContents().get(1);
//RuleElement:
// varDecl=VariableDeclaration
// | exprStmt=ExpressionStatement
// | while=While ';'?
// | for=For ';'?;
@Override public ParserRule getRule() { return rule; }
//varDecl=VariableDeclaration
//| exprStmt=ExpressionStatement
//| while=While ';'?
//| for=For ';'?
public Alternatives getAlternatives() { return cAlternatives; }
//varDecl=VariableDeclaration
public Assignment getVarDeclAssignment_0() { return cVarDeclAssignment_0; }
//VariableDeclaration
public RuleCall getVarDeclVariableDeclarationParserRuleCall_0_0() { return cVarDeclVariableDeclarationParserRuleCall_0_0; }
//exprStmt=ExpressionStatement
public Assignment getExprStmtAssignment_1() { return cExprStmtAssignment_1; }
//ExpressionStatement
public RuleCall getExprStmtExpressionStatementParserRuleCall_1_0() { return cExprStmtExpressionStatementParserRuleCall_1_0; }
//while=While ';'?
public Group getGroup_2() { return cGroup_2; }
//while=While
public Assignment getWhileAssignment_2_0() { return cWhileAssignment_2_0; }
//While
public RuleCall getWhileWhileParserRuleCall_2_0_0() { return cWhileWhileParserRuleCall_2_0_0; }
//';'?
public Keyword getSemicolonKeyword_2_1() { return cSemicolonKeyword_2_1; }
//for=For ';'?
public Group getGroup_3() { return cGroup_3; }
//for=For
public Assignment getForAssignment_3_0() { return cForAssignment_3_0; }
//For
public RuleCall getForForParserRuleCall_3_0_0() { return cForForParserRuleCall_3_0_0; }
//';'?
public Keyword getSemicolonKeyword_3_1() { return cSemicolonKeyword_3_1; }
}
public class RuleModifierElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.RuleModifier");
private final Assignment cProtectedAssignment = (Assignment)rule.eContents().get(1);
private final Keyword cProtectedProtectedKeyword_0 = (Keyword)cProtectedAssignment.eContents().get(0);
//RuleModifier:
// protected='protected';
@Override public ParserRule getRule() { return rule; }
//protected='protected'
public Assignment getProtectedAssignment() { return cProtectedAssignment; }
//'protected'
public Keyword getProtectedProtectedKeyword_0() { return cProtectedProtectedKeyword_0; }
}
public class ExpressionStatementElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.ExpressionStatement");
private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1);
private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0);
private final Group cGroup_0_0 = (Group)cGroup_0.eContents().get(0);
private final Assignment cVarAssignment_0_0_0 = (Assignment)cGroup_0_0.eContents().get(0);
private final RuleCall cVarIdentifierParserRuleCall_0_0_0_0 = (RuleCall)cVarAssignment_0_0_0.eContents().get(0);
private final Group cGroup_0_0_1 = (Group)cGroup_0_0.eContents().get(1);
private final Keyword cFullStopKeyword_0_0_1_0 = (Keyword)cGroup_0_0_1.eContents().get(0);
private final Assignment cFieldAssignment_0_0_1_1 = (Assignment)cGroup_0_0_1.eContents().get(1);
private final RuleCall cFieldIdentifierParserRuleCall_0_0_1_1_0 = (RuleCall)cFieldAssignment_0_0_1_1.eContents().get(0);
private final Keyword cEqualsSignKeyword_0_0_2 = (Keyword)cGroup_0_0.eContents().get(2);
private final Assignment cExprAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1);
private final RuleCall cExprExpressionParserRuleCall_0_1_0 = (RuleCall)cExprAssignment_0_1.eContents().get(0);
private final Keyword cSemicolonKeyword_0_2 = (Keyword)cGroup_0.eContents().get(2);
private final Group cGroup_1 = (Group)cAlternatives.eContents().get(1);
private final Assignment cAltAssignment_1_0 = (Assignment)cGroup_1.eContents().get(0);
private final RuleCall cAltAlternativeParserRuleCall_1_0_0 = (RuleCall)cAltAssignment_1_0.eContents().get(0);
private final Keyword cSemicolonKeyword_1_1 = (Keyword)cGroup_1.eContents().get(1);
//// ----------------------- overriding and extending parts of the expression grammar -------------------
//ExpressionStatement:
// (var=Identifier ('.' field=Identifier)? '=')?
// expr=Expression ';' | alt=Alternative ';'?;
@Override public ParserRule getRule() { return rule; }
//(var=Identifier ('.' field=Identifier)? '=')?
//expr=Expression ';' | alt=Alternative ';'?
public Alternatives getAlternatives() { return cAlternatives; }
//(var=Identifier ('.' field=Identifier)? '=')?
//expr=Expression ';'
public Group getGroup_0() { return cGroup_0; }
//(var=Identifier ('.' field=Identifier)? '=')?
public Group getGroup_0_0() { return cGroup_0_0; }
//var=Identifier
public Assignment getVarAssignment_0_0_0() { return cVarAssignment_0_0_0; }
//Identifier
public RuleCall getVarIdentifierParserRuleCall_0_0_0_0() { return cVarIdentifierParserRuleCall_0_0_0_0; }
//('.' field=Identifier)?
public Group getGroup_0_0_1() { return cGroup_0_0_1; }
//'.'
public Keyword getFullStopKeyword_0_0_1_0() { return cFullStopKeyword_0_0_1_0; }
//field=Identifier
public Assignment getFieldAssignment_0_0_1_1() { return cFieldAssignment_0_0_1_1; }
//Identifier
public RuleCall getFieldIdentifierParserRuleCall_0_0_1_1_0() { return cFieldIdentifierParserRuleCall_0_0_1_1_0; }
//'='
public Keyword getEqualsSignKeyword_0_0_2() { return cEqualsSignKeyword_0_0_2; }
//expr=Expression
public Assignment getExprAssignment_0_1() { return cExprAssignment_0_1; }
//Expression
public RuleCall getExprExpressionParserRuleCall_0_1_0() { return cExprExpressionParserRuleCall_0_1_0; }
//';'
public Keyword getSemicolonKeyword_0_2() { return cSemicolonKeyword_0_2; }
//alt=Alternative ';'?
public Group getGroup_1() { return cGroup_1; }
//alt=Alternative
public Assignment getAltAssignment_1_0() { return cAltAssignment_1_0; }
//Alternative
public RuleCall getAltAlternativeParserRuleCall_1_0_0() { return cAltAlternativeParserRuleCall_1_0_0; }
//';'?
public Keyword getSemicolonKeyword_1_1() { return cSemicolonKeyword_1_1; }
}
public class PrimaryExpressionElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.PrimaryExpression");
private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1);
private final Assignment cOtherExAssignment_0 = (Assignment)cAlternatives.eContents().get(0);
private final RuleCall cOtherExExpressionOrQualifiedExecutionParserRuleCall_0_0 = (RuleCall)cOtherExAssignment_0.eContents().get(0);
private final Assignment cUnqExAssignment_1 = (Assignment)cAlternatives.eContents().get(1);
private final RuleCall cUnqExUnqualifiedExecutionParserRuleCall_1_0 = (RuleCall)cUnqExAssignment_1.eContents().get(0);
private final Assignment cSuperExAssignment_2 = (Assignment)cAlternatives.eContents().get(2);
private final RuleCall cSuperExSuperExecutionParserRuleCall_2_0 = (RuleCall)cSuperExAssignment_2.eContents().get(0);
private final Assignment cSysExAssignment_3 = (Assignment)cAlternatives.eContents().get(3);
private final RuleCall cSysExSystemExecutionParserRuleCall_3_0 = (RuleCall)cSysExAssignment_3.eContents().get(0);
private final Assignment cMapAssignment_4 = (Assignment)cAlternatives.eContents().get(4);
private final RuleCall cMapMapParserRuleCall_4_0 = (RuleCall)cMapAssignment_4.eContents().get(0);
private final Assignment cJoinAssignment_5 = (Assignment)cAlternatives.eContents().get(5);
private final RuleCall cJoinJoinParserRuleCall_5_0 = (RuleCall)cJoinAssignment_5.eContents().get(0);
private final Assignment cInstantiateAssignment_6 = (Assignment)cAlternatives.eContents().get(6);
private final RuleCall cInstantiateInstantiateParserRuleCall_6_0 = (RuleCall)cInstantiateAssignment_6.eContents().get(0);
private final Assignment cNewExAssignment_7 = (Assignment)cAlternatives.eContents().get(7);
private final RuleCall cNewExConstructorExecutionParserRuleCall_7_0 = (RuleCall)cNewExAssignment_7.eContents().get(0);
//PrimaryExpression:
// otherEx=ExpressionOrQualifiedExecution
// | unqEx=UnqualifiedExecution
// | superEx=SuperExecution
// | sysEx=SystemExecution
// | map=Map
// | join=Join
// | instantiate=Instantiate
// | newEx=ConstructorExecution;
@Override public ParserRule getRule() { return rule; }
//otherEx=ExpressionOrQualifiedExecution
//| unqEx=UnqualifiedExecution
//| superEx=SuperExecution
//| sysEx=SystemExecution
//| map=Map
//| join=Join
//| instantiate=Instantiate
//| newEx=ConstructorExecution
public Alternatives getAlternatives() { return cAlternatives; }
//otherEx=ExpressionOrQualifiedExecution
public Assignment getOtherExAssignment_0() { return cOtherExAssignment_0; }
//ExpressionOrQualifiedExecution
public RuleCall getOtherExExpressionOrQualifiedExecutionParserRuleCall_0_0() { return cOtherExExpressionOrQualifiedExecutionParserRuleCall_0_0; }
//unqEx=UnqualifiedExecution
public Assignment getUnqExAssignment_1() { return cUnqExAssignment_1; }
//UnqualifiedExecution
public RuleCall getUnqExUnqualifiedExecutionParserRuleCall_1_0() { return cUnqExUnqualifiedExecutionParserRuleCall_1_0; }
//superEx=SuperExecution
public Assignment getSuperExAssignment_2() { return cSuperExAssignment_2; }
//SuperExecution
public RuleCall getSuperExSuperExecutionParserRuleCall_2_0() { return cSuperExSuperExecutionParserRuleCall_2_0; }
//sysEx=SystemExecution
public Assignment getSysExAssignment_3() { return cSysExAssignment_3; }
//SystemExecution
public RuleCall getSysExSystemExecutionParserRuleCall_3_0() { return cSysExSystemExecutionParserRuleCall_3_0; }
//map=Map
public Assignment getMapAssignment_4() { return cMapAssignment_4; }
//Map
public RuleCall getMapMapParserRuleCall_4_0() { return cMapMapParserRuleCall_4_0; }
//join=Join
public Assignment getJoinAssignment_5() { return cJoinAssignment_5; }
//Join
public RuleCall getJoinJoinParserRuleCall_5_0() { return cJoinJoinParserRuleCall_5_0; }
//instantiate=Instantiate
public Assignment getInstantiateAssignment_6() { return cInstantiateAssignment_6; }
//Instantiate
public RuleCall getInstantiateInstantiateParserRuleCall_6_0() { return cInstantiateInstantiateParserRuleCall_6_0; }
//newEx=ConstructorExecution
public Assignment getNewExAssignment_7() { return cNewExAssignment_7; }
//ConstructorExecution
public RuleCall getNewExConstructorExecutionParserRuleCall_7_0() { return cNewExConstructorExecutionParserRuleCall_7_0; }
}
public class InstantiateElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.Instantiate");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cInstantiateKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Alternatives cAlternatives_1 = (Alternatives)cGroup.eContents().get(1);
private final Assignment cProjectAssignment_1_0 = (Assignment)cAlternatives_1.eContents().get(0);
private final RuleCall cProjectIdentifierParserRuleCall_1_0_0 = (RuleCall)cProjectAssignment_1_0.eContents().get(0);
private final Assignment cRuleNameAssignment_1_1 = (Assignment)cAlternatives_1.eContents().get(1);
private final RuleCall cRuleNameSTRINGTerminalRuleCall_1_1_0 = (RuleCall)cRuleNameAssignment_1_1.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_2 = (Keyword)cGroup.eContents().get(2);
private final Assignment cParamAssignment_3 = (Assignment)cGroup.eContents().get(3);
private final RuleCall cParamArgumentListParserRuleCall_3_0 = (RuleCall)cParamAssignment_3.eContents().get(0);
private final Keyword cRightParenthesisKeyword_4 = (Keyword)cGroup.eContents().get(4);
private final Assignment cVersionSpecAssignment_5 = (Assignment)cGroup.eContents().get(5);
private final RuleCall cVersionSpecVersionSpecParserRuleCall_5_0 = (RuleCall)cVersionSpecAssignment_5.eContents().get(0);
//Instantiate:
// 'instantiate' (project=Identifier | ruleName=STRING)
// '(' param=ArgumentList? ')' versionSpec=VersionSpec?;
@Override public ParserRule getRule() { return rule; }
//'instantiate' (project=Identifier | ruleName=STRING)
//'(' param=ArgumentList? ')' versionSpec=VersionSpec?
public Group getGroup() { return cGroup; }
//'instantiate'
public Keyword getInstantiateKeyword_0() { return cInstantiateKeyword_0; }
//(project=Identifier | ruleName=STRING)
public Alternatives getAlternatives_1() { return cAlternatives_1; }
//project=Identifier
public Assignment getProjectAssignment_1_0() { return cProjectAssignment_1_0; }
//Identifier
public RuleCall getProjectIdentifierParserRuleCall_1_0_0() { return cProjectIdentifierParserRuleCall_1_0_0; }
//ruleName=STRING
public Assignment getRuleNameAssignment_1_1() { return cRuleNameAssignment_1_1; }
//STRING
public RuleCall getRuleNameSTRINGTerminalRuleCall_1_1_0() { return cRuleNameSTRINGTerminalRuleCall_1_1_0; }
//'('
public Keyword getLeftParenthesisKeyword_2() { return cLeftParenthesisKeyword_2; }
//param=ArgumentList?
public Assignment getParamAssignment_3() { return cParamAssignment_3; }
//ArgumentList
public RuleCall getParamArgumentListParserRuleCall_3_0() { return cParamArgumentListParserRuleCall_3_0; }
//')'
public Keyword getRightParenthesisKeyword_4() { return cRightParenthesisKeyword_4; }
//versionSpec=VersionSpec?
public Assignment getVersionSpecAssignment_5() { return cVersionSpecAssignment_5; }
//VersionSpec
public RuleCall getVersionSpecVersionSpecParserRuleCall_5_0() { return cVersionSpecVersionSpecParserRuleCall_5_0; }
}
public class LoopVariableElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.LoopVariable");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cTypeAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final RuleCall cTypeTypeParserRuleCall_0_0 = (RuleCall)cTypeAssignment_0.eContents().get(0);
private final Assignment cVarAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cVarIdentifierParserRuleCall_1_0 = (RuleCall)cVarAssignment_1.eContents().get(0);
//LoopVariable:
// type=Type?
// var=Identifier;
@Override public ParserRule getRule() { return rule; }
//type=Type?
//var=Identifier
public Group getGroup() { return cGroup; }
//type=Type?
public Assignment getTypeAssignment_0() { return cTypeAssignment_0; }
//Type
public RuleCall getTypeTypeParserRuleCall_0_0() { return cTypeTypeParserRuleCall_0_0; }
//var=Identifier
public Assignment getVarAssignment_1() { return cVarAssignment_1; }
//Identifier
public RuleCall getVarIdentifierParserRuleCall_1_0() { return cVarIdentifierParserRuleCall_1_0; }
}
public class MapElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.Map");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cMapKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cVarAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cVarLoopVariableParserRuleCall_2_0 = (RuleCall)cVarAssignment_2.eContents().get(0);
private final Group cGroup_3 = (Group)cGroup.eContents().get(3);
private final Keyword cCommaKeyword_3_0 = (Keyword)cGroup_3.eContents().get(0);
private final Assignment cVarAssignment_3_1 = (Assignment)cGroup_3.eContents().get(1);
private final RuleCall cVarLoopVariableParserRuleCall_3_1_0 = (RuleCall)cVarAssignment_3_1.eContents().get(0);
private final Assignment cSeparatorAssignment_4 = (Assignment)cGroup.eContents().get(4);
private final Alternatives cSeparatorAlternatives_4_0 = (Alternatives)cSeparatorAssignment_4.eContents().get(0);
private final Keyword cSeparatorEqualsSignKeyword_4_0_0 = (Keyword)cSeparatorAlternatives_4_0.eContents().get(0);
private final Keyword cSeparatorColonKeyword_4_0_1 = (Keyword)cSeparatorAlternatives_4_0.eContents().get(1);
private final Assignment cExprAssignment_5 = (Assignment)cGroup.eContents().get(5);
private final RuleCall cExprExpressionParserRuleCall_5_0 = (RuleCall)cExprAssignment_5.eContents().get(0);
private final Keyword cRightParenthesisKeyword_6 = (Keyword)cGroup.eContents().get(6);
private final Assignment cBlockAssignment_7 = (Assignment)cGroup.eContents().get(7);
private final RuleCall cBlockRuleElementBlockParserRuleCall_7_0 = (RuleCall)cBlockAssignment_7.eContents().get(0);
//Map:
// 'map' '(' var+=LoopVariable (',' var+=LoopVariable)* separator=('=' | ':') expr=Expression ')'
// block=RuleElementBlock;
@Override public ParserRule getRule() { return rule; }
//'map' '(' var+=LoopVariable (',' var+=LoopVariable)* separator=('=' | ':') expr=Expression ')'
//block=RuleElementBlock
public Group getGroup() { return cGroup; }
//'map'
public Keyword getMapKeyword_0() { return cMapKeyword_0; }
//'('
public Keyword getLeftParenthesisKeyword_1() { return cLeftParenthesisKeyword_1; }
//var+=LoopVariable
public Assignment getVarAssignment_2() { return cVarAssignment_2; }
//LoopVariable
public RuleCall getVarLoopVariableParserRuleCall_2_0() { return cVarLoopVariableParserRuleCall_2_0; }
//(',' var+=LoopVariable)*
public Group getGroup_3() { return cGroup_3; }
//','
public Keyword getCommaKeyword_3_0() { return cCommaKeyword_3_0; }
//var+=LoopVariable
public Assignment getVarAssignment_3_1() { return cVarAssignment_3_1; }
//LoopVariable
public RuleCall getVarLoopVariableParserRuleCall_3_1_0() { return cVarLoopVariableParserRuleCall_3_1_0; }
//separator=('=' | ':')
public Assignment getSeparatorAssignment_4() { return cSeparatorAssignment_4; }
//('=' | ':')
public Alternatives getSeparatorAlternatives_4_0() { return cSeparatorAlternatives_4_0; }
//'='
public Keyword getSeparatorEqualsSignKeyword_4_0_0() { return cSeparatorEqualsSignKeyword_4_0_0; }
//':'
public Keyword getSeparatorColonKeyword_4_0_1() { return cSeparatorColonKeyword_4_0_1; }
//expr=Expression
public Assignment getExprAssignment_5() { return cExprAssignment_5; }
//Expression
public RuleCall getExprExpressionParserRuleCall_5_0() { return cExprExpressionParserRuleCall_5_0; }
//')'
public Keyword getRightParenthesisKeyword_6() { return cRightParenthesisKeyword_6; }
//block=RuleElementBlock
public Assignment getBlockAssignment_7() { return cBlockAssignment_7; }
//RuleElementBlock
public RuleCall getBlockRuleElementBlockParserRuleCall_7_0() { return cBlockRuleElementBlockParserRuleCall_7_0; }
}
public class ForElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.For");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cForKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cVarAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cVarLoopVariableParserRuleCall_2_0 = (RuleCall)cVarAssignment_2.eContents().get(0);
private final Group cGroup_3 = (Group)cGroup.eContents().get(3);
private final Keyword cCommaKeyword_3_0 = (Keyword)cGroup_3.eContents().get(0);
private final Assignment cVarAssignment_3_1 = (Assignment)cGroup_3.eContents().get(1);
private final RuleCall cVarLoopVariableParserRuleCall_3_1_0 = (RuleCall)cVarAssignment_3_1.eContents().get(0);
private final Assignment cSeparatorAssignment_4 = (Assignment)cGroup.eContents().get(4);
private final Alternatives cSeparatorAlternatives_4_0 = (Alternatives)cSeparatorAssignment_4.eContents().get(0);
private final Keyword cSeparatorEqualsSignKeyword_4_0_0 = (Keyword)cSeparatorAlternatives_4_0.eContents().get(0);
private final Keyword cSeparatorColonKeyword_4_0_1 = (Keyword)cSeparatorAlternatives_4_0.eContents().get(1);
private final Assignment cExprAssignment_5 = (Assignment)cGroup.eContents().get(5);
private final RuleCall cExprExpressionParserRuleCall_5_0 = (RuleCall)cExprAssignment_5.eContents().get(0);
private final Keyword cRightParenthesisKeyword_6 = (Keyword)cGroup.eContents().get(6);
private final Assignment cBlockAssignment_7 = (Assignment)cGroup.eContents().get(7);
private final RuleCall cBlockRuleElementBlockParserRuleCall_7_0 = (RuleCall)cBlockAssignment_7.eContents().get(0);
//For:
// 'for' '(' var+=LoopVariable (',' var+=LoopVariable)* separator=('=' | ':') expr=Expression ')'
// block=RuleElementBlock;
@Override public ParserRule getRule() { return rule; }
//'for' '(' var+=LoopVariable (',' var+=LoopVariable)* separator=('=' | ':') expr=Expression ')'
//block=RuleElementBlock
public Group getGroup() { return cGroup; }
//'for'
public Keyword getForKeyword_0() { return cForKeyword_0; }
//'('
public Keyword getLeftParenthesisKeyword_1() { return cLeftParenthesisKeyword_1; }
//var+=LoopVariable
public Assignment getVarAssignment_2() { return cVarAssignment_2; }
//LoopVariable
public RuleCall getVarLoopVariableParserRuleCall_2_0() { return cVarLoopVariableParserRuleCall_2_0; }
//(',' var+=LoopVariable)*
public Group getGroup_3() { return cGroup_3; }
//','
public Keyword getCommaKeyword_3_0() { return cCommaKeyword_3_0; }
//var+=LoopVariable
public Assignment getVarAssignment_3_1() { return cVarAssignment_3_1; }
//LoopVariable
public RuleCall getVarLoopVariableParserRuleCall_3_1_0() { return cVarLoopVariableParserRuleCall_3_1_0; }
//separator=('=' | ':')
public Assignment getSeparatorAssignment_4() { return cSeparatorAssignment_4; }
//('=' | ':')
public Alternatives getSeparatorAlternatives_4_0() { return cSeparatorAlternatives_4_0; }
//'='
public Keyword getSeparatorEqualsSignKeyword_4_0_0() { return cSeparatorEqualsSignKeyword_4_0_0; }
//':'
public Keyword getSeparatorColonKeyword_4_0_1() { return cSeparatorColonKeyword_4_0_1; }
//expr=Expression
public Assignment getExprAssignment_5() { return cExprAssignment_5; }
//Expression
public RuleCall getExprExpressionParserRuleCall_5_0() { return cExprExpressionParserRuleCall_5_0; }
//')'
public Keyword getRightParenthesisKeyword_6() { return cRightParenthesisKeyword_6; }
//block=RuleElementBlock
public Assignment getBlockAssignment_7() { return cBlockAssignment_7; }
//RuleElementBlock
public RuleCall getBlockRuleElementBlockParserRuleCall_7_0() { return cBlockRuleElementBlockParserRuleCall_7_0; }
}
public class WhileElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.While");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cWhileKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cExprAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cExprExpressionParserRuleCall_2_0 = (RuleCall)cExprAssignment_2.eContents().get(0);
private final Keyword cRightParenthesisKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Assignment cBlockAssignment_4 = (Assignment)cGroup.eContents().get(4);
private final RuleCall cBlockRuleElementBlockParserRuleCall_4_0 = (RuleCall)cBlockAssignment_4.eContents().get(0);
//While:
// 'while' '(' expr=Expression ')'
// block=RuleElementBlock;
@Override public ParserRule getRule() { return rule; }
//'while' '(' expr=Expression ')'
//block=RuleElementBlock
public Group getGroup() { return cGroup; }
//'while'
public Keyword getWhileKeyword_0() { return cWhileKeyword_0; }
//'('
public Keyword getLeftParenthesisKeyword_1() { return cLeftParenthesisKeyword_1; }
//expr=Expression
public Assignment getExprAssignment_2() { return cExprAssignment_2; }
//Expression
public RuleCall getExprExpressionParserRuleCall_2_0() { return cExprExpressionParserRuleCall_2_0; }
//')'
public Keyword getRightParenthesisKeyword_3() { return cRightParenthesisKeyword_3; }
//block=RuleElementBlock
public Assignment getBlockAssignment_4() { return cBlockAssignment_4; }
//RuleElementBlock
public RuleCall getBlockRuleElementBlockParserRuleCall_4_0() { return cBlockRuleElementBlockParserRuleCall_4_0; }
}
public class AlternativeElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.Alternative");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cIfKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cExprAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cExprExpressionParserRuleCall_2_0 = (RuleCall)cExprAssignment_2.eContents().get(0);
private final Keyword cRightParenthesisKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Assignment cIfAssignment_4 = (Assignment)cGroup.eContents().get(4);
private final RuleCall cIfStatementOrBlockParserRuleCall_4_0 = (RuleCall)cIfAssignment_4.eContents().get(0);
private final Group cGroup_5 = (Group)cGroup.eContents().get(5);
private final Keyword cElseKeyword_5_0 = (Keyword)cGroup_5.eContents().get(0);
private final Assignment cElseAssignment_5_1 = (Assignment)cGroup_5.eContents().get(1);
private final RuleCall cElseStatementOrBlockParserRuleCall_5_1_0 = (RuleCall)cElseAssignment_5_1.eContents().get(0);
//Alternative:
// 'if' '(' expr=Expression ')' if=StatementOrBlock (=>'else' else=StatementOrBlock)?;
@Override public ParserRule getRule() { return rule; }
//'if' '(' expr=Expression ')' if=StatementOrBlock (=>'else' else=StatementOrBlock)?
public Group getGroup() { return cGroup; }
//'if'
public Keyword getIfKeyword_0() { return cIfKeyword_0; }
//'('
public Keyword getLeftParenthesisKeyword_1() { return cLeftParenthesisKeyword_1; }
//expr=Expression
public Assignment getExprAssignment_2() { return cExprAssignment_2; }
//Expression
public RuleCall getExprExpressionParserRuleCall_2_0() { return cExprExpressionParserRuleCall_2_0; }
//')'
public Keyword getRightParenthesisKeyword_3() { return cRightParenthesisKeyword_3; }
//if=StatementOrBlock
public Assignment getIfAssignment_4() { return cIfAssignment_4; }
//StatementOrBlock
public RuleCall getIfStatementOrBlockParserRuleCall_4_0() { return cIfStatementOrBlockParserRuleCall_4_0; }
//(=>'else' else=StatementOrBlock)?
public Group getGroup_5() { return cGroup_5; }
//=>'else'
public Keyword getElseKeyword_5_0() { return cElseKeyword_5_0; }
//else=StatementOrBlock
public Assignment getElseAssignment_5_1() { return cElseAssignment_5_1; }
//StatementOrBlock
public RuleCall getElseStatementOrBlockParserRuleCall_5_1_0() { return cElseStatementOrBlockParserRuleCall_5_1_0; }
}
public class StatementOrBlockElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.StatementOrBlock");
private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1);
private final Assignment cExStmtAssignment_0 = (Assignment)cAlternatives.eContents().get(0);
private final RuleCall cExStmtExpressionStatementParserRuleCall_0_0 = (RuleCall)cExStmtAssignment_0.eContents().get(0);
private final Assignment cBlockAssignment_1 = (Assignment)cAlternatives.eContents().get(1);
private final RuleCall cBlockRuleElementBlockParserRuleCall_1_0 = (RuleCall)cBlockAssignment_1.eContents().get(0);
//StatementOrBlock:
// exStmt=ExpressionStatement | block=RuleElementBlock;
@Override public ParserRule getRule() { return rule; }
//exStmt=ExpressionStatement | block=RuleElementBlock
public Alternatives getAlternatives() { return cAlternatives; }
//exStmt=ExpressionStatement
public Assignment getExStmtAssignment_0() { return cExStmtAssignment_0; }
//ExpressionStatement
public RuleCall getExStmtExpressionStatementParserRuleCall_0_0() { return cExStmtExpressionStatementParserRuleCall_0_0; }
//block=RuleElementBlock
public Assignment getBlockAssignment_1() { return cBlockAssignment_1; }
//RuleElementBlock
public RuleCall getBlockRuleElementBlockParserRuleCall_1_0() { return cBlockRuleElementBlockParserRuleCall_1_0; }
}
public class JoinElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.Join");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cJoinKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_1 = (Keyword)cGroup.eContents().get(1);
private final Assignment cVar1Assignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cVar1JoinVariableParserRuleCall_2_0 = (RuleCall)cVar1Assignment_2.eContents().get(0);
private final Keyword cCommaKeyword_3 = (Keyword)cGroup.eContents().get(3);
private final Assignment cVar2Assignment_4 = (Assignment)cGroup.eContents().get(4);
private final RuleCall cVar2JoinVariableParserRuleCall_4_0 = (RuleCall)cVar2Assignment_4.eContents().get(0);
private final Keyword cRightParenthesisKeyword_5 = (Keyword)cGroup.eContents().get(5);
private final Group cGroup_6 = (Group)cGroup.eContents().get(6);
private final Keyword cWithKeyword_6_0 = (Keyword)cGroup_6.eContents().get(0);
private final Keyword cLeftParenthesisKeyword_6_1 = (Keyword)cGroup_6.eContents().get(1);
private final Assignment cConditionAssignment_6_2 = (Assignment)cGroup_6.eContents().get(2);
private final RuleCall cConditionExpressionParserRuleCall_6_2_0 = (RuleCall)cConditionAssignment_6_2.eContents().get(0);
private final Keyword cRightParenthesisKeyword_6_3 = (Keyword)cGroup_6.eContents().get(3);
//Join:
// 'join' '('
// var1=JoinVariable ','
// var2=JoinVariable ')' ('with'
// '(' condition=Expression ')')?;
@Override public ParserRule getRule() { return rule; }
//'join' '('
//var1=JoinVariable ','
//var2=JoinVariable ')' ('with'
//'(' condition=Expression ')')?
public Group getGroup() { return cGroup; }
//'join'
public Keyword getJoinKeyword_0() { return cJoinKeyword_0; }
//'('
public Keyword getLeftParenthesisKeyword_1() { return cLeftParenthesisKeyword_1; }
//var1=JoinVariable
public Assignment getVar1Assignment_2() { return cVar1Assignment_2; }
//JoinVariable
public RuleCall getVar1JoinVariableParserRuleCall_2_0() { return cVar1JoinVariableParserRuleCall_2_0; }
//','
public Keyword getCommaKeyword_3() { return cCommaKeyword_3; }
//var2=JoinVariable
public Assignment getVar2Assignment_4() { return cVar2Assignment_4; }
//JoinVariable
public RuleCall getVar2JoinVariableParserRuleCall_4_0() { return cVar2JoinVariableParserRuleCall_4_0; }
//')'
public Keyword getRightParenthesisKeyword_5() { return cRightParenthesisKeyword_5; }
//('with'
//'(' condition=Expression ')')?
public Group getGroup_6() { return cGroup_6; }
//'with'
public Keyword getWithKeyword_6_0() { return cWithKeyword_6_0; }
//'('
public Keyword getLeftParenthesisKeyword_6_1() { return cLeftParenthesisKeyword_6_1; }
//condition=Expression
public Assignment getConditionAssignment_6_2() { return cConditionAssignment_6_2; }
//Expression
public RuleCall getConditionExpressionParserRuleCall_6_2_0() { return cConditionExpressionParserRuleCall_6_2_0; }
//')'
public Keyword getRightParenthesisKeyword_6_3() { return cRightParenthesisKeyword_6_3; }
}
public class JoinVariableElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.JoinVariable");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Assignment cExclAssignment_0 = (Assignment)cGroup.eContents().get(0);
private final Keyword cExclExcludeKeyword_0_0 = (Keyword)cExclAssignment_0.eContents().get(0);
private final Assignment cVarAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cVarIdentifierParserRuleCall_1_0 = (RuleCall)cVarAssignment_1.eContents().get(0);
private final Keyword cColonKeyword_2 = (Keyword)cGroup.eContents().get(2);
private final Assignment cExprAssignment_3 = (Assignment)cGroup.eContents().get(3);
private final RuleCall cExprExpressionParserRuleCall_3_0 = (RuleCall)cExprAssignment_3.eContents().get(0);
//JoinVariable:
// excl='exclude'? var=Identifier
// ':'
// expr=Expression;
@Override public ParserRule getRule() { return rule; }
//excl='exclude'? var=Identifier
//':'
//expr=Expression
public Group getGroup() { return cGroup; }
//excl='exclude'?
public Assignment getExclAssignment_0() { return cExclAssignment_0; }
//'exclude'
public Keyword getExclExcludeKeyword_0_0() { return cExclExcludeKeyword_0_0; }
//var=Identifier
public Assignment getVarAssignment_1() { return cVarAssignment_1; }
//Identifier
public RuleCall getVarIdentifierParserRuleCall_1_0() { return cVarIdentifierParserRuleCall_1_0; }
//':'
public Keyword getColonKeyword_2() { return cColonKeyword_2; }
//expr=Expression
public Assignment getExprAssignment_3() { return cExprAssignment_3; }
//Expression
public RuleCall getExprExpressionParserRuleCall_3_0() { return cExprExpressionParserRuleCall_3_0; }
}
public class SystemExecutionElements extends AbstractParserRuleElementFinder {
private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "de.uni_hildesheim.sse.VilBuildLanguage.SystemExecution");
private final Group cGroup = (Group)rule.eContents().get(1);
private final Keyword cExecuteKeyword_0 = (Keyword)cGroup.eContents().get(0);
private final Assignment cCallAssignment_1 = (Assignment)cGroup.eContents().get(1);
private final RuleCall cCallCallParserRuleCall_1_0 = (RuleCall)cCallAssignment_1.eContents().get(0);
private final Assignment cCallsAssignment_2 = (Assignment)cGroup.eContents().get(2);
private final RuleCall cCallsSubCallParserRuleCall_2_0 = (RuleCall)cCallsAssignment_2.eContents().get(0);
//SystemExecution:
// 'execute' call=Call calls+=SubCall*;
@Override public ParserRule getRule() { return rule; }
//'execute' call=Call calls+=SubCall*
public Group getGroup() { return cGroup; }
//'execute'
public Keyword getExecuteKeyword_0() { return cExecuteKeyword_0; }
//call=Call
public Assignment getCallAssignment_1() { return cCallAssignment_1; }
//Call
public RuleCall getCallCallParserRuleCall_1_0() { return cCallCallParserRuleCall_1_0; }
//calls+=SubCall*
public Assignment getCallsAssignment_2() { return cCallsAssignment_2; }
//SubCall
public RuleCall getCallsSubCallParserRuleCall_2_0() { return cCallsSubCallParserRuleCall_2_0; }
}
private final ImplementationUnitElements pImplementationUnit;
private final RequireElements pRequire;
private final LanguageUnitElements pLanguageUnit;
private final ScriptParentDeclElements pScriptParentDecl;
private final LoadPropertiesElements pLoadProperties;
private final ScriptContentsElements pScriptContents;
private final RuleDeclarationElements pRuleDeclaration;
private final RuleConditionsElements pRuleConditions;
private final RuleElementBlockElements pRuleElementBlock;
private final RuleElementElements pRuleElement;
private final RuleModifierElements pRuleModifier;
private final ExpressionStatementElements pExpressionStatement;
private final PrimaryExpressionElements pPrimaryExpression;
private final InstantiateElements pInstantiate;
private final LoopVariableElements pLoopVariable;
private final MapElements pMap;
private final ForElements pFor;
private final WhileElements pWhile;
private final AlternativeElements pAlternative;
private final StatementOrBlockElements pStatementOrBlock;
private final JoinElements pJoin;
private final JoinVariableElements pJoinVariable;
private final SystemExecutionElements pSystemExecution;
private final Grammar grammar;
private final ExpressionDslGrammarAccess gaExpressionDsl;
@Inject
public VilBuildLanguageGrammarAccess(GrammarProvider grammarProvider,
ExpressionDslGrammarAccess gaExpressionDsl) {
this.grammar = internalFindGrammar(grammarProvider);
this.gaExpressionDsl = gaExpressionDsl;
this.pImplementationUnit = new ImplementationUnitElements();
this.pRequire = new RequireElements();
this.pLanguageUnit = new LanguageUnitElements();
this.pScriptParentDecl = new ScriptParentDeclElements();
this.pLoadProperties = new LoadPropertiesElements();
this.pScriptContents = new ScriptContentsElements();
this.pRuleDeclaration = new RuleDeclarationElements();
this.pRuleConditions = new RuleConditionsElements();
this.pRuleElementBlock = new RuleElementBlockElements();
this.pRuleElement = new RuleElementElements();
this.pRuleModifier = new RuleModifierElements();
this.pExpressionStatement = new ExpressionStatementElements();
this.pPrimaryExpression = new PrimaryExpressionElements();
this.pInstantiate = new InstantiateElements();
this.pLoopVariable = new LoopVariableElements();
this.pMap = new MapElements();
this.pFor = new ForElements();
this.pWhile = new WhileElements();
this.pAlternative = new AlternativeElements();
this.pStatementOrBlock = new StatementOrBlockElements();
this.pJoin = new JoinElements();
this.pJoinVariable = new JoinVariableElements();
this.pSystemExecution = new SystemExecutionElements();
}
protected Grammar internalFindGrammar(GrammarProvider grammarProvider) {
Grammar grammar = grammarProvider.getGrammar(this);
while (grammar != null) {
if ("de.uni_hildesheim.sse.VilBuildLanguage".equals(grammar.getName())) {
return grammar;
}
List<Grammar> grammars = grammar.getUsedGrammars();
if (!grammars.isEmpty()) {
grammar = grammars.iterator().next();
} else {
return null;
}
}
return grammar;
}
@Override
public Grammar getGrammar() {
return grammar;
}
public ExpressionDslGrammarAccess getExpressionDslGrammarAccess() {
return gaExpressionDsl;
}
//ImplementationUnit:
// {ImplementationUnit} imports+=Import*
// requires+=Require*
// scripts+=LanguageUnit*;
public ImplementationUnitElements getImplementationUnitAccess() {
return pImplementationUnit;
}
public ParserRule getImplementationUnitRule() {
return getImplementationUnitAccess().getRule();
}
//Require:
// // here fqn because this may reference a specific project (of an external project)
// 'requireVTL' name=STRING versionSpec=VersionSpec
// ';';
public RequireElements getRequireAccess() {
return pRequire;
}
public ParserRule getRequireRule() {
return getRequireAccess().getRule();
}
//// ---------------- project header
//LanguageUnit:
// advices+=Advice*
// 'vilScript' name=Identifier
// '(' param=ParameterList? ')'
// parent=ScriptParentDecl?
// '{'
// version=VersionStmt?
// loadProperties+=LoadProperties*
// contents=ScriptContents
// '}' ';'?;
public LanguageUnitElements getLanguageUnitAccess() {
return pLanguageUnit;
}
public ParserRule getLanguageUnitRule() {
return getLanguageUnitAccess().getRule();
}
//ScriptParentDecl:
// 'extends' name=Identifier // here identifier because this references a complete project
//;
public ScriptParentDeclElements getScriptParentDeclAccess() {
return pScriptParentDecl;
}
public ParserRule getScriptParentDeclRule() {
return getScriptParentDeclAccess().getRule();
}
//LoadProperties:
// 'load' 'properties' path=STRING // here string because this references a file
// ';';
public LoadPropertiesElements getLoadPropertiesAccess() {
return pLoadProperties;
}
public ParserRule getLoadPropertiesRule() {
return getLoadPropertiesAccess().getRule();
}
//ScriptContents:
// {ScriptContents} (elements+=VariableDeclaration
// | elements+=Compound
// | elements+=TypeDef
// | elements+=RuleDeclaration)*;
public ScriptContentsElements getScriptContentsAccess() {
return pScriptContents;
}
public ParserRule getScriptContentsRule() {
return getScriptContentsAccess().getRule();
}
//// ---------------- rules
//RuleDeclaration:
// {RuleDeclaration} (modifier=RuleModifier?
// type=Type?
// name=Identifier
// '(' paramList=ParameterList? ')'
// '=')?
// conditions=RuleConditions?
// block=RuleElementBlock
// ';'?;
public RuleDeclarationElements getRuleDeclarationAccess() {
return pRuleDeclaration;
}
public ParserRule getRuleDeclarationRule() {
return getRuleDeclarationAccess().getRule();
}
//RuleConditions:
// {RuleConditions} postcondition+=LogicalExpression?
// ':' (preconditions+=LogicalExpression (',' preconditions+=LogicalExpression)*)?;
public RuleConditionsElements getRuleConditionsAccess() {
return pRuleConditions;
}
public ParserRule getRuleConditionsRule() {
return getRuleConditionsAccess().getRule();
}
//RuleElementBlock:
// {RuleElementBlock}
// '{'
// elements+=RuleElement*
// '}';
public RuleElementBlockElements getRuleElementBlockAccess() {
return pRuleElementBlock;
}
public ParserRule getRuleElementBlockRule() {
return getRuleElementBlockAccess().getRule();
}
//RuleElement:
// varDecl=VariableDeclaration
// | exprStmt=ExpressionStatement
// | while=While ';'?
// | for=For ';'?;
public RuleElementElements getRuleElementAccess() {
return pRuleElement;
}
public ParserRule getRuleElementRule() {
return getRuleElementAccess().getRule();
}
//RuleModifier:
// protected='protected';
public RuleModifierElements getRuleModifierAccess() {
return pRuleModifier;
}
public ParserRule getRuleModifierRule() {
return getRuleModifierAccess().getRule();
}
//// ----------------------- overriding and extending parts of the expression grammar -------------------
//ExpressionStatement:
// (var=Identifier ('.' field=Identifier)? '=')?
// expr=Expression ';' | alt=Alternative ';'?;
public ExpressionStatementElements getExpressionStatementAccess() {
return pExpressionStatement;
}
public ParserRule getExpressionStatementRule() {
return getExpressionStatementAccess().getRule();
}
//PrimaryExpression:
// otherEx=ExpressionOrQualifiedExecution
// | unqEx=UnqualifiedExecution
// | superEx=SuperExecution
// | sysEx=SystemExecution
// | map=Map
// | join=Join
// | instantiate=Instantiate
// | newEx=ConstructorExecution;
public PrimaryExpressionElements getPrimaryExpressionAccess() {
return pPrimaryExpression;
}
public ParserRule getPrimaryExpressionRule() {
return getPrimaryExpressionAccess().getRule();
}
//Instantiate:
// 'instantiate' (project=Identifier | ruleName=STRING)
// '(' param=ArgumentList? ')' versionSpec=VersionSpec?;
public InstantiateElements getInstantiateAccess() {
return pInstantiate;
}
public ParserRule getInstantiateRule() {
return getInstantiateAccess().getRule();
}
//LoopVariable:
// type=Type?
// var=Identifier;
public LoopVariableElements getLoopVariableAccess() {
return pLoopVariable;
}
public ParserRule getLoopVariableRule() {
return getLoopVariableAccess().getRule();
}
//Map:
// 'map' '(' var+=LoopVariable (',' var+=LoopVariable)* separator=('=' | ':') expr=Expression ')'
// block=RuleElementBlock;
public MapElements getMapAccess() {
return pMap;
}
public ParserRule getMapRule() {
return getMapAccess().getRule();
}
//For:
// 'for' '(' var+=LoopVariable (',' var+=LoopVariable)* separator=('=' | ':') expr=Expression ')'
// block=RuleElementBlock;
public ForElements getForAccess() {
return pFor;
}
public ParserRule getForRule() {
return getForAccess().getRule();
}
//While:
// 'while' '(' expr=Expression ')'
// block=RuleElementBlock;
public WhileElements getWhileAccess() {
return pWhile;
}
public ParserRule getWhileRule() {
return getWhileAccess().getRule();
}
//Alternative:
// 'if' '(' expr=Expression ')' if=StatementOrBlock (=>'else' else=StatementOrBlock)?;
public AlternativeElements getAlternativeAccess() {
return pAlternative;
}
public ParserRule getAlternativeRule() {
return getAlternativeAccess().getRule();
}
//StatementOrBlock:
// exStmt=ExpressionStatement | block=RuleElementBlock;
public StatementOrBlockElements getStatementOrBlockAccess() {
return pStatementOrBlock;
}
public ParserRule getStatementOrBlockRule() {
return getStatementOrBlockAccess().getRule();
}
//Join:
// 'join' '('
// var1=JoinVariable ','
// var2=JoinVariable ')' ('with'
// '(' condition=Expression ')')?;
public JoinElements getJoinAccess() {
return pJoin;
}
public ParserRule getJoinRule() {
return getJoinAccess().getRule();
}
//JoinVariable:
// excl='exclude'? var=Identifier
// ':'
// expr=Expression;
public JoinVariableElements getJoinVariableAccess() {
return pJoinVariable;
}
public ParserRule getJoinVariableRule() {
return getJoinVariableAccess().getRule();
}
//SystemExecution:
// 'execute' call=Call calls+=SubCall*;
public SystemExecutionElements getSystemExecutionAccess() {
return pSystemExecution;
}
public ParserRule getSystemExecutionRule() {
return getSystemExecutionAccess().getRule();
}
//VariableDeclaration:
// const='const'?
// type=Type
// name=Identifier ('=' expression=Expression)?
// ';';
public ExpressionDslGrammarAccess.VariableDeclarationElements getVariableDeclarationAccess() {
return gaExpressionDsl.getVariableDeclarationAccess();
}
public ParserRule getVariableDeclarationRule() {
return getVariableDeclarationAccess().getRule();
}
//Compound:
// abstract='abstract'? 'compound' name=Identifier ('refines' super=Identifier)? '{'
// vars+=VariableDeclaration*
// '}' ';'?;
public ExpressionDslGrammarAccess.CompoundElements getCompoundAccess() {
return gaExpressionDsl.getCompoundAccess();
}
public ParserRule getCompoundRule() {
return getCompoundAccess().getRule();
}
//TypeDef:
// 'typedef'
// name=Identifier
// type=Type
// ';';
public ExpressionDslGrammarAccess.TypeDefElements getTypeDefAccess() {
return gaExpressionDsl.getTypeDefAccess();
}
public ParserRule getTypeDefRule() {
return getTypeDefAccess().getRule();
}
//// used in extending languages
//Advice:
// '@advice' '(' name=QualifiedName ')'
// versionSpec=VersionSpec?;
public ExpressionDslGrammarAccess.AdviceElements getAdviceAccess() {
return gaExpressionDsl.getAdviceAccess();
}
public ParserRule getAdviceRule() {
return getAdviceAccess().getRule();
}
//VersionSpec:
// 'with' restriction=Expression;
public ExpressionDslGrammarAccess.VersionSpecElements getVersionSpecAccess() {
return gaExpressionDsl.getVersionSpecAccess();
}
public ParserRule getVersionSpecRule() {
return getVersionSpecAccess().getRule();
}
//ParameterList:
// param+=Parameter (',' param+=Parameter)*;
public ExpressionDslGrammarAccess.ParameterListElements getParameterListAccess() {
return gaExpressionDsl.getParameterListAccess();
}
public ParserRule getParameterListRule() {
return getParameterListAccess().getRule();
}
//Parameter:
// type=Type
// name=Identifier ('=' dflt=Expression)?;
public ExpressionDslGrammarAccess.ParameterElements getParameterAccess() {
return gaExpressionDsl.getParameterAccess();
}
public ParserRule getParameterRule() {
return getParameterAccess().getRule();
}
//VersionStmt:
// 'version'
// version=VERSION
// ';';
public ExpressionDslGrammarAccess.VersionStmtElements getVersionStmtAccess() {
return gaExpressionDsl.getVersionStmtAccess();
}
public ParserRule getVersionStmtRule() {
return getVersionStmtAccess().getRule();
}
//Import:
// // here fqn because this may reference a specific project (of an external project)
// 'import' name=Identifier versionSpec=VersionSpec? ';';
public ExpressionDslGrammarAccess.ImportElements getImportAccess() {
return gaExpressionDsl.getImportAccess();
}
public ParserRule getImportRule() {
return getImportAccess().getRule();
}
//Expression:
// expr=LogicalExpression | init=ContainerInitializer;
public ExpressionDslGrammarAccess.ExpressionElements getExpressionAccess() {
return gaExpressionDsl.getExpressionAccess();
}
public ParserRule getExpressionRule() {
return getExpressionAccess().getRule();
}
//LogicalExpression:
// left=EqualityExpression
// right+=LogicalExpressionPart*;
public ExpressionDslGrammarAccess.LogicalExpressionElements getLogicalExpressionAccess() {
return gaExpressionDsl.getLogicalExpressionAccess();
}
public ParserRule getLogicalExpressionRule() {
return getLogicalExpressionAccess().getRule();
}
//LogicalExpressionPart:
// op=LogicalOperator
// ex=EqualityExpression;
public ExpressionDslGrammarAccess.LogicalExpressionPartElements getLogicalExpressionPartAccess() {
return gaExpressionDsl.getLogicalExpressionPartAccess();
}
public ParserRule getLogicalExpressionPartRule() {
return getLogicalExpressionPartAccess().getRule();
}
//LogicalOperator:
// 'and'
// | 'or'
// | 'xor'
// | 'implies'
// | 'iff';
public ExpressionDslGrammarAccess.LogicalOperatorElements getLogicalOperatorAccess() {
return gaExpressionDsl.getLogicalOperatorAccess();
}
public ParserRule getLogicalOperatorRule() {
return getLogicalOperatorAccess().getRule();
}
//EqualityExpression:
// left=RelationalExpression
// right=EqualityExpressionPart?;
public ExpressionDslGrammarAccess.EqualityExpressionElements getEqualityExpressionAccess() {
return gaExpressionDsl.getEqualityExpressionAccess();
}
public ParserRule getEqualityExpressionRule() {
return getEqualityExpressionAccess().getRule();
}
//EqualityExpressionPart:
// op=EqualityOperator
// ex=RelationalExpression;
public ExpressionDslGrammarAccess.EqualityExpressionPartElements getEqualityExpressionPartAccess() {
return gaExpressionDsl.getEqualityExpressionPartAccess();
}
public ParserRule getEqualityExpressionPartRule() {
return getEqualityExpressionPartAccess().getRule();
}
//EqualityOperator:
// '=='
// | '<>'
// | '!=';
public ExpressionDslGrammarAccess.EqualityOperatorElements getEqualityOperatorAccess() {
return gaExpressionDsl.getEqualityOperatorAccess();
}
public ParserRule getEqualityOperatorRule() {
return getEqualityOperatorAccess().getRule();
}
//RelationalExpression:
// left=AdditiveExpression (right=RelationalExpressionPart right2=RelationalExpressionPart?)?;
public ExpressionDslGrammarAccess.RelationalExpressionElements getRelationalExpressionAccess() {
return gaExpressionDsl.getRelationalExpressionAccess();
}
public ParserRule getRelationalExpressionRule() {
return getRelationalExpressionAccess().getRule();
}
//RelationalExpressionPart:
// op=RelationalOperator
// ex=AdditiveExpression;
public ExpressionDslGrammarAccess.RelationalExpressionPartElements getRelationalExpressionPartAccess() {
return gaExpressionDsl.getRelationalExpressionPartAccess();
}
public ParserRule getRelationalExpressionPartRule() {
return getRelationalExpressionPartAccess().getRule();
}
//RelationalOperator:
// '>'
// | '<'
// | '>='
// | '<=';
public ExpressionDslGrammarAccess.RelationalOperatorElements getRelationalOperatorAccess() {
return gaExpressionDsl.getRelationalOperatorAccess();
}
public ParserRule getRelationalOperatorRule() {
return getRelationalOperatorAccess().getRule();
}
//AdditiveExpression:
// left=MultiplicativeExpression
// right+=AdditiveExpressionPart*;
public ExpressionDslGrammarAccess.AdditiveExpressionElements getAdditiveExpressionAccess() {
return gaExpressionDsl.getAdditiveExpressionAccess();
}
public ParserRule getAdditiveExpressionRule() {
return getAdditiveExpressionAccess().getRule();
}
//AdditiveExpressionPart:
// op=AdditiveOperator
// ex=MultiplicativeExpression;
public ExpressionDslGrammarAccess.AdditiveExpressionPartElements getAdditiveExpressionPartAccess() {
return gaExpressionDsl.getAdditiveExpressionPartAccess();
}
public ParserRule getAdditiveExpressionPartRule() {
return getAdditiveExpressionPartAccess().getRule();
}
//AdditiveOperator:
// '+'
// | '-';
public ExpressionDslGrammarAccess.AdditiveOperatorElements getAdditiveOperatorAccess() {
return gaExpressionDsl.getAdditiveOperatorAccess();
}
public ParserRule getAdditiveOperatorRule() {
return getAdditiveOperatorAccess().getRule();
}
//MultiplicativeExpression:
// left=UnaryExpression
// right=MultiplicativeExpressionPart?;
public ExpressionDslGrammarAccess.MultiplicativeExpressionElements getMultiplicativeExpressionAccess() {
return gaExpressionDsl.getMultiplicativeExpressionAccess();
}
public ParserRule getMultiplicativeExpressionRule() {
return getMultiplicativeExpressionAccess().getRule();
}
//MultiplicativeExpressionPart:
// op=MultiplicativeOperator
// expr=UnaryExpression;
public ExpressionDslGrammarAccess.MultiplicativeExpressionPartElements getMultiplicativeExpressionPartAccess() {
return gaExpressionDsl.getMultiplicativeExpressionPartAccess();
}
public ParserRule getMultiplicativeExpressionPartRule() {
return getMultiplicativeExpressionPartAccess().getRule();
}
//MultiplicativeOperator:
// '*'
// | '/';
public ExpressionDslGrammarAccess.MultiplicativeOperatorElements getMultiplicativeOperatorAccess() {
return gaExpressionDsl.getMultiplicativeOperatorAccess();
}
public ParserRule getMultiplicativeOperatorRule() {
return getMultiplicativeOperatorAccess().getRule();
}
//UnaryExpression:
// op=UnaryOperator?
// expr=PostfixExpression;
public ExpressionDslGrammarAccess.UnaryExpressionElements getUnaryExpressionAccess() {
return gaExpressionDsl.getUnaryExpressionAccess();
}
public ParserRule getUnaryExpressionRule() {
return getUnaryExpressionAccess().getRule();
}
//UnaryOperator:
// 'not'
// | '!'
// | '-';
public ExpressionDslGrammarAccess.UnaryOperatorElements getUnaryOperatorAccess() {
return gaExpressionDsl.getUnaryOperatorAccess();
}
public ParserRule getUnaryOperatorRule() {
return getUnaryOperatorAccess().getRule();
}
//PostfixExpression:
// left=super::PrimaryExpression // left here for extensions
//;
public ExpressionDslGrammarAccess.PostfixExpressionElements getPostfixExpressionAccess() {
return gaExpressionDsl.getPostfixExpressionAccess();
}
public ParserRule getPostfixExpressionRule() {
return getPostfixExpressionAccess().getRule();
}
//ExpressionOrQualifiedExecution:
// (val=Constant
// | '(' parenthesis=Expression ')') calls+=SubCall*;
public ExpressionDslGrammarAccess.ExpressionOrQualifiedExecutionElements getExpressionOrQualifiedExecutionAccess() {
return gaExpressionDsl.getExpressionOrQualifiedExecutionAccess();
}
public ParserRule getExpressionOrQualifiedExecutionRule() {
return getExpressionOrQualifiedExecutionAccess().getRule();
}
//UnqualifiedExecution:
// call=Call calls+=SubCall*;
public ExpressionDslGrammarAccess.UnqualifiedExecutionElements getUnqualifiedExecutionAccess() {
return gaExpressionDsl.getUnqualifiedExecutionAccess();
}
public ParserRule getUnqualifiedExecutionRule() {
return getUnqualifiedExecutionAccess().getRule();
}
//SuperExecution:
// 'super' '.' call=Call calls+=SubCall*;
public ExpressionDslGrammarAccess.SuperExecutionElements getSuperExecutionAccess() {
return gaExpressionDsl.getSuperExecutionAccess();
}
public ParserRule getSuperExecutionRule() {
return getSuperExecutionAccess().getRule();
}
//ConstructorExecution:
// 'new' type=Type '(' param=ArgumentList? ')' calls+=SubCall*;
public ExpressionDslGrammarAccess.ConstructorExecutionElements getConstructorExecutionAccess() {
return gaExpressionDsl.getConstructorExecutionAccess();
}
public ParserRule getConstructorExecutionRule() {
return getConstructorExecutionAccess().getRule();
}
//SubCall:
// type=('.' | '->') call=Call
// | '[' arrayEx=Expression ']' // IVML addition to OCL
//;
public ExpressionDslGrammarAccess.SubCallElements getSubCallAccess() {
return gaExpressionDsl.getSubCallAccess();
}
public ParserRule getSubCallRule() {
return getSubCallAccess().getRule();
}
//Declarator:
// decl+=Declaration (';' decl+=Declaration)* '|';
public ExpressionDslGrammarAccess.DeclaratorElements getDeclaratorAccess() {
return gaExpressionDsl.getDeclaratorAccess();
}
public ParserRule getDeclaratorRule() {
return getDeclaratorAccess().getRule();
}
//Declaration:
// type=Type? units+=DeclarationUnit (',' units+=DeclarationUnit)*;
public ExpressionDslGrammarAccess.DeclarationElements getDeclarationAccess() {
return gaExpressionDsl.getDeclarationAccess();
}
public ParserRule getDeclarationRule() {
return getDeclarationAccess().getRule();
}
//DeclarationUnit:
// id=Identifier ('=' deflt=Expression)?;
public ExpressionDslGrammarAccess.DeclarationUnitElements getDeclarationUnitAccess() {
return gaExpressionDsl.getDeclarationUnitAccess();
}
public ParserRule getDeclarationUnitRule() {
return getDeclarationUnitAccess().getRule();
}
//Call:
// name=QualifiedPrefix
// '('
// decl=Declarator?
// param=ArgumentList?
// ')';
public ExpressionDslGrammarAccess.CallElements getCallAccess() {
return gaExpressionDsl.getCallAccess();
}
public ParserRule getCallRule() {
return getCallAccess().getRule();
}
//ArgumentList:
// param+=NamedArgument (','
// param+=NamedArgument)*;
public ExpressionDslGrammarAccess.ArgumentListElements getArgumentListAccess() {
return gaExpressionDsl.getArgumentListAccess();
}
public ParserRule getArgumentListRule() {
return getArgumentListAccess().getRule();
}
//NamedArgument:
// (name=Identifier '=')?
// ex=Expression;
public ExpressionDslGrammarAccess.NamedArgumentElements getNamedArgumentAccess() {
return gaExpressionDsl.getNamedArgumentAccess();
}
public ParserRule getNamedArgumentRule() {
return getNamedArgumentAccess().getRule();
}
//QualifiedPrefix:
// qname+=Identifier (qname+='::' qname+=Identifier)*;
public ExpressionDslGrammarAccess.QualifiedPrefixElements getQualifiedPrefixAccess() {
return gaExpressionDsl.getQualifiedPrefixAccess();
}
public ParserRule getQualifiedPrefixRule() {
return getQualifiedPrefixAccess().getRule();
}
//QualifiedName:
// prefix=QualifiedPrefix (qname+='.' qname+=Identifier)*;
public ExpressionDslGrammarAccess.QualifiedNameElements getQualifiedNameAccess() {
return gaExpressionDsl.getQualifiedNameAccess();
}
public ParserRule getQualifiedNameRule() {
return getQualifiedNameAccess().getRule();
}
//Constant:
// nValue=NumValue
// | sValue=STRING
// | qValue=QualifiedName
// | bValue=('true' | 'false') | null='null'
// | =>version=VERSION;
public ExpressionDslGrammarAccess.ConstantElements getConstantAccess() {
return gaExpressionDsl.getConstantAccess();
}
public ParserRule getConstantRule() {
return getConstantAccess().getRule();
}
//NumValue:
// val=NUMBER;
public ExpressionDslGrammarAccess.NumValueElements getNumValueAccess() {
return gaExpressionDsl.getNumValueAccess();
}
public ParserRule getNumValueRule() {
return getNumValueAccess().getRule();
}
//Identifier:
// ID | VERSION | EXPONENT | "version";
public ExpressionDslGrammarAccess.IdentifierElements getIdentifierAccess() {
return gaExpressionDsl.getIdentifierAccess();
}
public ParserRule getIdentifierRule() {
return getIdentifierAccess().getRule();
}
//Type:
// name=QualifiedPrefix // specific types will be dynamically loaded at start-up
// | set='setOf' param=TypeParameters | seq='sequenceOf' param=TypeParameters | map='mapOf' param=TypeParameters |
// call='callOf' return=Type? param=TypeParameters;
public ExpressionDslGrammarAccess.TypeElements getTypeAccess() {
return gaExpressionDsl.getTypeAccess();
}
public ParserRule getTypeRule() {
return getTypeAccess().getRule();
}
//TypeParameters:
// '(' param+=Type (',' param+=Type)* ')';
public ExpressionDslGrammarAccess.TypeParametersElements getTypeParametersAccess() {
return gaExpressionDsl.getTypeParametersAccess();
}
public ParserRule getTypeParametersRule() {
return getTypeParametersAccess().getRule();
}
//ContainerInitializer:
// {ContainerInitializer}
// '{' (exprs+=ContainerInitializerExpression (',' exprs+=ContainerInitializerExpression)*)? '}';
public ExpressionDslGrammarAccess.ContainerInitializerElements getContainerInitializerAccess() {
return gaExpressionDsl.getContainerInitializerAccess();
}
public ParserRule getContainerInitializerRule() {
return getContainerInitializerAccess().getRule();
}
//ContainerInitializerExpression:
// logical=LogicalExpression
// | container=ContainerInitializer;
public ExpressionDslGrammarAccess.ContainerInitializerExpressionElements getContainerInitializerExpressionAccess() {
return gaExpressionDsl.getContainerInitializerExpressionAccess();
}
public ParserRule getContainerInitializerExpressionRule() {
return getContainerInitializerExpressionAccess().getRule();
}
//terminal VERSION:
// 'v' '0'..'9'+ ('.' '0'..'9'+)*;
public TerminalRule getVERSIONRule() {
return gaExpressionDsl.getVERSIONRule();
}
//terminal ID:
// ('a'..'z' | 'A'..'Z' | '_' | '$') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*;
public TerminalRule getIDRule() {
return gaExpressionDsl.getIDRule();
}
//terminal NUMBER:
// '-'? ('0'..'9'+ ('.' '0'..'9'* EXPONENT?)?
// | '.' '0'..'9'+ EXPONENT?
// | '0'..'9'+ EXPONENT);
public TerminalRule getNUMBERRule() {
return gaExpressionDsl.getNUMBERRule();
}
//terminal EXPONENT:
// ('e' | 'E') ('+' | '-')? '0'..'9'+;
public TerminalRule getEXPONENTRule() {
return gaExpressionDsl.getEXPONENTRule();
}
//terminal STRING:
// '"' ('\\' ('b' | 't' | 'n' | 'f' | 'r' | 'u' | '"' | "'" | '\\') | !('\\' | '"'))* '"' |
// "'" ('\\' ('b' | 't' | 'n' | 'f' | 'r' | 'u' | '"' | "'" | '\\') | !('\\' | "'"))* "'";
public TerminalRule getSTRINGRule() {
return gaExpressionDsl.getSTRINGRule();
}
//terminal ML_COMMENT:
// '/*'->'*/';
public TerminalRule getML_COMMENTRule() {
return gaExpressionDsl.getML_COMMENTRule();
}
//terminal SL_COMMENT:
// '//' !('\n' | '\r')* ('\r'? '\n')?;
public TerminalRule getSL_COMMENTRule() {
return gaExpressionDsl.getSL_COMMENTRule();
}
//terminal WS:
// ' ' | '\t' | '\r' | '\n'+;
public TerminalRule getWSRule() {
return gaExpressionDsl.getWSRule();
}
//terminal ANY_OTHER:
// .;
public TerminalRule getANY_OTHERRule() {
return gaExpressionDsl.getANY_OTHERRule();
}
}
|
3e0db3832d157557192fdb5013131a052c5f44f1 | 1,650 | java | Java | tests/features/pause/PauseBurstsTest2.java | angoodkind/DARPA_AA | fd554d34db28102e1e53919d565e2f2ddeda0d90 | [
"MIT"
] | 1 | 2018-09-06T08:11:15.000Z | 2018-09-06T08:11:15.000Z | tests/features/pause/PauseBurstsTest2.java | angoodkind/DARPA_AA | fd554d34db28102e1e53919d565e2f2ddeda0d90 | [
"MIT"
] | null | null | null | tests/features/pause/PauseBurstsTest2.java | angoodkind/DARPA_AA | fd554d34db28102e1e53919d565e2f2ddeda0d90 | [
"MIT"
] | null | null | null | 42.307692 | 116 | 0.72 | 5,793 | package features.pause;
import static junit.framework.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import features.pause.PauseBursts;
/**
* A Test class for BetKSEPause
*/
public class PauseBurstsTest2 {
private PauseBursts pauser;
@Before
public void setUp() {
pauser = new PauseBursts();
}
@Test
public void testInitPauseCorrectlyCountsPauses() {
String keystrokes = "0:20c:65535:1334533622746:0 1:20c:65535:1334533622818:0 0:10:65535:1334533778889:0 " +
"1:10:65535:1334533779025:0 0:4d:109:1334533779025:0 1:4d:109:1334533779130:1 0:59:121:1334533779130:1 " +
"1:59:121:1334533779209:2 0:20:32:1334533779209:2 1:20:32:1334533779313:3 0:46:102:1334533779601:3 " +
"0:41:97:1334533779665:4 1:46:102:1334533779689:5 1:41:97:1334533779785:5 0:56:118:1334533779785:5 " +
"1:56:118:1334533779873:6 0:4f:111:1334533779937:6 0:52:114:1334533779991:7 1:4f:111:1334533780025:8 " +
"1:52:114:1334533780081:8 0:49:105:1334533780753:8 0:54:116:1334533780809:9 1:49:105:1334533780841:10 " +
"0:45:101:1334533780865:10 1:54:116:1334533780897:11 0:20:32:1334533780921:11 1:45:101:1334533781009:12 " +
"1:20:32:1334533781049:12 0:42:98:1334533781409:12 0:4f:111:1334533781473:13 1:42:98:1334533781513:14 " +
"1:4f:111:1334533781537:14 0:4f:111:1334533781601:14 1:4f:111:1334533781665:15 0:4b:107:1334533781745:15 " +
"0:20:32:1334533781825:16 1:4b:107:1334533781873:17 1:20:32:1334533781913:17 0:49:105:1334533781963:17";
pauser.generatePauseDownList(keystrokes,250);
assertEquals(4, pauser.getPauseDownList().size());
}
}
|
3e0db3ad99ada2d35e9da8ce7536b281a7306d1a | 315 | java | Java | depth/src/main/java/com/github/florent37/depth/lib/MathHelper.java | suyimin/Depth | 46f0abbb9ba892d8669162bfd62f2d1f72f4b4a7 | [
"MIT"
] | 833 | 2017-03-06T17:32:13.000Z | 2022-02-21T02:16:23.000Z | depth/src/main/java/com/github/florent37/depth/lib/MathHelper.java | suyimin/Depth | 46f0abbb9ba892d8669162bfd62f2d1f72f4b4a7 | [
"MIT"
] | 1 | 2017-03-08T13:17:00.000Z | 2017-04-19T18:33:03.000Z | depth/src/main/java/com/github/florent37/depth/lib/MathHelper.java | suyimin/Depth | 46f0abbb9ba892d8669162bfd62f2d1f72f4b4a7 | [
"MIT"
] | 108 | 2017-03-07T01:32:03.000Z | 2021-11-08T15:41:28.000Z | 21 | 78 | 0.653968 | 5,794 | package com.github.florent37.depth.lib;
import java.util.Random;
public class MathHelper {
public static Random rand = new Random();
public static float randomRange(float min, float max) {
int randomNum = rand.nextInt(((int) max - (int) min) + 1) + (int) min;
return randomNum;
}
}
|
3e0db4a7c7caa42eeb0a2005a76c272d89d1b306 | 23,574 | java | Java | modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java | sruehl/openapi-generator | faf1f5d81d4d58532c8464f6ffcfc708485ba8d5 | [
"Apache-2.0"
] | 5 | 2019-12-03T13:50:09.000Z | 2021-11-14T12:59:48.000Z | modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java | sruehl/openapi-generator | faf1f5d81d4d58532c8464f6ffcfc708485ba8d5 | [
"Apache-2.0"
] | null | null | null | modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java | sruehl/openapi-generator | faf1f5d81d4d58532c8464f6ffcfc708485ba8d5 | [
"Apache-2.0"
] | null | null | null | 37.658147 | 599 | 0.58836 | 5,795 | /*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* 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 org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static final String UNDEFINED_VALUE = "undefined";
protected String modelPropertyNaming = "camelCase";
protected Boolean supportsES6 = true;
protected HashSet<String> languageGenericTypes;
public AbstractTypeScriptClientCodegen() {
super();
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
supportsInheritance = true;
// to support multiple inheritance e.g. export interface ModelC extends ModelA, ModelB
//supportsMultipleInheritance = true;
// NOTE: TypeScript uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons.
reservedWords.addAll(Arrays.asList(
// local variable names used in API methods (endpoints)
"varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
"requestOptions",
// Typescript reserved words
"abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"));
languageSpecificPrimitives = new HashSet<>(Arrays.asList(
"string",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object",
"Array",
"Date",
"number",
"any",
"File",
"Error",
"Map"
));
languageGenericTypes = new HashSet<String>(Arrays.asList(
"Array"
));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
typeMapping.put("Array", "Array");
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("int", "number");
typeMapping.put("float", "number");
typeMapping.put("number", "number");
typeMapping.put("long", "number");
typeMapping.put("short", "number");
typeMapping.put("char", "string");
typeMapping.put("double", "number");
typeMapping.put("object", "any");
typeMapping.put("integer", "number");
typeMapping.put("Map", "any");
typeMapping.put("map", "any");
typeMapping.put("date", "string");
typeMapping.put("DateTime", "Date");
typeMapping.put("binary", "any");
typeMapping.put("File", "any");
typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
typeMapping.put("Error", "Error");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false"));
}
@Override
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("TS_POST_PROCESS_FILE"))) {
LOGGER.info("Hint: Environment variable 'TS_POST_PROCESS_FILE' (optional) not defined. E.g. to format the source code, please try 'export TS_POST_PROCESS_FILE=\"/usr/local/bin/prettier --write\"' (Linux/Mac)");
}
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
}
if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) {
setSupportsES6(Boolean.valueOf(additionalProperties.get(CodegenConstants.SUPPORTS_ES6).toString()));
additionalProperties.put("supportsES6", getSupportsES6());
}
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String toParamName(String name) {
// sanitize name
name = sanitizeName(name, "[^\\w$]");
if ("_".equals(name)) {
name = "_u";
}
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
name = getNameUsingModelPropertyNaming(name);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toVarName(String name) {
name = this.toParamName(name);
// if the proprty name has any breaking characters such as :, ;, . etc.
// then wrap the name within single quotes.
// my:interface:property: string; => 'my:interface:property': string;
if (propertyHasBreakingCharacters(name)) {
name = "\'" + name + "\'";
}
return name;
}
/**
* Checks whether property names have breaking characters like ':', '-'.
* @param str string to check for breaking characters
* @return <code>true</code> if breaking characters are present and <code>false</code> if not
*/
private boolean propertyHasBreakingCharacters(String str) {
final String regex = "^.*[+*:;,.()-]+.*$";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(str);
boolean matches = matcher.matches();
return matches;
}
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
if (languageSpecificPrimitives.contains(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName);
return modelName;
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return "{ [key: string]: " + getTypeDeclaration(inner) + "; }";
} else if (ModelUtils.isFileSchema(p)) {
return "any";
} else if (ModelUtils.isBinarySchema(p)) {
return "any";
}
return super.getTypeDeclaration(p);
}
@Override
protected String getParameterDataType(Parameter parameter, Schema p) {
// handle enums of various data types
Schema inner;
if (ModelUtils.isArraySchema(p)) {
ArraySchema mp1 = (ArraySchema) p;
inner = mp1.getItems();
return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = ModelUtils.getAdditionalProperties(p);
return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
} else if (ModelUtils.isStringSchema(p)) {
// Handle string enums
if (p.getEnum() != null) {
return enumValuesToEnumTypeUnion(p.getEnum(), "string");
}
} else if (ModelUtils.isIntegerSchema(p)) {
// Handle integer enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
} else if (ModelUtils.isNumberSchema(p)) {
// Handle double enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
}
/* TODO revise the logic below
else if (ModelUtils.isDateSchema(p)) {
// Handle date enums
DateSchema sp = (DateSchema) p;
if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
}
} else if (ModelUtils.isDateTimeSchema(p)) {
// Handle datetime enums
DateTimeSchema sp = (DateTimeSchema) p;
if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
}
}*/
return this.getTypeDeclaration(p);
}
/**
* Converts a list of strings to a literal union for representing enum values as a type.
* Example output: 'available' | 'pending' | 'sold'
*
* @param values list of allowed enum values
* @param dataType either "string" or "number"
* @return a literal union for representing enum values as a type
*/
protected String enumValuesToEnumTypeUnion(List<String> values, String dataType) {
StringBuilder b = new StringBuilder();
boolean isFirst = true;
for (String value : values) {
if (!isFirst) {
b.append(" | ");
}
b.append(toEnumValue(value.toString(), dataType));
isFirst = false;
}
return b.toString();
}
/**
* Converts a list of numbers to a literal union for representing enum values as a type.
* Example output: 3 | 9 | 55
*
* @param values a list of numbers
* @return a literal union for representing enum values as a type
*/
protected String numericEnumValuesToEnumTypeUnion(List<Number> values) {
List<String> stringValues = new ArrayList<>();
for (Number value : values) {
stringValues.add(value.toString());
}
return enumValuesToEnumTypeUnion(stringValues, "number");
}
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isDateSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isDateTimeSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'";
}
return UNDEFINED_VALUE;
} else {
return UNDEFINED_VALUE;
}
}
@Override
protected boolean isReservedWord(String word) {
// NOTE: This differs from super's implementation in that TypeScript does _not_ want case insensitive matching.
return reservedWords.contains(word);
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type))
return type;
} else
type = openAPIType;
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
// append _ at the beginning, e.g. _return
if (isReservedWord(operationId)) {
return escapeReservedWord(camelize(sanitizeName(operationId), true));
}
return camelize(sanitizeName(operationId), true);
}
public void setModelPropertyNaming(String naming) {
if ("original".equals(naming) || "camelCase".equals(naming) ||
"PascalCase".equals(naming) || "snake_case".equals(naming)) {
this.modelPropertyNaming = naming;
} else {
throw new IllegalArgumentException("Invalid model property naming '" +
naming + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
public String getModelPropertyNaming() {
return this.modelPropertyNaming;
}
public String getNameUsingModelPropertyNaming(String name) {
switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) {
case original:
return name;
case camelCase:
return camelize(name, true);
case PascalCase:
return camelize(name);
case snake_case:
return underscore(name);
default:
throw new IllegalArgumentException("Invalid model property naming '" +
name + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
@Override
public String toEnumValue(String value, String datatype) {
if ("number".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "Empty";
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(getSymbolName(name));
}
// number
if ("number".equals(datatype)) {
String varName = "NUMBER_" + name;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(name);
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
// camelize the enum variable name
// ref: https://basarat.gitbooks.io/typescript/content/docs/enums.html
enumName = camelize(enumName);
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = toModelName(property.name) + "Enum";
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
List<Object> models = (List<Object>) postProcessModelsEnum(objs).get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.imports = new TreeSet(cm.imports);
// name enum with model name, e.g. StatusEnum => Pet.StatusEnum
for (CodegenProperty var : cm.vars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + "." + var.enumName);
}
}
if (cm.parent != null) {
for (CodegenProperty var : cm.allVars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum
.replace(var.enumName, cm.classname + "." + var.enumName);
}
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessAllModels(objs);
for (Map.Entry<String, Object> entry : result.entrySet()) {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
if (cm.discriminator != null && cm.children != null) {
for (CodegenModel child : cm.children) {
this.setDiscriminatorValue(child, cm.discriminator.getPropertyName(), this.getDiscriminatorValue(child));
}
}
}
}
return result;
}
public void setSupportsES6(Boolean value) {
supportsES6 = value;
}
public Boolean getSupportsES6() {
return supportsES6;
}
private void setDiscriminatorValue(CodegenModel model, String baseName, String value) {
for (CodegenProperty prop : model.allVars) {
if (prop.baseName.equals(baseName)) {
prop.discriminatorValue = value;
}
}
if (model.children != null) {
final boolean newDiscriminator = model.discriminator != null;
for (CodegenModel child : model.children) {
this.setDiscriminatorValue(child, baseName, newDiscriminator ? value : this.getDiscriminatorValue(child));
}
}
}
private String getDiscriminatorValue(CodegenModel model) {
return model.vendorExtensions.containsKey(X_DISCRIMINATOR_TYPE) ?
(String) model.vendorExtensions.get(X_DISCRIMINATOR_TYPE) : model.classname;
}
@Override
public String escapeQuotationMark(String input) {
// remove ', " to avoid code injection
return input.replace("\"", "").replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public void postProcessFile(File file, String fileType) {
super.postProcessFile(file, fileType);
if (file == null) {
return;
}
String tsPostProcessFile = System.getenv("TS_POST_PROCESS_FILE");
if (StringUtils.isEmpty(tsPostProcessFile)) {
return; // skip if TS_POST_PROCESS_FILE env variable is not defined
}
// only process files with ts extension
if ("ts".equals(FilenameUtils.getExtension(file.toString()))) {
String command = tsPostProcessFile + " " + file.toString();
try {
Process p = Runtime.getRuntime().exec(command);
int exitValue = p.waitFor();
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: " + command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
}
}
}
}
|
3e0db5adafa6e1fb443c17954b0465f3ec7ede3f | 688 | java | Java | android-app/src/main/java/com/msplearning/android/app/widget/LessonItemView.java | veniltonjr/msplearning | 179533b1f511ac1362dec4256e6dc14a048a7773 | [
"Apache-2.0"
] | 1 | 2015-06-03T02:01:10.000Z | 2015-06-03T02:01:10.000Z | android-app/src/main/java/com/msplearning/android/app/widget/LessonItemView.java | veniltonjr/msplearning | 179533b1f511ac1362dec4256e6dc14a048a7773 | [
"Apache-2.0"
] | null | null | null | android-app/src/main/java/com/msplearning/android/app/widget/LessonItemView.java | veniltonjr/msplearning | 179533b1f511ac1362dec4256e6dc14a048a7773 | [
"Apache-2.0"
] | 1 | 2016-09-16T11:46:29.000Z | 2016-09-16T11:46:29.000Z | 24.571429 | 67 | 0.8125 | 5,796 | package com.msplearning.android.app.widget;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import android.content.Context;
import android.widget.TextView;
import com.msplearning.android.app.R;
import com.msplearning.android.app.widget.generic.AbstractItemView;
import com.msplearning.entity.Lesson;
@EViewGroup(R.layout.widget_list_item)
public class LessonItemView extends AbstractItemView<Lesson> {
@ViewById(R.id.textview_description)
TextView mLessonName;
public LessonItemView(Context context) {
super(context);
}
@Override
public void bind(Lesson lesson) {
this.mLessonName.setText(lesson.getName());
}
}
|
3e0db6255a05d93c37b14b6df9bdf95df9cd4c82 | 173 | java | Java | src/main/java/yalter/mousetweaks/api/MouseTweaksIgnore.java | p455w0rd/WirelessPatternTerminal | 6bd77b10736edb0fe0e0c852ff6c54b24469d180 | [
"MIT"
] | null | null | null | src/main/java/yalter/mousetweaks/api/MouseTweaksIgnore.java | p455w0rd/WirelessPatternTerminal | 6bd77b10736edb0fe0e0c852ff6c54b24469d180 | [
"MIT"
] | 3 | 2019-11-15T19:31:42.000Z | 2021-08-16T08:01:40.000Z | src/main/java/yalter/mousetweaks/api/MouseTweaksIgnore.java | p455w0rd/WirelessPatternTerminal | 6bd77b10736edb0fe0e0c852ff6c54b24469d180 | [
"MIT"
] | 2 | 2021-01-28T10:23:38.000Z | 2021-08-31T17:59:55.000Z | 15.727273 | 37 | 0.780347 | 5,797 | package yalter.mousetweaks.api;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE
})
public @interface MouseTweaksIgnore {
}
|
3e0db6cc6ed809e5d7a43567766dec5040ee5ce3 | 1,472 | java | Java | src/main/java/com/cognifide/bdd/demo/po/product/TrianglePage.java | wttech/bobcat-aem-integration-tests | 43767a8d88260457c6c96ff77432f5652738de17 | [
"Apache-2.0"
] | 2 | 2017-03-12T05:14:55.000Z | 2018-02-04T20:34:16.000Z | src/main/java/com/cognifide/bdd/demo/po/product/TrianglePage.java | Cognifide/bobcat-aem-integration-tests | 43767a8d88260457c6c96ff77432f5652738de17 | [
"Apache-2.0"
] | 3 | 2017-04-16T04:49:47.000Z | 2018-06-05T06:20:17.000Z | src/main/java/com/cognifide/bdd/demo/po/product/TrianglePage.java | wttech/bobcat-aem-integration-tests | 43767a8d88260457c6c96ff77432f5652738de17 | [
"Apache-2.0"
] | 3 | 2018-09-12T14:56:07.000Z | 2020-05-30T22:08:25.000Z | 27.259259 | 93 | 0.738451 | 5,798 | /*-
* #%L
* Bobcat
* %%
* Copyright (C) 2016 Wunderman Thompson Technology
* %%
* 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.
* #L%
*/
package com.cognifide.bdd.demo.po.product;
import org.openqa.selenium.support.FindBy;
import com.cognifide.bdd.demo.po.summer.ImageComponent;
import com.cognifide.qa.bb.aem.page.AuthorPage;
import com.cognifide.qa.bb.qualifier.Frame;
import com.cognifide.qa.bb.qualifier.PageObject;
@PageObject
@Frame("$cq")
public class TrianglePage extends AuthorPage {
private static final String PAGE_URL = "/cf#/content/geometrixx/en/products/triangle.html";
private static final String PAGE_TITLE = "Triangle";
@FindBy(css = ".body_container .image")
private ImageComponent imageComponent;
@Override
public String getContentPath() {
return PAGE_URL;
}
@Override
public String getPageTitle() {
return PAGE_TITLE;
}
public ImageComponent getImageComponent() {
return imageComponent;
}
}
|
3e0db71994d68e10ae661908dc4d0025f6e2eb66 | 9,763 | java | Java | app/src/main/java/com/rba18/adapters/MoneyListAdapter.java | codyhalstead/RB18 | e4ffd63320be05a3072521f2126c7beac5a68552 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rba18/adapters/MoneyListAdapter.java | codyhalstead/RB18 | e4ffd63320be05a3072521f2126c7beac5a68552 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rba18/adapters/MoneyListAdapter.java | codyhalstead/RB18 | e4ffd63320be05a3072521f2126c7beac5a68552 | [
"Apache-2.0"
] | null | null | null | 44.377273 | 170 | 0.658199 | 5,799 | package com.rba18.adapters;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.rba18.R;
import com.rba18.helpers.DateAndCurrencyDisplayer;
import com.rba18.model.ExpenseLogEntry;
import com.rba18.model.MoneyLogEntry;
import com.rba18.model.PaymentLogEntry;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class MoneyListAdapter extends BaseAdapter implements Filterable {
private ArrayList<MoneyLogEntry> mMoneyArray;
private ArrayList<MoneyLogEntry> mFilteredResults;
private Context mContext;
private String mSearchText;
private ColorStateList mHighlightColor;
private Date mTodaysDate;
private Date mDateToHighlight;
private int mDateFormatCode, mMoneyFormatCode;
private boolean mGreyOutEnabled;
public MoneyListAdapter(Context context, ArrayList<MoneyLogEntry> moneyArray, ColorStateList highlightColor, @Nullable Date dateToHighlight, boolean greyOutEnabled) {
super();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
mMoneyArray = moneyArray;
mFilteredResults = moneyArray;
mContext = context;
mSearchText = "";
mHighlightColor = highlightColor;
mTodaysDate = new Date(System.currentTimeMillis());
mDateToHighlight = dateToHighlight;
mDateFormatCode = preferences.getInt("dateFormat", DateAndCurrencyDisplayer.DATE_MMDDYYYY);
mMoneyFormatCode = preferences.getInt("currency", DateAndCurrencyDisplayer.CURRENCY_US);
mGreyOutEnabled = greyOutEnabled;
}
private static class ViewHolder {
TextView amountTV;
TextView dateTV;
TextView typeTV;
TextView descriptionTV;
TextView wasCompletedTV;
}
@Override
public int getCount() {
if(mFilteredResults != null) {
return mFilteredResults.size();
}
return 0;
}
@Override
public MoneyLogEntry getItem(int i) {
return mFilteredResults.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
MoneyLogEntry moneyEntry = getItem(position);
MoneyListAdapter.ViewHolder viewHolder;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.row_expense, viewGroup, false);
viewHolder = new MoneyListAdapter.ViewHolder();
viewHolder.amountTV = convertView.findViewById(R.id.expenseRowAmountTV);
viewHolder.dateTV = convertView.findViewById(R.id.expenseRowDateTV);
viewHolder.typeTV = convertView.findViewById(R.id.expenseRowTypeTV);
viewHolder.descriptionTV = convertView.findViewById(R.id.expenseRowDescriptionTV);
viewHolder.wasCompletedTV = convertView.findViewById(R.id.expenseRowWasPaidTV);
convertView.setTag(viewHolder);
} else {
viewHolder = (MoneyListAdapter.ViewHolder) convertView.getTag();
}
if (moneyEntry != null) {
viewHolder.dateTV.setText(DateAndCurrencyDisplayer.getDateToDisplay(mDateFormatCode, moneyEntry.getDate()));
if(mDateToHighlight != null){
if(moneyEntry.getDate().equals(mDateToHighlight)){
viewHolder.dateTV.setTextColor(mContext.getResources().getColor(R.color.green_colorPrimaryDark));
} else {
viewHolder.dateTV.setTextColor(mContext.getResources().getColor(R.color.text_light));
}
}
if(mGreyOutEnabled) {
if (mTodaysDate.compareTo(moneyEntry.getDate()) < 0) {
convertView.setBackgroundColor(convertView.getResources().getColor(R.color.rowDarkenedBackground));
} else {
convertView.setBackgroundColor(convertView.getResources().getColor(R.color.white));
}
}
if(moneyEntry instanceof ExpenseLogEntry){
ExpenseLogEntry expense = (ExpenseLogEntry)moneyEntry;
viewHolder.amountTV.setText(DateAndCurrencyDisplayer.getCurrencyToDisplay(mMoneyFormatCode, expense.getAmount()));
viewHolder.typeTV.setText(expense.getTypeLabel());
viewHolder.amountTV.setTextColor(mContext.getResources().getColor(R.color.red));
if(expense.getIsCompleted()) {
viewHolder.wasCompletedTV.setText(R.string.paid);
viewHolder.wasCompletedTV.setTextColor(convertView.getResources().getColor(R.color.caldroid_black));
} else {
viewHolder.wasCompletedTV.setText(R.string.not_paid);
viewHolder.wasCompletedTV.setTextColor(convertView.getResources().getColor(R.color.red));
}
} else if(moneyEntry instanceof PaymentLogEntry){
PaymentLogEntry income = (PaymentLogEntry) moneyEntry;
viewHolder.amountTV.setText(DateAndCurrencyDisplayer.getCurrencyToDisplay(mMoneyFormatCode, income.getAmount()));
viewHolder.typeTV.setText(income.getTypeLabel());
viewHolder.amountTV.setTextColor(mContext.getResources().getColor(R.color.green_colorPrimaryDark));
if(income.getIsCompleted()) {
viewHolder.wasCompletedTV.setText(R.string.received);
viewHolder.wasCompletedTV.setTextColor(convertView.getResources().getColor(R.color.caldroid_black));
} else {
viewHolder.wasCompletedTV.setText(R.string.not_received);
viewHolder.wasCompletedTV.setTextColor(convertView.getResources().getColor(R.color.red));
}
} else {
viewHolder.amountTV.setText(DateAndCurrencyDisplayer.getCurrencyToDisplay(mMoneyFormatCode, moneyEntry.getAmount()));
viewHolder.typeTV.setText("");
viewHolder.amountTV.setTextColor(mContext.getResources().getColor(R.color.caldroid_darker_gray));
}
setTextHighlightSearch(viewHolder.descriptionTV, moneyEntry.getDescription());
}
return convertView;
}
//Used to change color of any text matching search
private void setTextHighlightSearch(TextView textView, String theTextToSet) {
//If user has any text in the search bar
if (mSearchText != null && !mSearchText.isEmpty()) {
int startPos = theTextToSet.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
int endPos = startPos + mSearchText.length();
if (startPos != -1) {
//If theTextToSet contains match, highlight match
Spannable spannable = new SpannableString(theTextToSet);
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, mHighlightColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
} else {
//Set regular text if not
textView.setText(theTextToSet);
}
} else {
//Set regular text if search bar is empty
textView.setText(theTextToSet);
}
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<MoneyLogEntry> FilteredArrayNames = new ArrayList<>();
mSearchText = constraint.toString().toLowerCase();
//Perform users search
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mMoneyArray.size(); i++) {
MoneyLogEntry dataNames = mMoneyArray.get(i);
//If users search matches any part of any apartment value, add to new filtered list
if (dataNames.getDescription().toLowerCase().contains(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mFilteredResults = (ArrayList<MoneyLogEntry>) filterResults.values;
notifyDataSetChanged();
}
};
}
//Retrieve filtered results
public ArrayList<MoneyLogEntry> getFilteredResults() {
return mFilteredResults;
}
public void updateResults(ArrayList<MoneyLogEntry> results) {
mMoneyArray = results;
mFilteredResults = results;
//Triggers the list update
notifyDataSetChanged();
}
}
|
3e0db73e9ca7bae5077fccb86f3264a9e6b54c72 | 692 | java | Java | AndyHo/Java/src/app/Q122_best_time_to_buy_and_sell_stock_2.java | QuenLo/leecode | ce861103949510dc54fd5cb336bd992c40748de2 | [
"MIT"
] | 6 | 2018-06-13T06:48:42.000Z | 2020-11-25T10:48:13.000Z | AndyHo/Java/src/app/Q122_best_time_to_buy_and_sell_stock_2.java | QuenLo/leecode | ce861103949510dc54fd5cb336bd992c40748de2 | [
"MIT"
] | null | null | null | AndyHo/Java/src/app/Q122_best_time_to_buy_and_sell_stock_2.java | QuenLo/leecode | ce861103949510dc54fd5cb336bd992c40748de2 | [
"MIT"
] | null | null | null | 28.833333 | 81 | 0.473988 | 5,800 | package app;
class Q122_best_time_to_buy_and_sell_stock_2
{
public int maxProfit(int[] prices)
{
if( prices.length == 0 || prices == null ) return 0;
int valley = prices[ 0 ];
int peak = prices[ 0 ];
int i = 0, maxprofit = 0;
while( i < prices.length - 1 )
{
// find the valley
while( i + 1 < prices.length && prices[ i ] >= prices[ i + 1 ] ) i++;
valley = prices[ i ];
// find the peak
while( i + 1 < prices.length && prices[ i ] <= prices[ i + 1 ] ) i++;
peak = prices[ i ];
maxprofit += (peak - valley);
}
return maxprofit;
}
} |
3e0db7e5aff30a21e8ece5731873be4c5d4c33c6 | 392 | java | Java | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/dao/SeckillSessionDao.java | HuFeiqun/gulimall | d1c5cdc5478c741c8c48aac556197337b9662255 | [
"Apache-2.0"
] | null | null | null | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/dao/SeckillSessionDao.java | HuFeiqun/gulimall | d1c5cdc5478c741c8c48aac556197337b9662255 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:11:01.000Z | 2021-09-20T21:00:44.000Z | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/dao/SeckillSessionDao.java | HuFeiqun/gulimall | d1c5cdc5478c741c8c48aac556197337b9662255 | [
"Apache-2.0"
] | null | null | null | 21.777778 | 77 | 0.77551 | 5,801 | package com.atguigu.gulimall.coupon.dao;
import com.atguigu.gulimall.coupon.entity.SeckillSessionEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 秒杀活动场次
*
* @author hfq
* @email anpch@example.com
* @date 2020-07-14 22:03:31
*/
@Mapper
public interface SeckillSessionDao extends BaseMapper<SeckillSessionEntity> {
}
|
3e0db8a60093ddd9552358840015895689d3ce0b | 6,930 | java | Java | src/android/DialogWifiImpl.java | LiuHaoFight/DialogWifi | afb3d69e205090b1611e4fed99f56676ffde5298 | [
"Apache-2.0"
] | null | null | null | src/android/DialogWifiImpl.java | LiuHaoFight/DialogWifi | afb3d69e205090b1611e4fed99f56676ffde5298 | [
"Apache-2.0"
] | null | null | null | src/android/DialogWifiImpl.java | LiuHaoFight/DialogWifi | afb3d69e205090b1611e4fed99f56676ffde5298 | [
"Apache-2.0"
] | null | null | null | 30 | 100 | 0.627561 | 5,802 | package com.siemens.plugins.DialogWifi;
import android.util.Log;
import com.koushikdutta.async.AsyncSSLSocket;
import com.koushikdutta.async.AsyncSSLSocketWrapper;
import com.koushikdutta.async.AsyncServer;
import com.koushikdutta.async.AsyncSocket;
import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.callback.CompletedCallback;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class DialogWifiImpl {
private static final String TAG = DialogWifi.class.getSimpleName();
private boolean mIsSocketConnected = false;
// socket
private AsyncSSLSocket mSSLSocket = null;
private SSLParameters sslParameters;
public String mHost;
public int mPort;
private ISocketStatusCallback mSocketStatusCallback;
public interface ISocketStatusCallback {
void onConnectResult(boolean connected);
void onClosed();
void onDateReport(JSONObject jsonObject);
}
public interface IWriteCallback {
void onWriteResult(boolean result);
}
public void setHost(String host, int port) {
this.mHost = host;
this.mPort = port;
}
public void write(JSONObject object, CompletedCallback callback) {
if (mSSLSocket != null && mSSLSocket.isOpen()) {
Log.i(TAG, "Socket is opened");
} else {
Log.e(TAG, "Socket is closed");
callback.onCompleted(new Exception());
return;
}
byte[] byteMsg = object.toString().getBytes(StandardCharsets.UTF_8);
if (byteMsg == null) {
return;
}
com.koushikdutta.async.Util.writeAll(mSSLSocket, byteMsg, callback);
}
/**
* Socket connection initialize.
*/
public void onInitSocket(ISocketStatusCallback callback) {
Log.i(TAG, "onInitSocket()");
this.mSocketStatusCallback = callback;
onClose();
// if (mIsSocketConnected || mSSLSocket != null) {
// Log.e(TAG, "Socket already connected.");
// if (this.mSocketStatusCallback != null) {
// this.mSocketStatusCallback.onConnectResult(true);
// }
// return;
// }
// mIsSocketConnected = true;
// if (mSSLSocket == null || !mSSLSocket.isOpen()) {
new Runnable() {
@Override
public void run() {
AsyncServer.getDefault().connectSocket(new InetSocketAddress(mHost, mPort),
(Exception ex, final AsyncSocket socket) -> {
Log.i(TAG, "AP Server Connection Completed");
if (socket != null && ex == null) {
handleConnectCompletedWithTLS(socket);
} else {
Log.e(TAG, "Socket is not connected.");
mIsSocketConnected = false;
if (mSocketStatusCallback != null) {
mSocketStatusCallback.onConnectResult(false);
}
}
});
}
}.run();
// } else {
// Log.i(TAG, "Socket is already Opened.");
// }
}
public void onClose() {
Log.i(TAG, "onClose.");
if (mSSLSocket != null) {
mSSLSocket.close();
mSSLSocket = null;
mIsSocketConnected = false;
}
}
/**
* Socket Connect Handler Registration With TLS
*/
private void handleConnectCompletedWithTLS(final AsyncSocket socket) {
Log.i(TAG, "handleConnectCompletedWithTLS");
SSLContext sslCtx;
SSLEngine sslEng = null;
TrustManager[] tm = null;
try {
tm = new TrustManager[] { createTrustMangerForAll() };
try {
sslParameters = SSLContext.getDefault().getDefaultSSLParameters();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Log.d(TAG, "sslParameters.getProtocols() = " + Arrays.toString(sslParameters.getProtocols()));
sslCtx = SSLContext.getInstance("TLSv1.2");
sslCtx.init(null, tm, new SecureRandom());
sslEng = sslCtx.createSSLEngine();
} catch (Exception e) {
Log.e(TAG, "SSLContext Init Unknown Exception Error");
e.printStackTrace();
}
AsyncSSLSocketWrapper.handshake(socket, mHost, 9900,
sslEng, tm, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, true,
(Exception e, AsyncSSLSocket sslSocket) -> {
Log.i(TAG, "onHandshakeComplete");
if (e != null || sslSocket == null) {
Log.e(TAG, "onHandshakeCompleted Error");
e.printStackTrace();
mIsSocketConnected = false;
mSSLSocket = null;
if (mSocketStatusCallback != null) {
mSocketStatusCallback.onConnectResult(false);
}
return;
}
mSSLSocket = sslSocket;
sslSocket.setWriteableCallback(() -> Log.i(TAG, "Writeable CallBack"));
// Data Callback from Device AP
sslSocket.setDataCallback((DataEmitter emitter, ByteBufferList bb) -> {
Log.i(TAG, "DataCallback");
if (bb != null) {
Log.i(TAG, "[TLS] received : " + bb.toString());
try {
JSONObject jsonObject = new JSONObject(bb.readString());
if (mSocketStatusCallback != null) {
mSocketStatusCallback.onDateReport(jsonObject);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
} else {
Log.i(TAG, "input is null~~");
}
});
// Socket close Callback
sslSocket.setClosedCallback(ex1 -> {
Log.i(TAG, "Socket Closed");
if (ex1 != null) {
Log.e(TAG, "ClosedCallback Error");
ex1.printStackTrace();
}
if (mSocketStatusCallback != null) {
mSocketStatusCallback.onClosed();
}
});
sslSocket.setEndCallback(ex12 -> {
Log.i(TAG, "Socket End");
if (ex12 != null) {
Log.e(TAG, "EndCallback Error");
ex12.printStackTrace();
}
if (mSocketStatusCallback != null) {
mSocketStatusCallback.onClosed();
}
});
if (mSocketStatusCallback != null) {
mSocketStatusCallback.onConnectResult(true);
}
});
}
/**
* Create TrustManager for All Cert
*/
private TrustManager createTrustMangerForAll() {
return new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
};
}
}
|
3e0db90ff7a1e60f27c03c84a764263554f8a142 | 2,915 | java | Java | jbone-sys/jbone-sys-common/src/main/java/cn/jbone/sys/common/UserRequestDO.java | wuming89/jbone | 5ed64e46d055110878b9d5f1234aca266afe4d4b | [
"Apache-2.0"
] | 3 | 2020-11-12T06:36:00.000Z | 2020-11-12T06:36:03.000Z | jbone-sys/jbone-sys-common/src/main/java/cn/jbone/sys/common/UserRequestDO.java | wuming89/jbone | 5ed64e46d055110878b9d5f1234aca266afe4d4b | [
"Apache-2.0"
] | 5 | 2019-11-13T12:22:32.000Z | 2021-05-08T17:58:17.000Z | jbone-sys/jbone-sys-common/src/main/java/cn/jbone/sys/common/UserRequestDO.java | wuming89/jbone | 5ed64e46d055110878b9d5f1234aca266afe4d4b | [
"Apache-2.0"
] | 1 | 2021-05-23T14:18:15.000Z | 2021-05-23T14:18:15.000Z | 31.010638 | 122 | 0.727959 | 5,803 | package cn.jbone.sys.common;
import cn.jbone.common.dataobject.SearchListDO;
import lombok.Data;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
@Data
public class UserRequestDO extends SearchListDO {
Integer userId;
String username;
List<UserRequestModule> modules = Arrays.asList(UserRequestModule.BASE);
String serverName;
String roleName;
String realName;
List<Integer> userIds;
public UserRequestDO(){}
public UserRequestDO(Integer userId){
this.userId = userId;
}
public UserRequestDO(Integer userId,List<UserRequestModule> userRequestModules){
this.userId = userId;
modules.addAll(userRequestModules);
}
public static UserRequestDO buildSimple(String username){
UserRequestDO userRequestDO = new UserRequestDO();
userRequestDO.setUsername(username);
return userRequestDO;
}
public static UserRequestDO buildSimple(Integer userId){
UserRequestDO userRequestDO = new UserRequestDO();
userRequestDO.setUserId(userId);
return userRequestDO;
}
public static UserRequestDO buildSimple(List<Integer> userIds){
UserRequestDO userRequestDO = new UserRequestDO();
userRequestDO.setUserIds(userIds);
return userRequestDO;
}
public static UserRequestDO buildSecurity(String username){
UserRequestDO userRequestDO = new UserRequestDO();
userRequestDO.setUsername(username);
userRequestDO.setModules(Arrays.asList(UserRequestModule.BASE,UserRequestModule.SECURITY));
return userRequestDO;
}
public static UserRequestDO buildSecurity(Integer userId){
UserRequestDO userRequestDO = new UserRequestDO();
userRequestDO.setUserId(userId);
userRequestDO.setModules(Arrays.asList(UserRequestModule.BASE,UserRequestModule.SECURITY));
return userRequestDO;
}
public static UserRequestDO buildAll(Integer userId,String serverName){
UserRequestDO userRequestDO = new UserRequestDO();
userRequestDO.setUserId(userId);
userRequestDO.setModules(Arrays.asList(UserRequestModule.BASE,UserRequestModule.AUTH,UserRequestModule.SECURITY));
userRequestDO.setServerName(serverName);
return userRequestDO;
}
public static UserRequestDO buildAll(String username,String serverName){
UserRequestDO userRequestDO = new UserRequestDO();
userRequestDO.setUsername(username);
userRequestDO.setModules(Arrays.asList(UserRequestModule.BASE,UserRequestModule.AUTH,UserRequestModule.SECURITY));
userRequestDO.setServerName(serverName);
return userRequestDO;
}
public enum UserRequestModule{
BASE,SECURITY,AUTH
}
public boolean containsModule(UserRequestModule userRequestModule){
return modules.contains(userRequestModule);
}
}
|
3e0dba28afca956b4dfa53012dcedecb1dc43c7d | 84 | java | Java | app/src/main/java/com/xin/coolweather/gson/Image.java | star0224/coolweather | 52fd832808327603a42c658448b1ed014b37f6d5 | [
"Apache-2.0"
] | 1 | 2019-04-15T08:13:52.000Z | 2019-04-15T08:13:52.000Z | app/src/main/java/com/xin/coolweather/gson/Image.java | star0224/coolweather | 52fd832808327603a42c658448b1ed014b37f6d5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/xin/coolweather/gson/Image.java | star0224/coolweather | 52fd832808327603a42c658448b1ed014b37f6d5 | [
"Apache-2.0"
] | null | null | null | 9.333333 | 33 | 0.702381 | 5,804 | package com.xin.coolweather.gson;
public class Image {
public String url;
}
|
3e0dba89e9a9d41d0134e54955c64bd85f422f7a | 540 | java | Java | src/main/java/KnowledgeableReview201901/designPatterns/proxy/ProxyImage.java | zkydrx/mypractices | 894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07 | [
"Apache-2.0"
] | null | null | null | src/main/java/KnowledgeableReview201901/designPatterns/proxy/ProxyImage.java | zkydrx/mypractices | 894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07 | [
"Apache-2.0"
] | 1 | 2020-06-15T20:06:08.000Z | 2020-06-15T20:06:08.000Z | src/main/java/KnowledgeableReview201901/designPatterns/proxy/ProxyImage.java | zkydrx/mypractices | 894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07 | [
"Apache-2.0"
] | null | null | null | 18 | 55 | 0.62037 | 5,805 | package KnowledgeableReview201901.designPatterns.proxy;
/**
* Created with IntelliJ IDEA.
* Author: Abbot
* Date: 2018-03-22
* Time: 09:31:21
* Description:
*/
public class ProxyImage implements Image
{
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName)
{
this.fileName = fileName;
}
@Override
public void display()
{
if(realImage ==null)
{
realImage = new RealImage(fileName);
}
realImage.display();
}
}
|
3e0dbb4d7b3b2b9bddc3ab3edff0b817aae7ba73 | 2,590 | java | Java | src/main/java/com/chillimport/server/entities/ObservedProperty.java | Tschuuuls/ChillImport | b44fddc537be81c157dc9598662a79e26444a4a7 | [
"MIT"
] | null | null | null | src/main/java/com/chillimport/server/entities/ObservedProperty.java | Tschuuuls/ChillImport | b44fddc537be81c157dc9598662a79e26444a4a7 | [
"MIT"
] | 166 | 2019-12-06T11:20:14.000Z | 2022-03-25T04:13:56.000Z | src/main/java/com/chillimport/server/entities/ObservedProperty.java | Tschuuuls/ChillImport | b44fddc537be81c157dc9598662a79e26444a4a7 | [
"MIT"
] | 5 | 2019-09-17T08:36:29.000Z | 2021-06-09T08:51:28.000Z | 30.833333 | 134 | 0.669112 | 5,806 | package com.chillimport.server.entities;
import de.fraunhofer.iosb.ilt.sta.service.SensorThingsService;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* describes an observed property, which specifies the phenomenon of an observation
*/
public class ObservedProperty extends Entity {
private String definition;
public ObservedProperty() {
}
/**
* creates a new observed property
*
* @param name name of the observed property
* @param description description of the observed property
* @param definition definition of the observed property
*/
public ObservedProperty(String name, String description, String definition) {
super(name, description);
this.definition = definition;
}
/**
* converts a frost standard observed property to a chillimport standard observed property
*
* @param obsprop frost standard observed property
*/
public ObservedProperty(de.fraunhofer.iosb.ilt.sta.model.ObservedProperty obsprop) {
super(obsprop.getName(), obsprop.getDescription());
this.setFrostId(obsprop.getId().getJson());
this.definition = obsprop.getDefinition();
}
/**
* returns the definition of the observed property
*
* @return definition of the observed property
*/
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
/**
* converts the chillimport standard observed property to a frost standard observed property
*
* @return frost standard observed property
*
* @throws URISyntaxException if definition string has wrong syntax
*/
public de.fraunhofer.iosb.ilt.sta.model.ObservedProperty convertToFrostStandard(URL frostUrl) throws URISyntaxException {
if (!(getFrostId() == null || getFrostId().isEmpty())) {
SensorThingsService service;
try {
service = new SensorThingsService(frostUrl);
return service.observedProperties().find(Long.parseLong(getFrostId()));
} catch (Exception e) {
}
}
return new de.fraunhofer.iosb.ilt.sta.model.ObservedProperty(this.getName(), new URI(this.definition), this.getDescription());
}
@Override
public boolean equals(Object obj) {
return (obj instanceof ObservedProperty &&
super.equals(obj) && this.definition.equals(((ObservedProperty) obj).getDefinition()));
}
}
|
3e0dbb58bb6284823e9ffcbf5bcfdfb9bcd9eb12 | 811 | java | Java | broccoli-core/src/main/java/nl/tudelft/broccoli/core/powerup/joker/JokerPowerUp.java | fabianishere/broccoli | 5f36652aa59a4c04f53d6272e638f5d520e5668a | [
"MIT"
] | 3 | 2018-12-19T07:16:40.000Z | 2019-11-26T05:22:59.000Z | broccoli-core/src/main/java/nl/tudelft/broccoli/core/powerup/joker/JokerPowerUp.java | fabianishere/broccoli | 5f36652aa59a4c04f53d6272e638f5d520e5668a | [
"MIT"
] | null | null | null | broccoli-core/src/main/java/nl/tudelft/broccoli/core/powerup/joker/JokerPowerUp.java | fabianishere/broccoli | 5f36652aa59a4c04f53d6272e638f5d520e5668a | [
"MIT"
] | null | null | null | 33.12 | 91 | 0.730676 | 5,807 | package nl.tudelft.broccoli.core.powerup.joker;
import nl.tudelft.broccoli.core.MarbleType;
import nl.tudelft.broccoli.core.nexus.NexusContext;
import nl.tudelft.broccoli.core.powerup.PowerUp;
import nl.tudelft.broccoli.core.receptor.Receptor;
/**
* This power-up spawns two joker marbles as soon as it is activated.
*
* @author Fabian Mastenbroek (nnheo@example.com)
*/
public class JokerPowerUp implements PowerUp {
/**
* This method will be invoked when the player has activated the power-up.
*
* @param receptor The receptor that has obtained the power-up.
*/
@Override
public void activate(Receptor receptor) {
NexusContext context = receptor.getTile().getGrid().getSession().getNexusContext();
context.add(MarbleType.JOKER, MarbleType.JOKER);
}
}
|
3e0dbc3c26b6e82f58b237b4aeb003782bf352a2 | 863 | java | Java | src/main/java/io/github/vertxchina/nodes/NavigatableScene.java | czj4093/ShallVTalk | 1bfc81fa4ec1e886b972eaf8b4f38d8f2909990a | [
"MIT"
] | 15 | 2022-02-24T12:21:12.000Z | 2022-03-13T13:36:14.000Z | src/main/java/io/github/vertxchina/nodes/NavigatableScene.java | czj4093/ShallVTalk | 1bfc81fa4ec1e886b972eaf8b4f38d8f2909990a | [
"MIT"
] | 1 | 2022-02-24T04:21:13.000Z | 2022-02-24T04:21:13.000Z | src/main/java/io/github/vertxchina/nodes/NavigatableScene.java | czj4093/ShallVTalk | 1bfc81fa4ec1e886b972eaf8b4f38d8f2909990a | [
"MIT"
] | 21 | 2022-02-24T05:09:00.000Z | 2022-03-15T03:05:06.000Z | 25.382353 | 75 | 0.727694 | 5,808 | package io.github.vertxchina.nodes;
import javafx.scene.Parent;
import javafx.scene.Scene;
import java.util.HashMap;
import java.util.Map;
public class NavigatableScene extends Scene {
public NavigatableScene(ConstructorFunction function, Map parameters){
super(function.construct(parameters));
routes.put("/",function);
}
public Map<String, ConstructorFunction> routes = new HashMap<>();
public NavigatableScene route(String path, ConstructorFunction function){
routes.put(path, function);
return this;
}
public Parent navigate(String path){
return navigate(path, new HashMap<>());
}
public Parent navigate(String path, Map parameters){
var root = this.routes.get(path).construct(parameters);
this.setRoot(root);
this.getWindow().sizeToScene();
this.getWindow().centerOnScreen();
return root;
}
}
|
3e0dbcd60aa110feae69339ff2267fa6bd958e61 | 1,129 | java | Java | sharepoint/src/main/java/com/zaubersoftware/jiol/sharepoint/items/ListItem.java | jcodagnone/jiolsucker | 54f7bde409b7f9fe35745eb574d53453d1846be8 | [
"Apache-2.0"
] | 1 | 2015-06-23T12:37:43.000Z | 2015-06-23T12:37:43.000Z | sharepoint/src/main/java/com/zaubersoftware/jiol/sharepoint/items/ListItem.java | jcodagnone/jiolsucker | 54f7bde409b7f9fe35745eb574d53453d1846be8 | [
"Apache-2.0"
] | null | null | null | sharepoint/src/main/java/com/zaubersoftware/jiol/sharepoint/items/ListItem.java | jcodagnone/jiolsucker | 54f7bde409b7f9fe35745eb574d53453d1846be8 | [
"Apache-2.0"
] | null | null | null | 31.361111 | 77 | 0.697963 | 5,809 | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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.zaubersoftware.jiol.sharepoint.items;
/**
* Sharepoint List Item
* http://msdn.microsoft.com/en-us/library/ms774821(v=office.12).aspx
*
* @author Juan F. Codagnone
* @since Mar 8, 2011
*/
public interface ListItem {
/** @return true if the item contains the property */
boolean contains(String key);
/** @return item property */
String get(String key);
/** @return item property typed */
<T> T get(String key, Class<T> clazz);
}
|
3e0dbe8aa0af1120fd4f0ebb7a46dc1691ffca83 | 319 | java | Java | hands-on/2-spring-data/src/main/java/com/datastax/workshop/hello/HelloWorldRestController.java | datastaxdevs/conference-2021-javazone | c7e2813c92aad25f0c847d4b545043cd0b4bec7d | [
"Apache-2.0"
] | null | null | null | hands-on/2-spring-data/src/main/java/com/datastax/workshop/hello/HelloWorldRestController.java | datastaxdevs/conference-2021-javazone | c7e2813c92aad25f0c847d4b545043cd0b4bec7d | [
"Apache-2.0"
] | null | null | null | hands-on/2-spring-data/src/main/java/com/datastax/workshop/hello/HelloWorldRestController.java | datastaxdevs/conference-2021-javazone | c7e2813c92aad25f0c847d4b545043cd0b4bec7d | [
"Apache-2.0"
] | null | null | null | 22.785714 | 62 | 0.742947 | 5,810 | package com.datastax.workshop.hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldRestController {
@RequestMapping("/")
public String hello() {
return "Hello World !";
}
} |
3e0dbec2c117a0235008615a946036c9b3012806 | 1,088 | java | Java | src/main/java/com/mysiteforme/admin/upload/UploadUtil.java | laoxiong168/eclectric | 06cfe672a12856617015031469e5629dfd0f835c | [
"Apache-2.0"
] | 2 | 2019-07-29T10:28:05.000Z | 2019-07-29T10:28:11.000Z | src/main/java/com/mysiteforme/admin/upload/UploadUtil.java | laoxiong168/eclectric | 06cfe672a12856617015031469e5629dfd0f835c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mysiteforme/admin/upload/UploadUtil.java | laoxiong168/eclectric | 06cfe672a12856617015031469e5629dfd0f835c | [
"Apache-2.0"
] | null | null | null | 21.76 | 90 | 0.66636 | 5,811 | package com.mysiteforme.admin.upload;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
/**
* Created by wangl on 2018/2/8.
* todo: 云上传工具
*/
public interface UploadUtil {
/**
* 文件上传方法
* @param file MultipartFile文件对象
* @return 文件在云上的地址
*/
public String upload(MultipartFile file) throws IOException, NoSuchAlgorithmException;
/**
* 删除已经上传到云上的文件
* @param path 文件地址
* @return 是否删除成功
*/
public Boolean delet(String path);
/**
* 上传网络文件
* @param url 网络文件的地址
* @return 文件在云上的地址
*/
public String uploadNetFile(String url) throws IOException, NoSuchAlgorithmException;
/**
* 上传本地指定路径的图片
* @param localPath (指的是用户的)本地路径
* @return
*/
public String uploadLocalImg(String localPath);
/**
* 上传base64格式的文件
* @param base64 文件的base64编码
* @return
*/
public String uploadBase64(String base64);
}
|
3e0dbefc6ac3a2f80838e686f31ec3f22dfcd47d | 6,602 | java | Java | core/src/test/java/io/costax/jpa/fetching/BestWayToFetchAnAssociationDefinedByASubclass.java | jlmc/hibernate-tunings | 2f6a8e807c6b77e9b456c851b9a6569a4b3fac68 | [
"MIT"
] | 2 | 2019-11-19T23:27:29.000Z | 2020-12-10T07:26:35.000Z | core/src/test/java/io/costax/jpa/fetching/BestWayToFetchAnAssociationDefinedByASubclass.java | jlmc/hibernate-tunings | 2f6a8e807c6b77e9b456c851b9a6569a4b3fac68 | [
"MIT"
] | 16 | 2019-02-03T13:01:08.000Z | 2022-02-16T01:14:39.000Z | core/src/test/java/io/costax/jpa/fetching/BestWayToFetchAnAssociationDefinedByASubclass.java | jlmc/hibernate-tunings | 2f6a8e807c6b77e9b456c851b9a6569a4b3fac68 | [
"MIT"
] | 1 | 2019-11-19T23:27:31.000Z | 2019-11-19T23:27:31.000Z | 29.473214 | 120 | 0.538473 | 5,812 | package io.costax.jpa.fetching;
import io.costax.jpa.util.HSQLDBJPATest;
import org.junit.jupiter.api.Test;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import static java.time.LocalDate.parse;
/**
* By using Hibernate’s 1st level cache and its guarantee that within a Hibernate Session,
* a database record gets only mapped by 1 entity object, you can implement this very efficiently.
* Your 1st query gets all the Book entities and their Publisher, which you need for your use case.
*/
public class BestWayToFetchAnAssociationDefinedByASubclass extends HSQLDBJPATest {
@Override
protected Class<?>[] entities() {
return new Class[]{
Publication.class,
Book.class,
BlogPost.class,
Publisher.class,
Author.class
};
}
@Override
protected void additionalProperties(final Properties properties) {
properties.put("hibernate.format_sql", "true");
}
@Override
protected void afterInit() {
// create some records
doInJPA(em -> {
Author luisCamoes = new Author("Luis", "Camões");
Author fernandoPessoa = new Author("Fernando", "Pessoa");
Author joaoCosta = new Author("Joao", "Costa");
em.persist(luisCamoes);
em.persist(fernandoPessoa);
em.persist(joaoCosta);
final Publisher publisherPT = new Publisher("Portugal a ler");
em.persist(publisherPT);
fernandoPessoa.add(
new Book("O banqueiro anarquista", parse("1922-01-01"), 123, publisherPT));
fernandoPessoa.add(
new Book("Mensagem", parse("1934-01-01"), 123, publisherPT));
luisCamoes.add(
new Book("Lusiadas", parse("1572-01-01"), 123, publisherPT));
joaoCosta.add(
new BlogPost("Best Way To Fetch An Association Defined By A Subclass", parse("2020-06-22"), "xxx"));
});
}
@Test
void test() {
final List<Publication> publications1 =
doInJPA(em -> {
final List<Book> booksWithPublisherFetched = em.createQuery("""
select b
from Book b
join b.author a
join fetch b.publisher p
where a.lastName = :lastName
"""
, Book.class)
.setParameter("lastName", "Pessoa")
.getResultList();
for (Book b : booksWithPublisherFetched) {
LOGGER.info("{}", b);
}
final List<Publication> publications = em.createQuery("""
select p
from Publication p
join p.author a
where a.lastName = :lastName
""", Publication.class)
.setParameter("lastName", "Pessoa")
.getResultList();
return publications;
});
for (Publication p : publications1) {
if (p instanceof BlogPost) {
BlogPost blog = (BlogPost) p;
LOGGER.info("BlogPost - " + blog.title + " was published at " + blog.url);
} else {
Book book = (Book) p;
LOGGER.info("Book - " + book.title + " was published by " + book.publisher.name);
LOGGER.info("{}", book);
}
}
}
@Entity(name = "Publication")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
//@DiscriminatorColumn()
static abstract class Publication {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
protected String title;
@Version
protected int version;
@ManyToOne(fetch = FetchType.LAZY)
protected Author author;
protected LocalDate publishingDate;
protected Publication() {
}
public Publication(final String title, final LocalDate publishingDate) {
this.title = title;
this.publishingDate = publishingDate;
}
public void setAuthor(final Author author) {
this.author = author;
}
}
@Entity(name = "BlogPost")
@DiscriminatorValue("BlogPost")
static class BlogPost extends Publication {
private String url;
BlogPost() {
}
public BlogPost(final String title, final LocalDate publishingDate, final String url) {
super(title, publishingDate);
this.url = url;
}
}
@Entity(name = "Book")
@DiscriminatorValue("Book")
static class Book extends Publication {
private int pages;
@ManyToOne
private Publisher publisher;
Book() {
}
public Book(final String title, final LocalDate publishingDate, final int pages, final Publisher publisher) {
super(title, publishingDate);
this.pages = pages;
this.publisher = publisher;
}
}
@Entity(name = "Publisher")
static class Publisher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
Publisher() {
}
public Publisher(final String name) {
this.name = name;
}
}
@Entity(name = "Author")
static class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@Version
private int version;
@OneToMany(mappedBy = "author", cascade = {CascadeType.ALL}, orphanRemoval = true)
private final Set<Publication> publications = new HashSet<>();
Author() {
}
public Author(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void add(Publication publication) {
publication.setAuthor(this);
publications.add(publication);
}
}
}
|
3e0dc0166c0e3ba44bd31fe44333dc0d231d1563 | 1,260 | java | Java | src/main/java/io/airlift/airline/ParseArgumentsUnexpectedException.java | Siddhesh-Ghadi/airline | cc79a8f120c459fb79ee3f55d5e00392b4a616d5 | [
"Apache-2.0"
] | 681 | 2015-01-05T09:20:19.000Z | 2022-01-26T13:40:42.000Z | src/main/java/io/airlift/airline/ParseArgumentsUnexpectedException.java | Siddhesh-Ghadi/airline | cc79a8f120c459fb79ee3f55d5e00392b4a616d5 | [
"Apache-2.0"
] | 37 | 2015-01-12T11:30:53.000Z | 2021-12-25T23:15:59.000Z | src/main/java/io/airlift/airline/ParseArgumentsUnexpectedException.java | Siddhesh-Ghadi/airline | cc79a8f120c459fb79ee3f55d5e00392b4a616d5 | [
"Apache-2.0"
] | 123 | 2015-01-20T07:41:31.000Z | 2022-01-26T13:40:46.000Z | 30.731707 | 75 | 0.738095 | 5,813 | /*
* Copyright (C) 2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 io.airlift.airline;
import com.google.common.collect.ImmutableList;
import java.util.List;
public class ParseArgumentsUnexpectedException
extends ParseException
{
private final List<String> unparsedInput;
ParseArgumentsUnexpectedException(List<String> unparsedInput)
{
super("Found unexpected parameters: %s", unparsedInput);
this.unparsedInput = ImmutableList.copyOf(unparsedInput);
}
public List<String> getUnparsedInput()
{
return unparsedInput;
}
}
|
3e0dc0679013a78eddc7a2834bcb8c85dc4834f7 | 147,689 | java | Java | engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceInteractionTest.java | AndreaGiardini/camunda-bpm-platform | ce60b6799ab381f817f1b6f39883576678a43cfa | [
"Apache-2.0"
] | 1 | 2020-05-20T19:15:09.000Z | 2020-05-20T19:15:09.000Z | engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceInteractionTest.java | AndreaGiardini/camunda-bpm-platform | ce60b6799ab381f817f1b6f39883576678a43cfa | [
"Apache-2.0"
] | null | null | null | engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceInteractionTest.java | AndreaGiardini/camunda-bpm-platform | ce60b6799ab381f817f1b6f39883576678a43cfa | [
"Apache-2.0"
] | null | null | null | 42.390643 | 194 | 0.74382 | 5,814 | package org.camunda.bpm.engine.rest;
import static com.jayway.restassured.RestAssured.given;
import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ID;
import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockBatch;
import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.camunda.bpm.engine.AuthorizationException;
import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.batch.Batch;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery;
import org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl;
import org.camunda.bpm.engine.impl.HistoryServiceImpl;
import org.camunda.bpm.engine.impl.ManagementServiceImpl;
import org.camunda.bpm.engine.impl.RuntimeServiceImpl;
import org.camunda.bpm.engine.impl.batch.BatchEntity;
import org.camunda.bpm.engine.impl.util.IoUtil;
import org.camunda.bpm.engine.rest.dto.batch.BatchDto;
import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto;
import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto;
import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto;
import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceSuspensionStateDto;
import org.camunda.bpm.engine.rest.dto.runtime.SetJobRetriesByProcessDto;
import org.camunda.bpm.engine.rest.dto.runtime.batch.DeleteProcessInstancesDto;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.exception.RestException;
import org.camunda.bpm.engine.rest.helper.EqualsList;
import org.camunda.bpm.engine.rest.helper.EqualsMap;
import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper;
import org.camunda.bpm.engine.rest.helper.ExampleVariableObject;
import org.camunda.bpm.engine.rest.helper.MockObjectValue;
import org.camunda.bpm.engine.rest.helper.MockProvider;
import org.camunda.bpm.engine.rest.helper.VariableTypeHelper;
import org.camunda.bpm.engine.rest.helper.variable.EqualsNullValue;
import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue;
import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue;
import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue;
import org.camunda.bpm.engine.rest.util.JsonPathUtil;
import org.camunda.bpm.engine.rest.util.ModificationInstructionBuilder;
import org.camunda.bpm.engine.rest.util.VariablesBuilder;
import org.camunda.bpm.engine.rest.util.container.TestContainerRule;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.ProcessInstanceModificationInstantiationBuilder;
import org.camunda.bpm.engine.runtime.ProcessInstanceQuery;
import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateSelectBuilder;
import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateTenantBuilder;
import org.camunda.bpm.engine.runtime.UpdateProcessInstancesSuspensionStateBuilder;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.type.SerializableValueType;
import org.camunda.bpm.engine.variable.type.ValueType;
import org.camunda.bpm.engine.variable.value.FileValue;
import org.camunda.bpm.engine.variable.value.LongValue;
import org.camunda.bpm.engine.variable.value.ObjectValue;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import org.mockito.Mockito;
public class ProcessInstanceRestServiceInteractionTest extends
AbstractRestServiceTest {
protected static final String TEST_DELETE_REASON = "test";
protected static final String RETRIES = "retries";
@ClassRule
public static TestContainerRule rule = new TestContainerRule();
protected static final String PROCESS_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/process-instance";
protected static final String SINGLE_PROCESS_INSTANCE_URL = PROCESS_INSTANCE_URL + "/{id}";
protected static final String PROCESS_INSTANCE_VARIABLES_URL = SINGLE_PROCESS_INSTANCE_URL + "/variables";
protected static final String DELETE_PROCESS_INSTANCES_ASYNC_URL = PROCESS_INSTANCE_URL + "/delete";
protected static final String DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL = PROCESS_INSTANCE_URL + "/delete-historic-query-based";
protected static final String SET_JOB_RETRIES_ASYNC_URL = PROCESS_INSTANCE_URL + "/job-retries";
protected static final String SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL = PROCESS_INSTANCE_URL + "/job-retries-historic-query-based";
protected static final String SINGLE_PROCESS_INSTANCE_VARIABLE_URL = PROCESS_INSTANCE_VARIABLES_URL + "/{varId}";
protected static final String SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL = SINGLE_PROCESS_INSTANCE_VARIABLE_URL + "/data";
protected static final String PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL = SINGLE_PROCESS_INSTANCE_URL + "/activity-instances";
protected static final String EXAMPLE_PROCESS_INSTANCE_ID_WITH_NULL_VALUE_AS_VARIABLE = "aProcessInstanceWithNullValueAsVariable";
protected static final String SINGLE_PROCESS_INSTANCE_SUSPENDED_URL = SINGLE_PROCESS_INSTANCE_URL + "/suspended";
protected static final String PROCESS_INSTANCE_SUSPENDED_URL = PROCESS_INSTANCE_URL + "/suspended";
protected static final String PROCESS_INSTANCE_SUSPENDED_ASYNC_URL = PROCESS_INSTANCE_URL + "/suspended-async";
protected static final String PROCESS_INSTANCE_MODIFICATION_URL = SINGLE_PROCESS_INSTANCE_URL + "/modification";
protected static final String PROCESS_INSTANCE_MODIFICATION_ASYNC_URL = SINGLE_PROCESS_INSTANCE_URL + "/modification-async";
protected static final VariableMap EXAMPLE_OBJECT_VARIABLES = Variables.createVariables();
static {
ExampleVariableObject variableValue = new ExampleVariableObject();
variableValue.setProperty1("aPropertyValue");
variableValue.setProperty2(true);
EXAMPLE_OBJECT_VARIABLES.putValueTyped(EXAMPLE_VARIABLE_KEY,
MockObjectValue
.fromObjectValue(Variables.objectValue(variableValue).serializationDataFormat("application/json").create())
.objectTypeName(ExampleVariableObject.class.getName()));
}
private RuntimeServiceImpl runtimeServiceMock;
private ManagementServiceImpl mockManagementService;
private HistoryServiceImpl historyServiceMock;
private UpdateProcessInstanceSuspensionStateTenantBuilder mockUpdateSuspensionStateBuilder;
private UpdateProcessInstanceSuspensionStateSelectBuilder mockUpdateSuspensionStateSelectBuilder;
private UpdateProcessInstancesSuspensionStateBuilder mockUpdateProcessInstancesSuspensionStateBuilder;
@Before
public void setUpRuntimeData() {
runtimeServiceMock = mock(RuntimeServiceImpl.class);
mockManagementService = mock(ManagementServiceImpl.class);
historyServiceMock = mock(HistoryServiceImpl.class);
// variables
when(runtimeServiceMock.getVariablesTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, true)).thenReturn(EXAMPLE_VARIABLES);
when(runtimeServiceMock.getVariablesTyped(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, true)).thenReturn(EXAMPLE_OBJECT_VARIABLES);
when(runtimeServiceMock.getVariablesTyped(EXAMPLE_PROCESS_INSTANCE_ID_WITH_NULL_VALUE_AS_VARIABLE, true)).thenReturn(EXAMPLE_VARIABLES_WITH_NULL_VALUE);
// activity instances
when(runtimeServiceMock.getActivityInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)).thenReturn(EXAMPLE_ACTIVITY_INSTANCE);
mockUpdateSuspensionStateSelectBuilder = mock(UpdateProcessInstanceSuspensionStateSelectBuilder.class);
when(runtimeServiceMock.updateProcessInstanceSuspensionState()).thenReturn(mockUpdateSuspensionStateSelectBuilder);
mockUpdateSuspensionStateBuilder = mock(UpdateProcessInstanceSuspensionStateTenantBuilder.class);
when(mockUpdateSuspensionStateSelectBuilder.byProcessInstanceId(anyString())).thenReturn(mockUpdateSuspensionStateBuilder);
when(mockUpdateSuspensionStateSelectBuilder.byProcessDefinitionId(anyString())).thenReturn(mockUpdateSuspensionStateBuilder);
when(mockUpdateSuspensionStateSelectBuilder.byProcessDefinitionKey(anyString())).thenReturn(mockUpdateSuspensionStateBuilder);
mockUpdateProcessInstancesSuspensionStateBuilder = mock(UpdateProcessInstancesSuspensionStateBuilder.class);
when(mockUpdateSuspensionStateSelectBuilder.byProcessInstanceIds(anyList())).thenReturn(mockUpdateProcessInstancesSuspensionStateBuilder);
when(mockUpdateSuspensionStateSelectBuilder.byProcessInstanceQuery(any(ProcessInstanceQuery.class))).thenReturn(mockUpdateProcessInstancesSuspensionStateBuilder);
when(mockUpdateSuspensionStateSelectBuilder.byHistoricProcessInstanceQuery(any(HistoricProcessInstanceQuery.class))).thenReturn(mockUpdateProcessInstancesSuspensionStateBuilder);
// runtime service
when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock);
when(processEngine.getManagementService()).thenReturn(mockManagementService);
when(processEngine.getHistoryService()).thenReturn(historyServiceMock);
}
@Test
public void testGetActivityInstanceTree() {
Response response = given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.OK.getStatusCode())
.body("id", equalTo(EXAMPLE_ACTIVITY_INSTANCE_ID))
.body("parentActivityInstanceId", equalTo(EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID))
.body("activityId", equalTo(EXAMPLE_ACTIVITY_ID))
.body("processInstanceId", equalTo(EXAMPLE_PROCESS_INSTANCE_ID))
.body("processDefinitionId", equalTo(EXAMPLE_PROCESS_DEFINITION_ID))
.body("executionIds", not(empty()))
.body("executionIds[0]", equalTo(EXAMPLE_EXECUTION_ID))
.body("activityName", equalTo(EXAMPLE_ACTIVITY_NAME))
// "name" is deprecated and there for legacy reasons
.body("name", equalTo(EXAMPLE_ACTIVITY_NAME))
.body("childActivityInstances", not(empty()))
.body("childActivityInstances[0].id", equalTo(CHILD_EXAMPLE_ACTIVITY_INSTANCE_ID))
.body("childActivityInstances[0].parentActivityInstanceId", equalTo(CHILD_EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID))
.body("childActivityInstances[0].activityId", equalTo(CHILD_EXAMPLE_ACTIVITY_ID))
.body("childActivityInstances[0].activityType", equalTo(CHILD_EXAMPLE_ACTIVITY_TYPE))
.body("childActivityInstances[0].activityName", equalTo(CHILD_EXAMPLE_ACTIVITY_NAME))
.body("childActivityInstances[0].name", equalTo(CHILD_EXAMPLE_ACTIVITY_NAME))
.body("childActivityInstances[0].processInstanceId", equalTo(CHILD_EXAMPLE_PROCESS_INSTANCE_ID))
.body("childActivityInstances[0].processDefinitionId", equalTo(CHILD_EXAMPLE_PROCESS_DEFINITION_ID))
.body("childActivityInstances[0].executionIds", not(empty()))
.body("childActivityInstances[0].childActivityInstances", empty())
.body("childActivityInstances[0].childTransitionInstances", empty())
.body("childTransitionInstances", not(empty()))
.body("childTransitionInstances[0].id", equalTo(CHILD_EXAMPLE_ACTIVITY_INSTANCE_ID))
.body("childTransitionInstances[0].parentActivityInstanceId", equalTo(CHILD_EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID))
.body("childTransitionInstances[0].activityId", equalTo(CHILD_EXAMPLE_ACTIVITY_ID))
.body("childTransitionInstances[0].activityName", equalTo(CHILD_EXAMPLE_ACTIVITY_NAME))
.body("childTransitionInstances[0].activityType", equalTo(CHILD_EXAMPLE_ACTIVITY_TYPE))
.body("childTransitionInstances[0].targetActivityId", equalTo(CHILD_EXAMPLE_ACTIVITY_ID))
.body("childTransitionInstances[0].processInstanceId", equalTo(CHILD_EXAMPLE_PROCESS_INSTANCE_ID))
.body("childTransitionInstances[0].processDefinitionId", equalTo(CHILD_EXAMPLE_PROCESS_DEFINITION_ID))
.body("childTransitionInstances[0].executionId", equalTo(EXAMPLE_EXECUTION_ID))
.when().get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL);
Assert.assertEquals("Should return right number of properties", 11, response.jsonPath().getMap("").size());
}
@Test
public void testGetActivityInstanceTreeForNonExistingProcessInstance() {
when(runtimeServiceMock.getActivityInstance(anyString())).thenReturn(null);
given().pathParam("id", "aNonExistingProcessInstanceId")
.then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Process instance with id aNonExistingProcessInstanceId does not exist"))
.when().get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL);
}
@Test
public void testGetActivityInstanceTreeWithInternalError() {
when(runtimeServiceMock.getActivityInstance(anyString())).thenThrow(new ProcessEngineException("expected exception"));
given().pathParam("id", "aNonExistingProcessInstanceId")
.then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("expected exception"))
.when().get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL);
}
@Test
public void testGetActivityInstanceTreeThrowsAuthorizationException() {
String message = "expected exception";
when(runtimeServiceMock.getActivityInstance(anyString())).thenThrow(new AuthorizationException(message));
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL);
}
@Test
public void testGetVariables() {
Response response = given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.OK.getStatusCode())
.body(EXAMPLE_VARIABLE_KEY, notNullValue())
.body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue()))
.body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(String.class.getSimpleName()))
.when().get(PROCESS_INSTANCE_VARIABLES_URL);
Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size());
}
@Test
public void testDeleteAsync() {
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
when(runtimeServiceMock.deleteProcessInstancesAsync(anyListOf(String.class), any(ProcessInstanceQuery.class), anyString(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity());
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("deleteReason", TEST_DELETE_REASON);
given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL);
verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync(ids, null, TEST_DELETE_REASON, false, false);
}
@Test
public void testDeleteAsyncWithQuery() {
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("deleteReason", TEST_DELETE_REASON);
ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
messageBodyJson.put("processInstanceQuery", query);
when(runtimeServiceMock.deleteProcessInstancesAsync(anyListOf(String.class), any(ProcessInstanceQuery.class), anyString(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL);
verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync(
anyListOf(String.class), Mockito.any(ProcessInstanceQuery.class), Mockito.eq(TEST_DELETE_REASON), Mockito.eq(false), Mockito.eq(false));
}
@Test
public void testDeleteAsyncWithBadRequestQuery() {
doThrow(new BadUserRequestException("process instance ids are empty"))
.when(runtimeServiceMock).deleteProcessInstancesAsync(eq((List<String>) null), eq((ProcessInstanceQuery) null), anyString(), anyBoolean(), anyBoolean());
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("deleteReason", TEST_DELETE_REASON);
given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL);
}
@Test
public void testDeleteAsyncWithSkipCustomListeners() {
when(runtimeServiceMock.deleteProcessInstancesAsync(anyListOf(String.class), any(ProcessInstanceQuery.class), anyString(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity());
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("deleteReason", TEST_DELETE_REASON);
messageBodyJson.put("processInstanceIds", Arrays.asList("processInstanceId1", "processInstanceId2"));
messageBodyJson.put("skipCustomListeners", true);
given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL);
verify(runtimeServiceMock).deleteProcessInstancesAsync(anyListOf(String.class), Mockito.any(ProcessInstanceQuery.class), Mockito.eq(TEST_DELETE_REASON), Mockito.eq(true), Mockito.eq(false));
}
@Test
public void testDeleteAsyncWithSkipSubprocesses() {
when(runtimeServiceMock.deleteProcessInstancesAsync(anyListOf(String.class), any(ProcessInstanceQuery.class), anyString(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity());
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("deleteReason", TEST_DELETE_REASON);
messageBodyJson.put("processInstanceIds", Arrays.asList("processInstanceId1", "processInstanceId2"));
messageBodyJson.put("skipSubprocesses", true);
given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL);
verify(runtimeServiceMock).deleteProcessInstancesAsync(
anyListOf(String.class),
Mockito.any(ProcessInstanceQuery.class),
Mockito.eq(TEST_DELETE_REASON),
Mockito.eq(false),
Mockito.eq(true));
}
@Test
public void testDeleteAsyncHistoricQueryBasedWithQuery() {
when(runtimeServiceMock.deleteProcessInstancesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyString(),
anyBoolean(),
anyBoolean()))
.thenReturn(new BatchEntity());
HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQueryImpl.class);
when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery);
List<HistoricProcessInstance> historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances();
when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances);
DeleteProcessInstancesDto body = new DeleteProcessInstancesDto();
body.setHistoricProcessInstanceQuery(new HistoricProcessInstanceQueryDto());
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL);
verify(runtimeServiceMock,
times(1)).deleteProcessInstancesAsync(
Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID),
null,
null,
false,
false);
}
@Test
public void testDeleteAsyncHistoricQueryBasedWithProcessInstanceIds() {
when(runtimeServiceMock.deleteProcessInstancesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyString(),
anyBoolean(),
anyBoolean()))
.thenReturn(new BatchEntity());
DeleteProcessInstancesDto body = new DeleteProcessInstancesDto();
body.setProcessInstanceIds(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID));
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL);
verify(runtimeServiceMock,
times(1)).deleteProcessInstancesAsync(
Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID),
null,
null,
false,
false);
}
@Test
public void testDeleteAsyncHistoricQueryBasedWithQueryAndProcessInstanceIds() {
when(runtimeServiceMock.deleteProcessInstancesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyString(),
anyBoolean(),
anyBoolean()))
.thenReturn(new BatchEntity());
HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQueryImpl.class);
when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery);
List<HistoricProcessInstance> historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances();
when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances);
DeleteProcessInstancesDto body = new DeleteProcessInstancesDto();
body.setHistoricProcessInstanceQuery(new HistoricProcessInstanceQueryDto());
body.setProcessInstanceIds(Arrays.asList(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID));
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL);
verify(runtimeServiceMock,
times(1)).deleteProcessInstancesAsync(
Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID),
null,
null,
false,
false);
}
@Test
public void testDeleteAsyncHistoricQueryBasedWithoutQueryAndWithoutProcessInstanceIds() {
doThrow(new BadUserRequestException("processInstanceIds is empty"))
.when(runtimeServiceMock).deleteProcessInstancesAsync(
anyListOf(String.class),
eq((ProcessInstanceQuery) null),
anyString(),
anyBoolean(),
anyBoolean());
given()
.contentType(ContentType.JSON).body(new DeleteProcessInstancesDto())
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL);
verify(runtimeServiceMock,
times(1)).deleteProcessInstancesAsync(
new ArrayList<String>(),
null,
null,
false,
false);
}
@Test
public void testDeleteAsyncHistoricQueryBasedWithDeleteReason() {
when(runtimeServiceMock.deleteProcessInstancesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyString(),
anyBoolean(),
anyBoolean()))
.thenReturn(new BatchEntity());
DeleteProcessInstancesDto body = new DeleteProcessInstancesDto();
body.setDeleteReason(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON);
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL);
verify(runtimeServiceMock,
times(1)).deleteProcessInstancesAsync(
new ArrayList<String>(),
null,
MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON,
false,
false);
}
@Test
public void testDeleteAsyncHistoricQueryBasedWithSkipCustomListenerTrue() {
when(runtimeServiceMock.deleteProcessInstancesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyString(),
anyBoolean(),
anyBoolean()))
.thenReturn(new BatchEntity());
DeleteProcessInstancesDto body = new DeleteProcessInstancesDto();
body.setSkipCustomListeners(true);
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL);
verify(runtimeServiceMock,
times(1)).deleteProcessInstancesAsync(
new ArrayList<String>(),
null,
null,
true,
false);
}
@Test
public void testDeleteAsyncHistoricQueryBasedWithSkipSubprocesses() {
when(runtimeServiceMock.deleteProcessInstancesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyString(),
anyBoolean(),
anyBoolean()))
.thenReturn(new BatchEntity());
DeleteProcessInstancesDto body = new DeleteProcessInstancesDto();
body.setSkipSubprocesses(true);
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL);
verify(runtimeServiceMock,
times(1)).deleteProcessInstancesAsync(
new ArrayList<String>(),
null,
null,
false,
true);
}
@Test
public void testGetVariablesWithNullValue() {
Response response = given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID_WITH_NULL_VALUE_AS_VARIABLE)
.then().expect().statusCode(Status.OK.getStatusCode())
.body(EXAMPLE_ANOTHER_VARIABLE_KEY, notNullValue())
.body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".value", nullValue())
.body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".type", equalTo("Null"))
.when().get(PROCESS_INSTANCE_VARIABLES_URL);
Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size());
}
@Test
public void testGetFileVariable() {
String variableKey = "aVariableKey";
final byte[] byteContent = "some bytes".getBytes();
String filename = "test.txt";
String mimeType = "text/plain";
FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(mimeType).create();
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), eq(true)))
.thenReturn(variableValue);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.contentType(ContentType.JSON.toString())
.and()
.body("valueInfo.mimeType", equalTo(mimeType))
.body("valueInfo.filename", equalTo(filename))
.body("value", nullValue())
.when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testGetNullFileVariable() {
String variableKey = "aVariableKey";
String filename = "test.txt";
String mimeType = "text/plain";
FileValue variableValue = Variables.fileValue(filename).mimeType(mimeType).create();
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean()))
.thenReturn(variableValue);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.contentType(ContentType.TEXT.toString())
.and()
.body(is(equalTo("")))
.when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
}
@Test
public void testGetFileVariableDownloadWithType() {
String variableKey = "aVariableKey";
final byte[] byteContent = "some bytes".getBytes();
String filename = "test.txt";
FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create();
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean()))
.thenReturn(variableValue);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.contentType(ContentType.TEXT.toString())
.and()
.body(is(equalTo(new String(byteContent))))
.when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
}
@Test
public void testGetFileVariableDownloadWithTypeAndEncoding() {
String variableKey = "aVariableKey";
final byte[] byteContent = "some bytes".getBytes();
String filename = "test.txt";
String encoding = "UTF-8";
FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create();
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean()))
.thenReturn(variableValue);
Response response = given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.body(is(equalTo(new String(byteContent))))
.when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
String contentType = response.contentType().replaceAll(" ", "");
assertThat(contentType, is(ContentType.TEXT + ";charset=" + encoding));
}
@Test
public void testGetFileVariableDownloadWithoutType() {
String variableKey = "aVariableKey";
final byte[] byteContent = "some bytes".getBytes();
String filename = "test.txt";
FileValue variableValue = Variables.fileValue(filename).file(byteContent).create();
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean()))
.thenReturn(variableValue);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.and()
.body(is(equalTo(new String(byteContent))))
.header("Content-Disposition", containsString(filename))
.when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
}
@Test
public void testCannotDownloadVariableOtherThanFile() {
String variableKey = "aVariableKey";
LongValue variableValue = Variables.longValue(123L);
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean()))
.thenReturn(variableValue);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.contentType(MediaType.APPLICATION_JSON)
.and()
.when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
}
@Test
public void testJavaObjectVariableSerialization() {
Response response = given().pathParam("id", MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.OK.getStatusCode())
.body(EXAMPLE_VARIABLE_KEY, notNullValue())
.body(EXAMPLE_VARIABLE_KEY + ".value.property1", equalTo("aPropertyValue"))
.body(EXAMPLE_VARIABLE_KEY + ".value.property2", equalTo(true))
.body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT)))
.body(EXAMPLE_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ExampleVariableObject.class.getName()))
.body(EXAMPLE_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json"))
.when().get(PROCESS_INSTANCE_VARIABLES_URL);
Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size());
}
@Test
public void testGetObjectVariables() {
// given
String variableKey = "aVariableId";
List<String> payload = Arrays.asList("a", "b");
ObjectValue variableValue =
MockObjectValue
.fromObjectValue(Variables
.objectValue(payload)
.serializationDataFormat("application/json")
.create())
.objectTypeName(ArrayList.class.getName())
.serializedValue("a serialized value"); // this should differ from the serialized json
when(runtimeServiceMock.getVariablesTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), anyBoolean()))
.thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue));
// when
given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.OK.getStatusCode())
.body(variableKey + ".value", equalTo(payload))
.body(variableKey + ".type", equalTo("Object"))
.body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json"))
.body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName()))
.when().get(PROCESS_INSTANCE_VARIABLES_URL);
// then
verify(runtimeServiceMock).getVariablesTyped(EXAMPLE_PROCESS_INSTANCE_ID, true);
}
@Test
public void testGetObjectVariablesSerialized() {
// given
String variableKey = "aVariableId";
ObjectValue variableValue =
Variables
.serializedObjectValue("a serialized value")
.serializationDataFormat("application/json")
.objectTypeName(ArrayList.class.getName())
.create();
when(runtimeServiceMock.getVariablesTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), anyBoolean()))
.thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue));
// when
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.queryParam("deserializeValues", false)
.then().expect().statusCode(Status.OK.getStatusCode())
.body(variableKey + ".value", equalTo("a serialized value"))
.body(variableKey + ".type", equalTo("Object"))
.body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json"))
.body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName()))
.when().get(PROCESS_INSTANCE_VARIABLES_URL);
// then
verify(runtimeServiceMock).getVariablesTyped(EXAMPLE_PROCESS_INSTANCE_ID, false);
}
@Test
public void testGetVariablesForNonExistingProcessInstance() {
when(runtimeServiceMock.getVariablesTyped(anyString(), anyBoolean())).thenThrow(new ProcessEngineException("expected exception"));
given().pathParam("id", "aNonExistingProcessInstanceId")
.then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(ProcessEngineException.class.getSimpleName()))
.body("message", equalTo("expected exception"))
.when().get(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testGetVariablesThrowsAuthorizationException() {
String message = "expected exception";
when(runtimeServiceMock.getVariablesTyped(anyString(), anyBoolean())).thenThrow(new AuthorizationException(message));
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.get(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testGetSingleInstance() {
ProcessInstance mockInstance = MockProvider.createMockInstance();
ProcessInstanceQuery sampleInstanceQuery = mock(ProcessInstanceQuery.class);
when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(sampleInstanceQuery);
when(sampleInstanceQuery.processInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)).thenReturn(sampleInstanceQuery);
when(sampleInstanceQuery.singleResult()).thenReturn(mockInstance);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.OK.getStatusCode())
.body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID))
.body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED))
.body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))
.body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY))
.body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED))
.body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID))
.when().get(SINGLE_PROCESS_INSTANCE_URL);
}
@Test
public void testGetNonExistingProcessInstance() {
ProcessInstanceQuery sampleInstanceQuery = mock(ProcessInstanceQuery.class);
when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(sampleInstanceQuery);
when(sampleInstanceQuery.processInstanceId(anyString())).thenReturn(sampleInstanceQuery);
when(sampleInstanceQuery.singleResult()).thenReturn(null);
given().pathParam("id", "aNonExistingInstanceId")
.then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Process instance with id aNonExistingInstanceId does not exist"))
.when().get(SINGLE_PROCESS_INSTANCE_URL);
}
@Test
public void testDeleteProcessInstance() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false);
}
@Test
public void testDeleteNonExistingProcessInstance() {
doThrow(new ProcessEngineException("expected exception")).when(runtimeServiceMock).deleteProcessInstance(anyString(), anyString(), anyBoolean(), anyBoolean(), anyBoolean() ,anyBoolean());
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Process instance with id " + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID + " does not exist"))
.when().delete(SINGLE_PROCESS_INSTANCE_URL);
}
@Test
public void testDeleteProcessInstanceThrowsAuthorizationException() {
String message = "expected exception";
doThrow(new AuthorizationException(message)).when(runtimeServiceMock).deleteProcessInstance(anyString(), anyString(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean());
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.delete(SINGLE_PROCESS_INSTANCE_URL);
}
@Test
public void testNoGivenDeleteReason1() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false);
}
@Test
public void testDeleteProcessInstanceSkipCustomListeners() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipCustomListeners", true).then().expect()
.statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, true, true, false, false);
}
@Test
public void testDeleteProcessInstanceWithCustomListeners() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipCustomListeners", false).then().expect()
.statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false);
}
@Test
public void testDeleteProcessInstanceSkipIoMappings() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipIoMappings", true).then().expect()
.statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, true, false);
}
@Test
public void testDeleteProcessInstanceWithoutSkipingIoMappings() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipIoMappings", false).then().expect()
.statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false);
}
@Test
public void testDeleteProcessInstanceSkipSubprocesses() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipSubprocesses", true).then().expect()
.statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, true);
}
@Test
public void testDeleteProcessInstanceWithoutSkipSubprocesses() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipSubprocesses", false).then().expect()
.statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL);
verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false);
}
@Test
public void testVariableModification() {
String variableKey = "aKey";
int variableValue = 123;
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables();
messageBodyJson.put("modifications", modifications);
List<String> deletions = new ArrayList<String>();
deletions.add("deleteKey");
messageBodyJson.put("deletions", deletions);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
Map<String, Object> expectedModifications = new HashMap<String, Object>();
expectedModifications.put(variableKey, variableValue);
verify(runtimeServiceMock).updateVariables(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), argThat(new EqualsMap(expectedModifications)),
argThat(new EqualsList(deletions)));
}
@Test
public void testVariableModificationWithUnparseableInteger() {
String variableKey = "aKey";
String variableValue = "1abc";
String variableType = "Integer";
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables();
messageBodyJson.put("modifications", modifications);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot modify variables for process instance: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class)))
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testVariableModificationWithUnparseableShort() {
String variableKey = "aKey";
String variableValue = "1abc";
String variableType = "Short";
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables();
messageBodyJson.put("modifications", modifications);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot modify variables for process instance: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class)))
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testVariableModificationWithUnparseableLong() {
String variableKey = "aKey";
String variableValue = "1abc";
String variableType = "Long";
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables();
messageBodyJson.put("modifications", modifications);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot modify variables for process instance: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class)))
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testVariableModificationWithUnparseableDouble() {
String variableKey = "aKey";
String variableValue = "1abc";
String variableType = "Double";
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables();
messageBodyJson.put("modifications", modifications);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot modify variables for process instance: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class)))
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testVariableModificationWithUnparseableDate() {
String variableKey = "aKey";
String variableValue = "1abc";
String variableType = "Date";
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables();
messageBodyJson.put("modifications", modifications);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot modify variables for process instance: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class)))
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testVariableModificationWithNotSupportedType() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String variableType = "X";
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables();
messageBodyJson.put("modifications", modifications);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot modify variables for process instance: Unsupported value type 'X'"))
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testVariableModificationForNonExistingProcessInstance() {
doThrow(new ProcessEngineException("expected exception")).when(runtimeServiceMock).updateVariables(anyString(), anyMapOf(String.class, Object.class), anyCollectionOf(String.class));
String variableKey = "aKey";
int variableValue = 123;
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables();
messageBodyJson.put("modifications", modifications);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson)
.then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(RestException.class.getSimpleName()))
.body("message", equalTo("Cannot modify variables for process instance " + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID + ": expected exception"))
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testEmptyVariableModification() {
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testVariableModificationThrowsAuthorizationException() {
String variableKey = "aKey";
int variableValue = 123;
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
Map<String, Object> modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables();
messageBodyJson.put("modifications", modifications);
String message = "excpected exception";
doThrow(new AuthorizationException(message)).when(runtimeServiceMock).updateVariables(anyString(), anyMapOf(String.class, Object.class), anyCollectionOf(String.class));
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.body("type", is(AuthorizationException.class.getSimpleName()))
.body("message", is(message))
.when()
.post(PROCESS_INSTANCE_VARIABLES_URL);
}
@Test
public void testGetSingleVariable() {
String variableKey = "aVariableKey";
int variableValue = 123;
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), eq(true)))
.thenReturn(Variables.integerValue(variableValue));
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.then().expect().statusCode(Status.OK.getStatusCode())
.body("value", is(123))
.body("type", is("Integer"))
.when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testNonExistingVariable() {
String variableKey = "aVariableKey";
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(null);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.then().expect().statusCode(Status.NOT_FOUND.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", is("process instance variable with name " + variableKey + " does not exist"))
.when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testGetSingleVariableThrowsAuthorizationException() {
String variableKey = "aVariableKey";
String message = "excpected exception";
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenThrow(new AuthorizationException(message));
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.body("type", is(AuthorizationException.class.getSimpleName()))
.body("message", is(message))
.when()
.get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testGetSingleLocalVariableData() {
when(runtimeServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_BYTES_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE_BYTES);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", EXAMPLE_BYTES_VARIABLE_KEY)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.when()
.get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock).getVariableTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_BYTES_VARIABLE_KEY, false);
}
@Test
public void testGetSingleLocalVariableDataNonExisting() {
when(runtimeServiceMock.getVariableTyped(anyString(), eq("nonExisting"), eq(false))).thenReturn(null);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", "nonExisting")
.then()
.expect()
.statusCode(Status.NOT_FOUND.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", is("process instance variable with name " + "nonExisting" + " does not exist"))
.when()
.get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock).getVariableTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, "nonExisting", false);
}
@Test
public void testGetSingleLocalVariabledataNotBinary() {
when(runtimeServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", EXAMPLE_VARIABLE_KEY)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when()
.get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock).getVariableTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_VARIABLE_KEY, false);
}
@Test
public void testGetSingleLocalObjectVariable() {
// given
String variableKey = "aVariableId";
List<String> payload = Arrays.asList("a", "b");
ObjectValue variableValue =
MockObjectValue
.fromObjectValue(Variables
.objectValue(payload)
.serializationDataFormat("application/json")
.create())
.objectTypeName(ArrayList.class.getName())
.serializedValue("a serialized value"); // this should differ from the serialized json
when(runtimeServiceMock.getVariableTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue);
// when
given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.then().expect().statusCode(Status.OK.getStatusCode())
.body("value", equalTo(payload))
.body("type", equalTo("Object"))
.body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json"))
.body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName()))
.when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
// then
verify(runtimeServiceMock).getVariableTyped(EXAMPLE_PROCESS_INSTANCE_ID, variableKey, true);
}
@Test
public void testGetSingleLocalObjectVariableSerialized() {
// given
String variableKey = "aVariableId";
ObjectValue variableValue =
Variables
.serializedObjectValue("a serialized value")
.serializationDataFormat("application/json")
.objectTypeName(ArrayList.class.getName())
.create();
when(runtimeServiceMock.getVariableTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue);
// when
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.queryParam("deserializeValue", false)
.then().expect().statusCode(Status.OK.getStatusCode())
.body("value", equalTo("a serialized value"))
.body("type", equalTo("Object"))
.body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json"))
.body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName()))
.when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
// then
verify(runtimeServiceMock).getVariableTyped(EXAMPLE_PROCESS_INSTANCE_ID, variableKey, false);
}
@Test
public void testGetVariableForNonExistingInstance() {
String variableKey = "aVariableKey";
when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), eq(true)))
.thenThrow(new ProcessEngineException("expected exception"));
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(RestException.class.getSimpleName()))
.body("message", is("Cannot get process instance variable " + variableKey + ": expected exception"))
.when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariable() {
String variableKey = "aVariableKey";
String variableValue = "aVariableValue";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsUntypedValue.matcher().value(variableValue)));
}
@Test
public void testPutSingleVariableWithTypeString() {
String variableKey = "aVariableKey";
String variableValue = "aVariableValue";
String type = "String";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.stringValue(variableValue)));
}
@Test
public void testPutSingleVariableWithTypeInteger() {
String variableKey = "aVariableKey";
Integer variableValue = 123;
String type = "Integer";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.integerValue(variableValue)));
}
@Test
public void testPutSingleVariableWithUnparseableInteger() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String type = "Integer";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot put process instance variable aVariableKey: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class)))
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariableWithTypeShort() {
String variableKey = "aVariableKey";
Short variableValue = 123;
String type = "Short";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.shortValue(variableValue)));
}
@Test
public void testPutSingleVariableWithUnparseableShort() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String type = "Short";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot put process instance variable aVariableKey: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class)))
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariableWithTypeLong() {
String variableKey = "aVariableKey";
Long variableValue = Long.valueOf(123);
String type = "Long";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.longValue(variableValue)));
}
@Test
public void testPutSingleVariableWithUnparseableLong() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String type = "Long";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot put process instance variable aVariableKey: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class)))
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariableWithTypeDouble() {
String variableKey = "aVariableKey";
Double variableValue = 123.456;
String type = "Double";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.doubleValue(variableValue)));
}
@Test
public void testPutSingleVariableWithUnparseableDouble() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String type = "Double";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot put process instance variable aVariableKey: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class)))
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariableWithTypeBoolean() {
String variableKey = "aVariableKey";
Boolean variableValue = true;
String type = "Boolean";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.booleanValue(variableValue)));
}
@Test
public void testPutSingleVariableWithTypeDate() throws Exception {
Date now = new Date();
String variableKey = "aVariableKey";
String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now);
String type = "Date";
Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue);
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.dateValue(expectedValue)));
}
@Test
public void testPutSingleVariableWithUnparseableDate() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String type = "Date";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot put process instance variable aVariableKey: "
+ ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class)))
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariableWithNotSupportedType() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String type = "X";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot put process instance variable aVariableKey: Unsupported value type 'X'"))
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariableThrowsAuthorizationException() {
String variableKey = "aVariableKey";
String variableValue = "1abc";
String type = "String";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue, type);
String message = "expected exception";
doThrow(new AuthorizationException(message)).when(runtimeServiceMock).setVariable(anyString(), anyString(), any());
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.contentType(ContentType.JSON)
.body(variableJson)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleBinaryVariable() throws Exception {
byte[] bytes = "someContent".getBytes();
String variableKey = "aVariableKey";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.multiPart("data", null, bytes)
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.bytesValue(bytes)));
}
@Test
public void testPutSingleBinaryVariableWithValueType() throws Exception {
byte[] bytes = "someContent".getBytes();
String variableKey = "aVariableKey";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.multiPart("data", null, bytes)
.multiPart("valueType", "Bytes", "text/plain")
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.bytesValue(bytes)));
}
@Test
public void testPutSingleBinaryVariableWithNoValue() throws Exception {
byte[] bytes = new byte[0];
String variableKey = "aVariableKey";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.multiPart("data", null, bytes)
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsPrimitiveValue.bytesValue(bytes)));
}
@Test
public void testPutSingleBinaryVariableThrowsAuthorizationException() {
byte[] bytes = "someContent".getBytes();
String variableKey = "aVariableKey";
String message = "expected exception";
doThrow(new AuthorizationException(message)).when(runtimeServiceMock).setVariable(anyString(), anyString(), any());
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.multiPart("data", "unspecified", bytes)
.expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
}
@Test
public void testPutSingleSerializableVariable() throws Exception {
ArrayList<String> serializable = new ArrayList<String>();
serializable.add("foo");
ObjectMapper mapper = new ObjectMapper();
String jsonBytes = mapper.writeValueAsString(serializable);
String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical();
String variableKey = "aVariableKey";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.multiPart("data", jsonBytes, MediaType.APPLICATION_JSON)
.multiPart("type", typeName, MediaType.TEXT_PLAIN)
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable)));
}
@Test
public void testPutSingleSerializableVariableUnsupportedMediaType() throws Exception {
ArrayList<String> serializable = new ArrayList<String>();
serializable.add("foo");
ObjectMapper mapper = new ObjectMapper();
String jsonBytes = mapper.writeValueAsString(serializable);
String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical();
String variableKey = "aVariableKey";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.multiPart("data", jsonBytes, "unsupported")
.multiPart("type", typeName, MediaType.TEXT_PLAIN)
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body(containsString("Unrecognized content type for serialized java type: unsupported"))
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
verify(runtimeServiceMock, never()).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
eq(serializable));
}
@Test
public void testPutSingleVariableFromSerialized() throws Exception {
String serializedValue = "{\"prop\" : \"value\"}";
Map<String, Object> requestJson = VariablesBuilder
.getObjectValueMap(serializedValue, ValueType.OBJECT.getName(), "aDataFormat", "aRootType");
String variableKey = "aVariableKey";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON)
.body(requestJson)
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(
eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsObjectValue.objectValueMatcher()
.serializedValue(serializedValue)
.serializationFormat("aDataFormat")
.objectTypeName("aRootType")));
}
@Test
public void testPutSingleVariableFromInvalidSerialized() throws Exception {
String serializedValue = "{\"prop\" : \"value\"}";
Map<String, Object> requestJson = VariablesBuilder
.getObjectValueMap(serializedValue, "aNonExistingType", null, null);
String variableKey = "aVariableKey";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON)
.body(requestJson)
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Cannot put process instance variable aVariableKey: Unsupported value type 'aNonExistingType'"))
.when()
.put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPutSingleVariableFromSerializedWithNoValue() {
String variableKey = "aVariableKey";
Map<String, Object> requestJson = VariablesBuilder
.getObjectValueMap(null, ValueType.OBJECT.getName(), null, null);
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(requestJson)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(
eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsObjectValue.objectValueMatcher()));
}
@Test
public void testPutSingleVariableWithNoValue() {
String variableKey = "aVariableKey";
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey),
argThat(EqualsNullValue.matcher()));
}
@Test
public void testPutVariableForNonExistingInstance() {
String variableKey = "aVariableKey";
String variableValue = "aVariableValue";
Map<String, Object> variableJson = VariablesBuilder.getVariableValueMap(variableValue);
doThrow(new ProcessEngineException("expected exception"))
.when(runtimeServiceMock)
.setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), any());
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.contentType(ContentType.JSON).body(variableJson)
.then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(RestException.class.getSimpleName()))
.body("message", is("Cannot put process instance variable " + variableKey + ": expected exception"))
.when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testPostSingleFileVariableWithEncodingAndMimeType() throws Exception {
byte[] value = "some text".getBytes();
String variableKey = "aVariableKey";
String encoding = "utf-8";
String filename = "test.txt";
String mimetype = MediaType.TEXT_PLAIN;
given()
.pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey)
.multiPart("data", filename, value, mimetype + "; encoding="+encoding)
.multiPart("valueType", "File", "text/plain")
.header("accept", MediaType.APPLICATION_JSON)
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
ArgumentCaptor<FileValue> captor = ArgumentCaptor.forClass(FileValue.class);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey),
captor.capture());
FileValue captured = captor.getValue();
assertThat(captured.getEncoding(), is(encoding));
assertThat(captured.getFilename(), is(filename));
assertThat(captured.getMimeType(), is(mimetype));
assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value));
}
@Test
public void testPostSingleFileVariableWithMimeType() throws Exception {
byte[] value = "some text".getBytes();
String variableKey = "aVariableKey";
String filename = "test.txt";
String mimetype = MediaType.TEXT_PLAIN;
given()
.pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey)
.multiPart("data", filename, value, mimetype)
.multiPart("valueType", "File", "text/plain")
.header("accept", MediaType.APPLICATION_JSON)
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
ArgumentCaptor<FileValue> captor = ArgumentCaptor.forClass(FileValue.class);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey),
captor.capture());
FileValue captured = captor.getValue();
assertThat(captured.getEncoding(), is(nullValue()));
assertThat(captured.getFilename(), is(filename));
assertThat(captured.getMimeType(), is(mimetype));
assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value));
}
@Test
public void testPostSingleFileVariableWithEncoding() throws Exception {
byte[] value = "some text".getBytes();
String variableKey = "aVariableKey";
String encoding = "utf-8";
String filename = "test.txt";
given()
.pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey)
.multiPart("data", filename, value, "encoding="+encoding)
.multiPart("valueType", "File", "text/plain")
.header("accept", MediaType.APPLICATION_JSON)
.expect()
//when the user passes an encoding, he has to provide the type, too
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
}
@Test
public void testPostSingleFileVariableOnlyFilename() throws Exception {
String variableKey = "aVariableKey";
String filename = "test.txt";
given()
.pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey)
.multiPart("data", filename, new byte[0])
.multiPart("valueType", "File", "text/plain")
.header("accept", MediaType.APPLICATION_JSON)
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL);
ArgumentCaptor<FileValue> captor = ArgumentCaptor.forClass(FileValue.class);
verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey),
captor.capture());
FileValue captured = captor.getValue();
assertThat(captured.getEncoding(), is(nullValue()));
assertThat(captured.getFilename(), is(filename));
assertThat(captured.getMimeType(), is(MediaType.APPLICATION_OCTET_STREAM));
assertThat(captured.getValue().available(), is(0));
}
@Test
public void testDeleteSingleVariable() {
String variableKey = "aVariableKey";
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
.when().delete(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
verify(runtimeServiceMock).removeVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey));
}
@Test
public void testDeleteVariableForNonExistingInstance() {
String variableKey = "aVariableKey";
doThrow(new ProcessEngineException("expected exception"))
.when(runtimeServiceMock).removeVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey));
given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey)
.then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(RestException.class.getSimpleName()))
.body("message", is("Cannot delete process instance variable " + variableKey + ": expected exception"))
.when().delete(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testDeleteVariableThrowsAuthorizationException() {
String variableKey = "aVariableKey";
String message = "expected exception";
doThrow(new AuthorizationException(message)).when(runtimeServiceMock).removeVariable(anyString(), anyString());
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.pathParam("varId", variableKey)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", is(AuthorizationException.class.getSimpleName()))
.body("message", is(message))
.when()
.delete(SINGLE_PROCESS_INSTANCE_VARIABLE_URL);
}
@Test
public void testActivateInstance() {
ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto();
dto.setSuspended(false);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(dto)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
verify(mockUpdateSuspensionStateBuilder).activate();
}
@Test
public void testActivateThrowsProcessEngineException() {
ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto();
dto.setSuspended(false);
String expectedMessage = "expectedMessage";
doThrow(new ProcessEngineException(expectedMessage))
.when(mockUpdateSuspensionStateBuilder)
.activate();
given()
.pathParam("id", MockProvider.EXAMPLE_NON_EXISTENT_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(dto)
.then()
.expect()
.statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(ProcessEngineException.class.getSimpleName()))
.body("message", is(expectedMessage))
.when()
.put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testActivateThrowsAuthorizationException() {
ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto();
dto.setSuspended(false);
String message = "expectedMessage";
doThrow(new AuthorizationException(message))
.when(mockUpdateSuspensionStateBuilder)
.activate();
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(dto)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendInstance() {
ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto();
dto.setSuspended(true);
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(dto)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
verify(mockUpdateSuspensionStateBuilder).suspend();
}
@Test
public void testSuspendThrowsProcessEngineException() {
ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto();
dto.setSuspended(true);
String expectedMessage = "expectedMessage";
doThrow(new ProcessEngineException(expectedMessage))
.when(mockUpdateSuspensionStateBuilder)
.suspend();
given()
.pathParam("id", MockProvider.EXAMPLE_NON_EXISTENT_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(dto)
.then()
.expect()
.statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(ProcessEngineException.class.getSimpleName()))
.body("message", is(expectedMessage))
.when()
.put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendWithMultipleByParameters() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
String message = "Only one of processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state.";
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", is(message))
.when()
.put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendThrowsAuthorizationException() {
ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto();
dto.setSuspended(true);
String message = "expectedMessage";
doThrow(new AuthorizationException(message))
.when(mockUpdateSuspensionStateBuilder)
.suspend();
given()
.pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(dto)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testActivateProcessInstanceByProcessDefinitionKey() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
verify(mockUpdateSuspensionStateBuilder).activate();
}
@Test
public void testActivateProcessInstanceByProcessDefinitionKeyWithException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
String expectedException = "expectedException";
doThrow(new ProcessEngineException(expectedException))
.when(mockUpdateSuspensionStateBuilder)
.activate();
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(ProcessEngineException.class.getSimpleName()))
.body("message", is(expectedException))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testActivateProcessInstanceByProcessDefinitionKeyThrowsAuthorizationException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
String message = "expectedMessage";
doThrow(new AuthorizationException(message))
.when(mockUpdateSuspensionStateBuilder)
.activate();
given()
.contentType(ContentType.JSON)
.body(params)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionKey() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
verify(mockUpdateSuspensionStateBuilder).suspend();
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionKeyWithException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
String expectedException = "expectedException";
doThrow(new ProcessEngineException(expectedException))
.when(mockUpdateSuspensionStateBuilder)
.suspend();
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(ProcessEngineException.class.getSimpleName()))
.body("message", is(expectedException))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionKeyThrowsAuthorizationException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
String message = "expectedMessage";
doThrow(new AuthorizationException(message))
.when(mockUpdateSuspensionStateBuilder)
.suspend();
given()
.contentType(ContentType.JSON)
.body(params)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testActivateProcessInstanceByProcessDefinitionKeyAndTenantId() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
verify(mockUpdateSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID);
verify(mockUpdateSuspensionStateBuilder).activate();
}
@Test
public void testActivateProcessInstanceByProcessDefinitionKeyWithoutTenantId() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
params.put("processDefinitionWithoutTenantId", true);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
verify(mockUpdateSuspensionStateBuilder).processDefinitionWithoutTenantId();
verify(mockUpdateSuspensionStateBuilder).activate();
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionKeyAndTenantId() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
verify(mockUpdateSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID);
verify(mockUpdateSuspensionStateBuilder).suspend();
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionKeyWithoutTenantId() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
params.put("processDefinitionWithoutTenantId", true);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
verify(mockUpdateSuspensionStateBuilder).processDefinitionWithoutTenantId();
verify(mockUpdateSuspensionStateBuilder).suspend();
}
@Test
public void testActivateProcessInstanceByProcessDefinitionId() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
verify(mockUpdateSuspensionStateBuilder).activate();
}
@Test
public void testActivateProcessInstanceByProcessDefinitionIdWithException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
String expectedException = "expectedException";
doThrow(new ProcessEngineException(expectedException))
.when(mockUpdateSuspensionStateBuilder)
.activate();
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(ProcessEngineException.class.getSimpleName()))
.body("message", is(expectedException))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testActivateProcessInstanceByProcessDefinitionIdThrowsAuthorizationException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
String message = "expectedMessage";
doThrow(new AuthorizationException(message))
.when(mockUpdateSuspensionStateBuilder)
.activate();
given()
.contentType(ContentType.JSON)
.body(params)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionId() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
verify(mockUpdateSuspensionStateBuilder).suspend();
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionIdWithException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
String expectedException = "expectedException";
doThrow(new ProcessEngineException(expectedException))
.when(mockUpdateSuspensionStateBuilder)
.suspend();
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("type", is(ProcessEngineException.class.getSimpleName()))
.body("message", is(expectedException))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendProcessInstanceByProcessDefinitionIdThrowsAuthorizationException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
String message = "expectedMessage";
doThrow(new AuthorizationException(message))
.when(mockUpdateSuspensionStateBuilder)
.suspend();
given()
.contentType(ContentType.JSON)
.body(params)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testActivateProcessInstanceByIdShouldThrowException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", false);
params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
String message = "Either processDefinitionId or processDefinitionKey can be set to update the suspension state.";
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", is(message))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendProcessInstanceByIdShouldThrowException() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
String message = "Either processDefinitionId or processDefinitionKey can be set to update the suspension state.";
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", is(message))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendProcessInstanceByNothing() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("suspended", true);
String message = "Either processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state.";
given()
.contentType(ContentType.JSON)
.body(params)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", is(message))
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
}
@Test
public void testSuspendInstances() {
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("suspended", true);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend();
}
@Test
public void testActivateInstances() {
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("suspended", false);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).activate();
}
@Test
public void testSuspendInstancesMultipleGroupOperations() {
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("processInstanceQuery", query);
messageBodyJson.put("suspended", true);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).byProcessInstanceQuery(query.toQuery(processEngine));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend();
}
@Test
public void testSuspendProcessInstanceQuery() {
ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceQuery", query);
messageBodyJson.put("suspended", true);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend();
}
@Test
public void testActivateProcessInstanceQuery() {
ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceQuery", query);
messageBodyJson.put("suspended", false);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).activate();
}
@Test
public void testSuspendHistoricProcessInstanceQuery() {
HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("historicProcessInstanceQuery", query);
messageBodyJson.put("suspended", true);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byHistoricProcessInstanceQuery(any(HistoricProcessInstanceQuery.class));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend();
}
@Test
public void testActivateHistoricProcessInstanceQuery() {
HistoricProcessInstanceDto query = new HistoricProcessInstanceDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("historicProcessInstanceQuery", query);
messageBodyJson.put("suspended", false);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.put(PROCESS_INSTANCE_SUSPENDED_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byHistoricProcessInstanceQuery(any(HistoricProcessInstanceQuery.class));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).activate();
}
@Test
public void testSuspendAsyncWithProcessInstances() {
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("suspended", true);
when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync();
}
@Test
public void testActivateAsyncWithProcessInstances() {
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("suspended", false);
when(mockUpdateProcessInstancesSuspensionStateBuilder.activateAsync()).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).activateAsync();
}
@Test
public void testSuspendAsyncWithProcessInstanceQuery() {
ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceQuery", query);
messageBodyJson.put("suspended", true);
when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync();
}
@Test
public void testActivateAsyncWithProcessInstanceQuery() {
ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceQuery", query);
messageBodyJson.put("suspended", false);
when(mockUpdateProcessInstancesSuspensionStateBuilder.activateAsync()).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).activateAsync();
}
@Test
public void testSuspendAsyncWithHistoricProcessInstanceQuery() {
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("suspended", true);
when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync();
}
@Test
public void testActivateAsyncWithHistoricProcessInstanceQuery() {
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("suspended", false);
when(mockUpdateProcessInstancesSuspensionStateBuilder.activateAsync()).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).activateAsync();
}
@Test
public void testSuspendAsyncWithMultipleGroupOperations() {
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
ProcessInstanceQueryDto query = new ProcessInstanceQueryDto();
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstanceIds", ids);
messageBodyJson.put("processInstanceQuery", query);
messageBodyJson.put("suspended", true);
when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity());
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids);
verify(mockUpdateProcessInstancesSuspensionStateBuilder).byProcessInstanceQuery(query.toQuery(processEngine));
verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync();
}
@Test
public void testSuspendAsyncWithNothing() {
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("suspended", true);
String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state.";
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", is(message))
.when()
.post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL);
}
@Test
public void testProcessInstanceModification() {
ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder();
when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder);
Map<String, Object> json = new HashMap<String, Object>();
json.put("skipCustomListeners", true);
json.put("skipIoMappings", true);
List<Map<String, Object>> instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson());
instructions.add(ModificationInstructionBuilder.cancellation().activityInstanceId("activityInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.cancellation().transitionInstanceId("transitionInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson());
instructions.add(ModificationInstructionBuilder.startBefore()
.activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson());
instructions.add(ModificationInstructionBuilder.startAfter()
.activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson());
instructions.add(ModificationInstructionBuilder.startTransition()
.transitionId("transitionId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID));
InOrder inOrder = inOrder(mockModificationBuilder);
inOrder.verify(mockModificationBuilder).cancelAllForActivity("activityId");
inOrder.verify(mockModificationBuilder).cancelActivityInstance("activityInstanceId");
inOrder.verify(mockModificationBuilder).cancelTransitionInstance("transitionInstanceId");
inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId");
inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId", "ancestorActivityInstanceId");
inOrder.verify(mockModificationBuilder).startAfterActivity("activityId");
inOrder.verify(mockModificationBuilder).startAfterActivity("activityId", "ancestorActivityInstanceId");
inOrder.verify(mockModificationBuilder).startTransition("transitionId");
inOrder.verify(mockModificationBuilder).startTransition("transitionId", "ancestorActivityInstanceId");
inOrder.verify(mockModificationBuilder).execute(true, true);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testProcessInstanceModificationWithVariables() {
ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder();
when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder);
Map<String, Object> json = new HashMap<String, Object>();
List<Map<String, Object>> instructions = new ArrayList<Map<String, Object>>();
instructions.add(
ModificationInstructionBuilder.startBefore()
.activityId("activityId")
.variables(VariablesBuilder.create()
.variable("var", "value", "String", false)
.variable("varLocal", "valueLocal", "String", true)
.getVariables())
.getJson());
instructions.add(
ModificationInstructionBuilder.startAfter()
.activityId("activityId")
.variables(VariablesBuilder.create()
.variable("var", 52, "Integer", false)
.variable("varLocal", 74, "Integer", true)
.getVariables())
.getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.NO_CONTENT.getStatusCode())
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID));
InOrder inOrder = inOrder(mockModificationBuilder);
inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId");
verify(mockModificationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.stringValue("valueLocal")));
verify(mockModificationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.stringValue("value")));
inOrder.verify(mockModificationBuilder).startAfterActivity("activityId");
verify(mockModificationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.integerValue(52)));
verify(mockModificationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.integerValue(74)));
inOrder.verify(mockModificationBuilder).execute(false, false);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testInvalidModification() {
Map<String, Object> json = new HashMap<String, Object>();
// start before: missing activity id
List<Map<String, Object>> instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.startBefore().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("'activityId' must be set"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
// start after: missing ancestor activity instance id
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.startAfter().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("'activityId' must be set"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
// start transition: missing ancestor activity instance id
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.startTransition().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("'transitionId' must be set"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
// cancel: missing activity id and activity instance id
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.cancellation().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("For instruction type 'cancel': exactly one, "
+ "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
// cancel: both, activity id and activity instance id, set
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.cancellation().activityId("anActivityId")
.activityInstanceId("anActivityInstanceId").getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("For instruction type 'cancel': exactly one, "
+ "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
}
@Test
public void testModifyProcessInstanceThrowsAuthorizationException() {
ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder();
when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder);
String message = "expected exception";
doThrow(new AuthorizationException(message)).when(mockModificationBuilder).execute(anyBoolean(), anyBoolean());
Map<String, Object> json = new HashMap<String, Object>();
List<Map<String, Object>> instructions = new ArrayList<Map<String, Object>>();
instructions.add(
ModificationInstructionBuilder.startBefore()
.activityId("activityId")
.variables(VariablesBuilder.create()
.variable("var", "value", "String", false)
.variable("varLocal", "valueLocal", "String", true)
.getVariables())
.getJson());
instructions.add(
ModificationInstructionBuilder.startAfter()
.activityId("activityId")
.variables(VariablesBuilder.create()
.variable("var", 52, "Integer", false)
.variable("varLocal", 74, "Integer", true)
.getVariables())
.getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_URL);
}
@Test
public void testSetRetriesByProcessAsync() {
List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
Batch batchEntity = MockProvider.createMockBatch();
when(mockManagementService.setJobRetriesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyInt())
).thenReturn(batchEntity);
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstances", ids);
messageBodyJson.put(RETRIES, 5);
Response response = given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_URL);
verifyBatchJson(response.asString());
verify(mockManagementService, times(1)).setJobRetriesAsync(
eq(ids), eq((ProcessInstanceQuery) null), eq(5));
}
@Test
public void testSetRetriesByProcessAsyncWithQuery() {
Batch batchEntity = MockProvider.createMockBatch();
when(mockManagementService.setJobRetriesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
anyInt())
).thenReturn(batchEntity);
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put(RETRIES, 5);
HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto();
messageBodyJson.put("processInstanceQuery", query);
Response response = given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_URL);
verifyBatchJson(response.asString());
verify(mockManagementService, times(1)).setJobRetriesAsync(
eq((List<String>) null), any(ProcessInstanceQuery.class), Mockito.eq(5));
}
@Test
public void testSetRetriesByProcessWithBadRequestQuery() {
doThrow(new BadUserRequestException("job ids are empty"))
.when(mockManagementService).setJobRetriesAsync(eq((List<String>) null), eq((ProcessInstanceQuery) null), anyInt());
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put(RETRIES, 5);
given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_URL);
}
@Test
public void testSetRetriesByProcessWithoutRetries() {
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put("processInstances", null);
given()
.contentType(ContentType.JSON)
.body(messageBodyJson)
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_URL);
}
@Test
public void testSetRetriesByProcessWithNegativeRetries() {
doThrow(new BadUserRequestException("retries are negative"))
.when(mockManagementService).setJobRetriesAsync(
anyListOf(String.class),
any(ProcessInstanceQuery.class),
eq(-1));
Map<String, Object> messageBodyJson = new HashMap<String, Object>();
messageBodyJson.put(RETRIES, -1);
HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto();
messageBodyJson.put("processInstanceQuery", query);
given()
.contentType(ContentType.JSON).body(messageBodyJson)
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_URL);
}
@Test
public void testSetRetriesByProcessAsyncHistoricQueryBasedWithQuery() {
Batch batchEntity = MockProvider.createMockBatch();
when(mockManagementService.setJobRetriesAsync(
anyListOf(String.class),
eq((ProcessInstanceQuery) null),
anyInt())
).thenReturn(batchEntity);
HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class);
when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery);
List<HistoricProcessInstance> historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances();
when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances);
SetJobRetriesByProcessDto body = new SetJobRetriesByProcessDto();
body.setRetries(MockProvider.EXAMPLE_JOB_RETRIES);
body.setHistoricProcessInstanceQuery(new HistoricProcessInstanceQueryDto());
Response response = given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL);
verifyBatchJson(response.asString());
verify(mockManagementService, times(1)).setJobRetriesAsync(
eq(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)), eq((ProcessInstanceQuery) null), eq(MockProvider.EXAMPLE_JOB_RETRIES));
}
@Test
public void testSetRetriesByProcessAsyncHistoricQueryBasedWithProcessInstanceIds() {
Batch batchEntity = MockProvider.createMockBatch();
when(mockManagementService.setJobRetriesAsync(
anyListOf(String.class),
eq((ProcessInstanceQuery) null),
anyInt())
).thenReturn(batchEntity);
SetJobRetriesByProcessDto body = new SetJobRetriesByProcessDto();
body.setRetries(MockProvider.EXAMPLE_JOB_RETRIES);
body.setProcessInstances(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID));
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL);
verify(mockManagementService, times(1)).setJobRetriesAsync(
eq(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)), eq((ProcessInstanceQuery) null), eq(MockProvider.EXAMPLE_JOB_RETRIES));
}
@Test
public void testSetRetriesByProcessAsyncHistoricQueryBasedWithQueryAndProcessInstanceIds() {
Batch batchEntity = MockProvider.createMockBatch();
when(mockManagementService.setJobRetriesAsync(
anyListOf(String.class),
eq((ProcessInstanceQuery) null),
anyInt())
).thenReturn(batchEntity);
HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class);
when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery);
List<HistoricProcessInstance> historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances();
when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances);
SetJobRetriesByProcessDto body = new SetJobRetriesByProcessDto();
body.setRetries(MockProvider.EXAMPLE_JOB_RETRIES);
body.setProcessInstances(Arrays.asList(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID));
body.setHistoricProcessInstanceQuery(new HistoricProcessInstanceQueryDto());
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL);
verify(mockManagementService, times(1)).setJobRetriesAsync(
eq(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID)),
eq((ProcessInstanceQuery) null),
eq(MockProvider.EXAMPLE_JOB_RETRIES));
}
@Test
public void testSetRetriesByProcessAsyncHistoricQueryBasedWithBadRequestQuery() {
doThrow(new BadUserRequestException("jobIds is empty"))
.when(mockManagementService).setJobRetriesAsync(eq(new ArrayList<String>()), eq((ProcessInstanceQuery) null), anyInt());
SetJobRetriesByProcessDto body = new SetJobRetriesByProcessDto();
body.setRetries(MockProvider.EXAMPLE_JOB_RETRIES);
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL);
}
@Test
public void testSetRetriesByProcessAsyncHistoricQueryBasedWithNegativeRetries() {
doThrow(new BadUserRequestException("retries are negative"))
.when(mockManagementService).setJobRetriesAsync(
anyListOf(String.class),
eq((ProcessInstanceQuery) null),
eq(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES));
HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class);
when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery);
List<HistoricProcessInstance> historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances();
when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances);
SetJobRetriesByProcessDto body = new SetJobRetriesByProcessDto();
body.setRetries(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES);
body.setHistoricProcessInstanceQuery(new HistoricProcessInstanceQueryDto());
given()
.contentType(ContentType.JSON).body(body)
.then().expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL);
}
@Test
public void testProcessInstanceModificationAsync() {
ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder();
when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder);
Batch batchMock = createMockBatch();
when(mockModificationBuilder.executeAsync(anyBoolean(), anyBoolean())).thenReturn(batchMock);
Map<String, Object> json = new HashMap<String, Object>();
json.put("skipCustomListeners", true);
json.put("skipIoMappings", true);
List<Map<String, Object>> instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson());
instructions.add(ModificationInstructionBuilder.cancellation().activityInstanceId("activityInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.cancellation().transitionInstanceId("transitionInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson());
instructions.add(ModificationInstructionBuilder.startBefore()
.activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson());
instructions.add(ModificationInstructionBuilder.startAfter()
.activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson());
instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson());
instructions.add(ModificationInstructionBuilder.startTransition()
.transitionId("transitionId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL);
verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID));
InOrder inOrder = inOrder(mockModificationBuilder);
inOrder.verify(mockModificationBuilder).cancelAllForActivity("activityId");
inOrder.verify(mockModificationBuilder).cancelActivityInstance("activityInstanceId");
inOrder.verify(mockModificationBuilder).cancelTransitionInstance("transitionInstanceId");
inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId");
inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId", "ancestorActivityInstanceId");
inOrder.verify(mockModificationBuilder).startAfterActivity("activityId");
inOrder.verify(mockModificationBuilder).startAfterActivity("activityId", "ancestorActivityInstanceId");
inOrder.verify(mockModificationBuilder).startTransition("transitionId");
inOrder.verify(mockModificationBuilder).startTransition("transitionId", "ancestorActivityInstanceId");
inOrder.verify(mockModificationBuilder).executeAsync(true, true);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testInvalidModificationAsync() {
Map<String, Object> json = new HashMap<String, Object>();
// start before: missing activity id
List<Map<String, Object>> instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.startBefore().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("'activityId' must be set"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL);
// start after: missing ancestor activity instance id
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.startAfter().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("'activityId' must be set"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL);
// start transition: missing ancestor activity instance id
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.startTransition().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("'transitionId' must be set"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL);
// cancel: missing activity id and activity instance id
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.cancellation().getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("For instruction type 'cancel': exactly one, "
+ "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL);
// cancel: both, activity id and activity instance id, set
instructions = new ArrayList<Map<String, Object>>();
instructions.add(ModificationInstructionBuilder.cancellation().activityId("anActivityId")
.activityInstanceId("anActivityInstanceId").getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.body("type", is(InvalidRequestException.class.getSimpleName()))
.body("message", containsString("For instruction type 'cancel': exactly one, "
+ "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required"))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL);
}
@Test
public void testModifyProcessInstanceAsyncThrowsAuthorizationException() {
ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder();
when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder);
String message = "expected exception";
doThrow(new AuthorizationException(message)).when(mockModificationBuilder).executeAsync(anyBoolean(), anyBoolean());
Map<String, Object> json = new HashMap<String, Object>();
List<Map<String, Object>> instructions = new ArrayList<Map<String, Object>>();
instructions.add(
ModificationInstructionBuilder.startBefore()
.activityId("activityId")
.getJson());
instructions.add(
ModificationInstructionBuilder.startAfter()
.activityId("activityId")
.getJson());
json.put("instructions", instructions);
given()
.pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID)
.contentType(ContentType.JSON)
.body(json)
.then().expect()
.statusCode(Status.FORBIDDEN.getStatusCode())
.contentType(ContentType.JSON)
.body("type", equalTo(AuthorizationException.class.getSimpleName()))
.body("message", equalTo(message))
.when()
.post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL);
}
@SuppressWarnings("unchecked")
protected ProcessInstanceModificationInstantiationBuilder setUpMockModificationBuilder() {
ProcessInstanceModificationInstantiationBuilder mockModificationBuilder =
mock(ProcessInstanceModificationInstantiationBuilder.class);
when(mockModificationBuilder.cancelActivityInstance(anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.cancelAllForActivity(anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.startAfterActivity(anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.startAfterActivity(anyString(), anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.startBeforeActivity(anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.startBeforeActivity(anyString(), anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.startTransition(anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.startTransition(anyString(), anyString())).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.setVariables(any(Map.class))).thenReturn(mockModificationBuilder);
when(mockModificationBuilder.setVariablesLocal(any(Map.class))).thenReturn(mockModificationBuilder);
return mockModificationBuilder;
}
protected void verifyBatchJson(String batchJson) {
BatchDto batch = JsonPathUtil.from(batchJson).getObject("", BatchDto.class);
assertNotNull("The returned batch should not be null.", batch);
assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId());
assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType());
assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs());
assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed());
assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob());
assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId());
assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId());
assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId());
assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId());
}
}
|
3e0dc2091a7f4af183f9fe387c5a63aff41f2a06 | 7,169 | java | Java | src/main/java/sibModel/UpdateSmsCampaign.java | fecc82/APIv3-java-library | d932cda3ca8fb1e063390ff17eb1807001d7a98f | [
"MIT"
] | 1 | 2022-03-27T22:32:14.000Z | 2022-03-27T22:32:14.000Z | src/main/java/sibModel/UpdateSmsCampaign.java | fecc82/APIv3-java-library | d932cda3ca8fb1e063390ff17eb1807001d7a98f | [
"MIT"
] | null | null | null | src/main/java/sibModel/UpdateSmsCampaign.java | fecc82/APIv3-java-library | d932cda3ca8fb1e063390ff17eb1807001d7a98f | [
"MIT"
] | null | null | null | 34 | 841 | 0.696125 | 5,815 | /*
* SendinBlue API
* SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable |
*
* OpenAPI spec version: 3.0.0
* Contact: anpch@example.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package sibModel;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import sibModel.CreateSmsCampaignRecipients;
/**
* UpdateSmsCampaign
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2022-03-02T23:12:13.151+05:30")
public class UpdateSmsCampaign {
@SerializedName("name")
private String name = null;
@SerializedName("sender")
private String sender = null;
@SerializedName("content")
private String content = null;
@SerializedName("recipients")
private CreateSmsCampaignRecipients recipients = null;
@SerializedName("scheduledAt")
private String scheduledAt = null;
@SerializedName("unicodeEnabled")
private Boolean unicodeEnabled = false;
public UpdateSmsCampaign name(String name) {
this.name = name;
return this;
}
/**
* Name of the campaign
* @return name
**/
@ApiModelProperty(example = "Spring Promo Code", value = "Name of the campaign")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UpdateSmsCampaign sender(String sender) {
this.sender = sender;
return this;
}
/**
* Name of the sender. **The number of characters is limited to 11 for alphanumeric characters and 15 for numeric characters**
* @return sender
**/
@ApiModelProperty(example = "MyShop", value = "Name of the sender. **The number of characters is limited to 11 for alphanumeric characters and 15 for numeric characters**")
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public UpdateSmsCampaign content(String content) {
this.content = content;
return this;
}
/**
* Content of the message. The maximum characters used per SMS is 160, if used more than that, it will be counted as more than one SMS
* @return content
**/
@ApiModelProperty(example = "Get a discount by visiting our NY store and saying : Happy Spring!", value = "Content of the message. The maximum characters used per SMS is 160, if used more than that, it will be counted as more than one SMS")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public UpdateSmsCampaign recipients(CreateSmsCampaignRecipients recipients) {
this.recipients = recipients;
return this;
}
/**
* Get recipients
* @return recipients
**/
@ApiModelProperty(value = "")
public CreateSmsCampaignRecipients getRecipients() {
return recipients;
}
public void setRecipients(CreateSmsCampaignRecipients recipients) {
this.recipients = recipients;
}
public UpdateSmsCampaign scheduledAt(String scheduledAt) {
this.scheduledAt = scheduledAt;
return this;
}
/**
* UTC date-time on which the campaign has to run (YYYY-MM-DDTHH:mm:ss.SSSZ). Prefer to pass your timezone in date-time format for accurate result.
* @return scheduledAt
**/
@ApiModelProperty(example = "2017-05-05T12:30:00+02:00", value = "UTC date-time on which the campaign has to run (YYYY-MM-DDTHH:mm:ss.SSSZ). Prefer to pass your timezone in date-time format for accurate result.")
public String getScheduledAt() {
return scheduledAt;
}
public void setScheduledAt(String scheduledAt) {
this.scheduledAt = scheduledAt;
}
public UpdateSmsCampaign unicodeEnabled(Boolean unicodeEnabled) {
this.unicodeEnabled = unicodeEnabled;
return this;
}
/**
* Format of the message. It indicates whether the content should be treated as unicode or not.
* @return unicodeEnabled
**/
@ApiModelProperty(example = "true", value = "Format of the message. It indicates whether the content should be treated as unicode or not.")
public Boolean isUnicodeEnabled() {
return unicodeEnabled;
}
public void setUnicodeEnabled(Boolean unicodeEnabled) {
this.unicodeEnabled = unicodeEnabled;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UpdateSmsCampaign updateSmsCampaign = (UpdateSmsCampaign) o;
return Objects.equals(this.name, updateSmsCampaign.name) &&
Objects.equals(this.sender, updateSmsCampaign.sender) &&
Objects.equals(this.content, updateSmsCampaign.content) &&
Objects.equals(this.recipients, updateSmsCampaign.recipients) &&
Objects.equals(this.scheduledAt, updateSmsCampaign.scheduledAt) &&
Objects.equals(this.unicodeEnabled, updateSmsCampaign.unicodeEnabled);
}
@Override
public int hashCode() {
return Objects.hash(name, sender, content, recipients, scheduledAt, unicodeEnabled);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UpdateSmsCampaign {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" sender: ").append(toIndentedString(sender)).append("\n");
sb.append(" content: ").append(toIndentedString(content)).append("\n");
sb.append(" recipients: ").append(toIndentedString(recipients)).append("\n");
sb.append(" scheduledAt: ").append(toIndentedString(scheduledAt)).append("\n");
sb.append(" unicodeEnabled: ").append(toIndentedString(unicodeEnabled)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e0dc283584f6d030d9edf99230e37011720faf0 | 1,760 | java | Java | jwebform-spring-boot-starter/src/main/java/jwebform/spring/ContainerFormRunnerArgumentResolver.java | jochen777/jWebForm | 67a989cfa4adf90ca6b0ec1abb653a1332d78a9a | [
"MIT"
] | 19 | 2017-07-07T21:44:56.000Z | 2021-11-30T22:32:50.000Z | jwebform-spring-boot-starter/src/main/java/jwebform/spring/ContainerFormRunnerArgumentResolver.java | jochen777/jWebForm | 67a989cfa4adf90ca6b0ec1abb653a1332d78a9a | [
"MIT"
] | 4 | 2018-10-29T10:47:37.000Z | 2019-07-18T11:48:39.000Z | jwebform-spring-boot-starter/src/main/java/jwebform/spring/ContainerFormRunnerArgumentResolver.java | jochen777/jWebForm | 67a989cfa4adf90ca6b0ec1abb653a1332d78a9a | [
"MIT"
] | 1 | 2020-09-27T23:26:54.000Z | 2020-09-27T23:26:54.000Z | 35.2 | 101 | 0.804545 | 5,816 | package jwebform.spring;
import jwebform.integration.ContainerFormRunner;
import jwebform.integration.FormRunnerConfig;
import jwebform.processor.FormGenerator;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
public class ContainerFormRunnerArgumentResolver implements HandlerMethodArgumentResolver {
private final FormRunnerConfig formRunnerConfig;
public ContainerFormRunnerArgumentResolver(
FormRunnerConfig formRunnerConfig) {
this.formRunnerConfig = formRunnerConfig;
}
@Override
public Object resolveArgument(MethodParameter methodParam, ModelAndViewContainer mavContainer,
NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception {
methodParam.increaseNestingLevel();
Class<FormGenerator> typeOfBean = (Class<FormGenerator>) methodParam.getNestedParameterType();
methodParam.decreaseNestingLevel();
ContainerFormRunner f = new ContainerFormRunner<FormGenerator>(
typeOfBean, t -> request.getParameter(t),
t -> request.getNativeRequest(HttpServletRequest.class).getSession().getAttribute(t),
(t, v) -> request.getNativeRequest(HttpServletRequest.class).getSession().setAttribute(t, v),
(t, v) -> mavContainer.addAttribute(t, v), formRunnerConfig);
return f;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(ContainerFormRunner.class);
}
}
|
3e0dc2912ac2d339862b51ca11071fbd5464aeea | 2,023 | java | Java | mongodb/aggregation/src/main/java/example/springdata/mongodb/aggregation/OrderRepository.java | patel243/spring-data-examples | e5365aefa5a9df4d79ffc124a5bf337ff434838e | [
"Apache-2.0"
] | 4,772 | 2015-01-06T12:36:15.000Z | 2022-03-30T13:37:02.000Z | mongodb/aggregation/src/main/java/example/springdata/mongodb/aggregation/OrderRepository.java | patel243/spring-data-examples | e5365aefa5a9df4d79ffc124a5bf337ff434838e | [
"Apache-2.0"
] | 519 | 2015-01-04T17:10:10.000Z | 2022-03-30T06:20:17.000Z | mongodb/aggregation/src/main/java/example/springdata/mongodb/aggregation/OrderRepository.java | patel243/spring-data-examples | e5365aefa5a9df4d79ffc124a5bf337ff434838e | [
"Apache-2.0"
] | 3,670 | 2015-01-06T03:47:23.000Z | 2022-03-31T12:16:18.000Z | 43.978261 | 189 | 0.681167 | 5,817 | /*
* Copyright 2013-2021 the original author or authors.
*
* 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
*
* https://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 example.springdata.mongodb.aggregation;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.repository.CrudRepository;
/**
* A repository interface assembling CRUD functionality as well as the API to invoke the methods implemented manually.
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Divya Srivastava
*/
public interface OrderRepository extends CrudRepository<Order, String>, OrderRepositoryCustom {
@Aggregation("{ $group : { _id : $customerId, total : { $sum : 1 } } }")
List<OrdersPerCustomer> totalOrdersPerCustomer(Sort sort);
@Aggregation(pipeline = { "{ $match : { customerId : ?0 } }", "{ $count : total }" })
Long totalOrdersForCustomer(String customerId);
@Aggregation(pipeline = { "{ $match : { id : ?0 } }", "{ $unwind : { path : '$items' } }",
"{ $project : { id : 1 , customerId : 1 , items : 1 , lineTotal : { $multiply: [ '$items.price' , '$items.quantity' ] } } }",
"{ $group : { '_id' : '$_id' , 'netAmount' : { $sum : '$lineTotal' } , 'items' : { $addToSet : '$items' } } }",
"{ $project : { 'orderId' : '$_id' , 'items' : 1 , 'netAmount' : 1 , 'taxAmount' : { $multiply: [ '$netAmount' , 0.19 ] } , 'totalAmount' : { $multiply: [ '$netAmount' , 1.19 ] } } }" })
Invoice aggregateInvoiceForOrder(String orderId);
}
|
3e0dc34cb0b3786a836d362a6bee1ccea9f5610f | 97 | java | Java | src/main/java/co/luisfe/bridge/Implementador.java | femoru/patronbridge | b08ce6daa7b2774503e78b6485f41da0ce1e0ea2 | [
"MIT"
] | null | null | null | src/main/java/co/luisfe/bridge/Implementador.java | femoru/patronbridge | b08ce6daa7b2774503e78b6485f41da0ce1e0ea2 | [
"MIT"
] | null | null | null | src/main/java/co/luisfe/bridge/Implementador.java | femoru/patronbridge | b08ce6daa7b2774503e78b6485f41da0ce1e0ea2 | [
"MIT"
] | null | null | null | 13.857143 | 33 | 0.690722 | 5,818 | package co.luisfe.bridge;
public interface Implementador {
public void procesar();
}
|
3e0dc4d7552f54b48a6bf7f34b0d4a40bd124767 | 423 | java | Java | Klayton Junior/trabalhos/Lista de Exercicios 2/src/Condicional/ex17.java | IgorVieira/FirstClass-GlobalRHSolutions | 7b5a8094649e0d2f4e051aac798f68140f09d125 | [
"MIT"
] | null | null | null | Klayton Junior/trabalhos/Lista de Exercicios 2/src/Condicional/ex17.java | IgorVieira/FirstClass-GlobalRHSolutions | 7b5a8094649e0d2f4e051aac798f68140f09d125 | [
"MIT"
] | null | null | null | Klayton Junior/trabalhos/Lista de Exercicios 2/src/Condicional/ex17.java | IgorVieira/FirstClass-GlobalRHSolutions | 7b5a8094649e0d2f4e051aac798f68140f09d125 | [
"MIT"
] | null | null | null | 18.391304 | 77 | 0.671395 | 5,819 | package Condicional;
import javax.swing.JOptionPane;
public class ex17 {
public static void main(String[]args){
int x;
x = Integer.parseInt(JOptionPane.showInputDialog(null,"Digite sua senha"));
if(x==4531){
JOptionPane.showMessageDialog(null, "Senha correta"
+"\n Acesso permitido");
}else{
JOptionPane.showMessageDialog(null, "Senha incorreta"
+"\n Acesso negado");
}
}
} |
3e0dc551c670e3b7239f2e19cdf27a28bacd27bc | 588 | java | Java | src/speedtest/TrigTest.java | zachdeibert/JavaSpeedTest | 8a3d186ebcb7a04888b6aab0ed4112898adf07ad | [
"MIT"
] | null | null | null | src/speedtest/TrigTest.java | zachdeibert/JavaSpeedTest | 8a3d186ebcb7a04888b6aab0ed4112898adf07ad | [
"MIT"
] | null | null | null | src/speedtest/TrigTest.java | zachdeibert/JavaSpeedTest | 8a3d186ebcb7a04888b6aab0ed4112898adf07ad | [
"MIT"
] | null | null | null | 25.565217 | 59 | 0.430272 | 5,820 | package speedtest;
public class TrigTest extends Test {
private final float nums[] = randomize(ITERATIONS / 2);
@Override
public void run() {
try {
for ( int i = 0; i < nums.length; i++ ) {
final float a = nums[i];
cli.System.Math.Sin(a);
cli.System.Math.Cos(a);
}
} catch ( final Throwable t ) {
for ( int i = 0; i < nums.length; i++ ) {
final float a = nums[i];
Math.sin(a);
Math.cos(a);
}
}
}
}
|
3e0dc568ffdbd12b506ed7eb2ea73600594ef802 | 5,280 | java | Java | dsl/src/main/java/cd/go/contrib/plugins/configrepo/groovy/dsl/Job.java | marques-work/gocd-groovy-dsl-config-plugin | 537d2eda129d0eb7467ca6735efb09e052089392 | [
"Apache-2.0"
] | 5 | 2019-04-30T20:13:35.000Z | 2021-08-08T17:22:31.000Z | dsl/src/main/java/cd/go/contrib/plugins/configrepo/groovy/dsl/Job.java | marques-work/gocd-groovy-dsl-config-plugin | 537d2eda129d0eb7467ca6735efb09e052089392 | [
"Apache-2.0"
] | 155 | 2019-04-05T15:33:59.000Z | 2022-01-29T15:35:14.000Z | dsl/src/main/java/cd/go/contrib/plugins/configrepo/groovy/dsl/Job.java | chadlwilson/gocd-groovy-dsl-config-plugin | 40ba2f022ddad36947412db29e59a28095991002 | [
"Apache-2.0"
] | 12 | 2019-04-05T14:56:59.000Z | 2021-09-28T12:07:18.000Z | 32.392638 | 220 | 0.683523 | 5,821 | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* 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 cd.go.contrib.plugins.configrepo.groovy.dsl;
import cd.go.contrib.plugins.configrepo.groovy.dsl.util.RunInstanceCount;
import com.fasterxml.jackson.annotation.JsonProperty;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovy.transform.stc.ClosureParams;
import groovy.transform.stc.SimpleType;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.validation.Valid;
import javax.validation.constraints.PositiveOrZero;
import java.util.ArrayList;
import java.util.List;
import static groovy.lang.Closure.DELEGATE_ONLY;
import static lombok.AccessLevel.NONE;
/**
* Represents a job.
* <p>
* {@includeCode job-with-simple-task.groovy}
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class Job extends HasEnvironmentVariables<Job> {
/**
* The number of agents this job should run on.
* Defaults to {@code 1}. Set to string {@code "all"}
* to run on all agents.
*/
@JsonProperty("run_instance_count")
@RunInstanceCount
private Object runInstanceCount;
/**
* The job hung timeout (in minutes). If there is no console output for within this
* interval of time, the job is assumed to be jung and will be terminated by GoCD.
* <p>
* Defaults to {@code 0} to never timeout.
*/
@JsonProperty("timeout")
@PositiveOrZero
private Integer timeout;
/**
* A job can be configured to run on an elastic agent by specifying this attribute, which maps to the id of an
* existing {@code <profile>} defined in the main config xml.
*
* <strong>MUST NOT</strong> be specified along with {@link Job#resources}
*/
@JsonProperty("elastic_profile_id")
private String elasticProfileId;
/**
* Specifies the list of resources that will be matched against jobs.
* An Agent must have all the Resources specified for a Job to be able to run this job.
*
* <strong>MUST NOT</strong> be specified along with {@link Job#elasticProfileId}
*/
@JsonProperty("resources")
private List<String> resources = new ArrayList<>();
@Getter(value = NONE)
@Setter(value = NONE)
@JsonProperty("tabs")
@Valid
private Tabs tabs = new Tabs();
@Getter(value = NONE)
@Setter(value = NONE)
@JsonProperty("artifacts")
@Valid
private Artifacts artifacts = new Artifacts();
@Getter(value = NONE)
@Setter(value = NONE)
@JsonProperty("tasks")
@Valid
private Tasks tasks = new Tasks();
@Getter(value = NONE)
@Setter(value = NONE)
@JsonProperty("properties")
@Valid
private Properties properties = new Properties();
public Job() {
this(null);
}
public Job(String name) {
this(name, null);
}
public Job(String name, @DelegatesTo(value = Job.class, strategy = DELEGATE_ONLY) @ClosureParams(value = SimpleType.class, options = "cd.go.contrib.plugins.configrepo.groovy.dsl.Job") Closure cl) {
super(name);
configure(cl);
}
/**
* The list of artifacts generated by this job.
* <p>
* {@includeCode artifacts.big.groovy}
*/
public Artifacts artifacts(@DelegatesTo(value = Artifacts.class, strategy = DELEGATE_ONLY) @ClosureParams(value = SimpleType.class, options = "cd.go.contrib.plugins.configrepo.groovy.dsl.Artifacts") Closure cl) {
artifacts.configure(cl);
return artifacts;
}
/**
* The sequence of tasks executed by this job.
* <p>
* {@includeCode job-with-tasks.groovy}
*/
public Tasks tasks(@DelegatesTo(value = Tasks.class, strategy = DELEGATE_ONLY) @ClosureParams(value = SimpleType.class, options = "cd.go.contrib.plugins.configrepo.groovy.dsl.Tasks") Closure cl) {
tasks.configure(cl);
return tasks;
}
/**
* The list of tabs displayed on the job detail page.
* <p>
* {@includeCode job-with-tabs.groovy}
*/
public Tabs tabs(@DelegatesTo(value = Tabs.class, strategy = DELEGATE_ONLY) @ClosureParams(value = SimpleType.class, options = "cd.go.contrib.plugins.configrepo.groovy.dsl.Tabs") Closure cl) {
tabs.configure(cl);
return tabs;
}
/**
* The list of properties published by this job
* <p>
* {@includeCode job-with-properties.groovy}
*/
public Properties properties(@DelegatesTo(value = Properties.class, strategy = DELEGATE_ONLY) @ClosureParams(value = SimpleType.class, options = "cd.go.contrib.plugins.configrepo.groovy.dsl.Properties") Closure cl) {
properties.configure(cl);
return properties;
}
}
|
3e0dc58734b49707cc8cdcdece9895d97cd33d76 | 2,358 | java | Java | repose-aggregator/core/core-lib/src/main/java/org/openrepose/core/services/rms/ImmutableStatusCodes.java | olacabs/repose | 795b009edc46bcd10d4b337622239155749a92dd | [
"Apache-2.0"
] | null | null | null | repose-aggregator/core/core-lib/src/main/java/org/openrepose/core/services/rms/ImmutableStatusCodes.java | olacabs/repose | 795b009edc46bcd10d4b337622239155749a92dd | [
"Apache-2.0"
] | null | null | null | repose-aggregator/core/core-lib/src/main/java/org/openrepose/core/services/rms/ImmutableStatusCodes.java | olacabs/repose | 795b009edc46bcd10d4b337622239155749a92dd | [
"Apache-2.0"
] | 1 | 2021-03-29T09:35:51.000Z | 2021-03-29T09:35:51.000Z | 36.84375 | 102 | 0.679813 | 5,822 | /*
* _=_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_=
* Repose
* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
* Copyright (C) 2010 - 2015 Rackspace US, Inc.
* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
* 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 org.openrepose.core.services.rms;
import org.openrepose.core.services.rms.config.StatusCodeMatcher;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* @author fran
*/
public final class ImmutableStatusCodes {
private final List<StatusCodeMatcher> statusCodeMatcherList = new LinkedList<StatusCodeMatcher>();
private final Map<String, Pattern> statusCodeRegexes = new HashMap<String, Pattern>();
private ImmutableStatusCodes(List<StatusCodeMatcher> statusCodes) {
statusCodeMatcherList.clear();
statusCodeMatcherList.addAll(statusCodes);
statusCodeRegexes.clear();
for (StatusCodeMatcher code : statusCodeMatcherList) {
statusCodeRegexes.put(code.getId(), Pattern.compile(code.getCodeRegex()));
}
}
public static ImmutableStatusCodes build(List<StatusCodeMatcher> statusCodeMatchers) {
return new ImmutableStatusCodes(statusCodeMatchers);
}
public StatusCodeMatcher getMatchingStatusCode(String statusCode) {
StatusCodeMatcher matchedCode = null;
for (StatusCodeMatcher code : statusCodeMatcherList) {
if (statusCodeRegexes.get(code.getId()).matcher(statusCode).matches()) {
matchedCode = code;
break;
}
}
return matchedCode;
}
}
|
3e0dc609123418bacff92699b0a3a06a6715a65f | 3,033 | java | Java | gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/set6/light/Card6_019.java | stevetotheizz0/gemp-swccg-public | 05529086de91ecb03807fda820d98ec8a1465246 | [
"MIT"
] | 19 | 2020-08-30T18:44:38.000Z | 2022-02-10T18:23:49.000Z | gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/set6/light/Card6_019.java | stevetotheizz0/gemp-swccg-public | 05529086de91ecb03807fda820d98ec8a1465246 | [
"MIT"
] | 480 | 2020-09-11T00:19:27.000Z | 2022-03-31T19:46:37.000Z | gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/set6/light/Card6_019.java | stevetotheizz0/gemp-swccg-public | 05529086de91ecb03807fda820d98ec8a1465246 | [
"MIT"
] | 21 | 2020-08-29T16:19:44.000Z | 2022-03-29T01:37:39.000Z | 44.602941 | 172 | 0.717771 | 5,823 | package com.gempukku.swccgo.cards.set6.light;
import com.gempukku.swccgo.cards.AbstractAlien;
import com.gempukku.swccgo.cards.GameConditions;
import com.gempukku.swccgo.cards.conditions.AtCondition;
import com.gempukku.swccgo.cards.effects.usage.OncePerPhaseEffect;
import com.gempukku.swccgo.common.*;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.actions.TopLevelGameTextAction;
import com.gempukku.swccgo.logic.effects.PutCardFromHandOnBottomOfUsedPileEffect;
import com.gempukku.swccgo.logic.effects.choose.DrawCardIntoHandFromReserveDeckEffect;
import com.gempukku.swccgo.logic.modifiers.Modifier;
import com.gempukku.swccgo.logic.modifiers.PowerModifier;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Set: Jabba's Palace
* Type: Character
* Subtype: Alien
* Title: Ishi Tib
*/
public class Card6_019 extends AbstractAlien {
public Card6_019() {
super(Side.LIGHT, 3, 2, 1, 1, 2, "Ishi Tib", Uniqueness.RESTRICTED_3);
setArmor(3);
setLore("Extremely efficient organizers. Sought after by transgalactic corporations. Spend a large part of their life underwater. Protected by rough, thick skin.");
setGameText("Power +1 at any swamp. During your draw phase, may place one card from your hand on bottom of Used Pile to draw a card from Reserve Deck.");
addIcons(Icon.JABBAS_PALACE);
setSpecies(Species.ISHI_TIB);
}
@Override
protected List<Modifier> getGameTextWhileActiveInPlayModifiers(SwccgGame game, final PhysicalCard self) {
List<Modifier> modifiers = new LinkedList<Modifier>();
modifiers.add(new PowerModifier(self, new AtCondition(self, Filters.swamp), 1));
return modifiers;
}
@Override
protected List<TopLevelGameTextAction> getGameTextTopLevelActions(final String playerId, SwccgGame game, final PhysicalCard self, int gameTextSourceCardId) {
// Check condition(s)
if (GameConditions.isOnceDuringYourPhase(game, self, playerId, gameTextSourceCardId, Phase.DRAW)
&& GameConditions.hasHand(game, playerId)
&& GameConditions.hasReserveDeck(game, playerId)) {
final TopLevelGameTextAction action = new TopLevelGameTextAction(self, gameTextSourceCardId);
action.setText("Place card from hand in Used Pile");
action.setActionMsg("Draw top card of Reserve Deck");
// Update usage limit(s)
action.appendUsage(
new OncePerPhaseEffect(action));
// Pay cost(s)
action.appendCost(
new PutCardFromHandOnBottomOfUsedPileEffect(action, playerId));
// Perform result(s)
action.appendEffect(
new DrawCardIntoHandFromReserveDeckEffect(action, playerId));
return Collections.singletonList(action);
}
return null;
}
}
|
3e0dc6b7197e94e54a8f7b4725ff0060e9608529 | 348 | java | Java | node_modules/unimodules-file-system-interface/android/build/generated/source/buildConfig/debug/org/unimodules/interfaces/filesystem/BuildConfig.java | FullStackDevCoach/Kobiton-ToDoList | 25ad56fbb564107f7cd8363350bcd6361045d59a | [
"Apache-2.0"
] | null | null | null | node_modules/unimodules-file-system-interface/android/build/generated/source/buildConfig/debug/org/unimodules/interfaces/filesystem/BuildConfig.java | FullStackDevCoach/Kobiton-ToDoList | 25ad56fbb564107f7cd8363350bcd6361045d59a | [
"Apache-2.0"
] | null | null | null | node_modules/unimodules-file-system-interface/android/build/generated/source/buildConfig/debug/org/unimodules/interfaces/filesystem/BuildConfig.java | FullStackDevCoach/Kobiton-ToDoList | 25ad56fbb564107f7cd8363350bcd6361045d59a | [
"Apache-2.0"
] | null | null | null | 31.636364 | 91 | 0.775862 | 5,825 | /**
* Automatically generated file. DO NOT MODIFY
*/
package org.unimodules.interfaces.filesystem;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String LIBRARY_PACKAGE_NAME = "org.unimodules.interfaces.filesystem";
public static final String BUILD_TYPE = "debug";
}
|
3e0dc6d736545599137d7896949a060194f94afa | 7,654 | java | Java | case-server/src/main/java/com/xiaoju/framework/handler/RecordRoom.java | yimfeng/AgileTC | 10312758f4375e94832a39cfc5199585832136a0 | [
"Apache-2.0"
] | 493 | 2020-09-04T07:48:21.000Z | 2022-03-31T18:24:31.000Z | case-server/src/main/java/com/xiaoju/framework/handler/RecordRoom.java | liwanlei/AgileTC | 3407027dc06bedc8a808a32c56f89fddaf059600 | [
"Apache-2.0"
] | 81 | 2020-09-08T10:30:05.000Z | 2022-03-27T12:18:35.000Z | case-server/src/main/java/com/xiaoju/framework/handler/RecordRoom.java | liwanlei/AgileTC | 3407027dc06bedc8a808a32c56f89fddaf059600 | [
"Apache-2.0"
] | 209 | 2020-09-04T07:43:53.000Z | 2022-03-25T11:44:56.000Z | 46.108434 | 158 | 0.623857 | 5,826 | package com.xiaoju.framework.handler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoju.framework.entity.dto.RecordWsDto;
import com.xiaoju.framework.entity.persistent.ExecRecord;
import com.xiaoju.framework.entity.xmind.IntCount;
import com.xiaoju.framework.util.BitBaseUtil;
import com.xiaoju.framework.util.TreeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.stream.Collectors;
import static com.xiaoju.framework.constants.SystemConstant.COMMA;
/**
* Created by didi on 2021/3/27.
*/
public class RecordRoom extends Room {
private static final Logger LOGGER = LoggerFactory.getLogger(RecordRoom.class);
private long recordId;
private ExecRecord recordUpdate;
private String executors;
public RecordRoom(Long id) {
super(id);
recordId = BitBaseUtil.getHigh32(id);
}
@Override
public Player createAndAddPlayer(Client client) {
Player p = super.createAndAddPlayer(client);
// 合并record和用例后发送给前端
String caseContent = testCaseContent != null ? testCaseContent : testCase.getCaseContent();
if (p.getRoom().players.size() <= 1) {
mergeRecoed(p.getClient().getRecordId(), caseContent);
}
p.getClient().sendMessage(CaseMessageType.EDITOR, testCaseContent);
LOGGER.info(Thread.currentThread().getName() + ": 新的用户加入成功,传输用例内容: " + testCaseContent);
return p;
}
@Override
protected void internalRemovePlayer(Player p) {
super.internalRemovePlayer(p);
// 如果是最后一个用户离开,需要关闭广播任务
if (players.size() == 0) {
if (testCaseContent != null) {
LOGGER.info(Thread.currentThread().getName() + ": 当前的用例内容是:" + testCaseContent);
// testCase.setCaseContent(testCaseContent);
testCase.setGmtModified(new Date(System.currentTimeMillis()));
JSONObject jsonObject = TreeUtil.parse(testCaseContent);
JSONObject jsonProgress = jsonObject.getJSONObject("progress");
Integer totalCount = jsonObject.getInteger("totalCount");
Integer passCount = jsonObject.getInteger("passCount");
Integer failCount = jsonObject.getInteger("failCount");
Integer blockCount = jsonObject.getInteger("blockCount");
Integer successCount = jsonObject.getInteger("successCount");
Integer ignoreCount = jsonObject.getInteger("ignoreCount");
ExecRecord recordUpdate = new ExecRecord();
recordUpdate.setId(Long.valueOf(recordId));
List<String> names = Arrays.stream(executors.split(COMMA)).filter(e->!StringUtils.isEmpty(e)).collect(Collectors.toList());
long count = names.stream().filter(e -> e.equals(p.getClient().getClientName())).count();
if (count > 0) {
// 有重合,不管了
;
} else {
// 没重合往后面塞一个
names.add(p.getClient().getClientName());
executors = String.join(",", names);
}
recordUpdate.setExecutors(executors);
recordUpdate.setModifier(p.getClient().getClientName());
recordUpdate.setGmtModified(new Date(System.currentTimeMillis()));
recordUpdate.setCaseContent(jsonProgress.toJSONString());
recordUpdate.setFailCount(failCount);
recordUpdate.setBlockCount(blockCount);
recordUpdate.setIgnoreCount(ignoreCount);
recordUpdate.setPassCount(passCount);
recordUpdate.setTotalCount(totalCount);
recordUpdate.setSuccessCount(successCount);
synchronized (WebSocket.getRoomLock()) {
recordService.modifyRecord(recordUpdate);
LOGGER.info(Thread.currentThread().getName() + ": 数据库用例记录更新。");
WebSocket.getRooms().remove(Long.valueOf(BitBaseUtil.mergeLong(Long.valueOf(recordId), Long.valueOf(testCase.getId()))));
LOGGER.info(Thread.currentThread().getName() + ": [websocket-onClose 关闭当前Room成功]当前sessionid:" + p.getClient().getSession().getId());
}
} else {
synchronized (WebSocket.getRoomLock()) {
WebSocket.getRooms().remove(Long.valueOf(BitBaseUtil.mergeLong(Long.valueOf(recordId), Long.valueOf(testCase.getId()))));
LOGGER.info(Thread.currentThread().getName() + ": [websocket-onClose 关闭当前Room成功]用户未变更,当前sessionid:" + p.getClient().getSession().getId());
}
}
LOGGER.info(Thread.currentThread().getName() + ": 最后一名用户 " + p.getClient().getClientName() + " 离开,关闭。");
}
// 广播有用户离开
broadcastRoomMessage(CaseMessageType.NOTIFY, "当前用户数:" + players.size() + "。用例执行者 " + p.getClient().getClientName() + " 离开");
}
public void mergeRecoed(Long recordId, String caseContentStr) {
RecordWsDto dto = recordService.getWsRecord(recordId);
if (dto == null) {
//todo: 在controller层应该已经创建了任务,因此这里一定不为空
assert false;
LOGGER.error(Thread.currentThread().getName() + ": 当前用例执行者初次打开任务");
}
executors = dto.getExecutors();
String recordContent = dto.getCaseContent();
JSONObject recordObj = new JSONObject();
if (StringUtils.isEmpty(recordContent)) {
// 其实当前任务还没有任何执行记录
LOGGER.info(Thread.currentThread().getName() + ": first create record.");
} else if (recordContent.startsWith("[{")) {
JSONArray jsonArray = JSON.parseArray(recordContent);
for (Object o : jsonArray) {
recordObj.put(((JSONObject) o).getString("id"), ((JSONObject) o).getLong("progress"));
}
} else {
recordObj = JSON.parseObject(recordContent);
}
IntCount ExecCount = new IntCount(recordObj.size());
// 如果当前record是圈选了部分的圈选用例
if (!StringUtils.isEmpty(dto.getChooseContent()) && !dto.getChooseContent().contains("\"priority\":[\"0\"]")) {
Map<String, List<String>> chosen = JSON.parseObject(dto.getChooseContent(), Map.class);
JSONObject caseContent = JSON.parseObject(caseContentStr);
JSONObject caseRoot = caseContent.getJSONObject("root");
Stack<JSONObject> objCheck = new Stack<>();
Stack<IntCount> iCheck = new Stack<>();
objCheck.push(caseRoot);
List<String> priority = chosen.get("priority");
List<String> resource = chosen.get("resource");
//获取对应级别用例
if (!CollectionUtils.isEmpty(priority)) {
TreeUtil.getPriority(objCheck, iCheck, caseRoot, priority);
}
if (!CollectionUtils.isEmpty(resource)) {
TreeUtil.getChosenCase(caseRoot, new HashSet<>(resource), "resource");
}
TreeUtil.mergeExecRecord(caseContent.getJSONObject("root"), recordObj, ExecCount);
testCaseContent = caseContent.toJSONString();
} else {
// 如果是全部的,那么直接把testcase 给 merge过来
JSONObject caseContent = JSON.parseObject(caseContentStr);
TreeUtil.mergeExecRecord(caseContent.getJSONObject("root"), recordObj, ExecCount);
testCaseContent = caseContent.toJSONString();
}
}
}
|
3e0dc87a7016f384e9ee3b64cd8436e821c4a2d1 | 1,759 | java | Java | okapi/libraries/lib-beans/src/main/java/net/sf/okapi/lib/beans/v1/AltTransBean.java | vistatec/vistatec-okapi | 17cd885f5fefd8236a95a0b203272795c42fea88 | [
"Apache-2.0"
] | 2 | 2018-08-15T02:40:30.000Z | 2019-12-20T12:43:56.000Z | okapi/libraries/lib-beans/src/main/java/net/sf/okapi/lib/beans/v1/AltTransBean.java | vistatec/vistatec-okapi | 17cd885f5fefd8236a95a0b203272795c42fea88 | [
"Apache-2.0"
] | null | null | null | okapi/libraries/lib-beans/src/main/java/net/sf/okapi/lib/beans/v1/AltTransBean.java | vistatec/vistatec-okapi | 17cd885f5fefd8236a95a0b203272795c42fea88 | [
"Apache-2.0"
] | 1 | 2019-08-21T06:22:25.000Z | 2019-08-21T06:22:25.000Z | 26.651515 | 77 | 0.656623 | 5,827 | /*===========================================================================
Copyright (C) 2008-2010 by the Okapi Framework contributors
-----------------------------------------------------------------------------
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 net.sf.okapi.lib.beans.v1;
import net.sf.okapi.lib.persistence.IPersistenceSession;
import net.sf.okapi.lib.persistence.PersistenceBean;
public class AltTransBean extends PersistenceBean<Object> {
private String srcLang;
private String trgLang;
private TextUnitBean tu = new TextUnitBean();
@Override
protected Object createObject(IPersistenceSession session) {
return null;
}
@Override
protected void fromObject(Object obj, IPersistenceSession session) {
}
@Override
protected void setObject(Object obj, IPersistenceSession session) {
}
public String getSrcLang() {
return srcLang;
}
public void setSrcLang(String srcLang) {
this.srcLang = srcLang;
}
public String getTrgLang() {
return trgLang;
}
public void setTrgLang(String trgLang) {
this.trgLang = trgLang;
}
public TextUnitBean getTu() {
return tu;
}
public void setTu(TextUnitBean tu) {
this.tu = tu;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.