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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1468deb744ec53da621d43f69df08c68db11ca | 2,340 | java | Java | src/main/java/org/proteored/miapeapi/xml/mzidentml/autogenerated/MeasureType.java | smdb21/java-miape-api | 5a49b49a3fed97ea5e441e85fe2cf8621b4e0900 | [
"Apache-2.0"
] | 1 | 2016-02-11T16:03:08.000Z | 2016-02-11T16:03:08.000Z | src/main/java/org/proteored/miapeapi/xml/mzidentml/autogenerated/MeasureType.java | smdb21/java-miape-api | 5a49b49a3fed97ea5e441e85fe2cf8621b4e0900 | [
"Apache-2.0"
] | 1 | 2019-11-14T19:01:23.000Z | 2019-11-14T19:01:23.000Z | src/main/java/org/proteored/miapeapi/xml/mzidentml/autogenerated/MeasureType.java | smdb21/java-miape-api | 5a49b49a3fed97ea5e441e85fe2cf8621b4e0900 | [
"Apache-2.0"
] | null | null | null | 29.620253 | 126 | 0.667094 | 8,637 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-257
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.09.14 at 07:25:56 PM CEST
//
package org.proteored.miapeapi.xml.mzidentml.autogenerated;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for MeasureType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="MeasureType">
* <complexContent>
* <extension base="{http://psidev.info/psi/pi/mzIdentML/1.0}FuGE.Common.IdentifiableType">
* <sequence>
* <element ref="{http://psidev.info/psi/pi/mzIdentML/1.0}cvParam" maxOccurs="unbounded"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MeasureType", propOrder = {
"cvParam"
})
public class MeasureType
extends FuGECommonIdentifiableType
{
@XmlElement(required = true)
protected List<FuGECommonOntologyCvParamType> cvParam;
/**
* Gets the value of the cvParam property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cvParam property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCvParam().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FuGECommonOntologyCvParamType }
*
*
*/
public List<FuGECommonOntologyCvParamType> getCvParam() {
if (cvParam == null) {
cvParam = new ArrayList<FuGECommonOntologyCvParamType>();
}
return this.cvParam;
}
}
|
3e1469034873a471583cad2932e242335a9bbe2a | 1,108 | java | Java | jet_library/src/main/java/com/meiyou/jet/proxy/ProxyMethodHandler.java | gybin02/Jet | ec47536efaf5f61309260eba2cf4dbd89b285667 | [
"Apache-2.0"
] | 79 | 2017-06-13T00:40:32.000Z | 2021-07-04T12:27:45.000Z | jet_library/src/main/java/com/meiyou/jet/proxy/ProxyMethodHandler.java | gybin02/Jet | ec47536efaf5f61309260eba2cf4dbd89b285667 | [
"Apache-2.0"
] | null | null | null | jet_library/src/main/java/com/meiyou/jet/proxy/ProxyMethodHandler.java | gybin02/Jet | ec47536efaf5f61309260eba2cf4dbd89b285667 | [
"Apache-2.0"
] | 15 | 2017-06-13T01:51:08.000Z | 2020-12-24T07:53:53.000Z | 28.410256 | 109 | 0.673285 | 8,638 | package com.jet.jet.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Proxy 方法代理类
* @author zhengxiaobin
* @since 17/5/22
*/
public class ProxyMethodHandler implements InvocationHandler {
private static final String TAG = "JetProxy";
private final String targetClazzName;
public ProxyMethodHandler(String targetClazzName) {
this.targetClazzName = targetClazzName;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//异常类,异常方法,出错等会有Log, Throw 会被不捕获住
Class clazz = Class.forName(targetClazzName);
Object newInstance = clazz.newInstance();
String methodName = method.getName();
Method realMethod = clazz.getMethod(methodName, method.getParameterTypes());
// if (realMethod == null) {
// Log.e(TAG, String.format("can't find Method:%s in class : %s", methodName, targetClazzName));
// return null;
// }
realMethod.setAccessible(true);
return realMethod.invoke(newInstance, args);
}
}
|
3e14695c6fcb7a1d9bbcfcdf085f017142d99e2a | 910 | java | Java | app/src/main/java/at/specure/android/api/reqres/measurement_server/MeasurementServerRsp.java | SPECURE/ont-android-client | dcbc5d394c55c72f775db2f1d0ec53d535d20dc2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/at/specure/android/api/reqres/measurement_server/MeasurementServerRsp.java | SPECURE/ont-android-client | dcbc5d394c55c72f775db2f1d0ec53d535d20dc2 | [
"Apache-2.0"
] | 1 | 2018-01-12T16:15:06.000Z | 2018-01-12T16:15:06.000Z | app/src/main/java/at/specure/android/api/reqres/measurement_server/MeasurementServerRsp.java | SPECURE/ont-android-client | dcbc5d394c55c72f775db2f1d0ec53d535d20dc2 | [
"Apache-2.0"
] | 2 | 2017-12-20T12:43:39.000Z | 2017-12-26T08:17:28.000Z | 33.703704 | 81 | 0.60989 | 8,639 | /*******************************************************************************
* Copyright 2014-2017 Specure GmbH
*
* 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 at.specure.android.api.reqres.measurement_server;
/**
* Created by michal.cadrik on 7/27/2017.
*/
public class MeasurementServerRsp {
}
|
3e1469f5012c859112c9422dee2c84b85fe27ae7 | 1,080 | java | Java | src/main/java/com/example/gson/GsonJson2Java.java | riversun/java-json-gson-jackson-http | a8febaecf76cb738fc294165aaa1273aa6080f3f | [
"MIT"
] | null | null | null | src/main/java/com/example/gson/GsonJson2Java.java | riversun/java-json-gson-jackson-http | a8febaecf76cb738fc294165aaa1273aa6080f3f | [
"MIT"
] | null | null | null | src/main/java/com/example/gson/GsonJson2Java.java | riversun/java-json-gson-jackson-http | a8febaecf76cb738fc294165aaa1273aa6080f3f | [
"MIT"
] | null | null | null | 36 | 78 | 0.401852 | 8,640 | package com.example.gson;
import com.google.gson.Gson;
public class GsonJson2Java {
public static void main(String[] args) {
String json =
"{" +
" \"person\": {" +
" \"firstName\": \"John\"," +
" \"lastName\": \"Doe\"," +
" \"address\": \"NewYork\"," +
" \"pets\": [" +
" {\"type\": \"Dog\", \"name\": \"Jolly\"}," +
" {\"type\": \"Cat\", \"name\": \"Grizabella\"}," +
" {\"type\": \"Fish\", \"name\": \"Nimo\"}" +
" ]" +
" }" +
"}";
Gson gson = new Gson();
Model model = gson.fromJson(json, Model.class);
System.out.println("firstName:" + model.person.firstName);
System.out.println("lastName:" + model.person.lastName);
System.out.println("address:" + model.person.address);
System.out.println("1st pet:" + model.person.pets.get(0).name);
}
}
|
3e146a69c0fc2da3509dc5a06c747391a530b477 | 1,010 | java | Java | app/src/main/java/ceui/lisa/model/ListComment.java | Rimliya/Pixiv-Shaft-fork | 21678b96fd3cc32f45acb08d2591e9502a89db58 | [
"MIT"
] | 2,174 | 2019-06-19T13:11:37.000Z | 2022-03-31T18:09:05.000Z | app/src/main/java/ceui/lisa/model/ListComment.java | Rimliya/Pixiv-Shaft-fork | 21678b96fd3cc32f45acb08d2591e9502a89db58 | [
"MIT"
] | 349 | 2019-06-16T08:51:15.000Z | 2022-03-28T12:21:18.000Z | app/src/main/java/ceui/lisa/model/ListComment.java | Rimliya/Pixiv-Shaft-fork | 21678b96fd3cc32f45acb08d2591e9502a89db58 | [
"MIT"
] | 184 | 2019-06-22T01:22:53.000Z | 2022-03-25T11:10:52.000Z | 21.489362 | 64 | 0.676238 | 8,641 | package ceui.lisa.model;
import java.util.List;
import ceui.lisa.interfaces.ListShow;
import ceui.lisa.models.ReplyCommentBean;
public class ListComment implements ListShow<ReplyCommentBean> {
private List<ReplyCommentBean> comments;
private String next_url;
private int total_comments;
public List<ReplyCommentBean> getComments() {
return this.comments;
}
public void setComments(List<ReplyCommentBean> paramList) {
this.comments = paramList;
}
public String getNext_url() {
return this.next_url;
}
public void setNext_url(String paramString) {
this.next_url = paramString;
}
public int getTotal_comments() {
return this.total_comments;
}
public void setTotal_comments(int paramInt) {
this.total_comments = paramInt;
}
@Override
public List<ReplyCommentBean> getList() {
return comments;
}
@Override
public String getNextUrl() {
return next_url;
}
}
|
3e146a96d3251199796e7d60c399da73f4e23913 | 1,957 | java | Java | sdk/costmanagement/azure-resourcemanager-costmanagement/src/main/java/com/azure/resourcemanager/costmanagement/models/OperationDisplay.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/costmanagement/azure-resourcemanager-costmanagement/src/main/java/com/azure/resourcemanager/costmanagement/models/OperationDisplay.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/costmanagement/azure-resourcemanager-costmanagement/src/main/java/com/azure/resourcemanager/costmanagement/models/OperationDisplay.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 27.957143 | 98 | 0.676546 | 8,642 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.costmanagement.models;
import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The object that represents the operation. */
@Immutable
public final class OperationDisplay {
@JsonIgnore private final ClientLogger logger = new ClientLogger(OperationDisplay.class);
/*
* Service provider: Microsoft.CostManagement.
*/
@JsonProperty(value = "provider", access = JsonProperty.Access.WRITE_ONLY)
private String provider;
/*
* Resource on which the operation is performed: Dimensions, Query.
*/
@JsonProperty(value = "resource", access = JsonProperty.Access.WRITE_ONLY)
private String resource;
/*
* Operation type: Read, write, delete, etc.
*/
@JsonProperty(value = "operation", access = JsonProperty.Access.WRITE_ONLY)
private String operation;
/**
* Get the provider property: Service provider: Microsoft.CostManagement.
*
* @return the provider value.
*/
public String provider() {
return this.provider;
}
/**
* Get the resource property: Resource on which the operation is performed: Dimensions, Query.
*
* @return the resource value.
*/
public String resource() {
return this.resource;
}
/**
* Get the operation property: Operation type: Read, write, delete, etc.
*
* @return the operation value.
*/
public String operation() {
return this.operation;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
3e146aae8b6f5c484c815fd21e1f8ec3f21998b9 | 685 | java | Java | example-junit4/src/test/java/com/tngtech/archunit/exampletest/junit4/DependencyRulesTest.java | pdibenedetto/ArchUnit-Examples | fe7e56f399d364fe1d71fb39629fc2b58489b5ee | [
"Apache-2.0"
] | 359 | 2018-01-31T19:46:39.000Z | 2022-03-23T13:59:22.000Z | example-junit4/src/test/java/com/tngtech/archunit/exampletest/junit4/DependencyRulesTest.java | Coqni/ArchUnit-Examples | eff53b3a5e117033e7c8a78d963a21d7b929f707 | [
"Apache-2.0"
] | 7 | 2019-05-21T17:27:54.000Z | 2021-11-26T07:39:34.000Z | example-junit4/src/test/java/com/tngtech/archunit/exampletest/junit4/DependencyRulesTest.java | Coqni/ArchUnit-Examples | eff53b3a5e117033e7c8a78d963a21d7b929f707 | [
"Apache-2.0"
] | 73 | 2018-09-03T15:51:28.000Z | 2022-03-31T02:21:43.000Z | 36.052632 | 99 | 0.854015 | 8,643 | package com.tngtech.archunit.exampletest.junit4;
import com.tngtech.archunit.example.layers.ClassViolatingCodingRules;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.junit.ArchUnitRunner;
import com.tngtech.archunit.lang.ArchRule;
import org.junit.runner.RunWith;
import static com.tngtech.archunit.library.DependencyRules.NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES;
@RunWith(ArchUnitRunner.class)
@AnalyzeClasses(packagesOf = ClassViolatingCodingRules.class)
public class DependencyRulesTest {
@ArchTest
static final ArchRule no_accesses_to_upper_package = NO_CLASSES_SHOULD_DEPEND_UPPER_PACKAGES;
}
|
3e146ab16c68afa435060500f01ec9d6c8ee56a6 | 2,592 | java | Java | modules/module-passenger-utils/src/main/java/org/gov/uk/homeoffice/digital/permissions/passenger/utils/DateTimeUtils.java | UKHomeOffice/passenger | a304c6c601dd67999c4cc9e9bf4d9c760bc5110c | [
"MIT"
] | null | null | null | modules/module-passenger-utils/src/main/java/org/gov/uk/homeoffice/digital/permissions/passenger/utils/DateTimeUtils.java | UKHomeOffice/passenger | a304c6c601dd67999c4cc9e9bf4d9c760bc5110c | [
"MIT"
] | null | null | null | modules/module-passenger-utils/src/main/java/org/gov/uk/homeoffice/digital/permissions/passenger/utils/DateTimeUtils.java | UKHomeOffice/passenger | a304c6c601dd67999c4cc9e9bf4d9c760bc5110c | [
"MIT"
] | 1 | 2021-04-11T09:23:42.000Z | 2021-04-11T09:23:42.000Z | 38.117647 | 134 | 0.689043 | 8,644 | package org.gov.uk.homeoffice.digital.permissions.passenger.utils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import static java.lang.String.format;
public class DateTimeUtils {
private static final String DEFAULT_DATE_PATTERN = "dd MMM yyyy";
private static final String DEFAULT_DATE_TIME_PATTERN = "dd MMM yyyy HH:mm";
public static final String DISPLAY_DATE_TIME_PATTERN = "EEEE, d MMM yyyy";
public static String parse(final LocalDate date) {
return parse(date, DEFAULT_DATE_PATTERN);
}
public static String parse(final LocalDateTime dateTime) {
return parse(dateTime, DEFAULT_DATE_TIME_PATTERN);
}
public static String parse(final LocalDate date, final String pattern) {
return date.format(DateTimeFormatter.ofPattern(pattern));
}
public static String parse(final LocalDateTime dateTime, final String pattern) {
return dateTime.format(DateTimeFormatter.ofPattern(pattern));
}
public static String parse(final LocalDate date, final String pattern, boolean includeOrdinal) {
return (includeOrdinal && pattern.contains("'%s'"))
? format(date.format(DateTimeFormatter.ofPattern(pattern)), getOrdinalFor(date.get(ChronoField.DAY_OF_MONTH)))
: date.format(DateTimeFormatter.ofPattern(pattern));
}
public static String parse(final LocalDateTime dateTime, final String pattern, boolean includeOrdinal) {
return (includeOrdinal && pattern.contains("'%s'"))
? format(dateTime.format(DateTimeFormatter.ofPattern(pattern)), getOrdinalFor(dateTime.get(ChronoField.DAY_OF_MONTH)))
: dateTime.format(DateTimeFormatter.ofPattern(pattern));
}
private static String getOrdinalFor(int dayOfMonth) {
if (dayOfMonth < 1 || dayOfMonth > 31)
throw new IllegalArgumentException("Invalid day of month: " + dayOfMonth);
if (dayOfMonth >= 11 && dayOfMonth <= 13) {
return "th";
}
switch (dayOfMonth % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
public static String toDisplayDate(final LocalDate date) {
return date != null ? date.format(DateTimeFormatter.BASIC_ISO_DATE) : "";
}
public static LocalDate fromDisplayDate(final String displayDate){
return LocalDate.parse(displayDate, DateTimeFormatter.BASIC_ISO_DATE);
}
}
|
3e146b9a82b009780cabc8d44b10004219df838c | 16,666 | java | Java | subsys/metrics/reporter/src/main/java/org/commonjava/indy/metrics/zabbix/sender/IndyZabbixSender.java | ruhan1/indy | f48ab96ac6935f1a5562fc883993e4e0e1e23a97 | [
"Apache-2.0"
] | null | null | null | subsys/metrics/reporter/src/main/java/org/commonjava/indy/metrics/zabbix/sender/IndyZabbixSender.java | ruhan1/indy | f48ab96ac6935f1a5562fc883993e4e0e1e23a97 | [
"Apache-2.0"
] | null | null | null | subsys/metrics/reporter/src/main/java/org/commonjava/indy/metrics/zabbix/sender/IndyZabbixSender.java | ruhan1/indy | f48ab96ac6935f1a5562fc883993e4e0e1e23a97 | [
"Apache-2.0"
] | null | null | null | 27.684385 | 129 | 0.581663 | 8,645 | /**
* Copyright (C) 2011-2019 Red Hat, Inc. (https://github.com/Commonjava/indy)
*
* 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.commonjava.indy.metrics.zabbix.sender;
import org.commonjava.indy.IndyException;
import org.commonjava.indy.metrics.exception.IndyMetricsException;
import org.commonjava.indy.metrics.zabbix.api.IndyZabbixApi;
import org.commonjava.indy.metrics.zabbix.api.ZabbixApi;
import org.commonjava.indy.metrics.zabbix.cache.ZabbixCacheStorage;
import org.commonjava.indy.subsys.http.IndyHttpException;
import org.commonjava.indy.subsys.http.IndyHttpProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by xiabai on 4/1/17.
*/
public class IndyZabbixSender
{
private static final Logger logger = LoggerFactory.getLogger( IndyZabbixSender.class );
private ZabbixSender sender;
private boolean bCreateNotExistHostGroup = true;
private boolean bCreateNotExistHost = true;
private boolean bCreateNotExistItem = true;
private boolean bCreateNotExistZabbixApi = true;
private ZabbixApi zabbixApi;
private String zabbixHostUrl;
private String hostGroup = "NOS";//// default host group
private String group = "NOS";
private long clock = 0l;
private String hostName;
private String ip;
private String zabbixUserName;
private String zabbixUserPwd;
private ZabbixCacheStorage zabbixCacheStorage;
private IndyHttpProvider indyHttpProvider;
private static final String regEx = "^-?[0-9]+$";
private static final Pattern pat = Pattern.compile( regEx );
public static Builder create()
{
return new Builder();
}
public static class Builder
{
boolean bCreateNotExistHostGroup = true;
boolean bCreateNotExistHost = true;
boolean bCreateNotExistItem = true;
boolean bCreateNotExistZabbixSender = true;
ZabbixApi zabbixApi;
String zabbixHostUrl;
String hostGroup = "NOS";//// default host group
String group = "NOS";
long clock = 0l;
String hostName;
String ip;
String zabbixUserName;
String zabbixUserPwd;
String zabbixHost;
int zabbixPort;
ZabbixCacheStorage zabbixCacheStorage;
IndyHttpProvider indyHttpProvider;
public Builder metricsZabbixCache( ZabbixCacheStorage zabbixCacheStorage )
{
this.zabbixCacheStorage = zabbixCacheStorage;
return this;
}
public Builder indyHttpProvider( IndyHttpProvider indyHttpProvider )
{
this.indyHttpProvider = indyHttpProvider;
return this;
}
public Builder zabbixHost( String zabbixHost )
{
this.zabbixHost = zabbixHost;
return this;
}
public Builder hostName( String hostName )
{
this.hostName = hostName;
return this;
}
public Builder zabbixPort( int zabbixPort )
{
this.zabbixPort = zabbixPort;
return this;
}
public Builder bCreateNotExistHostGroup( boolean bCreateNotExistHostGroup )
{
this.bCreateNotExistHostGroup = bCreateNotExistHostGroup;
return this;
}
public Builder bCreateNotExistHost( boolean bCreateNotExistHost )
{
this.bCreateNotExistHost = bCreateNotExistHost;
return this;
}
public Builder bCreateNotExistItem( boolean bCreateNotExistItem )
{
this.bCreateNotExistItem = bCreateNotExistItem;
return this;
}
public Builder bCreateNotExistZabbixSender( boolean bCreateNotExistZabbixSender )
{
this.bCreateNotExistZabbixSender = bCreateNotExistZabbixSender;
return this;
}
public Builder zabbixApi( ZabbixApi zabbixApi )
{
this.zabbixApi = zabbixApi;
return this;
}
public Builder zabbixHostUrl( String zabbixHostUrl )
{
this.zabbixHostUrl = zabbixHostUrl;
return this;
}
public Builder hostGroup( String hostGroup )
{
this.hostGroup = hostGroup;
return this;
}
public Builder group( String group )
{
this.group = group;
return this;
}
public Builder ip( String ip )
{
this.ip = ip;
return this;
}
public Builder zabbixUserName( String zabbixUserName )
{
this.zabbixUserName = zabbixUserName;
return this;
}
public Builder clock( long clock )
{
this.clock = clock;
return this;
}
public Builder zabbixUserPwd( String zabbixUserPwd )
{
this.zabbixUserPwd = zabbixUserPwd;
return this;
}
public IndyZabbixSender build()
{
return new IndyZabbixSender( this.bCreateNotExistHostGroup, this.bCreateNotExistHost,
this.bCreateNotExistItem, this.bCreateNotExistZabbixSender, this.zabbixApi,
this.zabbixHostUrl, this.hostGroup, this.group, this.clock, this.hostName,
this.ip, this.zabbixUserName, this.zabbixUserPwd, this.zabbixHost,
this.zabbixPort, this.indyHttpProvider, this.zabbixCacheStorage );
}
}
public IndyZabbixSender( boolean bCreateNotExistHostGroup, boolean bCreateNotExistHost, boolean bCreateNotExistItem,
boolean bCreateNotExistZabbixApi, ZabbixApi zabbixApi, String zabbixHostUrl,
String hostGroup, String group, long clock, String hostName, String ip,
String zabbixUserName, String zabbixUserPwd, String zabbixHost, int zabbixPort,
IndyHttpProvider indyHttpProvider, ZabbixCacheStorage zabbixCacheStorage )
{
this.bCreateNotExistHostGroup = bCreateNotExistHostGroup;
this.bCreateNotExistHost = bCreateNotExistHost;
this.bCreateNotExistItem = bCreateNotExistItem;
this.bCreateNotExistZabbixApi = bCreateNotExistZabbixApi;
this.zabbixApi = zabbixApi;
this.zabbixHostUrl = zabbixHostUrl;
this.hostGroup = hostGroup;
this.group = group;
this.clock = clock;
this.hostName = hostName;
this.ip = ip;
this.zabbixUserName = zabbixUserName;
this.zabbixUserPwd = zabbixUserPwd;
this.indyHttpProvider = indyHttpProvider;
this.zabbixCacheStorage = zabbixCacheStorage;
this.sender = new ZabbixSender( zabbixHost, zabbixPort );
}
String checkHostGroup( String hostGroup ) throws IOException, IndyHttpException, IndyMetricsException
{
if ( zabbixCacheStorage.getHostGroup( hostGroup ) == null )
{
try
{
this.zabbixApiInit();
String groupid = zabbixApi.getHostgroup( hostGroup );
if ( groupid == null )
{
groupid = zabbixApi.hostgroupCreate( hostGroup );
zabbixCacheStorage.putHostGroup( hostGroup, groupid );
}
zabbixCacheStorage.putHostGroup( hostGroup, groupid );
return groupid;
}
finally
{
this.destroy();
}
}
return null;
}
String checkHost( String host, String ip ) throws IOException, IndyHttpException, IndyMetricsException
{
try
{
if ( zabbixCacheStorage.getHost( host ) == null )
{
this.zabbixApiInit();
String hostid = zabbixApi.getHost( host );
if ( hostid != null )
{
zabbixCacheStorage.putHost( host, hostid );
}
else
{// host not exists, create it.
hostid = zabbixApi.hostCreate( host, zabbixCacheStorage.getHostGroup( hostGroup ), ip );
zabbixCacheStorage.putHost( host, hostid );
}
return hostid;
}
}
finally
{
this.destroy();
}
return null;
}
private String itemCacheKey( String host, String item )
{
return host + ":" + item;
}
String checkItem( String host, String item, int valueType ) throws IOException, IndyHttpException, IndyMetricsException
{
try
{
if ( zabbixCacheStorage.getItem( itemCacheKey( host, item ) ) == null )
{
this.zabbixApiInit();
String itemid = zabbixApi.getItem( host, item, zabbixCacheStorage.getHost( host ) );
if ( itemid == null )
{
itemid = zabbixApi.createItem( host, item, zabbixCacheStorage.getHost( host ), valueType );
zabbixCacheStorage.putItem( itemCacheKey( host, item ), itemid );
}
else
{
// put into metricsZabbixCache
zabbixCacheStorage.putItem( itemCacheKey( host, item ), itemid );
}
return itemid;
}
}
finally
{
this.destroy();
}
return null;
}
public SenderResult send( DataObject dataObject ) throws IOException, IndyException
{
return this.send( dataObject, System.currentTimeMillis() / 1000L );
}
public SenderResult send( DataObject dataObject, long clock ) throws IOException, IndyException
{
return this.send( Collections.singletonList( dataObject ), clock );
}
public SenderResult send( List<DataObject> dataObjectList ) throws IOException, IndyException
{
return this.send( dataObjectList, System.currentTimeMillis() / 1000L );
}
/**
*
* @param dataObjectList
* @param clock
* TimeUnit is SECONDS.
* @return
* @throws IOException
*/
public SenderResult send( List<DataObject> dataObjectList, long clock )
throws IOException, IndyHttpException, IndyMetricsException
{
if ( bCreateNotExistHostGroup )
{
try
{
checkHostGroup( hostGroup );
}
catch ( IndyHttpException e )
{
logger.error( "Check HostGroup of Zabbix is error:" + e.getMessage() );
throw e;
}
}
if ( bCreateNotExistHost )
{
try
{
checkHost( hostName, ip );
}
catch ( IndyHttpException e )
{
logger.error( "Check Host of Zabbix is error:" + e.getMessage() );
throw e;
}
}
if ( bCreateNotExistItem )
{
for ( DataObject object : dataObjectList )
{
String key = object.getKey();
int vauleType = 0;
Matcher mat = pat.matcher( object.getValue() );
if ( !mat.find() )
{
vauleType = 4;
}
try
{
checkItem( hostName, key, vauleType );
}
catch ( IndyHttpException e )
{
logger.error( "Check Item of Zabbix is error:" + e.getMessage() );
throw e;
}
}
}
try
{
SenderResult senderResult = sender.send( dataObjectList, clock );
if ( !senderResult.success() )
{
logger.error( "send data to zabbix server error! senderResult:" + senderResult );
}
return senderResult;
}
catch ( IOException e )
{
logger.error( "send data to zabbix server error!", e );
throw e;
}
}
public void destroy()
{
if ( bCreateNotExistZabbixApi )
{
return;
}
if ( zabbixApi != null )
zabbixApi.destroy();
}
private void zabbixApiInit() throws IndyMetricsException, IOException, IndyHttpException
{
if ( !bCreateNotExistZabbixApi )
{
return;
}
if ( this.zabbixHostUrl == null || "".equals( this.zabbixHostUrl ) )
{
throw new IndyMetricsException( "can not find Zabbix's Host" );
}
zabbixApi = new IndyZabbixApi( this.zabbixHostUrl, indyHttpProvider.createClient( new URL( zabbixHostUrl ).getHost() ) );
zabbixApi.init();
if ( this.zabbixUserName == null || "".equals( this.zabbixUserName ) || this.zabbixUserPwd == null || "".equals(
this.zabbixUserPwd ) )
{
throw new IndyMetricsException( "can not find Zabbix's username or password" );
}
boolean login = zabbixApi.login( this.zabbixUserName, this.zabbixUserPwd );
logger.info( "User:" + this.zabbixUserName + " login is " + login );
}
public ZabbixApi getZabbixApi()
{
return zabbixApi;
}
public void setZabbixApi( ZabbixApi zabbixApi )
{
this.zabbixApi = zabbixApi;
}
public boolean isbCreateNotExistHost()
{
return bCreateNotExistHost;
}
public void setbCreateNotExistHost( boolean bCreateNotExistHost )
{
this.bCreateNotExistHost = bCreateNotExistHost;
}
public String getHostGroup()
{
return hostGroup;
}
public void setHostGroup( String hostGroup )
{
this.hostGroup = hostGroup;
}
public boolean isbCreateNotExistItem()
{
return bCreateNotExistItem;
}
public void setbCreateNotExistItem( boolean bCreateNotExistItem )
{
this.bCreateNotExistItem = bCreateNotExistItem;
}
public String getGroup()
{
return group;
}
public void setGroup( String group )
{
this.group = group;
}
public long getClock()
{
return clock;
}
public void setClock( long clock )
{
this.clock = clock;
}
public String getHostName()
{
return hostName;
}
public void setHostName( String hostName )
{
this.hostName = hostName;
}
public String getIp()
{
return ip;
}
public void setIp( String ip )
{
this.ip = ip;
}
public boolean isbCreateNotExistHostGroup()
{
return bCreateNotExistHostGroup;
}
public void setbCreateNotExistHostGroup( boolean bCreateNotExistHostGroup )
{
this.bCreateNotExistHostGroup = bCreateNotExistHostGroup;
}
public String getZabbixHostUrl()
{
return zabbixHostUrl;
}
public void setZabbixHostUrl( String zabbixHostUrl )
{
this.zabbixHostUrl = zabbixHostUrl;
}
public String getZabbixUserName()
{
return zabbixUserName;
}
public void setZabbixUserName( String zabbixUserName )
{
this.zabbixUserName = zabbixUserName;
}
public String getZabbixUserPwd()
{
return zabbixUserPwd;
}
public void setZabbixUserPwd( String zabbixUserPwd )
{
this.zabbixUserPwd = zabbixUserPwd;
}
public boolean isbCreateNotExistZabbixApi()
{
return bCreateNotExistZabbixApi;
}
public void setbCreateNotExistZabbixApi( boolean bCreateNotExistZabbixApi )
{
this.bCreateNotExistZabbixApi = bCreateNotExistZabbixApi;
}
}
|
3e146ba102d3c7901160dd1711ffce8c58326dba | 913 | java | Java | src/msf/fc/rest/ec/node/nodes/operation/data/entity/NodeDeleteUpdateNodeEcEntity.java | multi-service-fabric/fabric-controller | 2b9788ff5e3a95ce1b82c4a80464592effe45e82 | [
"Apache-2.0"
] | 2 | 2018-03-19T03:45:16.000Z | 2018-09-10T01:45:42.000Z | src/msf/fc/rest/ec/node/nodes/operation/data/entity/NodeDeleteUpdateNodeEcEntity.java | multi-service-fabric/fabric-controller | 2b9788ff5e3a95ce1b82c4a80464592effe45e82 | [
"Apache-2.0"
] | null | null | null | src/msf/fc/rest/ec/node/nodes/operation/data/entity/NodeDeleteUpdateNodeEcEntity.java | multi-service-fabric/fabric-controller | 2b9788ff5e3a95ce1b82c4a80464592effe45e82 | [
"Apache-2.0"
] | 1 | 2020-04-02T01:18:38.000Z | 2020-04-02T01:18:38.000Z | 18.632653 | 56 | 0.727273 | 8,646 |
package msf.fc.rest.ec.node.nodes.operation.data.entity;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.google.gson.annotations.SerializedName;
public class NodeDeleteUpdateNodeEcEntity {
@SerializedName("node_id")
private String nodeId;
@SerializedName("node_type")
private String nodeType;
@SerializedName("cluster_area")
private String clusterArea;
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getNodeType() {
return nodeType;
}
public void setNodeType(String nodeType) {
this.nodeType = nodeType;
}
public String getClusterArea() {
return clusterArea;
}
public void setClusterArea(String clusterArea) {
this.clusterArea = clusterArea;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
3e146be3c2456a1ea3f3de04ffe76098de88a3b4 | 4,917 | java | Java | bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java | msyoon222/so-tata | 564715d54e0ea9752a01488eed142d4a4440cd3a | [
"Apache-2.0"
] | null | null | null | bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java | msyoon222/so-tata | 564715d54e0ea9752a01488eed142d4a4440cd3a | [
"Apache-2.0"
] | null | null | null | bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java | msyoon222/so-tata | 564715d54e0ea9752a01488eed142d4a4440cd3a | [
"Apache-2.0"
] | null | null | null | 45.527778 | 107 | 0.718731 | 8,647 | /*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.pnf.delegate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.CORRELATION_ID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID;
import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.TIMEOUT_FOR_NOTIFICATION;
import java.util.UUID;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake;
import org.junit.Before;
import org.junit.Test;
public class PnfCheckInputsTest {
private static final String DEFAULT_TIMEOUT = "P1D";
private static final String VALID_UUID = UUID.nameUUIDFromBytes("testUuid".getBytes()).toString();
private static final String RESERVED_UUID = new UUID(0, 0).toString();
private DelegateExecution delegateExecution;
@Before
public void setUp() {
delegateExecution = new DelegateExecutionFake();
delegateExecution.setVariable("testProcessKey", "testProcessKeyValue");
}
@Test
public void shouldThrowException_whenCorrelationIdNotSet() {
PnfCheckInputs testedObject = prepareExecutionForCorrelationId(null);
assertThatThrownBy(() -> testedObject.execute(delegateExecution)).isInstanceOf(BpmnError.class);
}
@Test
public void shouldThrowException_whenTimeoutIsEmptyStringAndDefaultIsNotDefined() {
PnfCheckInputs testedObject = prepareExecutionForTimeout(null, "");
assertThatThrownBy(() -> testedObject.execute(delegateExecution)).isInstanceOf(BpmnError.class);
}
@Test
public void shouldSetDefaultTimeout_whenTimeoutIsNotSet() {
PnfCheckInputs testedObject = prepareExecutionForTimeout(DEFAULT_TIMEOUT, null);
testedObject.execute(delegateExecution);
assertThat(delegateExecution.getVariable(TIMEOUT_FOR_NOTIFICATION)).isEqualTo(DEFAULT_TIMEOUT);
}
@Test
public void shouldThrowException_whenPnfUuidIsNotSet() {
PnfCheckInputs testedObject = prepareExecutionForUuid(null);
assertThatThrownBy(() -> testedObject.execute(delegateExecution)).isInstanceOf(BpmnError.class);
}
@Test
public void shouldThrowException_whenPnfUuidIsEmptyString() {
PnfCheckInputs testedObject = prepareExecutionForUuid("");
assertThatThrownBy(() -> testedObject.execute(delegateExecution)).isInstanceOf(BpmnError.class);
}
@Test
public void shouldThrowException_whenPnfUuidIsReservedUuid() {
PnfCheckInputs testedObject = prepareExecutionForUuid(RESERVED_UUID);
assertThatThrownBy(() -> testedObject.execute(delegateExecution)).isInstanceOf(BpmnError.class);
}
private PnfCheckInputs prepareExecutionForCorrelationId(String correlationId) {
PnfCheckInputs testedObject = new PnfCheckInputs(DEFAULT_TIMEOUT);
delegateExecution.setVariable(CORRELATION_ID, correlationId);
delegateExecution.setVariable(PNF_UUID, VALID_UUID);
return testedObject;
}
private PnfCheckInputs prepareExecutionForTimeout(String defaultTimeout, String timeout) {
PnfCheckInputs testedObject = new PnfCheckInputs(defaultTimeout);
delegateExecution.setVariable(CORRELATION_ID, "testCorrelationId");
delegateExecution.setVariable(PNF_UUID, VALID_UUID);
delegateExecution.setVariable(TIMEOUT_FOR_NOTIFICATION, timeout);
return testedObject;
}
private PnfCheckInputs prepareExecutionForUuid(String uuid) {
PnfCheckInputs testedObject = new PnfCheckInputs(DEFAULT_TIMEOUT);
delegateExecution.setVariable(CORRELATION_ID, "testCorrelationId");
delegateExecution.setVariable(PNF_UUID, uuid);
return testedObject;
}
} |
3e146ce1b496c6d6f475afc1ee7ff880afdc63de | 2,384 | java | Java | pinot-core/src/main/java/org/apache/pinot/core/operator/combine/AggregationOnlyCombineOperator.java | nizarhejazi/pinot | d616a097e5b28443b42a9e84113d3fced254444d | [
"Apache-2.0"
] | 2,144 | 2015-06-10T16:02:11.000Z | 2018-11-08T07:59:13.000Z | pinot-core/src/main/java/org/apache/pinot/core/operator/combine/AggregationOnlyCombineOperator.java | nizarhejazi/pinot | d616a097e5b28443b42a9e84113d3fced254444d | [
"Apache-2.0"
] | 1,894 | 2015-06-11T05:17:48.000Z | 2018-11-09T19:22:27.000Z | pinot-core/src/main/java/org/apache/pinot/core/operator/combine/AggregationOnlyCombineOperator.java | nizarhejazi/pinot | d616a097e5b28443b42a9e84113d3fced254444d | [
"Apache-2.0"
] | 418 | 2015-06-10T15:53:06.000Z | 2018-11-09T00:05:06.000Z | 40.40678 | 114 | 0.773909 | 8,648 | /**
* 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.pinot.core.operator.combine;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.apache.pinot.core.common.Operator;
import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
import org.apache.pinot.core.query.aggregation.function.AggregationFunction;
import org.apache.pinot.core.query.request.context.QueryContext;
/**
* Combine operator for aggregation only queries.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class AggregationOnlyCombineOperator extends BaseCombineOperator {
private static final String EXPLAIN_NAME = "COMBINE_AGGREGATE";
public AggregationOnlyCombineOperator(List<Operator> operators, QueryContext queryContext,
ExecutorService executorService) {
super(operators, queryContext, executorService);
}
@Override
public String toExplainString() {
return EXPLAIN_NAME;
}
@Override
protected void mergeResultsBlocks(IntermediateResultsBlock mergedBlock, IntermediateResultsBlock blockToMerge) {
AggregationFunction[] aggregationFunctions = mergedBlock.getAggregationFunctions();
List<Object> mergedResults = mergedBlock.getAggregationResult();
List<Object> resultsToMerge = blockToMerge.getAggregationResult();
assert aggregationFunctions != null && mergedResults != null && resultsToMerge != null;
int numAggregationFunctions = aggregationFunctions.length;
for (int i = 0; i < numAggregationFunctions; i++) {
mergedResults.set(i, aggregationFunctions[i].merge(mergedResults.get(i), resultsToMerge.get(i)));
}
}
}
|
3e146ce58613e8a8d7cf13bf62bf67f0dfeba9b9 | 3,634 | java | Java | gidl-generator/src/test/java/eu/chorevolution/transformations/generativeapproach/gidlgenerator/GIDLGeneratorTest.java | chorevolution/transformations | 287abfe2f7733fc3e7df050c0f73a3ccf2d40caa | [
"Apache-2.0"
] | null | null | null | gidl-generator/src/test/java/eu/chorevolution/transformations/generativeapproach/gidlgenerator/GIDLGeneratorTest.java | chorevolution/transformations | 287abfe2f7733fc3e7df050c0f73a3ccf2d40caa | [
"Apache-2.0"
] | null | null | null | gidl-generator/src/test/java/eu/chorevolution/transformations/generativeapproach/gidlgenerator/GIDLGeneratorTest.java | chorevolution/transformations | 287abfe2f7733fc3e7df050c0f73a3ccf2d40caa | [
"Apache-2.0"
] | null | null | null | 31.877193 | 108 | 0.757017 | 8,649 | /*
* Copyright 2015 The CHOReVOLUTION 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 eu.chorevolution.transformations.generativeapproach.gidlgenerator;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GIDLGeneratorTest {
private static final String TEST_RESOURCES = "." + File.separatorChar + "src" + File.separatorChar + "test"
+ File.separatorChar + "resources" + File.separatorChar;
private static final String WSDL_FILE_EXTENSION = ".wsdl";
private static final String GIDL_FILE_EXTENSION = ".gidl";
private static final String INPUT_TEST_RESOURCES_FOLDER_NAME = "input";
private static final String OUTPUT_TEST_RESOURCES_FOLDER_NAME = "output";
private static Logger logger = LoggerFactory.getLogger(GIDLGeneratorTest.class);
@Rule
public TestName currentTestName = new TestName();
@Before
public void setUp() {
}
@Test
public void test_01() {
Assert.assertTrue(runGenerator(currentTestName.getMethodName(),"STApp" ));
}
@Test
public void test_02() {
Assert.assertTrue(runGenerator(currentTestName.getMethodName(), "dts-accidents"));
}
@Test
public void test_03() {
Assert.assertTrue(runGenerator(currentTestName.getMethodName(), "journeyplanner"));
}
@Test
public void test_04() {
Assert.assertTrue(runGenerator(currentTestName.getMethodName(), "bridge"));
}
@Test
public void test_05() {
Assert.assertTrue(runGenerator(currentTestName.getMethodName(), "congestion"));
}
@Test
public void test_06() {
Assert.assertTrue(runGenerator(currentTestName.getMethodName(), "news"));
}
@Test
public void test_07() {
Assert.assertTrue(runGenerator(currentTestName.getMethodName(), "DTS-HERE"));
}
private boolean runGenerator(String testName, String fileName) {
boolean genratedGIDLModel = true;
FileDeleteStrategy.FORCE.deleteQuietly(
new File(TEST_RESOURCES + testName + File.separatorChar + OUTPUT_TEST_RESOURCES_FOLDER_NAME));
File WSDLFile = new File(TEST_RESOURCES + testName + File.separatorChar + INPUT_TEST_RESOURCES_FOLDER_NAME
+ File.separatorChar + fileName + WSDL_FILE_EXTENSION);
try {
GIDLGeneratorRequest gidlGeneatorRequest = new GIDLGeneratorRequest(
FileUtils.readFileToByteArray(WSDLFile), fileName);
FileUtils.writeByteArrayToFile(
new File(TEST_RESOURCES + testName + File.separatorChar + OUTPUT_TEST_RESOURCES_FOLDER_NAME
+ File.separatorChar
+ WSDLFile.getName().replace(WSDL_FILE_EXTENSION, GIDL_FILE_EXTENSION)),
new GIDLGenerator().generate(gidlGeneatorRequest).getGidlContent());
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
logger.error(testName + " > " + errors.toString());
genratedGIDLModel = false;
}
return genratedGIDLModel;
}
}
|
3e146e0b31da38807feefea33fe12c076d3b5edd | 1,121 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/LinearTeleOP.java | DroidRageFTC/69901FTCFreightFrenzy | 05650a2a90a88b22bddb884aaac1673000f90a54 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/LinearTeleOP.java | DroidRageFTC/69901FTCFreightFrenzy | 05650a2a90a88b22bddb884aaac1673000f90a54 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/LinearTeleOP.java | DroidRageFTC/69901FTCFreightFrenzy | 05650a2a90a88b22bddb884aaac1673000f90a54 | [
"MIT"
] | null | null | null | 35.03125 | 73 | 0.743087 | 8,650 | package org.firstinspires.ftc.teamcode;
import com.acmerobotics.dashboard.config.Config;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
@Config
@TeleOp(name="arm test")
public class LinearTeleOP extends LinearOpMode {
public DcMotorEx armMotor = null;
public static String motorName = "armMotor";
@Override
public void runOpMode() throws InterruptedException {
armMotor = hardwareMap.get(DcMotorEx.class,motorName);
armMotor.setDirection(DcMotorSimple.Direction.FORWARD);
armMotor.setZeroPowerBehavior(DcMotorEx.ZeroPowerBehavior.BRAKE);
armMotor.setMode(DcMotorEx.RunMode.RUN_USING_ENCODER);
armMotor.setMode(DcMotorEx.RunMode.STOP_AND_RESET_ENCODER);
// Arm Encoders
armMotor.setTargetPosition(0);
armMotor.setMode(DcMotorEx.RunMode.RUN_TO_POSITION);
armMotor.setPower(0.3);
waitForStart();
while (!isStopRequested()) {
}
}
}
|
3e146e6fb9fe3cc39933128e73f5e7b31bd22320 | 6,114 | java | Java | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/classloader/share/CorrectClasses/testCorrectClass.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/classloader/share/CorrectClasses/testCorrectClass.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | null | null | null | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/classloader/share/CorrectClasses/testCorrectClass.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | 36.831325 | 82 | 0.534184 | 8,651 | /*
* 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.harmony.test.stress.classloader.share.CorrectClasses;
import junit.framework.TestCase;
import org.apache.harmony.test.stress.classloader.share.ClassLoaderTestError;
import org.apache.harmony.test.share.stress.ReliabilityRunner;
import java.util.Random;
import java.io.File;
public class testCorrectClass extends TestCase {
public testCorrectClass() {
super();
random = new Random();
}
private Random random;
public static final int LOOPCNT = 10000;
private static final char[] SEPARATOR = { File.separatorChar };
private static final String TESTNN = "testCorrectClass_";
private static final String TESTNN0 = "testCorrectClass_0";
public static boolean logIn = true;
public int test(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
System.setProperty("org.apache.harmony.test."
+ "stress.classloader.share."
+ "CorrectClasses.testCorrectClass.arg" + i, args[i]);
}
}
test();
return ReliabilityRunner.RESULT_PASS;
}
public void test() {
final int ARGS_COUNT = 4;
String[] preTestArgs = new String[ARGS_COUNT];
int testArgsCount;
for (testArgsCount = 0; testArgsCount < ARGS_COUNT; testArgsCount++) {
preTestArgs[testArgsCount] = System
.getProperty("org.apache.harmony.test."
+ "stress.classloader.share."
+ "CorrectClasses.testCorrectClass.arg"
+ testArgsCount);
if (preTestArgs[testArgsCount] == null) {
break;
}
}
String[] testArgs = new String[testArgsCount];
for (int k = 0; k < testArgsCount; k++) {
testArgs[k] = preTestArgs[k];
}
// testArgs[0] - mode
// testArgs[1] - number of iterations
// testArgs[2] - number of used classes
// testArgs[3] - classes location
int mode = testArgs.length <= 0 ? 1 : Integer.valueOf(testArgs[0])
.intValue();
int cntLoop = testArgs.length <= 1 ? LOOPCNT : Integer.valueOf(
testArgs[1]).intValue();
int cntClss = testArgs.length <= 2 ? 0 : Integer.valueOf(testArgs[2])
.intValue();
if (mode != 1) {
mode = cntClss;
}
String path = testArgs.length <= 3 ? null : testArgs[3];
if (path == null) {
ReliabilityRunner.debug("Class files location is not defined");
ReliabilityRunner.mainTest.addError(this, new ClassLoaderTestError());
}
String sep = new String(SEPARATOR);
String pkgN = this.getClass().getPackage().getName();
pkgN = pkgN.replace('.', SEPARATOR[0]);
pkgN = path.concat(sep).concat(pkgN).concat(sep);
String clName = TESTNN0;
if (logIn) {
ReliabilityRunner.debug("Try to load a lot of correct classes ");
ReliabilityRunner.debug("Number of used classes: " + cntClss);
ReliabilityRunner.debug("Number of iterations: " + cntLoop);
}
Class[] arrCls;
// Object[] arrObj;
newClassLoader[] cLoad;
for (int i = 0; i < cntLoop; i++) {
arrCls = new Class[cntClss];
cLoad = new newClassLoader[mode];
int nn = -1;
try {
if (mode == 1) {
cLoad[0] = new newClassLoader();
cLoad[0].setPath(pkgN);
}
for (int j = 0; j < cntClss; j++) {
nn = (mode == 1 ? 0 : j);
if (mode != 1) {
cLoad[nn] = new newClassLoader();
cLoad[nn].setPath(pkgN);
}
int randomInt = random.nextInt();
if (randomInt < 0) {
randomInt = 0 - randomInt;
}
String name = TESTNN.concat(Integer.toString(randomInt));
arrCls[j] = cLoad[nn].loadClass(clName, name);
if (arrCls[j] == null) {
ReliabilityRunner.debug("Null class. Step: " + j
+ " iteration:" + i);
ReliabilityRunner.mainTest.addError(this,
new ClassLoaderTestError());
}
int ll = arrCls[j].getDeclaredFields().length;
if (ll != 1) {
ReliabilityRunner.debug("Incorrect fields number " + ll
+ " class " + arrCls[j] + " Step: " + j
+ " iteration:" + i);
ReliabilityRunner.mainTest.addError(this,
new ClassLoaderTestError());
}
}
} catch (OutOfMemoryError e) {
} catch (Throwable e) {
ReliabilityRunner.debug(e.toString());
ReliabilityRunner.mainTest.addError(this, e);
}
arrCls = null;
cLoad = null;
}
}
}
|
3e146e79a64cf3e2b7e0cc5178f39adc0a22a83c | 2,623 | java | Java | test/smoke/testApps/SimpleCalculator/src/smokeTest/java/com/microsoft/applicationinsights/smoketest/MyTestTest.java | lukeza/ApplicationInsights-Java | ae6c8959d9c5b3854305ae8032bedf25e2c32a47 | [
"MIT"
] | 1 | 2021-07-07T06:30:29.000Z | 2021-07-07T06:30:29.000Z | test/smoke/testApps/SimpleCalculator/src/smokeTest/java/com/microsoft/applicationinsights/smoketest/MyTestTest.java | lukeza/ApplicationInsights-Java | ae6c8959d9c5b3854305ae8032bedf25e2c32a47 | [
"MIT"
] | null | null | null | test/smoke/testApps/SimpleCalculator/src/smokeTest/java/com/microsoft/applicationinsights/smoketest/MyTestTest.java | lukeza/ApplicationInsights-Java | ae6c8959d9c5b3854305ae8032bedf25e2c32a47 | [
"MIT"
] | null | null | null | 40.353846 | 135 | 0.746092 | 8,652 | package com.microsoft.applicationinsights.smoketest;
import java.util.concurrent.TimeUnit;
import java.util.List;
import com.microsoft.applicationinsights.internal.schemav2.Data;
import com.microsoft.applicationinsights.internal.schemav2.DataPoint;
import com.microsoft.applicationinsights.internal.schemav2.DataPointType;
import com.microsoft.applicationinsights.internal.schemav2.Envelope;
import com.microsoft.applicationinsights.internal.schemav2.MetricData;
import org.junit.*;
import static org.junit.Assert.*;
@UseAgent
public class MyTestTest extends AiSmokeTest {
@Test
public void doCalcSendsRequestDataAndMetricData() throws Exception {
System.out.println("Wait for app to finish deploying...");
String appContext = warFileName.replace(".war", "");
String baseUrl = "http://localhost:" + appServerPort + "/" + appContext;
waitForUrl(baseUrl, 60, TimeUnit.SECONDS, appContext);
System.out.println("Test app health check complete.");
String url = baseUrl+"/doCalc?leftOperand=1&rightOperand=2&operator=plus";
String content = HttpHelper.get(url);
assertNotNull(content);
assertTrue(content.length() > 0);
System.out.println("Waiting 10s for telemetry...");
TimeUnit.SECONDS.sleep(10);
System.out.println("Finished waiting for telemetry. Starting validation...");
assertTrue("mocked ingestion has no data", mockedIngestion.hasData());
assertTrue("mocked ingestion has 0 items", mockedIngestion.getItemCount() > 0);
assertEquals(2, mockedIngestion.getCountForType("RequestData"));
assertEquals(1, mockedIngestion.getCountForType("MetricData"));
int totalItems = mockedIngestion.getItemCount();
int expectedItems = 3;
assertEquals(String.format("There were %d extra telemetry items received.", expectedItems - totalItems), expectedItems, totalItems);
// TODO get metric data envelope and verify value
Envelope mEnvelope = mockedIngestion.getItemsByType("MetricData").get(0);
Data<MetricData> dHolder = (Data<MetricData>) mEnvelope.getData();
MetricData d = dHolder.getBaseData();
List<DataPoint> metrics = d.getMetrics();
assertEquals(1, metrics.size());
DataPoint dp = metrics.get(0);
final double expectedValue = 111222333.0;
final double epsilon = Math.ulp(expectedValue);
assertEquals(DataPointType.Measurement, dp.getKind());
assertEquals(expectedValue, dp.getValue(), epsilon);
assertEquals("TimeToRespond", dp.getName());
assertEquals(Integer.valueOf(1), dp.getCount());
assertNull(dp.getMin());
assertNull(dp.getMax());
assertNull(dp.getStdDev());
}
} |
3e146fd3767a043db5c8e1cd0d2c529a33c7cb23 | 2,207 | java | Java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/v2/MultipartUploadContext.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/v2/MultipartUploadContext.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/v2/MultipartUploadContext.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 31.084507 | 93 | 0.703217 | 8,653 | /*
* Copyright 2011-2021 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.s3.internal.crypto.v2;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Contextual information for an in-flight multipart upload.
*/
public abstract class MultipartUploadContext {
private final String bucketName;
private final String key;
private boolean hasFinalPartBeenSeen;
/** the materialDescription is an optional attribute that is only non-null
* when the material description is set on a per request basis
*/
private Map<String, String> materialsDescription;
protected MultipartUploadContext(String bucketName, String key) {
this.bucketName = bucketName;
this.key = key;
}
public final String getBucketName() {
return bucketName;
}
public final String getKey() {
return key;
}
public final boolean hasFinalPartBeenSeen() {
return hasFinalPartBeenSeen;
}
public final void setHasFinalPartBeenSeen(boolean hasFinalPartBeenSeen) {
this.hasFinalPartBeenSeen = hasFinalPartBeenSeen;
}
/**
* @return the materialsDescription
*/
public final Map<String, String> getMaterialsDescription() {
return materialsDescription;
}
/**
* @param materialsDescription the materialsDescription to set
*/
public final void setMaterialsDescription(
Map<String, String> materialsDescription) {
this.materialsDescription = materialsDescription == null
? null
: Collections.unmodifiableMap(new HashMap<String, String>(materialsDescription));
}
}
|
3e146ff5130eb9c9a0fb7e77d8c2de99f2214a98 | 770 | java | Java | src/main/java/cc/mrbird/febs/system/mapper/RoleMapper.java | Zoybzo/CFactory0.2 | 13817ae0cb0482b6a56540eae3fe706ba33ba5e6 | [
"Apache-2.0"
] | 1 | 2021-07-21T09:19:19.000Z | 2021-07-21T09:19:19.000Z | src/main/java/cc/mrbird/febs/system/mapper/RoleMapper.java | Zoybzo/CFactory0.2 | 13817ae0cb0482b6a56540eae3fe706ba33ba5e6 | [
"Apache-2.0"
] | null | null | null | src/main/java/cc/mrbird/febs/system/mapper/RoleMapper.java | Zoybzo/CFactory0.2 | 13817ae0cb0482b6a56540eae3fe706ba33ba5e6 | [
"Apache-2.0"
] | null | null | null | 22.647059 | 73 | 0.674026 | 8,654 | package cc.mrbird.febs.system.mapper;
import cc.mrbird.febs.system.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author MrBird
*/
public interface RoleMapper extends BaseMapper<Role> {
Long countRole(@Param("role") Role role);
/**
* 通过用户名查找用户角色
*
* @param username 用户名
* @return 用户角色集合
*/
List<Role> findUserRole(String username);
/**
* 查找角色详情
*
* @param page 分页
* @param role 角色
* @return IPage
*/
<T> IPage<Role> findRolePage(Page<T> page, @Param("role") Role role);
}
|
3e146ffdab7cdfa2ac52965396f56055ca85604a | 18,763 | java | Java | dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SimpleSearch.java | bireme/DSpace-6-FUNASA | fd29e3eda4be65e8ee217efae98c43187b419d17 | [
"BSD-3-Clause"
] | 10 | 2015-08-26T14:22:21.000Z | 2019-07-02T14:18:09.000Z | dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SimpleSearch.java | bireme/DSpace-6-FUNASA | fd29e3eda4be65e8ee217efae98c43187b419d17 | [
"BSD-3-Clause"
] | 690 | 2015-07-16T20:44:35.000Z | 2022-03-14T17:42:44.000Z | dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SimpleSearch.java | Sergio-strazzacappa/Dspace | 2aaa2aa526058b122637e8cc4400e47ea5499cd4 | [
"BSD-3-Clause"
] | 14 | 2018-05-15T16:44:09.000Z | 2022-03-09T18:44:02.000Z | 45.321256 | 227 | 0.676065 | 8,655 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.discovery;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.commons.lang.StringUtils;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.*;
import org.dspace.app.xmlui.wing.element.Item;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.*;
import org.dspace.core.Context;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.discovery.*;
import org.dspace.discovery.configuration.DiscoveryConfiguration;
import org.dspace.discovery.configuration.DiscoverySearchFilter;
import org.xml.sax.SAXException;
/**
* Perform a simple search of the repository. The user provides a simple one
* field query (the URL parameter is named query) and the results are processed.
*
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
* @author Adán Román Ruiz <aroman@arvo.es> (Bugfix)
*/
public class SimpleSearch extends AbstractSearch implements CacheableProcessingComponent {
/**
* Language Strings
*/
private static final Message T_title =
message("xmlui.ArtifactBrowser.SimpleSearch.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.SimpleSearch.trail");
private static final Message T_search_scope =
message("xmlui.Discovery.SimpleSearch.search_scope");
private static final Message T_head =
message("xmlui.ArtifactBrowser.SimpleSearch.head");
// private static final Message T_search_label =
// message("xmlui.discovery.SimpleSearch.search_label");
private static final Message T_go = message("xmlui.general.go");
private static final Message T_filter_label = message("xmlui.Discovery.SimpleSearch.filter_head");
private static final Message T_filter_help = message("xmlui.Discovery.SimpleSearch.filter_help");
private static final Message T_filter_current_filters = message("xmlui.Discovery.AbstractSearch.filters.controls.current-filters.head");
private static final Message T_filter_new_filters = message("xmlui.Discovery.AbstractSearch.filters.controls.new-filters.head");
private static final Message T_filter_controls_apply = message("xmlui.Discovery.AbstractSearch.filters.controls.apply-filters");
private static final Message T_filter_controls_add = message("xmlui.Discovery.AbstractSearch.filters.controls.add-filter");
private static final Message T_filter_controls_remove = message("xmlui.Discovery.AbstractSearch.filters.controls.remove-filter");
private static final Message T_filters_show = message("xmlui.Discovery.AbstractSearch.filters.display");
private static final Message T_filter_contain = message("xmlui.Discovery.SimpleSearch.filter.contains");
private static final Message T_filter_equals = message("xmlui.Discovery.SimpleSearch.filter.equals");
private static final Message T_filter_notcontain = message("xmlui.Discovery.SimpleSearch.filter.notcontains");
private static final Message T_filter_notequals = message("xmlui.Discovery.SimpleSearch.filter.notequals");
private static final Message T_filter_authority = message("xmlui.Discovery.SimpleSearch.filter.authority");
private static final Message T_filter_notauthority = message("xmlui.Discovery.SimpleSearch.filter.notauthority");
private static final Message T_did_you_mean = message("xmlui.Discovery.SimpleSearch.did_you_mean");
/**
* Add Page metadata.
* @throws org.dspace.app.xmlui.wing.WingException passed through.
* @throws java.sql.SQLException passed through.
*/
@Override
public void addPageMeta(PageMeta pageMeta) throws WingException, SQLException {
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if ((dso instanceof org.dspace.content.Collection) || (dso instanceof Community)) {
HandleUtil.buildHandleTrail(context, dso, pageMeta, contextPath, true);
}
pageMeta.addTrail().addContent(T_trail);
}
/**
* build the DRI page representing the body of the search query. This
* provides a widget to generate a new query and list of search results if
* present.
* @throws org.xml.sax.SAXException passed through.
* @throws org.dspace.app.xmlui.wing.WingException passed through.
* @throws java.sql.SQLException passed through.
* @throws java.io.IOException passed through.
* @throws org.dspace.authorize.AuthorizeException passed through.
*/
@Override
public void addBody(Body body) throws SAXException, WingException,
SQLException, IOException, AuthorizeException {
Context.Mode originalMode = context.getCurrentMode();
context.setMode(Context.Mode.READ_ONLY);
Request request = ObjectModelHelper.getRequest(objectModel);
String queryString = getQuery();
// Build the DRI Body
Division search = body.addDivision("search", "primary");
search.setHead(T_head);
String searchUrl = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.url") + "/JSON/discovery/search";
search.addHidden("discovery-json-search-url").setValue(searchUrl);
DSpaceObject currentScope = getScope();
if(currentScope != null){
search.addHidden("discovery-json-scope").setValue(currentScope.getHandle());
}
search.addHidden("contextpath").setValue(contextPath);
Map<String, String[]> fqs = getParameterFilterQueries();
Division searchBoxDivision = search.addDivision("discovery-search-box", "discoverySearchBox");
Division mainSearchDiv = searchBoxDivision.addInteractiveDivision("general-query",
"discover", Division.METHOD_GET, "discover-search-box");
List searchList = mainSearchDiv.addList("primary-search", List.TYPE_FORM);
// searchList.setHead(T_search_label);
if (variableScope())
{
Select scope = searchList.addItem().addSelect("scope");
scope.setLabel(T_search_scope);
buildScopeList(scope);
}
Item searchBoxItem = searchList.addItem();
Text text = searchBoxItem.addText("query");
text.setValue(queryString);
searchBoxItem.addButton("submit", "search-icon").setValue(T_go);
if(queryResults != null && StringUtils.isNotBlank(queryResults.getSpellCheckQuery()))
{
Item didYouMeanItem = searchList.addItem("did-you-mean", "didYouMean");
didYouMeanItem.addContent(T_did_you_mean);
didYouMeanItem.addXref(getSuggestUrl(queryResults.getSpellCheckQuery()), queryResults.getSpellCheckQuery(), "didYouMean");
}
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
DiscoveryConfiguration discoveryConfiguration = SearchUtils.getDiscoveryConfiguration(dso);
java.util.List<DiscoverySearchFilter> filterFields = discoveryConfiguration.getSearchFilters();
java.util.List<String> filterTypes = DiscoveryUIUtils.getRepeatableParameters(request, "filtertype");
java.util.List<String> filterOperators = DiscoveryUIUtils.getRepeatableParameters(request, "filter_relational_operator");
java.util.List<String> filterValues = DiscoveryUIUtils.getRepeatableParameters(request, "filter");
if(0 < filterFields.size() && filterTypes.size() == 0)
{
//Display the add filters url ONLY if we have no filters selected & filters can be added
searchList.addItem().addXref("display-filters", T_filters_show);
}
addHiddenFormFields("search", request, fqs, mainSearchDiv);
if(0 < filterFields.size())
{
Division searchFiltersDiv = searchBoxDivision.addInteractiveDivision("search-filters",
"discover", Division.METHOD_GET, "discover-filters-box " + (0 < filterTypes.size() ? "" : "hidden"));
Division filtersWrapper = searchFiltersDiv.addDivision("discovery-filters-wrapper");
filtersWrapper.setHead(T_filter_label);
filtersWrapper.addPara(T_filter_help);
Table filtersTable = filtersWrapper.addTable("discovery-filters", 1, 4, "discovery-filters");
//If we have any filters, show them
if(filterTypes.size() > 0)
{
filtersTable.addRow(Row.ROLE_HEADER).addCell("", Cell.ROLE_HEADER, 1, 4, "new-filter-header").addContent(T_filter_current_filters);
for (int i = 0; i < filterTypes.size(); i++)
{
String filterType = filterTypes.get(i);
String filterValue = filterValues.get(i);
String filterOperator = filterOperators.get(i);
if(StringUtils.isNotBlank(filterValue))
{
Row row = filtersTable.addRow("used-filters-" + i+1, Row.ROLE_DATA, "search-filter used-filter");
addFilterRow(filterFields, i+1, row, filterType, filterOperator, filterValue);
}
}
filtersTable.addRow("filler-row", Row.ROLE_DATA, "search-filter filler").addCell(1, 4).addContent("");
filtersTable.addRow(Row.ROLE_HEADER).addCell("", Cell.ROLE_HEADER, 1, 4, "new-filter-header").addContent(T_filter_new_filters);
}
int index = filterTypes.size() + 1;
Row row = filtersTable.addRow("filter-new-" + index, Row.ROLE_DATA, "search-filter");
addFilterRow(filterFields, index, row, null, null, null);
Row filterControlsItem = filtersTable.addRow("filter-controls", Row.ROLE_DATA, "apply-filter");
// filterControlsItem.addCell(1, 3).addContent("");
filterControlsItem.addCell(1, 4).addButton("submit_apply_filter", "discovery-apply-filter-button").setValue(T_filter_controls_apply);
addHiddenFormFields("filter", request, fqs, searchFiltersDiv);
}
// query.addPara(null, "button-list").addButton("submit").setValue(T_go);
// Build the DRI Body
//Division results = body.addDivision("results", "primary");
//results.setHead(T_head);
buildMainForm(search);
// Add the result division
try {
buildSearchResultsDivision(search);
} catch (SearchServiceException e) {
throw new UIException(e.getMessage(), e);
}
context.setMode(originalMode);
}
protected void addFilterRow(java.util.List<DiscoverySearchFilter> filterFields, int index, Row row, String selectedFilterType, String relationalOperator, String value) throws WingException {
Select select = row.addCell("", Cell.ROLE_DATA, "selection").addSelect("filtertype_" + index);
//For each field found (at least one) add options
for (DiscoverySearchFilter searchFilter : filterFields)
{
select.addOption(StringUtils.equals(searchFilter.getIndexFieldName(), selectedFilterType), searchFilter.getIndexFieldName(), message("xmlui.ArtifactBrowser.SimpleSearch.filter." + searchFilter.getIndexFieldName()));
}
Select typeSelect = row.addCell("", Cell.ROLE_DATA, "selection").addSelect("filter_relational_operator_" + index);
typeSelect.addOption(StringUtils.equals(relationalOperator, "contains"), "contains", T_filter_contain);
typeSelect.addOption(StringUtils.equals(relationalOperator, "equals"), "equals", T_filter_equals);
typeSelect.addOption(StringUtils.equals(relationalOperator, "authority"), "authority", T_filter_authority);
typeSelect.addOption(StringUtils.equals(relationalOperator, "notcontains"), "notcontains", T_filter_notcontain);
typeSelect.addOption(StringUtils.equals(relationalOperator, "notequals"), "notequals", T_filter_notequals);
typeSelect.addOption(StringUtils.equals(relationalOperator, "notauthority"), "notauthority", T_filter_notauthority);
//Add a box so we can search for our value
row.addCell("", Cell.ROLE_DATA, "discovery-filter-input-cell").addText("filter_" + index, "discovery-filter-input").setValue(value == null ? "" : value);
//And last add an add button
Cell buttonsCell = row.addCell("filter-controls_" + index, Cell.ROLE_DATA, "filter-controls");
buttonsCell.addButton("add-filter_" + index, "filter-control filter-add").setValue(T_filter_controls_add);
buttonsCell.addButton("remove-filter_" + index, "filter-control filter-remove").setValue(T_filter_controls_remove);
}
@Override
protected String getBasicUrl() throws SQLException {
Request request = ObjectModelHelper.getRequest(objectModel);
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
return request.getContextPath() + (dso == null ? "" : "/handle/" + dso.getHandle()) + "/discover";
}
@Override
protected Map<String, String[]> getParameterFilterQueries(){
return DiscoveryUIUtils.getParameterFilterQueries(ObjectModelHelper.getRequest(objectModel));
}
/**
* Returns all the filter queries for use by discovery
* This method returns more expanded filter queries then the getParameterFilterQueries
* @return an array containing the filter queries
*/
@Override
protected String[] getFilterQueries() {
return DiscoveryUIUtils.getFilterQueries(ObjectModelHelper.getRequest(objectModel), context);
}
/**
* Get the search query from the URL parameter, if none is found the empty
* string is returned.
* @return decoded query.
* @throws org.dspace.app.xmlui.utils.UIException passed through.
*/
@Override
protected String getQuery() throws UIException {
Request request = ObjectModelHelper.getRequest(objectModel);
String query = decodeFromURL(request.getParameter("query"));
if (query == null)
{
return "";
}
return query.trim();
}
/**
* Generate a URL to the simple search.
* @return the URL.
* @throws org.dspace.app.xmlui.utils.UIException passed through.
*/
@Override
protected String generateURL(Map<String, String> parameters)
throws UIException {
String query = getQuery();
if (!"".equals(query) && parameters.get("query") == null)
{
parameters.put("query", encodeForURL(query));
}
if (parameters.get("page") == null)
{
parameters.put("page", String.valueOf(getParameterPage()));
}
if (parameters.get("rpp") == null)
{
parameters.put("rpp", String.valueOf(getParameterRpp()));
}
if (parameters.get("group_by") == null)
{
parameters.put("group_by", String.valueOf(this.getParameterGroup()));
}
if (parameters.get("sort_by") == null && getParameterSortBy() != null)
{
parameters.put("sort_by", String.valueOf(getParameterSortBy()));
}
if (parameters.get("order") == null && getParameterOrder() != null)
{
parameters.put("order", getParameterOrder());
}
if (parameters.get("etal") == null)
{
parameters.put("etal", String.valueOf(getParameterEtAl()));
}
if(parameters.get("scope") == null && getParameterScope() != null)
{
parameters.put("scope", getParameterScope());
}
return AbstractDSpaceTransformer.generateURL("discover", parameters);
}
/**
* Since the layout is creating separate forms for each search part
* this method will add hidden fields containing the values from other form parts
*
* @param type the type of our form
* @param request the request
* @param fqs the filter queries
* @param division the division that requires the hidden fields
* @throws WingException will never occur
*/
private void addHiddenFormFields(String type, Request request, Map<String, String[]> fqs, Division division) throws WingException {
if(type.equals("filter") || type.equals("sort")){
if(request.getParameter("query") != null){
division.addHidden("query").setValue(request.getParameter("query"));
}
if(request.getParameter("scope") != null){
division.addHidden("scope").setValue(request.getParameter("scope"));
}
}
//Add the filter queries, current search settings so these remain saved when performing a new search !
if(type.equals("search") || type.equals("sort"))
{
for (String parameter : fqs.keySet())
{
String[] values = fqs.get(parameter);
for (String value : values) {
division.addHidden(parameter).setValue(value);
}
}
}
if(type.equals("search") || type.equals("filter")){
if(request.getParameter("rpp") != null){
division.addHidden("rpp").setValue(request.getParameter("rpp"));
}
if(request.getParameter("sort_by") != null){
division.addHidden("sort_by").setValue(request.getParameter("sort_by"));
}
if(request.getParameter("order") != null){
division.addHidden("order").setValue(request.getParameter("order"));
}
}
}
protected String getSuggestUrl(String newQuery) throws UIException {
Map parameters = new HashMap();
parameters.put("query", newQuery);
return addFilterQueriesToUrl(generateURL(parameters));
}
}
|
3e147027d9b4799a842e286ab6155e80c934d3e7 | 1,405 | java | Java | domain/src/main/java/com/vpaliy/domain/interactor/SingleInteractor.java | bholanathbarik9748/Melophile | ec280911108db8b3963bf452bd26a835022aea20 | [
"Apache-2.0"
] | 812 | 2017-09-03T04:15:05.000Z | 2018-06-19T03:31:01.000Z | domain/src/main/java/com/vpaliy/domain/interactor/SingleInteractor.java | bholanathbarik9748/Melophile | ec280911108db8b3963bf452bd26a835022aea20 | [
"Apache-2.0"
] | 7 | 2017-09-03T14:14:59.000Z | 2018-05-25T02:45:52.000Z | domain/src/main/java/com/vpaliy/domain/interactor/SingleInteractor.java | bholanathbarik9748/Melophile | ec280911108db8b3963bf452bd26a835022aea20 | [
"Apache-2.0"
] | 125 | 2017-09-03T05:06:12.000Z | 2018-05-08T09:43:14.000Z | 31.931818 | 106 | 0.742349 | 8,656 | package com.vpaliy.domain.interactor;
import com.vpaliy.domain.executor.BaseSchedulerProvider;
import io.reactivex.Single;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableSingleObserver;
public abstract class SingleInteractor<T, Params> {
protected BaseSchedulerProvider schedulerProvider;
protected CompositeDisposable disposables;
public SingleInteractor(BaseSchedulerProvider schedulerProvider) {
this.schedulerProvider = schedulerProvider;
this.disposables = new CompositeDisposable();
}
public abstract Single<T> buildUseCase(Params params);
public void execute(DisposableSingleObserver<T> singleObserver, Params params) {
Single<T> single = buildUseCase(params)
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui());
disposables.add(single.subscribeWith(singleObserver));
}
public void execute(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError, Params params) {
Single<T> single = buildUseCase(params);
if (single != null) {
single = single.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui());
disposables.add(single.subscribe(onSuccess, onError));
}
}
public void dispose() {
if (!disposables.isDisposed()) {
disposables.clear();
}
}
}
|
3e1470c6ef203306e91c149fcb3725414df9ce8d | 1,794 | java | Java | MCP/1.7.10/1/Spigot/src/main/java/net/minecraft/server/EnumToolMaterial.java | KoaDev/Minecraft | 6a9a14fd913107a4075f28136400d197059194e3 | [
"MIT"
] | null | null | null | MCP/1.7.10/1/Spigot/src/main/java/net/minecraft/server/EnumToolMaterial.java | KoaDev/Minecraft | 6a9a14fd913107a4075f28136400d197059194e3 | [
"MIT"
] | null | null | null | MCP/1.7.10/1/Spigot/src/main/java/net/minecraft/server/EnumToolMaterial.java | KoaDev/Minecraft | 6a9a14fd913107a4075f28136400d197059194e3 | [
"MIT"
] | null | null | null | 28.03125 | 155 | 0.519509 | 8,657 | package net.minecraft.server;
public enum EnumToolMaterial {
/** Alkazia */
WOOD("WOOD", 0, 0, 59, 2.0F, 0.0F, 15),
STONE("STONE", 1, 1, 131, 4.0F, 1.0F, 5),
IRON("IRON", 2, 2, 250, 6.0F, 2.0F, 14),
DIAMOND("EMERALD", 3, 3, 1561, 7.0F, 3.0F, 10),
GOLD("GOLD", 4, 0, 32, 12.0F, 0.0F, 22),
BAUXITE("BAUXITE", 5, 2, 900, 7.0F, 4.0F, 14),
GRANITE("GRANITE", 6, 3, 2000, 11.0F, 5.0F, 10),
OPALE("OPALE", 7, 3, 3000, 13.0F, 6.0F, 10),
METEOR("METEOR", 8, 3, 3600, 15.0F, 7.0F, 10);
private final int f;
private final int g;
private final float h;
private final float i;
private final int j;
private static final EnumToolMaterial[] k = new EnumToolMaterial[] { WOOD, STONE, IRON, DIAMOND, GOLD, BAUXITE, GRANITE, OPALE, METEOR}; /** Alkazia */
private EnumToolMaterial(String s, int i, int j, int k, float f, float f1, int l) {
this.f = j;
this.g = k;
this.h = f;
this.i = f1;
this.j = l;
}
public int a() {
return this.g;
}
public float b() {
return this.h;
}
public float c() {
return this.i;
}
public int d() {
return this.f;
}
public int e() {
return this.j;
}
public Item f() {
return this == WOOD ? Item.getItemOf(Blocks.WOOD) :
(this == STONE ? Item.getItemOf(Blocks.COBBLESTONE) :
(this == GOLD ? Items.GOLD_INGOT :
(this == IRON ? Items.IRON_INGOT :
(this == DIAMOND ? Items.DIAMOND :
(this == BAUXITE ? Items.BAUXITE_INGOT :
(this == OPALE ? Items.OPALE :
(this == GRANITE ? Items.GRANITE :
(this == METEOR ? Items.METEOR_FRAGMENT :
null))))))));
}
} |
3e1470e4f1f9d5287107fc7797be853dd5a3b8ef | 1,827 | java | Java | tis-datax/tis-datax-mongodb-plugin/src/main/java/com/qlangtech/tis/plugin/datax/BasicMongoDBContext.java | liufu1986007/plugins | fb923d619384449922bf9f1d56615b657a4c250e | [
"Apache-2.0"
] | 3 | 2021-11-01T10:11:36.000Z | 2022-03-09T10:41:00.000Z | tis-datax/tis-datax-mongodb-plugin/src/main/java/com/qlangtech/tis/plugin/datax/BasicMongoDBContext.java | liufu1986007/plugins | fb923d619384449922bf9f1d56615b657a4c250e | [
"Apache-2.0"
] | 6 | 2021-12-27T09:33:54.000Z | 2022-03-30T11:58:48.000Z | tis-datax/tis-datax-mongodb-plugin/src/main/java/com/qlangtech/tis/plugin/datax/BasicMongoDBContext.java | liufu1986007/plugins | fb923d619384449922bf9f1d56615b657a4c250e | [
"Apache-2.0"
] | 3 | 2021-11-22T03:41:00.000Z | 2022-03-18T06:51:54.000Z | 32.052632 | 99 | 0.702791 | 8,658 | /**
* 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.qlangtech.tis.plugin.datax;
import com.qlangtech.tis.plugin.ds.mangodb.MangoDBDataSourceFactory;
import java.util.stream.Collectors;
/**
* @author: 百岁(baisui@qlangtech.com)
* @create: 2021-06-20 20:43
**/
public class BasicMongoDBContext {
private final MangoDBDataSourceFactory dsFactory;
public BasicMongoDBContext(MangoDBDataSourceFactory dsFactory) {
this.dsFactory = dsFactory;
}
public String getServerAddress() {
return MangoDBDataSourceFactory.getAddressList(this.dsFactory.address)
.stream().map((address) -> "\"" + address + "\"").collect(Collectors.joining(","));
}
public boolean isContainCredential() {
return this.dsFactory.isContainCredential();
}
public String getUserName() {
return this.dsFactory.username;
}
public String getPassword() {
return this.dsFactory.password;
}
public String getDbName() {
return this.dsFactory.dbName;
}
}
|
3e1470e5b9cdfce5117a88bd986a391f5af4a46e | 9,142 | java | Java | src/erp/mtrn/data/STrnDeliveryAckUtilities.java | swaplicado/siie32 | c1dbde9e7a6d55d85804c50751b7ebab6676bbd6 | [
"MIT"
] | null | null | null | src/erp/mtrn/data/STrnDeliveryAckUtilities.java | swaplicado/siie32 | c1dbde9e7a6d55d85804c50751b7ebab6676bbd6 | [
"MIT"
] | null | null | null | src/erp/mtrn/data/STrnDeliveryAckUtilities.java | swaplicado/siie32 | c1dbde9e7a6d55d85804c50751b7ebab6676bbd6 | [
"MIT"
] | 2 | 2017-01-14T17:20:25.000Z | 2018-07-19T14:41:16.000Z | 51.359551 | 195 | 0.594728 | 8,659 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mtrn.data;
import erp.lib.SLibConstants;
import erp.mcfg.data.SDataParamsCompany;
import java.io.File;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* @author Daniel López
*/
public abstract class STrnDeliveryAckUtilities {
/**
* Gets all delivery acknowledgment registries of desired document.
* @param client GUI client.
* @param dpsKey Desired document key.
* @return Array list of delivery acknowledgment registries of desired document.
* @throws Exception
*/
public static ArrayList<SDataDpsDeliveryAck> getDpsDeliveryAcks(erp.client.SClientInterface client, int[] dpsKey) throws Exception {
ArrayList<SDataDpsDeliveryAck> dpsDeliveryAcks = new ArrayList<>();
String sql = "";
Statement statement = client.getSession().getDatabase().getConnection().createStatement();
Statement statementRead = client.getSession().getDatabase().getConnection().createStatement();
ResultSet resultSet = null;
sql = "SELECT id_dps_ack "
+ "FROM trn_dps_ack "
+ "WHERE fid_year = " + dpsKey[0] + " AND "
+ "fid_doc = " + dpsKey[1] + " AND "
+ "b_del = 0 "
+ "ORDER BY id_dps_ack ";
resultSet = statement.executeQuery(sql);
while (resultSet.next()){
SDataDpsDeliveryAck deliveryAck = new SDataDpsDeliveryAck();
deliveryAck.read(new int[] { resultSet.getInt(1) }, statementRead);
dpsDeliveryAcks.add(deliveryAck);
}
return dpsDeliveryAcks;
}
/**
* Gets all delivery acknowledgment files of desired document.
* @param client GUI client.
* @param dpsKey Desired document key.
* @return Array list of delivery acknowledgment files array of two dimensions (index 0: user name; index 1: system name) of desired document.
* @throws Exception
*/
public static ArrayList<File[]> getFiles(erp.client.SClientInterface client, int[] dpsKey) throws Exception {
ArrayList<File[]> files = new ArrayList<>();
String sql = "";
Statement statement = client.getSession().getDatabase().getConnection().createStatement();
ResultSet resultSet = null;
sql = "SELECT id_dps_ack, name_usr, name_sys "
+ "FROM trn_dps_ack "
+ "WHERE fid_year = " + dpsKey[0] + " AND "
+ "fid_doc = " + dpsKey[1] + " AND "
+ "b_del = 0 "
+ "ORDER BY name_sys, id_dps_ack ";
resultSet = statement.executeQuery(sql);
while(resultSet.next()) {
files.add(new File[] {
new File(resultSet.getString("name_usr")),
new File(SDataParamsCompany.FILES_DIR + "\\" + resultSet.getString("name_sys"))
});
}
return files;
}
/**
* Download all delivery acknowledgment files of desired document into user selected directory.
* @param client GUI client.
* @param dpsKey Desired document key.
* @throws Exception
*/
public static void downloadFiles(erp.client.SClientInterface client, int[] dpsKey) throws Exception {
//solicitar directorio de destino al usuario (≈ solicitar confirmación al usuario)
client.getFileChooser().setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (client.getFileChooser().showSaveDialog(client.getFrame()) == JFileChooser.APPROVE_OPTION) { //si el usuario sí proporcionó el directorio de destino
String path = client.getFileChooser().getSelectedFile().getAbsolutePath();
//obtener lista de registros de acuse de entrega del documento (ArrayList<SDataDpsDeliveryAck>)
ArrayList<SDataDpsDeliveryAck> dpsDeliveryAcks = getDpsDeliveryAcks(client, dpsKey);
if (dpsDeliveryAcks.isEmpty()) { //si no hay registros:
//informar al usuario que no hay archivos
client.showMsgBoxInformation("El documento no tiene archivos de acuse de entrega.");
}
else {
//para cada registro en la lista de registros de acuse de entrega del documento:
for (SDataDpsDeliveryAck deliveryAck : dpsDeliveryAcks) {
//leer archivo del registro de acuse de entrega
deliveryAck.setAuxFile(deliveryAck.createFileFromSystemPath());
//guardar archivo en el directorio de destino
deliveryAck.saveFileCustomPath(path);
}
//informar al usuario el número de archivos descargados
client.showMsgBoxInformation("Se descargaron " + dpsDeliveryAcks.size() + " archivo(s).");
}
}
}
/**
* Delete all delivery acknowledgment files of desired document.
* @param client GUI client.
* @param dpsKey Desired document key.
* @throws Exception
*/
public static void deleteFiles(erp.client.SClientInterface client, int[] dpsKey) throws Exception {
//solicitar confirmación al usuario para eliminar los archivos de acuses de entrega
if(client.showMsgBoxConfirm("Se eliminarán todos los acuses de entrega del documento."+ SLibConstants.MSG_CNF_MSG_CONT) == JOptionPane.YES_OPTION) {
ArrayList<SDataDpsDeliveryAck> dpsDeliveryAcks = getDpsDeliveryAcks(client, dpsKey); //obtener lista de registros de acuse de entrega del documento
if (dpsDeliveryAcks.isEmpty()) { //si no hay registros:
client.showMsgBoxInformation("El documento no tiene archivos de acuse de entrega.");
}
else {
for (SDataDpsDeliveryAck deliveryAck : dpsDeliveryAcks) {
File filePath = new File(SDataParamsCompany.FILES_DIR + "\\" + deliveryAck.getNameSystem());
filePath.delete(); //eliminar archivo en el directorio de destino
String sql = "UPDATE trn_dps_ack SET "
+ "b_del = 1, "
+ "fid_usr_del = " + client.getSession().getUser().getPkUserId() + ", "
+ "ts_del = NOW() "
+ "WHERE fid_year = " + dpsKey[0] + " AND fid_doc = " + dpsKey[1] + " AND b_del = 0 "; //modificar registro de acuse de entrega del documento
client.getSession().getStatement().execute(sql);
}
client.showMsgBoxInformation("Se eliminaron " + dpsDeliveryAcks.size() + " archivo(s).");
}
}
}
/**
* Reasign all delivery acknowledgment files from source document to destiny document.
* @param client
* @param dpsSourceKey Source document key.
* @param dpsDestinyKey Destiny document key.
* @throws Exception
*/
public static void reasignFiles(erp.client.SClientInterface client, int[] dpsSourceKey, int[] dpsDestinyKey) throws Exception {
if(client.showMsgBoxConfirm("Se reasignarán los acuses de entrega."+ SLibConstants.MSG_CNF_MSG_CONT) == JOptionPane.YES_OPTION){
ArrayList<SDataDpsDeliveryAck> dpsDeliveryAcks = getDpsDeliveryAcks(client, dpsSourceKey); //obtener lista de registros de acuse de entrega del documento
if (dpsDeliveryAcks.isEmpty()) { //si no hay registros:
client.showMsgBoxInformation("El documento no tiene archivos de acuse de entrega."); //informar al usuario que no hay archivos
}
else {
for (SDataDpsDeliveryAck deliveryAck : dpsDeliveryAcks) {
String sql = "UPDATE trn_dps_ack SET "
+ "fid_year = " + dpsDestinyKey[0] + ", "
+ "fid_doc = " + dpsDestinyKey[1] + ", "
+ "fid_usr_edit = " + client.getSession().getUser().getPkUserId() + ", "
+ "ts_edit = NOW() "
+ "WHERE fid_year = " + dpsSourceKey[0] + " AND fid_doc = " + dpsSourceKey[1] + " AND b_del = 0 "; //reasignar el documento de destino en el registro de acuse de entrega
client.getSession().getStatement().execute(sql); //guardar cambios al registro de acuse de entrega
}
client.showMsgBoxInformation("Se reasignaron " + dpsDeliveryAcks.size() + " archivo(s)."); //informar al usuario el número de archivos reasignados
}
}
}
} |
3e147104fa5c1577f8809c518cc43aa5aedefe1b | 2,781 | java | Java | middleware_old/src/middleware/LiveTransaction.java | barzan/dbseer | 3ad0718f665a5beffa65df7be8998986dcdbf3db | [
"Apache-2.0"
] | 115 | 2015-06-27T15:09:07.000Z | 2022-01-06T04:09:35.000Z | middleware_old/src/middleware/LiveTransaction.java | barzan/dbseer | 3ad0718f665a5beffa65df7be8998986dcdbf3db | [
"Apache-2.0"
] | 10 | 2015-06-27T15:10:49.000Z | 2021-11-14T12:13:24.000Z | middleware_old/src/middleware/LiveTransaction.java | barzan/dbseer | 3ad0718f665a5beffa65df7be8998986dcdbf3db | [
"Apache-2.0"
] | 28 | 2015-09-23T05:49:32.000Z | 2021-12-09T09:13:46.000Z | 21.229008 | 103 | 0.645092 | 8,660 | /*
* Copyright 2013 Barzan Mozafari
*
* 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 middleware;
import java.util.ArrayList;
/**
* Transaction class for live monitoring.
*
* Created by dyoon on 5/15/15.
*/
public class LiveTransaction
{
public static final int MAX_TABLE = 100;
private int id;
private int maxTableId;
private long latency;
private ArrayList<LiveQuery> queries;
private LiveTransactionLocation location;
public LiveTransaction(int id)
{
this.id = id;
maxTableId = 0;
latency = 0;
queries = new ArrayList<LiveQuery>();
location = new LiveTransactionLocation();
}
public synchronized void addQuery(LiveQuery query)
{
queries.add(query);
}
public synchronized String getEntireStatements()
{
String statement = "";
for (LiveQuery q : queries)
{
statement += q.getStatement();
statement += "\n";
}
return statement;
}
public ArrayList<LiveQuery> getQueries()
{
return queries;
}
public LiveTransactionLocation getLocation()
{
return location;
}
public void addStatement(int tableId, int type)
{
if (tableId > location.maxTableId)
{
location.maxTableId = tableId;
}
switch (type)
{
case LiveTransactionLocation.SELECT:
{
location.numSelect[tableId]++;
break;
}
case LiveTransactionLocation.UPDATE:
{
location.numUpdate[tableId]++;
break;
}
case LiveTransactionLocation.DELETE:
{
location.numDelete[tableId]++;
break;
}
case LiveTransactionLocation.INSERT:
{
location.numInsert[tableId]++;
break;
}
default:
break;
}
}
public void printTransactionStat()
{
System.out.println("tx = ");
for (int i = 0;i <location.maxTableId;++i)
{
System.out.print(String.format("%.0f,%.0f,%.0f,%.0f,",
location.numSelect[i], location.numUpdate[i], location.numDelete[i], location.numInsert[i]));
}
System.out.println();
}
public int getMaxTableId()
{
return maxTableId;
}
public long getLatency()
{
return latency;
}
public void setLatency(long latency)
{
this.latency = latency;
}
}
|
3e147132745192f18cc439a4080bb071c313c0f4 | 379 | java | Java | Pattern/src/pattern/state/Client.java | minggo620/java_pattern | 5c1301081d14933e02980c8d56ed567ca7d744d8 | [
"MIT"
] | null | null | null | Pattern/src/pattern/state/Client.java | minggo620/java_pattern | 5c1301081d14933e02980c8d56ed567ca7d744d8 | [
"MIT"
] | null | null | null | Pattern/src/pattern/state/Client.java | minggo620/java_pattern | 5c1301081d14933e02980c8d56ed567ca7d744d8 | [
"MIT"
] | null | null | null | 15.791667 | 44 | 0.6781 | 8,661 | package pattern.state;
/**
* 状态模式
* 1.跟策略一样的是都在Context中执行操作方法。
* 2.跟策略不一样的是每种状态执行会影响其他状态执行的结果。
* @author minggo
* @time 2017年7月18日下午5:10:47
*/
public class Client {
public static void main(String[] args) {
Context context = new Context();
context.setMetroState(new OpeningState());
context.open();
context.close();
context.run();
context.stop();
}
}
|
3e14719e8bbf92505c204d1dc722b1946b328423 | 7,408 | java | Java | src/test/java/io/breezil/queryfier/engine/QueryBuilderTest.java | chicojfp/querify | 190595cf84e98f0798c0751a3737cebcb4bc98f1 | [
"MIT"
] | 1 | 2019-09-13T15:38:08.000Z | 2019-09-13T15:38:08.000Z | src/test/java/io/breezil/queryfier/engine/QueryBuilderTest.java | chicojfp/querify | 190595cf84e98f0798c0751a3737cebcb4bc98f1 | [
"MIT"
] | 2 | 2019-09-13T14:13:11.000Z | 2019-09-13T17:04:11.000Z | src/test/java/io/breezil/queryfier/engine/QueryBuilderTest.java | chicojfp/querify | 190595cf84e98f0798c0751a3737cebcb4bc98f1 | [
"MIT"
] | 1 | 2019-09-13T15:41:49.000Z | 2019-09-13T15:41:49.000Z | 30.113821 | 107 | 0.723002 | 8,662 | package io.breezil.queryfier.engine;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import io.breezil.queryfier.engine.QQuery;
import io.breezil.queryfier.engine.StateFilterTest;
public class QueryBuilderTest {
private StateFilterTest sf;
private int NUMBER_OF_TOTAL_PROJECTIONS = 5;
private int NUMBER_OF_QUERIED_PROJECTIONS = 1;
private int ONE_SORTED_COLUNM = 1;
private int TWO_SORTED_COLUNM = 2;
private String ASC_SORTING = "ASC";
private String DESC_SORTING = "DESC";
private String COUNTRY_COLUMN_ALIAS = "country";
private String COUNTRY_COLUMN_FULL_NAME = "country.name";
private String NAME_COLUMN_ALIAS = "name";
private String NAME_COLUMN_FULL_NAME = "name";
private String STATE_FIELD_NAME = "name";
private String BRASIL = "Brasil";
private int NO_PROJECTIONS = 0;
private int ONE_PROJECTION = 1;
private int TWO_PROJECTION = 2;
@Before
public void configura() {
sf = new StateFilterTest();
sf.setCountry(BRASIL);
sf.setGovernor("Manoel Bandeira");
sf.setMain("Louca da Espanha");
sf.setName("Passárgada");
}
@Test
public void recuperaTodasAsColunasSeNenhumaForInformada() {
QQuery q = convertDTO2Query(sf);
Assert.assertEquals("A consulta deveria não retornou todos os elementos.",
NUMBER_OF_TOTAL_PROJECTIONS, q.getProjections().size());
}
@Test
public void recuperaApenasColunasInformadas() {
sf.addColumn("main");
QQuery q = convertDTO2Query(sf);
Assert.assertEquals("A consulta deveria retornar apenas 1 projeção.",
NUMBER_OF_QUERIED_PROJECTIONS, q.getProjections().size());
}
@Test
public void deveOrdenarAscendentemente() {
sf.addSortedColumns("governor");
QQuery q = convertDTO2Query(sf);
Assert.assertEquals("A consulta deveria retornar apenas 1 projeção.",
ONE_SORTED_COLUNM, q.getSortColumns().size());
Assert.assertEquals("A ordenação não está ordenando ascendente por padrão.",
ASC_SORTING, q.getSortColumns().get(0).getOrder());
}
@Test
public void deveOrdenarDescendentemente() {
sf.addSortedColumns("!name");
QQuery q = convertDTO2Query(sf);
Assert.assertEquals("A consulta deveria retornar apenas 1 projeção.",
ONE_SORTED_COLUNM, q.getSortColumns().size());
Assert.assertEquals("A ordenação não está excendente descendentemente quando usa o padrão !nome_coluna.",
DESC_SORTING, q.getSortColumns().get(0).getOrder());
}
@Test
public void deveOrdernarPorMaisDeUmCampo() {
QQuery q = addSortedColumns();
Assert.assertEquals("A ordenação não está ordenando descendentemente quando usa o padrão !nome_coluna.",
DESC_SORTING, q.getSortColumns().get(0).getOrder());
Assert.assertEquals("A ordenação não está ordenando ascendente por padrão.",
ASC_SORTING, q.getSortColumns().get(1).getOrder());
}
@Test
public void deveManterAPrecedenciaDeOrdenacao() {
QQuery q = addSortedColumns();
Assert.assertEquals("A ordenação não está ordenando descendentemente quando usa o padrão !nome_coluna.",
"main", q.getSortColumns().get(0).getItem());
Assert.assertEquals("A ordenação não está ordenando ascendente por padrão.",
"governor", q.getSortColumns().get(1).getItem());
}
private QQuery addSortedColumns() {
sf.addSortedColumns("!main");
sf.addSortedColumns("governor");
QQuery q = convertDTO2Query(sf);
Assert.assertEquals("A consulta deveria retornar duas projeções.",
TWO_SORTED_COLUNM, q.getSortColumns().size());
return q;
}
@Test
public void deveFiltrarPorColunasNaoNulas() {
StateFilterTest sf = new StateFilterTest();
QQuery q = convertDTO2Query(sf);
Assert.assertEquals("Não deve haver projeções com valores nulos.",
NO_PROJECTIONS, q.getSelections().size());
sf.setCountry(BRASIL);
q = convertDTO2Query(sf);
Assert.assertEquals("Deve haver uma projeção para o campo não nulo",
ONE_PROJECTION, q.getSelections().size());
Assert.assertEquals("Deve haver uma projeção para o campo não nulo",
COUNTRY_COLUMN_ALIAS, q.getSelections().get(0).getAlias());
Assert.assertEquals("Deve haver um mapeamento para o nome real da coluna",
COUNTRY_COLUMN_FULL_NAME, q.getSelections().get(0).getItem());
sf.setName("PE");
q = convertDTO2Query(sf);
Assert.assertEquals("Deve haver uma projeção para o campo não nulo",
TWO_PROJECTION, q.getSelections().size());
Assert.assertEquals("Deve haver uma projeção para o campo não nulo",
NAME_COLUMN_ALIAS, q.getSelections().get(0).getAlias());
Assert.assertEquals("Deve haver uma projeção para o campo não nulo",
NAME_COLUMN_FULL_NAME, q.getSelections().get(0).getItem());
}
@Test
public void deveSuportarConsultasComDistinctEmColunaEspecifica() {
StateFilterTest sf = new StateFilterTest();
sf.setCountry(BRASIL);
sf.addColumn(STATE_FIELD_NAME);
sf.setDistinct(true);
QQuery q = convertDTO2Query(sf);
System.out.println(q.toDTOQuery());
Assert.assertEquals("Deve haver apenas um agrupamento conforme definido",
ONE_PROJECTION, q.getGroups().size());
}
@Test
public void deveAgruparDemaisColunasSemAgregacao() {
StateFilterTest sf = new StateFilterTest();
sf.setCountry(BRASIL);
sf.addColumns("count@main", "sum@population");
sf.addColumns(COUNTRY_COLUMN_ALIAS, STATE_FIELD_NAME);
QQuery q = convertDTO2Query(sf);
System.out.println(q.toDTOQuery());
Assert.assertEquals("Deve haver apenas um agrupamento conforme definido",
TWO_PROJECTION, q.getGroups().size());
}
@Test
public void deveAgruparColunasSemAgregacao() {
StateFilterTest sf = new StateFilterTest();
sf.setCountry(BRASIL);
sf.addColumn("count@name");
sf.addColumns(STATE_FIELD_NAME);
QQuery q = convertDTO2Query(sf);
System.out.println(q.toDTOQuery());
Assert.assertEquals("Deve haver apenas um agrupamento conforme definido",
ONE_PROJECTION, q.getGroups().size());
}
@Test
public void deveSuportarConsultasComDistinct() {
StateFilterTest sf = new StateFilterTest();
sf.setCountry(BRASIL);
sf.addColumns(STATE_FIELD_NAME, "main");
sf.setDistinct(true);
QQuery q = convertDTO2Query(sf);
Assert.assertEquals("Deve haver apenas dois agrupamentos conforme definido",
TWO_PROJECTION, q.getGroups().size());
}
@Test
public void testarAParada() {
StateFilterTest sf = new StateFilterTest();
sf.setCountry(BRASIL);
sf.setGovernor("Manoel Bandeira");
sf.setMain("Louca da Espanha");
sf.setName("Passárgada");
sf.addColumn(COUNTRY_COLUMN_ALIAS);
sf.addColumn("main");
sf.addSortedColumns(COUNTRY_COLUMN_ALIAS);
sf.addSortedColumns("!main");
QQuery q = convertDTO2Query(sf);
System.out.println(q);
}
private QQuery convertDTO2Query(StateFilterTest sf) {
QQuery q = null;
try {
q = new QueryBuilder().parseQuery(sf);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return q;
}
@Test
public void consultarEntidadesPais() {
CityFilterTest sf = new CityFilterTest();
sf.setCountry(BRASIL);
sf.setState("PE");
sf.setMajor("Lima Barreto");
sf.setName("Bruzudanga");
sf.addSortedColumns("major");
sf.addSortedColumns("!name");
QQuery q = null;
try {
q = new QueryBuilder().parseQuery(sf);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(q);
}
}
|
3e1471aaf21c5ae9bf87d4a54376772e640da125 | 15,072 | java | Java | google-cloud-clients/google-cloud-compute/src/test/java/com/google/cloud/compute/v1/GlobalAddressClientTest.java | qian-long/google-cloud-java | 266c880f2cae29bd1c3d8960d823c2179aa77448 | [
"Apache-2.0"
] | 2 | 2019-08-25T15:16:57.000Z | 2019-08-25T15:17:04.000Z | google-cloud-clients/google-cloud-compute/src/test/java/com/google/cloud/compute/v1/GlobalAddressClientTest.java | qian-long/google-cloud-java | 266c880f2cae29bd1c3d8960d823c2179aa77448 | [
"Apache-2.0"
] | 3 | 2019-05-22T14:12:27.000Z | 2019-07-09T14:16:23.000Z | google-cloud-clients/google-cloud-compute/src/test/java/com/google/cloud/compute/v1/GlobalAddressClientTest.java | qian-long/google-cloud-java | 266c880f2cae29bd1c3d8960d823c2179aa77448 | [
"Apache-2.0"
] | 1 | 2019-12-10T05:41:00.000Z | 2019-12-10T05:41:00.000Z | 37.492537 | 109 | 0.695926 | 8,663 | /*
* Copyright 2019 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
*
* 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 com.google.cloud.compute.v1;
import static com.google.cloud.compute.v1.GlobalAddressClient.ListGlobalAddressesPagedResponse;
import static com.google.cloud.compute.v1.stub.HttpJsonGlobalAddressStub.deleteGlobalAddressMethodDescriptor;
import static com.google.cloud.compute.v1.stub.HttpJsonGlobalAddressStub.getGlobalAddressMethodDescriptor;
import static com.google.cloud.compute.v1.stub.HttpJsonGlobalAddressStub.insertGlobalAddressMethodDescriptor;
import static com.google.cloud.compute.v1.stub.HttpJsonGlobalAddressStub.listGlobalAddressesMethodDescriptor;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.httpjson.ApiMethodDescriptor;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.testing.MockHttpService;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.api.gax.rpc.testing.FakeStatusCode;
import com.google.cloud.compute.v1.stub.GlobalAddressStubSettings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@javax.annotation.Generated("by GAPIC")
public class GlobalAddressClientTest {
private static final List<ApiMethodDescriptor> METHOD_DESCRIPTORS =
ImmutableList.copyOf(
Lists.<ApiMethodDescriptor>newArrayList(
deleteGlobalAddressMethodDescriptor,
getGlobalAddressMethodDescriptor,
insertGlobalAddressMethodDescriptor,
listGlobalAddressesMethodDescriptor));
private static final MockHttpService mockService =
new MockHttpService(METHOD_DESCRIPTORS, GlobalAddressStubSettings.getDefaultEndpoint());
private static GlobalAddressClient client;
private static GlobalAddressSettings clientSettings;
@BeforeClass
public static void setUp() throws IOException {
clientSettings =
GlobalAddressSettings.newBuilder()
.setTransportChannelProvider(
GlobalAddressSettings.defaultHttpJsonTransportProviderBuilder()
.setHttpTransport(mockService)
.build())
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = GlobalAddressClient.create(clientSettings);
}
@After
public void cleanUp() {
mockService.reset();
}
@AfterClass
public static void tearDown() throws Exception {
client.close();
}
@Test
@SuppressWarnings("all")
public void deleteGlobalAddressTest() {
String clientOperationId = "clientOperationId-239630617";
String creationTimestamp = "creationTimestamp567396278";
String description = "description-1724546052";
String endTime = "endTime1725551537";
String httpErrorMessage = "httpErrorMessage1276263769";
Integer httpErrorStatusCode = 1386087020;
String id = "id3355";
String insertTime = "insertTime-103148397";
String kind = "kind3292052";
String name = "name3373707";
String operationType = "operationType-1432962286";
Integer progress = 1001078227;
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
String selfLink = "selfLink-1691268851";
String startTime = "startTime-1573145462";
String status = "status-892481550";
String statusMessage = "statusMessage-239442758";
String targetId = "targetId-815576439";
String targetLink = "targetLink-2084812312";
String user = "user3599307";
ProjectZoneName zone = ProjectZoneName.of("[PROJECT]", "[ZONE]");
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId(clientOperationId)
.setCreationTimestamp(creationTimestamp)
.setDescription(description)
.setEndTime(endTime)
.setHttpErrorMessage(httpErrorMessage)
.setHttpErrorStatusCode(httpErrorStatusCode)
.setId(id)
.setInsertTime(insertTime)
.setKind(kind)
.setName(name)
.setOperationType(operationType)
.setProgress(progress)
.setRegion(region.toString())
.setSelfLink(selfLink)
.setStartTime(startTime)
.setStatus(status)
.setStatusMessage(statusMessage)
.setTargetId(targetId)
.setTargetLink(targetLink)
.setUser(user)
.setZone(zone.toString())
.build();
mockService.addResponse(expectedResponse);
ProjectGlobalAddressName address = ProjectGlobalAddressName.of("[PROJECT]", "[ADDRESS]");
Operation actualResponse = client.deleteGlobalAddress(address);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
@SuppressWarnings("all")
public void deleteGlobalAddressExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
ProjectGlobalAddressName address = ProjectGlobalAddressName.of("[PROJECT]", "[ADDRESS]");
client.deleteGlobalAddress(address);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void getGlobalAddressTest() {
ProjectGlobalAddressName address2 = ProjectGlobalAddressName.of("[PROJECT]", "[ADDRESS]");
String addressType = "addressType264307877";
String creationTimestamp = "creationTimestamp567396278";
String description = "description-1724546052";
String id = "id3355";
String ipVersion = "ipVersion-1315653184";
String kind = "kind3292052";
String name = "name3373707";
ProjectGlobalNetworkName network = ProjectGlobalNetworkName.of("[PROJECT]", "[NETWORK]");
String networkTier = "networkTier-19473069";
Integer prefixLength = 1157046989;
String purpose = "purpose-220463842";
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
String selfLink = "selfLink-1691268851";
String status = "status-892481550";
ProjectRegionSubnetworkName subnetwork =
ProjectRegionSubnetworkName.of("[PROJECT]", "[REGION]", "[SUBNETWORK]");
Address expectedResponse =
Address.newBuilder()
.setAddress(address2.toString())
.setAddressType(addressType)
.setCreationTimestamp(creationTimestamp)
.setDescription(description)
.setId(id)
.setIpVersion(ipVersion)
.setKind(kind)
.setName(name)
.setNetwork(network.toString())
.setNetworkTier(networkTier)
.setPrefixLength(prefixLength)
.setPurpose(purpose)
.setRegion(region.toString())
.setSelfLink(selfLink)
.setStatus(status)
.setSubnetwork(subnetwork.toString())
.build();
mockService.addResponse(expectedResponse);
ProjectGlobalAddressName address = ProjectGlobalAddressName.of("[PROJECT]", "[ADDRESS]");
Address actualResponse = client.getGlobalAddress(address);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
@SuppressWarnings("all")
public void getGlobalAddressExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
ProjectGlobalAddressName address = ProjectGlobalAddressName.of("[PROJECT]", "[ADDRESS]");
client.getGlobalAddress(address);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void insertGlobalAddressTest() {
String clientOperationId = "clientOperationId-239630617";
String creationTimestamp = "creationTimestamp567396278";
String description = "description-1724546052";
String endTime = "endTime1725551537";
String httpErrorMessage = "httpErrorMessage1276263769";
Integer httpErrorStatusCode = 1386087020;
String id = "id3355";
String insertTime = "insertTime-103148397";
String kind = "kind3292052";
String name = "name3373707";
String operationType = "operationType-1432962286";
Integer progress = 1001078227;
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
String selfLink = "selfLink-1691268851";
String startTime = "startTime-1573145462";
String status = "status-892481550";
String statusMessage = "statusMessage-239442758";
String targetId = "targetId-815576439";
String targetLink = "targetLink-2084812312";
String user = "user3599307";
ProjectZoneName zone = ProjectZoneName.of("[PROJECT]", "[ZONE]");
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId(clientOperationId)
.setCreationTimestamp(creationTimestamp)
.setDescription(description)
.setEndTime(endTime)
.setHttpErrorMessage(httpErrorMessage)
.setHttpErrorStatusCode(httpErrorStatusCode)
.setId(id)
.setInsertTime(insertTime)
.setKind(kind)
.setName(name)
.setOperationType(operationType)
.setProgress(progress)
.setRegion(region.toString())
.setSelfLink(selfLink)
.setStartTime(startTime)
.setStatus(status)
.setStatusMessage(statusMessage)
.setTargetId(targetId)
.setTargetLink(targetLink)
.setUser(user)
.setZone(zone.toString())
.build();
mockService.addResponse(expectedResponse);
ProjectName project = ProjectName.of("[PROJECT]");
Address addressResource = Address.newBuilder().build();
Operation actualResponse = client.insertGlobalAddress(project, addressResource);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
@SuppressWarnings("all")
public void insertGlobalAddressExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
ProjectName project = ProjectName.of("[PROJECT]");
Address addressResource = Address.newBuilder().build();
client.insertGlobalAddress(project, addressResource);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
@SuppressWarnings("all")
public void listGlobalAddressesTest() {
String id = "id3355";
String kind = "kind3292052";
String nextPageToken = "";
String selfLink = "selfLink-1691268851";
Address itemsElement = Address.newBuilder().build();
List<Address> items = Arrays.asList(itemsElement);
AddressList expectedResponse =
AddressList.newBuilder()
.setId(id)
.setKind(kind)
.setNextPageToken(nextPageToken)
.setSelfLink(selfLink)
.addAllItems(items)
.build();
mockService.addResponse(expectedResponse);
ProjectName project = ProjectName.of("[PROJECT]");
ListGlobalAddressesPagedResponse pagedListResponse = client.listGlobalAddresses(project);
List<Address> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getItemsList().get(0), resources.get(0));
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
@SuppressWarnings("all")
public void listGlobalAddressesExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
ProjectName project = ProjectName.of("[PROJECT]");
client.listGlobalAddresses(project);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
}
|
3e1472919ca91ab9f88cc2f157d002699a274e68 | 3,300 | java | Java | aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/transform/ServiceStatisticsMarshaller.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-xray/src/main/java/com/amazonaws/services/xray/model/transform/ServiceStatisticsMarshaller.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-xray/src/main/java/com/amazonaws/services/xray/model/transform/ServiceStatisticsMarshaller.java | pgoranss/aws-sdk-java | 041ffc4197309c98c4be534b43ca2bda146e4f7c | [
"Apache-2.0"
] | 1 | 2019-07-22T16:24:05.000Z | 2019-07-22T16:24:05.000Z | 48.529412 | 156 | 0.760303 | 8,664 | /*
* 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.xray.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.xray.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ServiceStatisticsMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ServiceStatisticsMarshaller {
private static final MarshallingInfo<Long> OKCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("OkCount").build();
private static final MarshallingInfo<StructuredPojo> ERRORSTATISTICS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ErrorStatistics").build();
private static final MarshallingInfo<StructuredPojo> FAULTSTATISTICS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("FaultStatistics").build();
private static final MarshallingInfo<Long> TOTALCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("TotalCount").build();
private static final MarshallingInfo<Double> TOTALRESPONSETIME_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TotalResponseTime").build();
private static final ServiceStatisticsMarshaller instance = new ServiceStatisticsMarshaller();
public static ServiceStatisticsMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ServiceStatistics serviceStatistics, ProtocolMarshaller protocolMarshaller) {
if (serviceStatistics == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(serviceStatistics.getOkCount(), OKCOUNT_BINDING);
protocolMarshaller.marshall(serviceStatistics.getErrorStatistics(), ERRORSTATISTICS_BINDING);
protocolMarshaller.marshall(serviceStatistics.getFaultStatistics(), FAULTSTATISTICS_BINDING);
protocolMarshaller.marshall(serviceStatistics.getTotalCount(), TOTALCOUNT_BINDING);
protocolMarshaller.marshall(serviceStatistics.getTotalResponseTime(), TOTALRESPONSETIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
3e1472e3ea1d793ca10e112be07322304999c615 | 1,298 | java | Java | xml/relaxng/src/org/intellij/plugins/relaxNG/compact/formatting/RncFormattingModelBuilder.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | xml/relaxng/src/org/intellij/plugins/relaxNG/compact/formatting/RncFormattingModelBuilder.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | null | null | null | xml/relaxng/src/org/intellij/plugins/relaxNG/compact/formatting/RncFormattingModelBuilder.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 1 | 2020-10-15T05:56:42.000Z | 2020-10-15T05:56:42.000Z | 40.5625 | 130 | 0.798921 | 8,665 | /*
* Copyright 2007 Sascha Weinreuter
*
* 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.intellij.plugins.relaxNG.compact.formatting;
import com.intellij.formatting.FormattingContext;
import com.intellij.formatting.FormattingModel;
import com.intellij.formatting.FormattingModelBuilder;
import com.intellij.formatting.FormattingModelProvider;
import org.jetbrains.annotations.NotNull;
public class RncFormattingModelBuilder implements FormattingModelBuilder {
@Override
public @NotNull FormattingModel createModel(@NotNull FormattingContext formattingContext) {
return FormattingModelProvider.createFormattingModelForPsiFile(
formattingContext.getContainingFile(), new RncBlock(formattingContext.getNode()), formattingContext.getCodeStyleSettings());
}
} |
3e1473f1c8ebb185abe0bade29ace6ba33369579 | 6,722 | java | Java | src/org/plovr/AbstractGetHandler.java | bellau/plovr | f9592e5de4f74d1991bcd095ecc134a04705370e | [
"Apache-2.0"
] | 1 | 2015-03-27T10:31:30.000Z | 2015-03-27T10:31:30.000Z | src/org/plovr/AbstractGetHandler.java | bellau/plovr | f9592e5de4f74d1991bcd095ecc134a04705370e | [
"Apache-2.0"
] | null | null | null | src/org/plovr/AbstractGetHandler.java | bellau/plovr | f9592e5de4f74d1991bcd095ecc134a04705370e | [
"Apache-2.0"
] | null | null | null | 35.010417 | 96 | 0.650997 | 8,666 | package org.plovr;
import java.io.IOException;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
abstract class AbstractGetHandler implements HttpHandler {
private static final Logger logger = Logger.getLogger(
"org.plovr.AbstractGetHandler");
protected final CompilationServer server;
private final boolean usesRestfulPath;
AbstractGetHandler(CompilationServer server) {
this(server, false /* usesRestfulPath */);
}
/**
* @param server
* @param usesRestfulPath If true, then the config id will be specified by a
* query parameter named "id". If false, then the config id will be
* embedded in the URL as follows:
* http://localhost:9810/command_name/config_id/other/args?like=this
*/
AbstractGetHandler(CompilationServer server, boolean usesRestfulPath) {
this.server = server;
// TODO(bolinfest): Consider switching all handlers to use RESTful URLs.
this.usesRestfulPath = usesRestfulPath;
}
@Override
public final void handle(HttpExchange ex) throws IOException {
HttpExchangeDelegate exchange = new HttpExchangeDelegate(ex);
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
try {
QueryData queryData = QueryData.createFromUri(exchange.getRequestURI());
String id;
if (usesRestfulPath) {
id = parseConfigIdFromRestUri(exchange.getRequestURI());
} else {
id = queryData.getParam("id");
}
if (id == null) {
HttpUtil.writeNullResponse(exchange);
} else {
Config config = server.getConfigById(id);
if (config == null) {
HttpUtil.writeErrorMessageResponse(exchange,
"Unknown configuration id: " + id);
return;
}
// First, use query parameters from the script tag to update the config.
config = ConfigParser.update(config, queryData);
// Modify query parameters based on the referrer. This is more
// convenient for the developer, so it should be used to override
// the default settings.
URI referrer = HttpUtil.getReferrer(exchange);
if (referrer != null) {
QueryData referrerData = QueryData.createFromUri(referrer);
config = ConfigParser.update(config, referrerData);
}
// Set the cache headers
setCacheHeaders(exchange.getResponseHeaders());
doGet(exchange, queryData, config);
}
} catch (Throwable t) {
logger.log(Level.SEVERE, "Error during GET request to " + exchange.getRequestURI(), t);
// Even though there has been an error, it is important to write a
// response or else the client will hang.
if (exchange.haveResponseHeadersBeenSent()) {
// If the response headers have already been sent, then just close
// whatever has been written to the response.
try {
exchange.getResponseBody().close();
} catch (IOException e) {
// Let the user know, but don't take down plovr.
e.printStackTrace();
}
} else {
HttpUtil.writeErrorMessageResponse(exchange, t.getMessage());
}
}
}
}
/**
* Sets the cache headers to disable caching of resources.
* See http://code.google.com/p/doctype/wiki/ArticleHttpCaching
*/
protected void setCacheHeaders(Headers headers) {
DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
headers.set("Date", format.format(new Date()));
headers.set("Expires", "Fri, 01 Jan 1990 00:00:00 GMT");
headers.set("Pragma", "no-cache");
headers.set("Cache-control", "no-cache, must-revalidate");
}
/**
* Regex (as text) to match a config id. Stored as a string so it can be
* included in other regexes.
*/
static final String CONFIG_ID_PATTERN = "[\\w-]+";
/**
* Pattern used to select the handler name and config id from a plovr URI path.
* The first group is the handler name and the second group is the config id.
*/
private static final Pattern URI_ID_PATTERN = Pattern.compile(
"/(\\w+)/(" + CONFIG_ID_PATTERN + ")/.*");
@VisibleForTesting
static String parseConfigIdFromRestUri(URI uri) {
String path = uri.getPath();
Matcher matcher = URI_ID_PATTERN.matcher(path);
if (matcher.matches()) {
return matcher.group(2);
} else {
return null;
}
}
/**
* Successfully returns a {@link Compilation} (and records it as the latest
* {@link Compilation} for the config), or returns null, indicating that no
* {@link Compilation} could be found and that an error message was already
* written.
*/
protected final @Nullable Compilation getCompilation(
HttpExchange exchange, QueryData data, Config config) throws IOException{
final boolean recordCompilation = true;
return getCompilation(exchange, data, config, recordCompilation);
}
protected final @Nullable Compilation getCompilation(
HttpExchange exchange,
QueryData data,
Config config,
boolean recordCompilation) throws IOException {
// Make sure that RAW mode was not used.
CompilationMode mode = config.getCompilationMode();
if (mode == CompilationMode.RAW) {
HttpUtil.writeErrorMessageResponse(exchange,
"Not applicable for RAW mode");
return null;
}
// Make sure that this code has been compiled.
try {
return CompilationUtil.getCompilationOrFail(server, config, recordCompilation);
} catch (CompilationException e) {
logger.log(Level.SEVERE, "Error during compilation", e);
HttpUtil.writeNullResponse(exchange);
return null;
}
}
/**
* All parameters are guaranteed to be non-null.
* @param exchange
* @param data
* @param config
* @throws IOException
*/
protected abstract void doGet(HttpExchange exchange, QueryData data,
Config config) throws IOException;
}
|
3e147492bb3557f33139f50ded25f14c1a65bb22 | 8,541 | java | Java | samples/java/src/main/java/Anoncreds.java | phuctu1901/indy-sdk | f5d035177eb23900d56ab009cdb59dbd898483d4 | [
"Apache-2.0"
] | 636 | 2017-05-25T07:45:43.000Z | 2022-03-23T22:30:34.000Z | samples/java/src/main/java/Anoncreds.java | phuctu1901/indy-sdk | f5d035177eb23900d56ab009cdb59dbd898483d4 | [
"Apache-2.0"
] | 731 | 2017-05-29T07:15:08.000Z | 2022-03-31T07:55:58.000Z | samples/java/src/main/java/Anoncreds.java | phuctu1901/indy-sdk | f5d035177eb23900d56ab009cdb59dbd898483d4 | [
"Apache-2.0"
] | 904 | 2017-05-25T07:45:49.000Z | 2022-03-31T07:43:31.000Z | 45.430851 | 148 | 0.754947 | 8,667 | import org.hyperledger.indy.sdk.anoncreds.AnoncredsResults;
import org.hyperledger.indy.sdk.anoncreds.CredentialsSearchForProofReq;
import org.hyperledger.indy.sdk.pool.Pool;
import org.hyperledger.indy.sdk.wallet.Wallet;
import org.json.JSONArray;
import org.json.JSONObject;
import utils.PoolUtils;
import static org.hyperledger.indy.sdk.anoncreds.Anoncreds.*;
import static org.junit.Assert.*;
import static utils.PoolUtils.PROTOCOL_VERSION;
class Anoncreds {
static void demo() throws Exception {
System.out.println("Anoncreds sample -> started");
String issuerDid = "NcYxiDXkpYi6ov5FcYDi1e";
String proverDid = "VsKV7grR1BUE29mG2Fm2kX";
// Set protocol version 2 to work with Indy Node 1.4
Pool.setProtocolVersion(PROTOCOL_VERSION).get();
//1. Create and Open Pool
String poolName = PoolUtils.createPoolLedgerConfig();
Pool pool = Pool.openPoolLedger(poolName, "{}").get();
//2. Issuer Create and Open Wallet
String issuerWalletConfig = new JSONObject().put("id", "issuerWallet").toString();
String issuerWalletCredentials = new JSONObject().put("key", "issuer_wallet_key").toString();
Wallet.createWallet(issuerWalletConfig, issuerWalletCredentials).get();
Wallet issuerWallet = Wallet.openWallet(issuerWalletConfig, issuerWalletCredentials).get();
//3. Prover Create and Open Wallet
String proverWalletConfig = new JSONObject().put("id", "trusteeWallet").toString();
String proverWalletCredentials = new JSONObject().put("key", "prover_wallet_key").toString();
Wallet.createWallet(proverWalletConfig, proverWalletCredentials).get();
Wallet proverWallet = Wallet.openWallet(proverWalletConfig, proverWalletCredentials).get();
//4. Issuer Creates Credential Schema
String schemaName = "gvt";
String schemaVersion = "1.0";
String schemaAttributes = new JSONArray().put("name").put("age").put("sex").put("height").toString();
AnoncredsResults.IssuerCreateSchemaResult createSchemaResult =
issuerCreateSchema(issuerDid, schemaName, schemaVersion, schemaAttributes).get();
String schemaId = createSchemaResult.getSchemaId();
String schemaJson = createSchemaResult.getSchemaJson();
//5. Issuer create Credential Definition
String credDefTag = "Tag1";
String credDefConfigJson = new JSONObject().put("support_revocation", false).toString();
AnoncredsResults.IssuerCreateAndStoreCredentialDefResult createCredDefResult =
issuerCreateAndStoreCredentialDef(issuerWallet, issuerDid, schemaJson, credDefTag, null, credDefConfigJson).get();
String credDefId = createCredDefResult.getCredDefId();
String credDefJson = createCredDefResult.getCredDefJson();
//6. Prover create Master Secret
String masterSecretId = proverCreateMasterSecret(proverWallet, null).get();
//7. Issuer Creates Credential Offer
String credOffer = issuerCreateCredentialOffer(issuerWallet, credDefId).get();
//8. Prover Creates Credential Request
AnoncredsResults.ProverCreateCredentialRequestResult createCredReqResult =
proverCreateCredentialReq(proverWallet, proverDid, credOffer, credDefJson, masterSecretId).get();
String credReqJson = createCredReqResult.getCredentialRequestJson();
String credReqMetadataJson = createCredReqResult.getCredentialRequestMetadataJson();
//9. Issuer create Credential
// note that encoding is not standardized by Indy except that 32-bit integers are encoded as themselves. IS-786
String credValuesJson = new JSONObject()
.put("sex", new JSONObject().put("raw", "male").put("encoded", "594465709955896723921094925839488742869205008160769251991705001"))
.put("name", new JSONObject().put("raw", "Alex").put("encoded", "1139481716457488690172217916278103335"))
.put("height", new JSONObject().put("raw", "175").put("encoded", "175"))
.put("age", new JSONObject().put("raw", "28").put("encoded", "28"))
.toString();
AnoncredsResults.IssuerCreateCredentialResult createCredentialResult =
issuerCreateCredential(issuerWallet, credOffer, credReqJson, credValuesJson, null, - 1).get();
String credential = createCredentialResult.getCredentialJson();
//10. Prover Stores Credential
proverStoreCredential(proverWallet, null, credReqMetadataJson, credential, credDefJson, null).get();
//11. Prover Gets Credentials for Proof Request
String nonce = generateNonce().get();
String proofRequestJson = new JSONObject()
.put("nonce", nonce)
.put("name", "proof_req_1")
.put("version", "0.1")
.put("requested_attributes", new JSONObject()
.put("attr1_referent", new JSONObject().put("name", "name"))
.put("attr2_referent", new JSONObject().put("name", "sex"))
.put("attr3_referent", new JSONObject().put("name", "phone"))
)
.put("requested_predicates", new JSONObject()
.put("predicate1_referent", new JSONObject()
.put("name", "age")
.put("p_type", ">=")
.put("p_value", 18)
)
)
.toString();
CredentialsSearchForProofReq credentialsSearch = CredentialsSearchForProofReq.open(proverWallet, proofRequestJson, null).get();
JSONArray credentialsForAttribute1 = new JSONArray(credentialsSearch.fetchNextCredentials("attr1_referent", 100).get());
String credentialIdForAttribute1 = credentialsForAttribute1.getJSONObject(0).getJSONObject("cred_info").getString("referent");
JSONArray credentialsForAttribute2 = new JSONArray(credentialsSearch.fetchNextCredentials("attr2_referent", 100).get());
String credentialIdForAttribute2 = credentialsForAttribute2.getJSONObject(0).getJSONObject("cred_info").getString("referent");
JSONArray credentialsForAttribute3 = new JSONArray(credentialsSearch.fetchNextCredentials("attr3_referent", 100).get());
assertEquals(0, credentialsForAttribute3.length());
JSONArray credentialsForPredicate = new JSONArray(credentialsSearch.fetchNextCredentials("predicate1_referent", 100).get());
String credentialIdForPredicate = credentialsForPredicate.getJSONObject(0).getJSONObject("cred_info").getString("referent");
credentialsSearch.close();
//12. Prover Creates Proof
String selfAttestedValue = "8-800-300";
String requestedCredentialsJson = new JSONObject()
.put("self_attested_attributes", new JSONObject().put("attr3_referent", selfAttestedValue))
.put("requested_attributes", new JSONObject()
.put("attr1_referent", new JSONObject()
.put("cred_id", credentialIdForAttribute1)
.put("revealed", true)
)
.put("attr2_referent", new JSONObject()
.put("cred_id", credentialIdForAttribute2)
.put("revealed", false)
)
)
.put("requested_predicates", new JSONObject()
.put("predicate1_referent", new JSONObject()
.put("cred_id",credentialIdForPredicate)
)
)
.toString();
String schemas = new JSONObject().put(schemaId, new JSONObject(schemaJson)).toString();
String credentialDefs = new JSONObject().put(credDefId, new JSONObject(credDefJson)).toString();
String revocStates = new JSONObject().toString();
String proofJson = "";
try {
proofJson = proverCreateProof(proverWallet, proofRequestJson, requestedCredentialsJson,
masterSecretId, schemas, credentialDefs, revocStates).get();
} catch (Exception e){
System.out.println("");
}
JSONObject proof = new JSONObject(proofJson);
//13. Verifier verify Proof
JSONObject revealedAttr1 = proof.getJSONObject("requested_proof").getJSONObject("revealed_attrs").getJSONObject("attr1_referent");
assertEquals("Alex", revealedAttr1.getString("raw"));
assertNotNull(proof.getJSONObject("requested_proof").getJSONObject("unrevealed_attrs").getJSONObject("attr2_referent").getInt("sub_proof_index"));
assertEquals(selfAttestedValue, proof.getJSONObject("requested_proof").getJSONObject("self_attested_attrs").getString("attr3_referent"));
String revocRegDefs = new JSONObject().toString();
String revocRegs = new JSONObject().toString();
Boolean valid = verifierVerifyProof(proofRequestJson, proofJson, schemas, credentialDefs, revocRegDefs, revocRegs).get();
assertTrue(valid);
//14. Close and Delete issuer wallet
issuerWallet.closeWallet().get();
Wallet.deleteWallet(issuerWalletConfig, issuerWalletCredentials).get();
//15. Close and Delete prover wallet
proverWallet.closeWallet().get();
Wallet.deleteWallet(proverWalletConfig, proverWalletCredentials).get();
//16. Close pool
pool.closePoolLedger().get();
//17. Delete Pool ledger config
Pool.deletePoolLedgerConfig(poolName).get();
System.out.println("Anoncreds sample -> completed");
}
}
|
3e1474d88c111b21b32125936a6d0d105ca0b89b | 2,070 | java | Java | spring-boot-email-core/src/test/java/it/ozimov/springboot/mail/utils/StringUtilsTest.java | neesonqk/spring-boot-email-tools | 324551cc08919427e15d7d211b17d545c6e7a63d | [
"Apache-2.0"
] | 185 | 2016-03-12T14:07:55.000Z | 2021-11-30T04:56:50.000Z | spring-boot-email-core/src/test/java/it/ozimov/springboot/mail/utils/StringUtilsTest.java | neesonqk/spring-boot-email-tools | 324551cc08919427e15d7d211b17d545c6e7a63d | [
"Apache-2.0"
] | 78 | 2016-03-09T07:36:24.000Z | 2020-07-14T09:41:40.000Z | spring-boot-email-core/src/test/java/it/ozimov/springboot/mail/utils/StringUtilsTest.java | neesonqk/spring-boot-email-tools | 324551cc08919427e15d7d211b17d545c6e7a63d | [
"Apache-2.0"
] | 113 | 2016-04-24T08:55:54.000Z | 2022-01-05T10:02:26.000Z | 31.363636 | 109 | 0.688406 | 8,668 | /*
* Copyright 2012-2015 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 it.ozimov.springboot.mail.utils;
import org.assertj.core.api.JUnitSoftAssertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import static org.hamcrest.Matchers.*;
public class StringUtilsTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
public final JUnitSoftAssertions assertions = new JUnitSoftAssertions();
@Test
public void shouldBeUtilityClass() throws Exception {
//Arrange
Constructor<?> constructor = StringUtils.class.getDeclaredConstructor();
assertions.assertThat(Modifier.isPrivate(constructor.getModifiers()))
.as("Constructor of an Utility Class should be private")
.isTrue();
constructor.setAccessible(true);
expectedException.expectCause(
allOf(instanceOf(UnsupportedOperationException.class),
hasProperty("message", equalTo("This is a utility class and cannot be instantiated"))
));
//Act
constructor.newInstance();
}
@Test
public void shouldEmptyStringConstantNotChange() throws Exception {
//Act
String constant = StringUtils.EMPTY;
//Assert
assertions.assertThat(constant)
.isNotNull()
.isEmpty();
}
} |
3e147559476bb59e6090abb6d0b1d6a80e8aa081 | 7,213 | java | Java | app/src/main/java/com/semanadeeletronica/destincompleto/MainActivity.java | alinekborges/AndroidDestin | 326e80d04302fb73ece0ca436a0996b05dc73fd6 | [
"Apache-2.0"
] | 1 | 2015-02-02T14:40:49.000Z | 2015-02-02T14:40:49.000Z | app/src/main/java/com/semanadeeletronica/destincompleto/MainActivity.java | alinekborges/AndroidDestin | 326e80d04302fb73ece0ca436a0996b05dc73fd6 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/semanadeeletronica/destincompleto/MainActivity.java | alinekborges/AndroidDestin | 326e80d04302fb73ece0ca436a0996b05dc73fd6 | [
"Apache-2.0"
] | null | null | null | 37.567708 | 130 | 0.648829 | 8,669 | package com.semanadeeletronica.destincompleto;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.semanadeeletronica.destincompleto.adapter.ListAdapter;
import com.semanadeeletronica.destincompleto.model.Destination;
import com.semanadeeletronica.destincompleto.sample.SampleValues;
import com.semanadeeletronica.destincompleto.util.JSONDownloader;
import com.semanadeeletronica.destincompleto.util.Navigation;
import com.semanadeeletronica.destincompleto.util.Screen;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity extends Activity {
//region LAYOUT VARIABLES
//coloque aqui os layouts que precisam ser acessados via codigo
/* private TextView txt; */
private ListView listView;
private ArrayList<Destination> destinationList;
private Activity context;
//endregion
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponents();
}
/**
Inicializa os componentes de layout através de findViewById(R.id.xxx)
*/
private void initComponents() {
/* txt = (TextView) findViewById(R.id.txt);*/
listView = (ListView) findViewById(R.id.listView);
this.context = this;
// Infla o header e adiciona ao list view para deixar bonitinho :D
View header = getLayoutInflater().inflate(R.layout.list_header, null);
listView.addHeaderView(header);
//botoes de mudança de JSON e SAMPLE
final View github = header.findViewById(R.id.GITHUB);
final TextView json = (TextView) header.findViewById(R.id.JSON);
final TextView sample = (TextView) header.findViewById(R.id.SAMPLE);
header.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Navigation.navigate(context, Screen.Github, Navigation.Animation.GO);
}
});
github.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Navigation.navigate(context, Screen.Github, Navigation.Animation.GO);
}
});
json.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadTask().execute("");
json.setTextColor(getResources().getColor(android.R.color.white));
sample.setTextColor(getResources().getColor(R.color.gray));
}
});
sample.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sample.setTextColor(getResources().getColor(android.R.color.white));
json.setTextColor(getResources().getColor(R.color.gray));
destinationList = SampleValues.getDestinationsList();
ListAdapter adapter = new ListAdapter(context, destinationList);
listView.setAdapter(adapter);
listView.setDividerHeight(0);
//listener que escuta quando um item da lista é clicado
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Navigation.navigate(context, Screen.Detalhes, Navigation.Animation.GO, destinationList.get(position - 1));
}
});
}
});
//new DownloadTask().execute("");
//vou inicializar por padrao pelo sample
destinationList = SampleValues.getDestinationsList();
ListAdapter adapter = new ListAdapter(context, destinationList);
listView.setAdapter(adapter);
listView.setDividerHeight(0);
//listener que escuta quando um item da lista é clicado
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Navigation.navigate(context, Screen.Detalhes, Navigation.Animation.GO, destinationList.get(position-1));
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
Navigation.animate(this, Navigation.Animation.BACK);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public class DownloadTask extends AsyncTask<String, Long, ArrayList<Destination>> {
protected ArrayList<Destination> doInBackground(String... args) {
ArrayList<Destination> destinos = downloadDestinations();
return destinos;
}
@Override
protected void onPostExecute(ArrayList<Destination> result) {
destinationList = result;
ListAdapter adapter = new ListAdapter(context, destinationList);
listView.setAdapter(adapter);
listView.setDividerHeight(0);
//listener que escuta quando um item da lista é clicado
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Navigation.navigate(context, Screen.Detalhes, Navigation.Animation.GO, destinationList.get(position - 1));
}
});
}
protected ArrayList<Destination> downloadDestinations() {
Type destinosType = new TypeToken<ArrayList<Destination>>(){}.getType();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONDownloader downloader = new JSONDownloader();
String result = downloader.downloaderJSONArray("http://destino.herokuapp.com/destinos.json");
Log.i("Downloader", result);
ArrayList<Destination> destinations = null;
try {
destinations = gson.fromJson(result, destinosType);
} catch (Exception e) {
Log.i("Post parse", e.getMessage());
}
return destinations;
}
}
}
|
3e14770437bc32989de8f57fe6f00dc23f76e590 | 4,662 | java | Java | library/src/main/java/com/panxiaohe/springboard/library/FolderView.java | xiaohepan/springboardView | e78fc77bd1dd81a84c20b59591853b154b349f96 | [
"Apache-2.0"
] | 66 | 2016-03-26T11:20:38.000Z | 2021-12-13T08:19:00.000Z | library/src/main/java/com/panxiaohe/springboard/library/FolderView.java | xiaohepan/springboard | e78fc77bd1dd81a84c20b59591853b154b349f96 | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/panxiaohe/springboard/library/FolderView.java | xiaohepan/springboard | e78fc77bd1dd81a84c20b59591853b154b349f96 | [
"Apache-2.0"
] | 22 | 2016-03-27T12:37:10.000Z | 2020-07-31T07:30:13.000Z | 23.427136 | 104 | 0.589876 | 8,670 | package com.panxiaohe.springboard.library;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
/**
* Created by panxiaohe on 16/3/9.
* 展示文件夹的View
*/
public class FolderView extends SpringboardView
{
private boolean isOutOfFolder = false;
private MenuView parentLayout;
private FavoritesItem dragOutItem;
private int folderPosition;
public FolderView(Context context)
{
super(context);
}
public FolderView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public FolderView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
/**
* 判断是否手指移动到文件夹外边了
*/
public boolean moveOutFolder(int x, int y)
{
return x < 0 || y < 0 || x > getWidth() || y > getHeight();
}
@Override
public void onBeingDragging(MotionEvent event, float v)
{
int x = (int) event.getX();
int y = (int) event.getY();
if (!isOutOfFolder && moveOutFolder(x, y))
{
// Log.e("FolderLayout", "拖动中,拖出文件夹区域了");
getParentLayout().hideFolder();
dragOutItem = getAdapter().tempRemoveItem(folderPosition, temChangPosition);
isOutOfFolder = true;
dragPosition = -1;
}
if (v < getmMinimumVelocity())
{
if (isOutOfFolder)
{
parentLayout.dragOnChild(dragOutItem, event);
} else
{
if (dragPosition != -1 && temChangPosition != dragPosition)
{
// Log.e("FolderLayout", "交换位置 " + temChangPosition + " -->" + dragPosition);
onExchange();
}
countPageChange(x);
}
}
}
@Override
public void onDragFinished(MotionEvent event)
{
// int x = (int) event.getRawX();
// int y = (int) event.getRawY();
if (isOutOfFolder)
{
getParentLayout().onActionFolderClosed(dragOutItem, event);
} else
{
// Log.e("FolderLayout", "拖动结束,安置在" + temChangPosition + "位置");
getChildAt(temChangPosition).setVisibility(View.VISIBLE);
// setAnimationEnd();
// showDropAnimation(x, y);
}
}
@Override
public void onExchange()
{
getAdapter().exChangeSubItem(folderPosition, temChangPosition, dragPosition);
getChildAt(dragPosition).setVisibility(View.INVISIBLE);
temChangPosition = dragPosition;
}
@Override
public boolean ifCanMove(int position)
{
return true;
}
@Override
public boolean ifCanDelete(int position)
{
return getAdapter().ifCanDelete(folderPosition, position);
}
public MenuView getParentLayout()
{
return parentLayout;
}
public void setParentLayout(MenuView parentLayout)
{
this.parentLayout = parentLayout;
}
public int getFolderPosition()
{
return folderPosition;
}
public void setFolderPosition(int folderPosition)
{
this.folderPosition = folderPosition;
}
public void setAdapter(SpringboardAdapter mAdapter)
{
mAdapter.setFolderView(this);
super.setAdapter(mAdapter);
}
@Override
public void onItemClick(int position)
{
if (getAdapter().isEditting())
{
getAdapter().setEditing(false);
} else
{
if (getOnItemClickListener() != null)
{
getOnItemClickListener().onItemClick(getAdapter().getSubItem(folderPosition, position));
}
}
}
@Override
public int getItemCount()
{
return getAdapter().getSubItemCount(folderPosition);
}
@Override
public FrameLayout initItemView(int position)
{
FrameLayout view = mAdapter.initSubItemView(folderPosition, position, this);
mAdapter.configSubItemView(folderPosition, position, view);
return view;
}
@Override
public void onDelete(int position)
{
getAdapter().deleteItem(folderPosition, position);
computePageCountChange(false);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
{
getParentLayout().removeFolder();
return true;
}
return super.dispatchKeyEvent(event);
}
}
|
3e1478b8090f1c6a0f6f697dba9165b172451eb1 | 21,585 | java | Java | AL-Game/src/com/aionemu/gameserver/model/autogroup/AutoGroupType.java | karllgiovany/Aion-Lightning-4.9-SRC | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2019-09-24T23:26:34.000Z | 2019-09-24T23:26:34.000Z | AL-Game/src/com/aionemu/gameserver/model/autogroup/AutoGroupType.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | null | null | null | AL-Game/src/com/aionemu/gameserver/model/autogroup/AutoGroupType.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2017-12-28T16:59:47.000Z | 2017-12-28T16:59:47.000Z | 26.549815 | 106 | 0.570396 | 8,671 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning 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 for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.autogroup;
import com.aionemu.gameserver.dataholders.DataManager;
import java.util.List;
/**
* @author xTz
* @author GiGatR00n v4.7.5.x
*/
public enum AutoGroupType {
BARANATH_DREDGION(1, 600000, 12) {
@Override
AutoInstance newAutoInstance() {
return new AutoDredgionInstance();
}
},
CHANTRA_DREDGION(2, 600000, 12) {
@Override
AutoInstance newAutoInstance() {
return new AutoDredgionInstance();
}
},
TERATH_DREDGION(3, 600000, 12) {
@Override
AutoInstance newAutoInstance() {
return new AutoDredgionInstance();
}
},
ELYOS_FIRE_TEMPLE(4, 300000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
NOCHSANA_TRAINING_CAMP(5, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
DARK_POETA(6, 1200000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
STEEL_RAKE(7, 1200000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
UDAS_TEMPLE(8, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
LOWER_UDAS_TEMPLE(9, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
EMPYREAN_CRUCIBLE(11, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ASMODIANS_FIRE_TEMPLE(14, 300000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ARENA_OF_CHAOS_1(21, 110000, 8, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_CHAOS_2(22, 110000, 8, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_CHAOS_3(23, 110000, 8, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_DISCIPLINE_1(24, 110000, 2, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_DISCIPLINE_2(25, 110000, 2, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_DISCIPLINE_3(26, 110000, 2, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
CHAOS_TRAINING_GROUNDS_1(27, 110000, 8, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
CHAOS_TRAINING_GROUNDS_2(28, 110000, 8, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
CHAOS_TRAINING_GROUNDS_3(29, 110000, 8, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
DISCIPLINE_TRAINING_GROUNDS_1(30, 110000, 2, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
DISCIPLINE_TRAINING_GROUNDS_2(31, 110000, 2, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
DISCIPLINE_TRAINING_GROUNDS_3(32, 110000, 2, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_HARMONY_1(33, 110000, 6, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
ARENA_OF_HARMONY_2(34, 110000, 6, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
ARENA_OF_HARMONY_3(35, 110000, 6, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
ARENA_OF_GLORY_1(38, 110000, 4, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_CHAOS_4(39, 110000, 8, 4) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_DISCIPLINE_4(40, 110000, 2, 4) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
ARENA_OF_HARMONY_4(41, 110000, 6, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
ARENA_OF_GLORY_2(42, 110000, 4, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
CHAOS_TRAINING_GROUNDS_4(43, 110000, 8, 4) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
DISCIPLINE_TRAINING_GROUNDS_4(44, 110000, 2, 4) {
@Override
AutoInstance newAutoInstance() {
return new AutoPvPFFAInstance();
}
},
HARAMONIOUS_TRAINING_CENTER_4(45, 110000, 6, 4) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
HARAMONIOUS_TRAINING_CENTER_1(101, 110000, 6, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
HARAMONIOUS_TRAINING_CENTER_2(102, 110000, 6, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
HARAMONIOUS_TRAINING_CENTER_3(103, 110000, 6, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
UNITY_TRAINING_GROUNDS_1(104, 110000, 4, 1) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
UNITY_TRAINING_GROUNDS_2(105, 110000, 4, 2) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
UNITY_TRAINING_GROUNDS_3(106, 110000, 4, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoHarmonyInstance();
}
},
KAMAR_BATTLEFIELD(107, 600000, 24) {
@Override
AutoInstance newAutoInstance() {
return new AutoKamarBattlefieldInstance();
}
},
ENGULFED_OPHIDAN_BRIDGE(108, 600000, 12) {
@Override
AutoInstance newAutoInstance() {
return new AutoOphidanBridgeWarInstance();
}
},
IRON_WALL_WARFRONT(109, 600000, 48) {
@Override
AutoInstance newAutoInstance() {
return new AutoEternalBastionWarInstance();
}
},
IDGEL_DOME(111, 600000, 12) {
@Override
AutoInstance newAutoInstance() {
return new AutoIdgelDomeInstance();
}
},
UNSTABLE_ABYSSAL_SPLINTER_ELYOS(201, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
UNSTABLE_ABYSSAL_SPLINTER_ASMODIANS(206, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
FIRE_TEMPLE(302, 300000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
NOCHSANA_TRAINING_CAMP_2(303, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
DARK_POETA_2(304, 1200000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
THEOBOMOS_LAB(305, 1200000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ADMA_STRONGHOLD(306, 1200000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
DRAUPNIR_CAVE(307, 1200000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
STEEL_RAKE_2(308, 1200000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
UDAS_TEMPLE_2(309, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
LOWER_UDAS_TEMPLE_2(310, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
EMPYREAN_CRUCIBLE_2(311, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
RAKSANG(312, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
RENTUS_BASE(313, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
OPHIDAN_BRIDGE(314, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
INDRATU_FORTRESS(315, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
DANUAR_RELIQUARY(316, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
SAURO_MILITARY_SUPPLY_BASE(317, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
AETHEROGENETICS_LAB(318, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ELEMENTIS_FOREST(319, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ARGENT_MANOR(320, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
MUADA_TRENCHER(321, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
DRAGON_LORD_REFUGE(322, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ALQUIMIA_RESEARCH_CENTER(323, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
INFINITY_SHARD(324, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
IDGEL_RESEARCH_CENTER(325, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
VOID_CUBE(326, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
STEEL_ROSE_CARGO(327, 600000, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
STEEL_ROSE_QUARTERS(328, 600000, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
STEEL_ROSE_DECK(329, 600000, 3) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
NIGHTMARE_CIRCUS(330, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
BESHMUNDIR_TEMPLE_NORMAL(331, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
BESHMUNDIR_TEMPLE_HARD(332, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
TIAMAT_STRONGHOLD(333, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
AZOTURAN_FORTRESS(334, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ETERNAL_BASTION(335, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
DANUAR_SANCTUARY(336, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
RUKIBUKI_CIRCUS_TROUPE_CAMP(337, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
ILLUMINARY_OBELISK(338, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
SHUGO_IMPERIAL_TOMB(339, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
LUCKY_OPHIDAN_BRIDGE(340, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
},
LUCKY_DANUAR_RELIQUARY(341, 600000, 6) {
@Override
AutoInstance newAutoInstance() {
return new AutoGeneralInstance();
}
};
private int instanceMaskId;
private int time;
private byte playerSize;
private byte difficultId;
private AutoGroup template;
private AutoGroupType(int instanceMaskId, int time, int playerSize, int difficultId) {
this(instanceMaskId, time, playerSize);
this.difficultId = (byte) difficultId;
}
private AutoGroupType(int instanceMaskId, int time, int playerSize) {
this.instanceMaskId = instanceMaskId;
this.time = time;
this.playerSize = (byte) playerSize;
template = DataManager.AUTO_GROUP.getTemplateByInstaceMaskId(this.instanceMaskId);
}
public int getInstanceMapId() {
return template.getInstanceId();
}
public byte getPlayerSize() {
return playerSize;
}
public int getInstanceMaskId() {
return instanceMaskId;
}
public int getNameId() {
return template.getNameId();
}
public int getTittleId() {
return template.getTitleId();
}
public int getTime() {
return time;
}
public int getMinLevel() {
return template.getMinLvl();
}
public int getMaxLevel() {
return template.getMaxLvl();
}
public boolean hasRegisterGroup() {
return template.hasRegisterGroup();
}
public boolean hasRegisterQuick() {
return template.hasRegisterQuick();
}
public boolean hasRegisterNew() {
return template.hasRegisterNew();
}
public boolean containNpcId(int npcId) {
return template.getNpcIds().contains(npcId);
}
public List<Integer> getNpcIds() {
return template.getNpcIds();
}
public boolean isDredgion() {
switch (this) {
case BARANATH_DREDGION:
case CHANTRA_DREDGION:
case TERATH_DREDGION:
return true;
default:
break;
}
return false;
}
public static AutoGroupType getAGTByMaskId(int instanceMaskId) {
for (AutoGroupType autoGroupsType : values()) {
if (autoGroupsType.getInstanceMaskId() == instanceMaskId) {
return autoGroupsType;
}
}
return null;
}
public static AutoGroupType getAutoGroup(int level, int npcId) {
for (AutoGroupType agt : values()) {
if (agt.hasLevelPermit(level) && agt.containNpcId(npcId)) {
return agt;
}
}
return null;
}
public static AutoGroupType getAutoGroupByWorld(int level, int worldId) {
for (AutoGroupType agt : values()) {
if (agt.getInstanceMapId() == worldId && agt.hasLevelPermit(level)) {
return agt;
}
}
return null;
}
public static AutoGroupType getAutoGroup(int npcId) {
for (AutoGroupType agt : values()) {
if (agt.containNpcId(npcId)) {
return agt;
}
}
return null;
}
public boolean isPvPSoloArena() {
switch (this) {
case ARENA_OF_DISCIPLINE_1:
case ARENA_OF_DISCIPLINE_2:
case ARENA_OF_DISCIPLINE_3:
case ARENA_OF_DISCIPLINE_4:
return true;
default:
break;
}
return false;
}
public boolean isTrainingPvPSoloArena() {
switch (this) {
case DISCIPLINE_TRAINING_GROUNDS_1:
case DISCIPLINE_TRAINING_GROUNDS_2:
case DISCIPLINE_TRAINING_GROUNDS_3:
case DISCIPLINE_TRAINING_GROUNDS_4:
return true;
default:
break;
}
return false;
}
public boolean isPvPFFAArena() {
switch (this) {
case ARENA_OF_CHAOS_1:
case ARENA_OF_CHAOS_2:
case ARENA_OF_CHAOS_3:
case ARENA_OF_CHAOS_4:
return true;
default:
break;
}
return false;
}
public boolean isTrainingPvPFFAArena() {
switch (this) {
case CHAOS_TRAINING_GROUNDS_1:
case CHAOS_TRAINING_GROUNDS_2:
case CHAOS_TRAINING_GROUNDS_3:
case CHAOS_TRAINING_GROUNDS_4:
return true;
default:
break;
}
return false;
}
public boolean isTrainingHarmonyArena() {
switch (this) {
case HARAMONIOUS_TRAINING_CENTER_1:
case HARAMONIOUS_TRAINING_CENTER_2:
case HARAMONIOUS_TRAINING_CENTER_3:
case HARAMONIOUS_TRAINING_CENTER_4:
case UNITY_TRAINING_GROUNDS_1:
case UNITY_TRAINING_GROUNDS_2:
case UNITY_TRAINING_GROUNDS_3:
return true;
default:
break;
}
return false;
}
public boolean isHarmonyArena() {
switch (this) {
case ARENA_OF_HARMONY_1:
case ARENA_OF_HARMONY_2:
case ARENA_OF_HARMONY_3:
case ARENA_OF_HARMONY_4:
return true;
default:
break;
}
return false;
}
public boolean isGloryArena() {
switch (this) {
case ARENA_OF_GLORY_1:
case ARENA_OF_GLORY_2:
return true;
default:
break;
}
return false;
}
public boolean isKamar() {
switch (this) {
case KAMAR_BATTLEFIELD:
return true;
default:
break;
}
return false;
}
public boolean isOphidan() {
switch (this) {
case ENGULFED_OPHIDAN_BRIDGE:
return true;
default:
break;
}
return false;
}
public boolean isIronWall() {
switch (this) {
case IRON_WALL_WARFRONT:
return true;
default:
break;
}
return false;
}
public boolean isIdgelDome() {
switch (this) {
case IDGEL_DOME:
return true;
default:
break;
}
return false;
}
public boolean isPvpArena() {
return isTrainingPvPFFAArena() || isPvPFFAArena() || isTrainingPvPSoloArena() || isPvPSoloArena();
}
public boolean hasLevelPermit(int level) {
return level >= getMinLevel() && level <= getMaxLevel();
}
public byte getDifficultId() {
return difficultId;
}
public AutoInstance getAutoInstance() {
return newAutoInstance();
}
abstract AutoInstance newAutoInstance();
}
|
3e1478d2cc953a9da575ddc5a3989f44b3f4cd2c | 1,813 | java | Java | gulimall-product/src/main/java/com/clay/gulimall/product/service/impl/AttrGroupServiceImpl.java | abcdaaaaaaaaaaaaaaaaaaaaaaa/gulimall | 2f4e56308df77d0b94148f82b6a14be9751e50c5 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/clay/gulimall/product/service/impl/AttrGroupServiceImpl.java | abcdaaaaaaaaaaaaaaaaaaaaaaa/gulimall | 2f4e56308df77d0b94148f82b6a14be9751e50c5 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/clay/gulimall/product/service/impl/AttrGroupServiceImpl.java | abcdaaaaaaaaaaaaaaaaaaaaaaa/gulimall | 2f4e56308df77d0b94148f82b6a14be9751e50c5 | [
"Apache-2.0"
] | 1 | 2022-03-21T09:42:48.000Z | 2022-03-21T09:42:48.000Z | 40.288889 | 127 | 0.732488 | 8,672 | package com.clay.gulimall.product.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clay.gulimall.common.utils.PageUtils;
import com.clay.gulimall.common.utils.Query;
import com.clay.gulimall.product.dao.AttrGroupDao;
import com.clay.gulimall.product.entity.AttrGroupEntity;
import com.clay.gulimall.product.service.AttrGroupService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<AttrGroupEntity> page = this.page(
Query.page(params, AttrGroupEntity.class),
new QueryWrapper<AttrGroupEntity>()
);
return new PageUtils(page);
}
@Override
public PageUtils queryPage(Map<String, Object> params, Long logId) {
String key = params.getOrDefault("key", StringUtils.EMPTY).toString();
LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<>();
if (logId != null && logId != 0) {
wrapper.eq(AttrGroupEntity::getCatelogId, logId);
}
if (StringUtils.isNotBlank(key)) {
wrapper.and(obj -> obj.eq(AttrGroupEntity::getAttrGroupId, key).or().like(AttrGroupEntity::getAttrGroupName, key));
}
IPage<AttrGroupEntity> page = this.page(Query.page(params, AttrGroupEntity.class), wrapper);
return new PageUtils(page);
}
} |
3e14795293964e94b71e1f5f11304695fbcf7417 | 1,250 | java | Java | datasketches-memory-java8/src/main/java/org/apache/datasketches/memory/ReadOnlyException.java | apache/incubator-datasketches-memory | 67d7244b7a95ae3deffc0e9c8a69927a5f7461e1 | [
"Apache-2.0"
] | 24 | 2019-05-21T17:39:23.000Z | 2020-12-16T13:19:13.000Z | datasketches-memory-java8/src/main/java/org/apache/datasketches/memory/ReadOnlyException.java | apache/datasketches-memory | b981fdf9f1f1af3d18d41d7b79c4f62460c7156e | [
"Apache-2.0"
] | 17 | 2021-01-22T23:19:38.000Z | 2022-02-03T06:19:09.000Z | datasketches-memory-java8/src/main/java/org/apache/datasketches/memory/ReadOnlyException.java | apache/datasketches-memory | b981fdf9f1f1af3d18d41d7b79c4f62460c7156e | [
"Apache-2.0"
] | 10 | 2021-02-18T20:09:42.000Z | 2022-03-19T11:15:48.000Z | 32.051282 | 75 | 0.7328 | 8,673 | /*
* 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.datasketches.memory;
/**
* The exception thrown when attempting to write into a read-only Resource.
*
* @author Praveenkumar Venkatesan
*/
public class ReadOnlyException extends MemoryException {
private static final long serialVersionUID = 1L;
/**
* Read Only Exception
* @param message the error message
*/
public ReadOnlyException(final String message) {
super(message);
}
}
|
3e147a01fa6361b207c862d082b4f7af6f7864b0 | 1,046 | java | Java | chat-server/project/src/org/flamering/sample/chat/room/message/ExitRoomRequest.java | joelam789/flame-ring-sample | 6ef9cfbe5f634903d19077f54c9e79b60d7ff7cc | [
"Apache-2.0"
] | null | null | null | chat-server/project/src/org/flamering/sample/chat/room/message/ExitRoomRequest.java | joelam789/flame-ring-sample | 6ef9cfbe5f634903d19077f54c9e79b60d7ff7cc | [
"Apache-2.0"
] | null | null | null | chat-server/project/src/org/flamering/sample/chat/room/message/ExitRoomRequest.java | joelam789/flame-ring-sample | 6ef9cfbe5f634903d19077f54c9e79b60d7ff7cc | [
"Apache-2.0"
] | null | null | null | 20.115385 | 53 | 0.732314 | 8,674 | package org.flamering.sample.chat.room.message;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ExitRoomRequest {
private String messageName = "ExitRoomRequest";
private String userName = "";
private String userToken = "";
private String roomName = "";
@JsonProperty("msg")
public String getMessageName() {
return messageName;
}
@JsonProperty("msg")
public void setMessageName(String messageName) {
this.messageName = messageName;
}
@JsonProperty("user_name")
public String getUserName() {
return userName;
}
@JsonProperty("user_name")
public void setUserName(String userName) {
this.userName = userName;
}
@JsonProperty("user_token")
public String getUserToken() {
return userToken;
}
@JsonProperty("user_token")
public void setUserToken(String userToken) {
this.userToken = userToken;
}
@JsonProperty("room_name")
public String getRoomName() {
return roomName;
}
@JsonProperty("room_name")
public void setRoomName(String roomName) {
this.roomName = roomName;
}
}
|
3e147a025271545f7f8a155d8f68bd5d1fb8709e | 1,478 | java | Java | app/src/main/java/com/zhcw/app/ExternalApp.java | ycyangchun/TemplateAppProject | 95d10220861081f24a7eee46e2e373ce33250137 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zhcw/app/ExternalApp.java | ycyangchun/TemplateAppProject | 95d10220861081f24a7eee46e2e373ce33250137 | [
"Apache-2.0"
] | 1 | 2020-11-09T01:31:59.000Z | 2020-11-09T02:18:33.000Z | app/src/main/java/com/zhcw/app/ExternalApp.java | ycyangchun/TemplateAppProject | 95d10220861081f24a7eee46e2e373ce33250137 | [
"Apache-2.0"
] | null | null | null | 32.173913 | 180 | 0.726351 | 8,675 | /*
* Copyright (C) 2018 xuexiangjys(lyhxr@example.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.zhcw.app;
import android.app.Application;
import com.xuexiang.xormlite.ExternalDataBaseRepository;
import com.xuexiang.xormlite.annotation.DataBase;
import com.xuexiang.xormlite.enums.DataBaseType;
import com.zhcw.lib.db.ExternalDataBase;
/**
* <pre>
* desc : 外部存储的数据库
* author : xuexiang
* time : 2018/5/9 下午11:44
* </pre>
*/
@DataBase(name = "external", type = DataBaseType.EXTERNAL, path = "/storage/emulated/0/zhcwLib/databases")
public class ExternalApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ExternalDataBaseRepository.getInstance()
.setIDatabase(new ExternalDataBase(ExternalDataBaseRepository.DATABASE_PATH, ExternalDataBaseRepository.DATABASE_NAME, ExternalDataBaseRepository.DATABASE_VERSION))
.init(this);
}
}
|
3e147a13a1454b5432e46dd30705d1fab0010f40 | 561 | java | Java | src/test/java/com/fishercoder/_1790Test.java | Ildar10/Leetcode | f0bfc2f9077194576a996a6f8c581a4066e53175 | [
"Apache-2.0"
] | 3,508 | 2016-12-07T18:36:12.000Z | 2022-03-31T12:31:33.000Z | src/test/java/com/fishercoder/_1790Test.java | frankfanslc/Leetcode-5 | 3499e48b095a9d237ca1d8aee2010e15559ad41d | [
"Apache-2.0"
] | 62 | 2017-08-08T19:52:13.000Z | 2021-09-04T17:10:25.000Z | src/test/java/com/fishercoder/_1790Test.java | frankfanslc/Leetcode-5 | 3499e48b095a9d237ca1d8aee2010e15559ad41d | [
"Apache-2.0"
] | 1,389 | 2016-12-07T19:09:40.000Z | 2022-03-27T06:31:14.000Z | 20.035714 | 69 | 0.672014 | 8,676 | package com.fishercoder;
import com.fishercoder.solutions._1790;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class _1790Test {
private static _1790.Solution1 solution1;
@BeforeClass
public static void setup() {
solution1 = new _1790.Solution1();
}
@Test
public void test1() {
assertEquals(false, solution1.areAlmostEqual("a", "z"));
}
@Test
public void test2() {
assertEquals(true, solution1.areAlmostEqual("bank", "kanb"));
}
}
|
3e147a78657248eb1128a3aa5b665d943dd3d02c | 2,092 | java | Java | src/main/java/wicketforge/psi/WicketReferenceContributor.java | wicketforge/wicketforge | 99e0bc61ecced7fa0eb1b677b20658793b9512e6 | [
"Apache-2.0"
] | 14 | 2017-05-30T20:39:18.000Z | 2021-08-12T22:34:47.000Z | src/main/java/wicketforge/psi/WicketReferenceContributor.java | wicketforge/wicketforge | 99e0bc61ecced7fa0eb1b677b20658793b9512e6 | [
"Apache-2.0"
] | 10 | 2017-07-11T12:17:06.000Z | 2021-12-10T10:25:27.000Z | src/main/java/wicketforge/psi/WicketReferenceContributor.java | wicketforge/wicketforge | 99e0bc61ecced7fa0eb1b677b20658793b9512e6 | [
"Apache-2.0"
] | 7 | 2017-10-13T16:56:22.000Z | 2021-08-05T08:42:19.000Z | 43.583333 | 198 | 0.735182 | 8,677 | /*
* Copyright 2010 The WicketForge-Team
*
* 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 wicketforge.psi;
import com.intellij.patterns.*;
import com.intellij.psi.*;
import org.jetbrains.kotlin.idea.patterns.KotlinPatterns;
import org.jetbrains.kotlin.psi.KtParameter;
import wicketforge.Constants;
import wicketforge.psi.references.ClassWicketIdReferenceProvider;
import wicketforge.psi.references.MarkupWicketIdReferenceProvider;
/**
*/
public class WicketReferenceContributor extends PsiReferenceContributor {
@Override
public void registerReferenceProviders(PsiReferenceRegistrar registrar) {
{// java -> new Component("..." ...)
ElementPattern<PsiLiteralExpression> pattern = StandardPatterns.or(
//
PsiJavaPatterns.psiElement(PsiLiteralExpression.class).withParent(PsiExpressionList.class).withSuperParent(2, PsiCallExpression.class),
// for Anonymous create like Link's...
PsiJavaPatterns.psiElement(PsiLiteralExpression.class).withParent(PsiExpressionList.class).withSuperParent(2, PsiAnonymousClass.class).withSuperParent(3, PsiCallExpression.class)
);
registrar.registerReferenceProvider(pattern, new ClassWicketIdReferenceProvider());
}
{// html -> wicket:id
XmlAttributeValuePattern pattern = XmlPatterns.xmlAttributeValue(XmlPatterns.xmlAttribute().withName(Constants.WICKET_ID));
registrar.registerReferenceProvider(pattern, new MarkupWicketIdReferenceProvider());
}
}
}
|
3e147c30df338429b644677ae954a74fb3ec0b8f | 20,667 | java | Java | core/src/main/java/nl/nn/adapterframework/pipes/AbstractPipe.java | thomasverweij/iaf | 086f7fbae1d9ed8b9dee1024e50dc71076065755 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/nl/nn/adapterframework/pipes/AbstractPipe.java | thomasverweij/iaf | 086f7fbae1d9ed8b9dee1024e50dc71076065755 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/nl/nn/adapterframework/pipes/AbstractPipe.java | thomasverweij/iaf | 086f7fbae1d9ed8b9dee1024e50dc71076065755 | [
"Apache-2.0"
] | null | null | null | 33.769608 | 464 | 0.741907 | 8,678 | /*
Copyright 2013, 2016 Nationale-Nederlanden, 2020-2021 WeAreFrank!
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 nl.nn.adapterframework.pipes;
import java.lang.reflect.Field;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import lombok.Getter;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.configuration.ConfigurationWarnings;
import nl.nn.adapterframework.core.Adapter;
import nl.nn.adapterframework.core.DummyNamedObject;
import nl.nn.adapterframework.core.IConfigurable;
import nl.nn.adapterframework.core.IExtendedPipe;
import nl.nn.adapterframework.core.IPipe;
import nl.nn.adapterframework.core.IPipeLineSession;
import nl.nn.adapterframework.core.PipeForward;
import nl.nn.adapterframework.core.PipeLine;
import nl.nn.adapterframework.core.PipeLineExit;
import nl.nn.adapterframework.core.PipeRunException;
import nl.nn.adapterframework.core.PipeRunResult;
import nl.nn.adapterframework.core.PipeStartException;
import nl.nn.adapterframework.core.TransactionAttributes;
import nl.nn.adapterframework.doc.IbisDoc;
import nl.nn.adapterframework.monitoring.EventHandler;
import nl.nn.adapterframework.monitoring.EventThrowing;
import nl.nn.adapterframework.monitoring.MonitorManager;
import nl.nn.adapterframework.parameters.Parameter;
import nl.nn.adapterframework.parameters.ParameterList;
import nl.nn.adapterframework.stream.Message;
import nl.nn.adapterframework.util.AppConstants;
import nl.nn.adapterframework.util.Locker;
import nl.nn.adapterframework.util.SpringUtils;
import nl.nn.adapterframework.util.XmlUtils;
/**
* Base class for {@link IPipe Pipe}.
* A Pipe represents an action to take in a {@link PipeLine Pipeline}. This class is meant to be extended
* for defining steps or actions to take to complete a request. <br/>
* The contract is that a pipe is created (by the digester), {@link #setName(String)} is called and
* other setters are called, and then {@link IPipe#configure()} is called, optionally
* throwing a {@link ConfigurationException}. <br/>
* As much as possible, class instantiating should take place in the
* {@link IPipe#configure()} method.
* The object remains alive while the framework is running. When the pipe is to be run,
* the {@link IPipe#doPipe(Message, IPipeLineSession) doPipe} method is activated.
* <p>
* For the duration of the processing of a message by the {@link PipeLine pipeline} has a {@link IPipeLineSession pipeLineSession}.
* <br/>
* By this mechanism, pipes may communicate with one another.<br/>
* However, use this functionality with caution, as it is not desirable to make pipes dependent
* on each other. If a pipe expects something in a session, it is recommended that
* the key under which the information is stored is configurable (has a setter for this keyname).
* Also, the setting of something in the <code>PipeLineSession</code> should be done using
* this technique (specifying the key under which to store the value by a parameter).
* </p>
* <p>Since 4.1 this class also has parameters, so that descendants of this class automatically are parameter-enabled.
* However, your documentation should say if and how parameters are used!<p>
* <p> All pipes support a forward named 'exception' which will be followed in the pipeline in case the PipeRunExceptions are not handled by the pipe itself<p>
* <tr><td>{@link #setWriteToSecLog (boolean) writeToSecLog}</td><td>when set to <code>true</code> a record is written to the security log when the pipe has finished successfully</td><td>false</td></tr>
* <tr><td>{@link #setSecLogSessionKeys(String) secLogSessionKeys}</td><td>(only used when <code>writeToSecLog=true</code>) comma separated list of keys of session variables that is appended to the security log record</td><td> </td></tr>
* <tr><td>{@link #setLogIntermediaryResults (String) logIntermediaryResults}</td><td>when set, the value in AppConstants is overwritten (for this pipe only)</td><td> </td></tr>
* <tr><td>{@link #setHideRegex(String) hideRegex}</td><td>Regular expression to mask strings in the log. For example, the regular expression <code>(?<=<password>).*?(?=</password>)</code> will replace every character between keys '<password>' and '</password>'. <b>Note:</b> this feature is used at adapter level, so one pipe affects all pipes in the pipeline (and multiple values in different pipes are merged)</td><td> </td></tr>
* </table>
* </p>
*
* <p>
* <table border="1">
* <tr><th>nested elements</th><th>description</th></tr>
* <tr><td>{@link Locker locker}</td><td>optional: the pipe will only be executed if a lock could be set successfully</td></tr>
* </table>
* </p>
*
* @author Johan Verrips / Gerrit van Brakel
*
* @see IPipeLineSession
*/
public abstract class AbstractPipe extends TransactionAttributes implements IExtendedPipe, EventThrowing, IConfigurable, ApplicationContextAware {
private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader();
private @Getter ApplicationContext applicationContext;
private String name;
private String getInputFromSessionKey=null;
private String getInputFromFixedValue=null;
private String storeResultInSessionKey=null;
private boolean preserveInput=false;
private int maxThreads = 0;
private long durationThreshold = -1;
private String chompCharSize = null;
private String elementToMove = null;
private String elementToMoveSessionKey = null;
private String elementToMoveChain = null;
private boolean removeCompactMsgNamespaces = true;
private boolean restoreMovedElements=false;
private boolean namespaceAware=XmlUtils.isNamespaceAwareByDefault();
private boolean sizeStatistics = AppConstants.getInstance(configurationClassLoader).getBoolean("statistics.size", false);
private Locker locker;
private String emptyInputReplacement=null;
private boolean writeToSecLog = false;
private String secLogSessionKeys = null;
private String logIntermediaryResults = null;
private String hideRegex = null;
private boolean active=true;
private Map<String, PipeForward> pipeForwards = new Hashtable<String, PipeForward>();
private ParameterList parameterList = new ParameterList();
private EventHandler eventHandler=null;
private PipeLine pipeline;
private DummyNamedObject inSizeStatDummyObject=null;
private DummyNamedObject outSizeStatDummyObject=null;
public AbstractPipe() {
inSizeStatDummyObject = new DummyNamedObject();
outSizeStatDummyObject = new DummyNamedObject();
}
/**
* <code>configure()</code> is called after the {@link PipeLine Pipeline} is registered
* at the {@link Adapter Adapter}. Purpose of this method is to reduce
* creating connections to databases etc. in the {@link #doPipe(Message, IPipeLineSession) doPipe()} method.
* As much as possible class-instantiating should take place in the
* <code>configure()</code> method, to improve performance.
*/
@Override
public void configure() throws ConfigurationException {
ParameterList params = getParameterList();
if (params!=null) {
try {
params.configure();
} catch (ConfigurationException e) {
throw new ConfigurationException(getLogPrefix(null)+"while configuring parameters",e);
}
}
if (!StringUtils.isEmpty(getElementToMove()) && !StringUtils.isEmpty(getElementToMoveChain())) {
throw new ConfigurationException("cannot have both an elementToMove and an elementToMoveChain specified");
}
if (pipeForwards.isEmpty()) {
//TODO pipe will follow the next forward no need to show warning
ConfigurationWarnings.add(this, log, "has no pipe forwards defined");
} else {
for (Iterator<String> it = pipeForwards.keySet().iterator(); it.hasNext();) {
String forwardName = it.next();
PipeForward forward= pipeForwards.get(forwardName);
if (forward!=null) {
String path=forward.getPath();
if (path!=null) {
PipeLineExit plExit= pipeline.getPipeLineExits().get(path);
if (plExit==null){
if (pipeline.getPipe(path)==null){
ConfigurationWarnings.add(this, log, "has a forward of which the pipe to execute ["+path+"] is not defined");
}
}
}
}
}
}
if (getLocker() != null) {
getLocker().configure();
}
eventHandler = MonitorManager.getEventHandler();
super.configure();
}
/**
* Extension for IExtendedPipe that calls configure(void) in its implementation.
*/
@Override
public void configure(PipeLine pipeline) throws ConfigurationException {
this.pipeline=pipeline;
configure();
}
/**
* final method to ensure nobody overrides this...
*/
@Override
public final void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
protected <T> T createBean(Class<T> beanClass) {
return SpringUtils.createBean(applicationContext, beanClass);
}
/**
* This is where the action takes place. Pipes may only throw a PipeRunException,
* to be handled by the caller of this object.
*/
@Override
public abstract PipeRunResult doPipe (Message message, IPipeLineSession session) throws PipeRunException;
/**
* looks up a key in the pipeForward hashtable. <br/>
* A typical use would be on return from a Pipe: <br/>
* <code><pre>
* return new PipeRunResult(findForward("success"), result);
* </pre></code>
* In the pipeForward hashtable are available:
* <ul><li>All forwards defined in xml under the pipe element of this pipe</li>
* <li> All global forwards defined in xml under the PipeLine element</li>
* <li> All pipenames with their (identical) path</li>
* </ul>
* Therefore, you can directly jump to another pipe, although this is not recommended
* as the pipe should not know the existence of other pipes. Nevertheless, this feature
* may come in handy for switcher-pipes.<br/><br/>
* @param forward Name of the forward
* @return PipeForward
*/
//TODO: Create a 2nd findForwards method without all pipes in the hashtable and make the first one deprecated.
public PipeForward findForward(String forward){
if (StringUtils.isEmpty(forward)) {
return null;
}
return pipeForwards.get(forward);
}
@Override
public Map<String, PipeForward> getForwards(){
Map<String, PipeForward> forwards = new Hashtable<String, PipeForward>(pipeForwards);
PipeLine pipeline = getPipeLine();
if (pipeline==null) {
return null;
}
List<IPipe> pipes = pipeline.getPipes();
for (int i=0; i<pipes.size(); i++) {
String pipeName = pipes.get(i).getName();
if(forwards.containsKey(pipeName))
forwards.remove(pipeName);
}
return forwards;
}
/**
* Convenience method for building up log statements.
* This method may be called from within the <code>doPipe()</code> method with the current <code>PipeLineSession</code>
* as a parameter. Then it will use this parameter to retrieve the messageId. The method can be called with a <code>null</code> parameter
* from the <code>configure()</code>, <code>start()</code> and <code>stop()</code> methods.
* @return String with the name of the pipe and the message id of the current message.
*/
protected String getLogPrefix(IPipeLineSession session) {
StringBuilder sb = new StringBuilder();
sb.append("Pipe ["+getName()+"] ");
if (session!=null) {
sb.append("msgId ["+session.getMessageId()+"] ");
}
return sb.toString();
}
/**
* Register a PipeForward object to this Pipe. Global Forwards are added
* by the PipeLine. If a forward is already registered, it logs a warning.
* @see PipeLine
* @see PipeForward
*/
@Override
@IbisDoc({"30"})
public void registerForward(PipeForward forward) {
PipeForward current = pipeForwards.get(forward.getName());
if (current==null){
pipeForwards.put(forward.getName(), forward);
} else {
if (forward.getPath()!=null && forward.getPath().equals(current.getPath())) {
ConfigurationWarnings.add(this, log, "has forward ["+forward.getName()+"] which is already registered");
} else {
log.info(getLogPrefix(null)+"PipeForward ["+forward.getName()+"] already registered, pointing to ["+current.getPath()+"]. Ignoring new one, that points to ["+forward.getPath()+"]");
}
}
}
/**
* Perform necessary action to start the pipe. This method is executed
* after the {@link #configure()} method, for each start and stop command of the
* adapter.
*/
@Override
public void start() throws PipeStartException {
// if (getTransactionAttributeNum()>0 && getTransactionAttributeNum()!=JtaUtil.TRANSACTION_ATTRIBUTE_SUPPORTS) {
// try {
// // getUserTransaction, to make sure its available
// JtaUtil.getUserTransaction();
// } catch (NamingException e) {
// throw new PipeStartException(getLogPrefix(null)+"cannot obtain UserTransaction",e);
// }
// }
}
/**
* Perform necessary actions to stop the <code>Pipe</code>.<br/>
* For instance, closing JMS connections, dbms connections etc.
*/
@Override
public void stop() {}
/**
* The <code>toString()</code> method retrieves its value
* by reflection, so overriding this method is mostly not
* useful.
* @see ToStringBuilder#reflectionToString
*
**/
@Override
public String toString() {
try {
return (new ReflectionToStringBuilder(this) {
@Override
protected boolean accept(Field f) {
//TODO create a blacklist or whitelist
return super.accept(f) && !f.getName().contains("appConstants");
}
}).toString();
} catch (Throwable t) {
log.warn("exception getting string representation of pipe ["+getName()+"]", t);
}
return null;
}
/**
* Add a parameter to the list of parameters
* @param param the PipeParameter.
*/
@IbisDoc({"10"})
public void addParameter(Parameter param) {
log.debug("Pipe ["+getName()+"] added parameter ["+param.toString()+"]");
parameterList.add(param);
}
/**
* return the Parameters
*/
public ParameterList getParameterList() {
return parameterList;
}
@Override
public String getEventSourceName() {
return getLogPrefix(null).trim();
}
@Override
public void registerEvent(String description) {
if (eventHandler!=null) {
eventHandler.registerEvent(this,description);
}
}
@Override
public void throwEvent(String event) {
if (eventHandler!=null) {
eventHandler.fireEvent(this,event);
}
}
public PipeLine getPipeLine() {
return pipeline;
}
@Override
public Adapter getAdapter() {
if (getPipeLine()!=null) {
return getPipeLine().getAdapter();
}
return null;
}
/**
* Indicates the maximum number of treads ;that may call {@link #doPipe(Message, IPipeLineSession)} simultaneously in case
* A value of 0 indicates an unlimited number of threads.
*/
@IbisDoc({"maximum number of threads that may call {@link #doPipe(java.lang.Object, nl.nn.adapterframework.core.IPipeLineSession)} simultaneously", "0 (unlimited)"})
public void setMaxThreads(int newMaxThreads) {
maxThreads = newMaxThreads;
}
@Override
public int getMaxThreads() {
return maxThreads;
}
/**
* The functional name of this pipe
*/
@IbisDoc({"1", "name of the pipe", ""})
@Override
public void setName(String name) {
this.name=name;
inSizeStatDummyObject.setName(getName() + " (in)");
outSizeStatDummyObject.setName(getName() + " (out)");
}
@Override
public String getName() {
return this.name;
}
@IbisDoc({"2", "controls whether pipe is included in configuration. when set <code>false</code> or set to something else as <code>true</code>, (even set to the empty string), the pipe is not included in the configuration", "true"})
public void setActive(boolean b) {
active = b;
}
@Override
public boolean isActive() {
return active;
}
@Override
public void setGetInputFromSessionKey(String string) {
getInputFromSessionKey = string;
}
@Override
public String getGetInputFromSessionKey() {
return getInputFromSessionKey;
}
@Override
public void setGetInputFromFixedValue(String string) {
getInputFromFixedValue = string;
}
@Override
public String getGetInputFromFixedValue() {
return getInputFromFixedValue;
}
@Override
public void setEmptyInputReplacement(String string) {
emptyInputReplacement = string;
}
@Override
public String getEmptyInputReplacement() {
return emptyInputReplacement;
}
@Override
public void setPreserveInput(boolean preserveInput) {
this.preserveInput = preserveInput;
}
@Override
public boolean isPreserveInput() {
return preserveInput;
}
@Override
public void setStoreResultInSessionKey(String string) {
storeResultInSessionKey = string;
}
@Override
public String getStoreResultInSessionKey() {
return storeResultInSessionKey;
}
@Override
public void setChompCharSize(String string) {
chompCharSize = string;
}
@Override
public String getChompCharSize() {
return chompCharSize;
}
@Override
public void setElementToMove(String string) {
elementToMove = string;
}
@Override
public String getElementToMove() {
return elementToMove;
}
@Override
public void setElementToMoveSessionKey(String string) {
elementToMoveSessionKey = string;
}
@Override
public String getElementToMoveSessionKey() {
return elementToMoveSessionKey;
}
@Override
public void setElementToMoveChain(String string) {
elementToMoveChain = string;
}
@Override
public String getElementToMoveChain() {
return elementToMoveChain;
}
@Override
public void setDurationThreshold(long maxDuration) {
this.durationThreshold = maxDuration;
}
@Override
public long getDurationThreshold() {
return durationThreshold;
}
@Override
public void setRemoveCompactMsgNamespaces(boolean b) {
removeCompactMsgNamespaces = b;
}
@Override
public boolean isRemoveCompactMsgNamespaces() {
return removeCompactMsgNamespaces;
}
@Override
public void setRestoreMovedElements(boolean restoreMovedElements) {
this.restoreMovedElements = restoreMovedElements;
}
@Override
public boolean isRestoreMovedElements() {
return restoreMovedElements;
}
@IbisDoc({"controls namespace-awareness of possible xml parsing in descender-classes", "application default"})
public void setNamespaceAware(boolean b) {
namespaceAware = b;
}
public boolean isNamespaceAware() {
return namespaceAware;
}
@Override
public boolean hasSizeStatistics() {
return sizeStatistics;
}
public void setSizeStatistics(boolean sizeStatistics) {
this.sizeStatistics = sizeStatistics;
}
@Override
@IbisDoc({"20"})
public void setLocker(Locker locker) {
this.locker = locker;
}
@Override
public Locker getLocker() {
return locker;
}
public DummyNamedObject getInSizeStatDummyObject() {
return inSizeStatDummyObject;
}
public DummyNamedObject getOutSizeStatDummyObject() {
return outSizeStatDummyObject;
}
@Override
public void setWriteToSecLog(boolean b) {
writeToSecLog = b;
}
@Override
public boolean isWriteToSecLog() {
return writeToSecLog;
}
@Override
public void setSecLogSessionKeys(String string) {
secLogSessionKeys = string;
}
@Override
public String getSecLogSessionKeys() {
return secLogSessionKeys;
}
public void setLogIntermediaryResults(String string) {
logIntermediaryResults = string;
}
public String getLogIntermediaryResults() {
return logIntermediaryResults;
}
@IbisDoc({"Regular expression to mask strings in the log. For example, the regular expression <code>(?<=<password>).*?(?=</password>)</code> will replace every character between keys '<password>' and '</password>'. <b>note:</b> this feature is used at adapter level, so one pipe affects all pipes in the pipeline (and multiple values in different pipes are merged)", ""})
public void setHideRegex(String hideRegex) {
this.hideRegex = hideRegex;
}
public String getHideRegex() {
return hideRegex;
}
}
|
3e147c4a3bc1dcc068a08b6ccc0e7b31170f580e | 898 | java | Java | src/main/java/com/alipay/api/response/KoubeiCateringPosDeskareaQueryResponse.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 333 | 2018-08-28T09:26:55.000Z | 2022-03-31T07:26:42.000Z | src/main/java/com/alipay/api/response/KoubeiCateringPosDeskareaQueryResponse.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 46 | 2018-09-27T03:52:42.000Z | 2021-08-10T07:54:57.000Z | src/main/java/com/alipay/api/response/KoubeiCateringPosDeskareaQueryResponse.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 158 | 2018-12-07T17:03:43.000Z | 2022-03-17T09:32:43.000Z | 25.657143 | 77 | 0.749443 | 8,679 | package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.DeskAreaEntity;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: koubei.catering.pos.deskarea.query response.
*
* @author auto create
* @since 1.0, 2019-01-07 20:51:15
*/
public class KoubeiCateringPosDeskareaQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 6129632982575218995L;
/**
* 餐区信息
*/
@ApiListField("pos_desk_area_list")
@ApiField("desk_area_entity")
private List<DeskAreaEntity> posDeskAreaList;
public void setPosDeskAreaList(List<DeskAreaEntity> posDeskAreaList) {
this.posDeskAreaList = posDeskAreaList;
}
public List<DeskAreaEntity> getPosDeskAreaList( ) {
return this.posDeskAreaList;
}
}
|
3e147c98a820f73f2265c40cd509d4e038598d02 | 1,407 | java | Java | cfg4j-core/src/test/java/org/cfg4j/source/empty/EmptyConfigurationSourceTest.java | Polaris-Dust/cfg4j | 47d4f63e5fc820c62631e557adc34a29d8ab396d | [
"Apache-2.0"
] | 594 | 2015-06-19T07:37:38.000Z | 2022-03-21T06:40:26.000Z | cfg4j-core/src/test/java/org/cfg4j/source/empty/EmptyConfigurationSourceTest.java | Polaris-Dust/cfg4j | 47d4f63e5fc820c62631e557adc34a29d8ab396d | [
"Apache-2.0"
] | 155 | 2015-06-09T05:19:46.000Z | 2021-11-21T19:05:43.000Z | cfg4j-core/src/test/java/org/cfg4j/source/empty/EmptyConfigurationSourceTest.java | Polaris-Dust/cfg4j | 47d4f63e5fc820c62631e557adc34a29d8ab396d | [
"Apache-2.0"
] | 151 | 2015-06-08T05:19:25.000Z | 2022-03-29T14:45:21.000Z | 28.26 | 76 | 0.7615 | 8,680 | /*
* Copyright 2015-2018 Norbert Potocki (anpch@example.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 org.cfg4j.source.empty;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class EmptyConfigurationSourceTest {
private EmptyConfigurationSource source;
@BeforeEach
void setUp() {
source = new EmptyConfigurationSource();
source.init();
}
@Test
void returnsEmptyConfiguration() {
assertThat(source.getConfiguration(new DefaultEnvironment())).isEmpty();
}
@Test
void returnsEmptyConfigurationForAnyEnvironment() {
assertThat(source.getConfiguration(mock(Environment.class))).isEmpty();
}
} |
3e147cc763b1c6613dd469e116091fb3f766246e | 16,366 | java | Java | harvester-admin/src/main/java/com/indexdata/masterkey/localindices/web/admin/controller/TransformationController.java | indexdata/localindices | af035e899e949f3d5a4bc73f73ecca6f118abefe | [
"Apache-2.0"
] | null | null | null | harvester-admin/src/main/java/com/indexdata/masterkey/localindices/web/admin/controller/TransformationController.java | indexdata/localindices | af035e899e949f3d5a4bc73f73ecca6f118abefe | [
"Apache-2.0"
] | null | null | null | harvester-admin/src/main/java/com/indexdata/masterkey/localindices/web/admin/controller/TransformationController.java | indexdata/localindices | af035e899e949f3d5a4bc73f73ecca6f118abefe | [
"Apache-2.0"
] | null | null | null | 31.114068 | 125 | 0.702065 | 8,681 | /*
* Copyright (c) 1995-2011, Index Data
* All rights reserved.
* See the file LICENCE for details.
*/
package com.indexdata.masterkey.localindices.web.admin.controller;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.indexdata.masterkey.localindices.dao.DAOException;
import com.indexdata.masterkey.localindices.dao.EntityInUse;
import com.indexdata.masterkey.localindices.dao.EntityQuery;
import com.indexdata.masterkey.localindices.dao.TransformationDAO;
import com.indexdata.masterkey.localindices.dao.TransformationDAOFactory;
import com.indexdata.masterkey.localindices.dao.TransformationStepAssociationDAO;
import com.indexdata.masterkey.localindices.dao.TransformationStepAssociationDAOFactory;
import com.indexdata.masterkey.localindices.dao.TransformationStepDAO;
import com.indexdata.masterkey.localindices.dao.TransformationStepDAOFactory;
import com.indexdata.masterkey.localindices.entity.BasicTransformation;
import com.indexdata.masterkey.localindices.entity.Transformation;
import com.indexdata.masterkey.localindices.entity.TransformationStep;
import com.indexdata.masterkey.localindices.entity.TransformationStepAssociation;
import com.indexdata.masterkey.localindices.entity.XmlTransformationStep;
import com.indexdata.masterkey.localindices.web.service.converter.TransformationBrief;
/**
* The controller for the Admin interface for Transformations, implements all
* the business logic and controls data access through DAO object
*
* @author Dennis
*/
public class TransformationController {
private Logger logger = Logger.getLogger(getClass());
// Transformation
private TransformationDAO dao;
private TransformationStepAssociationDAO associationDao;
//private TransformationStepDAO stepDao;
private Transformation current;
@SuppressWarnings("rawtypes")
private DataModel model;
@SuppressWarnings("rawtypes")
/* Transformations */
private List resources;
/* Steps for current transformations */
// private List<TransformationStepAssociation> stepAssociation = null;
private String stepMode = "hideEditStep();"; // which JS function should be
// called on load
private TransformationStepAssociation currentStepAssociation;
private TransformationStepDAO stepDao;
Stack<String> backActions = new Stack<String>();
String homeAction = "home";
// </editor-fold>
// <editor-fold defaultstate="collapsed"
// desc="Transformation list paging functions">
private int firstItem = 0;
private int batchSize = 20;
private int itemCount = -1;
private String errorMessage;
public TransformationController() {
try {
dao = TransformationDAOFactory.getTransformationDAO((ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext());
associationDao = TransformationStepAssociationDAOFactory.getDAO((ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext());
stepDao = TransformationStepDAOFactory.getDAO((ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext());
} catch (DAOException ex) {
logger.log(Level.FATAL, "Exception when retrieving DAO", ex);
}
}
public Transformation getTransformation() {
return current;
}
public void setTransformation(Transformation resource) {
this.current = resource;
// currentStepAssociation = current.getStepAssociations();
}
public int getBatchSize() {
return batchSize;
}
public int getFirstItem() {
return firstItem;
}
public int getLastItem() {
int count = getItemCount();
return (count < firstItem + batchSize) ? count : firstItem + batchSize;
}
public int getItemCount() {
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
if (itemCount == -1 || !isPb() && req.getAttribute("countRequestSeenFlag") == null) {
req.setAttribute("countRequestSeenFlag", "yes");
itemCount = dao.getCount(new EntityQuery());
}
return itemCount;
}
public String next() {
if (firstItem + batchSize < getItemCount()) {
firstItem += batchSize;
}
return list();
}
public String prev() {
firstItem -= batchSize;
if (firstItem < 0) {
firstItem = 0;
}
return list();
}
public String list() {
resources = null;
itemCount = -1;
return "list_transformations";
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="DAO methods">
/* add new resource */
public String prepareTransformationToAdd() {
current = new BasicTransformation();
return "new_transformation";
}
public String prepareCrossMapTransformationToAdd() {
// TODO
// current = new CrossMapTransformation();
return "new_crossmap_transformation";
}
/* Save and continue editing */
public String save() {
prePersist();
if (current.getId() == null)
dao.create(current);
else
current = dao.update(current);
return editCurrent();
}
public String saveExit() {
save();
current = null;
currentStepAssociation = null;
return list();
}
/* update resource */
public String prepareToEdit() {
current = getResourceFromRequestParam();
// stepAssociation = current.getStepAssociations();
currentStepAssociation = null;
postDePersist();
logger.log(Level.INFO, "Retrieved persisted resource of type " + current.getClass().getName());
if (current instanceof Transformation) {
return "edit_transformation";
}
/*
* else if (resource instanceof ZebraTransformation) { return
* "edit_zebraTransformation"; } else if (resource instanceof
* ConsoleTransformation) { return "edit_console"; } else if (resource
* instanceof XmlTransformation) { return "edit_xmlTransformation"; }
*/
else {
logger.log(Level.INFO, "Unknown resource type. No matching form defined.");
return "failure";
}
}
private boolean isPb() {
FacesContext ctx = FacesContext.getCurrentInstance();
return ctx.getRenderKit().getResponseStateManager().isPostback(ctx);
}
/* list resources */
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataModel getTransformations() {
// check if new request
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
if (resources == null || !isPb() && req.getAttribute("listRequestSeen") == null) {
req.setAttribute("listRequestSeen", "yes");
resources = (List) dao.retrieveBriefs(firstItem, batchSize, new EntityQuery());
}
if (resources != null)
Collections.sort(resources);
return new ListDataModel(resources);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public DataModel getTransformationSteps() {
List<TransformationStepAssociation> steps = new LinkedList<TransformationStepAssociation>();
/*
* stepDao . retrieveByTransformationId ( current . getId ( ) ) ;
*/
if (current != null)
steps = (List) current.getSteps();
return new ListDataModel(steps);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public DataModel<List<TransformationStepAssociation>> getTransformationStepAssociations() {
List<TransformationStepAssociation> steps = new LinkedList<TransformationStepAssociation>();
/*
* stepDao . retrieveByTransformationId ( current . getId ( ) ) ;
*/
if (current != null)
steps = (List<TransformationStepAssociation>) current.getStepAssociations();
return new ListDataModel(steps);
}
public String delete() {
current = getResourceFromRequestParam();
dao.delete(current);
current = null;
return list();
}
public String saveAndPurge() {
dao.delete(current);
prePersist();
current.setId(null);
dao.create(current);
current = null;
return list();
}
private void prePersist() {
}
private void postDePersist() {
}
public Transformation getResourceFromRequestParam() {
return getResourceFromRequestParam(null);
}
/* objects from request */
public Transformation getResourceFromRequestParam(String id_param) {
if (id_param == null)
id_param = "id";
Transformation o = null;
if (model != null) {
o = (Transformation) model.getRowData();
// o = em.merge(o);
} else {
String param = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get(id_param);
Long id = new Long(param);
o = dao.retrieveById(id);
}
return o;
}
/* objects from request */
public TransformationStep getStepFromRequestParam(String id_param)
{
if (id_param == null)
id_param = "id";
TransformationStep o;
String param = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(id_param);
Long id = new Long(param);
o = stepDao.retrieveById(id);
return o;
}
public String stackBackAction(String newAction) {
return backActions.push(newAction);
}
public String back() {
if (backActions.isEmpty())
return homeAction;
return backActions.pop();
}
public String home() {
return homeAction;
}
public String getHomeAction() {
return homeAction;
}
public void setHomeAction(String homeAction) {
this.homeAction = homeAction;
}
private int setupStep() {
int index = -1;
String idName = "stepID";
String param = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
.get(idName);
if (param != null && !"null".equals(param)) {
try {
Long id = new Long(param);
index = lookupIndexByID(id);
if (index >= 0)
currentStepAssociation = current.getStepAssociations().get(index);
else
currentStepAssociation = null;
} catch (Exception e) {
logger.error("Unable to get Step from parameter '" + idName + "' " + param + ". Error: "
+ e.getMessage());
}
}
logger.debug("Step from parameter '" + idName + "'=" + param + ": " + currentStepAssociation
+ " index: " + index);
return index;
}
private int lookupIndexByID(Long id) {
for (int index = 0; index < current.getStepAssociations().size(); index++) {
if (current.getStepAssociations().get(index).getId().equals(id))
return index;
}
return -1;
}
public String selectStepToInsert() {
return "insert_step";
}
public String addStep()
{
Transformation transformation = getResourceFromRequestParam("transformationID");
TransformationStep step = getStepFromRequestParam("stepID");
if (transformation != null && step != null) {
currentStepAssociation = new TransformationStepAssociation();
currentStepAssociation.setStep(step);
currentStepAssociation.setTransformation(transformation);
currentStepAssociation.setPosition(transformation.getSteps().size() + 1);
associationDao.create(currentStepAssociation);
logger.debug("Association id " + currentStepAssociation.getId()
+ " Transformation ID: " + currentStepAssociation.getTransformation().getId()
+ " Step ID: " + currentStepAssociation.getStep().getId());
transformation.addStepAssociation(currentStepAssociation);
// Should not happpen, but...
if (transformation.getId() == null)
dao.create(transformation);
current = dao.update(transformation);
}
else {
errorMessage = "Failed to attached Step (" + step + ") to Transformation (" + transformation + "): One was not found.";
return "transformation_failure";
}
return "insert_step";
}
public String editStep() {
setupStep();
stepMode = "showEditStep();";
// TODO edit depending on Step Type
return "edit_xsl_step";
}
public String editCurrent() {
return "edit_current";
}
public String upStep() {
setupStep();
upDownStep(currentStepAssociation, -1);
stepMode = "hideEditStep();";
// TODO replace with edit_current
return "up_step";
}
private void upDownStep(TransformationStepAssociation association, int i) {
int index;
for (index = 0; index < current.getStepAssociations().size(); index++) {
if (current.getStepAssociations().get(index).equals(association)) {
break;
}
}
int newIndex = index + i;
// If found and newIndex is within bounds
if (index < current.getStepAssociations().size() && newIndex >= 0
&& newIndex < current.getStepAssociations().size()) {
TransformationStepAssociation cur = current.getStepAssociations().get(index);
TransformationStepAssociation swap = current.getStepAssociations().get(newIndex);
cur.setPosition(cur.getPosition() + i);
swap.setPosition(swap.getPosition() - i);
current.getStepAssociations().set(newIndex, cur);
current.getStepAssociations().set(index, swap);
current = dao.update(current);
associationDao.update(cur);
associationDao.update(swap);
}
}
public String downStep() {
setupStep();
upDownStep(currentStepAssociation, 1);
stepMode = "hideEditStep();";
// TODO replace with edit_current
return "down_step";
}
public String deleteStep() {
// TransformationStepAssociation currentStep = null;
int index = setupStep();
if (currentStepAssociation != null && currentStepAssociation.getTransformation() != null) {
currentStepAssociation = current.getStepAssociations().remove(index);
try {
associationDao.delete(currentStepAssociation);
} catch (EntityInUse eiu) {
logger.warn("Cannot remove step association", eiu);
}
logger.debug("" + currentStepAssociation + " was removed.");
currentStepAssociation = null;
// TODO Need reordering!
}
stepMode = "hideEditStep();";
prePersist();
current = dao.update(current);
stepMode = "hideEditStep();";
return "delete_step";
}
public String saveStep() {
// TODO persist current step and association . Not on list, add
stepMode = "hideEditStep();";
if (!current.getStepAssociations().contains(currentStepAssociation)) {
current.addStepAssociation(currentStepAssociation);
currentStepAssociation.setTransformation(current);
prePersist();
associationDao.create(currentStepAssociation);
} else {
prePersist();
currentStepAssociation.setTransformation(current);
currentStepAssociation = associationDao.update(currentStepAssociation);
}
currentStepAssociation = null;
return "save_step";
}
public String cancel() {
current = null;
currentStepAssociation = null;
return list();
}
public TransformationStep getTransformationStep() {
if (currentStepAssociation == null) {
TransformationStep tmpStep = new XmlTransformationStep("", "", "");
return tmpStep;
}
return currentStepAssociation.getStep();
}
public void setTransformationStep(TransformationStepAssociation stepAssociation) {
this.currentStepAssociation = stepAssociation;
}
public List<SelectItem> getTransformationItems() {
List<SelectItem> list = new LinkedList<SelectItem>();
EntityQuery qry = new EntityQuery();
List<TransformationBrief> resources = dao.retrieveBriefs(0, dao.getCount(qry), qry);
list.add(new SelectItem("", "<Select Transformation>"));
if (resources != null)
for (TransformationBrief transformation : (List<TransformationBrief>) resources) {
if (transformation.isEnabled()) {
SelectItem selectItem = new SelectItem();
selectItem.setLabel(transformation.getName());
selectItem.setValue(transformation.getId());
list.add(selectItem);
}
}
return list;
}
public String getStepMode() {
return stepMode;
}
public void setStepMode(String stepMode) {
this.stepMode = stepMode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
|
3e147de3ad34cb2025c5cbea8a306b85228edfad | 2,262 | java | Java | 07-messaging/springboot-feat-messaging-rocketmq/src/main/java/xyz/flysium/dao/entity/OrderInfo.java | SvenAugustus/springboot2-bucket | f66577acffb11c88c7c15db4edfcb93ed7cc2958 | [
"Apache-2.0"
] | null | null | null | 07-messaging/springboot-feat-messaging-rocketmq/src/main/java/xyz/flysium/dao/entity/OrderInfo.java | SvenAugustus/springboot2-bucket | f66577acffb11c88c7c15db4edfcb93ed7cc2958 | [
"Apache-2.0"
] | null | null | null | 07-messaging/springboot-feat-messaging-rocketmq/src/main/java/xyz/flysium/dao/entity/OrderInfo.java | SvenAugustus/springboot2-bucket | f66577acffb11c88c7c15db4edfcb93ed7cc2958 | [
"Apache-2.0"
] | null | null | null | 20.944444 | 75 | 0.668435 | 8,682 | /*
* Copyright 2020 SvenAugustus
*
* 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 xyz.flysium.dao.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Order of User.
*
* @author Sven Augustus
*/
@Entity
@Table(name = "U_ORDER")
public class OrderInfo implements java.io.Serializable {
private static final long serialVersionUID = 4611610861953677600L;
@Id
// FIXME 这里为了方便H2 数据库模拟,使用 long ,实际生产环境可能采用 更长的整数存储 ?
private Long id;
@Column
private Long userId;
@Column
private Date createTime;
@Column
private Date modifyTime;
@Column
private String state;
public OrderInfo() {
}
public OrderInfo(long id, long userId, String state) {
this.id = id;
this.userId = userId;
this.state = state;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "OrderInfo{" +
"id=" + id +
", userId=" + userId +
", createTime=" + createTime +
", modifyTime=" + modifyTime +
", state='" + state + '\'' +
'}';
}
}
|
3e147e03fa9c0a24660b921ffb44873a60471672 | 2,306 | java | Java | src/main/java/com/hermestechnologies/domain/Product.java | Troll173/gamotko | 08b839f41cda3613ab1ddc14ea79ea4a3f0762aa | [
"MIT"
] | null | null | null | src/main/java/com/hermestechnologies/domain/Product.java | Troll173/gamotko | 08b839f41cda3613ab1ddc14ea79ea4a3f0762aa | [
"MIT"
] | null | null | null | src/main/java/com/hermestechnologies/domain/Product.java | Troll173/gamotko | 08b839f41cda3613ab1ddc14ea79ea4a3f0762aa | [
"MIT"
] | null | null | null | 21.961905 | 86 | 0.582827 | 8,683 | package com.hermestechnologies.domain;
import javax.persistence.*;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "products")
public class Product{
@Id
@GeneratedValue
private Integer id;
private String generic_name;
private String dosage;
private String preparation;
private String packaging;
private String brand_name;
@OneToMany(mappedBy="product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Stock> stocks;
@OneToMany(mappedBy="product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<PoItem> poItems;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGeneric_name() {
return generic_name;
}
public void setGeneric_name(String generic_name) {
this.generic_name = generic_name;
}
public String getDosage() {
return dosage;
}
public void setDosage(String dosage) {
this.dosage = dosage;
}
public String getPreparation() {
return preparation;
}
public void setPreparation(String preparation) {
this.preparation = preparation;
}
public String getPackaging() {
return packaging;
}
public void setPackaging(String packaging) {
this.packaging = packaging;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public Set<Stock> getStocks() {
return stocks;
}
public void setStocks(Set<Stock> stocks) {
this.stocks = stocks;
}
public Set<PoItem> getPoItems() {
return poItems;
}
public void setPoItems(Set<PoItem> poItems) {
this.poItems = poItems;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", generic_name='" + generic_name + '\'' +
", dosage='" + dosage + '\'' +
", preparation='" + preparation + '\'' +
", packaging='" + packaging + '\'' +
", brand_name='" + brand_name + '\'' +
", stocks=" + stocks +
'}';
}
}
|
3e147e3fd730a69ffde742c80def651d45ec9f59 | 561 | java | Java | src/main/java/com/tinnkyou/demo/demo2/UserConfig.java | TINNQYOU/dtemplates | e0274fa9e24756ebeef1bb0c354527ff36cc9864 | [
"Apache-2.0"
] | 1 | 2019-02-13T10:32:45.000Z | 2019-02-13T10:32:45.000Z | src/main/java/com/tinnkyou/demo/demo2/UserConfig.java | TINNQYOU/dtemplates | e0274fa9e24756ebeef1bb0c354527ff36cc9864 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tinnkyou/demo/demo2/UserConfig.java | TINNQYOU/dtemplates | e0274fa9e24756ebeef1bb0c354527ff36cc9864 | [
"Apache-2.0"
] | null | null | null | 24.391304 | 67 | 0.737968 | 8,684 | package com.tinnkyou.demo.demo2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
/**
* @author wb-cq355812
* @create 2019/06/13
*/
@Configuration
public class UserConfig {
@Bean(value = "user")
public User initUser(){
User u = new User();
u.setAge(12);
return u;
}
}
|
3e147ec01bc3024ff336f62b29e75f3bf7adb83a | 557 | java | Java | app/src/main/java/com/example/zoxy/mqttclient/Globals.java | zree/MQTTclient | ac0feecfe62f273c661d61f8c9092af0fc05da2f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/zoxy/mqttclient/Globals.java | zree/MQTTclient | ac0feecfe62f273c661d61f8c9092af0fc05da2f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/zoxy/mqttclient/Globals.java | zree/MQTTclient | ac0feecfe62f273c661d61f8c9092af0fc05da2f | [
"Apache-2.0"
] | null | null | null | 25.318182 | 67 | 0.719928 | 8,685 | package com.example.zoxy.mqttclient;
import android.content.Context;
/**
* Created by zoxy on 2017/5/1.
*/
public class Globals {
public static String playState = "STOPPED";
public static long playProgress = 0;
public static long totalTime = 0;
public static String TTSplayState = "FINISHED";
public static int volume = 10;
public static boolean boxConnect = false;
public static boolean NoticeOrNot = true;
public static Context curContext= null;
public static final String clientID = "UJ59xAlPEeeCbn3clmw9jw";
}
|
3e147eefe60980aec35b67cdbf6eeb28f7548694 | 1,571 | java | Java | HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/ClusterDasVmConfigInfo.java | HewlettPackard/SimpliVity-Citrix-VCenter-Plugin | 504cbeec6fce27a4b6b23887b28d6a4e85393f4b | [
"Apache-2.0"
] | null | null | null | HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/ClusterDasVmConfigInfo.java | HewlettPackard/SimpliVity-Citrix-VCenter-Plugin | 504cbeec6fce27a4b6b23887b28d6a4e85393f4b | [
"Apache-2.0"
] | null | null | null | HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/ClusterDasVmConfigInfo.java | HewlettPackard/SimpliVity-Citrix-VCenter-Plugin | 504cbeec6fce27a4b6b23887b28d6a4e85393f4b | [
"Apache-2.0"
] | 1 | 2018-10-03T16:53:11.000Z | 2018-10-03T16:53:11.000Z | 24.936508 | 110 | 0.677276 | 8,686 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.06.12 at 09:16:35 AM EDT
//
package com.vmware.vim25;
/**
*
*/
@SuppressWarnings("all")
public class ClusterDasVmConfigInfo
extends DynamicData
{
public ManagedObjectReference key;
public DasVmPriority restartPriority;
public Boolean powerOffOnIsolation;
public ClusterDasVmSettings dasSettings;
public ManagedObjectReference getKey() {
return key;
}
public void setKey(ManagedObjectReference key) {
this.key = key;
}
public DasVmPriority getRestartPriority() {
return restartPriority;
}
public void setRestartPriority(DasVmPriority restartPriority) {
this.restartPriority = restartPriority;
}
public Boolean getPowerOffOnIsolation() {
return powerOffOnIsolation;
}
public void setPowerOffOnIsolation(Boolean powerOffOnIsolation) {
this.powerOffOnIsolation = powerOffOnIsolation;
}
public Boolean isPowerOffOnIsolation() {
return powerOffOnIsolation;
}
public ClusterDasVmSettings getDasSettings() {
return dasSettings;
}
public void setDasSettings(ClusterDasVmSettings dasSettings) {
this.dasSettings = dasSettings;
}
}
|
3e147efc214984733f8bcbc923ffde4e55f28273 | 8,904 | java | Java | runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ExternalEnvironmentFactory.java | dmitriikuzinepam/beam | 0e05a220da8cc3f85f90c00a31fe0a6b0bbef24a | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 5,279 | 2016-12-29T04:00:44.000Z | 2022-03-31T22:56:45.000Z | runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ExternalEnvironmentFactory.java | dmitriikuzinepam/beam | 0e05a220da8cc3f85f90c00a31fe0a6b0bbef24a | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 14,149 | 2016-12-28T00:43:50.000Z | 2022-03-31T23:50:22.000Z | runners/java-fn-execution/src/main/java/org/apache/beam/runners/fnexecution/environment/ExternalEnvironmentFactory.java | dmitriikuzinepam/beam | 0e05a220da8cc3f85f90c00a31fe0a6b0bbef24a | [
"PSF-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 3,763 | 2016-12-29T04:06:10.000Z | 2022-03-31T22:25:49.000Z | 44.079208 | 97 | 0.750562 | 8,687 | /*
* 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.beam.runners.fnexecution.environment;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.beam.model.fnexecution.v1.BeamFnApi;
import org.apache.beam.model.fnexecution.v1.BeamFnExternalWorkerPoolGrpc;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.RunnerApi.Environment;
import org.apache.beam.runners.core.construction.BeamUrns;
import org.apache.beam.runners.fnexecution.artifact.ArtifactRetrievalService;
import org.apache.beam.runners.fnexecution.control.ControlClientPool;
import org.apache.beam.runners.fnexecution.control.FnApiControlClientPoolService;
import org.apache.beam.runners.fnexecution.control.InstructionRequestHandler;
import org.apache.beam.runners.fnexecution.logging.GrpcLoggingService;
import org.apache.beam.runners.fnexecution.provisioning.StaticGrpcProvisionService;
import org.apache.beam.sdk.fn.IdGenerator;
import org.apache.beam.sdk.fn.channel.ManagedChannelFactory;
import org.apache.beam.sdk.fn.server.GrpcFnServer;
import org.apache.beam.sdk.fn.server.ServerFactory;
import org.apache.beam.vendor.grpc.v1p36p0.io.grpc.ManagedChannel;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** An {@link EnvironmentFactory} which requests workers via the given URL in the Environment. */
public class ExternalEnvironmentFactory implements EnvironmentFactory {
private static final Logger LOG = LoggerFactory.getLogger(ExternalEnvironmentFactory.class);
// setting the environment variable allows to connect to worker pool running in Docker on Mac
private static final boolean IS_WORKER_POOL_IN_DOCKER_VM =
System.getenv().containsKey("BEAM_WORKER_POOL_IN_DOCKER_VM");
public static ExternalEnvironmentFactory create(
GrpcFnServer<FnApiControlClientPoolService> controlServiceServer,
GrpcFnServer<GrpcLoggingService> loggingServiceServer,
GrpcFnServer<ArtifactRetrievalService> retrievalServiceServer,
GrpcFnServer<StaticGrpcProvisionService> provisioningServiceServer,
ControlClientPool.Source clientSource,
IdGenerator idGenerator) {
return new ExternalEnvironmentFactory(
controlServiceServer,
loggingServiceServer,
retrievalServiceServer,
provisioningServiceServer,
idGenerator,
clientSource);
}
private final GrpcFnServer<FnApiControlClientPoolService> controlServiceServer;
private final GrpcFnServer<GrpcLoggingService> loggingServiceServer;
private final GrpcFnServer<ArtifactRetrievalService> retrievalServiceServer;
private final GrpcFnServer<StaticGrpcProvisionService> provisioningServiceServer;
private final IdGenerator idGenerator;
private final ControlClientPool.Source clientSource;
private ExternalEnvironmentFactory(
GrpcFnServer<FnApiControlClientPoolService> controlServiceServer,
GrpcFnServer<GrpcLoggingService> loggingServiceServer,
GrpcFnServer<ArtifactRetrievalService> retrievalServiceServer,
GrpcFnServer<StaticGrpcProvisionService> provisioningServiceServer,
IdGenerator idGenerator,
ControlClientPool.Source clientSource) {
this.controlServiceServer = controlServiceServer;
this.loggingServiceServer = loggingServiceServer;
this.retrievalServiceServer = retrievalServiceServer;
this.provisioningServiceServer = provisioningServiceServer;
this.idGenerator = idGenerator;
this.clientSource = clientSource;
}
/** Creates a new, active {@link RemoteEnvironment} backed by an unmanaged worker. */
@Override
public RemoteEnvironment createEnvironment(Environment environment, String workerId)
throws Exception {
Preconditions.checkState(
environment
.getUrn()
.equals(BeamUrns.getUrn(RunnerApi.StandardEnvironments.Environments.EXTERNAL)),
"The passed environment does not contain an ExternalPayload.");
final RunnerApi.ExternalPayload externalPayload =
RunnerApi.ExternalPayload.parseFrom(environment.getPayload());
BeamFnApi.StartWorkerRequest startWorkerRequest =
BeamFnApi.StartWorkerRequest.newBuilder()
.setWorkerId(workerId)
.setControlEndpoint(controlServiceServer.getApiServiceDescriptor())
.setLoggingEndpoint(loggingServiceServer.getApiServiceDescriptor())
.setArtifactEndpoint(retrievalServiceServer.getApiServiceDescriptor())
.setProvisionEndpoint(provisioningServiceServer.getApiServiceDescriptor())
.putAllParams(externalPayload.getParamsMap())
.build();
LOG.debug("Requesting worker ID {}", workerId);
final ManagedChannel managedChannel =
ManagedChannelFactory.createDefault().forDescriptor(externalPayload.getEndpoint());
BeamFnApi.StartWorkerResponse startWorkerResponse =
BeamFnExternalWorkerPoolGrpc.newBlockingStub(managedChannel)
.startWorker(startWorkerRequest);
if (!startWorkerResponse.getError().isEmpty()) {
throw new RuntimeException(startWorkerResponse.getError());
}
// Wait on a client from the gRPC server.
InstructionRequestHandler instructionHandler = null;
while (instructionHandler == null) {
try {
instructionHandler = clientSource.take(workerId, Duration.ofMinutes(2));
} catch (TimeoutException timeoutEx) {
LOG.info(
"Still waiting for startup of environment from {} for worker id {}",
externalPayload.getEndpoint().getUrl(),
workerId);
} catch (InterruptedException interruptEx) {
Thread.currentThread().interrupt();
managedChannel.shutdownNow();
throw new RuntimeException(interruptEx);
}
}
final InstructionRequestHandler finalInstructionHandler = instructionHandler;
return new RemoteEnvironment() {
@Override
public Environment getEnvironment() {
return environment;
}
@Override
public InstructionRequestHandler getInstructionRequestHandler() {
return finalInstructionHandler;
}
@Override
public void close() throws Exception {
try {
finalInstructionHandler.close();
BeamFnApi.StopWorkerRequest stopWorkerRequest =
BeamFnApi.StopWorkerRequest.newBuilder().setWorkerId(workerId).build();
LOG.debug("Closing worker ID {}", workerId);
BeamFnApi.StopWorkerResponse stopWorkerResponse =
BeamFnExternalWorkerPoolGrpc.newBlockingStub(managedChannel)
.stopWorker(stopWorkerRequest);
if (!stopWorkerResponse.getError().isEmpty()) {
throw new RuntimeException(stopWorkerResponse.getError());
}
} finally {
managedChannel.shutdown();
managedChannel.awaitTermination(10, TimeUnit.SECONDS);
if (!managedChannel.isTerminated()) {
managedChannel.shutdownNow();
}
}
}
};
}
/** Provider of ExternalEnvironmentFactory. */
public static class Provider implements EnvironmentFactory.Provider {
@Override
public EnvironmentFactory createEnvironmentFactory(
GrpcFnServer<FnApiControlClientPoolService> controlServiceServer,
GrpcFnServer<GrpcLoggingService> loggingServiceServer,
GrpcFnServer<ArtifactRetrievalService> retrievalServiceServer,
GrpcFnServer<StaticGrpcProvisionService> provisioningServiceServer,
ControlClientPool clientPool,
IdGenerator idGenerator) {
return create(
controlServiceServer,
loggingServiceServer,
retrievalServiceServer,
provisioningServiceServer,
clientPool.getSource(),
idGenerator);
}
@Override
public ServerFactory getServerFactory() {
if (IS_WORKER_POOL_IN_DOCKER_VM) {
return DockerEnvironmentFactory.DockerOnMac.getServerFactory();
}
return ServerFactory.createDefault();
}
}
}
|
3e147f4a8027efcf0eee6f4afb2984ebbbc5cded | 3,286 | java | Java | app/src/main/java/fr/free/nrw/commons/MediaWikiImageView.java | RockyIQ/apps-android-commons | d9caee8fdb3cd78d10b1bb67215ebb995d18e48f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/fr/free/nrw/commons/MediaWikiImageView.java | RockyIQ/apps-android-commons | d9caee8fdb3cd78d10b1bb67215ebb995d18e48f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/fr/free/nrw/commons/MediaWikiImageView.java | RockyIQ/apps-android-commons | d9caee8fdb3cd78d10b1bb67215ebb995d18e48f | [
"Apache-2.0"
] | 1 | 2018-04-20T10:10:14.000Z | 2018-04-20T10:10:14.000Z | 33.191919 | 109 | 0.624467 | 8,688 | package fr.free.nrw.commons;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.Toast;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import timber.log.Timber;
public class MediaWikiImageView extends SimpleDraweeView {
private ThumbnailFetchTask currentThumbnailTask;
public MediaWikiImageView(Context context) {
this(context, null);
init();
}
public MediaWikiImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init();
}
public MediaWikiImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void setMedia(Media media) {
if (currentThumbnailTask != null) {
currentThumbnailTask.cancel(true);
}
if(media == null) {
return;
}
if (CommonsApplication.getInstance().getThumbnailUrlCache().get(media.getFilename()) != null) {
setImageUrl(CommonsApplication.getInstance().getThumbnailUrlCache().get(media.getFilename()));
} else {
setImageUrl(null);
currentThumbnailTask = new ThumbnailFetchTask(media);
currentThumbnailTask.execute(media.getFilename());
}
}
@Override
protected void onDetachedFromWindow() {
if (currentThumbnailTask != null) {
currentThumbnailTask.cancel(true);
}
super.onDetachedFromWindow();
}
private void init() {
setHierarchy(GenericDraweeHierarchyBuilder
.newInstance(getResources())
.setPlaceholderImage(VectorDrawableCompat.create(getResources(),
R.drawable.ic_image_black_24dp, getContext().getTheme()))
.setFailureImage(VectorDrawableCompat.create(getResources(),
R.drawable.ic_image_black_24dp, getContext().getTheme()))
.build());
}
private void setImageUrl(@Nullable String url) {
setImageURI(url);
}
private class ThumbnailFetchTask extends MediaThumbnailFetchTask {
ThumbnailFetchTask(@NonNull Media media) {
super(media);
}
@Override
protected void onPostExecute(String result) {
if (isCancelled()) {
return;
}
if (TextUtils.isEmpty(result) && media.getLocalUri() != null) {
result = media.getLocalUri().toString();
} else {
// only cache meaningful thumbnails received from network.
try {
CommonsApplication.getInstance().getThumbnailUrlCache().put(media.getFilename(), result);
} catch (NullPointerException npe) {
Timber.e("error when adding pic to cache " + npe);
Toast.makeText(getContext(), R.string.error_while_cache, Toast.LENGTH_SHORT).show();
}
}
setImageUrl(result);
}
}
}
|
3e147f6a70205561c263a339bd2d8bf6aa9ccc42 | 652 | java | Java | Unit 1: Primitive Types/1.6.8: MLA Citation/Citation.java | pissmilk/CSA-CodeHS | 7bc9649c8b41a245e6489f8f3a343d99571ab9db | [
"MIT"
] | null | null | null | Unit 1: Primitive Types/1.6.8: MLA Citation/Citation.java | pissmilk/CSA-CodeHS | 7bc9649c8b41a245e6489f8f3a343d99571ab9db | [
"MIT"
] | null | null | null | Unit 1: Primitive Types/1.6.8: MLA Citation/Citation.java | pissmilk/CSA-CodeHS | 7bc9649c8b41a245e6489f8f3a343d99571ab9db | [
"MIT"
] | null | null | null | 38.352941 | 83 | 0.58589 | 8,689 | import java.util.Scanner;
public class Citation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the author's name as 'Last name, First name': ");
String a = input.nextLine();
System.out.println("Enter the title of the book: ");
String b = input.nextLine();
System.out.println("Enter the publisher of the book: ");
String c = input.nextLine();
System.out.println("Enter the year the book was published: ");
String d = input.nextLine();
System.out.println(a + ". " + b + ".\n" + c + ", " + d + '.');
}
}
|
3e147fe9397d39a150ca11996168c9387826752e | 13,637 | java | Java | openjdk/Generated/jdk/gensrc/sun/util/resources/cldr/rn/LocaleNames_rn.java | SunburstApps/OpenJSharp | 4875672d1dc6f09f10bb99ec67f98672b2be7011 | [
"Zlib"
] | 12 | 2018-04-04T12:47:40.000Z | 2022-01-02T04:36:38.000Z | openjdk-8u45-b14/build/linux-x86_64-normal-server-release/jdk/gensrc/sun/util/resources/cldr/rn/LocaleNames_rn.java | ams-ts-ikvm-bag/ikvm-src | 60009f5bdb4c9db68121f393b8b4c790a326bd32 | [
"Zlib"
] | null | null | null | openjdk-8u45-b14/build/linux-x86_64-normal-server-release/jdk/gensrc/sun/util/resources/cldr/rn/LocaleNames_rn.java | ams-ts-ikvm-bag/ikvm-src | 60009f5bdb4c9db68121f393b8b4c790a326bd32 | [
"Zlib"
] | 1 | 2021-12-10T07:51:50.000Z | 2021-12-10T07:51:50.000Z | 39.527536 | 79 | 0.449659 | 8,690 | /*
* Copyright (c) 2012, 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. 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.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under
* the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do so,
* provided that (a) the above copyright notice(s) and this permission notice
* appear with all copies of the Data Files or Software, (b) both the above
* copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written authorization
* of the copyright holder.
*/
package sun.util.resources.cldr.rn;
import sun.util.resources.OpenListResourceBundle;
public class LocaleNames_rn extends OpenListResourceBundle {
@Override
protected final Object[][] getContents() {
final Object[][] data = new Object[][] {
{ "AD", "Andora" },
{ "AE", "Leta Zunze Ubumwe z'Abarabu" },
{ "AF", "Afuganisitani" },
{ "AG", "Antigwa na Baribuda" },
{ "AI", "Angwila" },
{ "AL", "Alubaniya" },
{ "AM", "Arumeniya" },
{ "AN", "Antiye y'Abaholandi" },
{ "AO", "Angola" },
{ "AR", "Arijantine" },
{ "AS", "Samowa nyamerika" },
{ "AT", "Otirishe" },
{ "AU", "Ositaraliya" },
{ "AW", "Aruba" },
{ "AZ", "Azerubayijani" },
{ "BA", "Bosiniya na Herigozevine" },
{ "BB", "Barubadosi" },
{ "BD", "Bangaladeshi" },
{ "BE", "Ububiligi" },
{ "BF", "Burukina Faso" },
{ "BG", "Buligariya" },
{ "BH", "Bahareyini" },
{ "BI", "Uburundi" },
{ "BJ", "Bene" },
{ "BM", "Berimuda" },
{ "BN", "Buruneyi" },
{ "BO", "Boliviya" },
{ "BR", "Burezili" },
{ "BS", "Bahamasi" },
{ "BT", "Butani" },
{ "BW", "Botswana" },
{ "BY", "Belausi" },
{ "BZ", "Belize" },
{ "CA", "Kanada" },
{ "CD", "Repubulika Iharanira Demokarasi ya Kongo" },
{ "CF", "Repubulika ya Santarafurika" },
{ "CG", "Kongo" },
{ "CH", "Ubusuwisi" },
{ "CI", "Kotedivuware" },
{ "CK", "Izinga rya Kuku" },
{ "CL", "Shili" },
{ "CM", "Kameruni" },
{ "CN", "Ubushinwa" },
{ "CO", "Kolombiya" },
{ "CR", "Kositarika" },
{ "CS", "Seribiya na Montenegoro" },
{ "CU", "Kiba" },
{ "CV", "Ibirwa bya Kapuveri" },
{ "CY", "Izinga rya Shipure" },
{ "CZ", "Repubulika ya Ceke" },
{ "DE", "Ubudage" },
{ "DJ", "Jibuti" },
{ "DK", "Danimariki" },
{ "DM", "Dominika" },
{ "DO", "Repubulika ya Dominika" },
{ "DZ", "Alijeriya" },
{ "EC", "Ekwateri" },
{ "EE", "Esitoniya" },
{ "EG", "Misiri" },
{ "ER", "Elitereya" },
{ "ES", "Hisipaniya" },
{ "ET", "Etiyopiya" },
{ "FI", "Finilandi" },
{ "FJ", "Fiji" },
{ "FK", "Izinga rya Filikilandi" },
{ "FM", "Mikoroniziya" },
{ "FR", "Ubufaransa" },
{ "GA", "Gabo" },
{ "GB", "Ubwongereza" },
{ "GD", "Gerenada" },
{ "GE", "Jeworujiya" },
{ "GF", "Gwayana y'Abafaransa" },
{ "GH", "Gana" },
{ "GI", "Juburalitari" },
{ "GL", "Gurunilandi" },
{ "GM", "Gambiya" },
{ "GN", "Guneya" },
{ "GP", "Gwadelupe" },
{ "GQ", "Gineya Ekwatoriyali" },
{ "GR", "Ubugereki" },
{ "GT", "Gwatemala" },
{ "GU", "Gwamu" },
{ "GW", "Gineya Bisawu" },
{ "GY", "Guyane" },
{ "HN", "Hondurasi" },
{ "HR", "Korowasiya" },
{ "HT", "Hayiti" },
{ "HU", "Hungariya" },
{ "ID", "Indoneziya" },
{ "IE", "Irilandi" },
{ "IL", "Isiraheli" },
{ "IN", "Ubuhindi" },
{ "IO", "Intara y'Ubwongereza yo mu birwa by'Abahindi" },
{ "IQ", "Iraki" },
{ "IR", "Irani" },
{ "IS", "Ayisilandi" },
{ "IT", "Ubutaliyani" },
{ "JM", "Jamayika" },
{ "JO", "Yorudaniya" },
{ "JP", "Ubuyapani" },
{ "KE", "Kenya" },
{ "KG", "Kirigisitani" },
{ "KH", "Kamboje" },
{ "KI", "Kiribati" },
{ "KM", "Izinga rya Komore" },
{ "KN", "Sekitsi na Nevisi" },
{ "KP", "Koreya y'amajaruguru" },
{ "KR", "Koreya y'amajepfo" },
{ "KW", "Koweti" },
{ "KY", "Ibirwa bya Keyimani" },
{ "KZ", "Kazakisitani" },
{ "LA", "Layosi" },
{ "LB", "Libani" },
{ "LC", "Selusiya" },
{ "LI", "Lishyitenshitayini" },
{ "LK", "Sirilanka" },
{ "LR", "Liberiya" },
{ "LS", "Lesoto" },
{ "LT", "Lituwaniya" },
{ "LU", "Lukusamburu" },
{ "LV", "Lativa" },
{ "LY", "Libiya" },
{ "MA", "Maroke" },
{ "MC", "Monako" },
{ "MD", "Moludavi" },
{ "MG", "Madagasikari" },
{ "MH", "Izinga rya Marishari" },
{ "MK", "Masedoniya" },
{ "ML", "Mali" },
{ "MM", "Birimaniya" },
{ "MN", "Mongoliya" },
{ "MP", "Amazinga ya Mariyana ryo mu majaruguru" },
{ "MQ", "Maritiniki" },
{ "MR", "Moritaniya" },
{ "MS", "Monteserati" },
{ "MT", "Malita" },
{ "MU", "Izinga rya Morise" },
{ "MV", "Moludave" },
{ "MW", "Malawi" },
{ "MX", "Migizike" },
{ "MY", "Maleziya" },
{ "MZ", "Mozambiki" },
{ "NA", "Namibiya" },
{ "NC", "Niyukaledoniya" },
{ "NE", "Nijeri" },
{ "NF", "izinga rya Norufoluke" },
{ "NG", "Nijeriya" },
{ "NI", "Nikaragwa" },
{ "NL", "Ubuholandi" },
{ "NO", "Noruveji" },
{ "NP", "Nepali" },
{ "NR", "Nawuru" },
{ "NU", "Niyuwe" },
{ "NZ", "Nuvelizelandi" },
{ "OM", "Omani" },
{ "PA", "Panama" },
{ "PE", "Peru" },
{ "PF", "Polineziya y'Abafaransa" },
{ "PG", "Papuwa Niyugineya" },
{ "PH", "Amazinga ya Filipine" },
{ "PK", "Pakisitani" },
{ "PL", "Polonye" },
{ "PM", "Sempiyeri na Mikeloni" },
{ "PN", "Pitikeyirini" },
{ "PR", "Puwetoriko" },
{ "PS", "Palesitina Wesitibanka na Gaza" },
{ "PT", "Porutugali" },
{ "PW", "Palawu" },
{ "PY", "Paragwe" },
{ "QA", "Katari" },
{ "RE", "Amazinga ya Reyiniyo" },
{ "RO", "Rumaniya" },
{ "RU", "Uburusiya" },
{ "RW", "u Rwanda" },
{ "SA", "Arabiya Sawudite" },
{ "SB", "Amazinga ya Salumoni" },
{ "SC", "Amazinga ya Seyisheli" },
{ "SD", "Sudani" },
{ "SE", "Suwedi" },
{ "SG", "Singapuru" },
{ "SH", "Sehelene" },
{ "SI", "Siloveniya" },
{ "SK", "Silovakiya" },
{ "SL", "Siyeralewone" },
{ "SM", "Sanimarino" },
{ "SN", "Senegali" },
{ "SO", "Somaliya" },
{ "SR", "Suriname" },
{ "ST", "Sawotome na Perensipe" },
{ "SV", "Eli Saluvatori" },
{ "SY", "Siriya" },
{ "SZ", "Suwazilandi" },
{ "TC", "Amazinga ya Turkisi na Cayikosi" },
{ "TD", "Cadi" },
{ "TG", "Togo" },
{ "TH", "Tayilandi" },
{ "TJ", "Tajikisitani" },
{ "TK", "Tokelawu" },
{ "TL", "Timoru y'iburasirazuba" },
{ "TM", "Turukumenisitani" },
{ "TN", "Tuniziya" },
{ "TO", "Tonga" },
{ "TR", "Turukiya" },
{ "TT", "Tirinidadi na Tobago" },
{ "TV", "Tuvalu" },
{ "TW", "Tayiwani" },
{ "TZ", "Tanzaniya" },
{ "UA", "Ikerene" },
{ "UG", "Ubugande" },
{ "US", "Leta Zunze Ubumwe za Amerika" },
{ "UY", "Irigwe" },
{ "UZ", "Uzubekisitani" },
{ "VA", "Umurwa wa Vatikani" },
{ "VC", "Sevensa na Gerenadine" },
{ "VE", "Venezuwela" },
{ "VG", "Ibirwa by'isugi by'Abongereza" },
{ "VI", "Amazinga y'Isugi y'Abanyamerika" },
{ "VN", "Viyetinamu" },
{ "VU", "Vanuwatu" },
{ "WF", "Walisi na Futuna" },
{ "WS", "Samowa" },
{ "YE", "Yemeni" },
{ "YT", "Mayote" },
{ "ZA", "Afurika y'Epfo" },
{ "ZM", "Zambiya" },
{ "ZW", "Zimbabwe" },
{ "ak", "Igikani" },
{ "am", "Ikimuhariki" },
{ "ar", "Icarabu" },
{ "be", "Ikibelarusiya" },
{ "bg", "Ikinyabuligariya" },
{ "bn", "Ikibengali" },
{ "cs", "Igiceke" },
{ "de", "Ikidage" },
{ "el", "Ikigereki" },
{ "en", "Icongereza" },
{ "es", "Icesipanyolo" },
{ "fa", "Igiperisi" },
{ "fr", "Igifaransa" },
{ "ha", "Igihawusa" },
{ "hi", "Igihindi" },
{ "hu", "Ikinyahongiriya" },
{ "id", "Ikinyendoziya" },
{ "ig", "Ikigubo" },
{ "it", "Igitaliyani" },
{ "ja", "Ikiyapani" },
{ "jv", "Ikinyejava" },
{ "km", "Igikambodiya" },
{ "ko", "Ikinyakoreya" },
{ "ms", "Ikinyamaleziya" },
{ "my", "Ikinyabirimaniya" },
{ "ne", "Ikinepali" },
{ "nl", "Igiholandi" },
{ "pa", "Igipunjabi" },
{ "pl", "Ikinyapolonye" },
{ "pt", "Igiporutugari" },
{ "rn", "Ikirundi" },
{ "ro", "Ikinyarumaniya" },
{ "ru", "Ikirusiya" },
{ "rw", "Ikinyarwanda" },
{ "so", "Igisomali" },
{ "sv", "Igisuweduwa" },
{ "ta", "Igitamili" },
{ "th", "Ikinyatayilandi" },
{ "tr", "Igiturukiya" },
{ "uk", "Ikinyayukereni" },
{ "ur", "Inyeyurudu" },
{ "vi", "Ikinyaviyetinamu" },
{ "yo", "Ikiyoruba" },
{ "zh", "Igishinwa" },
{ "zu", "Ikizulu" },
};
return data;
}
}
|
3e1483a315801dbe4dc58a4cb345609e7da780eb | 467 | java | Java | udemy/curso-java/exercicios/src/arrays/EqualsHashCode.java | pedrolpsouza/curso-java-udemy | 587982f4550289766a0e5e415eef9454aee93ff7 | [
"MIT"
] | null | null | null | udemy/curso-java/exercicios/src/arrays/EqualsHashCode.java | pedrolpsouza/curso-java-udemy | 587982f4550289766a0e5e415eef9454aee93ff7 | [
"MIT"
] | null | null | null | udemy/curso-java/exercicios/src/arrays/EqualsHashCode.java | pedrolpsouza/curso-java-udemy | 587982f4550289766a0e5e415eef9454aee93ff7 | [
"MIT"
] | null | null | null | 22.045455 | 41 | 0.643299 | 8,691 | package arrays;
public class EqualsHashCode {
public static void main(String[] args) {
Usuario u1 = new Usuario();
u1.nome = "Pedro";
u1.email = "lyhxr@example.com";
Usuario u2 = new Usuario();
u2.nome = "Pedro";
u2.email = "lyhxr@example.com";
Usuario u3 = new Usuario();
u3.nome = "LOLZAO";
u3.email = "lyhxr@example.com";
//System.out.println(u1 == u2);
System.out.println(u1.equals(u2));
System.out.println(u2.equals(u3));
}
}
|
3e1483d9afd98ae68c12d8dc199e87e481164888 | 4,675 | java | Java | com/smartg/icc/Curve.java | andronix3/ICC | 9ed42bca7a6a2db14f61c28f25c229e48af9de84 | [
"BSD-3-Clause"
] | 1 | 2019-03-14T08:24:26.000Z | 2019-03-14T08:24:26.000Z | com/smartg/icc/Curve.java | andronix3/ICC | 9ed42bca7a6a2db14f61c28f25c229e48af9de84 | [
"BSD-3-Clause"
] | null | null | null | com/smartg/icc/Curve.java | andronix3/ICC | 9ed42bca7a6a2db14f61c28f25c229e48af9de84 | [
"BSD-3-Clause"
] | null | null | null | 27.5 | 96 | 0.644278 | 8,692 | /*
* Copyright (c) Andrey Kuznetsov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of imagero Andrey Kuznetsov nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.smartg.icc;
import com.smartg.icc.tag.Tag;
import com.smartg.icc.tag.Tag.ICurve;
import com.smartg.icc.tag.TagType;
public class Curve extends Tag implements ICurve {
int entryCount;
float[] values;
Curve inverse;
float gamma;
public Curve(float[] values) {
this(TagType.CURVE_TYPE, values);
}
public Curve(TagType tagType, float[] values) {
super(tagType);
this.values = values;
setValues(values);
}
protected void setValues(float[] values) {
if (values == null) {
entryCount = 0;
} else if (values.length == 1) {
gamma = values[0];
entryCount = 1;
} else {
entryCount = values.length;
}
}
boolean isIdentity() {
return entryCount == 0;
}
boolean isGamma() {
return entryCount == 1;
}
boolean isCurve() {
return entryCount > 1;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Curve: {");
sb.append("[entryCount=" + entryCount + "] ");
sb.append("[isIdentity=" + isIdentity() + "] ");
sb.append("[isGamma=" + isGamma() + "] ");
sb.append("[isCurve=" + isCurve() + "] ");
if (isGamma()) {
sb.append("[gamma=" + gamma + "]");
}
sb.append("}");
return sb.toString();
}
public float get(float a) {
if (isIdentity()) {
return a;
} else if (isGamma()) {
return (float) Math.pow(a, gamma);
} else {
if (a > 1.0f) {
return values[values.length - 1];
} else if (a < 0) {
return values[0];
}
int index = (int) (a * values.length);
if (index >= values.length) {
return values[values.length - 1];
}
if (index <= 0) {
return values[0];
}
int index2 = index + 1;
float length = values.length;
float smin = index / length;
float smax = index2 / length;
float dmin = values[index - 1];
float dmax = values[index2 - 1];
return interpolate(a, smin, smax, dmin, dmax);
}
}
protected final float interpolate(float x, float smin, float smax, float dmin, float dmax) {
float dHeight = dmax - dmin;
float sHeight = smax - smin;
return dmin + ((x - smin) * (dHeight / sHeight));
}
public ICurve inverse() {
if (inverse == null) {
if (entryCount > 1) {
float[] ivalues = new float[entryCount];
int prevIndex = 0;
for (int i = 0; i < entryCount; i++) {
float f = values[i];
int index = (int) (f * (entryCount - 1));
if (index < entryCount) {
for (int j = prevIndex + 1; j <= index; j++) {
ivalues[j] = i / (float) entryCount;
}
}
prevIndex = index;
}
inverse = new Curve(getTagType(), ivalues);
inverse.inverse = this;
} else if (entryCount == 1) {
float[] ivalues = new float[1];
float igamma = 1f / gamma;
ivalues[0] = igamma;
inverse = new Curve(getTagType(), ivalues);
inverse.inverse = this;
} else {
inverse = this;
}
}
return inverse;
}
public int getEntryCount() {
return entryCount;
}
public float getGamma() {
return gamma;
}
public float[] getValues() {
return values;
}
} |
3e1483d9e7d54f675830dbf11de5d3373a5b0a54 | 274 | java | Java | chapter_002/src/main/java/ru/job4j/chess/OccupiedCellException.java | wolfdog007/aruzhev | 90e1fc0dfd14c167e1ee9c65ee1c11c90321e629 | [
"Apache-2.0"
] | null | null | null | chapter_002/src/main/java/ru/job4j/chess/OccupiedCellException.java | wolfdog007/aruzhev | 90e1fc0dfd14c167e1ee9c65ee1c11c90321e629 | [
"Apache-2.0"
] | null | null | null | chapter_002/src/main/java/ru/job4j/chess/OccupiedCellException.java | wolfdog007/aruzhev | 90e1fc0dfd14c167e1ee9c65ee1c11c90321e629 | [
"Apache-2.0"
] | null | null | null | 17.125 | 54 | 0.624088 | 8,693 | package ru.job4j.chess;
/**
* @author Ruzhev Alexander
* @since 08.05.2017
*/
public class OccupiedCellException extends Exception {
/**
* Constructor.
* @param msg message
*/
public OccupiedCellException(String msg) {
super(msg);
}
}
|
3e148414b1256bf01f1789ebc46967bb7c17262c | 568 | java | Java | src/main/java/mho/wheels/iterables/NoRemoveIterator.java | mhogrefe/wheels | 15696dae9e4ae00f31baf77374f263449295062d | [
"MIT"
] | 3 | 2015-07-17T20:18:48.000Z | 2019-07-15T19:06:38.000Z | src/main/java/mho/wheels/iterables/NoRemoveIterator.java | mhogrefe/wheels | 15696dae9e4ae00f31baf77374f263449295062d | [
"MIT"
] | 1 | 2019-07-15T20:59:39.000Z | 2019-07-15T20:59:39.000Z | src/main/java/mho/wheels/iterables/NoRemoveIterator.java | mhogrefe/wheels | 15696dae9e4ae00f31baf77374f263449295062d | [
"MIT"
] | null | null | null | 28.4 | 111 | 0.697183 | 8,694 | package mho.wheels.iterables;
import java.util.Iterator;
/**
* An {@code Iterator} which does not support the {@link Iterator#remove()} method. If removal is attempted, an
* exception is thrown.
*
* @param <T> the type of the elements returned by this {@code NoRemoveIterator}
*/
public abstract class NoRemoveIterator<T> implements Iterator<T> {
/**
* Throw an exception if removal is attempted.
*/
@Override
public final void remove() {
throw new UnsupportedOperationException("This Iterator does not support removal.");
}
}
|
3e148440d6fb8f106d4c7dbe6e348b6bdc2db5bb | 217 | java | Java | src/main/java/moe/soaryn/spring002/repository/Clientes.java | SoarynAC/spring-angular-ws-api | 339e13f59aadde0e8ca7e2a5ae92175167436f1f | [
"MIT"
] | null | null | null | src/main/java/moe/soaryn/spring002/repository/Clientes.java | SoarynAC/spring-angular-ws-api | 339e13f59aadde0e8ca7e2a5ae92175167436f1f | [
"MIT"
] | null | null | null | src/main/java/moe/soaryn/spring002/repository/Clientes.java | SoarynAC/spring-angular-ws-api | 339e13f59aadde0e8ca7e2a5ae92175167436f1f | [
"MIT"
] | null | null | null | 21.7 | 64 | 0.824885 | 8,695 | package moe.soaryn.spring002.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import moe.soaryn.spring002.model.Cliente;
public interface Clientes extends JpaRepository<Cliente, Long> {
}
|
3e14848f9777f7b3a337052e7442494cf2890b4a | 1,180 | java | Java | src/main/java/cn/bestlang/algs/offer2/MaxSlidingWindow.java | ligenhw/algs | 097802acfa8adba9685a21cd4729feaa1c7018e1 | [
"MIT"
] | null | null | null | src/main/java/cn/bestlang/algs/offer2/MaxSlidingWindow.java | ligenhw/algs | 097802acfa8adba9685a21cd4729feaa1c7018e1 | [
"MIT"
] | null | null | null | src/main/java/cn/bestlang/algs/offer2/MaxSlidingWindow.java | ligenhw/algs | 097802acfa8adba9685a21cd4729feaa1c7018e1 | [
"MIT"
] | null | null | null | 23.137255 | 55 | 0.479661 | 8,696 | package cn.bestlang.algs.offer2;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
public class MaxSlidingWindow {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length == 0) {
return new int[]{};
}
PriorityQueue<Node> pq = new PriorityQueue<>();
Queue<Node> queue = new LinkedList<>();
for (int i = 0; i < k - 1; i++) {
Node node = new Node(nums[i], i);
pq.add(node);
queue.add(node);
}
int[] max = new int[nums.length - k + 1];
for (int i = k - 1; i < nums.length; i++) {
Node node = new Node(nums[i], i);
pq.add(node);
queue.add(node);
max[i - k + 1] = pq.peek().val;
Node poll = queue.poll();
pq.remove(poll);
}
return max;
}
static class Node implements Comparable<Node>{
int val;
int index;
public Node(int v, int i) {
val = v;
index = i;
}
@Override
public int compareTo(Node o) {
return o.val - val;
}
}
}
|
3e1484bd47823b2130098e1fc4135e9f374d9012 | 1,954 | java | Java | src/main/java/net/rhysholloway/donutmod/client/render/entity/LightDiscEntityRenderer.java | DoNotDoughnut/DonutMod1 | 772e9729817b71da8fa18cd30b7bd0945edac567 | [
"CC0-1.0"
] | null | null | null | src/main/java/net/rhysholloway/donutmod/client/render/entity/LightDiscEntityRenderer.java | DoNotDoughnut/DonutMod1 | 772e9729817b71da8fa18cd30b7bd0945edac567 | [
"CC0-1.0"
] | null | null | null | src/main/java/net/rhysholloway/donutmod/client/render/entity/LightDiscEntityRenderer.java | DoNotDoughnut/DonutMod1 | 772e9729817b71da8fa18cd30b7bd0945edac567 | [
"CC0-1.0"
] | null | null | null | 44.409091 | 152 | 0.817298 | 8,697 | package net.rhysholloway.donutmod.client.render.entity;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.EntityRenderDispatcher;
import net.minecraft.client.render.entity.EntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.MathHelper;
import net.rhysholloway.donutmod.DonutMod;
import net.rhysholloway.donutmod.client.render.entity.model.LightDiscModel;
import net.rhysholloway.donutmod.entity.projectile.LightDiscEntity;
public class LightDiscEntityRenderer extends EntityRenderer<LightDiscEntity> {
public static final Identifier TEXTURE = new Identifier(DonutMod.modId, "textures/entity/light_disc.png");
private LightDiscModel model;
public LightDiscEntityRenderer(EntityRenderDispatcher dispatcher) {
super(dispatcher);
model = new LightDiscModel();
}
public void render(LightDiscEntity entity, float yaw, float tickDelta, MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i) {
matrixStack.push();
matrixStack.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion(MathHelper.lerp(tickDelta, entity.prevYaw, entity.yaw) - 90.0F));
matrixStack.multiply(Vector3f.POSITIVE_Z.getDegreesQuaternion(MathHelper.lerp(tickDelta, entity.prevPitch, entity.pitch)));
this.model.setAngles(entity, tickDelta, 0.0F, -0.1F, 0.0F, 0.0F);
VertexConsumer vertexConsumer = vertexConsumerProvider.getBuffer(this.model.getLayer(TEXTURE));
this.model.render(matrixStack, vertexConsumer, i, OverlayTexture.DEFAULT_UV, 1.0F, 1.0F, 1.0F, 1.0F);
matrixStack.pop();
super.render(entity, yaw, tickDelta, matrixStack, vertexConsumerProvider, i);
}
@Override
public Identifier getTexture(LightDiscEntity entity) {
return TEXTURE;
}
}
|
3e1484cc8a858ff97f6aa5f86583e85c22431c3d | 1,971 | java | Java | carstore/src/main/java/com/gwtplatform/carstore/client/application/rating/RatingMobileModule.java | ArcBees/GWTP-Samples | 1b5d931ff1095037cef68d78acba60df6875c1a9 | [
"Apache-2.0"
] | 39 | 2015-02-02T14:52:06.000Z | 2020-01-17T09:21:55.000Z | carstore/src/main/java/com/gwtplatform/carstore/client/application/rating/RatingMobileModule.java | enterstudio/GWTP-Samples | 127c4c269b6884d1cdab6868224ef93bfd26f615 | [
"Apache-2.0"
] | 40 | 2015-01-08T15:15:56.000Z | 2019-06-27T11:06:32.000Z | carstore/src/main/java/com/gwtplatform/carstore/client/application/rating/RatingMobileModule.java | enterstudio/GWTP-Samples | 127c4c269b6884d1cdab6868224ef93bfd26f615 | [
"Apache-2.0"
] | 63 | 2015-02-01T20:56:16.000Z | 2021-06-05T10:21:23.000Z | 44.795455 | 120 | 0.783359 | 8,698 | /*
* Copyright 2013 ArcBees 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.gwtplatform.carstore.client.application.rating;
import com.google.gwt.inject.client.assistedinject.GinFactoryModuleBuilder;
import com.gwtplatform.carstore.client.application.rating.renderer.RatingCellFactory;
import com.gwtplatform.carstore.client.application.rating.ui.EditRatingPresenter;
import com.gwtplatform.carstore.client.application.rating.ui.EditRatingUiHandlers;
import com.gwtplatform.carstore.client.application.rating.ui.EditRatingView;
import com.gwtplatform.mvp.client.gin.AbstractPresenterModule;
public class RatingMobileModule extends AbstractPresenterModule {
@Override
protected void configure() {
install(new GinFactoryModuleBuilder().build(RatingCellFactory.class));
bindPresenter(RatingPresenter.class, RatingPresenter.MyView.class, RatingMobileView.class,
RatingPresenter.MyProxy.class);
bindPresenter(RatingDetailPresenter.class, RatingDetailPresenter.MyView.class, RatingDetailView.class,
RatingDetailPresenter.MyProxy.class);
bindSingletonPresenterWidget(EditRatingPresenter.class, EditRatingPresenter.MyView.class, EditRatingView.class);
bind(EditRatingUiHandlers.class).to(EditRatingPresenter.class);
bind(RatingUiHandlers.class).to(RatingPresenter.class);
bind(RatingDetailUiHandlers.class).to(RatingDetailPresenter.class);
}
}
|
3e14863caac84fb506f67922d0372269f493d92f | 1,488 | java | Java | src/awt/java/awt/image/RasterFormatException.java | dritanlatifi/AndroidPrefuse | 53ba64c2a1f95bfacedf6592361ad039233018c4 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 2 | 2016-02-22T10:33:04.000Z | 2016-10-12T01:35:48.000Z | src/awt/java/awt/image/RasterFormatException.java | dritanlatifi/AndroidPrefuse | 53ba64c2a1f95bfacedf6592361ad039233018c4 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2016-10-12T02:14:41.000Z | 2016-10-14T10:21:42.000Z | src/awt/java/awt/image/RasterFormatException.java | dritanlatifi/AndroidPrefuse | 53ba64c2a1f95bfacedf6592361ad039233018c4 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | 30.367347 | 79 | 0.700941 | 8,699 | /*
* 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.
*/
/**
* @author Igor V. Stolyarov
* @version $Revision$
*/
package awt.java.awt.image;
/**
* The RasterFormatException class represents the exception that is thrown when
* there's an invalid layout in the Raster.
*
* @since Android 1.0
*/
public class RasterFormatException extends RuntimeException {
/**
* The Constant serialVersionUID.
*/
private static final long serialVersionUID = 96598996116164315L;
/**
* Instantiates a new RasterFormatException with the specified detail
* message.
*
* @param s
* the detail message.
*/
public RasterFormatException(String s) {
super(s);
}
}
|
3e1486589216478b868afc263709c68dfd443aaf | 629 | java | Java | VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/RandomHealthIndicator.java | habuma/nfjs-samples | ada4e63e84e3db9d61c4a21bb878b37e026fa611 | [
"Apache-2.0"
] | 14 | 2018-05-06T15:03:10.000Z | 2021-09-24T17:20:23.000Z | VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/RandomHealthIndicator.java | habuma/nfjs-samples | ada4e63e84e3db9d61c4a21bb878b37e026fa611 | [
"Apache-2.0"
] | null | null | null | VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/RandomHealthIndicator.java | habuma/nfjs-samples | ada4e63e84e3db9d61c4a21bb878b37e026fa611 | [
"Apache-2.0"
] | 15 | 2018-03-17T20:01:17.000Z | 2022-03-30T15:49:29.000Z | 20.290323 | 72 | 0.682035 | 8,700 | package habuma;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class RandomHealthIndicator
implements HealthIndicator {
@Override
public Health health() {
double random = Math.random();
if (random > 0.5) {
// healthy
return Health
.up()
.withDetail("reason", "The value is sufficiently large: " + random)
.build();
}
// not-healthy
return Health
.down()
.withDetail("reason", "The value is too small: " + random)
.build();
}
}
|
3e148671dce42c8789a8690e76519fe2ba8c5816 | 246 | java | Java | etlloader/src/main/java/com/example/mapper/execute/ExecuteMapper.java | chenyingjie1001/etlloader | 46ebb60684add34bec7e7a14365f84dda22bdf7e | [
"Apache-2.0"
] | null | null | null | etlloader/src/main/java/com/example/mapper/execute/ExecuteMapper.java | chenyingjie1001/etlloader | 46ebb60684add34bec7e7a14365f84dda22bdf7e | [
"Apache-2.0"
] | null | null | null | etlloader/src/main/java/com/example/mapper/execute/ExecuteMapper.java | chenyingjie1001/etlloader | 46ebb60684add34bec7e7a14365f84dda22bdf7e | [
"Apache-2.0"
] | null | null | null | 20.5 | 63 | 0.825203 | 8,701 | package com.example.mapper.execute;
import org.apache.ibatis.annotations.Mapper;
import com.example.dto.execute.ExecuteTask;
import com.example.mapper.base.BaseMapper;
@Mapper
public interface ExecuteMapper extends BaseMapper<ExecuteTask>{
} |
3e1487791f403585034742ed670fbba56dc12675 | 2,165 | java | Java | graphsdk/src/main/java/com/microsoft/graph/generated/BaseWorkbookTableSortApplyBody.java | SailReal/msgraph-sdk-android | 68bf5bf437e8688142493de5faf88154c388d7c8 | [
"MIT"
] | 61 | 2016-06-11T20:14:35.000Z | 2021-06-09T03:47:07.000Z | graphsdk/src/main/java/com/microsoft/graph/generated/BaseWorkbookTableSortApplyBody.java | SailReal/msgraph-sdk-android | 68bf5bf437e8688142493de5faf88154c388d7c8 | [
"MIT"
] | 95 | 2016-03-30T22:16:20.000Z | 2020-09-03T18:37:43.000Z | graphsdk/src/main/java/com/microsoft/graph/generated/BaseWorkbookTableSortApplyBody.java | SailReal/msgraph-sdk-android | 68bf5bf437e8688142493de5faf88154c388d7c8 | [
"MIT"
] | 49 | 2016-03-30T19:52:31.000Z | 2022-02-25T11:04:50.000Z | 23.791209 | 152 | 0.606467 | 8,702 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.generated;
import com.microsoft.graph.concurrency.*;
import com.microsoft.graph.core.*;
import com.microsoft.graph.extensions.*;
import com.microsoft.graph.http.*;
import com.microsoft.graph.generated.*;
import com.microsoft.graph.options.*;
import com.microsoft.graph.serializer.*;
import java.util.Arrays;
import java.util.EnumSet;
import com.google.gson.JsonObject;
import com.google.gson.annotations.*;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Base Workbook Table Sort Apply Body.
*/
public class BaseWorkbookTableSortApplyBody {
/**
* The fields.
*
*/
@SerializedName("fields")
@Expose
public java.util.List<WorkbookSortField> fields;
/**
* The match Case.
*
*/
@SerializedName("matchCase")
@Expose
public Boolean matchCase;
/**
* The method.
*
*/
@SerializedName("method")
@Expose
public String method;
/**
* The raw representation of this class
*/
private transient JsonObject mRawObject;
/**
* The serializer
*/
private transient ISerializer mSerializer;
/**
* Gets the raw representation of this class
* @return the raw representation of this class
*/
public JsonObject getRawObject() {
return mRawObject;
}
/**
* Gets serializer
* @return the serializer
*/
protected ISerializer getSerializer() {
return mSerializer;
}
/**
* Sets the raw json object
*
* @param serializer The serializer
* @param json The json object to set this object to
*/
public void setRawObject(final ISerializer serializer, final JsonObject json) {
mSerializer = serializer;
mRawObject = json;
}
}
|
3e14878cb146227ca4567e82b38ffea7ce44e1c0 | 3,758 | java | Java | src/main/java/com/Calendars.java | Biokinetica/StanzaLib | 0af0467c82bf8d8eaa2e03d020ba4bca94ebbc6b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/Calendars.java | Biokinetica/StanzaLib | 0af0467c82bf8d8eaa2e03d020ba4bca94ebbc6b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/Calendars.java | Biokinetica/StanzaLib | 0af0467c82bf8d8eaa2e03d020ba4bca94ebbc6b | [
"Apache-2.0"
] | null | null | null | 39.557895 | 130 | 0.646088 | 8,703 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.models.CalendarRequest;
import com.models.CalendarResponse;
import com.models.DeleteCalendar;
import com.models.DeleteResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
*
* @author Brenton
*/
public class Calendars extends Concept {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public Calendars(StanzaClient client){
super(client);
}
public CalendarResponse getCalendar(String shortName){
HttpUrl.Builder url = new HttpUrl.Builder();
url.scheme("https")
.host("www.stanza.co")
.addEncodedPathSegment("/api/developer/")
.addEncodedPathSegment("retrieve_calendar")
.addEncodedQueryParameter("calendarShortname", shortName);
Request.Builder request = client.getRequestBuilder()
.get()
.url(url.build());
Response Stanza = client.executeRequest(request.build());
CalendarResponse calResponse = new CalendarResponse();
try {
calResponse = mapper.readValue(Stanza.body().string(), mapper.getTypeFactory().constructType(CalendarResponse.class));
} catch (IOException e) {
e.printStackTrace();
Logger.getLogger(Calendars.class.getName()).log(Level.SEVERE, null, e);
}
return calResponse;
}
public CalendarResponse createCalendar(CalendarRequest cal){
try {
Request.Builder request = client.getRequestBuilder()
.post(RequestBody.create(JSON, mapper.writeValueAsString(cal)))
.url("https://www.stanza.co/api/developer/create_calendar");
Response calResponse = client.executeRequest(request.build());
return mapper.readValue(calResponse.body().string(), mapper.getTypeFactory().constructType(CalendarResponse.class));
} catch (JsonProcessingException ex) {
Logger.getLogger(Calendars.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Calendars.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public DeleteResponse deleteCalendar(DeleteCalendar shortName){
HttpUrl.Builder url = new HttpUrl.Builder();
url.scheme("https")
.host("www.stanza.co")
.addEncodedPathSegment("/api/developer/")
.addEncodedPathSegment("delete_calendar")
.addEncodedPathSegment(shortName.getShortname());
try {
Request.Builder request = client.getRequestBuilder()
.delete(RequestBody.create(JSON, mapper.writeValueAsString(shortName)))
.url(url.build());
Response delResponse = client.executeRequest(request.build());
return mapper.readValue(delResponse.body().string(), mapper.getTypeFactory().constructType(DeleteResponse.class));
} catch (JsonProcessingException ex) {
Logger.getLogger(Calendars.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Calendars.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
|
3e1489e2a2ef8e06093706c6d6994ccd67c5ddf1 | 3,501 | java | Java | src/main/java/com/sri/ai/grinder/theory/base/LiteralStepSolver.java | ctjoreilly/aic-expresso | 01b0bbc33c2ad37fea12a645cbc6105abc7e5352 | [
"BSD-3-Clause"
] | 8 | 2015-05-08T23:13:56.000Z | 2018-03-28T13:42:26.000Z | src/main/java/com/sri/ai/grinder/theory/base/LiteralStepSolver.java | ctjoreilly/aic-expresso | 01b0bbc33c2ad37fea12a645cbc6105abc7e5352 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/sri/ai/grinder/theory/base/LiteralStepSolver.java | ctjoreilly/aic-expresso | 01b0bbc33c2ad37fea12a645cbc6105abc7e5352 | [
"BSD-3-Clause"
] | 1 | 2018-04-25T23:45:11.000Z | 2018-04-25T23:45:11.000Z | 36.46875 | 102 | 0.756927 | 8,704 | /*
* Copyright (c) 2013, SRI International
* All rights reserved.
* Licensed under the The BSD 3-Clause License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the aic-expresso nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sri.ai.grinder.theory.base;
import static com.sri.ai.grinder.theory.base.ConstantStepSolver.constantStepSolver;
import com.google.common.annotations.Beta;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.grinder.api.Context;
import com.sri.ai.grinder.api.StepSolver;
import com.sri.ai.grinder.core.constraint.ContextSplitting;
/**
* A context-dependent problem step solver
* that simply decides whether a literal is true or not.
* <p>
* <p>
* Note that this is different from {@link LiteralExpressionStepSolver}
* because that class produces a boolean {@link Expression}.
*
* @author braz
*
*/
@Beta
public class LiteralStepSolver implements StepSolver<Boolean> {
protected Expression literal;
public LiteralStepSolver(Expression literal) {
super();
this.literal = literal;
}
@Override
public LiteralStepSolver clone() {
try {
return (LiteralStepSolver) super.clone();
} catch (CloneNotSupportedException e) {
throw new Error("Trying to clone " + getClass() + " but cloning is not supported for this class.");
}
}
@Override
public StepSolver.Step<Boolean> step(Context context) {
ContextSplitting split = new ContextSplitting(literal, context);
switch (split.getResult()) {
case CONSTRAINT_IS_CONTRADICTORY:
return null;
case LITERAL_IS_TRUE:
return new Solution<Boolean>(true);
case LITERAL_IS_FALSE:
return new Solution<Boolean>(false);
case LITERAL_IS_UNDEFINED:
StepSolver<Boolean> ifTrue = constantStepSolver(true);
StepSolver<Boolean> ifFalse = constantStepSolver(false);
return new ItDependsOn<Boolean>(literal, split, ifTrue, ifFalse);
default:
throw new Error("Unrecognized splitting result.");
}
}
} |
3e1489e59a4874ce43b7018411e58906e16eb6a2 | 1,426 | java | Java | src/main/java/com/licel/jcardsim/crypto/KeyWithParameters.java | Jakuje/jcardsim | 0d6635b377b981556db11a5cba591eba039e4e96 | [
"Apache-2.0"
] | 140 | 2015-02-21T10:21:45.000Z | 2022-03-09T08:59:09.000Z | src/main/java/com/licel/jcardsim/crypto/KeyWithParameters.java | petrs/jcardsim | 1fbd556ef7af0d497d497d3909ce2bb1b96383b0 | [
"Apache-2.0"
] | 68 | 2015-01-09T16:26:12.000Z | 2022-03-15T03:59:59.000Z | src/main/java/com/licel/jcardsim/crypto/KeyWithParameters.java | petrs/jcardsim | 1fbd556ef7af0d497d497d3909ce2bb1b96383b0 | [
"Apache-2.0"
] | 92 | 2015-01-19T14:16:30.000Z | 2021-07-24T19:00:27.000Z | 30.340426 | 80 | 0.726508 | 8,705 | /*
* Copyright 2011 Licel 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.licel.jcardsim.crypto;
import java.security.SecureRandom;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.KeyGenerationParameters;
/**
* KeyWithParameters.
*/
public interface KeyWithParameters {
/**
* Get cipher key parameters for use with BouncyCastle Crypto API
*
* @return key parameters
*/
public CipherParameters getParameters();
/**
* Get keypair generation parameters for use with BouncyCastle Crypto API
* @param rnd Secure Random Generator
* @return key parameters
*/
public KeyGenerationParameters getKeyGenerationParameters(SecureRandom rnd);
/**
* Set cipher key for use with BouncyCastle Crypto API
* @param params key parameters
*/
public void setParameters(CipherParameters params);
}
|
3e1489e9a6f2df8a8e70002c07a5b7828365e60f | 2,617 | java | Java | ChickenNugget/app/src/main/java/com/example/chickennugget/MainActivity.java | saumitrasapre/android-practice-codes | 597104f1f2cd5eec99e16026fcab3333d9bc18d7 | [
"MIT"
] | 2 | 2020-05-18T23:02:39.000Z | 2021-05-08T19:53:14.000Z | ChickenNugget/app/src/main/java/com/example/chickennugget/MainActivity.java | saumitrasapre/android-practice-codes | 597104f1f2cd5eec99e16026fcab3333d9bc18d7 | [
"MIT"
] | null | null | null | ChickenNugget/app/src/main/java/com/example/chickennugget/MainActivity.java | saumitrasapre/android-practice-codes | 597104f1f2cd5eec99e16026fcab3333d9bc18d7 | [
"MIT"
] | null | null | null | 25.163462 | 134 | 0.659534 | 8,706 | package com.example.chickennugget;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GestureDetectorCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener {
TextView txtgo;
GestureDetectorCompat mygestdetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btngo=findViewById(R.id.appButton);
txtgo=findViewById(R.id.chickenMessage);
this.mygestdetector=new GestureDetectorCompat(this,this);
mygestdetector.setOnDoubleTapListener(this);
btngo.setOnClickListener(
new Button.OnClickListener()
{
public void onClick (View v)
{
txtgo.setText("Cha Cha Real Smooth!");
}
}
);
}
//GESTURES BEGIN
@Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
txtgo.setText("Single Tap!");
return true;
}
@Override
public boolean onDoubleTap(MotionEvent motionEvent) {
txtgo.setText("Double Tap!");
return true;
}
@Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
txtgo.setText("Double Tap!");
return true;
}
@Override
public boolean onDown(MotionEvent motionEvent) {
txtgo.setText("Down!");
return true;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
txtgo.setText("Up!");
return true;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
txtgo.setText("Scroll!");
return true;
}
@Override
public void onLongPress(MotionEvent motionEvent) {
txtgo.setText("Long Press!");
}
@Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
txtgo.setText("Fling!");
return true;
}
//GESTURES END
@Override
public boolean onTouchEvent(MotionEvent event) {
this.mygestdetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
}
|
3e148a2da3b0f65619f1767016da1c0e03f9a204 | 919 | java | Java | src/com/lidroid/xutils/http/client/entity/UploadEntity.java | gongmingming/BarCodeScan | 247876f0c2f2ec6be25ec0f203cf1f6e4aefd27e | [
"Apache-2.0"
] | 1,037 | 2015-01-04T12:34:16.000Z | 2022-03-22T16:30:32.000Z | src/com/lidroid/xutils/http/client/entity/UploadEntity.java | gongmingming/BarCodeScan | 247876f0c2f2ec6be25ec0f203cf1f6e4aefd27e | [
"Apache-2.0"
] | 3 | 2015-03-03T09:35:46.000Z | 2016-01-07T14:50:28.000Z | src/com/lidroid/xutils/http/client/entity/UploadEntity.java | gongmingming/BarCodeScan | 247876f0c2f2ec6be25ec0f203cf1f6e4aefd27e | [
"Apache-2.0"
] | 890 | 2015-01-06T08:37:27.000Z | 2021-07-29T05:37:33.000Z | 31.689655 | 75 | 0.744287 | 8,707 | /*
* Copyright (c) 2013. wyouflf (upchh@example.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.lidroid.xutils.http.client.entity;
import com.lidroid.xutils.http.callback.RequestCallBackHandler;
/**
* Created with IntelliJ IDEA.
* User: wyouflf
* Date: 13-7-3
* Time: 下午1:40
*/
public interface UploadEntity {
void setCallBackHandler(RequestCallBackHandler callBackHandler);
}
|
3e148adc20c59c7fdaa444aa20c7c292bf54bd89 | 783 | java | Java | http/src/main/java/com/parting_soul/http/net/request/MultipartRequest.java | PartingSoul/HttpUtils | 5e513afb2b4d01e76e23ce5472666e9ce57fe322 | [
"Apache-2.0"
] | null | null | null | http/src/main/java/com/parting_soul/http/net/request/MultipartRequest.java | PartingSoul/HttpUtils | 5e513afb2b4d01e76e23ce5472666e9ce57fe322 | [
"Apache-2.0"
] | null | null | null | http/src/main/java/com/parting_soul/http/net/request/MultipartRequest.java | PartingSoul/HttpUtils | 5e513afb2b4d01e76e23ce5472666e9ce57fe322 | [
"Apache-2.0"
] | null | null | null | 19.097561 | 75 | 0.614304 | 8,708 | package com.parting_soul.http.net.request;
import com.parting_soul.http.bean.FilePair;
import java.util.HashMap;
import java.util.Map;
/**
* @author parting_soul
* @date 2019-07-23
*/
public final class MultipartRequest extends BaseRequest<MultipartRequest> {
private Map<String, FilePair> mFilePairs;
public MultipartRequest(String url) {
super(url);
}
@Override
public Map<String, FilePair> getFilePairs() {
return mFilePairs;
}
/**
* 添加文件
*
* @param key
* @param pair
* @return
*/
public BaseRequest addFilePair(String key, FilePair pair) {
if (mFilePairs == null) {
mFilePairs = new HashMap<>();
}
mFilePairs.put(key, pair);
return this;
}
}
|
3e148b9a480b77b77f0525a5edf08bc99eb2ab81 | 573 | java | Java | entfrm-core/entfrm-security/src/main/java/com/entfrm/security/exception/ServerErrorException.java | gyliug/isstech | 82afa54deff81607f50986963c1208dcffe5f15f | [
"MIT"
] | null | null | null | entfrm-core/entfrm-security/src/main/java/com/entfrm/security/exception/ServerErrorException.java | gyliug/isstech | 82afa54deff81607f50986963c1208dcffe5f15f | [
"MIT"
] | null | null | null | entfrm-core/entfrm-security/src/main/java/com/entfrm/security/exception/ServerErrorException.java | gyliug/isstech | 82afa54deff81607f50986963c1208dcffe5f15f | [
"MIT"
] | null | null | null | 20.464286 | 64 | 0.774869 | 8,709 | package com.entfrm.security.exception;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.http.HttpStatus;
/**
* @author entfrm
* @date 2018/7/8
*/
@JsonSerialize(using = EntfrmAuth2ExceptionSerializer.class)
public class ServerErrorException extends EntfrmAuth2Exception {
public ServerErrorException(String msg, Throwable t) {
super(msg);
}
@Override
public String getOAuth2ErrorCode() {
return "server_error";
}
@Override
public int getHttpErrorCode() {
return HttpStatus.INTERNAL_SERVER_ERROR.value();
}
}
|
3e148c2915c8db082fd9a97765f0f74543fa51d6 | 4,083 | java | Java | DnDTools/src/nanotane/DnDGeneratorWindow/generators/EncGenTrevorScot.java | nanotane/DnDTextGenerator | 612fa74b8882d0096406203f5176bde8e6836814 | [
"MIT"
] | null | null | null | DnDTools/src/nanotane/DnDGeneratorWindow/generators/EncGenTrevorScot.java | nanotane/DnDTextGenerator | 612fa74b8882d0096406203f5176bde8e6836814 | [
"MIT"
] | null | null | null | DnDTools/src/nanotane/DnDGeneratorWindow/generators/EncGenTrevorScot.java | nanotane/DnDTextGenerator | 612fa74b8882d0096406203f5176bde8e6836814 | [
"MIT"
] | null | null | null | 31.407692 | 133 | 0.677443 | 8,710 | package nanotane.DnDGeneratorWindow.generators;
import java.util.ArrayList;
import java.util.Random;
import nanotane.DnDGeneratorWindow.TrevorScot.TrevoScotLists;
public class EncGenTrevorScot {
public static String generateCivilizedCountrySide()
{
int randomNum = (int)(Math.random() * 100);
String toReturn = "";
if(isBetween(randomNum, 0, 35)){
toReturn = genPeopleActivity();
} else if(isBetween(randomNum, 31, 35)){
toReturn = genAmbush(TrevoScotLists.CIV_COUNTRYSIDE_AMBUSH, TrevoScotLists.CIV_COUNTRYSIDE_RUSE, TrevoScotLists.AMBUSH_STRATEGY);
} else if(isBetween(randomNum, 36, 45)){
toReturn = genDangerousAnimal();
} else if(isBetween(randomNum, 46, 55)){
toReturn = genHazard();
} else if(isBetween(randomNum, 56, 65)){
toReturn = genOfValue();
} else if(isBetween(randomNum, 66, 100)){
toReturn = genBenign(TrevoScotLists.CIV_COUNTRYSIDE_BENIGN);
}
return toReturn;
}
public static String generateUrbanString()
{
int randomNum = (int)(Math.random() * 100);
String toReturn = "";
if(isBetween(randomNum, 0, 40)){
toReturn = genPeopleActivity();
} else if(isBetween(randomNum, 41, 50)){
toReturn = genAmbush(TrevoScotLists.URBAN_SAFE_AMBUSH, TrevoScotLists.URBAN_SAFE_RUSE, TrevoScotLists.AMBUSH_STRATEGY);
} else if(isBetween(randomNum, 51, 60)){
toReturn = genDangerousAnimal();
} else if(isBetween(randomNum, 61, 70)){
toReturn = genHazard();
} else if(isBetween(randomNum, 71, 80)){
toReturn = genOfValue();
} else if(isBetween(randomNum, 81, 100)){
toReturn = genBenign(TrevoScotLists.URBAN_SAFE_BENIGN);
}
return toReturn;
}
/**
* [People][Activity]
* @return
*/
private static String genPeopleActivity(){
Random rand = new Random();
int people = rand.nextInt(TrevoScotLists.PEOPLE.size());
int activity = rand.nextInt(TrevoScotLists.ACTIVITES.size());
String person = TrevoScotLists.PEOPLE.get(people);
String active = TrevoScotLists.ACTIVITES.get(activity);
if(person.equals("[Professional]")){
person = TrevoScotLists.PROFESSIONAL.get(rand.nextInt(TrevoScotLists.PROFESSIONAL.size()));
} else if(active.equals("[Working Class]")) {
person = TrevoScotLists.WORKING_CLASS.get(rand.nextInt(TrevoScotLists.PROFESSIONAL.size()));
}
return "Random People: " + TrevoScotLists.PEOPLE.get(people) + " " + TrevoScotLists.ACTIVITES.get(activity);
}
/**
* [Ambush] [Ruse] [Strategy]
* @return
*/
private static String genAmbush(ArrayList<String> pAmbush, ArrayList<String> pRuse,
ArrayList<String> pStrategy){
Random rand = new Random();
int ambush = rand.nextInt(pAmbush.size());
int ruse = rand.nextInt(pRuse.size());
int strategy = rand.nextInt(pStrategy.size());
return "Ambush! " + pAmbush.get(ambush) + " " + pRuse.get(ruse) + " " + pStrategy.get(strategy);
}
/**
* Dangerous Animal] [Size]
* @return
*/
private static String genDangerousAnimal(){
Random rand = new Random();
int animal = rand.nextInt(TrevoScotLists.ANIMAL.size());
return "Escaped Animal! " + TrevoScotLists.ANIMAL.get(animal);
}
/**
* [Hazard]
* @return
*/
private static String genHazard(){
Random rand = new Random();
int hazard = rand.nextInt(TrevoScotLists.HAZARDS.size());
return "Hazard: " + TrevoScotLists.HAZARDS.get(hazard);
}
/**
* [Of Value]
* @return
*/
private static String genOfValue(){
Random rand = new Random();
int value = rand.nextInt(TrevoScotLists.CIV_COUNTRYSIDE_LOOT.size());
return "Random Loot: " + TrevoScotLists.CIV_COUNTRYSIDE_LOOT.get(value);
}
/**
* [Benign]
* @return
*/
private static String genBenign(ArrayList<String> pBenign){
Random rand = new Random();
int benign = rand.nextInt(pBenign.size());
return "Benign Event: " + pBenign.get(benign);
}
private static boolean isBetween(int toCheck, int pLow, int pHigh) {
if(toCheck >= pLow && toCheck <= pHigh)
{
return true;
} else {
return false;
}
}
}
|
3e148c95b7a2f1d7d132d4d1232fdbf2e3a339ef | 10,964 | java | Java | subprojects/org.compiere.model/src/java/org/compiere/model/I_C_DunningLevel.java | iDempiere-micro/idempiere-micro | a5c09f37d68950b458cf23ce4a2c50e98c50ea2c | [
"MIT"
] | null | null | null | subprojects/org.compiere.model/src/java/org/compiere/model/I_C_DunningLevel.java | iDempiere-micro/idempiere-micro | a5c09f37d68950b458cf23ce4a2c50e98c50ea2c | [
"MIT"
] | 1 | 2018-07-09T12:41:14.000Z | 2018-07-09T13:13:06.000Z | subprojects/org.compiere.model/src/java/org/compiere/model/I_C_DunningLevel.java | iDempiere-micro/idempiere-micro | a5c09f37d68950b458cf23ce4a2c50e98c50ea2c | [
"MIT"
] | null | null | null | 28.776903 | 92 | 0.693816 | 8,711 | /******************************************************************************
* Product: iDempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2012 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program 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 for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via upchh@example.com or http://www.idempiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.idempiere.common.util.KeyNamePair;
/** Generated Interface for C_DunningLevel
* @author iDempiere (generated)
* @version Release 5.1
*/
public interface I_C_DunningLevel
{
/** TableName=C_DunningLevel */
public static final String Table_Name = "C_DunningLevel";
/** AD_Table_ID=331 */
public static final int Table_ID = 331;
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 3 - Client - Org
*/
BigDecimal accessLevel = BigDecimal.valueOf(3);
/** Load Meta Data */
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name C_Dunning_ID */
public static final String COLUMNNAME_C_Dunning_ID = "C_Dunning_ID";
/** Set Dunning.
* Dunning Rules for overdue invoices
*/
public void setC_Dunning_ID (int C_Dunning_ID);
/** Get Dunning.
* Dunning Rules for overdue invoices
*/
public int getC_Dunning_ID();
public I_C_Dunning getC_Dunning() throws RuntimeException;
/** Column name C_DunningLevel_ID */
public static final String COLUMNNAME_C_DunningLevel_ID = "C_DunningLevel_ID";
/** Set Dunning Level */
public void setC_DunningLevel_ID (int C_DunningLevel_ID);
/** Get Dunning Level */
public int getC_DunningLevel_ID();
/** Column name C_DunningLevel_UU */
public static final String COLUMNNAME_C_DunningLevel_UU = "C_DunningLevel_UU";
/** Set C_DunningLevel_UU */
public void setC_DunningLevel_UU (String C_DunningLevel_UU);
/** Get C_DunningLevel_UU */
public String getC_DunningLevel_UU();
/** Column name ChargeFee */
public static final String COLUMNNAME_ChargeFee = "ChargeFee";
/** Set Charge fee.
* Indicates if fees will be charged for overdue invoices
*/
public void setChargeFee (boolean ChargeFee);
/** Get Charge fee.
* Indicates if fees will be charged for overdue invoices
*/
public boolean isChargeFee();
/** Column name ChargeInterest */
public static final String COLUMNNAME_ChargeInterest = "ChargeInterest";
/** Set Charge Interest.
* Indicates if interest will be charged on overdue invoices
*/
public void setChargeInterest (boolean ChargeInterest);
/** Get Charge Interest.
* Indicates if interest will be charged on overdue invoices
*/
public boolean isChargeInterest();
/** Column name C_PaymentTerm_ID */
public static final String COLUMNNAME_C_PaymentTerm_ID = "C_PaymentTerm_ID";
/** Set Payment Term.
* The terms of Payment (timing, discount)
*/
public void setC_PaymentTerm_ID (int C_PaymentTerm_ID);
/** Get Payment Term.
* The terms of Payment (timing, discount)
*/
public int getC_PaymentTerm_ID();
public I_C_PaymentTerm getC_PaymentTerm() throws RuntimeException;
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name DaysAfterDue */
public static final String COLUMNNAME_DaysAfterDue = "DaysAfterDue";
/** Set Days after due date.
* Days after due date to dun (if negative days until due)
*/
public void setDaysAfterDue (BigDecimal DaysAfterDue);
/** Get Days after due date.
* Days after due date to dun (if negative days until due)
*/
public BigDecimal getDaysAfterDue();
/** Column name DaysBetweenDunning */
public static final String COLUMNNAME_DaysBetweenDunning = "DaysBetweenDunning";
/** Set Days between dunning.
* Days between sending dunning notices
*/
public void setDaysBetweenDunning (int DaysBetweenDunning);
/** Get Days between dunning.
* Days between sending dunning notices
*/
public int getDaysBetweenDunning();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name Dunning_PrintFormat_ID */
public static final String COLUMNNAME_Dunning_PrintFormat_ID = "Dunning_PrintFormat_ID";
/** Set Dunning Print Format.
* Print Format for printing Dunning Letters
*/
public void setDunning_PrintFormat_ID (int Dunning_PrintFormat_ID);
/** Get Dunning Print Format.
* Print Format for printing Dunning Letters
*/
public int getDunning_PrintFormat_ID();
public I_AD_PrintFormat getDunning_PrintFormat() throws RuntimeException;
/** Column name FeeAmt */
public static final String COLUMNNAME_FeeAmt = "FeeAmt";
/** Set Fee Amount.
* Fee amount in invoice currency
*/
public void setFeeAmt (BigDecimal FeeAmt);
/** Get Fee Amount.
* Fee amount in invoice currency
*/
public BigDecimal getFeeAmt();
/** Column name InterestPercent */
public static final String COLUMNNAME_InterestPercent = "InterestPercent";
/** Set Interest in percent.
* Percentage interest to charge on overdue invoices
*/
public void setInterestPercent (BigDecimal InterestPercent);
/** Get Interest in percent.
* Percentage interest to charge on overdue invoices
*/
public BigDecimal getInterestPercent();
/** Column name InvoiceCollectionType */
public static final String COLUMNNAME_InvoiceCollectionType = "InvoiceCollectionType";
/** Set Collection Status.
* Invoice Collection Status
*/
public void setInvoiceCollectionType (String InvoiceCollectionType);
/** Get Collection Status.
* Invoice Collection Status
*/
public String getInvoiceCollectionType();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name IsSetCreditStop */
public static final String COLUMNNAME_IsSetCreditStop = "IsSetCreditStop";
/** Set Credit Stop.
* Set the business partner to credit stop
*/
public void setIsSetCreditStop (boolean IsSetCreditStop);
/** Get Credit Stop.
* Set the business partner to credit stop
*/
public boolean isSetCreditStop();
/** Column name IsSetPaymentTerm */
public static final String COLUMNNAME_IsSetPaymentTerm = "IsSetPaymentTerm";
/** Set Set Payment Term.
* Set the payment term of the Business Partner
*/
public void setIsSetPaymentTerm (boolean IsSetPaymentTerm);
/** Get Set Payment Term.
* Set the payment term of the Business Partner
*/
public boolean isSetPaymentTerm();
/** Column name IsShowAllDue */
public static final String COLUMNNAME_IsShowAllDue = "IsShowAllDue";
/** Set Show All Due.
* Show/print all due invoices
*/
public void setIsShowAllDue (boolean IsShowAllDue);
/** Get Show All Due.
* Show/print all due invoices
*/
public boolean isShowAllDue();
/** Column name IsShowNotDue */
public static final String COLUMNNAME_IsShowNotDue = "IsShowNotDue";
/** Set Show Not Due.
* Show/print all invoices which are not due (yet).
*/
public void setIsShowNotDue (boolean IsShowNotDue);
/** Get Show Not Due.
* Show/print all invoices which are not due (yet).
*/
public boolean isShowNotDue();
/** Column name IsStatement */
public static final String COLUMNNAME_IsStatement = "IsStatement";
/** Set Is Statement.
* Dunning Level is a definition of a statement
*/
public void setIsStatement (boolean IsStatement);
/** Get Is Statement.
* Dunning Level is a definition of a statement
*/
public boolean isStatement();
/** Column name Name */
public static final String COLUMNNAME_Name = "Name";
/** Set Name.
* Alphanumeric identifier of the entity
*/
public void setName (String Name);
/** Get Name.
* Alphanumeric identifier of the entity
*/
public String getName();
/** Column name Note */
public static final String COLUMNNAME_Note = "Note";
/** Set Note.
* Optional additional user defined information
*/
public void setNote (String Note);
/** Get Note.
* Optional additional user defined information
*/
public String getNote();
/** Column name PrintName */
public static final String COLUMNNAME_PrintName = "PrintName";
/** Set Print Text.
* The label text to be printed on a document or correspondence.
*/
public void setPrintName (String PrintName);
/** Get Print Text.
* The label text to be printed on a document or correspondence.
*/
public String getPrintName();
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
}
|
3e148e5676c79eebfe0c62d2a9719e4263a1f36f | 8,788 | java | Java | src/main/java/org/mitre/icarus/cps/app/experiment/phase_05/ExamTiming.java | mitre-icarus/ICArUS-Challenge-Problem-Software-and-Data | de881551af982d625f8f15fc329590893f1299ca | [
"Apache-2.0"
] | null | null | null | src/main/java/org/mitre/icarus/cps/app/experiment/phase_05/ExamTiming.java | mitre-icarus/ICArUS-Challenge-Problem-Software-and-Data | de881551af982d625f8f15fc329590893f1299ca | [
"Apache-2.0"
] | null | null | null | src/main/java/org/mitre/icarus/cps/app/experiment/phase_05/ExamTiming.java | mitre-icarus/ICArUS-Challenge-Problem-Software-and-Data | de881551af982d625f8f15fc329590893f1299ca | [
"Apache-2.0"
] | null | null | null | 35.869388 | 133 | 0.647588 | 8,712 | /*
* NOTICE
* This software was produced for the office of the Director of National Intelligence (ODNI)
* Intelligence Advanced Research Projects Activity (IARPA) ICArUS program,
* BAA number IARPA-BAA-10-04, under contract 2009-0917826-016, and is subject
* to the Rights in Data-General Clause 52.227-14, Alt. IV (DEC 2007).
*
* This software and data is provided strictly to support demonstrations of ICArUS challenge problems
* and to assist in the development of cognitive-neuroscience architectures. It is not intended to be used
* in operational systems or environments.
*
* Copyright (C) 2015 The MITRE Corporation. All Rights Reserved.
*
*/
package org.mitre.icarus.cps.app.experiment.phase_05;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/**
* ExamTiming is used to store and calculate the timing of the different phases
* and trials within a phase for both training and test phases. An ArrayList contains
* a Timing Instance for each phase and trial with the elapsed milliseconds.
*
* @author EOVERLY
*
*/
public class ExamTiming {
private ArrayList <TimingInstance> timings = new ArrayList<TimingInstance>();
public void createTimingInstance(String phaseName, int currentPhase, int currentTrial){
//System.out.println("ExamTiming.createTimingInstance phase= " + currentPhase + " trial= " + currentTrial);
TimingInstance ti = new TimingInstance();
ti.startMillis = System.currentTimeMillis();
ti.phase = currentPhase;
ti.trial = currentTrial;
ti.phaseName = phaseName;
//System.out.println("startMillis= " + ti.startMillis + " phase= " + ti.phase + " trial= " + ti.trial);
timings.add(ti);
//System.out.println("examTiming.size= " + timings.size());
}
public void stopTimingInstance(int currentPhase, int currentTrial){
if(timings.size() == 0)
return;
//System.out.println("ExamTiming.stopTimingInstance phase= " + currentPhase + " trial= " + currentTrial);
int i = timings.size();
TimingInstance ti = (TimingInstance) timings.get(i-1);
timings.remove(ti);
long stopMillis = System.currentTimeMillis();
ti.elapsedMillis = stopMillis - ti.startMillis;
timings.add(ti);
//System.out.println("timings.size= " + timings.size());
//System.out.println("elapsed time= " + ti.elapsedMillis);
}
public ArrayList <TimingInstance> getExamTimings(){
return timings;
}
public class TimingInstance {
long startMillis;
long elapsedMillis;
long lastProbabilityMillis = 0L;
/*
* elapsed time for the user to set the probability
* we can have several probability timings for a particular trial
*/
ArrayList<Long> probabilityTimingArray = new ArrayList<Long>();
int phase;
int trial;
String phaseName;
/*
* when the user is presented with a layer selection
*/
long startLayerSelectMillis;
/*
* elapsed time from when the user was presented with a layer selection
*/
long elapsedLayerSelectMillis;
}
/*
* Set the elapsed time it took the user to select the intel layer selection for a given phase and trial
*/
public void stopLayerSelectTiming(int currentPhase, int currentTrial){
if(timings.size() == 0)
return;
//System.out.println("ExamTiming.stopLayerSelectTiming phase= " + currentPhase + " trial= " + currentTrial);
TimingInstance ti = null;
for(int i=0; i < timings.size(); i++){
ti = timings.get(i);
if((ti.phase == currentPhase) && (ti.trial == currentTrial)){ // find the right timing instance
ti.elapsedLayerSelectMillis = System.currentTimeMillis() - ti.startLayerSelectMillis;
System.out.println("ExamTiming.stopLayerSelectTiming timing= " + ti.elapsedLayerSelectMillis);
return;
}
}
}
/*
* Set the time when the user was presented with an intel layer selection for a given phase and trial
*/
public void startLayerSelectTiming(int currentPhase, int currentTrial){
if(timings.size() == 0)
return;
//System.out.println("ExamTiming.startLayerSelectTiming phase= " + currentPhase + " trial= " + currentTrial);
TimingInstance ti = null;
for(int i=0; i < timings.size(); i++){
ti = timings.get(i);
if((ti.phase == currentPhase) && (ti.trial == currentTrial)){ // find the right timing instance
ti.startLayerSelectMillis = System.currentTimeMillis();
return;
}
}
}
/*
* Return the elapsed time it took the user to select the intel layer selection for a given phase and trial
*/
public long getLayerSelectTiming(int currentPhase, int currentTrial){
if(timings.size() == 0)
return 0L;
//System.out.println("ExamTiming.getLayerSelectTiming phase= " + currentPhase + " trial= " + currentTrial);
TimingInstance ti = null;
for(int i=0; i < timings.size(); i++){
ti = timings.get(i);
if((ti.phase == currentPhase) && (ti.trial == currentTrial)){ // find the right timing instance
System.out.println("ExamTiming.getLayerSelectTiming returning timing=" + ti.elapsedLayerSelectMillis);
return ti.elapsedLayerSelectMillis;
}
}
return 0L; // couldn't find the timing instance
}
/*
* Set the elapsed time it took for the user to set the probability vector in a test trial
*/
public void setProbabilityTiming(int currentPhase, int currentTrial){
if(timings.size() == 0)
return;
//System.out.println("setProbabilityTiming phase= " + currentPhase + " trial= " + currentTrial);
long tempMillis = 0L;
long systemTime = System.currentTimeMillis();
TimingInstance ti = null;
for(int i=0; i < timings.size(); i++){
ti = timings.get(i);
if((ti.phase == currentPhase) && (ti.trial == currentTrial)){ // find the right timing instance
if(ti.probabilityTimingArray.size() == 0){
tempMillis = systemTime - ti.startMillis;
} else {
tempMillis = systemTime - ti.lastProbabilityMillis;
}
ti.probabilityTimingArray.add(tempMillis);
ti.lastProbabilityMillis = systemTime;
return;
}
}
}
/*
* Set the elapsed time it took for the user to set the probability vector in a test trial
*/
public long getProbabilityTiming(int currentPhase, int currentTrial, int index){
if(timings.size() == 0)
return -1L;
//System.out.println("ExamTiming.getProbabilityTiming phase= " + currentPhase + " trial= " + currentTrial + " index= " + index);
TimingInstance ti = null;
for(int i=0; i < timings.size(); i++){
ti = timings.get(i);
if((ti.phase == currentPhase) && (ti.trial == currentTrial)){ // find the right timing instance
if((ti.probabilityTimingArray.size() == 0) || (index + 1 > ti.probabilityTimingArray.size())){
System.err.println("ExamTiming.getProbabilityTiming index out of range, index= " + index);
return -1L;
} else {
//System.out.println("ExamTiming.getProbabilityTiming array size= " + ti.probabilityTimingArray.size());
return ti.probabilityTimingArray.get(index);
}
}
}
return -1L;
}
/*
* Return the sum of the timings for a given phase and trial.
* There might be more than one TimingInstance if the user hit the back button
*/
public long getTiming(int phase, int trial){
//System.out.println("ExamTiming.getTiming phase= " + phase + " trial= " + trial);
TimingInstance ti = null;
long elapsedTime = 0L;
for(int i=0; i < timings.size(); i++){
ti = timings.get(i);
if((ti.phase == phase) && (ti.trial == trial)){
elapsedTime = elapsedTime + ti.elapsedMillis;
}
}
return elapsedTime;
}
/* write timing data to a text file */
@Deprecated
public void saveTimingToFile(String fileName){
TimingInstance ti = null;
String buf = "";
int size = timings.size();
if(size == 0)
return;
//System.out.println("saveTimingToFile ");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
for(int i=0; i < size; i++){
ti = (TimingInstance) timings.get(i);
buf = ti.phaseName + " phase " + ti.phase + " trial " + ti.trial + " elapsed time (seconds) " + ti.elapsedMillis/1000;
out.write(buf);
out.newLine();
}
out.close();
} catch (IOException e) {
System.err.println("Error, could not write timing data to " + fileName);
e.printStackTrace();
}
}
}
|
3e148e641ee2673d3f8f7ea611d10773d6fdb51b | 597 | java | Java | src/main/java/codes/fepi/ldfspark/PageHandler.java | AUTplayed/ldfSpark | b4e786e0a0d500f24b824a47b020b4e120889c8a | [
"MIT"
] | null | null | null | src/main/java/codes/fepi/ldfspark/PageHandler.java | AUTplayed/ldfSpark | b4e786e0a0d500f24b824a47b020b4e120889c8a | [
"MIT"
] | null | null | null | src/main/java/codes/fepi/ldfspark/PageHandler.java | AUTplayed/ldfSpark | b4e786e0a0d500f24b824a47b020b4e120889c8a | [
"MIT"
] | null | null | null | 27.136364 | 107 | 0.728643 | 8,713 | package codes.fepi.ldfspark;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotate a class with this annotation. <br/>
* All methods of the annotated class have to be public to be detected, and have to return something. <br/>
* Possible Parameters are:
* <ul>
* <li>nothing</li>
* <li>spark.Request</li>
* <li>spark.Request, spark.Response</li>
* </ul>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PageHandler {
} |
3e148e73c2f92e9d4a1fa7b64657f844c6234fb3 | 31,430 | java | Java | src/test/java/com/yahoo/bullet/record/BulletRecordTest.java | NathanSpeidel/bullet-record | 84eb41572aac99d68ed11022851d13f2458ba865 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/yahoo/bullet/record/BulletRecordTest.java | NathanSpeidel/bullet-record | 84eb41572aac99d68ed11022851d13f2458ba865 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/yahoo/bullet/record/BulletRecordTest.java | NathanSpeidel/bullet-record | 84eb41572aac99d68ed11022851d13f2458ba865 | [
"Apache-2.0"
] | null | null | null | 41.355263 | 119 | 0.615749 | 8,714 | /*
* Copyright 2016, Yahoo Inc.
* Licensed under the terms of the Apache License, Version 2.0.
* See the LICENSE file associated with the project for terms.
*/
package com.yahoo.bullet.record;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.commons.lang3.tuple.Pair;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
@SuppressWarnings("unchecked")
public class BulletRecordTest {
private BulletRecord record;
public static byte[] getAvroBytes(Map<String, Object> data) {
try {
// Keep this independent from the code
BulletAvro record = new BulletAvro(data);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
SpecificDatumWriter<BulletAvro> writer = new SpecificDatumWriter<>(BulletAvro.class);
Encoder encoder = new EncoderFactory().directBinaryEncoder(stream, null);
stream.reset();
writer.write(record, encoder);
encoder.flush();
return stream.toByteArray();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public static byte[] getRecordBytes(BulletRecord record) {
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(byteStream);
outputStream.writeObject(record);
outputStream.close();
return byteStream.toByteArray();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public static BulletRecord fromRecordBytes(byte[] data) {
try {
ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(data));
return (BulletRecord) stream.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
@BeforeMethod
public void setup() {
record = new BulletRecord();
}
@Test
public void testSetBoolean() {
record.setBoolean("foo", false).setBoolean("bar", true).setBoolean("baz", null);
Assert.assertTrue((Boolean) record.get("bar"));
Assert.assertFalse((Boolean) record.get("foo"));
Assert.assertNull(record.get("baz"));
Assert.assertNull(record.get("dne"));
}
@Test
public void testSetString() {
record.setString("foo", "bar").setString("bar", "baz");
Assert.assertEquals(record.get("foo"), "bar");
Assert.assertEquals(record.get("bar"), "baz");
Assert.assertNull(record.get("dne"));
}
@Test
public void testSetLong() {
record.setLong("foo", 0L).setLong("bar", -1231231231231231231L).setLong("baz", null);
Assert.assertEquals(record.get("foo"), 0L);
Assert.assertEquals(record.get("bar"), -1231231231231231231L);
Assert.assertNull(record.get("baz"));
Assert.assertNull(record.get("dne"));
}
@Test
public void testSetDouble() {
record.setDouble("foo", 42.1).setDouble("bar", -1.13).setDouble("baz", null);
Assert.assertEquals(record.get("foo"), 42.1);
Assert.assertEquals(record.get("bar"), -1.13);
Assert.assertNull(record.get("baz"));
Assert.assertNull(record.get("dne"));
}
@Test
public void testSetMaps() {
Map<String, Long> dataA = new HashMap<>();
dataA.put("bar", 1L);
dataA.put("baz", 2L);
record.setLongMap("fooA", dataA);
Assert.assertTrue(record.get("fooA") instanceof Map);
Assert.assertEquals(record.get("fooA", "bar"), 1L);
Assert.assertEquals(record.get("fooA", "baz"), 2L);
Map<String, Double> dataB = new HashMap<>();
dataB.put("bar", 1.1);
dataB.put("baz", 2.2);
record.setDoubleMap("fooB", dataB);
Assert.assertTrue(record.get("fooB") instanceof Map);
Assert.assertEquals(record.get("fooB", "bar"), 1.1);
Assert.assertEquals(record.get("fooB", "baz"), 2.2);
Map<String, Boolean> dataC = new HashMap<>();
dataC.put("bar", false);
dataC.put("baz", true);
record.setBooleanMap("fooC", dataC);
Assert.assertTrue(record.get("fooC") instanceof Map);
Assert.assertEquals(record.get("fooC", "bar"), false);
Assert.assertEquals(record.get("fooC", "baz"), true);
Map<String, String> dataD = new HashMap<>();
dataD.put("bar", "foo");
dataD.put("baz", "norf");
record.setStringMap("fooD", dataD);
Assert.assertTrue(record.get("fooD") instanceof Map);
Assert.assertEquals(record.get("fooD", "bar"), "foo");
Assert.assertEquals(record.get("fooD", "baz"), "norf");
Assert.assertNull(record.get("dne"));
Assert.assertNull(record.get("dne", "bar"));
Assert.assertNull(record.get("dne", "baz"));
}
@Test
public void testSetMapOfMaps() {
Map<String, Map<String, Long>> dataA = new HashMap<>();
dataA.put("bar", singletonMap("a", 1L));
dataA.put("baz", singletonMap("b", 2L));
record.setMapOfLongMap("fooA", dataA);
Assert.assertTrue(record.get("fooA") instanceof Map);
Assert.assertTrue(record.get("fooA", "bar") instanceof Map);
Assert.assertTrue(record.get("fooA", "baz") instanceof Map);
Assert.assertEquals(record.get("fooA", "bar"), singletonMap("a", 1L));
Assert.assertEquals(record.get("fooA", "baz"), singletonMap("b", 2L));
Map<String, Map<String, Double>> dataB = new HashMap<>();
dataB.put("bar", singletonMap("a", 0.2));
dataB.put("baz", singletonMap("b", 0.1));
record.setMapOfDoubleMap("fooB", dataB);
Assert.assertTrue(record.get("fooB") instanceof Map);
Assert.assertTrue(record.get("fooB", "bar") instanceof Map);
Assert.assertTrue(record.get("fooB", "baz") instanceof Map);
Assert.assertEquals(record.get("fooB", "bar"), singletonMap("a", 0.2));
Assert.assertEquals(record.get("fooB", "baz"), singletonMap("b", 0.1));
Map<String, Map<String, Boolean>> dataC = new HashMap<>();
dataC.put("bar", singletonMap("a", false));
dataC.put("baz", singletonMap("b", true));
record.setMapOfBooleanMap("fooC", dataC);
Assert.assertTrue(record.get("fooC") instanceof Map);
Assert.assertTrue(record.get("fooC", "bar") instanceof Map);
Assert.assertTrue(record.get("fooC", "baz") instanceof Map);
Assert.assertEquals(record.get("fooC", "bar"), singletonMap("a", false));
Assert.assertEquals(record.get("fooC", "baz"), singletonMap("b", true));
Map<String, Map<String, String>> dataD = new HashMap<>();
dataD.put("bar", singletonMap("a", "foo"));
dataD.put("baz", singletonMap("b", "norf"));
record.setMapOfStringMap("fooD", dataD);
Assert.assertTrue(record.get("fooD") instanceof Map);
Assert.assertTrue(record.get("fooD", "bar") instanceof Map);
Assert.assertTrue(record.get("fooD", "baz") instanceof Map);
Assert.assertEquals(record.get("fooD", "bar"), singletonMap("a", "foo"));
Assert.assertEquals(record.get("fooD", "baz"), singletonMap("b", "norf"));
Assert.assertNull(record.get("dne"));
Assert.assertNull(record.get("dne", "bar"));
Assert.assertNull(record.get("dne", "baz"));
}
@Test
public void testSetListMaps() {
List<Map<String, Long>> dataA = new ArrayList<>();
dataA.add(singletonMap("a", 1L));
dataA.add(singletonMap("b", 2L));
record.setListOfLongMap("fooA", dataA);
Assert.assertTrue(record.get("fooA") instanceof List);
Assert.assertTrue(record.get("fooA", 0) instanceof Map);
Assert.assertTrue(record.get("fooA", 1) instanceof Map);
Assert.assertEquals(record.get("fooA", 0), singletonMap("a", 1L));
Assert.assertEquals(record.get("fooA", 1), singletonMap("b", 2L));
List<Map<String, Double>> dataB = new ArrayList<>();
dataB.add(singletonMap("a", 0.2));
dataB.add(singletonMap("b", 0.1));
record.setListOfDoubleMap("fooB", dataB);
Assert.assertTrue(record.get("fooB") instanceof List);
Assert.assertTrue(record.get("fooB", 0) instanceof Map);
Assert.assertTrue(record.get("fooB", 1) instanceof Map);
Assert.assertEquals(record.get("fooB", 0), singletonMap("a", 0.2));
Assert.assertEquals(record.get("fooB", 1), singletonMap("b", 0.1));
List<Map<String, Boolean>> dataC = new ArrayList<>();
dataC.add(singletonMap("a", false));
dataC.add(singletonMap("b", true));
record.setListOfBooleanMap("fooC", dataC);
Assert.assertTrue(record.get("fooC") instanceof List);
Assert.assertTrue(record.get("fooC", 0) instanceof Map);
Assert.assertTrue(record.get("fooC", 1) instanceof Map);
Assert.assertEquals(record.get("fooC", 0), singletonMap("a", false));
Assert.assertEquals(record.get("fooC", 1), singletonMap("b", true));
List<Map<String, String>> dataD = new ArrayList<>();
dataD.add(singletonMap("a", "foo"));
dataD.add(singletonMap("b", "norf"));
record.setListOfStringMap("fooD", dataD);
Assert.assertTrue(record.get("fooD") instanceof List);
Assert.assertTrue(record.get("fooD", 0) instanceof Map);
Assert.assertTrue(record.get("fooD", 1) instanceof Map);
Assert.assertEquals(record.get("fooD", 0), singletonMap("a", "foo"));
Assert.assertEquals(record.get("fooD", 1), singletonMap("b", "norf"));
Assert.assertNull(record.get("dne", -1));
Assert.assertNull(record.get("dne", 0));
Assert.assertNull(record.get("dne", 123123));
}
@Test
public void testInsertingFromAnotherRecord() {
record.setString("a", "foo");
record.setStringMap("b", singletonMap("b.1", "bar"));
Map<String, Boolean> data = new HashMap<>();
data.put("c.1", false);
record.setListOfBooleanMap("c", singletonList(data));
BulletRecord newRecord = new BulletRecord();
newRecord.set("newA", record, "a");
Assert.assertEquals(newRecord.get("newA"), "foo");
Assert.assertEquals(newRecord.toString(), "{newA:foo}");
newRecord.set("newB", record, "b", "b.1");
Assert.assertEquals(newRecord.get("newB"), "bar");
newRecord.set("newC", record, "c", 0);
Assert.assertEquals(newRecord.get("newC"), singletonMap("c.1", false));
// The Map isn't copied
((Map<String, Boolean>) record.get("c", 0)).put("c.1", true);
Assert.assertEquals(newRecord.get("newC"), singletonMap("c.1", true));
// And not in the first record either
data.put("c.2", false);
Assert.assertEquals(((Map) record.get("c", 0)).get("c.2"), false);
Assert.assertEquals(newRecord.get("newC", "c.2"), false);
}
@Test
public void testGetTopLevelField() {
record.setListOfStringMap("foo", singletonList(singletonMap("qux", "norf")));
record.setString("bar", null);
Assert.assertNull(record.get("bar"));
Assert.assertTrue(record.get("foo") instanceof List);
Assert.assertEquals(record.get("foo"), singletonList(singletonMap("qux", "norf")));
Assert.assertNull(record.get("dne"));
}
@Test
public void testGetMapField() {
record.setMap("foo", Pair.of("bar", "baz"), Pair.of("baz", "qux"));
Assert.assertTrue(record.get("foo") instanceof Map);
Assert.assertEquals(record.get("foo", "bar"), "baz");
Assert.assertEquals(record.get("foo", "baz"), "qux");
Assert.assertNull(record.get("dne"));
Assert.assertNull(record.get("foo", null));
Assert.assertNull(record.get("foo", ""));
Assert.assertNull(record.get("foo", "dne"));
}
@Test
public void testGetListIndex() {
record.setListMap("foo", singletonMap("a", 1L), singletonMap("b", 2L));
Assert.assertTrue(record.get("foo") instanceof List);
Assert.assertEquals(record.get("foo", 0), singletonMap("a", 1L));
Assert.assertEquals(record.get("foo", 1), singletonMap("b", 2L));
Assert.assertNull(record.get("dne", -1));
Assert.assertNull(record.get("dne", 0));
Assert.assertNull(record.get("dne", 123123));
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void testGetListBadIndex() {
record.setListMap("foo", singletonMap("a", 1L));
record.get("foo", 1);
}
@Test
public void testIterator() {
record.setString("1", "bar").setLong("2", 42L)
.setBoolean("3", false)
.setMap("4", Pair.of("4.1", false))
.setListOfDoubleMap("5", singletonList(singletonMap("5.1", 3.1)));
Map<String, Object> expectedMap = new HashMap<>();
expectedMap.put("1", "bar");
expectedMap.put("2", 42L);
expectedMap.put("3", false);
expectedMap.put("4", singletonMap("4.1", false));
expectedMap.put("5", singletonList(singletonMap("5.1", 3.1)));
int lastEntry = 0;
for (Map.Entry<String, Object> entry : record) {
int currentEntry = Integer.valueOf(entry.getKey());
Assert.assertTrue(lastEntry + 1 == currentEntry);
Assert.assertEquals(entry.getValue(), expectedMap.get(entry.getKey()));
lastEntry = currentEntry;
}
}
@Test
public void testToString() {
Assert.assertEquals(record.toString(), "{}");
record.setString("1", "bar");
Assert.assertEquals(record.toString(), "{1:bar}");
}
@Test
public void testHashcodeEdgeCases() {
Assert.assertEquals(record.hashCode(), new BulletRecord().hashCode());
record.setSerializedData(null);
record.setData(null);
BulletRecord another = new BulletRecord();
another.setSerializedData(null);
another.setData(null);
Assert.assertEquals(record.hashCode(), another.hashCode());
}
@Test
public void testEqualsEdgeCases() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false);
Assert.assertFalse(record.equals(null));
Assert.assertFalse(record.equals("foo"));
}
@Test
public void testEqualsDifferentRecord() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false);
BulletRecord another = new BulletRecord().setString("1", "bar");
Assert.assertFalse(record.equals(another));
}
@Test
public void testEqualsAndHashcodeByteArrays() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false)
.setMap("4", Pair.of("4.1", false), Pair.of("4.2", true), Pair.of("4.3", null))
.setListOfStringMap("5", singletonList(singletonMap("5.1", "foo")));
BulletRecord another = new BulletRecord();
another.setString("1", "bar").setLong("2", 42L).setBoolean("3", false)
.setMap("4", Pair.of("4.1", false), Pair.of("4.2", true), Pair.of("4.3", null))
.setListOfStringMap("5", singletonList(singletonMap("5.1", "foo")));
record.setSerializedData(getRecordBytes(record));
record.setDeserialized(false);
another.setSerializedData(getRecordBytes(another));
another.setDeserialized(false);
Assert.assertTrue(record.equals(another));
Assert.assertEquals(record.hashCode(), another.hashCode());
}
@Test
public void testEqualsAndHashcodeSameRecord() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false)
.setMap("4", Pair.of("4.1", false), Pair.of("4.2", true), Pair.of("4.3", null))
.setListOfStringMap("5", singletonList(singletonMap("5.1", "foo")));
BulletRecord another = new BulletRecord();
another.setString("1", "bar").setLong("2", 42L).setBoolean("3", false)
.setMap("4", Pair.of("4.1", false), Pair.of("4.2", true), Pair.of("4.3", null))
.setListOfStringMap("5", singletonList(singletonMap("5.1", "foo")));
Assert.assertTrue(record.equals(another));
Assert.assertEquals(record.hashCode(), another.hashCode());
// Change order and it should still pass
another = new BulletRecord();
another.setString("1", "bar").setLong("2", 42L).setBoolean("3", false)
.setListOfStringMap("5", singletonList(singletonMap("5.1", "foo")))
.setMap("4", Pair.of("4.1", false), Pair.of("4.2", true), Pair.of("4.3", null));
Assert.assertTrue(record.equals(another));
Assert.assertEquals(record.hashCode(), another.hashCode());
// If you reify the changed order and compare, it still should
record.setSerializedData(getRecordBytes(record));
record.setDeserialized(false);
another.setSerializedData(getRecordBytes(another));
another.setDeserialized(false);
Assert.assertTrue(record.equals(another));
Assert.assertEquals(record.hashCode(), another.hashCode());
}
@Test
public void testEqualsAndHashcodeCorruptedRecord() {
record.setSerializedData(null);
record.setData(null);
record.setDeserialized(false);
BulletRecord another = new BulletRecord();
another.setSerializedData(null);
another.setData(null);
another.setDeserialized(false);
Assert.assertTrue(record.equals(another));
Assert.assertEquals(record.hashCode(), another.hashCode());
another = new BulletRecord();
another.setString("foo", "bar");
Assert.assertFalse(record.equals(another));
// This may or may not be true. Much more likely to be true, so leaving it in
Assert.assertNotEquals(record.hashCode(), another.hashCode());
}
@Test
public void testForceReadData() {
// If already deserialized, should succeed
Assert.assertTrue(record.forceReadData());
// Force a bad read with no data and not deserialized.
record.setDeserialized(false);
Assert.assertFalse(record.forceReadData());
// Set the data to an invalid byte array and force a read
record = new BulletRecord();
record.setSerializedData("foo".getBytes());
record.setDeserialized(false);
Assert.assertFalse(record.forceReadData());
// Set the data to a valid byte array and force a read
record = new BulletRecord();
Map<String, Object> data = new HashMap<>();
data.put("foo", singletonMap("bar", "baz"));
data.put("qux", singletonList(singletonMap("bar", "baz")));
record.setSerializedData(getAvroBytes(data));
record.setDeserialized(false);
Assert.assertTrue(record.forceReadData());
Assert.assertEquals(record.get("foo"), singletonMap("bar", "baz"));
Assert.assertEquals(record.get("foo", "bar"), "baz");
Assert.assertEquals(record.get("qux"), singletonList(singletonMap("bar", "baz")));
Assert.assertEquals(record.get("qux", 0), singletonMap("bar", "baz"));
// Further force reads should return true
Assert.assertTrue(record.forceReadData());
Assert.assertTrue(record.forceReadData());
}
@Test
public void testSerializationDeserialization() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true), Pair.of("7.3", null))
.setMap("8", Pair.of("8.1", "foo"), Pair.of("8.2", "bar"), Pair.of("8.3", "baz"))
.setListOfLongMap("9", singletonList(singletonMap("9.1", 3L)))
.setListOfBooleanMap("10", singletonList(singletonMap("10.1", true)));
byte[] serialized = getRecordBytes(record);
Assert.assertNotNull(serialized);
BulletRecord reified = fromRecordBytes(serialized);
Assert.assertNotNull(reified);
Assert.assertEquals(reified.get("2"), 42L);
Assert.assertTrue((Boolean) reified.get("7", "7.2"));
Assert.assertNull(reified.get("7", "7.3"));
Assert.assertEquals(reified.get("9", 0), singletonMap("9.1", 3L));
}
@Test
public void testSerializationDeserializationOfEmptyRecord() {
byte[] serialized = getRecordBytes(record);
Assert.assertNotNull(serialized);
BulletRecord reified = fromRecordBytes(serialized);
Assert.assertNotNull(reified);
byte[] serializedAgain = getRecordBytes(record);
Assert.assertEquals(serializedAgain, serialized);
}
@Test
public void testSerializationWithBadStates() {
byte[] serialized = getRecordBytes(record);
BulletRecord reified = fromRecordBytes(serialized);
// This will destroy the byte array and force the record to think it has data in its map (it doesn't)
reified.setSerializedData(null);
reified.setDeserialized(true);
// The record should handle this case by pretending to be an empty record
byte[] serializedAgain = getRecordBytes(reified);
Assert.assertEquals(serializedAgain, serialized);
}
@Test
public void testDeserializationWithBadStates() {
byte[] serialized = getRecordBytes(record);
BulletRecord reified = fromRecordBytes(serialized);
// This will destroy the byte array, force the record to think it doesn't have data in its map and then
// force a read
reified.setSerializedData(null);
reified.setDeserialized(false);
Assert.assertFalse(reified.forceReadData());
// But the record is still iterable
Assert.assertNotNull(reified.iterator());
Assert.assertNull(reified.get("some field"));
}
@Test
public void testSerializationDeserializationWithoutReading() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34);
byte[] serialized = getRecordBytes(record);
Assert.assertNotNull(serialized);
BulletRecord reified = fromRecordBytes(serialized);
// Read and write without accessing anything
serialized = getRecordBytes(reified);
reified = fromRecordBytes(serialized);
Assert.assertNotNull(reified);
Assert.assertEquals(reified.get("4"), 0.34);
}
@Test
public void testSerializationDeserializationWithDataInput() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true), Pair.of("7.3", null))
.setMap("8", Pair.of("8.1", "foo"), Pair.of("8.2", "bar"), Pair.of("8.3", "baz"))
.setListOfLongMap("9", singletonList(singletonMap("9.1", 3L)))
.setListOfBooleanMap("10", singletonList(singletonMap("10.1", true)));
// SerDe
byte[] serialized = getRecordBytes(record);
BulletRecord reified = fromRecordBytes(serialized);
Assert.assertNotNull(serialized);
Assert.assertNotNull(reified);
Assert.assertEquals(reified.get("2"), 42L);
Assert.assertTrue((Boolean) reified.get("7", "7.2"));
Assert.assertNull(reified.get("7", "4.3"));
Assert.assertEquals(reified.get("9", 0), singletonMap("9.1", 3L));
// Add new fields and modify fields in the record
reified.setMap("2", Pair.of("2.1", 42L));
reified.setLong("11", 4L);
reified.setMap("12", Pair.of("12.1", "foo"));
// SerDe again
serialized = getRecordBytes(reified);
reified = fromRecordBytes(serialized);
// The old ones that went through the first cycle
Assert.assertNotNull(reified);
Assert.assertEquals(reified.get("1"), "bar");
Assert.assertEquals(reified.get("2", "2.1"), 42L);
Assert.assertFalse((Boolean) reified.get("3"));
Assert.assertEquals(reified.get("4"), 0.34);
Assert.assertNull(reified.get("7", "7.3"));
Assert.assertEquals(reified.get("8", "8.3"), "baz");
Assert.assertEquals(reified.get("10", 0), singletonMap("10.1", true));
// New ones added at the last cycle
Assert.assertEquals(reified.get("11"), 4L);
Assert.assertEquals(reified.get("12", "12.1"), "foo");
}
@Test
public void testRawByteArrayIsNotBacking() throws IOException {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34);
byte[] rawByteArray = record.getAsByteArray();
record.setString("1", "foo");
record.setString("5", "bar");
byte[] after = record.getAsByteArray();
Assert.assertNotEquals(after, rawByteArray);
}
@Test
public void testSerializationWithMapAndRawByteArray() throws IOException {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34);
// Get the raw data out
byte[] rawDataBytes = record.getAsByteArray();
// Create a new record from the raw data
BulletRecord reified = new BulletRecord(rawDataBytes);
Assert.assertTrue(record.equals(reified));
}
@Test
public void testBackingByteArrayIfDeserialized() throws IOException {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34);
byte[] rawDataBytes = record.getAsByteArray();
BulletRecord record = new BulletRecord(rawDataBytes);
Assert.assertEquals(record.getAsByteArray(), rawDataBytes);
Assert.assertEquals(record.get("1"), "bar");
Assert.assertEquals(record.get("2"), 42L);
Assert.assertEquals(record.get("3"), false);
Assert.assertEquals(record.get("4"), 0.34);
Assert.assertEquals(record.fieldCount(), 4);
}
@Test
public void testSameByteArrayPostSerialization() throws IOException {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34);
byte[] originalByteArray = record.getAsByteArray();
// Now serialize and deserialize the record
byte[] serialized = getRecordBytes(record);
BulletRecord reified = fromRecordBytes(serialized);
// Get the raw data again as bytes
byte[] rawByteArray = record.getAsByteArray();
Assert.assertEquals(rawByteArray, originalByteArray);
// Read something from it to force a map conversion
Assert.assertEquals(record.get("1"), "bar");
// Then check if it is still the same byte array
Assert.assertEquals(record.getAsByteArray(), rawByteArray);
}
@Test
public void testCopyRecordWithMap() {
Map<String, Object> contents = new HashMap<>();
Map<String, Long> innerMap = new HashMap<>();
contents.put("1", "foo");
contents.put("2", false);
contents.put("3", 1L);
contents.put("4", innerMap);
innerMap.put("4.1", 1L);
innerMap.put("4.2", 3L);
record.setString("1", "foo");
record.setBoolean("2", false);
record.setMap("4", Pair.of("4.1", 1L), Pair.of("4.2", 3L));
record.setLong("3", 1L);
Assert.assertEquals(new BulletRecord(contents), record);
}
@Test
public void testRenaming() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true))
.setListOfLongMap("9", singletonList(singletonMap("9.1", 3L)));
record.rename("1", "new1").rename("3", "new3").rename("7.4.1", "new2");
BulletRecord expected = new BulletRecord().setString("new1", "bar").setLong("2", 42L).setBoolean("new3", false)
.setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true))
.setListOfLongMap("9", singletonList(singletonMap("9.1", 3L)));
Assert.assertTrue(expected.equals(record));
}
@Test
public void testFieldCount() throws IOException {
Assert.assertEquals(record.fieldCount(), 0);
record.setString("foo", "bar");
Assert.assertEquals(record.fieldCount(), 1);
record.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true));
Assert.assertEquals(record.fieldCount(), 2);
record.remove("2");
record.remove("7");
Assert.assertEquals(record.fieldCount(), 1);
BulletRecord another = new BulletRecord(record.getAsByteArray());
Assert.assertEquals(another.fieldCount(), 1);
}
@Test
public void testRemoving() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true))
.setListOfLongMap("9", singletonList(singletonMap("9.1", 3L)));
record.remove("1").remove("3").remove("7.4.1").remove("9");
BulletRecord expected = new BulletRecord().setLong("2", 42L).setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true));
Assert.assertTrue(expected.equals(record));
}
@Test
public void testRemovingField() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true))
.setListOfLongMap("9", singletonList(singletonMap("9.1", 3L)));
Object data;
data = record.getAndRemove("1");
Assert.assertTrue(data instanceof String);
Assert.assertEquals(data, "bar");
data = record.getAndRemove("3");
Assert.assertTrue(data instanceof Boolean);
Assert.assertEquals(data, false);
data = record.getAndRemove("7.7.2");
Assert.assertNull(data);
}
@Test
public void testFieldPresence() {
record.setString("1", "bar").setLong("2", 42L).setBoolean("3", false).setDouble("4", 0.34)
.setMap("7", Pair.of("4.1", false), Pair.of("7.2", true));
Assert.assertTrue(record.hasField("1"));
Assert.assertTrue(record.hasField("7"));
Assert.assertFalse(record.hasField("7.4.1"));
Assert.assertFalse(record.hasField("foo"));
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Cannot read from record.*")
public void testFailingWhenCannotRead() {
record = new BulletRecord();
record.setSerializedData("foo".getBytes());
record.setDeserialized(false);
record.hasField("foo");
}
}
|
3e148e7782278a16e88bdb9880e24968fb365bd4 | 6,282 | java | Java | lang/src/main/java/net/openhft/lang/io/VanillaMappedFile.java | OpenHFT/Java-Lang | 52ef75e01334ba1bf0b59f193ffc213b37d81af1 | [
"Apache-2.0"
] | 135 | 2015-01-04T18:53:26.000Z | 2022-01-09T15:02:30.000Z | lang/src/main/java/net/openhft/lang/io/VanillaMappedFile.java | OpenHFT/Java-Lang | 52ef75e01334ba1bf0b59f193ffc213b37d81af1 | [
"Apache-2.0"
] | 26 | 2015-01-17T17:18:27.000Z | 2020-01-05T14:53:06.000Z | lang/src/main/java/net/openhft/lang/io/VanillaMappedFile.java | OpenHFT/Java-Lang | 52ef75e01334ba1bf0b59f193ffc213b37d81af1 | [
"Apache-2.0"
] | 65 | 2015-01-06T07:47:36.000Z | 2021-11-16T19:31:30.000Z | 38.777778 | 163 | 0.678287 | 8,715 | /*
* Copyright 2016 higherfrequencytrading.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 net.openhft.lang.io;
import net.openhft.lang.io.FileLifecycleListener.EventType;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/*
* Merge memory mapped files:
* - net.openhft.lang.io.MappedFile
* - net.openhft.lang.io.MappedStore
* - net.openhft.chronicle.VanillaFile
*/
public class VanillaMappedFile implements VanillaMappedResource {
private final File path;
private final FileChannel fileChannel;
private final VanillaMappedMode mode;
private final long size;
private final FileLifecycleListener fileLifecycleListener;
public VanillaMappedFile(final File path, VanillaMappedMode mode) throws IOException {
this(path, mode, -1, FileLifecycleListener.FileLifecycleListeners.IGNORE);
}
public VanillaMappedFile(final File path, VanillaMappedMode mode, long size,
FileLifecycleListener fileLifecycleListener) throws IOException {
this.path = path;
this.mode = mode;
this.size = size;
this.fileChannel = fileChannel(path, mode, this.size, fileLifecycleListener);
this.fileLifecycleListener = fileLifecycleListener;
}
private static FileChannel fileChannel(final File path, VanillaMappedMode mapMode, long size, FileLifecycleListener fileLifecycleListener) throws IOException {
long start = System.nanoTime();
FileChannel fileChannel = null;
try {
final RandomAccessFile raf = new RandomAccessFile(path, mapMode.stringValue());
if (size > 0 && raf.length() != size) {
if (mapMode.mapValue() != FileChannel.MapMode.READ_WRITE) {
throw new IOException("Cannot resize file to " + size + " as mode is not READ_WRITE");
}
raf.setLength(size);
}
fileChannel = raf.getChannel();
} catch (Exception e) {
throw wrap(e);
}
fileLifecycleListener.onEvent(EventType.NEW, path, System.nanoTime() - start);
return fileChannel;
}
private static IOException wrap(Throwable throwable) {
if (throwable instanceof InvocationTargetException) {
throwable = throwable.getCause();
} else if (throwable instanceof IOException) {
return (IOException) throwable;
}
return new IOException(throwable);
}
public static VanillaMappedFile readWrite(final File path) throws IOException {
return new VanillaMappedFile(path, VanillaMappedMode.RW);
}
public static VanillaMappedFile readWrite(final File path, long size) throws IOException {
return new VanillaMappedFile(path, VanillaMappedMode.RW, size,
FileLifecycleListener.FileLifecycleListeners.IGNORE);
}
public static VanillaMappedFile readOnly(final File path) throws IOException {
return new VanillaMappedFile(path, VanillaMappedMode.RO);
}
// *************************************************************************
// Helpers
// *************************************************************************
public static VanillaMappedFile readOnly(final File path, long size) throws IOException {
return new VanillaMappedFile(path, VanillaMappedMode.RO, size,
FileLifecycleListener.FileLifecycleListeners.IGNORE);
}
public static VanillaMappedBytes readWriteBytes(final File path, long size) throws IOException {
return readWriteBytes(path, size, -1);
}
public static VanillaMappedBytes readWriteBytes(final File path, long size, long index) throws IOException {
return readWriteBytes(path, size, index, FileLifecycleListener.FileLifecycleListeners.IGNORE);
}
public static VanillaMappedBytes readWriteBytes(final File path, long size, long index, FileLifecycleListener fileLifecycleListener) throws IOException {
VanillaMappedFile vmf = new VanillaMappedFile(path, VanillaMappedMode.RW, -1, fileLifecycleListener);
return new VanillaMappedBytes(path, vmf.map(0, size), index, vmf.fileChannel, fileLifecycleListener);
}
public VanillaMappedBytes bytes(long address, long size) throws IOException {
return new VanillaMappedBytes(this.path, map(address, size), -1, null, this.fileLifecycleListener);
}
public VanillaMappedBytes bytes(long address, long size, long index) throws IOException {
return new VanillaMappedBytes(this.path, map(address, size), index, null, this.fileLifecycleListener);
}
@Override
public String path() {
return this.path.getAbsolutePath();
}
@Override
public long size() {
try {
return this.fileChannel.size();
} catch (IOException e) {
return 0;
}
}
@Override
public synchronized void close() throws IOException {
if (this.fileChannel.isOpen()) {
long start = System.nanoTime();
this.fileChannel.close();
this.fileLifecycleListener.onEvent(EventType.CLOSE, this.path, System.nanoTime() - start);
}
}
private synchronized MappedByteBuffer map(long address, long size) throws IOException {
long start = System.nanoTime();
MappedByteBuffer buffer = this.fileChannel.map(this.mode.mapValue(), address, size);
buffer.order(ByteOrder.nativeOrder());
fileLifecycleListener.onEvent(EventType.MMAP, path, System.nanoTime() - start);
return buffer;
}
}
|
3e148ea0e5ed8f0db29ca3e48a2eef73ab551613 | 4,658 | java | Java | src/test/java/au/com/tommyq/MatchingEngineImplTest.java | tommyqqt/matching-engine | 59ad9ce0161f17b3bbfbe9047c8f21637b2c3999 | [
"MIT"
] | 3 | 2020-11-18T18:48:38.000Z | 2022-03-09T20:54:38.000Z | src/test/java/au/com/tommyq/MatchingEngineImplTest.java | tommyqqt/matching-engine | 59ad9ce0161f17b3bbfbe9047c8f21637b2c3999 | [
"MIT"
] | null | null | null | src/test/java/au/com/tommyq/MatchingEngineImplTest.java | tommyqqt/matching-engine | 59ad9ce0161f17b3bbfbe9047c8f21637b2c3999 | [
"MIT"
] | 1 | 2020-04-16T05:42:57.000Z | 2020-04-16T05:42:57.000Z | 41.221239 | 102 | 0.654573 | 8,716 | /*
* MIT License
*
* Copyright (c) 2019 tommyqqt
*
* 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 au.com.tommyq;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertTrue;
public class MatchingEngineImplTest {
private MatchingEngineImpl matchingEngine;
private List<InstrumentConfig> instruments;
private Set<String> outputs;
@Before
public void setUp() throws Exception {
instruments = new ArrayList<>();
outputs = new HashSet<>();
}
@After
public void tearDown() throws Exception {
instruments.clear();
outputs.clear();
}
@Test
public void testOutputEventToConsole() throws Exception {
instruments.add(new InstrumentConfig("USDCAD", 2.90, 3.10));
instruments.add(new InstrumentConfig("GBPEUR", 1.05, 2.2));
instruments.add(new InstrumentConfig("EURUSD", 1.04, 2.1));
matchingEngine = new MatchingEngineImpl(instruments, newSingleThreadExecutor(), outputs::add);
matchingEngine.start();
matchingEngine.placeOffer("AbcCapital", "USDCAD", 10, 2.99);
matchingEngine.placeBid("SuperInvestment", "USDCAD", 5, 2.98);
matchingEngine.display("USDCAD");
matchingEngine.placeBid("OneBank", "USDCAD", 10, 2.97);
matchingEngine.placeOffer("TravelExchanger", "USDCAD", 7, 2.97);
matchingEngine.display("USDCAD");
matchingEngine.placeBid("AbcCapital", "GBPEUR", 1, 1.1);
matchingEngine.placeBid("AbcCapital", "GBPEUR", 2, 1.2);
matchingEngine.placeBid("AbcCapital", "GBPEUR", 2, 1.3);
matchingEngine.placeBid("AbcCapital", "GBPEUR", 5, 1.3);
matchingEngine.placeOffer("AbcCapital", "GBPEUR", 2, 1.5);
matchingEngine.placeOffer("AbcCapital", "GBPEUR", 2, 1.5);
matchingEngine.placeOffer("AbcCapital", "GBPEUR", 5, 1.6);
matchingEngine.placeOffer("OneBank", "GBPEUR", 11, 1.15);
matchingEngine.display("GBPEUR");
matchingEngine.placeOffer("AbcCapital", "EURUSD", 2, 1.5);
matchingEngine.placeOffer("AbcCapital", "EURUSD", 17, 1.6);
matchingEngine.placeOffer("NewBank", "EURUSD", 16, 1.6);
matchingEngine.placeBid("OneBank", "EURUSD", 8, 1.61);
matchingEngine.display("EURUSD");
final CountDownLatch latch = new CountDownLatch(1);
final Thread waitThread = new Thread(() -> {
while(outputs.size() < 11){
LockSupport.parkNanos(1);
}
latch.countDown();
});
waitThread.start();
latch.await(1000, MILLISECONDS);
Arrays.asList(
"5 $2.98 | $2.99 10",
"OneBank bought 2 USDCAD from TravelExchanger @ $2.97",
"8 $2.97 | $2.99 10",
"SuperInvestment bought 5 USDCAD from TravelExchanger @ $2.98",
"1 $1.10 | $1.15 2",
"0 NaN | $1.60 27",
"AbcCapital bought 5 GBPEUR from OneBank @ $1.30",
"AbcCapital bought 2 GBPEUR from OneBank @ $1.20",
"AbcCapital bought 2 GBPEUR from OneBank @ $1.30",
"AbcCapital sold 2 EURUSD from OneBank @ $1.50",
"AbcCapital sold 6 EURUSD from OneBank @ $1.60"
)
.stream().forEach(s -> assertTrue(outputs.contains(s)));
}
} |
3e148f0160b60d3f546da6978d3d479981376ba2 | 914 | java | Java | Leecode for JAVA/src/longestCommonPrefix/Solution.java | jcp0578/practise-JAVA | 72c05bba391977dedca8167965089466b7d6e984 | [
"MIT"
] | null | null | null | Leecode for JAVA/src/longestCommonPrefix/Solution.java | jcp0578/practise-JAVA | 72c05bba391977dedca8167965089466b7d6e984 | [
"MIT"
] | null | null | null | Leecode for JAVA/src/longestCommonPrefix/Solution.java | jcp0578/practise-JAVA | 72c05bba391977dedca8167965089466b7d6e984 | [
"MIT"
] | null | null | null | 18.653061 | 56 | 0.568928 | 8,717 | package longestCommonPrefix;
/*
* 最长公共前缀
* 时间复杂度O(N^2)
* AC
* 4ms - 92.41%
*
*/
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null)
return "";
int len = strs.length;
if (len == 0)
return "";
StringBuffer out = new StringBuffer();
for (int j = 0;; j++) {
try {
char temp = strs[0].charAt(j);
int i = 1;
for (; i < len; i++) {
if (strs[i].charAt(j) == temp)
continue;
else
break;
}
if (i == len) {
out.append(temp);
} else
break;
} catch (StringIndexOutOfBoundsException e) {
break;
} catch (Exception e) {
e.printStackTrace(System.out);
break;
}
}
return out.toString();
}
public static void main(String[] args) {
String[] test_in = { "flower", "f", "flight" };
Solution test = new Solution();
System.out.println(test.longestCommonPrefix(test_in));
}
}
|
3e14906c8936de2e2c0d3a137ee1f22dc5683a91 | 294 | java | Java | _IntelliJ/Masterbuilders/src/at/mario/masterbuilders/listener/SneakListener.java | MarioMatschgi/Minecraft-Plugins | b1363d06b6d741337dc0c6c7e1c1231778356be4 | [
"MIT"
] | 1 | 2021-03-24T12:20:04.000Z | 2021-03-24T12:20:04.000Z | _Eclipse/Masterbuilders/src/at/mario/masterbuilders/listener/SneakListener.java | MarioMatschgi/Minecraft-Plugins | b1363d06b6d741337dc0c6c7e1c1231778356be4 | [
"MIT"
] | null | null | null | _Eclipse/Masterbuilders/src/at/mario/masterbuilders/listener/SneakListener.java | MarioMatschgi/Minecraft-Plugins | b1363d06b6d741337dc0c6c7e1c1231778356be4 | [
"MIT"
] | 2 | 2021-03-27T15:43:42.000Z | 2021-03-27T15:50:42.000Z | 21 | 54 | 0.809524 | 8,718 | package at.mario.masterbuilders.listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerToggleSneakEvent;
public class SneakListener implements Listener {
@EventHandler
public void onSneak(PlayerToggleSneakEvent e) {
}
}
|
3e1490edb15cd0ef63835be01a1dc1db1fae21d8 | 3,248 | java | Java | src/main/java/com/alipay/api/request/AlipaySocialBaseMessageDynamicicondataModifyRequest.java | wongoo/alipay-sdk-java-all | b3c2dd14a8ffba03a2b96a3dd98e4c4a2a11754b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/request/AlipaySocialBaseMessageDynamicicondataModifyRequest.java | wongoo/alipay-sdk-java-all | b3c2dd14a8ffba03a2b96a3dd98e4c4a2a11754b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/request/AlipaySocialBaseMessageDynamicicondataModifyRequest.java | wongoo/alipay-sdk-java-all | b3c2dd14a8ffba03a2b96a3dd98e4c4a2a11754b | [
"Apache-2.0"
] | null | null | null | 23.536232 | 146 | 0.711515 | 8,719 | package com.alipay.api.request;
import com.alipay.api.domain.AlipaySocialBaseMessageDynamicicondataModifyModel;
import java.util.Map;
import com.alipay.api.AlipayRequest;
import com.alipay.api.internal.util.AlipayHashMap;
import com.alipay.api.response.AlipaySocialBaseMessageDynamicicondataModifyResponse;
import com.alipay.api.AlipayObject;
/**
* ALIPAY API: alipay.social.base.message.dynamicicondata.modify request
*
* @author auto create
* @since 1.0, 2021-11-24 21:46:50
*/
public class AlipaySocialBaseMessageDynamicicondataModifyRequest implements AlipayRequest<AlipaySocialBaseMessageDynamicicondataModifyResponse> {
private AlipayHashMap udfParams; // add user-defined text parameters
private String apiVersion="1.0";
/**
* 应用中心-微动效-数据管理服务
*/
private String bizContent;
public void setBizContent(String bizContent) {
this.bizContent = bizContent;
}
public String getBizContent() {
return this.bizContent;
}
private String terminalType;
private String terminalInfo;
private String prodCode;
private String notifyUrl;
private String returnUrl;
private boolean needEncrypt=false;
private AlipayObject bizModel=null;
public String getNotifyUrl() {
return this.notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public String getReturnUrl() {
return this.returnUrl;
}
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
public String getApiVersion() {
return this.apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public void setTerminalType(String terminalType){
this.terminalType=terminalType;
}
public String getTerminalType(){
return this.terminalType;
}
public void setTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public String getTerminalInfo(){
return this.terminalInfo;
}
public void setProdCode(String prodCode) {
this.prodCode=prodCode;
}
public String getProdCode() {
return this.prodCode;
}
public String getApiMethodName() {
return "alipay.social.base.message.dynamicicondata.modify";
}
public Map<String, String> getTextParams() {
AlipayHashMap txtParams = new AlipayHashMap();
txtParams.put("biz_content", this.bizContent);
if(udfParams != null) {
txtParams.putAll(this.udfParams);
}
return txtParams;
}
public void putOtherTextParam(String key, String value) {
if(this.udfParams == null) {
this.udfParams = new AlipayHashMap();
}
this.udfParams.put(key, value);
}
public Class<AlipaySocialBaseMessageDynamicicondataModifyResponse> getResponseClass() {
return AlipaySocialBaseMessageDynamicicondataModifyResponse.class;
}
public boolean isNeedEncrypt() {
return this.needEncrypt;
}
public void setNeedEncrypt(boolean needEncrypt) {
this.needEncrypt=needEncrypt;
}
public AlipayObject getBizModel() {
return this.bizModel;
}
public void setBizModel(AlipayObject bizModel) {
this.bizModel=bizModel;
}
}
|
3e1490fae2cada40e029e39f66656c1732dd2d51 | 4,547 | java | Java | trunk/adhoc-internal/src/main/java/org/jfree/JCommonInfo.java | yblucky/mdrill | 8621180ac977e670a8e50a16053d4fce2b1c6a3e | [
"ICU",
"Apache-2.0"
] | 1,104 | 2015-01-01T07:45:27.000Z | 2022-03-31T04:09:24.000Z | trunk/adhoc-internal/src/main/java/org/jfree/JCommonInfo.java | jwpttcg66/mdrill | 3acf33cfa72527fc1d949e933cc87fba340f2524 | [
"ICU",
"Apache-2.0"
] | 7 | 2015-05-04T10:29:01.000Z | 2019-01-07T05:38:55.000Z | trunk/adhoc-internal/src/main/java/org/jfree/JCommonInfo.java | jwpttcg66/mdrill | 3acf33cfa72527fc1d949e933cc87fba340f2524 | [
"ICU",
"Apache-2.0"
] | 579 | 2015-01-04T06:40:10.000Z | 2022-03-28T11:53:15.000Z | 35.929134 | 80 | 0.610563 | 8,720 | /* ========================================================================
* JCommon : a free general purpose class library for the Java(tm) platform
* ========================================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ----------------
* JCommonInfo.java
* ----------------
* (C)opyright 2003-2008, by Thomas Morgner and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Thomas Morgner;
*
* $Id: JCommonInfo.java,v 1.8 2008/12/18 09:57:32 mungady Exp $
*
* Changes
* -------
* 07-Jun-2004 : Added JCommon header (DG);
* 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by
* Jess Thrysoee (DG);
*
*/
package org.jfree;
import java.util.Arrays;
import java.util.ResourceBundle;
import org.jfree.base.BaseBoot;
import org.jfree.base.Library;
import org.jfree.ui.about.Contributor;
import org.jfree.ui.about.Licences;
import org.jfree.ui.about.ProjectInfo;
import org.jfree.util.ResourceBundleWrapper;
/**
* Information about the JCommon project. One instance of this class is
* assigned to JCommon.INFO.
*
* @author David Gilbert
*/
public class JCommonInfo extends ProjectInfo {
/** The singleton instance of the project info object. */
private static JCommonInfo singleton;
/**
* Returns the single instance of this class.
*
* @return The single instance of information about the JCommon library.
*/
public static synchronized JCommonInfo getInstance() {
if (singleton == null) {
singleton = new JCommonInfo();
}
return singleton;
}
/**
* Creates a new instance.
*/
private JCommonInfo() {
// get a locale-specific resource bundle...
final String baseResourceClass = "org.jfree.resources.JCommonResources";
final ResourceBundle resources = ResourceBundleWrapper.getBundle(
baseResourceClass);
setName(resources.getString("project.name"));
setVersion(resources.getString("project.version"));
setInfo(resources.getString("project.info"));
setCopyright(resources.getString("project.copyright"));
setLicenceName("LGPL");
setLicenceText(Licences.getInstance().getLGPL());
setContributors(Arrays.asList(
new Contributor[] {
new Contributor("Anthony Boulestreau", "-"),
new Contributor("Jeremy Bowman", "-"),
new Contributor("J. David Eisenberg", "-"),
new Contributor("Paul English", "-"),
new Contributor("David Gilbert",
"envkt@example.com"),
new Contributor("Hans-Jurgen Greiner", "-"),
new Contributor("Arik Levin", "-"),
new Contributor("Achilleus Mantzios", "-"),
new Contributor("Thomas Meier", "-"),
new Contributor("Aaron Metzger", "-"),
new Contributor("Thomas Morgner", "-"),
new Contributor("Krzysztof Paz", "-"),
new Contributor("Nabuo Tamemasa", "-"),
new Contributor("Mark Watson", "-"),
new Contributor("Matthew Wright", "-"),
new Contributor("Hari", "-"),
new Contributor("Sam (oldman)", "-")
}
));
addOptionalLibrary(new Library("JUnit", "3.8", "IBM Public Licence",
"http://www.junit.org/"));
setBootClass(BaseBoot.class.getName());
}
}
|
3e149192fc79983bf335439d917c9ecf5b432a6b | 659 | java | Java | src/main/java/cynfoxwell/cyntweaks/CTModContainer.java | BoxOfFlex/CynTweaks | 43baa67a474222195feef5862a3460c2c3437258 | [
"Unlicense"
] | 2 | 2017-12-30T00:21:06.000Z | 2017-12-30T11:12:31.000Z | src/main/java/cynfoxwell/cyntweaks/CTModContainer.java | BoxOfFlex/CynTweaks | 43baa67a474222195feef5862a3460c2c3437258 | [
"Unlicense"
] | null | null | null | src/main/java/cynfoxwell/cyntweaks/CTModContainer.java | BoxOfFlex/CynTweaks | 43baa67a474222195feef5862a3460c2c3437258 | [
"Unlicense"
] | null | null | null | 34.684211 | 143 | 0.701062 | 8,721 | package cynfoxwell.cyntweaks;
import net.minecraftforge.fml.common.DummyModContainer;
import net.minecraftforge.fml.common.ModMetadata;
import java.util.Arrays;
public class CTModContainer extends DummyModContainer {
public CTModContainer() {
super(new ModMetadata());
final ModMetadata meta = this.getMetadata();
meta.modId = "cyntweaks-asm";
meta.name = "CynTweaks ASM";
meta.description = "*hacker voice* I'm in.\n\nThis is all stuff you don't need to worry about and most is configurable from main mod.";
meta.version = "GRADLE:VERSION";
meta.authorList = Arrays.asList("BoxOfFlex");
}
}
|
3e14920f8a2c860ca97def13ff151d74c9fe9fcb | 3,415 | java | Java | core/src/test/java/org/jboss/galleon/config/capability/dynamic/NullParamForRequiredDynamicCapabilityTestCase.java | aloubyansky/galleon | 5d841c57b38897da29967df053c8ad986df0d9c0 | [
"Apache-2.0"
] | 23 | 2018-03-16T09:51:38.000Z | 2021-11-07T20:32:36.000Z | core/src/test/java/org/jboss/galleon/config/capability/dynamic/NullParamForRequiredDynamicCapabilityTestCase.java | aloubyansky/galleon | 5d841c57b38897da29967df053c8ad986df0d9c0 | [
"Apache-2.0"
] | 27 | 2018-05-15T14:19:49.000Z | 2021-11-19T12:57:24.000Z | core/src/test/java/org/jboss/galleon/config/capability/dynamic/NullParamForRequiredDynamicCapabilityTestCase.java | aloubyansky/galleon | 5d841c57b38897da29967df053c8ad986df0d9c0 | [
"Apache-2.0"
] | 26 | 2018-04-13T10:14:20.000Z | 2022-03-01T15:42:50.000Z | 40.176471 | 130 | 0.666471 | 8,722 | /*
* Copyright 2016-2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.jboss.galleon.config.capability.dynamic;
import org.jboss.galleon.universe.galleon1.LegacyGalleon1Universe;
import org.jboss.galleon.universe.FeaturePackLocation.FPID;
import org.jboss.galleon.Errors;
import org.jboss.galleon.ProvisioningException;
import org.jboss.galleon.config.ConfigModel;
import org.jboss.galleon.config.FeatureConfig;
import org.jboss.galleon.config.FeaturePackConfig;
import org.jboss.galleon.creator.FeaturePackCreator;
import org.jboss.galleon.spec.FeatureParameterSpec;
import org.jboss.galleon.spec.FeatureSpec;
import org.jboss.galleon.test.PmInstallFeaturePackTestBase;
import org.junit.Assert;
/**
*
* @author Alexey Loubyansky
*/
public class NullParamForRequiredDynamicCapabilityTestCase extends PmInstallFeaturePackTestBase {
private static final FPID FP_GAV = LegacyGalleon1Universe.newFPID("org.jboss.pm.test:fp1", "1", "1.0.0.Final");
@Override
protected void createFeaturePacks(FeaturePackCreator creator) throws ProvisioningException {
creator
.newFeaturePack(FP_GAV)
.addFeatureSpec(FeatureSpec.builder("specA")
.providesCapability("cap.a")
.addParam(FeatureParameterSpec.createId("a"))
.build())
.addFeatureSpec(FeatureSpec.builder("specB")
.requiresCapability("cap.$a")
.addParam(FeatureParameterSpec.createId("b"))
.addParam(FeatureParameterSpec.create("a", true))
.build())
.addConfig(ConfigModel.builder()
.setName("main")
.addFeature(
new FeatureConfig("specB")
.setParam("b", "b1"))
.addFeature(
new FeatureConfig("specA")
.setParam("a", "a1"))
.build());
}
@Override
protected FeaturePackConfig featurePackConfig() {
return FeaturePackConfig.forLocation(FP_GAV.getLocation());
}
@Override
protected void pmSuccess() {
Assert.fail("There is no cap.a provider");
}
@Override
protected void pmFailure(Throwable e) {
Assert.assertEquals(Errors.failedToBuildConfigSpec(null, "main"), e.getMessage());
e = (ProvisioningException) e.getCause();
Assert.assertNotNull(e);
Assert.assertEquals("Failed to resolve capability cap.$a for {org.jboss.pm.test:fp1@galleon1}specB:b=b1", e.getMessage());
e = (ProvisioningException) e.getCause();
Assert.assertNotNull(e);
Assert.assertEquals("Parameter a is missing value to resolve capability cap.$a", e.getMessage());
}
}
|
3e14922be9ceddd5f2215abb41a615c415aca56d | 1,470 | java | Java | src/main/java/com/bkunzh/util/util/IOUtils.java | bkunzh/common-library | 6f537f14ab4042fa3818b68cd5ba6895c9ec2601 | [
"MIT"
] | 1 | 2019-02-28T18:36:26.000Z | 2019-02-28T18:36:26.000Z | src/main/java/com/bkunzh/util/util/IOUtils.java | bkunzh/common-library | 6f537f14ab4042fa3818b68cd5ba6895c9ec2601 | [
"MIT"
] | null | null | null | src/main/java/com/bkunzh/util/util/IOUtils.java | bkunzh/common-library | 6f537f14ab4042fa3818b68cd5ba6895c9ec2601 | [
"MIT"
] | null | null | null | 24.098361 | 90 | 0.544218 | 8,723 | package com.bkunzh.util.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Objects;
/**
* Created by bkunzhang on 2019/8/11.
*/
public class IOUtils {
/**
* 将输入流转换为字节数组
* @param in
* @return
* @throws IOException
*/
public static byte[] inputStreamToByteArray(InputStream in) throws IOException {
if (Objects.isNull(in)) {
return null;
}
byte[] textBytes = new byte[0];
byte[] buffer = new byte[4096];
int len = -1;
while ((len = in.read(buffer)) > -1) {
textBytes = ArrayUtils.concatByteArray(textBytes, Arrays.copyOf(buffer, len));
}
return textBytes;
}
/*
* 将输入流转换为字节数组。利用流的方式
*/
public static byte[] inputStream2ByteArray(InputStream in) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len = -1;
do {
len = in.read(buffer);
if (len > 0) {
bos.write(buffer, 0, len);
}
} while (len > -1);
return bos.toByteArray();
}
public static void closeInputStream(InputStream in) {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
3e1492b8982b8810d94f2cfee654b290b457895d | 4,555 | java | Java | scf-server/src/main/java/com/github/leeyazhou/scf/server/filter/ExecuteMethodFilter.java | bytesgo/iscoder-rpc | 7d42b2f82d3e295546814bc3b166a79667f8d044 | [
"Apache-2.0"
] | null | null | null | scf-server/src/main/java/com/github/leeyazhou/scf/server/filter/ExecuteMethodFilter.java | bytesgo/iscoder-rpc | 7d42b2f82d3e295546814bc3b166a79667f8d044 | [
"Apache-2.0"
] | null | null | null | scf-server/src/main/java/com/github/leeyazhou/scf/server/filter/ExecuteMethodFilter.java | bytesgo/iscoder-rpc | 7d42b2f82d3e295546814bc3b166a79667f8d044 | [
"Apache-2.0"
] | null | null | null | 38.601695 | 133 | 0.633589 | 8,724 | package com.github.leeyazhou.scf.server.filter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.leeyazhou.scf.core.entity.KeyValuePair;
import com.github.leeyazhou.scf.core.exception.ExceptionProtocol;
import com.github.leeyazhou.scf.protocol.entity.PlatformType;
import com.github.leeyazhou.scf.protocol.sdp.RequestProtocol;
import com.github.leeyazhou.scf.protocol.sfp.Protocol;
import com.github.leeyazhou.scf.server.contract.context.ExecFilterType;
import com.github.leeyazhou.scf.server.contract.context.Global;
import com.github.leeyazhou.scf.server.contract.context.SCFContext;
import com.github.leeyazhou.scf.server.contract.context.SCFResponse;
import com.github.leeyazhou.scf.server.contract.context.SecureContext;
import com.github.leeyazhou.scf.server.contract.context.ServerType;
import com.github.leeyazhou.scf.server.util.ExceptionUtil;
public class ExecuteMethodFilter implements IFilter {
private static final Logger logger = LoggerFactory.getLogger(ExecuteMethodFilter.class);
@Override
public int getPriority() {
return 0;
}
@Override
public void filter(SCFContext context) throws Exception {
Global global = Global.getSingleton();
Protocol p = context.getScfRequest().getProtocol();
SCFResponse response = new SCFResponse();
if (p.getPlatformType() == PlatformType.Java && context.getServerType() == ServerType.TCP) { // java
// 客户端支持权限认证
// 当前服务启动权限认证,并且当前channel通过校验,则进行方法校验
SecureContext securecontext = global.getGlobalSecureContext(context.getChannel().getNettyChannel());
if (global.getGlobalSecureIsRights()) {
// 当前服务启用权限认证,判断当前channel是否通过授权
if (securecontext.isRights()) {
RequestProtocol request = (RequestProtocol) p.getSdpEntity();
if (request != null) {
StringBuffer buff = new StringBuffer(request.getLookup() + "." + request.getMethodName());// 接口实现类.方法名(参数序列)
buff.append("(");
List<KeyValuePair> list = request.getParaKVList();
if (list != null) {
int i = 0;
for (KeyValuePair k : list) {
if (k != null) {
if (i > 0) {
buff.append(",");
}
buff.append(k.getKey());
++i;
}
}
}
buff.append(")");
boolean bool = true;
Map<String, List<String>> map = global.getSecureMap();
if (map != null) {
Iterator<Map.Entry<String, List<String>>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, List<String>> enty = (Map.Entry<String, List<String>>) iter.next();
for (String str : enty.getValue()) {
if (str.equalsIgnoreCase(buff.toString())) {
bool = false;
break;
}
}
}
}
if (bool) {
logger.error("当前调用方法没有授权!");
this.ContextException(context, p, response, "当前调用方法没有授权!", global.getGlobalSecureIsRights(),
securecontext.getDesKey().getBytes("utf-8"));
}
}
} else {
logger.error("当前连接没有通过权限认证!");
this.ContextException(context, p, response, "当前连接没有通过权限认证!");
}
}
}
}
public void ContextException(SCFContext context, Protocol protocol, SCFResponse response, String message, boolean bool, byte[] key)
throws Exception {
ExceptionProtocol ep = ExceptionUtil.createError(new Exception());
ep.setErrorMsg(message);
protocol.setSdpEntity(ep);
response.setResponseBuffer(protocol.toBytes(bool, key));
context.setScfResponse(response);
this.setInvokeAndFilter(context);
}
public void ContextException(SCFContext context, Protocol protocol, SCFResponse response, String message) throws Exception {
ExceptionProtocol ep = ExceptionUtil.createError(new Exception());
ep.setErrorMsg(message);
protocol.setSdpEntity(ep);
response.setResponseBuffer(protocol.toBytes());
context.setScfResponse(response);
this.setInvokeAndFilter(context);
}
public void setInvokeAndFilter(SCFContext context) {
context.setExecFilter(ExecFilterType.None);
context.setDoInvoke(false);
}
}
|
3e14930430dbc88ee71e18061692f546731bda46 | 1,341 | java | Java | src/test/java/tcl/CommonTest.java | ramdadam/itm_viewer | 3d01fba5cbd0de1cbe503833049535f5c5fae83d | [
"MIT"
] | 10 | 2020-06-08T12:43:14.000Z | 2022-03-26T10:15:59.000Z | src/test/java/tcl/CommonTest.java | ramdadam/itm_viewer | 3d01fba5cbd0de1cbe503833049535f5c5fae83d | [
"MIT"
] | 2 | 2020-09-30T13:12:34.000Z | 2021-02-06T17:29:35.000Z | src/test/java/tcl/CommonTest.java | ramdadam/itm_viewer | 3d01fba5cbd0de1cbe503833049535f5c5fae83d | [
"MIT"
] | 3 | 2020-06-08T12:43:16.000Z | 2021-03-13T14:17:45.000Z | 29.152174 | 63 | 0.572707 | 8,725 | package tcl;
import org.junit.Test;
import tcl.parser.Common;
import static org.junit.Assert.*;
import java.util.Arrays;
public class CommonTest {
@Test
public void concatArrays_validInput() {
byte[] a = new byte[] { 0x1, 0x2};
byte[] b = new byte[] { 0x3, 0x4};
byte[] expected_res = new byte[] { 0x1, 0x2, 0x3, 0x4};
byte[] res = Common.concatByteArrays(a, b);
assert(Arrays.equals(expected_res, res));
}
@Test
public void concatArrays_invalidInput() {
byte[] a = new byte[] { 0x1, 0x2};
byte[] b = new byte[] { 0x3, 0x4};
byte[] fail_res = new byte[] { 0x2, 0x2, 0x3, 0x4};
byte[] res = Common.concatByteArrays(a, b);
assertFalse(Arrays.equals(fail_res, res));
}
@Test
public void concatByte_validInput() {
byte[] a = new byte[] { 0x1, 0x2};
byte b = 0x3;
byte[] expected_res = new byte[] { 0x1, 0x2, 0x3};
byte[] res = Common.concatByte(a, b);
assert(Arrays.equals(expected_res, res));
}
@Test
public void concatByte_invalidInput() {
byte[] a = new byte[] { 0x1, 0x2};
byte b = 0x4;
byte[] expected_res = new byte[] { 0x1, 0x2, 0x3};
byte[] res = Common.concatByte(a, b);
assertFalse(Arrays.equals(expected_res, res));
}
}
|
3e1493a77769a92550b3022dd1b9fcdd85e3fb7f | 1,404 | java | Java | src/test/java/io/dummymaker/factory/FactoryTests.java | GoodforGod/dummymaker | 190625c85deea185d41d64a13532cd4c9c8f6708 | [
"MIT"
] | 12 | 2017-06-08T10:58:30.000Z | 2021-08-31T18:04:27.000Z | src/test/java/io/dummymaker/factory/FactoryTests.java | GoodforGod/dummymaker | 190625c85deea185d41d64a13532cd4c9c8f6708 | [
"MIT"
] | 28 | 2018-03-10T14:59:17.000Z | 2022-01-09T13:35:05.000Z | src/test/java/io/dummymaker/factory/FactoryTests.java | GoodforGod/dummymaker | 190625c85deea185d41d64a13532cd4c9c8f6708 | [
"MIT"
] | 4 | 2018-03-08T22:24:18.000Z | 2021-08-31T00:36:43.000Z | 25.071429 | 100 | 0.695869 | 8,726 | package io.dummymaker.factory;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import io.dummymaker.factory.impl.GenFactory;
import io.dummymaker.model.Dummy;
import io.dummymaker.model.DummyNoZeroConstructor;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
/**
* ! NO DESCRIPTION !
*
* @author GoodforGod
* @since 05.10.2019
*/
public class FactoryTests {
private final GenFactory factory = new GenFactory();
@Test
public void isEmptyForEmptyList() {
assertTrue(factory.fill(Collections.emptyList()).isEmpty());
}
@Test
public void isEmptyForNullList() {
assertTrue(factory.fill((List<Object>) null).isEmpty());
}
@Test
public void isNullForNull() {
assertNull(factory.fill((Dummy) null));
}
@Test
public void emptyWhenBuildLessThanZero() {
final List<Dummy> dummies = factory.build(Dummy.class, -2);
assertTrue(dummies.isEmpty());
}
@Test
public void emptyWhenBuildNonZeroConstructor() {
final List<DummyNoZeroConstructor> dummies = factory.build(DummyNoZeroConstructor.class, 2);
assertTrue(dummies.isEmpty());
}
@Test
public void nullWhenBuildNonZeroConstructor() {
final DummyNoZeroConstructor dummy = factory.build(DummyNoZeroConstructor.class);
assertNull(dummy);
}
}
|
3e1493e8078f6c5f1de1ab4c47db14b608d53c44 | 83 | java | Java | jdk/jdk-type/src/main/java/com/github/leleact/jtest/jdk/type/response/BaseResponse.java | leleact/JTest | 99aadb93b1d8f4ddd67ea9c8a64965c092ca80fb | [
"MIT"
] | null | null | null | jdk/jdk-type/src/main/java/com/github/leleact/jtest/jdk/type/response/BaseResponse.java | leleact/JTest | 99aadb93b1d8f4ddd67ea9c8a64965c092ca80fb | [
"MIT"
] | 19 | 2021-12-12T09:53:58.000Z | 2022-03-12T17:09:33.000Z | jdk/jdk-type/src/main/java/com/github/leleact/jtest/jdk/type/response/BaseResponse.java | leleact/JTest | 99aadb93b1d8f4ddd67ea9c8a64965c092ca80fb | [
"MIT"
] | null | null | null | 16.6 | 51 | 0.795181 | 8,727 | package com.github.leleact.jtest.jdk.type.response;
public class BaseResponse {
}
|
3e149405643c88d664abee9540d64ca4405bcc84 | 4,865 | java | Java | src/main/java/swordstat/init/EntitySortingInit.java | Parallens/sword-stat | 81ac68bb9d9065d3a07506314b346859d9dba443 | [
"MIT"
] | 2 | 2019-04-01T14:59:59.000Z | 2019-07-12T19:01:07.000Z | src/main/java/swordstat/init/EntitySortingInit.java | Parallens/sword-stat | 81ac68bb9d9065d3a07506314b346859d9dba443 | [
"MIT"
] | 1 | 2018-08-22T04:06:22.000Z | 2018-08-23T15:17:49.000Z | src/main/java/swordstat/init/EntitySortingInit.java | Parallens/sword-stat | 81ac68bb9d9065d3a07506314b346859d9dba443 | [
"MIT"
] | null | null | null | 29.664634 | 233 | 0.723947 | 8,728 | package swordstat.init;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.client.resources.Locale;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.registry.EntityEntry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import org.apache.commons.lang3.text.WordUtils;
import swordstat.SwordStat;
import swordstat.init.EntitySorter.EntitySorting;
import swordstat.init.EntitySorter.IEntityGroupSorter;
import swordstat.util.ServerResourceLocator;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
public final class EntitySortingInit {
/**
* Return a Multimap of mod ids to entities added by those mods. Thanks to <a href="https://github.com/McJtyMods/TheOneProbe/blob/9c1e1d94c30d795dc22ad35f752dbb8182250220/src/main/java/mcjty/theoneprobe/Tools.java">the one probe</a>
* for this one.
*
* @param entities Collection of entities to be sorted by mod id
* @return Multimap of mod ids to entities added by those mods
*/
public static Multimap<String, Class<? extends Entity>>
createModIDToEntityClassMapping( Collection<EntityEntry> entities ) {
Multimap<String, Class<? extends Entity>> modIDToEntityClassMapping = HashMultimap.create(128, 32);
for ( EntityEntry entry : entities ){
EntityRegistry.EntityRegistration modSpawn = EntityRegistry.instance().lookupModSpawn(entry.getEntityClass(), true);
String modID;
if ( modSpawn == null ){
modID = "Minecraft";
}
else {
ModContainer container = modSpawn.getContainer();
if ( container == null ){
modID = "Minecraft";
}
else {
modID = container.getModId();
}
}
modIDToEntityClassMapping.put(modID, entry.getEntityClass());
}
return modIDToEntityClassMapping;
}
/**
* Create an EntitySorting with (currently hardcoded) sorters
*
* @param entitySorter
* @param world
* @return
*/
public static EntitySorting createEntitySorting( final EntitySorter entitySorter,
final World world ) {
final IEntityGroupSorter bossSorter = new BossSorter(world);
final IEntityGroupSorter monsterSorter = new MonsterSorter(bossSorter);
final IEntityGroupSorter passiveSorter = new PassiveSorter(bossSorter, monsterSorter);
Map<String, IEntityGroupSorter> sorters = new HashMap<>();
sorters.put(ServerResourceLocator.BOSS_STRING, bossSorter);
sorters.put(ServerResourceLocator.MONSTER_STRING, monsterSorter);
sorters.put(ServerResourceLocator.PASSIVE_STRING, passiveSorter);
return entitySorter.sort(sorters);
}
private static class BossSorter implements IEntityGroupSorter {
private World world;
public BossSorter( World world ) {
this.world = world;
}
@Override
public boolean isInGroup( Class<? extends Entity> entityClass ) {
if ( Modifier.isAbstract(entityClass.getModifiers()) ){
return false;
}
Entity entity;
try {
entity = entityClass.getConstructor(World.class)
.newInstance(world);
} catch ( Exception e ){
SwordStat.LOGGER.error("Could not initialise entity of " + entityClass + ", skipping...");
return false;
}
if ( entity != null && !entity.isNonBoss() ){
// remove entity
entity.setDead();
return true;
}
else {
return false;
}
}
}
private static class MonsterSorter implements IEntityGroupSorter {
IEntityGroupSorter bossSorter;
public MonsterSorter( final IEntityGroupSorter bossSorter ) {
this.bossSorter = bossSorter;
}
@Override
public boolean isInGroup( Class<? extends Entity> entityClass ) {
if ( Modifier.isAbstract(entityClass.getModifiers()) ){
return false;
}
return EntityMob.class.isAssignableFrom(entityClass) &&
!bossSorter.isInGroup(entityClass);
}
}
private static class PassiveSorter implements IEntityGroupSorter {
private final IEntityGroupSorter bossSorter, monsterSorter;
public PassiveSorter( final IEntityGroupSorter bossSorter, final IEntityGroupSorter monsterSorter ) {
this.bossSorter = bossSorter;
this.monsterSorter = monsterSorter;
}
@Override
public boolean isInGroup( Class<? extends Entity> entityClass ) {
if ( Modifier.isAbstract(entityClass.getModifiers()) ){
return false;
}
// Check if living and not in the other groups
else if ( EntityLiving.class.isAssignableFrom(entityClass) ){
return !( bossSorter.isInGroup(entityClass) || monsterSorter.isInGroup(entityClass) );
}
else {
return false;
}
}
};
}
|
3e14940e30abc3175250eca3e227aaa64230bd68 | 1,384 | java | Java | src/main/java/com/qinwei/deathnote/aop/targetSource/EmptyTargetSource.java | qinweiVae/deathnote | 00323313562d8407e05d879407643d0767ffa00d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/qinwei/deathnote/aop/targetSource/EmptyTargetSource.java | qinweiVae/deathnote | 00323313562d8407e05d879407643d0767ffa00d | [
"Apache-2.0"
] | 3 | 2021-12-10T01:15:26.000Z | 2021-12-14T21:19:48.000Z | src/main/java/com/qinwei/deathnote/aop/targetSource/EmptyTargetSource.java | qinweiVae/deathnote | 00323313562d8407e05d879407643d0767ffa00d | [
"Apache-2.0"
] | null | null | null | 24.714286 | 107 | 0.683526 | 8,729 | package com.qinwei.deathnote.aop.targetSource;
import java.io.Serializable;
/**
* @author qinwei
* @date 2019-06-28
*/
public class EmptyTargetSource implements TargetSource, Serializable {
private static final long serialVersionUID = 2511851162302750931L;
private final Class<?> targetClass;
private final boolean isStatic;
public static final EmptyTargetSource INSTANCE = new EmptyTargetSource(null, true);
public static EmptyTargetSource forClass(Class<?> targetClass) {
return forClass(targetClass, true);
}
public static EmptyTargetSource forClass(Class<?> targetClass, boolean isStatic) {
return (targetClass == null && isStatic ? INSTANCE : new EmptyTargetSource(targetClass, isStatic));
}
private EmptyTargetSource(Class<?> targetClass, boolean isStatic) {
this.targetClass = targetClass;
this.isStatic = isStatic;
}
@Override
public boolean isStatic() {
return this.isStatic;
}
@Override
public Object getTarget() throws Exception {
return null;
}
@Override
public void releaseTarget(Object target) throws Exception {
}
@Override
public Class<?> getTargetClass() {
return this.targetClass;
}
private Object readResolve() {
return (this.targetClass == null && this.isStatic ? INSTANCE : this);
}
}
|
3e149488b0d5903d433e5dba962fea7995314dbc | 228 | java | Java | core/src/main/java/org/openstack4j/api/telemetry/ResourceService.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 204 | 2016-05-14T12:06:15.000Z | 2022-03-07T09:45:52.000Z | core/src/main/java/org/openstack4j/api/telemetry/ResourceService.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 721 | 2016-05-13T06:51:32.000Z | 2022-01-13T17:44:40.000Z | core/src/main/java/org/openstack4j/api/telemetry/ResourceService.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 291 | 2016-05-13T05:58:13.000Z | 2022-03-07T09:43:36.000Z | 16.285714 | 48 | 0.758772 | 8,730 | package org.openstack4j.api.telemetry;
import java.util.List;
import org.openstack4j.model.telemetry.Resource;
public interface ResourceService {
List<? extends Resource> list();
Resource get(String resourceId);
}
|
3e149494800437510343a08c2508f2fb3f56bb76 | 3,802 | java | Java | baselibrary/src/main/java/com/jusfoun/baselibrary/Util/RegularUtils.java | ZypTeam/TalkLaw | ad550878989338453f2644d8adbb5f1eca941f3e | [
"Apache-2.0"
] | null | null | null | baselibrary/src/main/java/com/jusfoun/baselibrary/Util/RegularUtils.java | ZypTeam/TalkLaw | ad550878989338453f2644d8adbb5f1eca941f3e | [
"Apache-2.0"
] | null | null | null | baselibrary/src/main/java/com/jusfoun/baselibrary/Util/RegularUtils.java | ZypTeam/TalkLaw | ad550878989338453f2644d8adbb5f1eca941f3e | [
"Apache-2.0"
] | null | null | null | 28.863636 | 111 | 0.527559 | 8,731 | package com.jusfoun.baselibrary.Util;
import android.text.TextUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author lee
* @version create time:2015年7月23日_上午11:28:38
* @Description 正则判断
*/
public class RegularUtils {
/**
* 验证Email
*
* @param email email地址,格式:zhangsan@ychag@example.com.cn,xxx代表邮件服务商
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkEmail(String email) {
if (TextUtils.isEmpty(email))
return false;
// String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";
String regex = "^(\\w-*\\.*)+@(\\w-?)+(\\.\\w{2,})+";
return Pattern.matches(regex, email);
}
/**
* 验证身份证号码
*
* @param idCard 居民身份证号码15位或18位,最后一位可能是数字或字母
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkIdCard(String idCard) {
String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}";
return Pattern.matches(regex, idCard);
}
/**
* 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港))
*
* @param mobile 移动、联通、电信运营商的号码段
* <p>移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡)
* 、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)</p>
* <p>联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)</p>
* <p>电信的号段:133、153、180(未启用)、189</p>
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkMobile(String mobile) {
String regex = "(\\+\\d+)?1[3458]\\d{9}$";
return Pattern.matches(regex, mobile);
}
/**
* 验证中文
*
* @param chinese 中文字符
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkChinese(String chinese) {
String regex = "^[\u4E00-\u9FA5]+$";
return Pattern.matches(regex, chinese);
}
/**
* 验证整数(正整数和负整数)
*
* @param digit 五位或五位以上0-9之间的整数
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkDigit(String digit) {
String regex = "\\+?[1-9]\\d{4,}";
return Pattern.matches(regex, digit);
}
/**
* 验证固定电话号码
*
* @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447
* <p><b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字,
* 数字之后是空格分隔的国家(地区)代码。</p>
* <p><b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号——
* 对不使用地区或城市代码的国家(地区),则省略该组件。</p>
* <p><b>电话号码:</b>这包含从 0 到 9 的一个或多个数字 </p>
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkPhone(String phone) {
String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$";
return Pattern.matches(regex, phone);
}
public static boolean checkFax(String fax) {
String regex = "^[+]?(\\d){1,3}[ ]?([-]?((\\d)|[ ]){1,12})+$";
return Pattern.matches(regex, fax);
}
/**
* 去除电话号码中的非数字字符
*
* @param string 要去除的字符串
* @return 纯数字电话号码
*/
public static String getNumber(String string) {
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(string);
return m.replaceAll("").trim();
}
/**
* 检查是否包含表情
*
* @param string
* @return
*/
public static boolean isEmoji(String string) {
if (TextUtils.isEmpty(string))
return false;
Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(string);
return m.find();
}
}
|
3e1494aa5871e626eaafd46ead6c0e5f81e0465f | 6,577 | java | Java | kogito-codegen-modules/kogito-codegen-processes/src/main/resources/class-templates/RestResourceQuarkusTemplate.java | lucamolteni/kogito-runtimes | d3c879a48d4ed662a1389c1122d1f4f4f9594045 | [
"Apache-2.0"
] | null | null | null | kogito-codegen-modules/kogito-codegen-processes/src/main/resources/class-templates/RestResourceQuarkusTemplate.java | lucamolteni/kogito-runtimes | d3c879a48d4ed662a1389c1122d1f4f4f9594045 | [
"Apache-2.0"
] | null | null | null | kogito-codegen-modules/kogito-codegen-processes/src/main/resources/class-templates/RestResourceQuarkusTemplate.java | lucamolteni/kogito-runtimes | d3c879a48d4ed662a1389c1122d1f4f4f9594045 | [
"Apache-2.0"
] | null | null | null | 42.432258 | 119 | 0.570777 | 8,732 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* 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.myspace.demo;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.ws.rs.Consumes;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
import org.jbpm.util.JsonSchemaUtil;
import org.kie.kogito.Application;
import org.kie.kogito.process.Process;
import org.kie.kogito.process.ProcessInstance;
import org.kie.kogito.process.ProcessInstanceExecutionException;
import org.kie.kogito.process.ProcessInstanceNotFoundException;
import org.kie.kogito.process.ProcessInstanceReadMode;
import org.kie.kogito.process.WorkItem;
import org.kie.kogito.process.workitem.Attachment;
import org.kie.kogito.process.workitem.AttachmentInfo;
import org.kie.kogito.process.workitem.Comment;
import org.kie.kogito.process.workitem.Policies;
import org.kie.kogito.process.impl.Sig;
import org.kie.kogito.services.uow.UnitOfWorkExecutor;
import org.kie.kogito.auth.IdentityProvider;
import org.jbpm.process.instance.impl.humantask.HumanTaskHelper;
import org.jbpm.process.instance.impl.humantask.HumanTaskTransition;
@Path("/$name$")
public class $Type$Resource {
Process<$Type$> process;
Application application;
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createResource_$name$(@Context HttpHeaders httpHeaders,
@Context UriInfo uriInfo,
@QueryParam("businessKey") String businessKey,
$Type$Input resource) {
return UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
$Type$Input inputModel = resource != null ? resource : new $Type$Input();
ProcessInstance<$Type$> pi = process.createInstance(businessKey, inputModel.toModel());
String startFromNode = httpHeaders.getHeaderString("X-KOGITO-StartFromNode");
if (startFromNode != null) {
pi.startFrom(startFromNode);
} else {
pi.start();
}
UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder().path(pi.id());
return Response.created(uriBuilder.build())
.entity(pi.checkError().variables().toOutput())
.build();
});
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<$Type$Output> getResources_$name$() {
return process.instances().values().stream()
.map(pi -> pi.variables().toOutput())
.collect(Collectors.toList());
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public $Type$Output getResource_$name$(@PathParam("id") String id) {
return process.instances()
.findById(id, ProcessInstanceReadMode.READ_ONLY)
.map(pi -> pi.variables().toOutput())
.orElseThrow(() -> new NotFoundException());
}
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public $Type$Output deleteResource_$name$(@PathParam("id") final String id) {
return UnitOfWorkExecutor.executeInUnitOfWork(
application.unitOfWorkManager(),
() -> process
.instances()
.findById(id)
.map(pi -> {
pi.abort();
return pi.checkError().variables().toOutput();
}))
.orElseThrow(() -> new NotFoundException());
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public $Type$Output updateModel_$name$(@PathParam("id") String id, $Type$ resource) {
return UnitOfWorkExecutor.executeInUnitOfWork(
application.unitOfWorkManager(),
() -> process
.instances()
.findById(id)
.map(pi -> pi.updateVariables(resource).toOutput()))
.orElseThrow(() -> new NotFoundException());
}
@GET
@Path("/{id}/tasks")
@Produces(MediaType.APPLICATION_JSON)
public List<WorkItem> getTasks_$name$(@PathParam("id") String id,
@QueryParam("user") final String user,
@QueryParam("group") final List<String> groups) {
return process.instances()
.findById(id, ProcessInstanceReadMode.READ_ONLY)
.map(pi -> pi.workItems(Policies.of(user, groups)))
.orElseThrow(() -> new NotFoundException());
}
}
|
3e1494ab3f4bc4a730b397c322dfb72e1531ce7c | 790 | java | Java | core/src/com/hwooy/shiftgamebeta/object_classes/Platform.java | jpanda109/ShiftGameBeta | 95c2c278a1c8934b5b295bed3719cbaee5dca4ae | [
"Apache-2.0"
] | null | null | null | core/src/com/hwooy/shiftgamebeta/object_classes/Platform.java | jpanda109/ShiftGameBeta | 95c2c278a1c8934b5b295bed3719cbaee5dca4ae | [
"Apache-2.0"
] | null | null | null | core/src/com/hwooy/shiftgamebeta/object_classes/Platform.java | jpanda109/ShiftGameBeta | 95c2c278a1c8934b5b295bed3719cbaee5dca4ae | [
"Apache-2.0"
] | null | null | null | 23.939394 | 142 | 0.672152 | 8,733 | package com.hwooy.shiftgamebeta.object_classes;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
/**
* Created by Anna Hwang on 12/3/2014.
*/
public class Platform extends ShiftObject {
public float SPEED;
public float PLATFORM_WIDTH;
public float PLATFORM_HEIGHT;
public Vector2 v1;
public Vector2 v2;
public Platform(Body body, String texturePath, float width, float height, float plat_w, float plat_h, float speed, Vector2 v1, Vector2 v2)
{
super(body, texturePath, width, height);
this.SPEED = speed;
this.v1 = v1;
this.v2 = v2;
this.PLATFORM_HEIGHT = plat_h;
this.PLATFORM_WIDTH = plat_w;
}
public void update()
{}
public void setInitialSpeed()
{}
}
|
3e1495668b28c2dde6d28efd08fc2811261a7142 | 656 | java | Java | org.hl7.fhir.r5/src/test/java/org/hl7/fhir/r5/test/AllTests.java | jkiddo/org.hl7.fhir.core | 793545f2d95e7fb9ee95b3b8ee837e733a391c69 | [
"Apache-2.0"
] | null | null | null | org.hl7.fhir.r5/src/test/java/org/hl7/fhir/r5/test/AllTests.java | jkiddo/org.hl7.fhir.core | 793545f2d95e7fb9ee95b3b8ee837e733a391c69 | [
"Apache-2.0"
] | null | null | null | org.hl7.fhir.r5/src/test/java/org/hl7/fhir/r5/test/AllTests.java | jkiddo/org.hl7.fhir.core | 793545f2d95e7fb9ee95b3b8ee837e733a391c69 | [
"Apache-2.0"
] | null | null | null | 26.24 | 51 | 0.748476 | 8,734 | package org.hl7.fhir.r5.test;
import org.hl7.fhir.r5.model.BaseDateTimeTypeTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
SnomedExpressionsTests.class,
GraphQLParserTests.class,
TurtleTests.class,
ProfileUtilitiesTests.class,
ResourceRoundTripTests.class,
GraphQLEngineTests.class,
LiquidEngineTests.class,
FHIRPathTests.class,
NarrativeGeneratorTests.class,
ShexGeneratorTests.class,
BaseDateTimeTypeTest.class,
SnapShotGenerationTests.class})
public class AllTests {
}
|
3e1495fe3ccabd9012c8789ef93f0592787b7089 | 1,354 | java | Java | app/models/Comment.java | dkvz/dorade-blog-engine | 3e3f6e98ea66211ca441fe8ceda53c0f75d5a423 | [
"Apache-2.0"
] | null | null | null | app/models/Comment.java | dkvz/dorade-blog-engine | 3e3f6e98ea66211ca441fe8ceda53c0f75d5a423 | [
"Apache-2.0"
] | null | null | null | app/models/Comment.java | dkvz/dorade-blog-engine | 3e3f6e98ea66211ca441fe8ceda53c0f75d5a423 | [
"Apache-2.0"
] | null | null | null | 20.515152 | 77 | 0.685377 | 8,735 | package models;
import java.text.*;
import java.util.*;
public class Comment {
private String comment;
private long id = -1;
private String author;
private long articleId;
private Date date;
private String clientIP;
public Map<String, Object> toReducedMap() {
Map<String, Object> res = new HashMap<String, Object>();
if (this.id >= 0) {
res.put("id", Long.toString(this.getId()));
}
res.put("author", this.getAuthor());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ssZ");
String formatted = dateFormat.format(this.getDate());
res.put("date", formatted);
res.put("comment", this.getComment());
return res;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public long getArticleId() {
return articleId;
}
public void setArticleId(long articleId) {
this.articleId = articleId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getClientIP() {
return clientIP;
}
public void setClientIP(String clientIP) {
this.clientIP = clientIP;
}
}
|
3e1496e1d0e5ad7ee9da916f3b6577d1e0264b96 | 2,640 | java | Java | neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/bolt/BoltDriver.java | fbiville/neo4j-jdbc | b672f9184fedd184b2d987673e87547b37c4743f | [
"Apache-2.0"
] | null | null | null | neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/bolt/BoltDriver.java | fbiville/neo4j-jdbc | b672f9184fedd184b2d987673e87547b37c4743f | [
"Apache-2.0"
] | null | null | null | neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/bolt/BoltDriver.java | fbiville/neo4j-jdbc | b672f9184fedd184b2d987673e87547b37c4743f | [
"Apache-2.0"
] | null | null | null | 33 | 119 | 0.720833 | 8,736 | /*
* Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it]
* <p>
* This file is part of the "LARUS Integration Framework for Neo4j".
* <p>
* The "LARUS Integration Framework for Neo4j" is 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
* <p>
* Created on 23/02/16
*/
package org.neo4j.jdbc.bolt;
import org.neo4j.driver.v1.*;
import org.neo4j.jdbc.BaseDriver;
import org.neo4j.jdbc.InstanceFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import static org.neo4j.driver.v1.Config.build;
/**
* @author AgileLARUS
* @since 3.0.0
*/
public class BoltDriver extends BaseDriver {
public final static String JDBC_BOLT_PREFIX = "bolt";
/**
* Default constructor.
*/
public BoltDriver() throws SQLException {
super(JDBC_BOLT_PREFIX);
}
@Override public Connection connect(String url, Properties props) throws SQLException {
if (url == null) {
throw new SQLException("null is not a valid url");
}
Connection connection = null;
if (acceptsURL(url)) {
String boltUrl = url.replace(BaseDriver.JDBC_PREFIX, "").replaceAll("^(" + JDBC_BOLT_PREFIX + ":)([^/])", "$1//$2");
try {
Properties info = parseUrlProperties(boltUrl, props);
Config.ConfigBuilder builder = build();
if (info.containsKey("nossl")) {
builder = builder.withEncryptionLevel(Config.EncryptionLevel.NONE);
}
Config config = builder.toConfig();
AuthToken authToken = getAuthToken(info);
Driver driver = GraphDatabase.driver(boltUrl, authToken, config);
Session session = driver.session();
BoltConnection boltConnection = new BoltConnection(session, info, url);
connection = InstanceFactory.debug(BoltConnection.class, boltConnection, BoltConnection.hasDebug(info));
} catch (Exception e) {
throw new SQLException(e);
}
}
return connection;
}
private AuthToken getAuthToken(Properties properties) {
if (properties.containsKey("user") && properties.containsKey("password")) {
return AuthTokens.basic(properties.getProperty("user"), properties.getProperty("password"));
}
return AuthTokens.none();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.