text
stringlengths 7
1.01M
|
|---|
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.openapi.models;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/** ConfigMap holds configuration data for pods to consume. */
@ApiModel(description = "ConfigMap holds configuration data for pods to consume.")
@javax.annotation.Generated(
value = "org.openapitools.codegen.languages.JavaClientCodegen",
date = "2021-09-20T22:55:54.394Z[Etc/UTC]")
public class V1ConfigMap implements io.kubernetes.client.common.KubernetesObject {
public static final String SERIALIZED_NAME_API_VERSION = "apiVersion";
@SerializedName(SERIALIZED_NAME_API_VERSION)
private String apiVersion;
public static final String SERIALIZED_NAME_BINARY_DATA = "binaryData";
@SerializedName(SERIALIZED_NAME_BINARY_DATA)
private Map<String, byte[]> binaryData = null;
public static final String SERIALIZED_NAME_DATA = "data";
@SerializedName(SERIALIZED_NAME_DATA)
private Map<String, String> data = null;
public static final String SERIALIZED_NAME_IMMUTABLE = "immutable";
@SerializedName(SERIALIZED_NAME_IMMUTABLE)
private Boolean immutable;
public static final String SERIALIZED_NAME_KIND = "kind";
@SerializedName(SERIALIZED_NAME_KIND)
private String kind;
public static final String SERIALIZED_NAME_METADATA = "metadata";
@SerializedName(SERIALIZED_NAME_METADATA)
private V1ObjectMeta metadata;
public V1ConfigMap apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/**
* APIVersion defines the versioned schema of this representation of an object. Servers should
* convert recognized schemas to the latest internal value, and may reject unrecognized values.
* More info:
* https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
*
* @return apiVersion
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources")
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public V1ConfigMap binaryData(Map<String, byte[]> binaryData) {
this.binaryData = binaryData;
return this;
}
public V1ConfigMap putBinaryDataItem(String key, byte[] binaryDataItem) {
if (this.binaryData == null) {
this.binaryData = new HashMap<>();
}
this.binaryData.put(key, binaryDataItem);
return this;
}
/**
* BinaryData contains the binary data. Each key must consist of alphanumeric characters,
* '-', '_' or '.'. BinaryData can contain byte sequences that are not in
* the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data
* field, this is enforced during validation process. Using this field will require 1.10+
* apiserver and kubelet.
*
* @return binaryData
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process. Using this field will require 1.10+ apiserver and kubelet.")
public Map<String, byte[]> getBinaryData() {
return binaryData;
}
public void setBinaryData(Map<String, byte[]> binaryData) {
this.binaryData = binaryData;
}
public V1ConfigMap data(Map<String, String> data) {
this.data = data;
return this;
}
public V1ConfigMap putDataItem(String key, String dataItem) {
if (this.data == null) {
this.data = new HashMap<>();
}
this.data.put(key, dataItem);
return this;
}
/**
* Data contains the configuration data. Each key must consist of alphanumeric characters,
* '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the
* BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData
* field, this is enforced during validation process.
*
* @return data
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"Data contains the configuration data. Each key must consist of alphanumeric characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData field, this is enforced during validation process.")
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
public V1ConfigMap immutable(Boolean immutable) {
this.immutable = immutable;
return this;
}
/**
* Immutable, if set to true, ensures that data stored in the ConfigMap cannot be updated (only
* object metadata can be modified). If not set to true, the field can be modified at any time.
* Defaulted to nil.
*
* @return immutable
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"Immutable, if set to true, ensures that data stored in the ConfigMap cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil.")
public Boolean getImmutable() {
return immutable;
}
public void setImmutable(Boolean immutable) {
this.immutable = immutable;
}
public V1ConfigMap kind(String kind) {
this.kind = kind;
return this;
}
/**
* Kind is a string value representing the REST resource this object represents. Servers may infer
* this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More
* info:
* https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
*
* @return kind
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds")
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public V1ConfigMap metadata(V1ObjectMeta metadata) {
this.metadata = metadata;
return this;
}
/**
* Get metadata
*
* @return metadata
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public V1ObjectMeta getMetadata() {
return metadata;
}
public void setMetadata(V1ObjectMeta metadata) {
this.metadata = metadata;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
V1ConfigMap v1ConfigMap = (V1ConfigMap) o;
return Objects.equals(this.apiVersion, v1ConfigMap.apiVersion)
&& Objects.equals(this.binaryData, v1ConfigMap.binaryData)
&& Objects.equals(this.data, v1ConfigMap.data)
&& Objects.equals(this.immutable, v1ConfigMap.immutable)
&& Objects.equals(this.kind, v1ConfigMap.kind)
&& Objects.equals(this.metadata, v1ConfigMap.metadata);
}
@Override
public int hashCode() {
return Objects.hash(apiVersion, binaryData, data, immutable, kind, metadata);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class V1ConfigMap {\n");
sb.append(" apiVersion: ").append(toIndentedString(apiVersion)).append("\n");
sb.append(" binaryData: ").append(toIndentedString(binaryData)).append("\n");
sb.append(" data: ").append(toIndentedString(data)).append("\n");
sb.append(" immutable: ").append(toIndentedString(immutable)).append("\n");
sb.append(" kind: ").append(toIndentedString(kind)).append("\n");
sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
public void writeToZip(byte b[], int off, int len) throws IOException {
if (zipstream == null) {
response.setContentType("application/vnd.google-earth.kmzl; charset=UTF-8");
zipstream = new ZipOutputStream(output);
zipstream.putNextEntry(new ZipEntry(kmlFileName));
}
zipstream.write(b, off, len);
}
|
package org.javarosa.core.util;
/**
* Convenience interface for states that do not have any transitions.
*/
public interface TrivialTransitions {
void done();
}
|
package rs.readahead.washington.mobile.bus.event;
import rs.readahead.washington.mobile.bus.IEvent;
import rs.readahead.washington.mobile.domain.entity.TrainModule;
public class DeleteTrainModuleEvent implements IEvent {
private final TrainModule module;
public DeleteTrainModuleEvent(TrainModule module) {
this.module = module;
}
public TrainModule getModule() {
return module;
}
}
|
package io.appium.android.bootstrap.handler;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiSelector;
import io.appium.android.bootstrap.*;
import io.appium.android.bootstrap.exceptions.ElementNotFoundException;
import io.appium.android.bootstrap.exceptions.InvalidSelectorException;
import io.appium.android.bootstrap.exceptions.InvalidStrategyException;
import io.appium.android.bootstrap.exceptions.UiSelectorSyntaxException;
import io.appium.android.bootstrap.selector.Strategy;
import io.appium.android.bootstrap.utils.ClassInstancePair;
import io.appium.android.bootstrap.utils.ElementHelpers;
import io.appium.android.bootstrap.utils.UiAutomatorParser;
import io.appium.android.bootstrap.utils.XMLHierarchy;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.regex.Pattern;
import static io.appium.android.bootstrap.utils.API.API_18;
/**
* This handler is used to find elements in the Android UI.
* <p/>
* Based on which {@link Strategy}, {@link UiSelector}, and optionally the
* contextId, the element Id or Ids are returned to the user.
*/
public class Find extends CommandHandler {
// These variables are expected to persist across executions.
AndroidElementsHash elements = AndroidElementsHash.getInstance();
static JSONObject apkStrings = null;
UiAutomatorParser uiAutomatorParser = new UiAutomatorParser();
/**
* java_package : type / name
*
* com.example.Test:id/enter
*
* ^[a-zA-Z_] - Java package must start with letter or underscore
* [a-zA-Z0-9\._]* - Java package may contain letters, numbers, periods and underscores
* : - : ends the package and starts the type
* [^\/]+ - type is made up of at least one non-/ characters
* \\/ - / ends the type and starts the name
* [\S]+$ - the name contains at least one non-space character and then the line is ended
*/
static final Pattern resourceIdRegex = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9\\._]*:[^\\/]+\\/[\\S]+$");
/*
* @param command The {@link AndroidCommand} used for this handler.
*
* @return {@link AndroidCommandResult}
*
* @throws JSONException
*
* @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android.
* bootstrap.AndroidCommand)
*/
@Override
public AndroidCommandResult execute(final AndroidCommand command)
throws JSONException {
final Hashtable<String, Object> params = command.params();
// only makes sense on a device
final Strategy strategy;
try {
strategy = Strategy.fromString((String) params.get("strategy"));
} catch (final InvalidStrategyException e) {
return new AndroidCommandResult(WDStatus.UNKNOWN_COMMAND, e.getMessage());
}
final String contextId = (String) params.get("context");
final String text = (String) params.get("selector");
final boolean multiple = (Boolean) params.get("multiple");
Logger.debug("Finding " + text + " using " + strategy.toString()
+ " with the contextId: " + contextId + " multiple: " + multiple);
try {
Object result = null;
List<UiSelector> selectors = getSelectors(strategy, text, multiple);
if (!multiple) {
for (final UiSelector sel : selectors) {
try {
Logger.debug("Using: " + sel.toString());
result = fetchElement(sel, contextId);
} catch (final ElementNotFoundException ignored) {
}
if (result != null) {
break;
}
}
} else {
List<AndroidElement> foundElements = new ArrayList<AndroidElement>();
for (final UiSelector sel : selectors) {
// With multiple selectors, we expect that some elements may not
// exist.
try {
Logger.debug("Using: " + sel.toString());
List<AndroidElement> elementsFromSelector = fetchElements(sel, contextId);
foundElements.addAll(elementsFromSelector);
} catch (final UiObjectNotFoundException ignored) {
}
}
if (strategy == Strategy.ANDROID_UIAUTOMATOR) {
foundElements = ElementHelpers.dedupe(foundElements);
}
result = elementsToJSONArray(foundElements);
}
// If there are no results, then return an error.
if (result == null) {
return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT,
"No element found");
}
return getSuccessResult(result);
} catch (final InvalidStrategyException e) {
return getErrorResult(e.getMessage());
} catch (final UiSelectorSyntaxException e) {
return new AndroidCommandResult(WDStatus.UNKNOWN_COMMAND, e.getMessage());
} catch (final ElementNotFoundException e) {
return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage());
} catch (ParserConfigurationException e) {
return getErrorResult("Error parsing xml hierarchy dump: " + e.getMessage());
} catch (InvalidSelectorException e) {
return new AndroidCommandResult(WDStatus.INVALID_SELECTOR, e.getMessage());
}
}
/**
* Get the element from the {@link AndroidElementsHash} and return the element
* id using JSON.
*
* @param sel
* A UiSelector that targets the element to fetch.
* @param contextId
* The Id of the element used for the context.
* @return JSONObject
* @throws JSONException
* @throws ElementNotFoundException
*/
private JSONObject fetchElement(final UiSelector sel, final String contextId)
throws JSONException, ElementNotFoundException {
final JSONObject res = new JSONObject();
final AndroidElement el = elements.getElement(sel, contextId);
return res.put("ELEMENT", el.getId());
}
/**
* Get an array of AndroidElement objects from the {@link AndroidElementsHash}
*
* @param sel
* A UiSelector that targets the element to fetch.
* @param contextId
* The Id of the element used for the context.
* @return ArrayList<AndroidElement>
* @throws UiObjectNotFoundException
*/
private ArrayList<AndroidElement> fetchElements(final UiSelector sel, final String contextId)
throws UiObjectNotFoundException {
return elements.getElements(sel, contextId);
}
/**
* Get a JSONArray to represent a collection of AndroidElements
*
* @param els collection of AndroidElement objects
* @return elements in the format which appium server returns
* @throws JSONException
*/
private JSONArray elementsToJSONArray(List<AndroidElement> els) throws JSONException {
final JSONArray resArray = new JSONArray();
for (AndroidElement el : els) {
resArray.put(ElementHelpers.toJSON(el));
}
return resArray;
}
/**
* Create and return a UiSelector based on the strategy, text, and how many
* you want returned.
*
* @param strategy
* The {@link Strategy} used to search for the element.
* @param text
* Any text used in the search (i.e. match, regex, etc.)
* @param many
* Boolean that is either only one element (false), or many (true)
* @return UiSelector
* @throws InvalidStrategyException
* @throws ElementNotFoundException
*/
private List<UiSelector> getSelectors(final Strategy strategy,
final String text, final boolean many) throws InvalidStrategyException,
ElementNotFoundException, UiSelectorSyntaxException, ParserConfigurationException, InvalidSelectorException {
final List<UiSelector> selectors = new ArrayList<UiSelector>();
UiSelector sel = new UiSelector();
switch (strategy) {
case XPATH:
for (UiSelector selector : getXPathSelectors(text, many)) {
selectors.add(selector);
}
break;
case CLASS_NAME:
sel = sel.className(text);
if (!many) {
sel = sel.instance(0);
}
selectors.add(sel);
break;
case ID:
// There are three types of ids on Android.
// 1. resourceId (API >= 18)
// 2. accessibility id (content description)
// 3. strings.xml id
//
// If text is a resource id then only use the resource id selector.
if (API_18 && resourceIdRegex.matcher(text).matches()) {
sel = sel.resourceId(text);
if (!many) {
sel = sel.instance(0);
}
selectors.add(sel);
break;
}
// must create a new selector or the selector from
// the resourceId search will cause problems
sel = new UiSelector().description(text);
if (!many) {
sel = sel.instance(0);
}
selectors.add(sel);
// resource id and content description failed to match
// so the strings.xml selector is used
UiSelector stringsXmlSelector = stringsXmlId(many, text);
if (stringsXmlSelector != null) {
selectors.add(stringsXmlSelector);
}
break;
case ACCESSIBILITY_ID:
sel = sel.description(text);
if (!many) {
sel = sel.instance(0);
}
selectors.add(sel);
break;
case NAME:
sel = new UiSelector().description(text);
if (!many) {
sel = sel.instance(0);
}
selectors.add(sel);
sel = new UiSelector().text(text);
if (!many) {
sel = sel.instance(0);
}
selectors.add(sel);
break;
case ANDROID_UIAUTOMATOR:
List<UiSelector> parsedSelectors;
try {
parsedSelectors = uiAutomatorParser.parse(text);
} catch (final UiSelectorSyntaxException e) {
throw new UiSelectorSyntaxException(
"Could not parse UiSelector argument: " + e.getMessage());
}
for (UiSelector selector : parsedSelectors) {
selectors.add(selector);
}
break;
case LINK_TEXT:
case PARTIAL_LINK_TEXT:
case CSS_SELECTOR:
default:
throw new InvalidStrategyException("Sorry, we don't support the '"
+ strategy.getStrategyName() + "' locator strategy yet");
}
return selectors;
}
/** Returns null on failure to match **/
private UiSelector stringsXmlId(final boolean many, String text) {
UiSelector sel = null;
try {
final String xmlValue = apkStrings.getString(text);
if (xmlValue == null || xmlValue.isEmpty()) {
return null;
}
sel = new UiSelector().text(xmlValue);
if (!many) {
sel = sel.instance(0);
}
} catch (JSONException e) {
} finally {
return sel;
}
}
/** returns List of UiSelectors for an xpath expression **/
private List<UiSelector> getXPathSelectors(final String expression, final boolean multiple) throws ElementNotFoundException, ParserConfigurationException, InvalidSelectorException {
List<UiSelector> selectors = new ArrayList<UiSelector>();
ArrayList<ClassInstancePair> pairs = XMLHierarchy.getClassInstancePairs(expression);
if (!multiple) {
if (pairs.size() == 0) {
throw new NoSuchElementException();
}
selectors.add(pairs.get(0).getSelector());
} else {
for (ClassInstancePair pair : pairs) {
selectors.add(pair.getSelector());
}
}
return selectors;
}
}
|
package br.com.senior.platform.workflow.pojos;
/**
* Nível de acesso ao processo
*/
public enum ProcessAccessLevel {
/**
* Editar e iniciar
*/
EDIT_AND_START,
/**
* Iniciar
*/
START,
/**
* Editar
*/
EDIT,
/**
* Nenhuma
*/
NONE
}
|
package com.yinglan.scg.mine.myvehicle;
import com.common.cklibrary.common.BasePresenter;
import com.common.cklibrary.common.BaseView;
/**
* Created by Administrator on 2017/2/11.
*/
public interface MyVehicleContract {
interface Presenter extends BasePresenter {
/**
* 获取我的车辆列表
*/
void getMyVehicleList();
/**
* 设置默认车辆
*/
void setModelDefault(int model_id);
}
interface View extends BaseView<Presenter, String> {
}
}
|
package com.leixu.write.leetcode;
/**
* Created by Lei on 2017/11/2.
*
* Description
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Spoilers:
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
给你一个整型数,求它的逆序整型数,而且有个小坑点,当它的逆序整型数溢出的话,那么就返回0,用我们代码表示的话可以求得结果保存在long中,最后把结果和整型的两个范围比较即可。
*
*/
public class Solution007 {
public int reverse(int x){
long res = 0;
for(; x != 0; x /= 10){ // x /= 10; 等同于 x = (int)(x / 10);
res = res * 10 + x % 10;
}
return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res;
}
public static void main(String[] args){
Solution007 solution = new Solution007();
System.out.println(solution.reverse(123));
System.out.println(solution.reverse(-123));
System.out.println(solution.reverse(100));
System.out.println(solution.reverse(1000000003));
}
}
|
package org.apache.maven.it;
/*
* 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.
*/
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
import java.io.File;
import java.util.List;
/**
* This is a test set for <a href="http://jira.codehaus.org/browse/MNG-3043">MNG-3043</a>.
*
* @author Benjamin Bentmann
*/
public class MavenITmng3043BestEffortReactorResolutionTest
extends AbstractMavenIntegrationTestCase
{
public MavenITmng3043BestEffortReactorResolutionTest()
{
super( "[3.0-alpha-3,)" );
}
/**
* Test that dependencies on attached artifacts like a test JAR or an EJB client JAR which have not been built
* yet, i.e. in build phases prior to "package" like "test", are satisfied from the output directories of the
* projects in the reactor. This is meant as a best effort to provide a class path for compilation or testing.
*/
public void testitTestPhase()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/mng-3043" );
Verifier verifier = newVerifier( testDir.getAbsolutePath() );
verifier.setAutoclean( false );
verifier.deleteDirectory( "consumer-a/target" );
verifier.deleteDirectory( "consumer-b/target" );
verifier.deleteDirectory( "consumer-c/target" );
verifier.deleteArtifacts( "org.apache.maven.its.mng3043" );
verifier.setLogFileName( "log-test.txt" );
verifier.executeGoal( "test" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
List<String> classpath;
classpath = verifier.loadLines( "consumer-a/target/compile.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-test" } );
assertNotContains( classpath, new String[] { "classes-main" } );
classpath = verifier.loadLines( "consumer-a/target/runtime.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-test" } );
assertNotContains( classpath, new String[] { "classes-main" } );
classpath = verifier.loadLines( "consumer-a/target/test.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-test" } );
assertNotContains( classpath, new String[] { "classes-main" } );
classpath = verifier.loadLines( "consumer-b/target/compile.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-main" } );
assertNotContains( classpath, new String[] { "classes-test" } );
classpath = verifier.loadLines( "consumer-b/target/runtime.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-main" } );
assertNotContains( classpath, new String[] { "classes-test" } );
classpath = verifier.loadLines( "consumer-b/target/test.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-main" } );
assertNotContains( classpath, new String[] { "classes-test" } );
classpath = verifier.loadLines( "consumer-c/target/compile.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-main" } );
assertContains( classpath, new String[] { "classes-test" } );
classpath = verifier.loadLines( "consumer-c/target/runtime.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-main" } );
assertContains( classpath, new String[] { "classes-test" } );
classpath = verifier.loadLines( "consumer-c/target/test.txt", "UTF-8" );
assertContains( classpath, new String[] { "classes-main" } );
assertContains( classpath, new String[] { "classes-test" } );
}
/**
* Test that dependency resolution still uses the actual artifact files once these have been
* assembled/attached in the "package" phase. This ensures the class path is accurate and not locked to
* the output directories of the best effort model from above.
*/
public void testitPackagePhase()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/mng-3043" );
Verifier verifier = newVerifier( testDir.getAbsolutePath() );
verifier.setAutoclean( false );
verifier.deleteDirectory( "consumer-a/target" );
verifier.deleteDirectory( "consumer-b/target" );
verifier.deleteDirectory( "consumer-c/target" );
verifier.deleteArtifacts( "org.apache.maven.its.mng3043" );
verifier.setLogFileName( "log-package.txt" );
verifier.executeGoal( "package" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
List<String> classpath;
classpath = verifier.loadLines( "consumer-a/target/compile.txt", "UTF-8" );
assertContains( classpath, new String[] { "tests.jar" } );
assertNotContains( classpath, new String[] { "client.jar" } );
classpath = verifier.loadLines( "consumer-a/target/runtime.txt", "UTF-8" );
assertContains( classpath, new String[] { "tests.jar" } );
assertNotContains( classpath, new String[] { "client.jar" } );
classpath = verifier.loadLines( "consumer-a/target/test.txt", "UTF-8" );
assertContains( classpath, new String[] { "tests.jar" } );
assertNotContains( classpath, new String[] { "client.jar" } );
classpath = verifier.loadLines( "consumer-b/target/compile.txt", "UTF-8" );
assertContains( classpath, new String[] { "client.jar" } );
assertNotContains( classpath, new String[] { "tests.jar" } );
classpath = verifier.loadLines( "consumer-b/target/runtime.txt", "UTF-8" );
assertContains( classpath, new String[] { "client.jar" } );
assertNotContains( classpath, new String[] { "tests.jar" } );
classpath = verifier.loadLines( "consumer-b/target/test.txt", "UTF-8" );
assertContains( classpath, new String[] { "client.jar" } );
assertNotContains( classpath, new String[] { "tests.jar" } );
classpath = verifier.loadLines( "consumer-c/target/compile.txt", "UTF-8" );
assertContains( classpath, new String[] { "client.jar" } );
assertContains( classpath, new String[] { "tests.jar" } );
classpath = verifier.loadLines( "consumer-c/target/runtime.txt", "UTF-8" );
assertContains( classpath, new String[] { "client.jar" } );
assertContains( classpath, new String[] { "tests.jar" } );
classpath = verifier.loadLines( "consumer-c/target/test.txt", "UTF-8" );
assertContains( classpath, new String[] { "client.jar" } );
assertContains( classpath, new String[] { "tests.jar" } );
}
private void assertContains( List<String> collection, String[] items )
{
for ( String item : items )
{
assertContains( collection, item );
}
}
private void assertContains( List<String> collection, String item )
{
assertTrue( item + " missing in " + collection, collection.contains( item ) );
}
private void assertNotContains( List<String> collection, String[] items )
{
for ( String item : items )
{
assertNotContains( collection, item );
}
}
private void assertNotContains( List<String> collection, String item )
{
assertFalse( item + " present in " + collection, collection.contains( item ) );
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.planner.optimizations;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.prestosql.connector.CatalogName;
import io.prestosql.cost.StatsAndCosts;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Metadata;
import io.prestosql.metadata.TableHandle;
import io.prestosql.plugin.tpch.TpchColumnHandle;
import io.prestosql.plugin.tpch.TpchTableHandle;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.planner.Plan;
import io.prestosql.sql.planner.PlanNodeIdAllocator;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.SymbolAllocator;
import io.prestosql.sql.planner.TypeAnalyzer;
import io.prestosql.sql.planner.TypeProvider;
import io.prestosql.sql.planner.assertions.BasePlanTest;
import io.prestosql.sql.planner.assertions.PlanAssert;
import io.prestosql.sql.planner.assertions.PlanMatchPattern;
import io.prestosql.sql.planner.iterative.rule.RemoveUnsupportedDynamicFilters;
import io.prestosql.sql.planner.iterative.rule.test.PlanBuilder;
import io.prestosql.sql.planner.plan.JoinNode;
import io.prestosql.sql.planner.plan.PlanNode;
import io.prestosql.sql.planner.plan.TableScanNode;
import io.prestosql.sql.planner.sanity.DynamicFiltersChecker;
import io.prestosql.testing.TestingTransactionHandle;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Optional;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.sql.DynamicFilters.createDynamicFilterExpression;
import static io.prestosql.sql.ExpressionUtils.combineConjuncts;
import static io.prestosql.sql.ExpressionUtils.combineDisjuncts;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.equiJoinClause;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.filter;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.join;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.output;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.tableScan;
import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER;
public class TestRemoveUnsupportedDynamicFilters
extends BasePlanTest
{
private Metadata metadata;
private PlanBuilder builder;
private Symbol lineitemOrderKeySymbol;
private TableScanNode lineitemTableScanNode;
private Symbol ordersOrderKeySymbol;
private TableScanNode ordersTableScanNode;
@BeforeClass
public void setup()
{
metadata = getQueryRunner().getMetadata();
builder = new PlanBuilder(new PlanNodeIdAllocator(), metadata);
CatalogName catalogName = getCurrentConnectorId();
TableHandle lineitemTableHandle = new TableHandle(
catalogName,
new TpchTableHandle("lineitem", 1.0),
TestingTransactionHandle.create(),
Optional.empty());
lineitemOrderKeySymbol = builder.symbol("LINEITEM_OK", BIGINT);
lineitemTableScanNode = builder.tableScan(lineitemTableHandle, ImmutableList.of(lineitemOrderKeySymbol), ImmutableMap.of(lineitemOrderKeySymbol, new TpchColumnHandle("orderkey", BIGINT)));
TableHandle ordersTableHandle = new TableHandle(
catalogName,
new TpchTableHandle("orders", 1.0),
TestingTransactionHandle.create(),
Optional.empty());
ordersOrderKeySymbol = builder.symbol("ORDERS_OK", BIGINT);
ordersTableScanNode = builder.tableScan(ordersTableHandle, ImmutableList.of(ordersOrderKeySymbol), ImmutableMap.of(ordersOrderKeySymbol, new TpchColumnHandle("orderkey", BIGINT)));
}
@Test
public void testUnconsumedDynamicFilterInJoin()
{
PlanNode root = builder.join(
INNER,
builder.filter(PlanBuilder.expression("ORDERS_OK > 0"), ordersTableScanNode),
lineitemTableScanNode,
ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
ImmutableList.of(ordersOrderKeySymbol),
Optional.empty(),
Optional.empty(),
Optional.empty(),
ImmutableMap.of("DF", lineitemOrderKeySymbol));
assertPlan(
removeUnsupportedDynamicFilters(root),
join(INNER,
ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")),
filter("ORDERS_OK > 0",
tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))),
tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))));
}
@Test
public void testDynamicFilterConsumedOnBuildSide()
{
PlanNode root = builder.join(
INNER,
builder.filter(
createDynamicFilterExpression(metadata, "DF", BIGINT, ordersOrderKeySymbol.toSymbolReference()),
ordersTableScanNode),
builder.filter(
createDynamicFilterExpression(metadata, "DF", BIGINT, ordersOrderKeySymbol.toSymbolReference()),
lineitemTableScanNode),
ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
ImmutableList.of(ordersOrderKeySymbol),
Optional.empty(),
Optional.empty(),
Optional.empty(),
ImmutableMap.of("DF", lineitemOrderKeySymbol));
assertPlan(
removeUnsupportedDynamicFilters(root),
join(INNER,
ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")),
filter(createDynamicFilterExpression(metadata, "DF", BIGINT, ordersOrderKeySymbol.toSymbolReference()),
tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))),
tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))));
}
@Test
public void testUnmatchedDynamicFilter()
{
PlanNode root = builder.output(
ImmutableList.of(),
ImmutableList.of(),
builder.join(
INNER,
ordersTableScanNode,
builder.filter(
combineConjuncts(
metadata,
PlanBuilder.expression("LINEITEM_OK > 0"),
createDynamicFilterExpression(metadata, "DF", BIGINT, lineitemOrderKeySymbol.toSymbolReference())),
lineitemTableScanNode),
ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
ImmutableList.of(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
ImmutableMap.of()));
assertPlan(
removeUnsupportedDynamicFilters(root),
output(
join(INNER,
ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")),
tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")),
filter("LINEITEM_OK > 0",
tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))))));
}
@Test
public void testNestedDynamicFilterDisjunctionRewrite()
{
PlanNode root = builder.output(
ImmutableList.of(),
ImmutableList.of(),
builder.join(
INNER,
ordersTableScanNode,
builder.filter(
combineConjuncts(
metadata,
combineDisjuncts(
metadata,
PlanBuilder.expression("LINEITEM_OK IS NULL"),
createDynamicFilterExpression(metadata, "DF", BIGINT, lineitemOrderKeySymbol.toSymbolReference())),
combineDisjuncts(
metadata,
PlanBuilder.expression("LINEITEM_OK IS NOT NULL"),
createDynamicFilterExpression(metadata, "DF", BIGINT, lineitemOrderKeySymbol.toSymbolReference()))),
lineitemTableScanNode),
ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
ImmutableList.of(ordersOrderKeySymbol),
Optional.empty(),
Optional.empty(),
Optional.empty(),
ImmutableMap.of()));
assertPlan(
removeUnsupportedDynamicFilters(root),
output(
join(INNER,
ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")),
tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")),
tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))));
}
@Test
public void testNestedDynamicFilterConjunctionRewrite()
{
PlanNode root = builder.output(ImmutableList.of(), ImmutableList.of(),
builder.join(
INNER,
ordersTableScanNode,
builder.filter(
combineDisjuncts(
metadata,
combineConjuncts(
metadata,
PlanBuilder.expression("LINEITEM_OK IS NULL"),
createDynamicFilterExpression(metadata, "DF", BIGINT, lineitemOrderKeySymbol.toSymbolReference())),
combineConjuncts(
metadata,
PlanBuilder.expression("LINEITEM_OK IS NOT NULL"),
createDynamicFilterExpression(metadata, "DF", BIGINT, lineitemOrderKeySymbol.toSymbolReference()))),
lineitemTableScanNode),
ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
ImmutableList.of(ordersOrderKeySymbol),
Optional.empty(),
Optional.empty(),
Optional.empty(),
ImmutableMap.of()));
assertPlan(
removeUnsupportedDynamicFilters(root),
output(
join(INNER,
ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")),
tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")),
filter(
combineDisjuncts(
metadata,
PlanBuilder.expression("LINEITEM_OK IS NULL"),
PlanBuilder.expression("LINEITEM_OK IS NOT NULL")),
tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))))));
}
PlanNode removeUnsupportedDynamicFilters(PlanNode root)
{
return getQueryRunner().inTransaction(session -> {
// metadata.getCatalogHandle() registers the catalog for the transaction
session.getCatalog().ifPresent(catalog -> metadata.getCatalogHandle(session, catalog));
PlanNode rewrittenPlan = new RemoveUnsupportedDynamicFilters(metadata).optimize(root, session, TypeProvider.empty(), new SymbolAllocator(), new PlanNodeIdAllocator(), WarningCollector.NOOP);
new DynamicFiltersChecker().validate(rewrittenPlan, session, metadata, new TypeAnalyzer(new SqlParser(), metadata), TypeProvider.empty(), WarningCollector.NOOP);
return rewrittenPlan;
});
}
protected void assertPlan(PlanNode actual, PlanMatchPattern pattern)
{
getQueryRunner().inTransaction(session -> {
// metadata.getCatalogHandle() registers the catalog for the transaction
session.getCatalog().ifPresent(catalog -> metadata.getCatalogHandle(session, catalog));
PlanAssert.assertPlan(session, metadata, getQueryRunner().getStatsCalculator(), new Plan(actual, builder.getTypes(), StatsAndCosts.empty()), pattern);
return null;
});
}
}
|
//: initialization/ArraysOfPrimitives.java
import static net.mindview.util.Print.*;
public class ArraysOfPrimitives {
public static void main(String[] args) {
int[] a1 = { 1, 2, 3, 4, 5 };
int[] a2;
a2 = a1;
for(int i = 0; i < a2.length; i++)
a2[i] = a2[i] + 1;
for(int i = 0; i < a1.length; i++)
print("a1[" + i + "] = " + a1[i]);
}
} /* Output:
a1[0] = 2
a1[1] = 3
a1[2] = 4
a1[3] = 5
a1[4] = 6
*///:~
|
/*
* Copyright 2014 Gurtam
*
* 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.sdk.wialon.item;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sdk.wialon.core.Session;
import com.sdk.wialon.item.prop.ItemProperties;
import com.sdk.wialon.remote.RemoteHttpClient;
import com.sdk.wialon.remote.handlers.ResponseHandler;
import java.util.Map;
public class User extends Item {
private Long fl;
private String hm;
private Map<String, String> mapps;
private ItemProperties mobileAppsPlugin;
public ItemProperties getMobileAppsPlugin(){
return mobileAppsPlugin ==null ? mobileAppsPlugin =new ItemProperties(mapps, "mapps", this, events.changeMobileApps, "user/update_mobile_app") : mobileAppsPlugin;
}
public User () {
itemType=ItemType.user;
}
/**
* User flags
* @return get user flags
*/
public Long getUserFlags() {
return fl;
}
/**
* Hosts mask, restrict list of IP addresses from which user can access Wialon, wildcards supported
* @return host mask
*/
public String getHostsMask() {
return hm;
}
/**
* Get ACL for this users over all items
* @param directAccess return only items with direct access for this user
* @param itemSuperclass item superclass
* @param callback callback that will receive information about user ACL
* result is object {itemId1: accessMask, itemId2: accessMask, ...}
*/
public void getItemsAccess( boolean directAccess, ItemType itemSuperclass, ResponseHandler callback) {
RemoteHttpClient.getInstance().remoteCall(
"user/get_items_access",
"{\"userId\":"+getId()+",\"itemSuperclass\":\""+itemSuperclass+"\",\"directAccess\":"+(directAccess ? 1 : 0)+"}",
callback);
}
/**
* Update this user access to some other, require ACL bit Item.accessFlag.setItemsAccess over user and Item.accessFlag.setAcl over item
* @param item item which access need to be updated
* @param accessMask new item ACL
* @param callback callback that will receive information about access update: callback(code), zero code is success
*/
public void updateItemAccess(Item item, long accessMask, ResponseHandler callback) {
RemoteHttpClient.getInstance().remoteCall(
"user/update_item_access",
"{\"userId\":"+getId()+",\"itemId\":"+item.getId()+",\"accessMask\":"+accessMask+"}",
callback);
}
/**
* Update this user flags, require ACL bit User.accessFlag.editUserFlags over user
* @param flags flags which to set, see User.userFlag for possible values
* canSendSMS and canCreateItems flags require all creators of this user to have them enabled
* @param flagsMask mask of which flags to set to ON/OFF. If mask contain invalid bits, request would be denied
* @param callback callback that will receive information about flags update
*/
public void updateUserFlags(long flags, long flagsMask, ResponseHandler callback) {
RemoteHttpClient.getInstance().remoteCall(
"user/update_user_flags",
"{\"userId\":"+getId()+",\"flags\":"+flags+",\"flagsMask\":"+flagsMask+"}",
getOnUpdatePropertiesCallback(callback));
}
/**
* Update hosts mask, from which user can access Wialon, require ACL bit User.accessFlag.editUserFlags over user
* @param hostsMask new wildcard-base hosts mask, use empty value to disable this restriction
* @param callback callback that will receive information about hosts mask update
*/
public void updateHostsMask(String hostsMask, ResponseHandler callback) {
JsonObject params=new JsonObject();
params.addProperty("userId", getId());
params.addProperty("hostsMask", hostsMask);
RemoteHttpClient.getInstance().remoteCall(
"user/update_hosts_mask",
params,
getOnUpdatePropertiesCallback(callback));
}
/**
* Get localization settings, remote call, require ACL bit wialon.item.Item.accessFlags.viewProperties over item
* @param callback callback that get result of server operation in form callback(code, result), where result represents JSON data for localization settings
*/
public void getLocale(ResponseHandler callback) {
RemoteHttpClient.getInstance().remoteCall(
"user/get_locale",
"{\"userId\":"+getId()+"}",
callback
);
}
/** Update this user localization settings
* @param locale localization parameters, format: {fd: text, wd: ubyte}
* @param callback callback that will receive information about localization update
*/
public void updateLocale(String locale, ResponseHandler callback) {
JsonObject params=new JsonObject();
params.addProperty("userId", getId());
params.add("locale", Session.getInstance().getJsonParser().parse(locale));
RemoteHttpClient.getInstance().remoteCall(
"user/update_locale",
params,
callback);
}
/**
* Update password require ACL bit User.accessFlag.operateAs over user and correct oldPassword OR
* User.accessFlag.editUserFlags and empty oldPassword
* @param oldPassword old password if only User.accessFlag.operateAs acl bit available
* @param newPassword new password
* @param callback callback that will receive information about password update
*/
public void updatePassword(String oldPassword, String newPassword, ResponseHandler callback) {
JsonObject params=new JsonObject();
params.addProperty("userId", getId());
params.addProperty("oldPassword", oldPassword);
params.addProperty("newPassword", newPassword);
RemoteHttpClient.getInstance().remoteCall(
"user/update_password",
params,
callback);
}
@Override
public boolean updateItemData(String key, JsonElement data) {
if (super.updateItemData(key, data))
return true;
else {
if (key.equals("hm")&& data.getAsString()!=null) {
setHostsMask(data.getAsString());
} else if (key.equals("fl") && data.getAsNumber()!=null) {
setUserFlags(data.getAsLong());
} else
return false;
return true;
}
}
private void setUserFlags(Long userFlags) {
if (this.fl==null || !this.fl.equals(userFlags)) {
Long oldFlags=this.fl==null ? null : new Long(this.fl);
this.fl = userFlags;
fireEvent(events.changeUserFlags, this, oldFlags, userFlags);
}
}
public void setHostsMask(String hostsMask) {
if (this.hm==null || !this.hm.equals(hostsMask)) {
String oldMask=this.hm==null ? null :new String(hostsMask);
this.hm = hostsMask;
fireEvent(events.changeHostsMask, this, oldMask, hostsMask);
}
}
/** Data flags constants */
public static enum dataFlag{
/** User flags */
flags(0x00000100),
/** User notifications plugin */
notifications(0x00000200),
/** User connectivity settings, e.g. hosts mask*/
connSettings(0x00000400),
/** User mobile apps */
mobileApps(0x00000800);
/** Flag value */
private long value;
private dataFlag (long value) {
this.value=value;
}
public long getValue() {
return value;
}
}
/** ACL flags constants */
public static enum accessFlag{
/** change users's ACL: provide to given user access to other items */
setItemsAccess(0x100000),
/** act as given user: create items, login as it, etc */
operateAs(0x200000),
/** change various flags for given user */
editUserFlags(0x400000);
/** Flag value */
private long value;
private accessFlag (long value) {
this.value=value;
}
public long getValue() {
return value;
}
}
/**
* Fetch default current user flags
* @return default user data flags
*/
public static long defaultDataFlags() {
return Item.dataFlag.base.getValue() | Item.dataFlag.customProps.getValue() | Item.dataFlag.billingProps.getValue() |
User.dataFlag.flags.getValue();
}
/** User flags constants */
public static enum userFlag{
/** User is disabled */
isDisabled(0x00000001),
/** User can not change its password */
cantChangePassword(0x00000002),
/** User can create items */
canCreateItems(0x00000004),
/** User can't change own settings */
isReadonly(0x00000010),
/** User can send SMS messages */
canSendSMS(0x00000020);
/** Flag value */
private long value;
private userFlag (long value) {
this.value=value;
}
public long getValue() {
return value;
}
}
/** Log message action constants */
/** Also user log will contain messages for all other items which user affected. */
/** Such actions starts with "user_" and looks like "user_update_name" or "user_create_poi". */
public static enum logMessageAction{
/** User specific actions */
/** User created */
userCreated("create_user"),
/** User hosts mask updated */
userUpdatedHostsMask("update_hosts_mask"),
/** User password updated */
userUpdatedPassword("update_user_pass"),
/** User flags updated */
userUpdatedFlags("update_user_flags"),
/** User notification created */
userCreatedNotification("create_user_notify"),
/** User notification deleted */
userDeletedNotification("delete_user_notify");
/** Flag value */
private String value;
private logMessageAction (String value) {
this.value=value;
}
public String getValue() {
return value;
}
}
public static enum events {
/** userFlags property has changed */
changeUserFlags,
/** hostsMask property has changed */
changeHostsMask,
/** mobile apps has changed */
changeMobileApps
}
}
|
package tachyon.master;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Throwables;
import tachyon.Constants;
import tachyon.HeartbeatThread;
import tachyon.LeaderInquireClient;
import tachyon.TachyonURI;
import tachyon.Version;
import tachyon.conf.CommonConf;
import tachyon.conf.UserConf;
import tachyon.thrift.BlockInfoException;
import tachyon.thrift.ClientBlockInfo;
import tachyon.thrift.ClientDependencyInfo;
import tachyon.thrift.ClientFileInfo;
import tachyon.thrift.ClientRawTableInfo;
import tachyon.thrift.ClientWorkerInfo;
import tachyon.thrift.Command;
import tachyon.thrift.DependencyDoesNotExistException;
import tachyon.thrift.FileAlreadyExistException;
import tachyon.thrift.FileDoesNotExistException;
import tachyon.thrift.InvalidPathException;
import tachyon.thrift.MasterService;
import tachyon.thrift.NetAddress;
import tachyon.thrift.NoWorkerException;
import tachyon.thrift.SuspectedFileSizeException;
import tachyon.thrift.TableColumnException;
import tachyon.thrift.TableDoesNotExistException;
import tachyon.thrift.TachyonException;
import tachyon.util.CommonUtils;
import tachyon.util.NetworkUtils;
/**
* The master server client side.
*
* Since MasterService.Client is not thread safe, this class has to guarantee thread safe.
*/
public class MasterClient implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private static final int MAX_CONNECT_TRY = 5;
private boolean mUseZookeeper;
private MasterService.Client mClient = null;
private InetSocketAddress mMasterAddress = null;
private TProtocol mProtocol = null;
private volatile boolean mConnected;
private volatile boolean mIsShutdown;
private volatile long mLastAccessedMs;
private volatile long mUserId = -1;
private HeartbeatThread mHeartbeatThread = null;
public MasterClient(InetSocketAddress masterAddress) {
this(masterAddress, CommonConf.get().USE_ZOOKEEPER);
}
public MasterClient(InetSocketAddress masterAddress, boolean useZookeeper) {
mUseZookeeper = useZookeeper;
if (!mUseZookeeper) {
mMasterAddress = masterAddress;
}
mConnected = false;
mIsShutdown = false;
}
/**
* @param workerId if -1, means the checkpoint is added directly by the client from underlayer fs.
* @param fileId
* @param length
* @param checkpointPath
* @return true if checkpoint is added for the <code>fileId</code> and false otherwise
* @throws FileDoesNotExistException
* @throws SuspectedFileSizeException
* @throws BlockInfoException
*/
public synchronized boolean addCheckpoint(long workerId, int fileId, long length,
String checkpointPath) throws FileDoesNotExistException, SuspectedFileSizeException,
BlockInfoException, IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.addCheckpoint(workerId, fileId, length, checkpointPath);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return false;
}
/**
* Clean the connect. E.g. if the client has not connect the master for a while, the connection
* should be shut down.
*/
@Override
public synchronized void close() {
if (mConnected) {
LOG.debug("Disconnecting from the master {}", mMasterAddress);
mConnected = false;
}
if (mProtocol != null) {
mProtocol.getTransport().close();
}
if (mHeartbeatThread != null) {
mHeartbeatThread.shutdown();
}
}
/**
* Connects to the Tachyon Master; an exception is thrown if this fails.
*/
public synchronized void connect() throws IOException {
mLastAccessedMs = System.currentTimeMillis();
if (mConnected) {
return;
}
close();
if (mIsShutdown) {
throw new IOException("Client is shutdown, will not try to connect");
}
int tries = 0;
Exception lastException = null;
while (tries ++ < MAX_CONNECT_TRY && !mIsShutdown) {
mMasterAddress = getMasterAddress();
LOG.info("Tachyon client (version " + Version.VERSION + ") is trying to connect master @ "
+ mMasterAddress);
mProtocol =
new TBinaryProtocol(new TFramedTransport(new TSocket(
NetworkUtils.getFqdnHost(mMasterAddress), mMasterAddress.getPort())));
mClient = new MasterService.Client(mProtocol);
mLastAccessedMs = System.currentTimeMillis();
try {
mProtocol.getTransport().open();
mHeartbeatThread =
new HeartbeatThread("Master_Client Heartbeat", new MasterClientHeartbeatExecutor(this,
UserConf.get().MASTER_CLIENT_TIMEOUT_MS),
UserConf.get().MASTER_CLIENT_TIMEOUT_MS / 2);
mHeartbeatThread.start();
} catch (TTransportException e) {
lastException = e;
LOG.error("Failed to connect (" + tries + ") to master " + mMasterAddress + " : "
+ e.getMessage());
if (mHeartbeatThread != null) {
mHeartbeatThread.shutdown();
}
CommonUtils.sleepMs(LOG, Constants.SECOND_MS);
continue;
}
try {
mUserId = mClient.user_getUserId();
} catch (TException e) {
lastException = e;
LOG.error(e.getMessage(), e);
continue;
}
LOG.info("User registered at the master " + mMasterAddress + " got UserId " + mUserId);
mConnected = true;
return;
}
// Reaching here indicates that we did not successfully connect.
throw new IOException("Failed to connect to master " + mMasterAddress + " after " + (tries - 1)
+ " attempts", lastException);
}
public synchronized ClientDependencyInfo getClientDependencyInfo(int did) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_getClientDependencyInfo(did);
} catch (DependencyDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized ClientFileInfo getFileStatus(int fileId, String path) throws IOException {
if (path == null) {
path = "";
}
if (fileId == -1 && !path.startsWith(TachyonURI.SEPARATOR)) {
throw new IOException("Illegal path parameter: " + path);
}
while (!mIsShutdown) {
connect();
try {
return mClient.getFileStatus(fileId, path);
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
synchronized long getLastAccessedMs() {
return mLastAccessedMs;
}
private synchronized InetSocketAddress getMasterAddress() {
if (!mUseZookeeper) {
return mMasterAddress;
}
LeaderInquireClient leaderInquireClient =
LeaderInquireClient.getClient(CommonConf.get().ZOOKEEPER_ADDRESS,
CommonConf.get().ZOOKEEPER_LEADER_PATH);
try {
String temp = leaderInquireClient.getMasterAddress();
return CommonUtils.parseInetSocketAddress(temp);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
public synchronized long getUserId() throws IOException {
while (!mIsShutdown) {
connect();
return mUserId;
}
return -1;
}
public synchronized List<ClientWorkerInfo> getWorkersInfo() throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.getWorkersInfo();
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized boolean isConnected() {
return mConnected;
}
public synchronized List<ClientFileInfo> listStatus(String path) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.liststatus(path);
} catch (InvalidPathException e) {
throw new IOException(e);
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
private synchronized void parameterCheck(int id, String path) throws IOException {
if (path == null) {
throw new IOException("Illegal path parameter: " + path + " ; Please use an empty string.");
}
if (id == -1 && (path == null || !path.startsWith(TachyonURI.SEPARATOR))) {
throw new IOException("Illegal path parameter: " + path);
}
}
/**
* TODO Consolidate this with close()
*/
public synchronized void shutdown() {
mIsShutdown = true;
if (mProtocol != null) {
mProtocol.getTransport().close();
}
close();
}
public synchronized void user_completeFile(int fId) throws IOException {
while (!mIsShutdown) {
connect();
try {
mClient.user_completeFile(fId);
return;
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
}
public synchronized int user_createDependency(List<String> parents, List<String> children,
String commandPrefix, List<ByteBuffer> data, String comment, String framework,
String frameworkVersion, int dependencyType, long childrenBlockSizeByte) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_createDependency(parents, children, commandPrefix, data, comment,
framework, frameworkVersion, dependencyType, childrenBlockSizeByte);
} catch (InvalidPathException e) {
throw new IOException(e);
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (FileAlreadyExistException e) {
throw new IOException(e);
} catch (BlockInfoException e) {
throw new IOException(e);
} catch (TachyonException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return -1;
}
public synchronized int user_createFile(String path, String ufsPath, long blockSizeByte,
boolean recursive) throws IOException {
if (path == null || !path.startsWith(TachyonURI.SEPARATOR)) {
throw new IOException("Illegal path parameter: " + path);
}
if (ufsPath == null) {
ufsPath = "";
}
while (!mIsShutdown) {
connect();
try {
return mClient.user_createFile(path, ufsPath, blockSizeByte, recursive);
} catch (FileAlreadyExistException e) {
throw new IOException(e);
} catch (InvalidPathException e) {
throw new IOException(e);
} catch (BlockInfoException e) {
throw new IOException(e);
} catch (TachyonException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return -1;
}
public synchronized long user_createNewBlock(int fId) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_createNewBlock(fId);
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return -1;
}
public synchronized int user_createRawTable(String path, int columns, ByteBuffer metadata)
throws IOException {
if (metadata == null) {
metadata = ByteBuffer.allocate(0);
}
while (!mIsShutdown) {
connect();
try {
return mClient.user_createRawTable(path, columns, metadata);
} catch (FileAlreadyExistException e) {
throw new IOException(e);
} catch (InvalidPathException e) {
throw new IOException(e);
} catch (TableColumnException e) {
throw new IOException(e);
} catch (TachyonException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return -1;
}
public synchronized boolean user_delete(int fileId, String path, boolean recursive)
throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_delete(fileId, path, recursive);
} catch (TachyonException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return false;
}
public synchronized long user_getBlockId(int fId, int index) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_getBlockId(fId, index);
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return -1;
}
public synchronized ClientBlockInfo user_getClientBlockInfo(long blockId) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_getClientBlockInfo(blockId);
} catch (FileDoesNotExistException e) {
throw new FileNotFoundException(e.getMessage());
} catch (BlockInfoException e) {
throw new IOException(e.getMessage(), e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized ClientRawTableInfo user_getClientRawTableInfo(int id, String path)
throws IOException {
parameterCheck(id, path);
while (!mIsShutdown) {
connect();
try {
ClientRawTableInfo ret = mClient.user_getClientRawTableInfo(id, path);
ret.setMetadata(CommonUtils.generateNewByteBufferFromThriftRPCResults(ret.metadata));
return ret;
} catch (TableDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized List<ClientBlockInfo> user_getFileBlocks(int fileId, String path)
throws IOException {
parameterCheck(fileId, path);
while (!mIsShutdown) {
connect();
try {
return mClient.user_getFileBlocks(fileId, path);
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized int user_getRawTableId(String path) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_getRawTableId(path);
} catch (InvalidPathException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return -1;
}
public synchronized String user_getUfsAddress() throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_getUfsAddress();
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized NetAddress user_getWorker(boolean random, String hostname)
throws NoWorkerException, IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_getWorker(random, hostname);
} catch (NoWorkerException e) {
throw e;
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized boolean user_mkdirs(String path, boolean recursive) throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.user_mkdirs(path, recursive);
} catch (FileAlreadyExistException e) {
throw new IOException(e);
} catch (InvalidPathException e) {
throw new IOException(e);
} catch (TachyonException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return false;
}
public synchronized boolean user_rename(int fileId, String srcPath, String dstPath)
throws IOException {
parameterCheck(fileId, srcPath);
while (!mIsShutdown) {
connect();
try {
return mClient.user_rename(fileId, srcPath, dstPath);
} catch (FileAlreadyExistException e) {
throw new IOException(e);
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (InvalidPathException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return false;
}
public synchronized void user_reportLostFile(int fileId) throws IOException {
while (!mIsShutdown) {
connect();
try {
mClient.user_reportLostFile(fileId);
return;
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
}
public synchronized void user_requestFilesInDependency(int depId) throws IOException {
while (!mIsShutdown) {
connect();
try {
mClient.user_requestFilesInDependency(depId);
return;
} catch (DependencyDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
}
public synchronized void user_setPinned(int id, boolean pinned) throws IOException {
while (!mIsShutdown) {
connect();
try {
mClient.user_setPinned(id, pinned);
return;
} catch (FileDoesNotExistException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
}
public synchronized void user_updateRawTableMetadata(int id, ByteBuffer metadata)
throws IOException {
while (!mIsShutdown) {
connect();
try {
mClient.user_updateRawTableMetadata(id, metadata);
return;
} catch (TableDoesNotExistException e) {
throw new IOException(e);
} catch (TachyonException e) {
throw new IOException(e);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
}
public synchronized void worker_cacheBlock(long workerId, long workerUsedBytes, long blockId,
long length) throws IOException, FileDoesNotExistException, SuspectedFileSizeException,
BlockInfoException {
while (!mIsShutdown) {
connect();
try {
mClient.worker_cacheBlock(workerId, workerUsedBytes, blockId, length);
return;
} catch (FileDoesNotExistException e) {
throw e;
} catch (SuspectedFileSizeException e) {
throw e;
} catch (BlockInfoException e) {
throw e;
} catch (TTransportException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
} catch (TException e) {
throw new IOException(e);
}
}
}
public synchronized Set<Integer> worker_getPinIdList() throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.worker_getPinIdList();
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
public synchronized List<Integer> worker_getPriorityDependencyList() throws IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.worker_getPriorityDependencyList();
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return new ArrayList<Integer>();
}
public synchronized Command worker_heartbeat(long workerId, long usedBytes,
List<Long> removedPartitionList) throws BlockInfoException, IOException {
while (!mIsShutdown) {
connect();
try {
return mClient.worker_heartbeat(workerId, usedBytes, removedPartitionList);
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return null;
}
/**
* Register the worker to the master.
*
* @param workerNetAddress Worker's NetAddress
* @param totalBytes Worker's capacity
* @param usedBytes Worker's used storage
* @param currentBlockList Blocks in worker's space.
* @return the worker id assigned by the master.
* @throws BlockInfoException
* @throws TException
*/
public synchronized long worker_register(NetAddress workerNetAddress, long totalBytes,
long usedBytes, List<Long> currentBlockList) throws BlockInfoException, IOException {
while (!mIsShutdown) {
connect();
try {
long ret =
mClient.worker_register(workerNetAddress, totalBytes, usedBytes, currentBlockList);
LOG.info("Registered at the master " + mMasterAddress + " from worker " + workerNetAddress
+ " , got WorkerId " + ret);
return ret;
} catch (TException e) {
LOG.error(e.getMessage(), e);
mConnected = false;
}
}
return -1;
}
}
|
/*
* 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 upatras.simulationmodels.devices;
import upatras.electricaldevicesimulation.simulationcore.enviromentbase.PowerEnviroment;
import upatras.utilitylibrary.library.measurements.units.electrical.ComplexPower;
/**
*
* @author Paris
*/
public class CoalPowerPlant extends PowerPlant {
public CoalPowerPlant(ComplexPower initial_power, ComplexPower max_power, PowerEnviroment enviroment) {
super(initial_power, max_power, max_power.dividedBy(250.0 * 60 * 1000, 250.0 * 60 * 1000), enviroment);
}
}
|
package com.huantansheng.easyphotos.utils.Color;
/**
* Created by huan on 2018/1/9.
*/
public class ColorUtils {
/**
* 判断颜色是否偏黑色
*
* @param color 颜色
* @return
*/
public static boolean isBlackColor(int color) {
int grey = toGrey(color);
return grey < 50;
}
/**
* 颜色转换成灰度值
*
* @param rgb 颜色
* @return 灰度值
*/
public static int toGrey(int rgb) {
int blue = rgb & 0x000000FF;
int green = (rgb & 0x0000FF00) >> 8;
int red = (rgb & 0x00FF0000) >> 16;
return (red * 38 + green * 75 + blue * 15) >> 7;
}
public static boolean isWhiteColor(int color) {
int grey = toGrey(color);
return grey > 200;
}
}
|
package org.schema.api.model.thing.creativeWork.article.socialMediaPosting;
import org.schema.api.model.thing.creativeWork.article.socialMediaPosting.SocialMediaPosting;
import org.schema.api.model.thing.creativeWork.CreativeWork;
public class DiscussionForumPosting extends SocialMediaPosting
{
private CreativeWork sharedContent;
public CreativeWork getSharedContent()
{
return sharedContent;
}
public void setSharedContent(CreativeWork sharedContent)
{
this.sharedContent = sharedContent;
}
}
|
// This Java source file was generated on 2020-09-09 10:37:57 (Malay Peninsula Standard Time)
package io.tealight.api.oanda.v20.def.transaction;
import io.tealight.api.oanda.v20.def.order.OrderPositionFill;
import io.tealight.api.oanda.v20.def.order.OrderTriggerCondition;
import io.tealight.api.oanda.v20.def.order.TimeInForce;
import java.time.ZonedDateTime;
public class MarketIfTouchedOrderRejectTransaction extends Transaction {
private TransactionType type = TransactionType.MARKET_IF_TOUCHED_ORDER_REJECT;
private String instrument;
private Double units;
private Double price;
private Double priceBound;
private TimeInForce timeInForce = TimeInForce.GTC;
private ZonedDateTime gtdTime;
private OrderPositionFill positionFill = OrderPositionFill.DEFAULT;
private OrderTriggerCondition triggerCondition = OrderTriggerCondition.DEFAULT;
private MarketIfTouchedOrderReason reason;
private ClientExtensions clientExtensions;
private TakeProfitDetails takeProfitOnFill;
private StopLossDetails stopLossOnFill;
private TrailingStopLossDetails trailingStopLossOnFill;
private GuaranteedStopLossDetails guaranteedStopLossOnFill;
private ClientExtensions tradeClientExtensions;
private String intendedReplacesOrderID;
private TransactionRejectReason rejectReason;
public TransactionType getType() {
return type;
}
public void setType(TransactionType type) {
this.type = type;
}
public String getInstrument() {
return instrument;
}
public void setInstrument(String instrument) {
this.instrument = instrument;
}
public Double getUnits() {
return units;
}
public void setUnits(Double units) {
this.units = units;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Double getPriceBound() {
return priceBound;
}
public void setPriceBound(Double priceBound) {
this.priceBound = priceBound;
}
public TimeInForce getTimeInForce() {
return timeInForce;
}
public void setTimeInForce(TimeInForce timeInForce) {
this.timeInForce = timeInForce;
}
public ZonedDateTime getGtdTime() {
return gtdTime;
}
public void setGtdTime(ZonedDateTime gtdTime) {
this.gtdTime = gtdTime;
}
public OrderPositionFill getPositionFill() {
return positionFill;
}
public void setPositionFill(OrderPositionFill positionFill) {
this.positionFill = positionFill;
}
public OrderTriggerCondition getTriggerCondition() {
return triggerCondition;
}
public void setTriggerCondition(OrderTriggerCondition triggerCondition) {
this.triggerCondition = triggerCondition;
}
public MarketIfTouchedOrderReason getReason() {
return reason;
}
public void setReason(MarketIfTouchedOrderReason reason) {
this.reason = reason;
}
public ClientExtensions getClientExtensions() {
return clientExtensions;
}
public void setClientExtensions(ClientExtensions clientExtensions) {
this.clientExtensions = clientExtensions;
}
public TakeProfitDetails getTakeProfitOnFill() {
return takeProfitOnFill;
}
public void setTakeProfitOnFill(TakeProfitDetails takeProfitOnFill) {
this.takeProfitOnFill = takeProfitOnFill;
}
public StopLossDetails getStopLossOnFill() {
return stopLossOnFill;
}
public void setStopLossOnFill(StopLossDetails stopLossOnFill) {
this.stopLossOnFill = stopLossOnFill;
}
public TrailingStopLossDetails getTrailingStopLossOnFill() {
return trailingStopLossOnFill;
}
public void setTrailingStopLossOnFill(TrailingStopLossDetails trailingStopLossOnFill) {
this.trailingStopLossOnFill = trailingStopLossOnFill;
}
public GuaranteedStopLossDetails getGuaranteedStopLossOnFill() {
return guaranteedStopLossOnFill;
}
public void setGuaranteedStopLossOnFill(GuaranteedStopLossDetails guaranteedStopLossOnFill) {
this.guaranteedStopLossOnFill = guaranteedStopLossOnFill;
}
public ClientExtensions getTradeClientExtensions() {
return tradeClientExtensions;
}
public void setTradeClientExtensions(ClientExtensions tradeClientExtensions) {
this.tradeClientExtensions = tradeClientExtensions;
}
public String getIntendedReplacesOrderID() {
return intendedReplacesOrderID;
}
public void setIntendedReplacesOrderID(String intendedReplacesOrderID) {
this.intendedReplacesOrderID = intendedReplacesOrderID;
}
public TransactionRejectReason getRejectReason() {
return rejectReason;
}
public void setRejectReason(TransactionRejectReason rejectReason) {
this.rejectReason = rejectReason;
}
}
|
// let's make nice and clear,
// proper seekbar preference.
package com.lenovo.parts;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.res.TypedArrayUtils;
import androidx.preference.*;
public class ProperSeekBarPreference extends Preference implements SeekBar.OnSeekBarChangeListener,
View.OnClickListener, View.OnLongClickListener {
protected final String TAG = getClass().getName();
protected static final String ANDROIDNS = "http://schemas.android.com/apk/res/android";
protected int mInterval = 1;
protected boolean mShowSign = false;
protected String mUnits = "";
protected boolean mContinuousUpdates = false;
protected int mMinValue = 0;
protected int mMaxValue = 100;
protected boolean mDefaultValueExists = false;
protected int mDefaultValue;
protected int mValue;
protected TextView mValueTextView;
protected ImageView mResetImageView;
protected ImageView mMinusImageView;
protected ImageView mPlusImageView;
protected SeekBar mSeekBar;
protected boolean mTrackingTouch = false;
protected int mTrackingValue;
public ProperSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProperSeekBarPreference);
try {
mInterval = a.getInt(R.styleable.ProperSeekBarPreference_interval, mInterval);
mShowSign = a.getBoolean(R.styleable.ProperSeekBarPreference_showSign, mShowSign);
String units = a.getString(R.styleable.ProperSeekBarPreference_units);
if (units != null)
mUnits = units;
mContinuousUpdates = a.getBoolean(R.styleable.ProperSeekBarPreference_continuousUpdates, mContinuousUpdates);
} finally {
a.recycle();
}
mMinValue = attrs.getAttributeIntValue(ANDROIDNS, "min", mMinValue);
mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", mMaxValue);
if (mMaxValue < mMinValue)
mMaxValue = mMinValue;
String defaultValue = attrs.getAttributeValue(ANDROIDNS, "defaultValue");
mDefaultValueExists = defaultValue != null && !defaultValue.isEmpty();
if (mDefaultValueExists) {
mDefaultValue = getLimitedValue(Integer.parseInt(defaultValue));
mValue = mDefaultValue;
} else {
mValue = mMinValue;
}
setLayoutResource(R.layout.preference_proper_seekbar);
}
public ProperSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public ProperSeekBarPreference(Context context, AttributeSet attrs) {
this(context, attrs, TypedArrayUtils.getAttr(context,
androidx.preference.R.attr.preferenceStyle,
android.R.attr.preferenceStyle));
}
public ProperSeekBarPreference(Context context) {
this(context, null);
}
@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
mValueTextView = (TextView) holder.findViewById(R.id.value);
mResetImageView = (ImageView) holder.findViewById(R.id.reset);
mMinusImageView = (ImageView) holder.findViewById(R.id.minus);
mPlusImageView = (ImageView) holder.findViewById(R.id.plus);
mSeekBar = (SeekBar) holder.findViewById(R.id.seekbar);
mSeekBar.setMax(getSeekValue(mMaxValue));
mSeekBar.setProgress(getSeekValue(mValue));
updateValueViews();
mSeekBar.setOnSeekBarChangeListener(this);
mResetImageView.setOnClickListener(this);
mMinusImageView.setOnClickListener(this);
mPlusImageView.setOnClickListener(this);
mResetImageView.setOnLongClickListener(this);
mMinusImageView.setOnLongClickListener(this);
mPlusImageView.setOnLongClickListener(this);
}
protected int getLimitedValue(int v) {
return v < mMinValue ? mMinValue : (v > mMaxValue ? mMaxValue : v);
}
protected int getSeekValue(int v) {
return 0 - Math.floorDiv(mMinValue - v, mInterval);
}
protected String getTextValue(int v) {
return (mShowSign && v > 0 ? "+" : "") + String.valueOf(v) + mUnits;
}
protected void updateValueViews() {
mValueTextView.setText(getContext().getString(R.string.proper_seekbar_value,
(!mTrackingTouch || mContinuousUpdates ? getTextValue(mValue) + (mDefaultValueExists && mValue == mDefaultValue ? " (" + getContext().getString(R.string.proper_seekbar_default_value) + ")" : "")
: "[" + getTextValue(mTrackingValue) + "]")));
if (!mDefaultValueExists || mValue == mDefaultValue || mTrackingTouch)
mResetImageView.setVisibility(View.INVISIBLE);
else
mResetImageView.setVisibility(View.VISIBLE);
if (mValue == mMinValue || mTrackingTouch) {
mMinusImageView.setClickable(false);
mMinusImageView.setColorFilter(getContext().getColor(R.color.disabled_text_color), PorterDuff.Mode.MULTIPLY);
} else {
mMinusImageView.setClickable(true);
mMinusImageView.clearColorFilter();
}
if (mValue == mMaxValue || mTrackingTouch) {
mPlusImageView.setClickable(false);
mPlusImageView.setColorFilter(getContext().getColor(R.color.disabled_text_color), PorterDuff.Mode.MULTIPLY);
} else {
mPlusImageView.setClickable(true);
mPlusImageView.clearColorFilter();
}
}
protected void changeValue(int newValue) {
// for subclasses
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int newValue = getLimitedValue(mMinValue + (progress * mInterval));
if (mTrackingTouch && !mContinuousUpdates) {
mTrackingValue = newValue;
updateValueViews();
} else if (mValue != newValue) {
// change rejected, revert to the previous value
if (!callChangeListener(newValue)) {
mSeekBar.setProgress(getSeekValue(mValue));
return;
}
// change accepted, store it
changeValue(newValue);
persistInt(newValue);
mValue = newValue;
updateValueViews();
notifyChanged();
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
mTrackingValue = mValue;
mTrackingTouch = true;
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mTrackingTouch = false;
if (!mContinuousUpdates)
onProgressChanged(mSeekBar, getSeekValue(mTrackingValue), false);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.reset:
Toast.makeText(getContext(), getContext().getString(R.string.proper_seekbar_default_value_to_set, getTextValue(mDefaultValue)),
Toast.LENGTH_LONG).show();
break;
case R.id.minus:
setValue(mValue - mInterval, true);
break;
case R.id.plus:
setValue(mValue + mInterval, true);
break;
}
}
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.reset:
setValue(mDefaultValue, true);
//Toast.makeText(getContext(), getContext().getString(R.string.proper_seekbar_default_value_is_set),
// Toast.LENGTH_LONG).show();
break;
case R.id.minus:
setValue(mMaxValue - mMinValue > mInterval * 2 && mMaxValue + mMinValue < mValue * 2 ? Math.floorDiv(mMaxValue + mMinValue, 2) : mMinValue, true);
break;
case R.id.plus:
setValue(mMaxValue - mMinValue > mInterval * 2 && mMaxValue + mMinValue > mValue * 2 ? -1 * Math.floorDiv(-1 * (mMaxValue + mMinValue), 2) : mMaxValue, true);
break;
}
return true;
}
// dont need too much shit about initial and default values
// its all done in constructor already
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue)
mValue = getPersistedInt(mValue);
}
@Override
public void setDefaultValue(Object defaultValue) {
if (defaultValue instanceof Integer)
setDefaultValue((Integer) defaultValue, mSeekBar != null);
else
setDefaultValue(defaultValue == null ? (String) null : defaultValue.toString(), mSeekBar != null);
}
public void setDefaultValue(int newValue, boolean update) {
newValue = getLimitedValue(newValue);
if (!mDefaultValueExists || mDefaultValue != newValue) {
mDefaultValueExists = true;
mDefaultValue = newValue;
if (update)
updateValueViews();
}
}
public void setDefaultValue(String newValue, boolean update) {
if (mDefaultValueExists && (newValue == null || newValue.isEmpty())) {
mDefaultValueExists = false;
if (update)
updateValueViews();
} else if (newValue != null && !newValue.isEmpty()) {
setDefaultValue(Integer.parseInt(newValue), update);
}
}
public void setValue(int newValue, boolean update) {
newValue = getLimitedValue(newValue);
if (mValue != newValue) {
if (update)
mSeekBar.setProgress(getSeekValue(newValue));
else
mValue = newValue;
}
}
public int getValue() {
return mValue;
}
// need some methods here to set/get other attrs at runtime,
// but who really need this ...
public void refresh(int newValue) {
// this will ...
setValue(newValue, mSeekBar != null);
}
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package androidx.core;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f030027;
public static final int font = 0x7f0300e0;
public static final int fontProviderAuthority = 0x7f0300e2;
public static final int fontProviderCerts = 0x7f0300e3;
public static final int fontProviderFetchStrategy = 0x7f0300e4;
public static final int fontProviderFetchTimeout = 0x7f0300e5;
public static final int fontProviderPackage = 0x7f0300e6;
public static final int fontProviderQuery = 0x7f0300e7;
public static final int fontStyle = 0x7f0300e8;
public static final int fontVariationSettings = 0x7f0300e9;
public static final int fontWeight = 0x7f0300ea;
public static final int ttcIndex = 0x7f030216;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f05006a;
public static final int notification_icon_bg_color = 0x7f05006b;
public static final int ripple_material_light = 0x7f050076;
public static final int secondary_text_default_material_light = 0x7f050078;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f060051;
public static final int compat_button_inset_vertical_material = 0x7f060052;
public static final int compat_button_padding_horizontal_material = 0x7f060053;
public static final int compat_button_padding_vertical_material = 0x7f060054;
public static final int compat_control_corner_material = 0x7f060055;
public static final int compat_notification_large_icon_max_height = 0x7f060056;
public static final int compat_notification_large_icon_max_width = 0x7f060057;
public static final int notification_action_icon_size = 0x7f0600c3;
public static final int notification_action_text_size = 0x7f0600c4;
public static final int notification_big_circle_margin = 0x7f0600c5;
public static final int notification_content_margin_start = 0x7f0600c6;
public static final int notification_large_icon_height = 0x7f0600c7;
public static final int notification_large_icon_width = 0x7f0600c8;
public static final int notification_main_column_padding_top = 0x7f0600c9;
public static final int notification_media_narrow_margin = 0x7f0600ca;
public static final int notification_right_icon_size = 0x7f0600cb;
public static final int notification_right_side_padding_top = 0x7f0600cc;
public static final int notification_small_icon_background_padding = 0x7f0600cd;
public static final int notification_small_icon_size_as_large = 0x7f0600ce;
public static final int notification_subtext_size = 0x7f0600cf;
public static final int notification_top_pad = 0x7f0600d0;
public static final int notification_top_pad_large_text = 0x7f0600d1;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f07007c;
public static final int notification_bg = 0x7f07007d;
public static final int notification_bg_low = 0x7f07007e;
public static final int notification_bg_low_normal = 0x7f07007f;
public static final int notification_bg_low_pressed = 0x7f070080;
public static final int notification_bg_normal = 0x7f070081;
public static final int notification_bg_normal_pressed = 0x7f070082;
public static final int notification_icon_background = 0x7f070083;
public static final int notification_template_icon_bg = 0x7f070084;
public static final int notification_template_icon_low_bg = 0x7f070085;
public static final int notification_tile_bg = 0x7f070086;
public static final int notify_panel_notification_icon_bg = 0x7f070087;
}
public static final class id {
private id() {}
public static final int accessibility_action_clickable_span = 0x7f080006;
public static final int accessibility_custom_action_0 = 0x7f080007;
public static final int accessibility_custom_action_1 = 0x7f080008;
public static final int accessibility_custom_action_10 = 0x7f080009;
public static final int accessibility_custom_action_11 = 0x7f08000a;
public static final int accessibility_custom_action_12 = 0x7f08000b;
public static final int accessibility_custom_action_13 = 0x7f08000c;
public static final int accessibility_custom_action_14 = 0x7f08000d;
public static final int accessibility_custom_action_15 = 0x7f08000e;
public static final int accessibility_custom_action_16 = 0x7f08000f;
public static final int accessibility_custom_action_17 = 0x7f080010;
public static final int accessibility_custom_action_18 = 0x7f080011;
public static final int accessibility_custom_action_19 = 0x7f080012;
public static final int accessibility_custom_action_2 = 0x7f080013;
public static final int accessibility_custom_action_20 = 0x7f080014;
public static final int accessibility_custom_action_21 = 0x7f080015;
public static final int accessibility_custom_action_22 = 0x7f080016;
public static final int accessibility_custom_action_23 = 0x7f080017;
public static final int accessibility_custom_action_24 = 0x7f080018;
public static final int accessibility_custom_action_25 = 0x7f080019;
public static final int accessibility_custom_action_26 = 0x7f08001a;
public static final int accessibility_custom_action_27 = 0x7f08001b;
public static final int accessibility_custom_action_28 = 0x7f08001c;
public static final int accessibility_custom_action_29 = 0x7f08001d;
public static final int accessibility_custom_action_3 = 0x7f08001e;
public static final int accessibility_custom_action_30 = 0x7f08001f;
public static final int accessibility_custom_action_31 = 0x7f080020;
public static final int accessibility_custom_action_4 = 0x7f080021;
public static final int accessibility_custom_action_5 = 0x7f080022;
public static final int accessibility_custom_action_6 = 0x7f080023;
public static final int accessibility_custom_action_7 = 0x7f080024;
public static final int accessibility_custom_action_8 = 0x7f080025;
public static final int accessibility_custom_action_9 = 0x7f080026;
public static final int action_container = 0x7f080030;
public static final int action_divider = 0x7f080032;
public static final int action_image = 0x7f080034;
public static final int action_text = 0x7f08003c;
public static final int actions = 0x7f08003d;
public static final int async = 0x7f080045;
public static final int blocking = 0x7f080049;
public static final int chronometer = 0x7f080054;
public static final int dialog_button = 0x7f080066;
public static final int forever = 0x7f080079;
public static final int icon = 0x7f080084;
public static final int icon_group = 0x7f080085;
public static final int info = 0x7f080088;
public static final int italic = 0x7f08008a;
public static final int line1 = 0x7f08008f;
public static final int line3 = 0x7f080090;
public static final int normal = 0x7f0800a1;
public static final int notification_background = 0x7f0800a4;
public static final int notification_main_column = 0x7f0800a5;
public static final int notification_main_column_container = 0x7f0800a6;
public static final int right_icon = 0x7f0800b9;
public static final int right_side = 0x7f0800ba;
public static final int tag_accessibility_actions = 0x7f0800e8;
public static final int tag_accessibility_clickable_spans = 0x7f0800e9;
public static final int tag_accessibility_heading = 0x7f0800ea;
public static final int tag_accessibility_pane_title = 0x7f0800eb;
public static final int tag_screen_reader_focusable = 0x7f0800ec;
public static final int tag_transition_group = 0x7f0800ed;
public static final int tag_unhandled_key_event_manager = 0x7f0800ee;
public static final int tag_unhandled_key_listeners = 0x7f0800ef;
public static final int text = 0x7f0800f0;
public static final int text2 = 0x7f0800f1;
public static final int time = 0x7f0800fa;
public static final int title = 0x7f0800fb;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f09000e;
}
public static final class layout {
private layout() {}
public static final int custom_dialog = 0x7f0b001f;
public static final int notification_action = 0x7f0b0030;
public static final int notification_action_tombstone = 0x7f0b0031;
public static final int notification_template_custom_big = 0x7f0b0038;
public static final int notification_template_icon_group = 0x7f0b0039;
public static final int notification_template_part_chronometer = 0x7f0b003d;
public static final int notification_template_part_time = 0x7f0b003e;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0e004d;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0f0119;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0f011a;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f011c;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0f011f;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0f0121;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01cb;
public static final int Widget_Compat_NotificationActionText = 0x7f0f01cc;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030027 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] FontFamily = { 0x7f0300e2, 0x7f0300e3, 0x7f0300e4, 0x7f0300e5, 0x7f0300e6, 0x7f0300e7 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300e0, 0x7f0300e8, 0x7f0300e9, 0x7f0300ea, 0x7f030216 };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
|
package org.corant.modules.mail;
import static org.corant.shared.util.Assertions.shouldNotNull;
import static org.corant.shared.util.Maps.toProperties;
import java.util.Date;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* corant-modules-mail
*
* @author jiang 2021/2/23
* @since
*/
public class MailSenderTemplate {
@Inject
private MailConfig config;
private MailSenderTemplate(MailConfig config) {
this.config = shouldNotNull(config);
}
public static MailSenderTemplate config(String protocol, String host, int port, String username,
String password, int connectionTimeout, Map<String, String> properties) {
MailConfig config =
new MailConfig(protocol, host, port, username, password, connectionTimeout, properties);
return new MailSenderTemplate(config);
}
public void send(String subject, String htmlMessage, String toAddress, String ccAddress)
throws MessagingException {
Multipart multipart = new MimeMultipart();
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlMessage, "text/html;charset=utf-8");
multipart.addBodyPart(htmlPart);
MimeMessage mimeMessage = new MimeMessage(getSession());
mimeMessage.setFrom(config.getUsername());
mimeMessage.setContent(multipart);
mimeMessage.setSubject(subject);
mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);
if (ccAddress != null) {
mimeMessage.setRecipients(Message.RecipientType.CC, ccAddress);
}
this.send(mimeMessage);
}
private Session getSession() {
return Session.getInstance(toProperties(config.getProperties()),
new DefaultAuthenticator(config.getUsername(), config.getPassword()));
}
private void send(MimeMessage mimeMessage) throws MessagingException {
try (Transport transport = getSession().getTransport(config.getProtocol())) {
transport.connect(config.getHost(), config.getPort(), config.getUsername(),
config.getPassword());
if (mimeMessage.getSentDate() == null) {
mimeMessage.setSentDate(new Date());
}
mimeMessage.saveChanges();
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
}
}
|
package cgeo.geocaching.connector.ec;
import static org.assertj.core.api.Assertions.assertThat;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.connector.ConnectorFactoryTest;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LogType;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
public class ECConnectorTest extends TestCase {
public static void testCanHandle() throws Exception {
assertThat(ECConnector.getInstance().canHandle("EC380")).isTrue();
assertThat(ECConnector.getInstance().canHandle("GC380")).isFalse();
assertThat(ECConnector.getInstance().canHandle("GCEC380")).overridingErrorMessage("faked EC codes must be handled during the import, otherwise GCECxxxx codes belong to 2 connectors").isFalse();
}
public static void testGetPossibleLogTypes() throws Exception {
final List<LogType> possibleLogTypes = ECConnector.getInstance().getPossibleLogTypes(createCache());
assertThat(possibleLogTypes).isNotNull();
assertThat(possibleLogTypes).isNotEmpty();
assertThat(possibleLogTypes).contains(LogType.FOUND_IT);
}
private static Geocache createCache() {
final Geocache geocache = new Geocache();
geocache.setType(CacheType.TRADITIONAL);
geocache.setGeocode("EC727");
return geocache;
}
public static void testGetGeocodeFromUrl() throws Exception {
assertThat(ECConnector.getInstance().getGeocodeFromUrl("http://extremcaching.com/index.php/output-2/738")).isEqualTo("EC738");
}
public static void testHandledGeocodes() {
Set<String> geocodes = ConnectorFactoryTest.getGeocodeSample();
assertThat(ECConnector.getInstance().handledGeocodes(geocodes)).containsOnly("EC1234", "EC5678");
}
}
|
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* 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.arialyy.aria.core.processor;
import com.arialyy.aria.core.inf.IEventHandler;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* Http文件长度适配器
*/
public interface IHttpFileLenAdapter extends IEventHandler {
/**
* 同伙header中的数据获取文件长度
*
* @param headers header参数{@link URLConnection#getHeaderFields()}
* @return 文件长度
*/
long handleFileLen(Map<String, List<String>> headers);
}
|
package org.apereo.cas.services;
import lombok.val;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.DeleteItemRequest;
import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest;
import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest;
import com.amazonaws.services.dynamodbv2.model.GetItemRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.util.TableUtils;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.configuration.model.support.dynamodb.DynamoDbServiceRegistryProperties;
import org.apereo.cas.services.util.DefaultRegisteredServiceJsonSerializer;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.serialization.StringSerializer;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* This is {@link DynamoDbServiceRegistryFacilitator}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
@Slf4j
@Getter
public class DynamoDbServiceRegistryFacilitator {
private final StringSerializer<RegisteredService> jsonSerializer = new DefaultRegisteredServiceJsonSerializer();
@Getter
private enum ColumnNames {
ID("id"), NAME("name"), DESCRIPTION("description"), SERVICE_ID("serviceId"), ENCODED("encoded");
private final String columnName;
ColumnNames(final String columnName) {
this.columnName = columnName;
}
}
private final DynamoDbServiceRegistryProperties dynamoDbProperties;
private final AmazonDynamoDB amazonDynamoDBClient;
public DynamoDbServiceRegistryFacilitator(final DynamoDbServiceRegistryProperties dynamoDbProperties,
final AmazonDynamoDB amazonDynamoDBClient) {
this.dynamoDbProperties = dynamoDbProperties;
this.amazonDynamoDBClient = amazonDynamoDBClient;
if (!dynamoDbProperties.isPreventTableCreationOnStartup()) {
createServicesTable(dynamoDbProperties.isDropTablesOnStartup());
}
}
/**
* Delete boolean.
*
* @param service the service
* @return the boolean
*/
public boolean delete(final RegisteredService service) {
val del = new DeleteItemRequest().withTableName(dynamoDbProperties.getTableName())
.withKey(CollectionUtils.wrap(ColumnNames.ID.getColumnName(), new AttributeValue(String.valueOf(service.getId()))));
LOGGER.debug("Submitting delete request [{}] for service [{}]", del, service);
val res = amazonDynamoDBClient.deleteItem(del);
LOGGER.debug("Delete request came back with result [{}]", res);
return res != null;
}
/**
* Count long.
*
* @return the long
*/
public long count() {
val scan = new ScanRequest(dynamoDbProperties.getTableName());
LOGGER.debug("Scanning table with request [{}] to count items", scan);
val result = this.amazonDynamoDBClient.scan(scan);
LOGGER.debug("Scanned table with result [{}]", scan);
return result.getCount();
}
/**
* Gets all.
*
* @return the all
*/
public List<RegisteredService> getAll() {
val scan = new ScanRequest(dynamoDbProperties.getTableName());
LOGGER.debug("Scanning table with request [{}]", scan);
val result = this.amazonDynamoDBClient.scan(scan);
LOGGER.debug("Scanned table with result [{}]", scan);
return result.getItems()
.stream()
.map(this::deserializeServiceFromBinaryBlob)
.sorted((o1, o2) -> Integer.valueOf(o1.getEvaluationOrder()).compareTo(o2.getEvaluationOrder()))
.collect(Collectors.toList());
}
/**
* Get registered service.
*
* @param id the id
* @return the registered service
*/
public RegisteredService get(final String id) {
val keys = new HashMap<String, AttributeValue>();
keys.put(ColumnNames.SERVICE_ID.getColumnName(), new AttributeValue(id));
return getRegisteredServiceByKeys(keys);
}
/**
* Get registered service.
*
* @param id the id
* @return the registered service
*/
public RegisteredService get(final long id) {
val keys = new HashMap<String, AttributeValue>();
keys.put(ColumnNames.ID.getColumnName(), new AttributeValue(String.valueOf(id)));
return getRegisteredServiceByKeys(keys);
}
private RegisteredService deserializeServiceFromBinaryBlob(final Map<String, AttributeValue> returnItem) {
val bb = returnItem.get(ColumnNames.ENCODED.getColumnName()).getB();
LOGGER.debug("Located binary encoding of service item [{}]. Transforming item into service object", returnItem);
try (val is = new ByteArrayInputStream(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining())) {
return this.jsonSerializer.from(is);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
private RegisteredService getRegisteredServiceByKeys(final Map<String, AttributeValue> keys) {
val request = new GetItemRequest().withKey(keys).withTableName(dynamoDbProperties.getTableName());
LOGGER.debug("Submitting request [{}] to get service with keys [{}]", request, keys);
val returnItem = amazonDynamoDBClient.getItem(request).getItem();
if (returnItem != null) {
val service = deserializeServiceFromBinaryBlob(returnItem);
LOGGER.debug("Located service [{}]", service);
return service;
}
return null;
}
/**
* Put.
*
* @param service the service
*/
public void put(final RegisteredService service) {
val values = buildTableAttributeValuesMapFromService(service);
val putItemRequest = new PutItemRequest(dynamoDbProperties.getTableName(), values);
LOGGER.debug("Submitting put request [{}] for service id [{}]", putItemRequest, service.getServiceId());
val putItemResult = amazonDynamoDBClient.putItem(putItemRequest);
LOGGER.debug("Service added with result [{}]", putItemResult);
}
/**
* Create tables.
*
* @param deleteTables the delete tables
*/
@SneakyThrows
public void createServicesTable(final boolean deleteTables) {
LOGGER.debug("Attempting to create DynamoDb services table");
val request = new CreateTableRequest().withAttributeDefinitions(
new AttributeDefinition(ColumnNames.ID.getColumnName(), ScalarAttributeType.S))
.withKeySchema(new KeySchemaElement(ColumnNames.ID.getColumnName(), KeyType.HASH))
.withProvisionedThroughput(new ProvisionedThroughput(dynamoDbProperties.getReadCapacity(),
dynamoDbProperties.getWriteCapacity())).withTableName(dynamoDbProperties.getTableName());
if (deleteTables) {
val delete = new DeleteTableRequest(request.getTableName());
LOGGER.debug("Sending delete request [{}] to remove table if necessary", delete);
TableUtils.deleteTableIfExists(amazonDynamoDBClient, delete);
}
LOGGER.debug("Sending delete request [{}] to create table", request);
TableUtils.createTableIfNotExists(amazonDynamoDBClient, request);
LOGGER.debug("Waiting until table [{}] becomes active...", request.getTableName());
TableUtils.waitUntilActive(amazonDynamoDBClient, request.getTableName());
val describeTableRequest = new DescribeTableRequest().withTableName(request.getTableName());
LOGGER.debug("Sending request [{}] to obtain table description...", describeTableRequest);
val tableDescription = amazonDynamoDBClient.describeTable(describeTableRequest).getTable();
LOGGER.debug("Located newly created table with description: [{}]", tableDescription);
}
/**
* Build table attribute values from map.
*
* @param service the service
* @return the map
*/
public Map<String, AttributeValue> buildTableAttributeValuesMapFromService(final RegisteredService service) {
val values = new HashMap<String, AttributeValue>();
values.put(ColumnNames.ID.getColumnName(), new AttributeValue(String.valueOf(service.getId())));
values.put(ColumnNames.NAME.getColumnName(), new AttributeValue(service.getName()));
values.put(ColumnNames.DESCRIPTION.getColumnName(), new AttributeValue(service.getDescription()));
values.put(ColumnNames.SERVICE_ID.getColumnName(), new AttributeValue(service.getServiceId()));
val out = new ByteArrayOutputStream();
jsonSerializer.to(out, service);
values.put(ColumnNames.ENCODED.getColumnName(), new AttributeValue().withB(ByteBuffer.wrap(out.toByteArray())));
LOGGER.debug("Created attribute values [{}] based on provided service [{}]", values, service);
return values;
}
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.servicemodel;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.servicemodel.ProtocolException;
/**
* The base .NET class managing System.ServiceModel.MessageHeaderException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.ServiceModel.MessageHeaderException" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.ServiceModel.MessageHeaderException</a>
*/
public class MessageHeaderException extends ProtocolException {
/**
* Fully assembly qualified name: System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
*/
public static final String assemblyFullName = "System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
/**
* Assembly name: System.ServiceModel
*/
public static final String assemblyShortName = "System.ServiceModel";
/**
* Qualified class name: System.ServiceModel.MessageHeaderException
*/
public static final String className = "System.ServiceModel.MessageHeaderException";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
JCNativeException jcNativeException = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException jce) {
JCOReflector.writeLog(jce);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public MessageHeaderException() {
super();
}
/**
* Internal constructor. Use with caution
*/
public MessageHeaderException(java.lang.Object instance) {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else if (instance instanceof JCNativeException) {
jcNativeException = (JCNativeException) instance;
classInstance = jcNativeException.getCLRException();
}
}
public MessageHeaderException(String message) {
super(message);
}
public MessageHeaderException(NetException cause) {
super(cause);
}
public MessageHeaderException(String message, NetException cause) {
super(message, cause);
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link MessageHeaderException}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link MessageHeaderException} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static MessageHeaderException cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new MessageHeaderException(from.getJCOInstance());
}
// Constructors section
public MessageHeaderException(java.lang.String message, boolean isDuplicate) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(message, isDuplicate));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public MessageHeaderException(java.lang.String message, java.lang.String headerName, java.lang.String ns) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(message, headerName, ns));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public MessageHeaderException(java.lang.String message, java.lang.String headerName, java.lang.String ns, boolean isDuplicate) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(message, headerName, ns, isDuplicate));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public MessageHeaderException(java.lang.String message, java.lang.String headerName, java.lang.String ns, boolean isDuplicate, NetException innerException) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(message, headerName, ns, isDuplicate, innerException == null ? null : innerException.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public MessageHeaderException(java.lang.String message, java.lang.String headerName, java.lang.String ns, NetException innerException) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(message, headerName, ns, innerException == null ? null : innerException.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
// Properties section
public boolean getIsDuplicate() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("IsDuplicate");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getHeaderName() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("HeaderName");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getHeaderNamespace() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("HeaderNamespace");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
}
|
/*
* Copyright 1999-2019 Seata.io Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.seata.server.storage.db.store;
import io.seata.common.exception.DataAccessException;
import io.seata.common.exception.StoreException;
import io.seata.common.util.IOUtil;
import io.seata.common.util.StringUtils;
import io.seata.config.Configuration;
import io.seata.config.ConfigurationFactory;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.constants.ServerTableColumnsName;
import io.seata.core.store.BranchTransactionDO;
import io.seata.core.store.GlobalTransactionDO;
import io.seata.core.store.LogStore;
import io.seata.core.store.db.sql.log.LogStoreSqlsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static io.seata.common.DefaultValues.DEFAULT_STORE_DB_BRANCH_TABLE;
import static io.seata.common.DefaultValues.DEFAULT_STORE_DB_GLOBAL_TABLE;
/**
* The type Log store data base dao.
*
* @author zhangsen
*/
public class LogStoreDataBaseDAO implements LogStore {
private static final Logger LOGGER = LoggerFactory.getLogger(LogStoreDataBaseDAO.class);
/**
* The transaction name key
*/
private static final String TRANSACTION_NAME_KEY = "TRANSACTION_NAME";
/**
* The transaction name default size is 128
*/
private static final int TRANSACTION_NAME_DEFAULT_SIZE = 128;
/**
* The constant CONFIG.
*/
protected static final Configuration CONFIG = ConfigurationFactory.getInstance();
/**
* The Log store data source.
*/
protected DataSource logStoreDataSource = null;
/**
* The Global table.
*/
protected String globalTable;
/**
* The Branch table.
*/
protected String branchTable;
private String dbType;
private int transactionNameColumnSize = TRANSACTION_NAME_DEFAULT_SIZE;
/**
* Instantiates a new Log store data base dao.
*
* @param logStoreDataSource the log store data source
*/
public LogStoreDataBaseDAO(DataSource logStoreDataSource) {
this.logStoreDataSource = logStoreDataSource;
globalTable = CONFIG.getConfig(ConfigurationKeys.STORE_DB_GLOBAL_TABLE,
DEFAULT_STORE_DB_GLOBAL_TABLE);
branchTable = CONFIG.getConfig(ConfigurationKeys.STORE_DB_BRANCH_TABLE,
DEFAULT_STORE_DB_BRANCH_TABLE);
dbType = CONFIG.getConfig(ConfigurationKeys.STORE_DB_TYPE);
if (StringUtils.isBlank(dbType)) {
throw new StoreException("there must be db type.");
}
if (logStoreDataSource == null) {
throw new StoreException("there must be logStoreDataSource.");
}
// init transaction_name size
initTransactionNameSize();
}
@Override
public GlobalTransactionDO queryGlobalTransactionDO(String xid) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getQueryGlobalTransactionSQL(globalTable);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setString(1, xid);
rs = ps.executeQuery();
if (rs.next()) {
return convertGlobalTransactionDO(rs);
} else {
return null;
}
} catch (SQLException e) {
throw new DataAccessException(e);
} finally {
IOUtil.close(rs, ps, conn);
}
}
@Override
public GlobalTransactionDO queryGlobalTransactionDO(long transactionId) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getQueryGlobalTransactionSQLByTransactionId(globalTable);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setLong(1, transactionId);
rs = ps.executeQuery();
if (rs.next()) {
return convertGlobalTransactionDO(rs);
} else {
return null;
}
} catch (SQLException e) {
throw new DataAccessException(e);
} finally {
IOUtil.close(rs, ps, conn);
}
}
@Override
public List<GlobalTransactionDO> queryGlobalTransactionDO(int[] statuses, int limit) {
List<GlobalTransactionDO> ret = new ArrayList<>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
String paramsPlaceHolder = org.apache.commons.lang.StringUtils.repeat("?", ",", statuses.length);
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getQueryGlobalTransactionSQLByStatus(globalTable, paramsPlaceHolder);
ps = conn.prepareStatement(sql);
for (int i = 0; i < statuses.length; i++) {
int status = statuses[i];
ps.setInt(i + 1, status);
}
ps.setInt(statuses.length + 1, limit);
rs = ps.executeQuery();
while (rs.next()) {
ret.add(convertGlobalTransactionDO(rs));
}
return ret;
} catch (SQLException e) {
throw new DataAccessException(e);
} finally {
IOUtil.close(rs, ps, conn);
}
}
@Override
public boolean insertGlobalTransactionDO(GlobalTransactionDO globalTransactionDO) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getInsertGlobalTransactionSQL(globalTable);
Connection conn = null;
PreparedStatement ps = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setString(1, globalTransactionDO.getXid());
ps.setLong(2, globalTransactionDO.getTransactionId());
ps.setInt(3, globalTransactionDO.getStatus());
ps.setString(4, globalTransactionDO.getApplicationId());
ps.setString(5, globalTransactionDO.getTransactionServiceGroup());
String transactionName = globalTransactionDO.getTransactionName();
transactionName = transactionName.length() > transactionNameColumnSize ? transactionName.substring(0,
transactionNameColumnSize) : transactionName;
ps.setString(6, transactionName);
ps.setInt(7, globalTransactionDO.getTimeout());
ps.setLong(8, globalTransactionDO.getBeginTime());
ps.setString(9, globalTransactionDO.getApplicationData());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new StoreException(e);
} finally {
IOUtil.close(ps, conn);
}
}
@Override
public boolean updateGlobalTransactionDO(GlobalTransactionDO globalTransactionDO) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getUpdateGlobalTransactionStatusSQL(globalTable);
Connection conn = null;
PreparedStatement ps = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setInt(1, globalTransactionDO.getStatus());
ps.setString(2, globalTransactionDO.getXid());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new StoreException(e);
} finally {
IOUtil.close(ps, conn);
}
}
@Override
public boolean deleteGlobalTransactionDO(GlobalTransactionDO globalTransactionDO) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getDeleteGlobalTransactionSQL(globalTable);
Connection conn = null;
PreparedStatement ps = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setString(1, globalTransactionDO.getXid());
ps.executeUpdate();
} catch (SQLException e) {
throw new StoreException(e);
} finally {
IOUtil.close(ps, conn);
}
return true;
}
@Override
public List<BranchTransactionDO> queryBranchTransactionDO(String xid) {
List<BranchTransactionDO> rets = new ArrayList<>();
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getQueryBranchTransaction(branchTable);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setString(1, xid);
rs = ps.executeQuery();
while (rs.next()) {
rets.add(convertBranchTransactionDO(rs));
}
return rets;
} catch (SQLException e) {
throw new DataAccessException(e);
} finally {
IOUtil.close(rs, ps, conn);
}
}
@Override
public List<BranchTransactionDO> queryBranchTransactionDO(List<String> xids) {
int length = xids.size();
List<BranchTransactionDO> rets = new ArrayList<>(length * 3);
String paramsPlaceHolder = org.apache.commons.lang.StringUtils.repeat("?", ",", length);
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getQueryBranchTransaction(branchTable, paramsPlaceHolder);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
for (int i = 0; i < length; i++) {
ps.setString(i + 1, xids.get(i));
}
rs = ps.executeQuery();
while (rs.next()) {
rets.add(convertBranchTransactionDO(rs));
}
return rets;
} catch (SQLException e) {
throw new DataAccessException(e);
} finally {
IOUtil.close(rs, ps, conn);
}
}
@Override
public boolean insertBranchTransactionDO(BranchTransactionDO branchTransactionDO) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getInsertBranchTransactionSQL(branchTable);
Connection conn = null;
PreparedStatement ps = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setString(1, branchTransactionDO.getXid());
ps.setLong(2, branchTransactionDO.getTransactionId());
ps.setLong(3, branchTransactionDO.getBranchId());
ps.setString(4, branchTransactionDO.getResourceGroupId());
ps.setString(5, branchTransactionDO.getResourceId());
ps.setString(6, branchTransactionDO.getBranchType());
ps.setInt(7, branchTransactionDO.getStatus());
ps.setString(8, branchTransactionDO.getClientId());
ps.setString(9, branchTransactionDO.getApplicationData());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new StoreException(e);
} finally {
IOUtil.close(ps, conn);
}
}
@Override
public boolean updateBranchTransactionDO(BranchTransactionDO branchTransactionDO) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getUpdateBranchTransactionStatusSQL(branchTable);
Connection conn = null;
PreparedStatement ps = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setInt(1, branchTransactionDO.getStatus());
ps.setString(2, branchTransactionDO.getXid());
ps.setLong(3, branchTransactionDO.getBranchId());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
throw new StoreException(e);
} finally {
IOUtil.close(ps, conn);
}
}
@Override
public boolean deleteBranchTransactionDO(BranchTransactionDO branchTransactionDO) {
String sql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getDeleteBranchTransactionByBranchIdSQL(branchTable);
Connection conn = null;
PreparedStatement ps = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setString(1, branchTransactionDO.getXid());
ps.setLong(2, branchTransactionDO.getBranchId());
ps.executeUpdate();
} catch (SQLException e) {
throw new StoreException(e);
} finally {
IOUtil.close(ps, conn);
}
return true;
}
@Override
public long getCurrentMaxSessionId(long high, long low) {
String transMaxSql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getQueryGlobalMax(globalTable);
String branchMaxSql = LogStoreSqlsFactory.getLogStoreSqls(dbType).getQueryBranchMax(branchTable);
long maxTransId = getCurrentMaxSessionId(transMaxSql, high, low);
long maxBranchId = getCurrentMaxSessionId(branchMaxSql, high, low);
return maxBranchId > maxTransId ? maxBranchId : maxTransId;
}
private long getCurrentMaxSessionId(String sql, long high, long low) {
long max = 0;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = logStoreDataSource.getConnection();
conn.setAutoCommit(true);
ps = conn.prepareStatement(sql);
ps.setLong(1, high);
ps.setLong(2, low);
rs = ps.executeQuery();
while (rs.next()) {
max = rs.getLong(1);
}
} catch (SQLException e) {
throw new DataAccessException(e);
} finally {
IOUtil.close(rs, ps, conn);
}
return max;
}
private GlobalTransactionDO convertGlobalTransactionDO(ResultSet rs) throws SQLException {
GlobalTransactionDO globalTransactionDO = new GlobalTransactionDO();
globalTransactionDO.setXid(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_XID));
globalTransactionDO.setStatus(rs.getInt(ServerTableColumnsName.GLOBAL_TABLE_STATUS));
globalTransactionDO.setApplicationId(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_APPLICATION_ID));
globalTransactionDO.setBeginTime(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_BEGIN_TIME));
globalTransactionDO.setTimeout(rs.getInt(ServerTableColumnsName.GLOBAL_TABLE_TIMEOUT));
globalTransactionDO.setTransactionId(rs.getLong(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_ID));
globalTransactionDO.setTransactionName(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_NAME));
globalTransactionDO.setTransactionServiceGroup(
rs.getString(ServerTableColumnsName.GLOBAL_TABLE_TRANSACTION_SERVICE_GROUP));
globalTransactionDO.setApplicationData(rs.getString(ServerTableColumnsName.GLOBAL_TABLE_APPLICATION_DATA));
globalTransactionDO.setGmtCreate(rs.getTimestamp(ServerTableColumnsName.GLOBAL_TABLE_GMT_CREATE));
globalTransactionDO.setGmtModified(rs.getTimestamp(ServerTableColumnsName.GLOBAL_TABLE_GMT_MODIFIED));
return globalTransactionDO;
}
private BranchTransactionDO convertBranchTransactionDO(ResultSet rs) throws SQLException {
BranchTransactionDO branchTransactionDO = new BranchTransactionDO();
branchTransactionDO.setResourceGroupId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_RESOURCE_GROUP_ID));
branchTransactionDO.setStatus(rs.getInt(ServerTableColumnsName.BRANCH_TABLE_STATUS));
branchTransactionDO.setApplicationData(rs.getString(ServerTableColumnsName.BRANCH_TABLE_APPLICATION_DATA));
branchTransactionDO.setClientId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_CLIENT_ID));
branchTransactionDO.setXid(rs.getString(ServerTableColumnsName.BRANCH_TABLE_XID));
branchTransactionDO.setResourceId(rs.getString(ServerTableColumnsName.BRANCH_TABLE_RESOURCE_ID));
branchTransactionDO.setBranchId(rs.getLong(ServerTableColumnsName.BRANCH_TABLE_BRANCH_ID));
branchTransactionDO.setBranchType(rs.getString(ServerTableColumnsName.BRANCH_TABLE_BRANCH_TYPE));
branchTransactionDO.setTransactionId(rs.getLong(ServerTableColumnsName.BRANCH_TABLE_TRANSACTION_ID));
branchTransactionDO.setGmtCreate(rs.getTimestamp(ServerTableColumnsName.BRANCH_TABLE_GMT_CREATE));
branchTransactionDO.setGmtModified(rs.getTimestamp(ServerTableColumnsName.BRANCH_TABLE_GMT_MODIFIED));
return branchTransactionDO;
}
/**
* the public modifier only for test
*/
public void initTransactionNameSize() {
ColumnInfo columnInfo = queryTableStructure(globalTable, TRANSACTION_NAME_KEY);
if (columnInfo == null) {
LOGGER.warn("{} table or {} column not found", globalTable, TRANSACTION_NAME_KEY);
return;
}
this.transactionNameColumnSize = columnInfo.getColumnSize();
}
/**
* query column info from table
*
* @param tableName the table name
* @param colName the column name
* @return the column info
*/
private ColumnInfo queryTableStructure(final String tableName, String colName) {
try (Connection conn = logStoreDataSource.getConnection()) {
DatabaseMetaData dbmd = conn.getMetaData();
String schema = getSchema(conn);
ResultSet tableRs = dbmd.getTables(null, schema, "%", new String[]{"TABLE"});
while (tableRs.next()) {
String table = tableRs.getString("TABLE_NAME");
if (StringUtils.equalsIgnoreCase(table, tableName)) {
ResultSet columnRs = conn.getMetaData().getColumns(null, schema, tableName, null);
while (columnRs.next()) {
ColumnInfo info = new ColumnInfo();
String columnName = columnRs.getString("COLUMN_NAME");
info.setColumnName(columnName);
String typeName = columnRs.getString("TYPE_NAME");
info.setTypeName(typeName);
int columnSize = columnRs.getInt("COLUMN_SIZE");
info.setColumnSize(columnSize);
String remarks = columnRs.getString("REMARKS");
info.setRemarks(remarks);
if (StringUtils.equalsIgnoreCase(columnName, colName)) {
return info;
}
}
break;
}
}
} catch (SQLException e) {
LOGGER.error("query transaction_name size fail, {}", e.getMessage(), e);
}
return null;
}
private String getSchema(Connection conn) throws SQLException {
if ("h2".equalsIgnoreCase(dbType)) {
return null;
}
return conn.getMetaData().getUserName();
}
/**
* Sets log store data source.
*
* @param logStoreDataSource the log store data source
*/
public void setLogStoreDataSource(DataSource logStoreDataSource) {
this.logStoreDataSource = logStoreDataSource;
}
/**
* Sets global table.
*
* @param globalTable the global table
*/
public void setGlobalTable(String globalTable) {
this.globalTable = globalTable;
}
/**
* Sets branch table.
*
* @param branchTable the branch table
*/
public void setBranchTable(String branchTable) {
this.branchTable = branchTable;
}
/**
* Sets db type.
*
* @param dbType the db type
*/
public void setDbType(String dbType) {
this.dbType = dbType;
}
public int getTransactionNameColumnSize() {
return transactionNameColumnSize;
}
/**
* column info
*/
private static class ColumnInfo {
private String columnName;
private String typeName;
private int columnSize;
private String remarks;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public int getColumnSize() {
return columnSize;
}
public void setColumnSize(int columnSize) {
this.columnSize = columnSize;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}
}
|
package com.service.impl;
import com.dao.UserDao;
import com.model.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* author:RhineDream
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User getUserByName(String username) {
return userDao.getUserByName(username);
}
@Override
public List<User> getUserList(User user) {
return userDao.getUserList(user);
}
@Override
public void insert(User user) {
userDao.insert(user);
}
}
|
//MyGrid.java
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class MyGrid extends JFrame {
MyGrid() {
super( "DaisLab" );
Container myContainer = getContentPane();
GridLayout gridLayout = new GridLayout( 3, 2, 5, 10 );
myContainer.setLayout( gridLayout );
JLabel myLabel1 = new JLabel( "Utino " );
JLabel myLabel2 = new JLabel( "Tiba " );
JLabel myLabel3 = new JLabel( "Simomura" );
JLabel myLabel4 = new JLabel( "takeda " );
JLabel myLabel5 = new JLabel( "utida " );
myContainer.add( myLabel1 );
myContainer.add( myLabel2 );
myContainer.add( myLabel3 );
myContainer.add( myLabel4 );
myContainer.add( myLabel5 );
setSize( 300, 200 );
setVisible( true );
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent we ) {
System.exit( 0 );
}
} );
}
public static void main( String [] args ) {
MyGrid myGrid = new MyGrid();
}
}
|
/*
* 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.autobet.model;
import org.javalite.activejdbc.Model;
public class KeyValueStoreEntry
extends Model
{
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudtasks.v2.model;
/**
* Request message for `GetIamPolicy` method.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Tasks API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GetIamPolicyRequest extends com.google.api.client.json.GenericJson {
/**
* OPTIONAL: A `GetPolicyOptions` object for specifying options to `GetIamPolicy`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GetPolicyOptions options;
/**
* OPTIONAL: A `GetPolicyOptions` object for specifying options to `GetIamPolicy`.
* @return value or {@code null} for none
*/
public GetPolicyOptions getOptions() {
return options;
}
/**
* OPTIONAL: A `GetPolicyOptions` object for specifying options to `GetIamPolicy`.
* @param options options or {@code null} for none
*/
public GetIamPolicyRequest setOptions(GetPolicyOptions options) {
this.options = options;
return this;
}
@Override
public GetIamPolicyRequest set(String fieldName, Object value) {
return (GetIamPolicyRequest) super.set(fieldName, value);
}
@Override
public GetIamPolicyRequest clone() {
return (GetIamPolicyRequest) super.clone();
}
}
|
package com.example.viewpagerexample;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.tree.injected;
import com.intellij.lang.injection.ConcatenationAwareInjector;
import com.intellij.lang.injection.MultiHostInjector;
import com.intellij.lang.injection.MultiHostRegistrar;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.extensions.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SimpleModificationTracker;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.PsiParameterizedCachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.ParameterizedCachedValue;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author cdr
*/
public class ConcatenationInjectorManager extends SimpleModificationTracker {
public static final ExtensionPointName<ConcatenationAwareInjector> CONCATENATION_INJECTOR_EP_NAME = ExtensionPointName.create("com.intellij.concatenationAwareInjector");
public ConcatenationInjectorManager(Project project, PsiManagerEx psiManagerEx) {
final ExtensionPoint<ConcatenationAwareInjector> concatPoint = Extensions.getArea(project).getExtensionPoint(CONCATENATION_INJECTOR_EP_NAME);
concatPoint.addExtensionPointListener(new ExtensionPointListener<ConcatenationAwareInjector>() {
@Override
public void extensionAdded(@NotNull ConcatenationAwareInjector injector, @Nullable PluginDescriptor pluginDescriptor) {
registerConcatenationInjector(injector);
}
@Override
public void extensionRemoved(@NotNull ConcatenationAwareInjector injector, @Nullable PluginDescriptor pluginDescriptor) {
unregisterConcatenationInjector(injector);
}
});
// clear caches even on non-physical changes
psiManagerEx.registerRunnableToRunOnAnyChange(this::incModificationCount);
}
public static ConcatenationInjectorManager getInstance(final Project project) {
return ServiceManager.getService(project, ConcatenationInjectorManager.class);
}
private static InjectionResult doCompute(@NotNull PsiFile containingFile,
@NotNull Project project,
@NotNull PsiElement anchor,
@NotNull PsiElement[] operands) {
PsiDocumentManager docManager = PsiDocumentManager.getInstance(project);
InjectionRegistrarImpl registrar = new InjectionRegistrarImpl(project, containingFile, anchor, docManager);
InjectionResult result = null;
ConcatenationInjectorManager concatenationInjectorManager = getInstance(project);
for (ConcatenationAwareInjector concatenationInjector : concatenationInjectorManager.myConcatenationInjectors) {
concatenationInjector.getLanguagesToInject(registrar, operands);
result = registrar.getInjectedResult();
if (result != null) break;
}
return result;
}
private static final Key<ParameterizedCachedValue<InjectionResult, PsiElement>> INJECTED_PSI_IN_CONCATENATION = Key.create("INJECTED_PSI_IN_CONCATENATION");
private static final Key<Integer> NO_CONCAT_INJECTION_TIMESTAMP = Key.create("NO_CONCAT_INJECTION_TIMESTAMP");
public abstract static class BaseConcatenation2InjectorAdapter implements MultiHostInjector {
private final ConcatenationInjectorManager myManager;
public BaseConcatenation2InjectorAdapter(ConcatenationInjectorManager manager) {
myManager = manager;
}
@Override
public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
if (myManager.myConcatenationInjectors.isEmpty()) return;
final PsiFile containingFile = ((InjectionRegistrarImpl)registrar).getHostPsiFile();
Project project = containingFile.getProject();
long modificationCount = PsiManager.getInstance(project).getModificationTracker().getModificationCount();
Pair<PsiElement, PsiElement[]> pair = computeAnchorAndOperands(context);
PsiElement anchor = pair.first;
PsiElement[] operands = pair.second;
Integer noInjectionTimestamp = anchor.getUserData(NO_CONCAT_INJECTION_TIMESTAMP);
InjectionResult result;
ParameterizedCachedValue<InjectionResult, PsiElement> data = null;
if (operands.length == 0 || noInjectionTimestamp != null && noInjectionTimestamp == modificationCount) {
result = null;
}
else {
data = anchor.getUserData(INJECTED_PSI_IN_CONCATENATION);
result = data == null ? null : data.getValue(context);
if (result == null || !result.isValid()) {
result = doCompute(containingFile, project, anchor, operands);
}
}
if (result != null) {
((InjectionRegistrarImpl)registrar).addToResults(result);
if (data == null) {
CachedValueProvider.Result<InjectionResult> cachedResult =
CachedValueProvider.Result.create(result, PsiModificationTracker.MODIFICATION_COUNT, myManager);
data = CachedValuesManager.getManager(project).createParameterizedCachedValue(
context1 -> {
PsiFile containingFile1 = context1.getContainingFile();
Project project1 = containingFile1.getProject();
Pair<PsiElement, PsiElement[]> pair1 = computeAnchorAndOperands(context1);
InjectionResult result1 = pair1.second.length == 0 ? null : doCompute(containingFile1, project1, pair1.first, pair1.second);
return result1 == null ? null : CachedValueProvider.Result.create(result1, PsiModificationTracker.MODIFICATION_COUNT, myManager);
}, false);
((PsiParameterizedCachedValue<InjectionResult, PsiElement>)data).setValue(cachedResult);
anchor.putUserData(INJECTED_PSI_IN_CONCATENATION, data);
if (anchor.getUserData(NO_CONCAT_INJECTION_TIMESTAMP) != null) {
anchor.putUserData(NO_CONCAT_INJECTION_TIMESTAMP, null);
}
}
}
else {
// cache no-injection flag
if (anchor.getUserData(INJECTED_PSI_IN_CONCATENATION) != null) {
anchor.putUserData(INJECTED_PSI_IN_CONCATENATION, null);
}
anchor.putUserData(NO_CONCAT_INJECTION_TIMESTAMP, (int)modificationCount);
}
}
protected abstract Pair<PsiElement, PsiElement[]> computeAnchorAndOperands(@NotNull PsiElement context);
}
private final List<ConcatenationAwareInjector> myConcatenationInjectors = ContainerUtil.createLockFreeCopyOnWriteList();
public void registerConcatenationInjector(@NotNull ConcatenationAwareInjector injector) {
myConcatenationInjectors.add(injector);
concatenationInjectorsChanged();
}
public boolean unregisterConcatenationInjector(@NotNull ConcatenationAwareInjector injector) {
boolean removed = myConcatenationInjectors.remove(injector);
concatenationInjectorsChanged();
return removed;
}
private void concatenationInjectorsChanged() {
incModificationCount();
}
}
|
/* */ package jp.cssj.sakae.pdf.c.a;
/* */
/* */ import java.io.BufferedInputStream;
/* */ import java.io.EOFException;
/* */ import java.io.IOException;
/* */ import java.io.InputStreamReader;
/* */ import java.io.Reader;
/* */ import java.net.URISyntaxException;
/* */ import jp.cssj.e.b;
/* */ import jp.cssj.e.b.a;
/* */ import jp.cssj.e.c;
/* */ import jp.cssj.sakae.e.c;
/* */ import jp.cssj.sakae.pdf.g.a;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ class d
/* */ {
/* */ private Reader a;
/* */ private int b;
/* */ private c c;
/* */
/* */ public int[] a(b source) throws IOException, g {
/* 32 */ c toCID = new c();
/* 33 */ a(source, toCID);
/* 34 */ return toCID.a();
/* */ }
/* */
/* */ private void a(b source, c toCID) throws IOException, g {
/* 38 */ this.a = new InputStreamReader(new BufferedInputStream(source.h()), "ISO-8859-1");
/* */ try {
/* */ try {
/* 41 */ String ptoken = null;
/* */ while (true) {
/* 43 */ String token = c();
/* 44 */ if (token.equals("usecmap")) {
/* 45 */ d parser = new d();
/* 46 */ String href = ptoken.substring(1);
/* 47 */ if (this.c == null) {
/* 48 */ this.c = (c)a.a();
/* */ }
/* 50 */ b source2 = this.c.b(jp.cssj.e.e.d.a("UTF-8", source.d(), href));
/* */ try {
/* 52 */ parser.a(source2, toCID);
/* */ } finally {
/* 54 */ this.c.a(source2);
/* */ }
/* 56 */ } else if (token.equals("begincidrange")) {
/* 57 */ b(toCID);
/* 58 */ } else if (token.equals("begincidchar")) {
/* 59 */ a(toCID);
/* 60 */ } else if (token.equals("/CIDSystemInfo")) {
/* 61 */ a();
/* */ }
/* 63 */ ptoken = token;
/* */ }
/* 65 */ } catch (EOFException eOFException) {
/* */
/* 67 */ } catch (URISyntaxException e) {
/* 68 */ IOException ioe = new IOException();
/* 69 */ ioe.initCause(e);
/* 70 */ throw ioe;
/* */ }
/* */ } finally {
/* 73 */ this.a.close();
/* */ }
/* */ }
/* */
/* */ private void a(c toCID) throws IOException, g {
/* */ while (true) {
/* 79 */ String a = c();
/* 80 */ if (a.equals("endcidchar")) {
/* */ break;
/* */ }
/* 83 */ String b = c();
/* 84 */ a = a.substring(1, a.length() - 1).trim();
/* */ try {
/* 86 */ int code = Integer.parseInt(a, 16);
/* 87 */ int offset = Integer.parseInt(b);
/* 88 */ toCID.a(code, offset);
/* 89 */ } catch (NumberFormatException numberFormatException) {}
/* */ }
/* */ }
/* */
/* */
/* */
/* */ private void b(c toCID) throws IOException, g {
/* */ while (true) {
/* 97 */ String a = c();
/* 98 */ if (a.equals("endcidrange")) {
/* */ break;
/* */ }
/* 101 */ String b = c();
/* 102 */ String str1 = c();
/* */
/* 104 */ a = a.substring(1, a.length() - 1).trim();
/* 105 */ b = b.substring(1, b.length() - 1).trim();
/* */ try {
/* 107 */ int start = Integer.parseInt(a, 16);
/* 108 */ int end = Integer.parseInt(b, 16);
/* 109 */ if (a.length() != b.length() || a.length() % 2 != 0) {
/* 110 */ throw new g("開始位置と終了位置のキャラクターコードのバイト数が一致しないか、偶数桁の116進数になっていません");
/* */ }
/* 112 */ int offset = Integer.parseInt(str1);
/* */
/* 114 */ int len = end - start + 1;
/* 115 */ for (int j = 0; j < len; j++) {
/* 116 */ toCID.a(start + j, offset + j);
/* */ }
/* 118 */ } catch (NumberFormatException numberFormatException) {}
/* */ }
/* */ }
/* */
/* */
/* */
/* */ private void a() throws IOException {
/* 125 */ c();
/* 126 */ String dict = c();
/* 127 */ if (!dict.equals("dict")) {
/* */ return;
/* */ }
/* 130 */ String dup = c();
/* 131 */ if (!dup.equals("dup")) {
/* */ return;
/* */ }
/* 134 */ String begin = c();
/* 135 */ if (!begin.equals("begin")) {
/* */ return;
/* */ }
/* */ while (true) {
/* 139 */ String key = c();
/* 140 */ if (key.equals("/Registry")) {
/* 141 */ c();
/* 142 */ String def = c();
/* 143 */ if (!def.equals("def"))
/* */ return; continue;
/* */ }
/* 146 */ if (key.equals("/Ordering")) {
/* 147 */ c();
/* 148 */ String def = c();
/* 149 */ if (!def.equals("def"))
/* */ return; continue;
/* */ }
/* 152 */ if (key.equals("/Supplement")) {
/* 153 */ c();
/* 154 */ String def = c();
/* 155 */ if (!def.equals("def"))
/* */ return; continue;
/* */ }
/* 158 */ if (key.equals("end")) {
/* */ break;
/* */ }
/* */ }
/* */ }
/* */
/* */ private void b() throws IOException {
/* 165 */ for (; this.b != -1 && Character.isWhitespace((char)this.b); this.b = this.a.read());
/* */
/* */
/* 168 */ if (this.b == -1) {
/* 169 */ throw new EOFException();
/* */ }
/* */ }
/* */
/* */ private String c() throws IOException {
/* 174 */ b();
/* 175 */ StringBuffer buff = new StringBuffer();
/* 176 */ for (; this.b != -1 && !Character.isWhitespace((char)this.b); this.b = this.a.read()) {
/* 177 */ buff.append((char)this.b);
/* */ }
/* 179 */ if (this.b == -1) {
/* 180 */ throw new EOFException();
/* */ }
/* 182 */ String s = buff.toString();
/* 183 */ return a.b(s, "MS932");
/* */ }
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/jp/cssj/sakae/pdf/c/a/d.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package momo.com.day25_imagecache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;
/**
* Created by Administrator on 2016/11/11 0011.
*/
public class ImageCache {
/**
* 用来存储图片的集合
*
* key--->图片的网址String
*
* value-->图片Bitmap
* */
//static Map<String,Bitmap> cache = new HashMap<>(); //强引用
static LruCache<String,Bitmap> lruCache;
//单例模式
private ImageCache(){
//初始化lruCache
//计算最大内存
long maxMemory = Runtime.getRuntime().maxMemory();
Log.d("Tag","maxMemory:"+maxMemory);
//设置缓存为最大内存的1/8
lruCache = new LruCache<String,Bitmap>((int) (maxMemory/8)){
@Override
protected int sizeOf(String key, Bitmap value) {
//计算bimap的大小
int count = value.getByteCount();
return count;
}
};
}
static ImageCache imageCache;
public static ImageCache getInstance(){
if(imageCache==null){
imageCache = new ImageCache();
}
return imageCache;
}
/**
* 存
* */
public void put(String url,Bitmap bitmap){
//先保存一份到SDcard
try {
SdUtils.saveBitmap(url,bitmap);
} catch (Exception e) {
e.printStackTrace();
}
/* WeakReference<Bitmap> bitmapWeakReference=new WeakReference<Bitmap>(bitmap); //弱引用
//弱引用容易被垃圾回收机制回收(不推荐使用弱引用)
//从弱引用中取出对象
bitmap= bitmapWeakReference.get();
if(bitmap!=null){}*/
//再缓存到内存中
lruCache.put(url,bitmap);
}
/**
* 根据图片网址,取出图片
* */
public Bitmap get(String url){
//先从内存中取,如果没取到,再到Sdcard中取
Bitmap bitmap = lruCache.get(url);
if(bitmap==null){
bitmap = SdUtils.getBitmapFromSD(url);
}
return bitmap;
}
}
|
/*
* 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.codecommit.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.codecommit.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* InvalidRepositoryTriggerDestinationArnException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidRepositoryTriggerDestinationArnExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private InvalidRepositoryTriggerDestinationArnExceptionUnmarshaller() {
super(com.amazonaws.services.codecommit.model.InvalidRepositoryTriggerDestinationArnException.class, "InvalidRepositoryTriggerDestinationArnException");
}
@Override
public com.amazonaws.services.codecommit.model.InvalidRepositoryTriggerDestinationArnException unmarshallFromContext(JsonUnmarshallerContext context)
throws Exception {
com.amazonaws.services.codecommit.model.InvalidRepositoryTriggerDestinationArnException invalidRepositoryTriggerDestinationArnException = new com.amazonaws.services.codecommit.model.InvalidRepositoryTriggerDestinationArnException(
null);
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return invalidRepositoryTriggerDestinationArnException;
}
private static InvalidRepositoryTriggerDestinationArnExceptionUnmarshaller instance;
public static InvalidRepositoryTriggerDestinationArnExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new InvalidRepositoryTriggerDestinationArnExceptionUnmarshaller();
return instance;
}
}
|
package br.com.klauskpm.buttonclickcounter;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
package io.smallrye.reactive.messaging.amqp.fault;
import static io.smallrye.reactive.messaging.amqp.i18n.AMQPLogging.log;
import java.util.concurrent.CompletionStage;
import io.smallrye.reactive.messaging.amqp.AmqpMessage;
import io.smallrye.reactive.messaging.amqp.ConnectionHolder;
import io.vertx.mutiny.core.Context;
public class AmqpFailStop implements AmqpFailureHandler {
private final String channel;
public AmqpFailStop(String channel) {
this.channel = channel;
}
@Override
public <V> CompletionStage<Void> handle(AmqpMessage<V> msg, Context context, Throwable reason) {
// We mark the message as rejected and fail.
log.nackedFailMessage(channel);
return ConnectionHolder.runOnContextAndReportFailure(context, reason, () -> msg.getAmqpMessage().rejected());
}
}
|
/**
* Inmemantlr - In memory compiler for Antlr 4
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Julian Thome <julian.thome.de@gmail.com>
*
* 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 org.snt.inmemantlr.exceptions;
/**
* this exception is thrown when the compilation fails
*/
public class CompilationErrorException extends CompilationException {
private static final long serialVersionUID = -3664250014314129370L;
/**
* constructor
*
* @param msg exception message
*/
public CompilationErrorException(String msg) {
super(msg);
}
/**
* constructor
*
* @param msg exception message
* @param cause the cause
*/
public CompilationErrorException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
/*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.protocol.noteattachment;
import org.apache.commons.lang3.StringUtils;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.coeus.sys.framework.validation.ErrorReporter;
import org.kuali.rice.kns.service.DictionaryValidationService;
/**
* This class contains methods to "help" in validating {@link ProtocolAttachmentBase ProtocolAttachmentBase}.
*/
public abstract class ProtocolAttachmentBaseRuleHelper {
private static final String OTHER_TYPE_CODE = "9";
private final ProtocolAttachmentService attachmentService;
private final DictionaryValidationService validationService;
private final ErrorReporter errorReporter = new ErrorReporter();
private String propertyPrefix;
/**
* Creates helper deferring the setting of the prefix to later and setting used services.
* @param attachmentService the Attachment Service
* @throws IllegalArgumentException if the attachmentService is null
*/
protected ProtocolAttachmentBaseRuleHelper(final ProtocolAttachmentService attachmentService,
final DictionaryValidationService validationService) {
if (attachmentService == null) {
throw new IllegalArgumentException("the attachmentService is null");
}
if (validationService == null) {
throw new IllegalArgumentException("the validationService is null");
}
this.attachmentService = attachmentService;
this.validationService = validationService;
}
protected ProtocolAttachmentBaseRuleHelper(final String aPropertyPrefix,
final ProtocolAttachmentService attachmentService,
final DictionaryValidationService validationService) {
if (attachmentService == null) {
throw new IllegalArgumentException("the attachmentService is null");
}
if (validationService == null) {
throw new IllegalArgumentException("the validationService is null");
}
this.attachmentService = attachmentService;
this.validationService = validationService;
this.resetPropertyPrefix(aPropertyPrefix);
}
/**
* Resets the property prefix.
* @param aPropertyPrefix the prefix (ex: notesAttachmentsHelper.newAttachmentProtocol)
* @throws IllegalArgumentException if the propertyPrefix is null
*/
public void resetPropertyPrefix(final String aPropertyPrefix) {
if (aPropertyPrefix == null) {
throw new IllegalArgumentException("propertyPrefix is null");
}
this.propertyPrefix = aPropertyPrefix;
}
/**
* Checks for a valid description when description is required. Creates a hard error.
* @param <T> the attachment "type"
* @param attachment the attachment.
* @return true is valid.
*/
public <T extends ProtocolAttachmentBase & TypedAttachment> boolean validDescriptionWhenRequired(final T attachment) {
if (attachment.getType() == null || attachment.getType().getCode() == null) {
return true;
}
if (StringUtils.isBlank(attachment.getDescription()) && OTHER_TYPE_CODE.equals(attachment.getType().getCode())) {
final ProtocolAttachmentTypeBase type = this.attachmentService.getTypeFromCode(attachment.getType().getCode());
this.errorReporter.reportError(this.propertyPrefix + "." + TypedAttachment.PropertyName.DESCRIPTION,
KeyConstants.ERROR_PROTOCOL_ATTACHMENT_MISSING_DESC, (type != null) ? type.getDescription(): "");
return false;
}
return true;
}
/**
* Checks for a valid type for a group. Creates a hard error.
*
* <p>
* This method does not validate the existence of a type code.
* This validation is done by {@link #validType(ProtocolAttachmentBase)}.
* If the type code is blank this method will return true.
* </p>
*
* @param <T> the attachment "type"
* @param attachment the attachment.
* @return true is valid.
*/
public <T extends ProtocolAttachmentBase & TypedAttachment> boolean validTypeForGroup(final T attachment) {
if (attachment.getType() == null || attachment.getType().getCode() == null) {
return true;
}
for (ProtocolAttachmentTypeBase type : this.attachmentService.getTypesForGroup(attachment.getGroupCode())) {
if (type != null && attachment.getType().getCode().equals(type.getCode())) {
return true;
}
}
final ProtocolAttachmentTypeBase type = this.attachmentService.getTypeFromCode(attachment.getType().getCode());
this.errorReporter.reportError(this.propertyPrefix + "." + TypedAttachment.PropertyName.TYPE_CODE,
KeyConstants.ERROR_PROTOCOL_ATTACHMENT_INVALID_TYPE, (type != null) ? type.getDescription(): "");
return false;
}
/**
* Validates that the selected file contains valid fields. Creates a hard error.
* @param attachmentBase the attachment.
* @return true if valid.
*/
boolean validFile(final ProtocolAttachmentBase attachmentBase) {
//This assumes that the status object has been refreshed from the DB
//and if not found the refresh action set the person to null.
//This is an artifact of using anon keys
final boolean valid;
//this got much more complex using anon keys
if (attachmentBase.getFile() == null) {
valid = false;
this.errorReporter.reportError(this.propertyPrefix + ".newFile",
KeyConstants.ERROR_PROTOCOL_ATTACHMENT_MISSING_FILE);
} else {
valid = this.validationService.isBusinessObjectValid(attachmentBase.getFile(), this.propertyPrefix);
}
return valid;
}
/**
* Validates the attachment's primitive fields (non reference fields). Creates a hard error.
*
* @param attachmentBase the attachment
* @return true if valid.
*/
public boolean validPrimitiveFields(final ProtocolAttachmentBase attachmentBase) {
final Long oldFileId = attachmentBase.getFileId();
try {
//adding a bogus file id to pass the validation service since the fileId is DB generated
attachmentBase.setFileId(Long.valueOf(0));
return this.validationService.isBusinessObjectValid(attachmentBase, this.propertyPrefix);
} finally {
attachmentBase.setFileId(oldFileId);
}
}
}
|
package team.benchem.framework.sdk;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.benchem.framework.service.TokenService;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@Component
@WebFilter(urlPatterns = "/*", filterName = "userContextFilter")
public class MicroServiceFilter implements Filter {
Logger logger = LoggerFactory.getLogger(MicroServiceFilter.class);
@Autowired
TokenService tokenService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.debug("MicroServiceFilter.init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.debug("MicroServiceFilter.doFilter -> begin");
UserContext usrCtx = UserContext.createUserContext();
HttpServletRequest req = (HttpServletRequest) request;
String token = req.getHeader("Suf-Token");
if(token != null && token.length() > 0) {
usrCtx.properties.put("Suf-Token", token);
JSONObject tokenBody = tokenService.getToken(token);
if(tokenBody != null) {
for (Map.Entry<String, Object> item : tokenBody.entrySet()) {
usrCtx.properties.put(item.getKey(), item.getValue());
}
}
}
chain.doFilter(request, response);
logger.debug("MicroServiceFilter.doFilter -> end");
}
@Override
public void destroy() {
logger.debug("MicroServiceFilter.destroy");
}
}
|
package com.numanstc.caching;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository {
Book getByIsbn(String isbn);
}
|
package net.sanmuyao.core.util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Properties;
/**
* 取本机机器信息
* @author 杜庆明
* 2014年12月17日
*/
public class ComputerUtils {
/**
* mac地址
*/
public static String getMAC() {
String host = getIP();
String mac = "";
StringBuffer sb = new StringBuffer();
try {
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(host));
byte[] macs = ni.getHardwareAddress();
for (int i = 0; i < macs.length; i++) {
mac = Integer.toHexString(macs[i] & 0xFF);
if (mac.length() == 1) {
mac = '0' + mac;
}
sb.append(mac + "-");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
mac = sb.toString();
mac = mac.substring(0, mac.length() - 1);
return mac;
}
/**
* 取计算机名称
* @return
*/
public static String getHostName() {
String hostName = "";
Collection<InetAddress> colInetAddress =getAllHostAddress();
for (InetAddress address : colInetAddress) {
if (address.isSiteLocalAddress()) {
hostName = address.getHostName().toString();
break;
}
}
return hostName;
}
/**
* 取本机ip地址
* 获取本机IP,排除 127.0.0.1
* @return
*/
public static String getIP(){
String ip = "";
Collection<InetAddress> colInetAddress =getAllHostAddress();
for (InetAddress address : colInetAddress) {
if (address.isSiteLocalAddress()) {
ip = address.getHostAddress();
break;
}
}
return ip;
}
/**
* 取所有本机ip地址
* @return
*/
private static Collection<InetAddress> getAllHostAddress() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
Collection<InetAddress> addresses = new ArrayList<InetAddress>();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
addresses.add(inetAddress);
}
}
return addresses;
} catch (SocketException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* 取本机操作系统版本
* @return
*/
public static String getOSVersion() {
String version = "";
try {
Properties props=System.getProperties();
version = props.getProperty("os.version");
} catch (Exception e) {
e.printStackTrace();
}
return version;
}
/**
* 取本机操作系统名称
* @return
*/
public static String getOSName() {
String name = "";
try{
Properties props=System.getProperties();
name = props.getProperty("os.name");
} catch (Exception e){
e.printStackTrace();
}
return name;
}
//java环境
public static void all(){
Properties props=System.getProperties();
System.out.println("Java的运行环境版本:"+props.getProperty("java.version"));
System.out.println("Java的运行环境供应商:"+props.getProperty("java.vendor"));
System.out.println("Java供应商的URL:"+props.getProperty("java.vendor.url"));
System.out.println("Java的安装路径:"+props.getProperty("java.home"));
System.out.println("Java的虚拟机规范版本:"+props.getProperty("java.vm.specification.version"));
System.out.println("Java的虚拟机规范供应商:"+props.getProperty("java.vm.specification.vendor"));
System.out.println("Java的虚拟机规范名称:"+props.getProperty("java.vm.specification.name"));
System.out.println("Java的虚拟机实现版本:"+props.getProperty("java.vm.version"));
System.out.println("Java的虚拟机实现供应商:"+props.getProperty("java.vm.vendor"));
System.out.println("Java的虚拟机实现名称:"+props.getProperty("java.vm.name"));
System.out.println("Java运行时环境规范版本:"+props.getProperty("java.specification.version"));
System.out.println("Java运行时环境规范供应商:"+props.getProperty("java.specification.vender"));
System.out.println("Java运行时环境规范名称:"+props.getProperty("java.specification.name"));
System.out.println("Java的类格式版本号:"+props.getProperty("java.class.version"));
System.out.println("Java的类路径:"+props.getProperty("java.class.path"));
System.out.println("加载库时搜索的路径列表:"+props.getProperty("java.library.path"));
System.out.println("默认的临时文件路径:"+props.getProperty("java.io.tmpdir"));
System.out.println("一个或多个扩展目录的路径:"+props.getProperty("java.ext.dirs"));
System.out.println("操作系统的名称:"+props.getProperty("os.name"));
System.out.println("操作系统的构架:"+props.getProperty("os.arch"));
System.out.println("操作系统的版本:"+props.getProperty("os.version"));
System.out.println("文件分隔符:"+props.getProperty("file.separator"));//在 unix 系统中是"/" System.out.println("路径分隔符:"+props.getProperty("path.separator"));//在 unix 系统中是":" System.out.println("行分隔符:"+props.getProperty("line.separator"));//在 unix 系统中是"/n" System.out.println("用户的账户名称:"+props.getProperty("user.name"));
System.out.println("用户的主目录:"+props.getProperty("user.home"));
System.out.println("用户的当前工作目录:"+props.getProperty("user.dir"));
}
public static void main(String[] args) {
System.out.println(getHostName());
}
}
|
/*
* Copyright (c) 2009, Sarah Heckman, Laurie Williams, Dright Ho
* All Rights Reserved.
*
* Permission has been explicitly granted to the University of Minnesota
* Software Engineering Center to use and distribute this source for
* educational purposes, including delivering online education through
* Coursera or other entities.
*
* No warranty is given regarding this software, including warranties as
* to the correctness or completeness of this software, including
* fitness for purpose.
*
*
* Modifications
* 20171114 - Ian De Silva - Updated to comply with JUnit 4 and to adhere to
* coding standards. Added test documentation.
*/
package edu.ncsu.csc326.coffeemaker;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Test;
import edu.ncsu.csc326.coffeemaker.exceptions.InventoryException;
import edu.ncsu.csc326.coffeemaker.exceptions.RecipeException;
/**
* Unit tests for CoffeeMaker class.
*
* @author Sarah Heckman
*/
public class CoffeeMakerTest {
/**
* The object under test.
*/
private CoffeeMaker coffeeMaker;
// Sample recipes to use in testing.
private Recipe recipe1;
private Recipe recipe2;
private Recipe recipe3;
private Recipe recipe4;
// private CoffeeMaker cm;
/**
* Initializes some recipes to test with and the {@link CoffeeMaker}
* object we wish to test.
*
* @throws RecipeException if there was an error parsing the ingredient
* amount when setting up the recipe.
*/
@Before
public void setUp() throws RecipeException {
coffeeMaker = new CoffeeMaker();
//Set up for r1
recipe1 = new Recipe();
recipe1.setName("Coffee");
recipe1.setAmtChocolate("0");
recipe1.setAmtCoffee("3");
recipe1.setAmtMilk("1");
recipe1.setAmtSugar("1");
recipe1.setPrice("50");
//Set up for r2
recipe2 = new Recipe();
recipe2.setName("Mocha");
recipe2.setAmtChocolate("20");
recipe2.setAmtCoffee("3");
recipe2.setAmtMilk("1");
recipe2.setAmtSugar("1");
recipe2.setPrice("75");
//Set up for r3
recipe3 = new Recipe();
recipe3.setName("Latte");
recipe3.setAmtChocolate("0");
recipe3.setAmtCoffee("3");
recipe3.setAmtMilk("3");
recipe3.setAmtSugar("1");
recipe3.setPrice("100");
//Set up for r4
recipe4 = new Recipe();
recipe4.setName("Hot Chocolate");
recipe4.setAmtChocolate("4");
recipe4.setAmtCoffee("0");
recipe4.setAmtMilk("1");
recipe4.setAmtSugar("1");
recipe4.setPrice("65");
}
/**
* Given a coffee maker with the default inventory
* When we add inventory with well-formed quantities
* Then we do not get an exception trying to read the inventory quantities.
*
* @throws InventoryException if there was an error parsing the quanity
* to a positive integer.
*/
@Test
public void testAddInventory() throws InventoryException {
coffeeMaker.addInventory("4","7","0","9");
}
/**
* Given a coffee maker with the default inventory
* When we add inventory with malformed quantities (i.e., a negative
* quantity and a non-numeric string)
* Then we get an inventory exception
*
* @throws InventoryException if there was an error parsing the quanity
* to a positive integer.
*/
@Test(expected = InventoryException.class)
public void testAddInventoryException() throws InventoryException {
coffeeMaker.addInventory("4", "-1", "asdf", "3");
}
/**
* Given a coffee maker with one valid recipe
* When we make coffee, selecting the valid recipe and paying more than
* the coffee costs
* Then we get the correct change back.
*/
@Test
public void testMakeCoffee() {
coffeeMaker.addRecipe(recipe1);
assertEquals(25, coffeeMaker.makeCoffee(0, 75));
}
@Test
public void testAddRecipe1() {
Recipe temp;
boolean contains = false;
coffeeMaker.addRecipe(recipe1);
Recipe[] array = coffeeMaker.getRecipes();
for (int i = 0; i < array.length; i++) {
temp = array[i];
if (recipe1 == temp) {
contains = true;
}
}
assertTrue("Recipe not added.",contains);
}
@Test
public void testAddRecipe1F() {
Recipe temp;
boolean contains = false;
coffeeMaker.addRecipe(recipe1);
Recipe[] array = coffeeMaker.getRecipes();
for (int i = 0; i < array.length; i++) {
temp = array[i];
if (recipe1 == temp) {
contains = true;
}
}
assertFalse("Recipe not added.",contains);
}
// @Test
// public void testDeleteRecipe() {
// Recipe temp;
// boolean contains = false;
// coffeeMaker.addRecipe(recipe1);
// contains = false;
// //R1 will be the recipe in slot 0, because it was the first (and only) one added.
// String name = coffeeMaker.deleteRecipe(0);
// Recipe[] array_deleted = coffeeMaker.getRecipes();
// for (Recipe recipe : array_deleted) {
// if (recipe != null && recipe.getName() != "") {
// contains = true;
// }
// }
// assertFalse("Recipe was not deleted.",contains);
// assertTrue("Wrong name returned while deleting recipe.",recipe1.getName().equals(name));
//
// assertNull("Null was not returned while deleting a recipe that did not exist.",coffeeMaker.deleteRecipe(1));
// assertEquals("Incorrect return value while deleting a recipe that was already deleted.",
// "", coffeeMaker.deleteRecipe(0)); //TODO This recipe was already deleted. Should it be null instead of ""?
// }
}
|
package com.turing.excercise.array;
import com.turing.excercise.TestResultsHelper;
//Find Middle, Search in left for first occurrence, Search in right for last occurance.
class MySolution {
public int[] searchRange(int[] nums, int target) {
if (nums.length == 0) return new int[]{-1, -1};
if (nums.length == 1 && nums[0] == target) return new int[]{0, 0};
if (nums[0] == target && nums[nums.length - 1] == target) return new int[]{0, nums.length - 1};
int bsIndex = binarySearch(nums, 0, nums.length - 1, target);
if (bsIndex == -1) return new int[]{-1, -1};
int start = bsIndex, end = bsIndex;
if ((bsIndex - 1 >= 0 && nums[bsIndex - 1] < target)
&& (bsIndex + 1 < nums.length && nums[bsIndex + 1] > target)) return new int[]{bsIndex, bsIndex};
start = findSmallestIndex(nums, bsIndex, 0, target);
end = findLargestIndex(nums, bsIndex, nums.length - 1, target);
return new int[]{start, end};
}
int binarySearch(int[] nums, int low, int high, int target) {
if (high >= low) {
int mid = (high - low) / 2 + low;
if (nums[mid] == target) return mid;
if (nums[mid] > target) return binarySearch(nums, low, mid - 1, target);
else return binarySearch(nums, mid + 1, high, target);
}
return -1;
}
int findSmallestIndex(int[] nums, int start, int end, int target) {
int base = start;
int i = 0;
while (base >= 0) {
if (nums[base] != target) break;
base = base - (int) Math.pow(2, i);
i++;
}
if (base <= 0) {
base = 0;
while (nums[base] != target) {
base++;
}
return base;
}
if (nums[base + 1] == target) return base + 1;
return findSmallestIndex(nums, start - base, end, target);
}
int findLargestIndex(int[] nums, int start, int end, int target) {
int base = start;
int i = 0;
while (base < nums.length - 1) {
if (nums[base] != target) break;
base = base + (int) Math.pow(2, i);
i++;
}
if (base >= nums.length - 1) {
base = nums.length - 1;
while (nums[base] != target) {
base--;
}
return base;
}
if (nums[base - 1] == target) return base - 1;
return findSmallestIndex(nums, start + base, end, target);
}
}
public class RangeTargetSorted {
public int[] searchRange(int[] nums, int target) {
int firstOccurrence = this.findBound(nums, target, true);
if (firstOccurrence == -1) {
return new int[]{-1, -1};
}
int lastOccurrence = this.findBound(nums, target, false);
return new int[]{firstOccurrence, lastOccurrence};
}
private int findBound(int[] nums, int target, boolean isFirst) {
int N = nums.length;
int begin = 0, end = N - 1;
while (begin <= end) {
int mid = (begin + end) / 2;
if (nums[mid] == target) {
if (isFirst) {
// This means we found our lower bound.
if (mid == begin || nums[mid - 1] != target) {
return mid;
}
// Search on the left side for the bound.
end = mid - 1;
} else {
// This means we found our upper bound.
if (mid == end || nums[mid + 1] != target) {
return mid;
}
// Search on the right side for the bound.
begin = mid + 1;
}
} else if (nums[mid] > target) {
end = mid - 1;
} else {
begin = mid + 1;
}
}
return -1;
}
public void run() {
int[] testcase1 = new int[]{5, 7, 7, 8, 8, 10};
int target1 = 8;
int[] testcase2 = new int[]{5, 7, 7, 8, 8, 10};
int target2 = 6;
int[] testcase3 = new int[]{};
int target3 = 0;
int[] testcase4 = new int[]{8, 8, 8, 8, 8, 8};
int target4 = 8;
int[] testcase5 = new int[]{1, 2, 2};
int target5 = 2;
TestResultsHelper.verify("1", new int[]{3, 4}, this.searchRange(testcase1, target1));
TestResultsHelper.verify("2", new int[]{-1, -1}, this.searchRange(testcase2, target2));
TestResultsHelper.verify("3", new int[]{-1, -1}, this.searchRange(testcase3, target3));
TestResultsHelper.verify("4", new int[]{0, 5}, this.searchRange(testcase4, target4));
TestResultsHelper.verify("5", new int[]{1, 2}, this.searchRange(testcase5, target5));
}
public static void main(String[] args) {
new RangeTargetSorted().run();
}
}
|
/*-
* ============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.servicedecomposition.tasks;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.aai.domain.yang.CloudRegion;
import org.onap.aai.domain.yang.Configuration;
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.aai.domain.yang.GenericVnfs;
import org.onap.aai.domain.yang.L3Network;
import org.onap.aai.domain.yang.L3Networks;
import org.onap.aai.domain.yang.ServiceInstance;
import org.onap.aai.domain.yang.ServiceInstances;
import org.onap.aai.domain.yang.VolumeGroup;
import org.onap.aai.domain.yang.VolumeGroups;
import org.onap.so.bpmn.common.InjectionHelper;
import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceSubscription;
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
import org.onap.so.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.client.aai.entities.uri.AAIUriFactory;
import org.onap.so.client.graphinventory.entities.uri.Depth;
import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization;
import org.onap.so.db.catalog.client.CatalogDbClient;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.serviceinstancebeans.CloudConfiguration;
import org.onap.so.serviceinstancebeans.ModelInfo;
import org.onap.so.serviceinstancebeans.RequestDetails;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class BBInputSetupUtilsTest {
protected ObjectMapper mapper = new ObjectMapper();
private static final String RESOURCE_PATH = "src/test/resources/__files/ExecuteBuildingBlock/";
@InjectMocks
BBInputSetupUtils bbInputSetupUtils = new BBInputSetupUtils();
@Mock
protected CatalogDbClient MOCK_catalogDbClient;
@Mock
protected RequestsDbClient MOCK_requestsDbClient;
@Mock
protected AAIResourcesClient MOCK_aaiResourcesClient;
@Mock
protected InjectionHelper MOCK_injectionHelper;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Before
public void setup(){
doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
}
@Test
public void testGetCatalogServiceByModelUUID() throws JsonParseException, JsonMappingException, IOException {
Service expected = mapper.readValue(
new File(RESOURCE_PATH + "CatalogServiceExpected.json"), Service.class);
RequestDetails requestDetails = new RequestDetails();
ModelInfo modelInfo = new ModelInfo();
modelInfo.setModelVersionId("modelUUID");
requestDetails.setModelInfo(modelInfo);
doReturn(expected).when(MOCK_catalogDbClient).getServiceByID("modelUUID");
Service actual = bbInputSetupUtils.getCatalogServiceByModelUUID(modelInfo.getModelVersionId());
assertThat(actual, sameBeanAs(expected));
}
@Test
public void testGetCatalogServiceByModelVersionAndModelInvariantUUID() throws JsonParseException, JsonMappingException, IOException {
String modelVersion = "modelVersion";
String modelInvariantUUID = "modelInvariantUUID";
Service expectedService = mapper.readValue(
new File(RESOURCE_PATH + "CatalogServiceExpected.json"), Service.class);
doReturn(expectedService).when(MOCK_catalogDbClient).getServiceByModelVersionAndModelInvariantUUID(isA(String.class), isA(String.class));
Service actualService = bbInputSetupUtils.getCatalogServiceByModelVersionAndModelInvariantUUID(modelVersion, modelInvariantUUID);
assertThat(actualService, sameBeanAs(expectedService));
}
@Test
public void testGetVnfcInstanceGroups() throws JsonParseException, JsonMappingException, IOException {
VnfcInstanceGroupCustomization vnfc = mapper.readValue(
new File(RESOURCE_PATH + "VnfcInstanceGroupCustomization.json"), VnfcInstanceGroupCustomization.class);
String modelCustomizationUUID = "modelCustomizationUUID";
doReturn(Arrays.asList(vnfc)).when(MOCK_catalogDbClient).getVnfcInstanceGroupsByVnfResourceCust(isA(String.class));
List<VnfcInstanceGroupCustomization> actualVnfcList = bbInputSetupUtils.getVnfcInstanceGroups(modelCustomizationUUID);
assertThat(actualVnfcList, sameBeanAs(Arrays.asList(vnfc)));
}
@Test
public void testGetRequestDetails() throws JsonParseException, JsonMappingException, IOException {
InfraActiveRequests infraActiveRequest = mapper.readValue(
new File(RESOURCE_PATH + "InfraActiveRequestExpected.json"),
InfraActiveRequests.class);
RequestDetails expected = mapper.readValue(
new File(RESOURCE_PATH + "RequestDetailsExpected.json"),
RequestDetails.class);
String requestId = "requestId";
doReturn(infraActiveRequest).when(MOCK_requestsDbClient).getInfraActiveRequestbyRequestId(requestId);
RequestDetails actual = bbInputSetupUtils.getRequestDetails(requestId);
assertThat(actual, sameBeanAs(expected));
}
@Test
public void getRequestDetailsNullTest() throws IOException {
RequestDetails requestDetails = bbInputSetupUtils.getRequestDetails("");
assertNull(requestDetails);
}
@Test
public void testGetCloudRegion() {
CloudConfiguration cloudConfig = new CloudConfiguration();
cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
Optional<org.onap.aai.domain.yang.CloudRegion> expected = Optional.of(new org.onap.aai.domain.yang.CloudRegion());
expected.get().setCloudOwner("cloudOwner");
expected.get().setCloudRegionId("lcpCloudRegionId");
doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.CloudRegion.class,
AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudConfig.getCloudOwner(),
cloudConfig.getLcpCloudRegionId()));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudConfig.getCloudOwner(),
cloudConfig.getLcpCloudRegionId());
bbInputSetupUtils.getCloudRegion(cloudConfig);
verify(MOCK_aaiResourcesClient, times(1)).get(CloudRegion.class, expectedUri);
}
@Test
public void testGetCloudRegionExceptionTest() {
CloudConfiguration cloudConfig = new CloudConfiguration();
cloudConfig.setLcpCloudRegionId("lcpCloudRegionId");
RequestDetails requestDetails = new RequestDetails();
requestDetails.setCloudConfiguration(cloudConfig);
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfig);
assertNull(cloudRegion);
}
@Test
public void testGetCloudRegionEmptyId() {
CloudConfiguration cloudConfig = new CloudConfiguration();
cloudConfig.setLcpCloudRegionId("");
RequestDetails requestDetails = new RequestDetails();
requestDetails.setCloudConfiguration(cloudConfig);
CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfig);
assertNull(cloudRegion);
}
@Test
public void testGetCloudRegionEmptyConfiguration() {
RequestDetails requestDetails = new RequestDetails();
CloudRegion cloudRegion = bbInputSetupUtils.getCloudRegion(requestDetails.getCloudConfiguration());
assertNull(cloudRegion);
}
@Test
public void testGetAAIInstanceGroup() {
Optional<org.onap.aai.domain.yang.InstanceGroup> expected = Optional.of(new org.onap.aai.domain.yang.InstanceGroup());
String instanceGroupId = "instanceGroupId";
expected.get().setId(instanceGroupId);
doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.InstanceGroup.class,
AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId);
bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.InstanceGroup.class, expectedUri);
}
@Test
public void testGetAAIInstanceGroupThrowNotFound() {
String instanceGroupId = "instanceGroupId";
doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.InstanceGroup.class,
AAIUriFactory.createResourceUri(AAIObjectType.INSTANCE_GROUP, instanceGroupId));
org.onap.aai.domain.yang.InstanceGroup actual = bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
assertNull(actual);
}
@Test
public void testGetAAICustomer() {
Optional<org.onap.aai.domain.yang.Customer> expected = Optional.of(new org.onap.aai.domain.yang.Customer());
String globalSubscriberId = "globalSubscriberId";
expected.get().setGlobalCustomerId(globalSubscriberId);
doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.Customer.class,
AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId);
bbInputSetupUtils.getAAICustomer(globalSubscriberId);
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.Customer.class, expectedUri);
}
@Test
public void testGetAAICustomerThrowNotFound() {
String globalSubscriberId = "globalSubscriberId";
doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.Customer.class,
AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalSubscriberId));
org.onap.aai.domain.yang.Customer actual = bbInputSetupUtils.getAAICustomer(globalSubscriberId);
assertNull(actual);
}
@Test
public void testGetAAIServiceSubscription() {
Optional<org.onap.aai.domain.yang.ServiceSubscription> expected = Optional.of(new org.onap.aai.domain.yang.ServiceSubscription());
String globalSubscriberId = "globalSubscriberId";
String subscriptionServiceType = "subscriptionServiceType";
expected.get().setServiceType(subscriptionServiceType);
doReturn(expected).when(MOCK_aaiResourcesClient).get(org.onap.aai.domain.yang.ServiceSubscription.class,
AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId,
subscriptionServiceType));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId,
subscriptionServiceType);
bbInputSetupUtils.getAAIServiceSubscription(globalSubscriberId, subscriptionServiceType);
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceSubscription.class, expectedUri);
}
@Test
public void testGetAAIServiceSubscriptionErrors() {
String globalSubId = null;
String subServiceType = null;
org.onap.aai.domain.yang.ServiceSubscription actual = bbInputSetupUtils.getAAIServiceSubscription(globalSubId, subServiceType);
assertNull(actual);
String globalSubId2 = "";
String subServiceType2 = "";
org.onap.aai.domain.yang.ServiceSubscription actual2 = bbInputSetupUtils.getAAIServiceSubscription(globalSubId2, subServiceType2);
assertNull(actual2);
String globalSubId3 = "";
String subServiceType3 = null;
org.onap.aai.domain.yang.ServiceSubscription actual3 = bbInputSetupUtils.getAAIServiceSubscription(globalSubId3, subServiceType3);
assertNull(actual3);
String globalSubId4 = null;
String subServiceType4 = "";
org.onap.aai.domain.yang.ServiceSubscription actual4 = bbInputSetupUtils.getAAIServiceSubscription(globalSubId4, subServiceType4);
assertNull(actual4);
}
@Test
public void testGetAAIServiceSubscriptionThrowNotFound() {
String globalSubscriberId = "globalSubscriberId";
String subscriptionServiceType = "subscriptionServiceType";
doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient)
.get(org.onap.aai.domain.yang.ServiceSubscription.class, AAIUriFactory.createResourceUri(
AAIObjectType.SERVICE_SUBSCRIPTION, globalSubscriberId, subscriptionServiceType));
org.onap.aai.domain.yang.ServiceSubscription actual = bbInputSetupUtils
.getAAIServiceSubscription(globalSubscriberId, subscriptionServiceType);
assertNull(actual);
}
@Test
public void testGetAAIServiceInstanceById() {
String serviceInstanceId = "serviceInstanceId";
ServiceInstance expectedServiceInstance = new ServiceInstance();
doReturn(Optional.of(expectedServiceInstance)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
assertThat(actualServiceInstance, sameBeanAs(expectedServiceInstance));
}
@Test
public void testGetAAIServiceInstanceByIdThrowNotFound() {
String serviceInstanceId = "serviceInstanceId";
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
assertNull(actualServiceInstance);
}
@Test
public void testGetAAIServiceInstanceByIdAndCustomer() {
String globalCustomerId = "globalCustomerId";
String serviceType = "serviceType";
String serviceInstanceId = "serviceInstanceId";
ServiceInstance expected = new ServiceInstance();
expected.setServiceInstanceId(serviceInstanceId);
doReturn(Optional.of(expected)).when(MOCK_aaiResourcesClient).get(isA(Class.class),
isA(AAIResourceUri.class));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(
AAIObjectType.SERVICE_INSTANCE, globalCustomerId, serviceType, serviceInstanceId).depth(Depth.TWO);
this.bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(globalCustomerId, serviceType, serviceInstanceId);
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceInstance.class, expectedUri);
}
@Test
public void testGetAAIServiceInstanceByIdAndCustomerThrowNotFound() {
String globalCustomerId = "globalCustomerId";
String serviceType = "serviceType";
String serviceInstanceId = "serviceInstanceId";
doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient();
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class),
isA(AAIResourceUri.class));
ServiceInstance actual = this.bbInputSetupUtils
.getAAIServiceInstanceByIdAndCustomer(globalCustomerId, serviceType, serviceInstanceId);
assertNull(actual);
}
@Test
public void testGetAAIServiceInstanceByName() throws Exception {
String serviceInstanceName = "serviceInstanceName";
ServiceInstance expectedServiceInstance = new ServiceInstance();
expectedServiceInstance.setServiceInstanceId("serviceInstanceId");
ServiceSubscription serviceSubscription = new ServiceSubscription();
serviceSubscription.setServiceType("serviceType");
Customer customer = new Customer();
customer.setGlobalCustomerId("globalCustomerId");
customer.setServiceSubscription(serviceSubscription);
ServiceInstances serviceInstances = new ServiceInstances();
serviceInstances.getServiceInstance().add(expectedServiceInstance);
doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, customer.getGlobalCustomerId(),
customer.getServiceSubscription().getServiceType())
.queryParam("service-instance-name", serviceInstanceName).depth(Depth.TWO);
bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.ServiceInstances.class, expectedUri);
}
@Test
public void testGetAAIServiceInstanceByNameException() throws Exception {
expectedException.expect(Exception.class);
String serviceInstanceName = "serviceInstanceName";
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setServiceInstanceId("serviceInstanceId");
ServiceSubscription serviceSubscription = new ServiceSubscription();
serviceSubscription.setServiceType("serviceType");
Customer customer = new Customer();
customer.setGlobalCustomerId("globalCustomerId");
customer.setServiceSubscription(serviceSubscription);
ServiceInstances serviceInstances = new ServiceInstances();
serviceInstances.getServiceInstance().add(serviceInstance);
serviceInstances.getServiceInstance().add(serviceInstance);
doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
}
@Test
public void testGetAAIServiceInstanceByNameNull() throws Exception {
String serviceInstanceName = "serviceInstanceName";
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setServiceInstanceId("serviceInstanceId");
ServiceSubscription serviceSubscription = new ServiceSubscription();
serviceSubscription.setServiceType("serviceType");
Customer customer = new Customer();
customer.setGlobalCustomerId("globalCustomerId");
customer.setServiceSubscription(serviceSubscription);
ServiceInstances serviceInstances = new ServiceInstances();
serviceInstances.getServiceInstance().add(serviceInstance);
serviceInstances.getServiceInstance().add(serviceInstance);
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
ServiceInstance actualServiceInstance = bbInputSetupUtils.getAAIServiceInstanceByName(serviceInstanceName, customer);
assertNull(actualServiceInstance);
}
@Test
public void testGetOptionalAAIServiceInstanceByNameException() throws Exception {
expectedException.expect(Exception.class);
String globalCustomerId = "globalCustomerId";
String serviceType = "serviceType";
String serviceInstanceId = "serviceInstanceId";
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setServiceInstanceId("serviceInstanceId");
serviceInstance.setServiceType(serviceType);
serviceInstance.setServiceInstanceName("serviceInstanceName");
ServiceInstances serviceInstances = new ServiceInstances();
serviceInstances.getServiceInstance().add(serviceInstance);
serviceInstances.getServiceInstance().add(serviceInstance);
doReturn(Optional.of(serviceInstances)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, serviceInstanceId);
}
@Test
public void testGetOptionalAAIServiceInstanceByNameNull() throws Exception {
String globalCustomerId = "globalCustomerId";
String serviceType = "serviceType";
String serviceInstanceId = "serviceInstanceId";
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
Optional<ServiceInstance> actual = this.bbInputSetupUtils
.getAAIServiceInstanceByName(globalCustomerId, serviceType, serviceInstanceId);
assertThat(actual, sameBeanAs(Optional.empty()));
}
@Test
public void testGetCatalogInstanceGroup() throws JsonParseException, JsonMappingException, IOException {
String modelUUID = "modelUUID";
org.onap.so.db.catalog.beans.InstanceGroup expectedInstanceGroup = mapper.readValue(
new File(RESOURCE_PATH + "InstanceGroup.json"), org.onap.so.db.catalog.beans.InstanceGroup.class);
doReturn(expectedInstanceGroup).when(MOCK_catalogDbClient).getInstanceGroupByModelUUID(isA(String.class));
org.onap.so.db.catalog.beans.InstanceGroup actualInstanceGroup = bbInputSetupUtils.getCatalogInstanceGroup(modelUUID);
assertThat(actualInstanceGroup, sameBeanAs(expectedInstanceGroup));
}
@Test
public void testGetCollectionResourceInstanceGroupCustomization() {
String modelCustomizationUUID = "modelCustomizationUUID";
CollectionResourceInstanceGroupCustomization expectedCollection = new CollectionResourceInstanceGroupCustomization();
doReturn(Arrays.asList(expectedCollection)).when(MOCK_catalogDbClient)
.getCollectionResourceInstanceGroupCustomizationByModelCustUUID(modelCustomizationUUID);
List<CollectionResourceInstanceGroupCustomization> actualCollection = bbInputSetupUtils
.getCollectionResourceInstanceGroupCustomization(modelCustomizationUUID);
assertThat(actualCollection, sameBeanAs(Arrays.asList(expectedCollection)));
}
@Test
public void testGetAAIGenericVnf() throws JsonParseException, JsonMappingException, IOException {
String vnfId = "vnfId";
GenericVnf expectedAaiVnf = mapper.readValue(
new File(RESOURCE_PATH + "aaiGenericVnfInput.json"), GenericVnf.class);
doReturn(Optional.of(expectedAaiVnf)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE);
GenericVnf actualAaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
assertThat(actualAaiVnf, sameBeanAs(expectedAaiVnf));
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.GenericVnf.class, expectedUri);
}
@Test
public void testGetAAIConfiguration() throws JsonParseException, JsonMappingException, IOException {
String configurationId = "configurationId";
Configuration expectedAaiConfiguration = mapper.readValue(
new File(RESOURCE_PATH + "ConfigurationInput.json"), Configuration.class);
doReturn(Optional.of(expectedAaiConfiguration)).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId).depth(Depth.ONE);
bbInputSetupUtils.getAAIConfiguration(configurationId);
verify(MOCK_aaiResourcesClient, times(1)).get(org.onap.aai.domain.yang.Configuration.class, expectedUri);
}
@Test
public void testGetAAIGenericVnfThrowNotFound() throws JsonParseException, JsonMappingException, IOException {
String vnfId = "vnfId";
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(isA(Class.class), isA(AAIResourceUri.class));
GenericVnf actualAaiVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
assertNull(actualAaiVnf);
}
@Test
public void testGetAAIResourceDepthOne() {
String vnfId = "vnfId";
AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
AAIResourceUri expectedUri = aaiResourceUri.clone().depth(Depth.ONE);
AAIResourceUri aaiResourceUriClone = aaiResourceUri.clone();
bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
verify(MOCK_aaiResourcesClient, times(1)).get(expectedUri);
assertEquals("Uri should not have changed", aaiResourceUriClone.build(), aaiResourceUri.build());
}
@Test
public void testGetAAIResourceDepthTwo() {
String vnfId = "vnfId";
AAIResourceUri aaiResourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId);
AAIResourceUri expectedUri = aaiResourceUri.clone().depth(Depth.TWO);
AAIResourceUri aaiResourceUriClone = aaiResourceUri.clone();
bbInputSetupUtils.getAAIResourceDepthTwo(aaiResourceUri);
verify(MOCK_aaiResourcesClient, times(1)).get(expectedUri);
assertEquals("Uri should not have changed", aaiResourceUriClone.build(), aaiResourceUri.build());
}
@Test
public void getRelatedNetworkByNameFromServiceInstanceTest() throws Exception {
Optional<L3Networks> expected = Optional.of(new L3Networks());
L3Network network = new L3Network();
network.setNetworkId("id123");
network.setNetworkName("name123");
expected.get().getL3Network().add(network);
doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
Optional<L3Network> actual = this.bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance("id123", "name123");
assertEquals(actual.get().getNetworkId(), expected.get().getL3Network().get(0).getNetworkId());
}
@Test
public void getRelatedNetworkByNameFromServiceInstanceMultipleNetworksExceptionTest() throws Exception {
expectedException.expect(Exception.class);
String serviceInstanceId = "serviceInstanceId";
String networkName = "networkName";
L3Network network = new L3Network();
network.setNetworkId("id123");
network.setNetworkName("name123");
L3Networks expected = new L3Networks();
expected.getL3Network().add(network);
expected.getL3Network().add(network);
doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName);
}
@Test
public void getRelatedNetworkByNameFromServiceInstanceNotFoundTest() throws Exception {
String serviceInstanceId = "serviceInstanceId";
String networkName = "networkName";
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class));
Optional<L3Network> actualNetwork = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName);
assertEquals(Optional.empty(), actualNetwork);
}
@Test
public void getRelatedVnfByNameFromServiceInstanceTest() throws Exception {
Optional<GenericVnfs> expected = Optional.of(new GenericVnfs());
GenericVnf vnf = new GenericVnf();
vnf.setVnfId("id123");
vnf.setVnfName("name123");
expected.get().getGenericVnf().add(vnf);
doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
Optional<GenericVnf> actual = this.bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance("id123", "name123");
assertEquals(actual.get().getVnfId(), expected.get().getGenericVnf().get(0).getVnfId());
}
@Test
public void getRelatedVnfByNameFromServiceInstanceMultipleVnfsExceptionTest() throws Exception {
expectedException.expect(Exception.class);
String serviceInstanceId = "serviceInstanceId";
String vnfName = "vnfName";
GenericVnf vnf = new GenericVnf();
vnf.setVnfId("id123");
vnf.setVnfName("name123");
GenericVnfs expectedVnf = new GenericVnfs();
expectedVnf.getGenericVnf().add(vnf);
expectedVnf.getGenericVnf().add(vnf);
doReturn(expectedVnf).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName);
}
@Test
public void getRelatedVnfByNameFromServiceInstanceNotFoundTest() throws Exception {
String serviceInstanceId = "serviceInstanceId";
String vnfName = "vnfName";
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class));
Optional<GenericVnf> actualVnf = this.bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName);
assertEquals(actualVnf, Optional.empty());
}
@Test
public void getRelatedVolumeGroupByNameFromVnfTest() throws Exception {
Optional<VolumeGroups> expected = Optional.of(new VolumeGroups());
VolumeGroup volumeGroup = new VolumeGroup();
volumeGroup.setVolumeGroupId("id123");
volumeGroup.setVolumeGroupName("name123");
expected.get().getVolumeGroup().add(volumeGroup);
doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
Optional<VolumeGroup> actual = this.bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "name123");
assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId());
}
@Test
public void getRelatedVolumeGroupByNameFromVnfMultipleVolumeGroupsExceptionTest() throws Exception {
expectedException.expect(Exception.class);
String vnfId = "vnfId";
String volumeGroupName = "volumeGroupName";
VolumeGroup volumeGroup = new VolumeGroup();
volumeGroup.setVolumeGroupId("id123");
volumeGroup.setVolumeGroupName("name123");
VolumeGroups expectedVolumeGroup = new VolumeGroups();
expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName);
}
@Test
public void getRelatedVolumeGroupByNameFromVnfNotFoundTest() throws Exception {
String vnfId = "vnfId";
String volumeGroupName = "volumeGroupName";
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
Optional<VolumeGroup> actualVolumeGroup = bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName);
assertEquals(actualVolumeGroup, Optional.empty());
}
@Test
public void getRelatedVolumeGroupByNameFromVfModuleTest() throws Exception {
Optional<VolumeGroups> expected = Optional.of(new VolumeGroups());
VolumeGroup volumeGroup = new VolumeGroup();
volumeGroup.setVolumeGroupId("id123");
volumeGroup.setVolumeGroupName("name123");
expected.get().getVolumeGroup().add(volumeGroup);
doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
Optional<VolumeGroup> actual = this.bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule("id123", "id123", "name123");
assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId());
}
@Test
public void getRelatedVolumeGroupByNameFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception {
expectedException.expect(Exception.class);
String vnfId = "vnfId";
String volumeGroupId = "volumeGroupId";
String volumeGroupName = "volumeGroupName";
VolumeGroup volumeGroup = new VolumeGroup();
volumeGroup.setVolumeGroupId("id123");
volumeGroup.setVolumeGroupName("name123");
VolumeGroups expectedVolumeGroup = new VolumeGroups();
expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
expectedVolumeGroup.getVolumeGroup().add(volumeGroup);
doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName);
}
@Test
public void getRelatedVolumeGroupByNameFromVfModuleNotFoundTest() throws Exception {
String vnfId = "vnfId";
String volumeGroupId = "volumeGroupId";
String volumeGroupName = "volumeGroupName";
doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class));
Optional<VolumeGroup> actualVolumeGroup = bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName);
assertEquals(actualVolumeGroup, Optional.empty());
}
}
|
package com.desgreen.education.siapp.ui.views.master_matpel;
import com.desgreen.education.siapp.AppPublicService;
import com.desgreen.education.siapp.backend.model.FDivision;
import com.desgreen.education.siapp.backend.model.FMatPel;
import com.desgreen.education.siapp.backend.model_sample.DummyData;
import com.desgreen.education.siapp.security_config.AuthUserDetailsService;
import com.desgreen.education.siapp.security_model.Role;
import com.desgreen.education.siapp.ui.MainLayout;
import com.desgreen.education.siapp.ui.components.FlexBoxLayout;
import com.desgreen.education.siapp.ui.components.ListItem;
import com.desgreen.education.siapp.ui.components.detailsdrawer.DetailsDrawer;
import com.desgreen.education.siapp.ui.components.detailsdrawer.DetailsDrawerFooter;
import com.desgreen.education.siapp.ui.components.detailsdrawer.DetailsDrawerHeader;
import com.desgreen.education.siapp.ui.components.navigation.bar.AppBar;
import com.desgreen.education.siapp.ui.layout.size.Horizontal;
import com.desgreen.education.siapp.ui.layout.size.Right;
import com.desgreen.education.siapp.ui.layout.size.Top;
import com.desgreen.education.siapp.ui.layout.size.Vertical;
import com.desgreen.education.siapp.ui.util.LumoStyles;
import com.desgreen.education.siapp.ui.util.UIUtils;
import com.desgreen.education.siapp.ui.util.css.BoxSizing;
import com.desgreen.education.siapp.ui.views.SplitViewFrame;
import com.vaadin.componentfactory.ToggleButton;
import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.converter.StringToBigDecimalConverter;
import com.vaadin.flow.data.provider.DataProvider;
import com.vaadin.flow.data.provider.ListDataProvider;
import com.vaadin.flow.data.renderer.ComponentRenderer;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.annotation.SpringComponent;
import com.vaadin.flow.spring.annotation.UIScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Objects;
@Secured({Role.ADMIN, Role.MNU_MATA_PELAJARAN})
@UIScope
@SpringComponent
@Route(value = "MatPelView", layout = MainLayout.class)
@PageTitle("MatPelView")
public class MatPelView extends SplitViewFrame {
protected MatPelModel model;
protected MatPelController controller;
protected MatPelListener listener;
@Autowired
private AppPublicService appPublicService;
@Autowired
public AuthUserDetailsService authUserDetailsService;
protected Grid<FMatPel> grid;
protected ListDataProvider<FMatPel> dataProvider;
protected DetailsDrawer detailsDrawer;
protected DetailsDrawerHeader detailsDrawerHeader;
private AppBar appBar;
private Button btnReloadFromDB;
private Button btnSearchForm;
private Button btnNewForm;
private Button btnDeleteDeleteForm;
protected Binder<FMatPel> binder = new BeanValidationBinder<>(FMatPel.class);
protected FMatPel currentDomain;
public MatPelView() {
super();
/**
* Init Dummy
*/
}
@PostConstruct
private void init(){
model = new MatPelModel(authUserDetailsService, appPublicService);
controller = new MatPelController(model, this);
// model = controller.model;
listener = controller;
// initAppBar();
// setViewContent(createContent());
// setViewDetails(createDetailsDrawer());
// filter();
/**
* Init Data
*/
}
@Override
protected void onAttach(AttachEvent attachEvent) {
super.onAttach(attachEvent);
initAppBar();
setViewContent(createContent());
setViewDetails(createDetailsDrawer());
filter();
binder.readBean(new FMatPel());
detailsDrawer.setContent(createDetails());
}
private void initAppBar() {
appBar = MainLayout.get().getAppBar();
appBar.searchModeOff();
btnSearchForm = appBar.addActionItem(VaadinIcon.SEARCH);
btnReloadFromDB = appBar.addActionItem(VaadinIcon.REFRESH);
btnNewForm = appBar.addActionItem(VaadinIcon.PLUS);
btnDeleteDeleteForm = appBar.addActionItem(VaadinIcon.TRASH);
btnNewForm.addThemeVariants(ButtonVariant.MATERIAL_OUTLINED);
btnDeleteDeleteForm.addThemeVariants(ButtonVariant.MATERIAL_OUTLINED, ButtonVariant.LUMO_ERROR);
btnReloadFromDB.addClickListener(e -> listener.aksiBtnReloadFromDb());
btnSearchForm.addClickListener(e -> appBar.searchModeOn());
btnNewForm.addClickListener(e -> listener.aksiBtnNewForm());
btnDeleteDeleteForm.addClickListener(e -> listener.aksiBtnDeleteForm());
appBar.addSearchListener( e -> listener.valueChangeListenerSearch(e));
/**
* SAVE DAN CANCEL
* berada pada createDetailsDrawer()
*/
}
private Component createContent() {
FlexBoxLayout content = new FlexBoxLayout(createGrid());
content.setBoxSizing(BoxSizing.BORDER_BOX);
content.setHeightFull();
content.setPadding(Horizontal.RESPONSIVE_X, Top.RESPONSIVE_X);
return content;
}
private Grid createGrid() {
grid = new Grid<>();
grid.addSelectionListener(event -> event.getFirstSelectedItem()
.ifPresent(this::showDetails));
//###### FROM MODEL
// dataProvider = DataProvider.ofCollection(DummyData.getFMatPels());
// dataProvider = DataProvider.ofCollection(new ArrayList<>());
dataProvider = DataProvider.ofCollection( model.mapHeader.values() );
grid.setDataProvider(dataProvider);
grid.setHeightFull();
grid.addColumn(FMatPel::getId)
.setAutoWidth(true)
.setFlexGrow(0)
.setFrozen(true)
.setHeader("ID")
.setSortable(true);
grid.addColumn(new ComponentRenderer<>(this::createDetilInfo))
.setAutoWidth(true)
.setHeader("Name MatPel")
.setComparator(FMatPel::getDescription)
.setSortable(true);
grid.addColumn(new ComponentRenderer<>(this::createActive))
.setAutoWidth(true)
.setFlexGrow(0)
.setHeader("Active")
.setTextAlign(ColumnTextAlign.END);
grid.addColumn(new ComponentRenderer<>(this::createDivision))
.setAutoWidth(true)
.setFlexGrow(0)
.setHeader("Division")
.setTextAlign(ColumnTextAlign.END)
.setSortable(true);
return grid;
}
private Component createDetilInfo(FMatPel fMatPel) {
ListItem item = new ListItem(fMatPel.getDescription(),
fMatPel.getKode1());
item.setPadding(Vertical.XS);
item.setSpacing(Right.S);
item.setPrefix(new Image(DummyData.getImageSource(fMatPel.getLogoIndex()), "Logo"));
return item;
}
private Component createActive(FMatPel fMatPel) {
Icon icon;
if (fMatPel.isStatActive()) {
icon = UIUtils.createPrimaryIcon(VaadinIcon.CHECK);
}else {
icon = UIUtils.createDisabledIcon(VaadinIcon.CLOSE);
}
return icon;
}
private Component createDivision(FMatPel fMatPel) {
return UIUtils.createBoldLabel(fMatPel.getFdivisionBean()!=null? fMatPel.getFdivisionBean().getDescription(): "");
}
private Component createComboDivisionInfo(FDivision fDivision) {
ListItem item = new ListItem( fDivision.getDescription(),
fDivision.getFcompanyBean().getDescription());
item.setPadding(Vertical.XS);
item.setSpacing(Right.M);
return item;
}
private Component createComboLogoIndex(int i) {
ListItem item = new ListItem("Logo-" + i + ".png");
item.setPadding(Vertical.XS);
item.setSpacing(Right.M);
Image logo = new Image(UIUtils.IMG_PATH + "logos/" + i + ".png", "logo");
logo.setMaxHeight("25px");
logo.addClassName(LumoStyles.Size.S);
item.setPrefix(logo);
return item;
}
// private Component createComboLogoIndex(Integer i) {
// ListItem item = new ListItem("OKE bos");
// item.setPadding(Vertical.XS);
// item.setPrefix(new Image(DummyData.getImageSource(), "Company logo"));
// item.setSpacing(Right.M);
// return item;
// }
// private Component createMatPelDateFrom(FMatPel fMatPel) {
// return new Span(UIUtils.formatDate(fMatPel.getMatPelFrom()));
// }
// private Component createMatPelDateTo(FMatPel fMatPel) {
// return new Span(UIUtils.formatDate(fMatPel.getMatPelTo()));
// }
DetailsDrawerFooter footer = new DetailsDrawerFooter();
private DetailsDrawer createDetailsDrawer() {
detailsDrawer = new DetailsDrawer(DetailsDrawer.Position.RIGHT);
// Header
detailsDrawerHeader = new DetailsDrawerHeader("");
detailsDrawerHeader.addCloseListener(buttonClickEvent -> detailsDrawer.hide());
detailsDrawer.setHeader(detailsDrawerHeader);
// Footer
footer.addSaveListener(e -> {
listener.aksiBtnSaveForm();
// UIUtils.showNotification("Changes saved.");
});
footer.addCancelListener(e -> {
detailsDrawer.hide();
listener.aksiBtnCancelForm();
});
detailsDrawer.setFooter(footer);
return detailsDrawer;
}
protected void showDetails(FMatPel fMatPel) {
if (fMatPel == null) {
fMatPel = new FMatPel();
}
// delete.setVisible(!product.isNewProduct());
currentDomain = fMatPel;
try {
binder.readBean(fMatPel);
}catch (Exception ex) {ex.printStackTrace();}
//delete.setVisible(!product.isNewProduct());
detailsDrawerHeader.setTitle(fMatPel.getDescription());
// detailsDrawer.setContent(createDetails(fMatPel));
detailsDrawer.show();
}
/**
* FORM COMPONENT
* dipanggil sekali saja
*/
private final TextField kode1 = new TextField();
private final TextField description = new TextField();
private final TextArea notes = new TextArea();
private final ComboBox<Integer> comboLogoIndex = new ComboBox<Integer>();
private final ComboBox<FDivision> comboFDivision = new ComboBox<FDivision>();
private final ToggleButton toggleStatActive = new ToggleButton();
// private FormLayout createDetails(FMatPel fMatPel) {
private FormLayout createDetails() {
// System.out.println(fMatPel.getAddress1());
/**
* Re Binding Datata
*/
binder.bindInstanceFields(this);
binder.forField(kode1).asRequired().bind(FMatPel::getKode1, FMatPel::setKode1);
binder.forField(description).asRequired().bind(FMatPel::getDescription, FMatPel::setDescription);
// .withConverter(new StringToBooleanConverter("", "Active", "Non-Active"))
// .bind(FMatPel::isStatActive, FMatPel::setStatActive);
binder.forField(comboLogoIndex)
.asRequired()
.bind(FMatPel::getLogoIndex, FMatPel::setLogoIndex);
binder.forField(comboFDivision)
.asRequired()
.bind(FMatPel::getFdivisionBean, FMatPel::setFdivisionBean);
binder.forField(toggleStatActive)
.bind(FMatPel::isStatActive, FMatPel::setStatActive);
/**
* Decorate the Form View
*/
kode1.setWidthFull();
description.setWidthFull();
notes.setWidthFull();
// checkStatusActive.setLabel("Active");
// checkStatusActive.setValue(true);
toggleStatActive.setLabel("Active");
toggleStatActive.addValueChangeListener(e -> {
if (e.getValue()==true) {
toggleStatActive.setLabel("Active");
}else {
toggleStatActive.setLabel("Non-active");
}
});
comboFDivision.setItems(model.listFDivision);
comboFDivision.setWidthFull();
comboFDivision.setItemLabelGenerator(p -> p.getKode1() + " " + p.getDescription());
// comboFDivision.setRenderer(new ComponentRenderer<>(item -> new Span(item.getDescription())));
comboFDivision.setRenderer(new ComponentRenderer<>(this::createComboDivisionInfo ));
comboLogoIndex.setItems(model.listLogoIndex);
comboLogoIndex.setWidthFull();
comboLogoIndex.setItemLabelGenerator(i -> "Logo" + "-" + i + ".png" );
comboLogoIndex.setRenderer(new ComponentRenderer<>(this::createComboLogoIndex ));
// comboLogoIndex.setRenderer(new ComponentRenderer<>(i -> {
// Image logo = new Image(UIUtils.IMG_PATH + "logos/" + i + ".png", "logo");
//// Icon logo = new Icon(VaadinIcon.FEMALE);
// logo.setMaxHeight("20px");
// Div div = new Div();
// div.setMaxHeight("20px");
// div.add(logo);
// div.add(UIUtils.createBoldLabel("logo-" + i +".png"));
//
// return div;
// }));
kode1.setValueChangeMode(ValueChangeMode.EAGER);
description.setValueChangeMode(ValueChangeMode.EAGER);
// Form layout
FormLayout form = new FormLayout();
form.addClassNames(LumoStyles.Padding.Bottom.L,
LumoStyles.Padding.Horizontal.L, LumoStyles.Padding.Top.S);
form.setResponsiveSteps(
new FormLayout.ResponsiveStep("0", 1,
FormLayout.ResponsiveStep.LabelsPosition.TOP),
new FormLayout.ResponsiveStep("21em", 2,
FormLayout.ResponsiveStep.LabelsPosition.TOP));
form.addFormItem(kode1, "Kode1");
// form.addFormItem(lastName, "Last Name");
FormLayout.FormItem descriptionItem = form.addFormItem(description, "Deskripsi");
FormLayout.FormItem notesItem = form.addFormItem(notes, "Catatan");
FormLayout.FormItem toggleStatusItem = form.addFormItem(toggleStatActive, "Status");
FormLayout.FormItem comboFDivisionItem = form.addFormItem(comboFDivision, "Division");
FormLayout.FormItem comboLogoIndexItem = form.addFormItem(comboLogoIndex, "Logo");
UIUtils.setColSpan(2, descriptionItem, notesItem, comboFDivisionItem, comboLogoIndexItem, toggleStatusItem);
// enable/disable save button while editing
binder.addStatusChangeListener(event -> {
final boolean isValid = !event.hasValidationErrors();
final boolean hasChanges = binder.hasChanges();
// save.setEnabled(hasChanges && isValid);
// discard.setEnabled(hasChanges);
footer.setEnabled(hasChanges && isValid);
});
return form;
}
private static class PriceConverter extends StringToBigDecimalConverter {
public PriceConverter() {
super(BigDecimal.ZERO, "Cannot convert value to a number.");
}
@Override
protected NumberFormat getFormat(Locale locale) {
// Always display currency with two decimals
final NumberFormat format = super.getFormat(locale);
if (format instanceof DecimalFormat) {
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
}
return format;
}
}
private void filter() {
// dataProvider.setFilterByValue(FMatPel::getRole, FMatPel.Role.ACCOUNTANT);
}
String filterText = "";
public void setFilter(String filterText) {
Objects.requireNonNull(filterText, "Filter text cannot be null.");
if (Objects.equals(this.filterText, filterText.trim())) {
return;
}
this.filterText = filterText.trim().toLowerCase(Locale.ENGLISH);
dataProvider.setFilter(domain -> passesFilter(domain.getKode1(), this.filterText)
|| passesFilter(domain.getDescription(), this.filterText)
);
}
private boolean passesFilter(Object object, String filterText) {
return object != null && object.toString().toLowerCase(Locale.ENGLISH)
.contains(filterText);
}
}
|
package sfrerichs.service;
import io.github.jhipster.config.JHipsterProperties;
import sfrerichs.config.audit.AuditEventConverter;
import sfrerichs.repository.PersistenceAuditEventRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
/**
* Service for managing audit events.
* <p>
* This is the default implementation to support SpringBoot Actuator {@code AuditEventRepository}.
*/
@Service
@Transactional
public class AuditEventService {
private final Logger log = LoggerFactory.getLogger(AuditEventService.class);
private final JHipsterProperties jHipsterProperties;
private final PersistenceAuditEventRepository persistenceAuditEventRepository;
private final AuditEventConverter auditEventConverter;
public AuditEventService(
PersistenceAuditEventRepository persistenceAuditEventRepository,
AuditEventConverter auditEventConverter, JHipsterProperties jhipsterProperties) {
this.persistenceAuditEventRepository = persistenceAuditEventRepository;
this.auditEventConverter = auditEventConverter;
this.jHipsterProperties = jhipsterProperties;
}
/**
* Old audit events should be automatically deleted after 30 days.
*
* This is scheduled to get fired at 12:00 (am).
*/
@Scheduled(cron = "0 0 12 * * ?")
public void removeOldAuditEvents() {
persistenceAuditEventRepository
.findByAuditEventDateBefore(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod(), ChronoUnit.DAYS))
.forEach(auditEvent -> {
log.debug("Deleting audit data {}", auditEvent);
persistenceAuditEventRepository.delete(auditEvent);
});
}
public Page<AuditEvent> findAll(Pageable pageable) {
return persistenceAuditEventRepository.findAll(pageable)
.map(auditEventConverter::convertToAuditEvent);
}
public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) {
return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable)
.map(auditEventConverter::convertToAuditEvent);
}
public Optional<AuditEvent> find(Long id) {
return persistenceAuditEventRepository.findById(id)
.map(auditEventConverter::convertToAuditEvent);
}
}
|
package com.boot.core.util;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.util.*;
/**
* HSSFWorkbook excel的文档对象
* HSSFSheet excel的表单
* HSSFRow excel的行
* HSSFCell excel的格子单元
* HSSFFont excel字体
* HSSFCellStyle cell样式
*/
public class ExcelUtil {
/**
* 导出Excel
*
* @param sheetName sheet名称
* @param title 标题
* @param mapList 内容
* @param wb HSSFWorkbook对象
* @param queryList 查询条件
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, List<LinkedHashMap<String, Object>> mapList, HSSFWorkbook wb, List queryList) {
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if (wb == null) {
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
// 第四步,在sheet中添加表头第1行,注意老版本poi对Excel的行数列数有限制 开始行数
HSSFRow row;
//是否有查询条件
if (queryList.size() > 0) {
row = sheet.createRow(0);//有查询条件 将查询条件放第一行
HSSFCell queryCell = null;
queryList.add(0, "查询条件: ");
for (int i = 0; i < queryList.size(); i++) {
queryCell = row.createCell(i);
queryCell.setCellValue(queryList.get(i) + "");
queryCell.setCellStyle(style);
}
row = sheet.createRow(1);//条件写入完毕 另开一行
} else {//没有查询条件 第0行开始
row = sheet.createRow(0);
}
//声明列对象
HSSFCell cell = null;
//创建标题
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//创建内容
for (int i = 0; i < mapList.size(); i++) {
if (queryList.size() > 0) {
row = sheet.createRow(i + 2);//有查询条件的开始行数
} else {
row = sheet.createRow(i + 1);//没有查询添加的开始行数
}
//设置列宽
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
LinkedHashMap<String, Object> map = mapList.get(i);
Object[] objects = map.values().toArray();
for (int j = 0; j < objects.length; j++) {
//将内容按顺序赋给对应的列对象
cell = row.createCell(j);
cell.setCellValue(objects[j] + "");
cell.setCellStyle(style);
}
}
return wb;
}
}
|
package mage.cards.b;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.keyword.SoulshiftAbility;
import mage.abilities.keyword.TrampleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
/**
*
* @author North
*/
public final class BodyOfJukai extends CardImpl {
public BodyOfJukai(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{7}{G}{G}");
this.subtype.add(SubType.SPIRIT);
this.power = new MageInt(8);
this.toughness = new MageInt(5);
this.addAbility(TrampleAbility.getInstance());
this.addAbility(new SoulshiftAbility(8));
}
public BodyOfJukai(final BodyOfJukai card) {
super(card);
}
@Override
public BodyOfJukai copy() {
return new BodyOfJukai(this);
}
}
|
package dk.lockfuglsang.xrayhunter.command;
import static dk.lockfuglsang.minecraft.po.I18nUtil.tr;
import java.util.List;
import java.util.Map;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import dk.lockfuglsang.minecraft.command.AbstractCommand;
import dk.lockfuglsang.util.LocationUtil;
import dk.lockfuglsang.util.TimeUtil;
import dk.lockfuglsang.xrayhunter.model.HuntSession;
import dk.lockfuglsang.xrayhunter.model.OreVein;
import dk.lockfuglsang.xrayhunter.model.PlayerStats;
import dk.lockfuglsang.xrayhunter.model.PlayerStatsComparator;
import dk.lockfuglsang.xrayhunter.model.PlayerStatsComparatorNether;
import dk.lockfuglsang.xrayhunter.model.VeinLocator;
import net.coreprotect.CoreProtectAPI;
/**
* Shows details about ore-veins found by a user
*/
public class DetailCommand extends AbstractCommand {
public DetailCommand() {
super("detail|d", null, "index ?page", "Shows mining details for a player");
}
@Override
public boolean execute(CommandSender sender, String alias, Map<String, Object> data, String... args) {
final HuntSession session = HuntSession.getSession(sender);
if (args.length >= 1 && args[0].matches("\\d+")) {
final int index = Integer.parseInt(args[0], 10);
if (index < 1 || session.getLookupCache() == null || session.getLookupCache().size() < index) {
sender.sendMessage(tr("Invalid index supplied, try running lookup again."));
} else {
final PlayerStats playerStats = session.getLookupCache().get(index-1);
session.setPlayerStat(playerStats);
final int page = args.length == 2 && args[1].matches("\\d+") ? Integer.parseInt(args[1], 10) : 1;
showDetails(sender, playerStats, session, page);
}
return true;
} else if (args.length >= 1) {
final PlayerStats stats = session.getPlayerStats(args[0]);
if (stats != null) {
final int page = args.length == 2 && args[1].matches("\\d+") ? Integer.parseInt(args[1], 10) : 1;
showDetails(sender, stats, session, page);
} else {
sender.sendMessage(tr("No player named {0} found in cache, try running lookup again.", args[0]));
}
return true;
} else if (session.getVeins() != null) {
showVeins(sender, session.getPlayerStats(), session.getVeins(), 1);
return true;
} else {
sender.sendMessage(tr("No player selected, use name or index!"));
}
return false;
}
private void showDetails(CommandSender sender, PlayerStats playerStats, HuntSession session, int page) {
final List<CoreProtectAPI.ParseResult> data = session.getUserData(playerStats.getPlayer());
if (data.isEmpty()) {
sender.sendMessage(tr("No data found for player {0}, try running lookup again.", playerStats.getPlayer()));
return;
}
final List<OreVein> veins = VeinLocator.getVeins(data);
session.setVeins(veins);
showVeins(sender, playerStats, veins, page);
}
private void showVeins(CommandSender sender, PlayerStats playerStats, List<OreVein> veins, int page) {
// TODO: 19/04/2015 - R4zorax: Pagination
final Player player = (Player) sender;
final StringBuilder sb = new StringBuilder();
final int maxPage = (veins.size() - 1) / 10 + 1;
final int p = page < 1 ? 1 : page > maxPage ? maxPage : page;
sb.append(tr("Showing what {0} has found §9({1}/{2})", playerStats.getPlayer(), p, maxPage) + "\n");
long tlast = System.currentTimeMillis();
int index = 1 + (p-1)*10;
for (final OreVein vein : veins.subList((p-1)*10, Math.min(p*10, veins.size()))) {
if(player.getWorld().getEnvironment() == World.Environment.NETHER) {
sb.append(tr("§7#{5,number} {0}: §9found §e{1} {2}{3}§9 ores at {4}",
TimeUtil.millisAsString(tlast - vein.getTime()),
vein.getSize(),
PlayerStatsComparatorNether.getColor(vein.getType()),
vein.getType().name().substring(0,3),
LocationUtil.asShortString(vein.getLocation()),
index++
) + "\n");
tlast = vein.getTime();
} else {
sb.append(tr("§7#{5,number} {0}: §9found §e{1} {2}{3}§9 ores at {4}",
TimeUtil.millisAsString(tlast - vein.getTime()),
vein.getSize(),
PlayerStatsComparator.getColor(vein.getType()),
vein.getType().name().substring(0,3),
LocationUtil.asShortString(vein.getLocation()),
index++
) + "\n");
tlast = vein.getTime();
}
}
sender.sendMessage(sb.toString().split("\n"));
}
}
|
package uk.gov.companieshouse.orders.api.interceptor;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
import static org.springframework.web.servlet.HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
import static uk.gov.companieshouse.orders.api.controller.BasketController.CHECKOUT_ID_PATH_VARIABLE;
import static uk.gov.companieshouse.orders.api.controller.OrderController.ORDER_ID_PATH_VARIABLE;
import static uk.gov.companieshouse.orders.api.interceptor.RequestMapper.ADD_ITEM;
import static uk.gov.companieshouse.orders.api.interceptor.RequestMapper.BASKET;
import static uk.gov.companieshouse.orders.api.interceptor.RequestMapper.CHECKOUT_BASKET;
import static uk.gov.companieshouse.orders.api.interceptor.RequestMapper.GET_CHECKOUT;
import static uk.gov.companieshouse.orders.api.interceptor.RequestMapper.GET_ORDER;
import static uk.gov.companieshouse.orders.api.interceptor.RequestMapper.GET_PAYMENT_DETAILS;
import static uk.gov.companieshouse.orders.api.interceptor.RequestMapper.PATCH_PAYMENT_DETAILS;
import static uk.gov.companieshouse.orders.api.logging.LoggingUtils.APPLICATION_NAMESPACE;
import static uk.gov.companieshouse.orders.api.util.EricHeaderHelper.API_KEY_IDENTITY_TYPE;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import uk.gov.companieshouse.api.util.security.AuthorisationUtil;
import uk.gov.companieshouse.logging.Logger;
import uk.gov.companieshouse.logging.LoggerFactory;
import uk.gov.companieshouse.orders.api.exception.ResourceNotFoundException;
import uk.gov.companieshouse.orders.api.logging.LoggingUtils;
import uk.gov.companieshouse.orders.api.model.AbstractOrder;
import uk.gov.companieshouse.orders.api.repository.CheckoutRepository;
import uk.gov.companieshouse.orders.api.repository.OrderRepository;
import uk.gov.companieshouse.orders.api.util.EricHeaderHelper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.function.Function;
@Service
public class UserAuthorisationInterceptor extends HandlerInterceptorAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(APPLICATION_NAMESPACE);
private static final String PATH_VARIABLES_ERROR = "No URI template path variables found in the request!";
private final RequestMapper requestMapper;
private final CheckoutRepository checkoutRepository;
private final OrderRepository orderRepository;
public UserAuthorisationInterceptor(final RequestMapper requestMapper,
final CheckoutRepository checkoutRepository,
final OrderRepository orderRepository) {
this.requestMapper = requestMapper;
this.checkoutRepository = checkoutRepository;
this.orderRepository = orderRepository;
}
@Override
public boolean preHandle(final HttpServletRequest request,
final HttpServletResponse response,
final Object handler) {
final RequestMappingInfo match = requestMapper.getRequestMapping(request);
if (match != null) {
switch (match.getName()) {
case ADD_ITEM:
case CHECKOUT_BASKET:
case BASKET:
return true; // no authorisation required
case GET_PAYMENT_DETAILS:
case GET_CHECKOUT:
return getRequestClientIsAuthorised(request, response, this::getCheckoutUserIsResourceOwner);
case GET_ORDER:
return getRequestClientIsAuthorised(request, response, this::getOrderUserIsResourceOwner);
case PATCH_PAYMENT_DETAILS:
return clientIsAuthorisedInternalApi(request, response);
default:
// This should not happen.
throw new IllegalArgumentException("Mapped request with no authoriser: " + match.getName());
}
}
return true;
}
/**
* Inspects ERIC populated headers to determine whether the request is authorised.
* @param request the request checked
* @param response the response, updated by this should the request be found to be unauthorised
* @param isResourceOwner the method to call to check resource ownership, should it be necessary
* @return whether the request is authorised (<code>true</code>), or not (<code>false</code>)
*/
private boolean getRequestClientIsAuthorised(
final HttpServletRequest request,
final HttpServletResponse response,
final BiPredicate<HttpServletRequest, HttpServletResponse> isResourceOwner) {
Map<String, Object> logMap = LoggingUtils.createLogMap();
final String identityType = EricHeaderHelper.getIdentityType(request);
logMap.put(LoggingUtils.IDENTITY_TYPE, identityType);
if (API_KEY_IDENTITY_TYPE.equals(identityType)) {
LOGGER.infoRequest(request,
"UserAuthorisationInterceptor: client is presenting an API key", logMap);
return clientIsAuthorisedInternalApi(request, response);
} else {
LOGGER.infoRequest(request,
"UserAuthorisationInterceptor: client is presenting signed in user credentials", logMap);
return isResourceOwner.test(request, response);
}
}
/**
* Inspects ERIC populated headers to determine whether the request comes from a user who is the owner of the
* checkout resource the get payment details request attempts to access.
* @param request the request checked
* @param response the response, updated by this should the request be found to be unauthorised
* @return whether the request is authorised (<code>true</code>), or not (<code>false</code>)
*/
private boolean getCheckoutUserIsResourceOwner(final HttpServletRequest request,
final HttpServletResponse response) {
return getRequestUserIsResourceOwner(request, response, CHECKOUT_ID_PATH_VARIABLE, this::retrieveCheckout);
}
/**
* Inspects ERIC populated headers to determine whether the request comes from a user who is the owner of the
* order resource the get order request attempts to access.
* @param request the request checked
* @param response the response, updated by this should the request be found to be unauthorised
* @return whether the request is authorised (<code>true</code>), or not (<code>false</code>)
*/
private boolean getOrderUserIsResourceOwner(final HttpServletRequest request,
final HttpServletResponse response) {
return getRequestUserIsResourceOwner(request, response, ORDER_ID_PATH_VARIABLE, this::retrieveOrder);
}
/**
* Inspects ERIC populated headers to determine whether the request comes from a user who is the owner of the
* checkout resource the get payment details request attempts to access.
* @param request the request checked
* @param response the response, updated by this should the request be found to be unauthorised
* @param resourceIdPathVariable the name of the resource ID Spring path variable
* @param findById the method to call to retrieve the resource by its ID
* @return whether the request is authorised (<code>true</code>), or not (<code>false</code>)
*/
private boolean getRequestUserIsResourceOwner(final HttpServletRequest request,
final HttpServletResponse response,
final String resourceIdPathVariable,
final Function<String, AbstractOrder> findById) {
final String requestUserId = EricHeaderHelper.getIdentity(request);
final String orderId = getPathVariable(request, resourceIdPathVariable);
final AbstractOrder order = findById.apply(orderId);
if (requestUserId.equals(order.getUserId())) {
LOGGER.infoRequest(request, "UserAuthorisationInterceptor: user is resource owner", null);
return true;
} else {
LOGGER.infoRequest(request, "UserAuthorisationInterceptor: user is not resource owner", null);
response.setStatus(UNAUTHORIZED.value());
return false;
}
}
/**
* Extracts the named Spring path variable from the request.
* @param request assumed to have been populated by Spring with the required path variable
* @param pathVariable the name of the path variable
* @return the path variable value
*/
private String getPathVariable(final HttpServletRequest request, final String pathVariable) {
final Map<String, String> uriTemplateVariables =
(Map<String, String>) request.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (uriTemplateVariables == null) {
// This should not happen.
LOGGER.error(PATH_VARIABLES_ERROR);
throw new IllegalStateException(PATH_VARIABLES_ERROR);
}
return uriTemplateVariables.get(pathVariable);
}
/**
* Retrieves the checkout identified by the ID from the checkout repository.
* @param checkoutId the checkout ID
* @return the checkout
*/
private AbstractOrder retrieveCheckout(final String checkoutId) {
return checkoutRepository.findById(checkoutId).orElseThrow(ResourceNotFoundException::new);
}
/**
* Retrieves the order identified by the ID from the order repository.
* @param orderId the order ID
* @return the order
*/
private AbstractOrder retrieveOrder(final String orderId) {
return orderRepository.findById(orderId).orElseThrow(ResourceNotFoundException::new);
}
/**
* Assuming the request contains ERIC headers representing an API client, this checks these to determine whether
* the API client has an internal user role (aka "elevated privileges").
* @param request the request to be checked
* @param response the response, updated by this should the request be found to be unauthorised
* @return whether the request is authorised (<code>true</code>), or not (<code>false</code>)
*/
private boolean clientIsAuthorisedInternalApi(final HttpServletRequest request, final HttpServletResponse response)
{
// We know we are dealing with an API request here due to prior work carried out by the
// UserAuthenticationInterceptor on this request.
final boolean isAuthorisedInternalApi = AuthorisationUtil.hasInternalUserRole(request);
if (!isAuthorisedInternalApi) {
LOGGER.infoRequest(request,
"UserAuthorisationInterceptor: client does not have required internal user role", null);
response.setStatus(UNAUTHORIZED.value());
} else {
LOGGER.infoRequest(request,
"UserAuthorisationInterceptor: client has required internal user role", null);
}
return isAuthorisedInternalApi;
}
}
|
package org.blender.dna;
import java.io.IOException;
import org.cakelab.blender.io.block.Block;
import org.cakelab.blender.io.block.BlockTable;
import org.cakelab.blender.nio.CArrayFacade;
import org.cakelab.blender.nio.CFacade;
import org.cakelab.blender.nio.CMetaData;
import org.cakelab.blender.nio.CPointer;
/**
* Generated facet for DNA struct type 'bNodeStack'.
*
* <h3>Class Documentation</h3>
*
*/
@CMetaData(size32=44, size64=48)
public class bNodeStack extends CFacade {
/**
* This is the sdna index of the struct bNodeStack.
* <p>
* It is required when allocating a new block to store data for bNodeStack.
* </p>
* @see {@link org.cakelab.blender.io.dna.internal.StructDNA}
* @see {@link org.cakelab.blender.io.block.BlockTable#allocate}
*/
public static final int __DNA__SDNA_INDEX = 400;
/**
* Field descriptor (offset) for struct member 'vec'.
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__vec);
* CPointer<CArrayFacade<Float>> p_vec = p.cast(new Class[]{CArrayFacade.class, Float.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'vec'</li>
* <li>Signature: 'float[4]'</li>
* <li>Actual Size (32bit/64bit): 16/16</li>
* </ul>
*/
public static final long[] __DNA__FIELD__vec = new long[]{0, 0};
/**
* Field descriptor (offset) for struct member 'min'.
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__min);
* CPointer<Float> p_min = p.cast(new Class[]{Float.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'min'</li>
* <li>Signature: 'float'</li>
* <li>Actual Size (32bit/64bit): 4/4</li>
* </ul>
*/
public static final long[] __DNA__FIELD__min = new long[]{16, 16};
/**
* Field descriptor (offset) for struct member 'max'.
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__max);
* CPointer<Float> p_max = p.cast(new Class[]{Float.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'max'</li>
* <li>Signature: 'float'</li>
* <li>Actual Size (32bit/64bit): 4/4</li>
* </ul>
*/
public static final long[] __DNA__FIELD__max = new long[]{20, 20};
/**
* Field descriptor (offset) for struct member 'data'.
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__data);
* CPointer<CPointer<Object>> p_data = p.cast(new Class[]{CPointer.class, Object.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'data'</li>
* <li>Signature: 'void*'</li>
* <li>Actual Size (32bit/64bit): 4/8</li>
* </ul>
*/
public static final long[] __DNA__FIELD__data = new long[]{24, 24};
/**
* Field descriptor (offset) for struct member 'hasinput'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> When input has link, tagged before executing. </p>
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__hasinput);
* CPointer<Short> p_hasinput = p.cast(new Class[]{Short.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'hasinput'</li>
* <li>Signature: 'short'</li>
* <li>Actual Size (32bit/64bit): 2/2</li>
* </ul>
*/
public static final long[] __DNA__FIELD__hasinput = new long[]{28, 32};
/**
* Field descriptor (offset) for struct member 'hasoutput'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> When output is linked, tagged before executing. </p>
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__hasoutput);
* CPointer<Short> p_hasoutput = p.cast(new Class[]{Short.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'hasoutput'</li>
* <li>Signature: 'short'</li>
* <li>Actual Size (32bit/64bit): 2/2</li>
* </ul>
*/
public static final long[] __DNA__FIELD__hasoutput = new long[]{30, 34};
/**
* Field descriptor (offset) for struct member 'datatype'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Type of data pointer. </p>
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__datatype);
* CPointer<Short> p_datatype = p.cast(new Class[]{Short.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'datatype'</li>
* <li>Signature: 'short'</li>
* <li>Actual Size (32bit/64bit): 2/2</li>
* </ul>
*/
public static final long[] __DNA__FIELD__datatype = new long[]{32, 36};
/**
* Field descriptor (offset) for struct member 'sockettype'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Type of socket stack comes from, to remap linking different sockets. </p>
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__sockettype);
* CPointer<Short> p_sockettype = p.cast(new Class[]{Short.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'sockettype'</li>
* <li>Signature: 'short'</li>
* <li>Actual Size (32bit/64bit): 2/2</li>
* </ul>
*/
public static final long[] __DNA__FIELD__sockettype = new long[]{34, 38};
/**
* Field descriptor (offset) for struct member 'is_copy'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Data is a copy of external data (no freeing). </p>
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__is_copy);
* CPointer<Short> p_is_copy = p.cast(new Class[]{Short.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'is_copy'</li>
* <li>Signature: 'short'</li>
* <li>Actual Size (32bit/64bit): 2/2</li>
* </ul>
*/
public static final long[] __DNA__FIELD__is_copy = new long[]{36, 40};
/**
* Field descriptor (offset) for struct member 'external'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Data is used by external nodes (no freeing). </p>
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD__external);
* CPointer<Short> p_external = p.cast(new Class[]{Short.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: 'external'</li>
* <li>Signature: 'short'</li>
* <li>Actual Size (32bit/64bit): 2/2</li>
* </ul>
*/
public static final long[] __DNA__FIELD__external = new long[]{38, 42};
/**
* Field descriptor (offset) for struct member '_pad'.
* <h3>Pointer Arithmetics</h3>
* <p>
* This is how you get a reference on the corresponding field in the struct:
* </p>
* <pre>
* bNodeStack bnodestack = ...;
* CPointer<Object> p = bnodestack.__dna__addressof(bNodeStack.__DNA__FIELD___pad);
* CPointer<CArrayFacade<Byte>> p__pad = p.cast(new Class[]{CArrayFacade.class, Byte.class});
* </pre>
* <h3>Metadata</h3>
* <ul>
* <li>Field: '_pad'</li>
* <li>Signature: 'char[4]'</li>
* <li>Actual Size (32bit/64bit): 4/4</li>
* </ul>
*/
public static final long[] __DNA__FIELD___pad = new long[]{40, 44};
public bNodeStack(long __address, Block __block, BlockTable __blockTable) {
super(__address, __block, __blockTable);
}
protected bNodeStack(bNodeStack that) {
super(that.__io__address, that.__io__block, that.__io__blockTable);
}
/**
* Get method for struct member 'vec'.
* @see #__DNA__FIELD__vec
*/
public CArrayFacade<Float> getVec() throws IOException
{
Class<?>[] __dna__targetTypes = new Class[]{Float.class};
int[] __dna__dimensions = new int[]{
4
};
if ((__io__pointersize == 8)) {
return new CArrayFacade<Float>(__io__address + 0, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable);
} else {
return new CArrayFacade<Float>(__io__address + 0, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable);
}
}
/**
* Set method for struct member 'vec'.
* @see #__DNA__FIELD__vec
*/
public void setVec(CArrayFacade<Float> vec) throws IOException
{
long __dna__offset;
if ((__io__pointersize == 8)) {
__dna__offset = 0;
} else {
__dna__offset = 0;
}
if (__io__equals(vec, __io__address + __dna__offset)) {
return;
} else if (__io__same__encoding(this, vec)) {
__io__native__copy(__io__block, __io__address + __dna__offset, vec);
} else {
__io__generic__copy( getVec(), vec);
}
}
/**
* Get method for struct member 'min'.
* @see #__DNA__FIELD__min
*/
public float getMin() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readFloat(__io__address + 16);
} else {
return __io__block.readFloat(__io__address + 16);
}
}
/**
* Set method for struct member 'min'.
* @see #__DNA__FIELD__min
*/
public void setMin(float min) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeFloat(__io__address + 16, min);
} else {
__io__block.writeFloat(__io__address + 16, min);
}
}
/**
* Get method for struct member 'max'.
* @see #__DNA__FIELD__max
*/
public float getMax() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readFloat(__io__address + 20);
} else {
return __io__block.readFloat(__io__address + 20);
}
}
/**
* Set method for struct member 'max'.
* @see #__DNA__FIELD__max
*/
public void setMax(float max) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeFloat(__io__address + 20, max);
} else {
__io__block.writeFloat(__io__address + 20, max);
}
}
/**
* Get method for struct member 'data'.
* @see #__DNA__FIELD__data
*/
public CPointer<Object> getData() throws IOException
{
long __dna__targetAddress;
if ((__io__pointersize == 8)) {
__dna__targetAddress = __io__block.readLong(__io__address + 24);
} else {
__dna__targetAddress = __io__block.readLong(__io__address + 24);
}
Class<?>[] __dna__targetTypes = new Class[]{Object.class};
return new CPointer<Object>(__dna__targetAddress, __dna__targetTypes, __io__blockTable.getBlock(__dna__targetAddress, -1), __io__blockTable);
}
/**
* Set method for struct member 'data'.
* @see #__DNA__FIELD__data
*/
public void setData(CPointer<Object> data) throws IOException
{
long __address = ((data == null) ? 0 : data.getAddress());
if ((__io__pointersize == 8)) {
__io__block.writeLong(__io__address + 24, __address);
} else {
__io__block.writeLong(__io__address + 24, __address);
}
}
/**
* Get method for struct member 'hasinput'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> When input has link, tagged before executing. </p>
* @see #__DNA__FIELD__hasinput
*/
public short getHasinput() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readShort(__io__address + 32);
} else {
return __io__block.readShort(__io__address + 28);
}
}
/**
* Set method for struct member 'hasinput'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> When input has link, tagged before executing. </p>
* @see #__DNA__FIELD__hasinput
*/
public void setHasinput(short hasinput) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeShort(__io__address + 32, hasinput);
} else {
__io__block.writeShort(__io__address + 28, hasinput);
}
}
/**
* Get method for struct member 'hasoutput'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> When output is linked, tagged before executing. </p>
* @see #__DNA__FIELD__hasoutput
*/
public short getHasoutput() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readShort(__io__address + 34);
} else {
return __io__block.readShort(__io__address + 30);
}
}
/**
* Set method for struct member 'hasoutput'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> When output is linked, tagged before executing. </p>
* @see #__DNA__FIELD__hasoutput
*/
public void setHasoutput(short hasoutput) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeShort(__io__address + 34, hasoutput);
} else {
__io__block.writeShort(__io__address + 30, hasoutput);
}
}
/**
* Get method for struct member 'datatype'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Type of data pointer. </p>
* @see #__DNA__FIELD__datatype
*/
public short getDatatype() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readShort(__io__address + 36);
} else {
return __io__block.readShort(__io__address + 32);
}
}
/**
* Set method for struct member 'datatype'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Type of data pointer. </p>
* @see #__DNA__FIELD__datatype
*/
public void setDatatype(short datatype) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeShort(__io__address + 36, datatype);
} else {
__io__block.writeShort(__io__address + 32, datatype);
}
}
/**
* Get method for struct member 'sockettype'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Type of socket stack comes from, to remap linking different sockets. </p>
* @see #__DNA__FIELD__sockettype
*/
public short getSockettype() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readShort(__io__address + 38);
} else {
return __io__block.readShort(__io__address + 34);
}
}
/**
* Set method for struct member 'sockettype'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Type of socket stack comes from, to remap linking different sockets. </p>
* @see #__DNA__FIELD__sockettype
*/
public void setSockettype(short sockettype) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeShort(__io__address + 38, sockettype);
} else {
__io__block.writeShort(__io__address + 34, sockettype);
}
}
/**
* Get method for struct member 'is_copy'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Data is a copy of external data (no freeing). </p>
* @see #__DNA__FIELD__is_copy
*/
public short getIs_copy() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readShort(__io__address + 40);
} else {
return __io__block.readShort(__io__address + 36);
}
}
/**
* Set method for struct member 'is_copy'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Data is a copy of external data (no freeing). </p>
* @see #__DNA__FIELD__is_copy
*/
public void setIs_copy(short is_copy) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeShort(__io__address + 40, is_copy);
} else {
__io__block.writeShort(__io__address + 36, is_copy);
}
}
/**
* Get method for struct member 'external'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Data is used by external nodes (no freeing). </p>
* @see #__DNA__FIELD__external
*/
public short getExternal() throws IOException
{
if ((__io__pointersize == 8)) {
return __io__block.readShort(__io__address + 42);
} else {
return __io__block.readShort(__io__address + 38);
}
}
/**
* Set method for struct member 'external'.
* <h3>Field Documentation</h3>
* <h4>Blender Source Code:</h4>
* <p> Data is used by external nodes (no freeing). </p>
* @see #__DNA__FIELD__external
*/
public void setExternal(short external) throws IOException
{
if ((__io__pointersize == 8)) {
__io__block.writeShort(__io__address + 42, external);
} else {
__io__block.writeShort(__io__address + 38, external);
}
}
/**
* Get method for struct member '_pad'.
* @see #__DNA__FIELD___pad
*/
public CArrayFacade<Byte> get_pad() throws IOException
{
Class<?>[] __dna__targetTypes = new Class[]{Byte.class};
int[] __dna__dimensions = new int[]{
4
};
if ((__io__pointersize == 8)) {
return new CArrayFacade<Byte>(__io__address + 44, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable);
} else {
return new CArrayFacade<Byte>(__io__address + 40, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable);
}
}
/**
* Set method for struct member '_pad'.
* @see #__DNA__FIELD___pad
*/
public void set_pad(CArrayFacade<Byte> _pad) throws IOException
{
long __dna__offset;
if ((__io__pointersize == 8)) {
__dna__offset = 44;
} else {
__dna__offset = 40;
}
if (__io__equals(_pad, __io__address + __dna__offset)) {
return;
} else if (__io__same__encoding(this, _pad)) {
__io__native__copy(__io__block, __io__address + __dna__offset, _pad);
} else {
__io__generic__copy( get_pad(), _pad);
}
}
/**
* Instantiates a pointer on this instance.
*/
public CPointer<bNodeStack> __io__addressof() {
return new CPointer<bNodeStack>(__io__address, new Class[]{bNodeStack.class}, __io__block, __io__blockTable);
}
}
|
package com.chris.bulleyeadmin.common.utils;
import com.chris.bulleyeadmin.common.entity.Constants;
import com.chris.bulleyeadmin.system.pojo.Account;
import com.chris.bulleyeadmin.system.pojo.Role;
import com.chris.bulleyeadmin.system.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Component
public class AuthUtil {
// public static final ThreadLocal<Account> local = new ThreadLocal<>();
@Autowired
private HttpServletRequest request;
public static User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object object = authentication.getPrincipal();
User user = null;
if (object instanceof User) {
user = (User) object;
return user;
}
}
return null;
}
public static User getCurrentUser(HttpServletRequest request) {
if (request == null) {
return null;
}
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if (user == null) {
user = getCurrentUser();
session.setAttribute("user", user);
}
return user;
}
public static void changeRole(String id, String name) {
User user = getCurrentUser();
for (Role role : AuthUtil.getCurrentUser().getRoles()) {
if (role.getId().equals(id)) {
user.setCurrentRole(role);
}
}
}
/**
* 获取用户的数据浏览权限
*
* @return
*/
public static String getAuthFlag() {
StringBuilder sb = new StringBuilder();
Role role = getCurrentUser().getCurrentRole();
/* if (act != null) {
for (Role role : act.getRole()) {
sb.append(role.getDataAuthFlag());
sb.append(";");
}
}*/
String strAuths = role.getDataAuthFlag();
if (strAuths.contains(Constants.ORGANIZATION)) {
return Constants.ORGANIZATION; //全院
}
if (strAuths.contains(Constants.DEPARTMENT)) {
return Constants.DEPARTMENT; //当前科室
}
return Constants.PERSONAL; //当前用户
}
}
|
package mage.cards.o;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.DiscardCardCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.UntapTargetEffect;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.effects.common.continuous.GainControlTargetEffect;
import mage.abilities.keyword.HasteAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Zone;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author fireshoes
*/
public final class Overtaker extends CardImpl {
public Overtaker(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{U}");
this.subtype.add(SubType.MERFOLK);
this.subtype.add(SubType.SPELLSHAPER);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// {3}{U}, {tap}, Discard a card: Untap target creature and gain control of it until end of turn. That creature gains haste until end of turn.
Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new UntapTargetEffect(), new ManaCostsImpl("{3}{U}"));
ability.addCost(new TapSourceCost());
ability.addCost(new DiscardCardCost());
Effect effect = new GainControlTargetEffect(Duration.EndOfTurn);
ability.addEffect(effect);
effect = new GainAbilityTargetEffect(HasteAbility.getInstance(), Duration.EndOfTurn);
ability.addEffect(effect);
ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability);
}
public Overtaker(final Overtaker card) {
super(card);
}
@Override
public Overtaker copy() {
return new Overtaker(this);
}
}
|
package com.codepath.apps.restclienttemplate.models;
import androidx.room.Embedded;
import java.util.ArrayList;
import java.util.List;
public class TweetWithUser {
@Embedded
User user;
@Embedded(prefix = "tweet_")
Tweet tweet;
public static List<Tweet> getTweetList(List<TweetWithUser> tweetWithUsers) {
List<Tweet> tweets = new ArrayList<>();
for(int i=0; i<tweetWithUsers.size(); i++){
Tweet tweet = tweetWithUsers.get(i).tweet;
tweet.user = tweetWithUsers.get(i).user;
tweets.add(tweet);
}
return tweets;
}
}
|
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.core5.reactor;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.hc.core5.concurrent.BasicFuture;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.function.Callback;
import org.apache.hc.core5.io.Closer;
class SingleCoreListeningIOReactor extends AbstractSingleCoreIOReactor implements ConnectionAcceptor {
private final IOReactorConfig reactorConfig;
private final Callback<SocketChannel> callback;
private final Queue<ListenerEndpointRequest> requestQueue;
private final ConcurrentMap<ListenerEndpoint, Boolean> endpoints;
private final AtomicBoolean paused;
private final long selectTimeoutMillis;
SingleCoreListeningIOReactor(
final Callback<Exception> exceptionCallback,
final IOReactorConfig ioReactorConfig,
final Callback<SocketChannel> callback) {
super(exceptionCallback);
this.reactorConfig = ioReactorConfig != null ? ioReactorConfig : IOReactorConfig.DEFAULT;
this.callback = callback;
this.requestQueue = new ConcurrentLinkedQueue<>();
this.endpoints = new ConcurrentHashMap<>();
this.paused = new AtomicBoolean(false);
this.selectTimeoutMillis = this.reactorConfig.getSelectInterval().toMilliseconds();
}
@Override
void doTerminate() {
ListenerEndpointRequest request;
while ((request = this.requestQueue.poll()) != null) {
request.cancel();
}
}
@Override
protected final void doExecute() throws IOException {
while (!Thread.currentThread().isInterrupted()) {
if (getStatus().compareTo(IOReactorStatus.ACTIVE) != 0) {
break;
}
final int readyCount = this.selector.select(this.selectTimeoutMillis);
if (getStatus().compareTo(IOReactorStatus.ACTIVE) != 0) {
break;
}
processEvents(readyCount);
}
}
private void processEvents(final int readyCount) throws IOException {
if (!this.paused.get()) {
processSessionRequests();
}
if (readyCount > 0) {
final Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
for (final SelectionKey key : selectedKeys) {
processEvent(key);
}
selectedKeys.clear();
}
}
private void processEvent(final SelectionKey key) throws IOException {
try {
if (key.isAcceptable()) {
final ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
for (;;) {
final SocketChannel socketChannel = serverChannel.accept();
if (socketChannel == null) {
break;
}
this.callback.execute(socketChannel);
}
}
} catch (final CancelledKeyException ex) {
final ListenerEndpoint endpoint = (ListenerEndpoint) key.attachment();
this.endpoints.remove(endpoint);
key.attach(null);
}
}
@Override
public Future<ListenerEndpoint> listen(final SocketAddress address, final FutureCallback<ListenerEndpoint> callback) {
if (getStatus().compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
throw new IOReactorShutdownException("I/O reactor has been shut down");
}
final BasicFuture<ListenerEndpoint> future = new BasicFuture<>(callback);
this.requestQueue.add(new ListenerEndpointRequest(address, future));
this.selector.wakeup();
return future;
}
private void processSessionRequests() throws IOException {
ListenerEndpointRequest request;
while ((request = this.requestQueue.poll()) != null) {
if (request.isCancelled()) {
continue;
}
final SocketAddress address = request.address;
final ServerSocketChannel serverChannel = ServerSocketChannel.open();
try {
final ServerSocket socket = serverChannel.socket();
socket.setReuseAddress(this.reactorConfig.isSoReuseAddress());
if (this.reactorConfig.getRcvBufSize() > 0) {
socket.setReceiveBufferSize(this.reactorConfig.getRcvBufSize());
}
serverChannel.configureBlocking(false);
try {
socket.bind(address, this.reactorConfig.getBacklogSize());
} catch (final BindException ex) {
final BindException detailedEx = new BindException(
String.format("Socket bind failure for socket %s, address=%s, BacklogSize=%,d: %s", socket,
address, this.reactorConfig.getBacklogSize(), ex));
detailedEx.setStackTrace(ex.getStackTrace());
throw detailedEx;
}
final SelectionKey key = serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
key.attach(request);
final ListenerEndpoint endpoint = new ListenerEndpointImpl(key, socket.getLocalSocketAddress());
this.endpoints.put(endpoint, Boolean.TRUE);
request.completed(endpoint);
} catch (final IOException ex) {
Closer.closeQuietly(serverChannel);
request.failed(ex);
}
}
}
@Override
public Set<ListenerEndpoint> getEndpoints() {
final Set<ListenerEndpoint> set = new HashSet<>();
final Iterator<ListenerEndpoint> it = this.endpoints.keySet().iterator();
while (it.hasNext()) {
final ListenerEndpoint endpoint = it.next();
if (!endpoint.isClosed()) {
set.add(endpoint);
} else {
it.remove();
}
}
return set;
}
@Override
public void pause() throws IOException {
if (paused.compareAndSet(false, true)) {
final Iterator<ListenerEndpoint> it = this.endpoints.keySet().iterator();
while (it.hasNext()) {
final ListenerEndpoint endpoint = it.next();
if (!endpoint.isClosed()) {
endpoint.close();
this.requestQueue.add(new ListenerEndpointRequest(endpoint.getAddress(), null));
}
it.remove();
}
}
}
@Override
public void resume() throws IOException {
if (paused.compareAndSet(true, false)) {
this.selector.wakeup();
}
}
}
|
/*
* 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.codecommit.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.codecommit.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* FileContentSizeLimitExceededException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class FileContentSizeLimitExceededExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private FileContentSizeLimitExceededExceptionUnmarshaller() {
super(com.amazonaws.services.codecommit.model.FileContentSizeLimitExceededException.class, "FileContentSizeLimitExceededException");
}
@Override
public com.amazonaws.services.codecommit.model.FileContentSizeLimitExceededException unmarshallFromContext(JsonUnmarshallerContext context)
throws Exception {
com.amazonaws.services.codecommit.model.FileContentSizeLimitExceededException fileContentSizeLimitExceededException = new com.amazonaws.services.codecommit.model.FileContentSizeLimitExceededException(
null);
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return fileContentSizeLimitExceededException;
}
private static FileContentSizeLimitExceededExceptionUnmarshaller instance;
public static FileContentSizeLimitExceededExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new FileContentSizeLimitExceededExceptionUnmarshaller();
return instance;
}
}
|
/*
* 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.
*/
/**
* Reusable dropwizard-based Trellis application components.
*
* This package implements common components for building a deployable dropwizard-based Trellis server.
*/
package org.trellisldp.dropwizard;
|
package wasdev.sample;
import java.util.Arrays;
import java.util.LinkedList;
public class Sentence {
private String _id;
private String _rev;
private String translationID;
private String fullSentence;
private LinkedList<String> sentenceChunks = new LinkedList<>();
private LinkedList<String> urls = new LinkedList<>();
// No-arg constructor
public Sentence() {
}
// Constructor
public Sentence(String translationID, String fullSentence) {
this.translationID = translationID;
this.fullSentence = fullSentence;
}
/** Begin getters/setters **/
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String get_rev() {
return _rev;
}
public void set_rev(String _rev) {
this._rev = _rev;
}
public String getTranslationID() {
return translationID;
}
public void setTranslationID(String translationID) {
this.translationID = translationID;
}
public String getFullSentence() {
return fullSentence;
}
public void setFullSentence(String fullSentence) {
this.fullSentence = fullSentence;
}
public LinkedList<String> getSentenceChunks() {
return sentenceChunks;
}
/**End getters/setters**/
// Adds new url for a word to a sentence object
public void addUrl(String url) {
this.urls.add(url);
}
// Splits sentence into separate words, see createSentenceChunks
public void chunkify() {
this.sentenceChunks = createSentenceChunks(fullSentence);
}
/*public String toString(){
String myString = "";
for(String s: sentenceChunks) {
myString += s + "\n";
}
return myString;
}*/
// Splits sentence into words after trimming, see trimSentence
private LinkedList<String> createSentenceChunks(String fullSentence) {
String mySentence = trimSentence(fullSentence);
sentenceChunks.addAll(Arrays.asList(mySentence.split(" ")));
return sentenceChunks;
}
// Trims sentence and removes spaces and punctuation
private String trimSentence(String fullSentence){
return fullSentence.trim().toLowerCase().replaceAll("[^a-zA-Z0-9 ]", "");
}
}
|
package com.thegongoliers.hardware;
import com.thegongoliers.input.switches.ResettableSwitch;
import com.thegongoliers.input.switches.Switch;
import com.thegongoliers.output.interfaces.Drivetrain;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.interfaces.Potentiometer;
import edu.wpi.first.wpilibj2.command.button.Button;
import edu.wpi.first.wpilibj2.command.button.Trigger;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class HardwareTest {
@Test
public void testMakeTrigger(){
Switch s = mock(Switch.class);
Trigger t = Hardware.makeTrigger(s::isTriggered);
assertNotNull(t);
when(s.isTriggered()).thenReturn(false);
assertFalse(t.get());
when(s.isTriggered()).thenReturn(true);
assertTrue(t.get());
}
@Test
public void testSwitchToTrigger(){
Switch s = mock(Switch.class);
Trigger t = Hardware.switchToTrigger(s);
assertNotNull(t);
when(s.isTriggered()).thenReturn(false);
assertFalse(t.get());
when(s.isTriggered()).thenReturn(true);
assertTrue(t.get());
}
@Test
public void testMakeButton(){
Switch s = mock(Switch.class);
Button t = Hardware.makeButton(s::isTriggered);
assertNotNull(t);
when(s.isTriggered()).thenReturn(false);
assertFalse(t.get());
when(s.isTriggered()).thenReturn(true);
assertTrue(t.get());
}
@Test
public void testCombineButtons(){
Switch s1 = mock(Switch.class);
Switch s2 = mock(Switch.class);
Switch s3 = mock(Switch.class);
Button button1 = Hardware.makeButton(s1::isTriggered);
Button button2 = Hardware.makeButton(s2::isTriggered);
Button button3 = Hardware.makeButton(s3::isTriggered);
Button combined = Hardware.combineButtons(button1, button2, button3);
// When all buttons are released, it should be false
when(s1.isTriggered()).thenReturn(false);
when(s2.isTriggered()).thenReturn(false);
when(s3.isTriggered()).thenReturn(false);
assertFalse(combined.get());
// When only one button is pressed, it should be false
when(s1.isTriggered()).thenReturn(true);
when(s2.isTriggered()).thenReturn(false);
when(s3.isTriggered()).thenReturn(false);
assertFalse(combined.get());
// When only two buttons are pressed, it should be false
when(s1.isTriggered()).thenReturn(false);
when(s2.isTriggered()).thenReturn(true);
when(s3.isTriggered()).thenReturn(true);
assertFalse(combined.get());
// When all buttons are pressed, it should be true
when(s1.isTriggered()).thenReturn(true);
when(s2.isTriggered()).thenReturn(true);
when(s3.isTriggered()).thenReturn(true);
assertTrue(combined.get());
}
@Test
public void testTriggerToButton(){
Switch s = mock(Switch.class);
Trigger t = Hardware.switchToTrigger(s);
Button b = Hardware.triggerToButton(t);
assertNotNull(t);
when(s.isTriggered()).thenReturn(false);
assertFalse(b.get());
when(s.isTriggered()).thenReturn(true);
assertTrue(b.get());
}
@Test
public void testMakeSwitch(){
Switch mockSwitch = mock(Switch.class);
Switch s = Hardware.makeSwitch(mockSwitch::isTriggered);
assertNotNull(s);
when(mockSwitch.isTriggered()).thenReturn(false);
assertFalse(s.isTriggered());
when(mockSwitch.isTriggered()).thenReturn(true);
assertTrue(s.isTriggered());
}
@Test
public void testMakeResettableSwitchFromSwitch(){
Switch mockSwitch = mock(Switch.class);
ResettableSwitch s = Hardware.makeResettableSwitch(mockSwitch);
assertNotNull(s);
when(mockSwitch.isTriggered()).thenReturn(false);
assertFalse(s.isTriggered());
when(mockSwitch.isTriggered()).thenReturn(true);
assertTrue(s.isTriggered());
when(mockSwitch.isTriggered()).thenReturn(false);
assertTrue(s.isTriggered());
s.reset();
assertFalse(s.isTriggered());
}
@Test
public void testInvertGyro(){
Gyro gyro = mock(Gyro.class);
Gyro g = Hardware.invertGyro(gyro);
assertNotNull(g);
when(gyro.getAngle()).thenReturn(10.0);
assertEquals(-10, g.getAngle(), 0.0001);
when(gyro.getAngle()).thenReturn(-20.0);
assertEquals(20, g.getAngle(), 0.0001);
when(gyro.getRate()).thenReturn(0.5);
assertEquals(-0.5, g.getRate(), 0.0001);
when(gyro.getRate()).thenReturn(-0.5);
assertEquals(0.5, g.getRate(), 0.0001);
}
@Test
public void testInvertPotentiometer(){
Potentiometer potentiometer = mock(Potentiometer.class);
Potentiometer p = Hardware.invertPotentiometer(potentiometer);
// Goes from 1000 -> 900, but it should be 0 -> 100
double rawAngle = 1000;
double offset = 1000;
assertNotNull(p);
when(potentiometer.get()).thenReturn(rawAngle - offset);
assertEquals(0, p.get(), 0.001);
rawAngle = 900;
when(potentiometer.get()).thenReturn(rawAngle - offset);
assertEquals(100, p.get(), 0.001);
rawAngle = 1100;
when(potentiometer.get()).thenReturn(rawAngle - offset);
assertEquals(-100, p.get(), 0.001);
}
@Test
public void testCreatingDrivetrain(){
DifferentialDrive differentialDrive = mock(DifferentialDrive.class);
Drivetrain drivetrain = Hardware.createDrivetrain(differentialDrive);
drivetrain.stop();
verify(differentialDrive).stopMotor();
drivetrain.arcade(1.0, 0.5);
verify(differentialDrive).arcadeDrive(1.0, 0.5, false);
drivetrain.tank(-1.0, 1.0);
verify(differentialDrive).tankDrive(-1.0, 1.0, false);
}
@Test
public void convertsVoltageToPWM(){
assertEquals(0, Hardware.voltageToPWM(0, () -> 10), 0.0001);
assertEquals(0, Hardware.voltageToPWM(0, null), 0.0001);
assertEquals(0, Hardware.voltageToPWM(0, () -> 0), 0.0001);
assertEquals(0.4, Hardware.voltageToPWM(4, () -> 10), 0.0001);
assertEquals(-0.4, Hardware.voltageToPWM(-4, () -> 10), 0.0001);
assertEquals(1, Hardware.voltageToPWM(12, () -> 10), 0.0001);
assertEquals(-1, Hardware.voltageToPWM(-12, () -> 10), 0.0001);
}
}
|
/*
* Copyright 2006-2021 Prowide
*
* 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.prowidesoftware.swift.model.field;
import com.prowidesoftware.swift.model.Tag;
import com.prowidesoftware.Generated;
import com.prowidesoftware.deprecation.ProwideDeprecated;
import com.prowidesoftware.deprecation.TargetYear;
import java.io.Serializable;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.prowidesoftware.swift.model.field.AmountContainer;
import com.prowidesoftware.swift.model.field.AmountResolver;
import org.apache.commons.lang3.StringUtils;
import com.prowidesoftware.swift.model.field.SwiftParseUtils;
import com.prowidesoftware.swift.model.field.Field;
import com.prowidesoftware.swift.model.*;
import com.prowidesoftware.swift.utils.SwiftFormatUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* <strong>SWIFT MT Field 35A</strong>
* <p>
* Model and parser for field 35A of a SWIFT MT message.
*
* <p>Subfields (components) Data types
* <ol>
* <li><code>String</code></li>
* <li><code>BigDecimal</code></li>
* </ol>
*
* <p>Structure definition
* <ul>
* <li>validation pattern: <code>3!a<AMOUNT>15</code></li>
* <li>parser pattern: <code>SN</code></li>
* <li>components pattern: <code>SN</code></li>
* </ul>
*
* <p>
* This class complies with standard release <strong>SRU2021</strong>
*/
@SuppressWarnings("unused")
@Generated
public class Field35A extends Field implements Serializable, AmountContainer {
/**
* Constant identifying the SRU to which this class belongs to.
*/
public static final int SRU = 2021;
private static final long serialVersionUID = 1L;
/**
* Constant with the field name 35A
*/
public static final String NAME = "35A";
/**
* same as NAME, intended to be clear when using static imports
*/
public static final String F_35A = "35A";
public static final String PARSER_PATTERN = "SN";
/**
* Components pattern
*
* Contains a description of the type for every component. This is <em>DEPRECATED</em>,
* use TYPES_PATTERN instead, because it distinguishes between N (number) and I (BigDecimal)
* @see #TYPES_PATTERN
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public static final String COMPONENTS_PATTERN = "SN";
/**
* Types pattern
*
* Contains a description of the type for every component, use instead of COMPONENTS_PATTERN.
* @since 9.2.7
*/
public static final String TYPES_PATTERN = "SI";
/**
* Component number for the Type subfield
*/
public static final Integer TYPE = 1;
/**
* Alternative (<em>DEPRECATED</em>) constant name for field's Type Component number
* @see #TYPE
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public static final Integer CURRENCY = 1;
/**
* Component number for the Quantity subfield
*/
public static final Integer QUANTITY = 2;
/**
* Alternative (<em>DEPRECATED</em>) constant name for field's Quantity Component number
* @see #QUANTITY
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public static final Integer AMOUNT = 2;
/**
* Default constructor. Creates a new field setting all components to null.
*/
public Field35A() {
super(2);
}
/**
* Creates a new field and initializes its components with content from the parameter value.
* @param value complete field value including separators and CRLF
*/
public Field35A(final String value) {
super(value);
}
/**
* Creates a new field and initializes its components with content from the parameter tag.
* The value is parsed with {@link #parse(String)}
* @throws IllegalArgumentException if the parameter tag is null or its tagname does not match the field name
* @since 7.8
*/
public Field35A(final Tag tag) {
this();
if (tag == null) {
throw new IllegalArgumentException("tag cannot be null.");
}
if (!StringUtils.equals(tag.getName(), "35A")) {
throw new IllegalArgumentException("cannot create field 35A from tag "+tag.getName()+", tagname must match the name of the field.");
}
parse(tag.getValue());
}
/**
* Copy constructor.<br>
* Initializes the components list with a deep copy of the source components list.
* @param source a field instance to copy
* @since 7.7
*/
public static Field35A newInstance(Field35A source) {
Field35A cp = new Field35A();
cp.setComponents(new ArrayList<>(source.getComponents()));
return cp;
}
/**
* Create a Tag with this field name and the given value.
* Shorthand for <code>new Tag(NAME, value)</code>
* @see #NAME
* @since 7.5
*/
public static Tag tag(final String value) {
return new Tag(NAME, value);
}
/**
* Create a Tag with this field name and an empty string as value
* Shorthand for <code>new Tag(NAME, "")</code>
* @see #NAME
* @since 7.5
*/
public static Tag emptyTag() {
return new Tag(NAME, "");
}
/**
* Parses the parameter value into the internal components structure.
*
* <p>Used to update all components from a full new value, as an alternative
* to setting individual components. Previous component values are overwritten.
*
* @param value complete field value including separators and CRLF
* @since 7.8
*/
@Override
public void parse(final String value) {
init(2);
setComponent1(SwiftParseUtils.getAlphaPrefix(value));
setComponent2(SwiftParseUtils.getNumericSuffix(value));
}
/**
* Serializes the fields' components into the single string value (SWIFT format)
*/
@Override
public String getValue() {
final StringBuilder result = new StringBuilder();
result.append(joinComponents());
return result.toString();
}
/**
* Returns a localized suitable for showing to humans string of a field component.<br>
*
* @param component number of the component to display
* @param locale optional locale to format date and amounts, if null, the default locale is used
* @return formatted component value or null if component number is invalid or not present
* @throws IllegalArgumentException if component number is invalid for the field
* @since 7.8
*/
@Override
public String getValueDisplay(int component, Locale locale) {
if (component < 1 || component > 2) {
throw new IllegalArgumentException("invalid component number " + component + " for field 35A");
}
if (component == 1) {
//default format (as is)
return getComponent(1);
}
if (component == 2) {
//amount, rate
java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance(notNull(locale));
f.setMaximumFractionDigits(13);
BigDecimal n = getComponent2AsBigDecimal();
if (n != null) {
return f.format(n);
}
}
return null;
}
/**
* Returns the field components pattern
*
* This method is <em>DEPRECATED</em>, use <code>typesPattern()</code> instead.
* @see #typesPattern()
* @return the static value of Field35A.COMPONENTS_PATTERN
*/
@Override
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public final String componentsPattern() {
return COMPONENTS_PATTERN;
}
/**
* Returns the field component types pattern
*
* This method returns a letter representing the type for each component in the Field. It supersedes
* the Components Pattern because it distinguishes between N (Number) and I (BigDecimal).
* @since 9.2.7
* @see #TYPES_PATTERN
* @return the static value of Field35A.TYPES_PATTERN
*/
@Override
public final String typesPattern() {
return TYPES_PATTERN;
}
/**
* Returns the field parser pattern
* @return the static value of Field35A.PARSER_PATTERN
*/
@Override
public final String parserPattern() {
return PARSER_PATTERN;
}
/**
* Returns the field validator pattern
*/
@Override
public final String validatorPattern() {
return "3!a<AMOUNT>15";
}
/**
* Given a component number it returns true if the component is optional,
* regardless of the field being mandatory in a particular message.<br>
* Being the field's value conformed by a composition of one or several
* internal component values, the field may be present in a message with
* a proper value but with some of its internal components not set.
*
* @param component component number, first component of a field is referenced as 1
* @return true if the component is optional for this field, false otherwise
*/
@Override
public boolean isOptional(int component) {
return false;
}
/**
* Returns true if the field is a GENERIC FIELD as specified by the standard.
* @return true if the field is generic, false otherwise
*/
@Override
public boolean isGeneric() {
return false;
}
/**
* Returns the defined amount of components.<br>
* This is not the amount of components present in the field instance, but the total amount of components
* that this field accepts as defined.
* @since 7.7
*/
@Override
public int componentsSize() {
return 2;
}
/**
* Returns english label for components.
* <br>
* The index in the list is in sync with specific field component structure.
* @see #getComponentLabel(int)
* @since 7.8.4
*/
@Override
public List<String> getComponentLabels() {
List<String> result = new ArrayList<>();
result.add("Type");
result.add("Quantity");
return result;
}
/**
* Returns a mapping between component numbers and their label in camel case format.
* @since 7.10.3
*/
@Override
protected Map<Integer, String> getComponentMap() {
Map<Integer, String> result = new HashMap<>();
result.put(1, "type");
result.put(2, "quantity");
return result;
}
/**
* Gets the component 1 (Type).
* @return the component 1
*/
public String getComponent1() {
return getComponent(1);
}
/**
* Gets the Type (component 1).
* @return the Type from component 1
*/
public String getType() {
return getComponent1();
}
/**
* Alternative <em>DEPRECATED</em> method getter for field's Type
* @see #getType()
* @since 9.2.7
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public String getCurrency() {
return getType();
}
/**
* Gets the component 2 (Quantity).
* @return the component 2
*/
public String getComponent2() {
return getComponent(2);
}
/**
* Get the component 2 as BigDecimal
*
* @return the component 2 converted to BigDecimal or null if cannot be converted
* @since 9.2.7
*/
public java.math.BigDecimal getComponent2AsBigDecimal() {
return SwiftFormatUtils.getBigDecimal(getComponent(2));
}
/**
* Get the component 2 as Number (BigDecimal)
*
* The value is returned as BigDecimal to keep compatibility with previous API. You should
* use <code>getComponent2AsBigDecimal()</code> to get the proper value.
*
* @return the component 2 converted to Number (BigDecimal) or null if cannot be converted
* @see #getComponent2AsBigDecimal()
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public java.lang.Number getComponent2AsNumber() {
return getComponent2AsBigDecimal();
}
/**
* Gets the Quantity (component 2).
* @return the Quantity from component 2
*/
public String getQuantity() {
return getComponent2();
}
/**
* Alternative <em>DEPRECATED</em> method getter for field's Quantity
* @see #getQuantity()
* @since 9.2.7
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public String getAmount() {
return getQuantity();
}
/**
* Get the Quantity (component 2) as BigDecimal
* @return the Quantity from component 2 converted to BigDecimal or null if cannot be converted
* @since 9.2.7
*/
public java.math.BigDecimal getQuantityAsBigDecimal() {
return getComponent2AsBigDecimal();
}
/**
* Get the Quantity (component 2) as as Number (BigDecimal)
*
* The value is returned as BigDecimal to keep compatibility with previous API. You should
* use <code>getComponent2AsBigDecimal()</code> to get the proper value.
*
* @return the component 2 converted to Number (BigDecimal) or null if cannot be converted
* @see #getQuantityAsBigDecimal()
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public java.lang.Number getQuantityAsNumber() {
return getComponent2AsNumber();
}
/**
* Alternative <em>DEPRECATED</em> method getter for field's Quantity as BigDecimal
* @see #getQuantityAsBigDecimal()
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public java.math.BigDecimal getAmountAsBigDecimal() {
return getQuantityAsBigDecimal();
}
/**
* Alternative <em>DEPRECATED</em> method getter for field's Quantity (component 2) as as Number (BigDecimal)
*
* The value is returned as BigDecimal to keep compatibility with previous API. You should
* use <code>getComponent2AsBigDecimal()</code> to get the proper value.
*
* @return the component 2 converted to Number (BigDecimal) or null if cannot be converted
* @see #getQuantityAsBigDecimal()
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public java.lang.Number getAmountAsNumber() {
return getQuantityAsNumber();
}
/**
* Set the component 1 (Type).
*
* @param component1 the Type to set
* @return the field object to enable build pattern
*/
public Field35A setComponent1(String component1) {
setComponent(1, component1);
return this;
}
/**
* Set the Type (component 1).
*
* @param component1 the Type to set
* @return the field object to enable build pattern
*/
public Field35A setType(String component1) {
return setComponent1(component1);
}
/**
* Alternative <em>DEPRECATED</em> method setter for field's Type
*
* @see #setType(String)
*
* @param component1 the Type to set
* @return the field object to enable build pattern
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public Field35A setCurrency(String component1) {
return setType(component1);
}
/**
* Set the component 2 (Quantity).
*
* @param component2 the Quantity to set
* @return the field object to enable build pattern
*/
public Field35A setComponent2(String component2) {
setComponent(2, component2);
return this;
}
/**
* Set the component2 from a BigDecimal object.
* <br>
* Parses the BigDecimal into a SWIFT amount with truncated zero decimals and mandatory decimal separator.
* <ul>
* <li>Example: 1234.00 -> 1234,</li>
* <li>Example: 1234 -> 1234,</li>
* <li>Example: 1234.56 -> 1234,56</li>
* </ul>
* @since 9.2.7
*
* @param component2 the BigDecimal with the Quantity content to set
* @return the field object to enable build pattern
*/
public Field35A setComponent2(java.math.BigDecimal component2) {
setComponent(2, SwiftFormatUtils.getBigDecimal(component2));
return this;
}
/**
* Alternative method setter for field's Quantity (component 2) as as Number
*
* This method supports java constant value boxing for simpler coding styles (ex: 10.0 becomes an Float)
*
* @param component2 the Number with the Quantity content to set
* @return the field object to enable build pattern
* @see #setQuantity(java.math.BigDecimal)
*/
public Field35A setComponent2(java.lang.Number component2) {
// NOTE: remember instanceof implicitly checks for non-null
if (component2 instanceof BigDecimal) {
setComponent(2, SwiftFormatUtils.getBigDecimal( (BigDecimal) component2));
} else if (component2 instanceof BigInteger) {
setComponent(2, SwiftFormatUtils.getBigDecimal(new BigDecimal( (BigInteger) component2)));
} else if (component2 instanceof Long || component2 instanceof Integer) {
setComponent(2, SwiftFormatUtils.getBigDecimal(BigDecimal.valueOf(component2.longValue())));
} else if (component2 != null) {
// it's other non-null Number (Float, Double, etc...)
setComponent(2, SwiftFormatUtils.getBigDecimal(BigDecimal.valueOf(component2.doubleValue())));
} else {
// explicitly set component as null
setComponent(2, null);
}
return this;
}
/**
* Set the Quantity (component 2).
*
* @param component2 the Quantity to set
* @return the field object to enable build pattern
*/
public Field35A setQuantity(String component2) {
return setComponent2(component2);
}
/**
* Set the Quantity (component 2) from a BigDecimal object.
*
* @see #setComponent2(java.math.BigDecimal)
*
* @param component2 BigDecimal with the Quantity content to set
* @return the field object to enable build pattern
* @since 9.2.7
*/
public Field35A setQuantity(java.math.BigDecimal component2) {
return setComponent2(component2);
}
/**
* Alternative method setter for field's Quantity (component 2) as as Number
*
* This method supports java constant value boxing for simpler coding styles (ex: 10 becomes an Integer)
*
* @param component2 the Number with the Quantity content to set
* @return the field object to enable build pattern
* @see #setQuantity(java.math.BigDecimal)
*/
public Field35A setQuantity(java.lang.Number component2) {
return setComponent2(component2);
}
/**
* Alternative <em>DEPRECATED</em> method setter for field's Quantity
*
* @see #setQuantity(String)
*
* @param component2 the Quantity to set
* @return the field object to enable build pattern
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public Field35A setAmount(String component2) {
return setQuantity(component2);
}
/**
* Alternative <em>DEPRECATED</em> method setter for field's Quantity from a BigDecimal object.
*
* @see #setComponent2(java.math.BigDecimal)
*
* @param component2 BigDecimal with the Quantity content to set
* @return the field object to enable build pattern
* @since 9.2.7
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public Field35A setAmount(java.math.BigDecimal component2) {
return setQuantity(component2);
}
/**
* Alternative <em>DEPRECATED</em> method setter for field's Quantity (component 2) as as Number
*
* This method supports java constant value boxing for simpler coding styles (ex: 10 becomes an Integer)
*
* @param component2 the Number with the Quantity content to set
* @return the field object to enable build pattern
* @see #setQuantity(java.math.BigDecimal)
*/
@Deprecated
@ProwideDeprecated(phase2=TargetYear.SRU2022)
public Field35A setAmount(java.lang.Number component2) {
return setQuantity(component2);
}
/**
* Returns the list of all NON-NULL amounts as BigDecimal
*
* @return the list of NON-NULL amounts as BigDecimal values
* @see AmountResolver#amounts(Field)
*/
public List<BigDecimal> amounts() {
return AmountResolver.amounts(this);
}
/**
* Returns the first amounts as BigDecimal
*
* @return the first amount as BigDecimal value. Can be null
* @see AmountResolver#amount(Field)
*/
public BigDecimal amount() {
return AmountResolver.amount(this);
}
/**
* Returns the field's name composed by the field number and the letter option (if any)
* @return the static value of Field35A.NAME
*/
@Override
public String getName() {
return NAME;
}
/**
* Gets the first occurrence form the tag list or null if not found.
* @return null if not found o block is null or empty
* @param block may be null or empty
*/
public static Field35A get(final SwiftTagListBlock block) {
if (block == null || block.isEmpty()) {
return null;
}
final Tag t = block.getTagByName(NAME);
if (t == null) {
return null;
}
return new Field35A(t) ;
}
/**
* Gets the first instance of Field35A in the given message.
* @param msg may be empty or null
* @return null if not found or msg is empty or null
* @see #get(SwiftTagListBlock)
*/
public static Field35A get(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty())
return null;
return get(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field35A in the given message
* an empty list is returned if none found.
* @param msg may be empty or null in which case an empty list is returned
* @see #getAll(SwiftTagListBlock)
*/
public static List<Field35A> getAll(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty())
return java.util.Collections.emptyList();
return getAll(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field35A from the given block
* an empty list is returned if none found.
*
* @param block may be empty or null in which case an empty list is returned
*/
public static List<Field35A> getAll(final SwiftTagListBlock block) {
final List<Field35A> result = new ArrayList<>();
if (block == null || block.isEmpty()) {
return result;
}
final Tag[] arr = block.getTagsByName(NAME);
if (arr != null && arr.length > 0) {
for (final Tag f : arr) {
result.add( new Field35A(f));
}
}
return result;
}
/**
* This method deserializes the JSON data into a Field35A object.
* @param json JSON structure including tuples with label and value for all field components
* @return a new field instance with the JSON data parsed into field components or an empty field id the JSON is invalid
* @since 7.10.3
* @see Field#fromJson(String)
*/
public static Field35A fromJson(final String json) {
Field35A field = new Field35A();
JsonParser parser = new JsonParser();
JsonObject jsonObject = (JsonObject) parser.parse(json);
// **** COMPONENT 1 - Type
// first try using alias's names (including deprecated ones, if any)
if (jsonObject.get("currency") != null) {
field.setComponent1(jsonObject.get("currency").getAsString());
}
// last try using the official component's name (overwrites alternatives and DEPRECATED)
if (jsonObject.get("type") != null) {
field.setComponent1(jsonObject.get("type").getAsString());
}
// **** COMPONENT 2 - Quantity
// first try using alias's names (including deprecated ones, if any)
if (jsonObject.get("amount") != null) {
field.setComponent2(jsonObject.get("amount").getAsString());
}
// last try using the official component's name (overwrites alternatives and DEPRECATED)
if (jsonObject.get("quantity") != null) {
field.setComponent2(jsonObject.get("quantity").getAsString());
}
return field;
}
}
|
package fy.game.blockpuzzle.gamepiece.sets;
import fy.game.blockpuzzle.gamepiece.IGamePieceSet;
/** GENERATED */
public class GamePieceSet0031 implements IGamePieceSet {
@Override
public String[] getGamePieceSet() {
String[] r = new String[1600];
r[0] = "#2x2#5#2";
r[1] = "#4#4#5";
r[2] = "#2#4:...........1L............";
r[3] = "#5#3#5";
r[4] = "#5#1#2";
r[5] = "#1#5#2";
r[6] = "#Ecke2#Ecke2#4";
r[7] = "#1#5#4";
r[8] = "#4#Ecke2#5";
r[9] = "#3#2x2#2";
r[10] = "#2#1#Ecke3";
r[11] = "#2x2#Ecke3#3";
r[12] = "#4#1#2";
r[13] = "#4#5#3";
r[14] = "#2#3#3";
r[15] = "#Ecke2#4#2x2";
r[16] = "#Ecke3#Ecke2#1";
r[17] = "#Ecke3#3#Ecke2";
r[18] = "#4#1#Ecke2";
r[19] = "#2#1#2";
r[20] = "#4#5#4";
r[21] = "#2#5#Ecke3";
r[22] = "#Ecke3#1#5";
r[23] = "#5#Ecke2#5";
r[24] = "#Ecke2#2x2#2";
r[25] = "#5#5#2";
r[26] = "#Ecke2#Ecke3#3";
r[27] = "#4#Ecke3#5";
r[28] = "#5#3#Ecke2";
r[29] = "#2#J#2";
r[30] = "#Ecke2#3x3#1";
r[31] = "#3#3x3#4";
r[32] = "#1#1#Ecke2";
r[33] = "#2#5#1";
r[34] = "#4#4#2x2_Bonus";
r[35] = "#1#2#Ecke2";
r[36] = "#2x2:...........1L............#Ecke3";
r[37] = "#Ecke2#Ecke3#3";
r[38] = "#Ecke3#4#3";
r[39] = "#5#3#2x2_Bonus";
r[40] = "#2x2_Bonus#2#5";
r[41] = "#2x2#J#Ecke2";
r[42] = "#Ecke3#4#Ecke2";
r[43] = "#Ecke2#2x2_Bonus#3";
r[44] = "#2x2#3#3";
r[45] = "#Ecke2#Ecke2#J";
r[46] = "#Ecke3#Ecke2#3";
r[47] = "#1#4#3";
r[48] = "#5#Ecke2#5";
r[49] = "#3#1#Ecke2";
r[50] = "#1#1#Ecke3";
r[51] = "#2#3x3#Ecke2";
r[52] = "#3#3#5";
r[53] = "#5#1#Ecke2";
r[54] = "#Ecke2#3x3#3";
r[55] = "#L#Ecke2#1";
r[56] = "#J#2x3#Ecke3";
r[57] = "#5#Ecke2#2";
r[58] = "#5#Ecke3#3";
r[59] = "#3#1#1";
r[60] = "#2x3#L#2x2_Bonus";
r[61] = "#Ecke2#2#1";
r[62] = "#4#1#3";
r[63] = "#3#4#2x2_Bonus";
r[64] = "#4#2#3x3";
r[65] = "#5#1#J";
r[66] = "#1#2#Ecke3";
r[67] = "#4#3#1";
r[68] = "#Ecke2#5#Ecke2";
r[69] = "#3x3#4#2";
r[70] = ":......L....4....444......#4#2x2_Bonus";
r[71] = "#2x3_Bonus#Ecke3#3";
r[72] = "#Ecke3#5#3";
r[73] = "#3#1#3";
r[74] = "#2x2_Bonus#Ecke3:..1....1....S....1.......";
r[75] = "#3#5#5";
r[76] = "#1#Ecke2#4";
r[77] = "#J#3#Ecke2";
r[78] = "#2#L#3x3";
r[79] = "#Ecke2#3#Ecke3";
r[80] = "#Ecke3#2x2#Ecke2";
r[81] = "#1#2#1";
r[82] = "#J#Ecke3#1";
r[83] = "#2#2x2#2x2";
r[84] = "#2x3_Bonus#3#2";
r[85] = "#5#2#2";
r[86] = "#3#3#Ecke2";
r[87] = "#4#Ecke2#4";
r[88] = "#1#3#2";
r[89] = "#Ecke2#5#Ecke2";
r[90] = "#Z#4#Ecke2";
r[91] = "#1#5#1";
r[92] = "#Ecke3#Z#2x3_Bonus";
r[93] = "#3x3#3#1";
r[94] = "#Ecke2#2#3";
r[95] = "#5#Z#Ecke2";
r[96] = "#5#Z#2x3";
r[97] = "#4#5#4";
r[98] = "#Ecke3#2#Ecke2";
r[99] = "#2x3_Bonus#S#4";
r[100] = "#J#Ecke2#Ecke2";
r[101] = "#1#5#2x2_Bonus";
r[102] = "#4#Ecke3#3x3";
r[103] = "#L#Ecke2#3";
r[104] = ":...........L6....66......#3#4";
r[105] = "#5#Ecke3#2";
r[106] = "#Z#4#2";
r[107] = "#3#3#2x2";
r[108] = "#Ecke3#3#2";
r[109] = "#3#Ecke2#S";
r[110] = "#Ecke2#3#2x3_Bonus";
r[111] = "#4#3#2x3_Bonus";
r[112] = "#3#1#3";
r[113] = "#3#4#Ecke2";
r[114] = "#4#2#5";
r[115] = "#4#3x3#2x2_Bonus";
r[116] = "#2x3#Z#5";
r[117] = "#3#Ecke2#1";
r[118] = "#2x3_Bonus#4#4";
r[119] = "#3x3#2x3#Ecke2";
r[120] = "#Ecke2#Ecke3#Ecke3";
r[121] = "#2#3#Z";
r[122] = "#Ecke2#4#Ecke3";
r[123] = "#2x2_Bonus#5#Ecke3";
r[124] = "#5#J#5";
r[125] = "#4#Ecke2#5";
r[126] = "#1#Ecke2#Ecke2";
r[127] = "#2#1#3";
r[128] = "#5#3#Z";
r[129] = "#3x3#Ecke3#3";
r[130] = "#Z#2x2_Bonus#Ecke2";
r[131] = "#5#2#2";
r[132] = "#1#Ecke3#3";
r[133] = "#2x3_Bonus#1#2";
r[134] = ":......11S..111...........#5#2x3";
r[135] = "#3#2#Ecke2";
r[136] = "#T#Z#1";
r[137] = "#Ecke2#S#5";
r[138] = ":..........222L2..........#T#2x2";
r[139] = "#Ecke3#Ecke3#2";
r[140] = "#3#3#Ecke3";
r[141] = "#1#J#2";
r[142] = ":......333..S33..333......#Ecke2#3";
r[143] = "#Ecke3#1#Z";
r[144] = "#1#Z#1";
r[145] = "#Ecke2#T#T";
r[146] = "#Ecke2#T#Ecke2";
r[147] = "#2x2#3#2";
r[148] = "#3#3#1";
r[149] = "#3#Ecke2#3";
r[150] = "#Ecke2#L#3x3";
r[151] = "#3#L#4";
r[152] = "#Ecke2#4#1";
r[153] = "#5#Ecke2#Ecke3";
r[154] = "#5#5#3x3_Bonus2";
r[155] = "#Ecke2#T#2x2_Bonus";
r[156] = "#4#Ecke3#2x3_Bonus";
r[157] = "#2x2_Bonus#Ecke3#4";
r[158] = "#3#Ecke3#3x3_Bonus3";
r[159] = "#1#2x2_Bonus#Ecke3";
r[160] = "#3#3x3_Bonus1#Ecke3";
r[161] = "#Ecke2#Ecke3#Ecke2";
r[162] = "#Ecke2#J#5";
r[163] = "#2#5#4";
r[164] = "#T#T#T";
r[165] = "#3#J#1";
r[166] = "#5#3#1";
r[167] = "#2x3#L#1";
r[168] = "#2#5#3";
r[169] = "#Z#T#3x3_Bonus2";
r[170] = "#T#T#4";
r[171] = "#Ecke3#2#Ecke2";
r[172] = ":..........1L11...........#T#2";
r[173] = "#L#2#5";
r[174] = "#5#T#T";
r[175] = "#4#Ecke3#L";
r[176] = "#5#L#1";
r[177] = "#T#Ecke2#3";
r[178] = "#5#2#4";
r[179] = "#2#5#4";
r[180] = "#5#2x2#4";
r[181] = "#T#5#T";
r[182] = "#2x2_Bonus#4_Bonus#5";
r[183] = "#T#T#Ecke3";
r[184] = "#2x3#4#1";
r[185] = "#5#Ecke2#T";
r[186] = "#1#Ecke3#1";
r[187] = "#5#4#T";
r[188] = "#2#4#Ecke2";
r[189] = "#2x3#2#1";
r[190] = "#3#4#Ecke3";
r[191] = "#L#T#4_Bonus";
r[192] = "#4#2#3";
r[193] = "#Ecke3#Ecke3#1";
r[194] = "#3x3#J#3";
r[195] = "#Ecke3#T#3x3_Bonus2";
r[196] = "#3#3x3#2";
r[197] = "#2:......333..333..3S3......#T";
r[198] = "#Ecke3#Ecke2#2";
r[199] = "#T#2x3#T";
r[200] = "#2x2_Bonus#2#3x3_Bonus3";
r[201] = "#1#3#T";
r[202] = "#2#2#5";
r[203] = "#3#Ecke2#4";
r[204] = "#2x2#2#T";
r[205] = "#2x2#4#1";
r[206] = ":......33...L3............#4_Bonus#3";
r[207] = "#Ecke3_Bonus1B#3#T";
r[208] = "#2#3x3_Bonus3#Ecke2";
r[209] = "#Z#2#1";
r[210] = "#2x2_Bonus#2x2#Ecke3";
r[211] = "#4#3x3#2Dots";
r[212] = "#Ecke2#2Dots#4";
r[213] = "#2#3x3_Bonus1#4_Bonus";
r[214] = "#Ecke2#T#J";
r[215] = "#Ecke3#1#3";
r[216] = "#4#Ecke2#Ecke2";
r[217] = "#4#3#3";
r[218] = "#4#2#Ecke2";
r[219] = "#3#T#2";
r[220] = "#1#3x3_Bonus2#4";
r[221] = "#1#1#2Dots";
r[222] = "#T#Ecke2:......33S..333..333......";
r[223] = "#3x3_Bonus3#5#2";
r[224] = "#2#Ecke2#L";
r[225] = "#Z#1#3";
r[226] = "#T#Ecke3#2";
r[227] = "#3x3_Bonus1#Ecke2#T";
r[228] = "#5#3x3_Bonus3#4";
r[229] = "#3#Ecke3_Bonus1B#4";
r[230] = "#5#Ecke2#Ecke2";
r[231] = "#1#2x2_Bonus#1";
r[232] = "#2x2#Z#3";
r[233] = "#3#3x3#2x3";
r[234] = "#2x2_Bonus#X#5";
r[235] = "#5#1#T";
r[236] = "#4#T#1";
r[237] = "#3x3#Ecke3_Bonus1B#4";
r[238] = "#Ecke3#Ecke2#2";
r[239] = "#Z#3x3_Bonus3#1";
r[240] = ":......5....L55...........#3#3";
r[241] = "#4_Bonus#J#S";
r[242] = "#Ecke3_Bonus1B#2#4";
r[243] = "#2x3_Bonus#3x3_Bonus1#1";
r[244] = "#3#T#1";
r[245] = "#4_Bonus#Ecke2#3x3";
r[246] = "#4#3#3x3";
r[247] = "#3x3_Bonus1#5#Ecke3_Bonus1A";
r[248] = "#L#3#3";
r[249] = "#2x3:.......44...S............#Ecke2";
r[250] = "#1_Bonus1#1#2";
r[251] = "#4#1#4";
r[252] = "#2x3_Bonus#S#1";
r[253] = "#5#T#2x3_Bonus";
r[254] = "#3x3_Bonus2#2x2_Bonus#3";
r[255] = "#X#5#2";
r[256] = "#X#2#3x3_Bonus2";
r[257] = "#2x3#5#1";
r[258] = "#4_Bonus#1#5";
r[259] = "#Ecke3#2#Ecke3_Bonus1B";
r[260] = "#T#2x3_Bonus#Ecke3";
r[261] = "#5#T#3";
r[262] = "#T#Ecke3#5";
r[263] = "#3#2x2_Bonus#4_Bonus";
r[264] = "#3#3x3_Bonus3#Ecke2";
r[265] = "#3x3_Bonus1#3#2x2_Bonus";
r[266] = "#T#Ecke3_Bonus1B#Ecke3_Bonus1A";
r[267] = "#2x3_Bonus#Ecke2#2";
r[268] = "#Ecke2#3x3_Bonus2#2";
r[269] = "#1#Ecke3#5";
r[270] = "#2#2x3#Ecke3_Bonus1A";
r[271] = "#1_Bonus1#Ecke3#Ecke3";
r[272] = "#2#5#3x3";
r[273] = "#Ecke3_Bonus1B#3#T";
r[274] = ":.......1....L............#T#2";
r[275] = "#4#1#1";
r[276] = "#2x3_Bonus#1_Bonus1#2x2";
r[277] = "#Ecke3#3#3";
r[278] = "#1#Z#1";
r[279] = "#2x3#3x3#4";
r[280] = "#5#4_Bonus#4";
r[281] = "#S#Ecke3#5";
r[282] = "#4#4#2x2";
r[283] = "#Ecke3#Ecke3#2";
r[284] = "#2#4#3x3_Bonus1";
r[285] = "#1#2x2#Ecke2";
r[286] = "#T#2x3_Bonus#Ecke3_Bonus1B";
r[287] = "#4#3x3_Bonus2#3x3";
r[288] = "#2x3#T#1_Bonus1";
r[289] = "#4#Ecke2#Ecke3_Bonus1B";
r[290] = "#4#4_Bonus#Ecke3_Bonus1B";
r[291] = "#1_Bonus1#1_Bonus1#5";
r[292] = "#2x3_Bonus#S#3";
r[293] = "#4#4#4";
r[294] = "#X#3x3_Bonus1#3";
r[295] = "#Ecke3_Bonus1B#T#4";
r[296] = "#S#5#Ecke3";
r[297] = "#T#5#T";
r[298] = "#5#3x3_Bonus2#Ecke3";
r[299] = "#3x3_Bonus1#L#X";
r[300] = "#L#Z#3";
r[301] = "#T#Ecke3_Bonus1B#T";
r[302] = "#S#2#2x2";
r[303] = "#Ecke2#2#2Dots";
r[304] = "#3#1_Bonus1#5";
r[305] = "#2x3_Bonus#5#3x3";
r[306] = "#4#Ecke3#2";
r[307] = "#3x3#T:..1....L....1....1.......";
r[308] = "#Ecke2#4#4";
r[309] = "#3x3_Bonus3#Ecke3#Ecke2";
r[310] = "#X#3x3_Bonus2#4";
r[311] = "#1_Bonus1#3x3_Bonus1#2Dots";
r[312] = "#5#L#5";
r[313] = "#3x3#1_Bonus1#4";
r[314] = "#5#T#Ecke3_Bonus1A";
r[315] = "#Ecke3_Bonus1A#Ecke3_Bonus1B#2x3";
r[316] = "#2#1_Bonus1#2x3";
r[317] = "#1:......3S...33............#4_Bonus";
r[318] = "#T#Ecke2#Ecke3";
r[319] = "#4#4#3x3_Bonus1";
r[320] = "#4#Ecke3#2x2";
r[321] = "#4#4#2x2";
r[322] = "#2x3_Bonus#S#Ecke3";
r[323] = "#Ecke2#1#1_Bonus1";
r[324] = "#3#3x3#3";
r[325] = "#Ecke3#2#4";
r[326] = "#4#4#T";
r[327] = "#2x3_Bonus#5#Ecke2";
r[328] = "#4#X#4";
r[329] = "#3x3_Bonus3#J#5";
r[330] = "#2x2#3x3#3";
r[331] = "#2x3#4#2Dots";
r[332] = "#3x3#4#3";
r[333] = "#S#S#T";
r[334] = "#3#Ecke3#1";
r[335] = "#T#L#Ecke3";
r[336] = "#J#Ecke2#3x3_Bonus1";
r[337] = "#3x3_Bonus2#2x3#3x3_Bonus1";
r[338] = "#1#T#Ecke2";
r[339] = "#5#Ecke3#3x3_Bonus1";
r[340] = "#2#1_Bonus1#1";
r[341] = "#4#Z:......333..L33..333......";
r[342] = "#T#T#2x3_Bonus";
r[343] = "#Ecke2#Ecke3_Bonus1A#Ecke2";
r[344] = "#1#2#1_Bonus1";
r[345] = "#Ecke3#4_Bonus#2Dots";
r[346] = "#Ecke3#Ecke3_Bonus1A#1_Bonus1";
r[347] = "#3x3_Bonus1#3x3_Bonus1#T";
r[348] = "#2x3#1_Bonus1#3x3_Bonus3";
r[349] = "#Ecke3_Bonus1B#2#2x3_Bonus";
r[350] = "#4#5#1";
r[351] = "#5#T#Ecke2";
r[352] = "#2x2#3#T";
r[353] = "#Ecke2#2#1_Bonus1";
r[354] = "#3x3#X#2x3_Bonus";
r[355] = "#1#5#3";
r[356] = "#2Dots#Ecke3#4";
r[357] = "#3#3x3_Bonus3#3";
r[358] = "#3#3x3#T";
r[359] = "#2x2_Bonus#1#Ecke2";
r[360] = "#4#3#3x3";
r[361] = "#L#T#3x3_Bonus1";
r[362] = "#J#4_Bonus#5";
r[363] = "#Ecke2#4#1";
r[364] = "#4_Bonus#4#3";
r[365] = "#3#5#X";
r[366] = "#4#Z#4_Bonus";
r[367] = "#T#Ecke3_Bonus1B#Ecke2";
r[368] = "#3x3#L#T";
r[369] = "#4#4#Ecke2";
r[370] = "#Ecke3_Bonus1A#3x3#L";
r[371] = "#4#S#T";
r[372] = "#T#3x3_Bonus3#3";
r[373] = "#4#Ecke3#T";
r[374] = "#1#L#4";
r[375] = "#3x3_Bonus3:......L3...33............#Ecke3";
r[376] = "#S#1#X";
r[377] = "#1#T#5";
r[378] = "#1_Bonus1#3x3#X";
r[379] = "#1#3#2x3";
r[380] = "#Ecke3#2x2#L";
r[381] = "#T#T#T";
r[382] = "#3x3#3#S";
r[383] = "#4#3x3_Bonus2#4";
r[384] = "#3#2#1";
r[385] = "#5#1_Bonus1#2x2_Bonus";
r[386] = "#2#2x3#3x3_Bonus1";
r[387] = "#4#5#2";
r[388] = "#1_Bonus1#T#1";
r[389] = "#J#4_Bonus#3x3";
r[390] = "#4_Bonus#3#2Dots";
r[391] = "#5#Ecke3_Bonus1A#Ecke2";
r[392] = "#3x3_Bonus2#4_Bonus#L";
r[393] = "#Z#Z#J";
r[394] = "#3#1#2Dots";
r[395] = "#4_Bonus#2#T";
r[396] = "#Ecke3_Bonus1B#T#4_Bonus";
r[397] = "#4#S#Ecke3_Bonus1B";
r[398] = "#Ecke2#3x3_Bonus2#2x3_Bonus";
r[399] = "#Ecke2#4#T";
r[400] = "#4#3#3x3_Bonus2";
r[401] = "#3#4#3x3_Bonus3";
r[402] = "#Ecke3#5#T";
r[403] = "#2#4#3";
r[404] = "#3#1_Bonus1#2";
r[405] = "#2Dots#T#3x3";
r[406] = "#S#T#4";
r[407] = "#1#2#1_Bonus1";
r[408] = "#Z#2#Ecke3_Bonus1A";
r[409] = ":...........55L...5.......#3#4_Bonus";
r[410] = "#4#2#X";
r[411] = "#2Dots#4#2Dots";
r[412] = "#T#3x3_Bonus3#T";
r[413] = "#3x3#4#Ecke3";
r[414] = "#Ecke2#1#Ecke2";
r[415] = "#2#Ecke3_Bonus1B#2x3";
r[416] = "#2#Ecke3_Bonus1B#Ecke2";
r[417] = "#T#T#Ecke3_Bonus2";
r[418] = "#3x3_Bonus2#3#3";
r[419] = "#2x2#T#1";
r[420] = "#L#J#3x3_Bonus3";
r[421] = "#2Dots#3#T";
r[422] = "#2x2_Bonus#4#5";
r[423] = "#T#3x3#3x3_Bonus2";
r[424] = "#T#2Dots#Ecke3";
r[425] = "#3#Z#T";
r[426] = "#2#3x3_Bonus3#Z";
r[427] = "#Ecke3#1#Ecke3";
r[428] = "#5#Ecke3_Bonus1B#5";
r[429] = "#2x2#Ecke3_Bonus2#2";
r[430] = "#1_Bonus1#2#1";
r[431] = "#2#2x2_Bonus#1_Bonus1";
r[432] = "#2x3#1#Ecke3_Bonus1B";
r[433] = "#3#2x2_Bonus#Ecke3";
r[434] = "#2#T#Z";
r[435] = "#T#2#4";
r[436] = "#1_Bonus1#3x3_Bonus3#2";
r[437] = "#T#2x3_Bonus#2x3_Bonus";
r[438] = "#T#3#Ecke3";
r[439] = "#Ecke3#Ecke3#3";
r[440] = "#T#4#S";
r[441] = "#3#T#4";
r[442] = "#Ecke2#X:..1....L....1....1.......";
r[443] = "#3#3#5";
r[444] = "#3#Ecke3#Ecke3_Bonus1B";
r[445] = "#1_Bonus1#3#T";
r[446] = "#1#3#3";
r[447] = "#5#5#2";
r[448] = "#Ecke3#3#4";
r[449] = "#T#1#2Dots";
r[450] = "#2x3_Bonus#X#T";
r[451] = "#3#L#Ecke2";
r[452] = "#S#1#Ecke3";
r[453] = "#3x3_Bonus3#Ecke3#3x3_Bonus2";
r[454] = "#1_Bonus1#L#1";
r[455] = "#T#S#3x3_Bonus1";
r[456] = "#T#Ecke3#1";
r[457] = "#Ecke2#2#4";
r[458] = "#2#2x3_Bonus#3x3";
r[459] = "#5#3x3_Bonus1:......333..S33..333......";
r[460] = "#2x2_Bonus#Ecke2#4";
r[461] = "#T#T#Ecke3_Bonus1B";
r[462] = "#1#X#4";
r[463] = "#5#Ecke3_Bonus1A#5";
r[464] = "#L#3#2x3";
r[465] = "#Ecke3_Bonus2#2#3";
r[466] = "#Ecke2#3x3_Bonus1#3x3_Bonus1";
r[467] = "#Z#1#3";
r[468] = "#2x3#4#2x3";
r[469] = "#4#Ecke2#T";
r[470] = "#2#Ecke2#Z";
r[471] = "#1#3x3_Bonus2#J";
r[472] = "#3x3_Bonus2#X#T";
r[473] = "#Ecke2#4#Ecke3_Bonus2";
r[474] = "#3x3_Bonus3#J#2x2";
r[475] = "#4#3x3_Bonus2#Ecke2";
r[476] = "#1#3x3:..L....1....1....1.......";
r[477] = "#Ecke2#T#1";
r[478] = "#2#T#5";
r[479] = "#2x3#3x3_Bonus2#Ecke3";
r[480] = "#1#2x2_Bonus#2";
r[481] = "#Ecke3#Ecke2#4";
r[482] = "#Ecke2#Ecke2#4";
r[483] = "#3#4_Bonus#3x3_Bonus1";
r[484] = "#3x3_Bonus3#5#1_Bonus1";
r[485] = "#5#4#Ecke3";
r[486] = "#1#Ecke3_Bonus1B#3x3_Bonus3";
r[487] = "#5#1#1_Bonus1";
r[488] = "#3#1_Bonus1#Ecke3_Bonus1A";
r[489] = "#Ecke2#Ecke3#3x3";
r[490] = "#Ecke3#3x3_Bonus2#T";
r[491] = "#4_Bonus#3#Ecke3";
r[492] = "#Ecke3#3x3_Bonus2#2x3_Bonus";
r[493] = "#2Dots#4#Z";
r[494] = "#Ecke3#5#Ecke3_Bonus1B";
r[495] = "#3#S#4_Bonus";
r[496] = "#T#Z#3x3";
r[497] = "#Ecke2#1_Bonus1#Ecke3_Bonus1A";
r[498] = "#1#Ecke2#Ecke3";
r[499] = "#3#T#2x3_Bonus";
r[500] = "#3#2#Z";
r[501] = "#Ecke2#X#2";
r[502] = "#4_Bonus#3x3_Bonus1#4";
r[503] = "#Ecke3#2x3_Bonus#2x2";
r[504] = "#3#2x3_Bonus#2Dots";
r[505] = "#2#1_Bonus1#Ecke2";
r[506] = "#Ecke3#1_Bonus1#3x3";
r[507] = "#Ecke2#2#Ecke2";
r[508] = "#3x3_Bonus3#3#3x3";
r[509] = "#Ecke3#T#2x2";
r[510] = "#Ecke2:............L............#1";
r[511] = "#2#Ecke2#1";
r[512] = "#Ecke3_Bonus2#Ecke3#S";
r[513] = "#T#3#2x3_Bonus";
r[514] = "#3#5#Z";
r[515] = "#Ecke2#1_Bonus1#2x3_Bonus";
r[516] = "#Ecke2#Ecke3_Bonus2#Ecke3_Bonus1B";
r[517] = "#4_Bonus#Ecke2#3x3";
r[518] = "#Ecke3#X#Ecke3_Bonus1A";
r[519] = "#3#4#3";
r[520] = "#3#2#Ecke3";
r[521] = "#1_Bonus1#Ecke3_Bonus1A#4";
r[522] = "#T#Ecke3#3";
r[523] = "#Ecke3_Bonus1B#4#3";
r[524] = "#3#4#3x3_Bonus1";
r[525] = "#X#5#3";
r[526] = "#4#X#4";
r[527] = "#2x2#2#3";
r[528] = "#3#Ecke2#3x3_Bonus1";
r[529] = "#1_Bonus1#3x3_Bonus1#4";
r[530] = "#5#Ecke3#Ecke2";
r[531] = "#2#3x3_Bonus1#4";
r[532] = "#3#1_Bonus1#2x3_Bonus";
r[533] = "#4#5#2";
r[534] = "#T#4_Bonus#Ecke3_Bonus1B";
r[535] = "#J#Ecke2#Slash";
r[536] = "#L#2x3#4";
r[537] = "#L#1#Ecke2";
r[538] = "#5#3#Ecke3";
r[539] = "#2x2_Bonus#5#2x2";
r[540] = "#5#5#1_Bonus1";
r[541] = "#4#4#4";
r[542] = "#4#Ecke3#T";
r[543] = "#3x3_Bonus1#2#5";
r[544] = ":.......1....L....1.......#T#T";
r[545] = "#Ecke2#2x3_Bonus#5";
r[546] = "#3#Ecke3#Ecke2";
r[547] = "#3#3#L";
r[548] = "#1#3#L";
r[549] = "#4#Ecke2#3";
r[550] = "#T#3x3#Ecke2";
r[551] = "#2#2#2Dots";
r[552] = "#Z#2x3_Bonus#1_Bonus1";
r[553] = "#T#5#2";
r[554] = "#2#2x3_Bonus#2Dots";
r[555] = "#2x3#T#3x3_Bonus2";
r[556] = "#4#Ecke3#5";
r[557] = "#3x3_Bonus2#4#2x2";
r[558] = "#Z#Ecke2#1";
r[559] = "#Slash#2x2#3";
r[560] = "#5#2x3#T";
r[561] = "#Z#3x3_Bonus1#5";
r[562] = "#Ecke2#2x2_Bonus#2Dots";
r[563] = "#Ecke3_Bonus2#3#5";
r[564] = "#1#1_Bonus1#3";
r[565] = "#3x3#2#3x3_Bonus2";
r[566] = "#Ecke3#2#Ecke2";
r[567] = "#3x3_Bonus1#1#1";
r[568] = "#1_Bonus1#4_Bonus#1";
r[569] = "#T#Ecke2#T";
r[570] = "#4#Ecke2#Ecke3_Bonus1A";
r[571] = "#T#2#2Dots";
r[572] = "#S#3#2";
r[573] = "#Ecke2#4#2";
r[574] = "#4_Bonus#3#1";
r[575] = "#T#5#T";
r[576] = "#3x3_Bonus1#5#1_Bonus1";
r[577] = "#2x2_Bonus#X:........L...5...5........";
r[578] = "#Ecke2#3x3_Bonus3#Ecke2";
r[579] = "#2#4#Ecke2";
r[580] = "#2#4_Bonus#4_Bonus";
r[581] = "#3x3_Bonus3#Ecke2#1";
r[582] = "#3#2x2_Bonus#Ecke3_Bonus2";
r[583] = "#Z#4#J";
r[584] = "#5#3x3#2";
r[585] = "#3x3#3#X";
r[586] = "#1#2#3";
r[587] = "#3x3_Bonus2#3#2x2_Bonus";
r[588] = "#4#3#Ecke3";
r[589] = "#4#2#2x3_Bonus";
r[590] = "#1#1_Bonus1#Ecke2";
r[591] = "#4#Ecke3#Ecke3_Bonus2";
r[592] = "#T#S#3x3_Bonus2";
r[593] = "#3#T#1_Bonus1";
r[594] = "#2#L#4";
r[595] = "#Ecke3#Ecke3_Bonus2#L";
r[596] = "#2x3_Bonus#2x3_Bonus#L";
r[597] = "#X#Ecke2#1";
r[598] = "#4#1#Ecke3";
r[599] = "#2x2_Bonus#3x3_Bonus3#S";
r[600] = "#2#T#L";
r[601] = "#3x3_Bonus3#1_Bonus1#2x3_Bonus";
r[602] = "#L#Ecke3#2x2_Bonus";
r[603] = "#2#1#Ecke3";
r[604] = "#3#T#2";
r[605] = "#Ecke3_Bonus1B#4#3";
r[606] = "#2#5#3x3_Bonus2";
r[607] = "#Ecke3_Bonus2#4#T";
r[608] = "#Ecke2#3x3_Bonus3#3x3_Bonus3";
r[609] = "#4#3x3_Bonus1:...........S11...........";
r[610] = "#5#Ecke3_Bonus1B#2";
r[611] = "#5#3x3_Bonus3:......444....4....L......";
r[612] = "#Ecke2#X#2x3_Bonus";
r[613] = "#X#3#3";
r[614] = "#1:............S............#4";
r[615] = "#Slash#X#1";
r[616] = "#1#3x3_Bonus1#Ecke2";
r[617] = "#1#2x3_Bonus#X";
r[618] = "#2#Ecke2#2x3_Bonus";
r[619] = "#X#T#Slash";
r[620] = "#2x3_Bonus#2#Ecke3_Bonus1B";
r[621] = "#3#2x3#Ecke2";
r[622] = "#Ecke2#Z#4";
r[623] = "#Ecke2#2Dots#2";
r[624] = "#2x2_Bonus#3x3_Bonus3#3x3_Bonus1";
r[625] = "#2x3_Bonus#1_Bonus1#4";
r[626] = "#Z#2#1";
r[627] = "#3x3_Bonus2#2#1";
r[628] = "#2x2_Bonus#Slash#3x3_Bonus3";
r[629] = "#2#3x3_Bonus2#T";
r[630] = "#3#2x2#3";
r[631] = "#5#5#2x3_Bonus";
r[632] = "#2x3_Bonus#3#2";
r[633] = "#3#Ecke3#4";
r[634] = "#2#T#1";
r[635] = "#3x3_Bonus1#Ecke2#3x3";
r[636] = "#5#Z#3";
r[637] = "#L#Ecke2#Ecke2";
r[638] = "#3x3#3x3_Bonus2#5";
r[639] = "#T#T#3x3";
r[640] = "#5#Ecke3_Bonus1B#Ecke3";
r[641] = "#2#T#1_Bonus1";
r[642] = "#T#1_Bonus1#2x3";
r[643] = "#Ecke2#T#4";
r[644] = "#5#Ecke3_Bonus2#2";
r[645] = "#3x3_Bonus1#4:...........11L...........";
r[646] = "#Ecke2#Ecke3#3x3_Bonus2";
r[647] = "#Ecke2#T#Ecke3_Bonus2";
r[648] = "#Ecke3_Bonus1A#T#Ecke3_Bonus2";
r[649] = "#2#3x3_Bonus2#Ecke3_Bonus2";
r[650] = "#Ecke2#Z#3";
r[651] = "#2#T#T";
r[652] = "#3#Ecke2#S";
r[653] = "#4_Bonus#2#Ecke2";
r[654] = "#Ecke2#2Dots#2x3_Bonus";
r[655] = "#4#4_Bonus#Ecke2";
r[656] = "#4#Ecke2#Ecke2";
r[657] = "#T#5#5";
r[658] = "#1_Bonus1#Ecke2#4";
r[659] = "#Ecke3#Ecke2#Ecke2";
r[660] = "#2#2#S";
r[661] = "#1_Bonus1#S#Z";
r[662] = "#T#Ecke3#Ecke2";
r[663] = "#T#3#Ecke3";
r[664] = "#2x3_Bonus#Ecke2#Ecke2";
r[665] = "#1#3#Ecke2";
r[666] = "#1#S#Ecke2";
r[667] = "#2Dots#1#Ecke3";
r[668] = "#Z#4#4";
r[669] = "#5#3#1_Bonus1";
r[670] = "#2#Ecke2#Z";
r[671] = "#2x2_Bonus#T#3";
r[672] = "#4#Slash#T";
r[673] = "#3x3#2Dots#3";
r[674] = "#5#Ecke2#Ecke3";
r[675] = "#Ecke3#2#Ecke3_Bonus1A";
r[676] = "#L#2#2x2";
r[677] = "#T#T#S";
r[678] = "#Ecke2#2#4";
r[679] = "#3:............L............#4";
r[680] = "#2#Ecke3#1";
r[681] = "#L#Ecke3#L";
r[682] = "#Ecke3_Bonus1B#2x2#Ecke2";
r[683] = "#1#Z#Ecke3_Bonus1B";
r[684] = "#3#1_Bonus1#Ecke3";
r[685] = "#1#2x3_Bonus#3";
r[686] = "#1_Bonus1#1#4";
r[687] = "#Ecke3_Bonus1A#4#Ecke3_Bonus1B";
r[688] = "#J#Z#1";
r[689] = "#Ecke3_Bonus2#Ecke2#3x3";
r[690] = "#T#Ecke3_Bonus1B#3x3_Bonus2";
r[691] = "#1#S#Z";
r[692] = "#3x3_Bonus2#Ecke3_Bonus1A#2x3_Bonus";
r[693] = "#2#5#1";
r[694] = "#Ecke3#Ecke2#Ecke2";
r[695] = "#Ecke2#T#Ecke3_Bonus1A";
r[696] = "#T#T#3x3_Bonus4";
r[697] = "#S#Ecke3_Bonus2#3x3";
r[698] = "#3#4#Ecke2";
r[699] = "#Ecke3_Bonus1B#2x2#4";
r[700] = "#2#3x3#Slash";
r[701] = "#Ecke3_Bonus1A#4#L";
r[702] = "#Ecke2#2#1";
r[703] = "#2#4#Ecke2";
r[704] = "#3x3_Bonus3#5#T";
r[705] = "#2x3#T#3";
r[706] = "#5#1#4";
r[707] = "#3x3#Ecke2#3";
r[708] = ":......333..333..3S3......#3x3_Bonus2#Ecke3_Bonus1B";
r[709] = "#3x3_Bonus3#T#3";
r[710] = "#Slash#4#X";
r[711] = "#2Dots#X#T";
r[712] = "#1#2Dots#2Dots";
r[713] = "#1_Bonus1:..........1L11...........#Ecke3";
r[714] = "#3#2x3_Bonus#1";
r[715] = "#Ecke2#T#Ecke3";
r[716] = "#Slash#T#2x2_Bonus";
r[717] = "#3x3_Bonus1#5#2";
r[718] = "#3x3_Bonus1#L#3";
r[719] = "#S#T#3x3_Bonus2";
r[720] = "#Ecke2#2#T";
r[721] = "#1_Bonus1#2x2#Z";
r[722] = "#2x2_Bonus#3#4";
r[723] = "#T#2Dots#Z";
r[724] = "#2x3_Bonus#Ecke3_Bonus2#2x3_Bonus";
r[725] = "#3x3_Bonus1#Ecke3_Bonus1B#5";
r[726] = "#Ecke3#Slash#3";
r[727] = "#4#Ecke2#1";
r[728] = "#3x3_Bonus3#2Dots#4";
r[729] = "#3x3_Bonus3#4#5";
r[730] = "#2#2#X";
r[731] = "#1#Slash#3x3_Bonus4";
r[732] = "#T#Slash#2x3";
r[733] = "#Ecke3#1_Bonus1#5";
r[734] = "#4_Bonus#Ecke3#J";
r[735] = "#5#Ecke3_Bonus1B#3x3_Bonus3";
r[736] = "#3x3_Bonus2#Ecke3_Bonus1B#2";
r[737] = "#S#Ecke3#T";
r[738] = "#3#T#2Dots";
r[739] = "#4#2#5";
r[740] = "#J#4#4";
r[741] = "#S#Ecke3_Bonus1A#4";
r[742] = "#Z#2#Ecke3_Bonus2";
r[743] = "#Ecke2#3#Slash";
r[744] = "#5#1_Bonus1#4";
r[745] = "#1#2#3";
r[746] = "#5#T#2x3";
r[747] = ":......4....4....4L4......#T#4_Bonus";
r[748] = "#Ecke3#5#Ecke2";
r[749] = "#1#3#2Dots";
r[750] = "#3x3#3x3_Bonus4#5";
r[751] = "#1#2Dots#2x3_Bonus";
r[752] = "#4_Bonus#Ecke2#X";
r[753] = "#3x3_Bonus2#2x2#Ecke3";
r[754] = "#4#Ecke3#3x3_Bonus3";
r[755] = "#S#4#2x2";
r[756] = "#1_Bonus1#Ecke3_Bonus1B#T";
r[757] = "#Ecke3#1_Bonus1#5";
r[758] = "#5#4#5";
r[759] = "#Ecke3#4#2";
r[760] = "#T#4#1";
r[761] = "#2#4#3x3_Bonus3";
r[762] = "#2x3#J#1_Bonus1";
r[763] = "#3#Ecke3_Bonus2#T";
r[764] = "#4#4#Z";
r[765] = "#1_Bonus1#1:......33...3S............";
r[766] = "#Ecke2#3x3#Slash";
r[767] = "#3#Ecke3_Bonus1B#3x3_Bonus3";
r[768] = "#3x3#3#4";
r[769] = "#2#3x3_Bonus2#Ecke3_Bonus1A";
r[770] = "#T#2x3_Bonus#T";
r[771] = "#Ecke2#S#T";
r[772] = "#2x3#Ecke3_Bonus2#T";
r[773] = "#2#2Dots#T";
r[774] = "#2#Ecke2#L";
r[775] = "#J#T#Ecke3_Bonus2";
r[776] = "#3#T#3x3_Bonus4";
r[777] = "#Ecke2#1_Bonus1#5";
r[778] = "#Ecke3_Bonus1A#2x2#4";
r[779] = "#T#1_Bonus1#1";
r[780] = "#Ecke3#L#4";
r[781] = ":......33L..333..333......#3x3#Ecke2";
r[782] = "#3#Ecke3#Ecke3";
r[783] = "#3x3_Bonus1#3#Slash";
r[784] = "#Slash#4_Bonus#3";
r[785] = "#3x3_Bonus1#2#5";
r[786] = "#4_Bonus#Ecke3_Bonus1B#Slash";
r[787] = "#Ecke3#4#1";
r[788] = "#Ecke3_Bonus1B#3x3_Bonus3#2Dots";
r[789] = "#1#4#5";
r[790] = "#1#T#Ecke3";
r[791] = "#Z#J#2";
r[792] = "#5#1_Bonus1#T";
r[793] = "#1_Bonus1#T#2x2_Bonus";
r[794] = "#4_Bonus#2x3#3x3_Bonus1";
r[795] = "#2x3_Bonus#3#3";
r[796] = "#L#Ecke2#1";
r[797] = "#1#5#2";
r[798] = "#4#J#4_Bonus";
r[799] = "#X#2x3_Bonus#3";
r[800] = "#T#3x3_Bonus3#4";
r[801] = "#4#2x2#3x3";
r[802] = "#3x3_Bonus1#3x3_Bonus4#4";
r[803] = "#Ecke2#3#Z";
r[804] = "#2Dots#J#Ecke3_Bonus1A";
r[805] = "#2x3_Bonus#4#1";
r[806] = "#3x3_Bonus3#1_Bonus1#Slash";
r[807] = "#2x2#S#2x2";
r[808] = "#2x2_Bonus#3x3_Bonus3#Z";
r[809] = "#J#Ecke2#3x3";
r[810] = "#2Dots#2x3_Bonus#5";
r[811] = "#Slash#3#2x2_Bonus";
r[812] = "#3#L#4";
r[813] = "#Ecke2#2Dots#L";
r[814] = "#5#L:.......1....1....L.......";
r[815] = "#T#L#2x2";
r[816] = "#4#2#Z";
r[817] = "#3#X#4";
r[818] = "#1#5#2";
r[819] = "#1#3#Slash";
r[820] = "#2#L#2x3_Bonus";
r[821] = "#4_Bonus#Ecke2#T";
r[822] = "#4#Ecke3_Bonus1B#T";
r[823] = "#2#2x2#Z";
r[824] = "#L#J#4_Bonus";
r[825] = "#3x3_Bonus3#1#4";
r[826] = "#Ecke3#S#T";
r[827] = "#2x2_Bonus#J#T";
r[828] = "#Ecke3_Bonus1B#Ecke3_Bonus1A#3x3_Bonus1";
r[829] = "#Z#4_Bonus#3x3_Bonus2";
r[830] = "#Ecke2#1_Bonus1#4";
r[831] = "#Ecke3_Bonus1A#S#4";
r[832] = "#4_Bonus#2x2#1";
r[833] = "#4#J#4_Bonus";
r[834] = "#Slash#3x3_Bonus4#Ecke2";
r[835] = "#5#T#Ecke3";
r[836] = "#3x3_Bonus3#L#3x3";
r[837] = "#T#5#2";
r[838] = "#2x3_Bonus#2x2_Bonus#1";
r[839] = "#2#Ecke3_Bonus1B#Ecke2";
r[840] = "#T#T#L";
r[841] = "#Ecke3#T#5";
r[842] = "#3#3#2x2";
r[843] = "#Ecke2#2Dots#Ecke3";
r[844] = "#Ecke2#Ecke2#3x3";
r[845] = "#4#Ecke2#Ecke2";
r[846] = "#3x3_Bonus2#Ecke3#3";
r[847] = "#1_Bonus2#Ecke2#Ecke2";
r[848] = "#2:......3L3..333..333......#Ecke3_Bonus1A";
r[849] = "#T#1_Bonus2#1_Bonus2";
r[850] = "#Z#Ecke3_Bonus2#4";
r[851] = "#T#Ecke3#BigSlash";
r[852] = "#X#5#4_Bonus";
r[853] = "#5#3x3#3";
r[854] = "#Ecke3#Slash#Ecke3";
r[855] = "#4#Ecke3_Bonus2#X";
r[856] = "#T#S#T";
r[857] = "#2x2_Bonus#Ecke3#4_Bonus";
r[858] = "#5#2#2x2";
r[859] = "#2x2#T#1_Bonus1";
r[860] = "#2x3_Bonus#4#2x2_Bonus";
r[861] = "#1_Bonus2#L#1";
r[862] = "#Ecke2#2#5";
r[863] = "#5#T#5";
r[864] = "#2Dots#Ecke2#S";
r[865] = "#4#2x3#L";
r[866] = "#Ecke3#4_Bonus#2Dots";
r[867] = "#4#1_Bonus2#Ecke3_Bonus1A";
r[868] = "#1#J#BigSlash";
r[869] = "#2#1#4";
r[870] = "#3x3#T#T";
r[871] = "#S#Z#5";
r[872] = "#4#4#Ecke2";
r[873] = "#2#4#Ecke3_Bonus1B";
r[874] = "#3#2#L";
r[875] = "#5#Ecke3#2";
r[876] = "#3x3_Bonus2#T#4";
r[877] = "#Ecke3#1_Bonus2#4";
r[878] = "#3x3_Bonus4#T#3";
r[879] = "#Ecke3#Ecke2#3x3_Bonus2";
r[880] = "#Ecke3#4#4_Bonus";
r[881] = "#Ecke3_Bonus1B#2x2_Bonus#T";
r[882] = ":............L............#3#T";
r[883] = "#3#Ecke3_Bonus1A#2";
r[884] = "#S#2#1_Bonus2";
r[885] = "#2Dots#Ecke3#3x3_Bonus2";
r[886] = "#Ecke3_Bonus1B#1_Bonus1#5";
r[887] = "#5#T#2";
r[888] = "#1_Bonus1#Slash#3x3_Bonus2";
r[889] = "#5#1_Bonus1#1";
r[890] = "#L#BigSlash#T";
r[891] = "#3#4#L";
r[892] = "#Ecke3_Bonus2#S#Slash";
r[893] = "#2x2_Bonus#Ecke3#J";
r[894] = "#J#4#Ecke3";
r[895] = "#1_Bonus1#3x3_Bonus4#1_Bonus2";
r[896] = "#2x2#Ecke2#S";
r[897] = "#1_Bonus1#Ecke3_Bonus2#Ecke2";
r[898] = "#BigSlash#Ecke3#4";
r[899] = "#T#1#Ecke3_Bonus2";
r[900] = "#X#X#BigSlash";
r[901] = "#T#Ecke3#4";
r[902] = "#2Dots#Ecke3:......4....4S............";
r[903] = "#T#2x3#X";
r[904] = "#BigSlash#4_Bonus#2x3_Bonus";
r[905] = "#1_Bonus2#S#4";
r[906] = "#1_Bonus1#2x3_Bonus#Ecke2";
r[907] = "#Ecke3#BigSlash#2x2";
r[908] = "#2x2#3#Ecke3";
r[909] = "#2#3x3_Bonus2#4_Bonus";
r[910] = "#Z#3x3_Bonus1#Ecke3_Bonus2";
r[911] = "#J#2x3#2x2_Bonus";
r[912] = "#2x2_Bonus#Ecke2#4";
r[913] = "#J#S#T";
r[914] = "#5#2#BigSlash";
r[915] = "#T#2x3_Bonus#T";
r[916] = ":......33...L3............#3#Ecke3";
r[917] = "#Ecke2#Ecke2#2x2_Bonus";
r[918] = "#4#1_Bonus1#2";
r[919] = "#3x3_Bonus2#Ecke3_Bonus2#5";
r[920] = "#4#3#X";
r[921] = "#5#L#3x3";
r[922] = "#Ecke3#3x3_Bonus2#T";
r[923] = "#X#X#3";
r[924] = "#Z#Ecke3_Bonus1A#2x3";
r[925] = "#Ecke3_Bonus1B#2x3_Bonus#Ecke3";
r[926] = "#4#5#3x3_Bonus2";
r[927] = "#1#S#T";
r[928] = "#Ecke3#Ecke3_Bonus1B#2x2";
r[929] = "#T#T#1_Bonus1";
r[930] = "#2#1_Bonus2#1";
r[931] = "#BigSlash#T#X";
r[932] = "#J#3x3_Bonus1#2x3_Bonus";
r[933] = "#L#4#2";
r[934] = "#1_Bonus2#4_Bonus#Ecke3_Bonus2";
r[935] = "#J#T#S";
r[936] = "#4#1_Bonus2#3x3_Bonus2";
r[937] = "#3x3_Bonus3#4#4";
r[938] = "#J#3x3_Bonus1#2";
r[939] = "#T#Ecke2#5";
r[940] = "#T#2x3_Bonus#2";
r[941] = "#Ecke2#Slash#3";
r[942] = "#Ecke3#2x2_Bonus#1";
r[943] = "#4#1_Bonus2#2x3_Bonus";
r[944] = "#Ecke3_Bonus1A#3:............S............";
r[945] = "#2#3x3_Bonus3#1_Bonus2";
r[946] = "#1_Bonus1#Ecke2#1";
r[947] = "#2x3_Bonus#1#2Dots";
r[948] = "#T#5#3x3_Bonus3";
r[949] = "#3#Ecke3:......4....L4............";
r[950] = "#3x3_Bonus4#2#Ecke2";
r[951] = "#2x3_Bonus#1#2";
r[952] = "#3x3_Bonus4#Slash#2x3_Bonus";
r[953] = "#T#Ecke2#J";
r[954] = "#4#5#S";
r[955] = "#T#4_Bonus#4";
r[956] = "#2#L#2x3_Bonus";
r[957] = "#L#5#1_Bonus2";
r[958] = "#5#2#Ecke3";
r[959] = "#Slash#5#Ecke2";
r[960] = "#1#2x3#Ecke3";
r[961] = "#4#Ecke3#1_Bonus2";
r[962] = "#2Dots#1#2";
r[963] = "#T#Ecke2#3";
r[964] = "#J#1_Bonus2#Ecke3_Bonus2";
r[965] = "#Ecke2#3x3#5";
r[966] = "#Ecke3#Ecke3#3x3_Bonus3";
r[967] = "#T#2x3_Bonus#T";
r[968] = "#1#1#3x3_Bonus2";
r[969] = "#5#1#1_Bonus1";
r[970] = "#Ecke2#J#Ecke2";
r[971] = "#5#5#Slash";
r[972] = "#4#3#3x3_Bonus4";
r[973] = "#3x3_Bonus2#3x3_Bonus2#T";
r[974] = "#Slash#Ecke2#Ecke3";
r[975] = "#3x3_Bonus1#3x3_Bonus3#Ecke3";
r[976] = "#T#4#T";
r[977] = "#Ecke3#1_Bonus1#Ecke3_Bonus1B";
r[978] = "#Ecke2#Ecke3_Bonus2#Ecke3";
r[979] = "#Ecke2#1_Bonus1#BigSlash";
r[980] = "#Ecke2#3#Ecke2";
r[981] = "#2x2#Ecke2#1";
r[982] = "#1#J#3";
r[983] = "#1_Bonus2:......4....4....L44......#2x2_Bonus";
r[984] = "#T#L#2x2_Bonus";
r[985] = "#3#BigSlash#Ecke3";
r[986] = "#T#2#Ecke3_Bonus1A";
r[987] = "#2#Ecke3_Bonus2#2x3";
r[988] = "#3#3#L";
r[989] = "#Ecke3#Ecke3#Ecke3";
r[990] = "#4#1_Bonus1#3";
r[991] = "#T#T#2x2_Bonus";
r[992] = "#2#3x3#3";
r[993] = "#4#2x2#1";
r[994] = "#1#T#Ecke3_Bonus2";
r[995] = "#3x3_Bonus3#Ecke3_Bonus1B#2x3";
r[996] = "#2x2_Bonus#1_Bonus1#4";
r[997] = "#T#3#3";
r[998] = "#5#1_Bonus2#Ecke2";
r[999] = "#2#Slash#2";
r[1000] = "#Ecke3#Slash#1_Bonus1";
r[1001] = "#2x2_Bonus#5#5";
r[1002] = "#Ecke3#3x3_Bonus3#1_Bonus2";
r[1003] = "#Ecke3#3x3_Bonus4#2x2_Bonus";
r[1004] = "#4_Bonus#1_Bonus2#Slash";
r[1005] = "#Ecke2#3#Ecke3_Bonus1A";
r[1006] = "#2x3#X_Bonus#1_Bonus2";
r[1007] = "#Ecke2#J#Ecke2";
r[1008] = "#4#Ecke3#Z";
r[1009] = "#Ecke3_Bonus2#Ecke2#3";
r[1010] = "#Ecke3_Bonus2#1#1";
r[1011] = "#2x2_Bonus#1#Ecke3";
r[1012] = "#Ecke3#3#4";
r[1013] = "#2x2_Bonus#J#5";
r[1014] = "#Ecke3_Bonus1A#X_Bonus#3";
r[1015] = "#4#L#2";
r[1016] = "#5#5#Slash";
r[1017] = ":..........1L11...........#BigSlash#Z";
r[1018] = "#3#BigSlash#3x3_Bonus2";
r[1019] = "#Ecke3_Bonus1B#5#2Dots";
r[1020] = "#L#1#3x3_Bonus3";
r[1021] = "#Ecke3_Bonus1B#BigSlash#4_Bonus";
r[1022] = "#T#4#3x3_Bonus1";
r[1023] = "#1#2x3#Ecke2";
r[1024] = "#3#4#T";
r[1025] = "#1_Bonus2#T#5";
r[1026] = "#5#L#Ecke3";
r[1027] = "#T#4#1_Bonus2";
r[1028] = "#T#T#4";
r[1029] = "#Ecke2#3#2x3_Bonus";
r[1030] = "#3x3_Bonus4#T#4";
r[1031] = "#2#4#3x3_Bonus3";
r[1032] = "#Ecke3#2#2";
r[1033] = "#4#S#4";
r[1034] = "#Ecke3_Bonus1A#1_Bonus1#2x2_Bonus";
r[1035] = "#T#2#1";
r[1036] = "#2#Ecke3_Bonus1B#1_Bonus1";
r[1037] = "#2#1_Bonus1#2x2_Bonus";
r[1038] = "#3x3_Bonus3#4#Ecke3_Bonus1B";
r[1039] = "#Ecke2#3#2";
r[1040] = "#4#1_Bonus2#2";
r[1041] = "#X#T#3";
r[1042] = "#4#Ecke2#1_Bonus2";
r[1043] = "#1_Bonus1#T#1_Bonus1";
r[1044] = "#5#Ecke2#3x3_Bonus1";
r[1045] = "#5#2x3_Bonus#Ecke3";
r[1046] = "#1#X#2x2";
r[1047] = "#2x2#3#3";
r[1048] = "#Ecke2#4#4";
r[1049] = "#BigSlash#3x3_Bonus3#2x3_Bonus";
r[1050] = "#T#L:............L............";
r[1051] = "#3x3_Bonus1#5#J";
r[1052] = "#Ecke3#2x3_Bonus#Z";
r[1053] = "#5#Ecke2#Z";
r[1054] = "#1_Bonus2#Ecke3#2x3";
r[1055] = "#2x3#3x3_Bonus2#X_Bonus";
r[1056] = "#1_Bonus2#T#Ecke2";
r[1057] = "#X#X_Bonus#4";
r[1058] = "#5#1_Bonus1#4";
r[1059] = "#1_Bonus2#S#Ecke3";
r[1060] = "#Ecke2#2Dots#X";
r[1061] = "#4#T#2Dots";
r[1062] = "#4#3x3_Bonus2#J";
r[1063] = "#Ecke3_Bonus2#BigSlash#X";
r[1064] = "#2#1_Bonus1#Ecke3";
r[1065] = "#Ecke2#Ecke2#2x3";
r[1066] = "#1#4#4";
r[1067] = "#2x2#2x2#2x3_Bonus";
r[1068] = "#5#2x3_Bonus#Ecke3_Bonus1A";
r[1069] = "#Z#2#Ecke2";
r[1070] = "#L#3#3x3_Bonus3";
r[1071] = "#4#3#S";
r[1072] = "#Ecke2#4#Ecke3";
r[1073] = "#X#X_Bonus#Z";
r[1074] = "#3#2#J";
r[1075] = "#Slash#3#3";
r[1076] = "#3#Ecke2#2x2_Bonus";
r[1077] = "#S#5#4";
r[1078] = "#2#Ecke2#BigSlash";
r[1079] = "#2#Ecke2#T";
r[1080] = "#T#Ecke3#5";
r[1081] = "#2#1#2";
r[1082] = "#4#5#3x3_Bonus2";
r[1083] = "#2Dots#2x3_Bonus#4";
r[1084] = "#Ecke2:....L...2...3...4...5....#2";
r[1085] = "#T#T#3";
r[1086] = "#J#L#4";
r[1087] = "#4#T#3x3_Bonus4";
r[1088] = "#Z#T#Z";
r[1089] = "#Ecke2#3x3_Bonus4#4";
r[1090] = "#T#Ecke3_Bonus1A#5";
r[1091] = "#3#S#L";
r[1092] = "#X_Bonus#T#Ecke3";
r[1093] = "#5#5#Ecke2";
r[1094] = "#2Dots#T#S";
r[1095] = "#2#X_Bonus#Ecke2";
r[1096] = "#3x3_Bonus2#T#1_Bonus1";
r[1097] = "#3x3_Bonus2#5#4";
r[1098] = "#5#2#Ecke3";
r[1099] = "#3x3_Bonus1#2Dots#1_Bonus2";
r[1100] = "#BigSlash#X#BigSlash";
r[1101] = "#X_Bonus#2x2_Bonus#X";
r[1102] = "#2x2_Bonus#Ecke3_Bonus2#1";
r[1103] = "#X_Bonus#Slash#3";
r[1104] = "#3#Slash#Ecke2";
r[1105] = "#Ecke3#X#T";
r[1106] = "#2Dots#3#L";
r[1107] = "#2#1_Bonus1#2";
r[1108] = "#2x2#T#BigSlash";
r[1109] = "#3#4_Bonus#1";
r[1110] = "#Ecke3_Bonus1A#2Dots#Z";
r[1111] = "#1#L#X";
r[1112] = "#1_Bonus1#2x3_Bonus#2";
r[1113] = "#5#2#4_Bonus";
r[1114] = "#5#2Dots#4_Bonus";
r[1115] = "#2x3_Bonus#1#Ecke2";
r[1116] = "#1_Bonus2#5#3x3_Bonus1";
r[1117] = "#Ecke3#4#3x3_Bonus3";
r[1118] = ":............L............#3#1";
r[1119] = "#Ecke3_Bonus1B#Ecke2#1";
r[1120] = "#1_Bonus2#2#S";
r[1121] = "#Ecke3#1_Bonus2#3";
r[1122] = "#1_Bonus1#3#Ecke2";
r[1123] = "#1#3x3#4";
r[1124] = "#1#Ecke2#1_Bonus1";
r[1125] = "#3x3#3x3_Bonus4#1";
r[1126] = "#X_Bonus#3#3x3_Bonus2";
r[1127] = "#1_Bonus2#Ecke3#2";
r[1128] = "#1#1#Ecke2";
r[1129] = "#Ecke3_Bonus1A#4#3x3_Bonus3";
r[1130] = "#1#Ecke2#Ecke3";
r[1131] = "#T#3#2x2";
r[1132] = "#Ecke3#2#1";
r[1133] = "#Ecke2#1_Bonus1#L";
r[1134] = "#2x3#3#3";
r[1135] = "#X#J#3";
r[1136] = "#2#Z#1";
r[1137] = "#2x2#1_Bonus2#Ecke2";
r[1138] = "#1#1_Bonus1#3x3";
r[1139] = "#BigSlash#Ecke3#1_Bonus2";
r[1140] = "#Ecke2#3#Ecke3";
r[1141] = "#4#Ecke3_Bonus2#X";
r[1142] = "#T#Ecke2#1";
r[1143] = "#2x3_Bonus#1#Ecke3_Bonus1B";
r[1144] = "#Ecke3#Ecke3_Bonus2#3x3_Bonus1";
r[1145] = "#X_Bonus#1_Bonus1#1_Bonus1";
r[1146] = "#BigSlash#5#5";
r[1147] = "#Ecke2#Ecke3#2";
r[1148] = "#1_Bonus1#3#1";
r[1149] = "#Ecke2#4#3x3";
r[1150] = "#3x3_Bonus3#Ecke3_Bonus2#4";
r[1151] = "#S#Ecke3_Bonus1A:..........111L...........";
r[1152] = "#J#2#T";
r[1153] = "#J#Z#Ecke3";
r[1154] = "#J#5#Ecke3_Bonus2";
r[1155] = "#Ecke2#3x3#S";
r[1156] = "#2x2#1_Bonus1#S";
r[1157] = "#Ecke3#Ecke3#L";
r[1158] = "#5#5#3";
r[1159] = "#3x3_Bonus3#Ecke3#Z";
r[1160] = "#4#5#3";
r[1161] = "#5#5#X";
r[1162] = "#3:...........S6....66......#3x3_Bonus3";
r[1163] = "#2#3x3_Bonus1#Ecke3_Bonus2";
r[1164] = "#2#1#2x3";
r[1165] = "#2Dots#1_Bonus2#Ecke2";
r[1166] = "#2Dots#S#T";
r[1167] = "#Ecke3#2x2#Ecke2";
r[1168] = "#T#3#4";
r[1169] = "#3x3_Bonus2#Ecke3#Ecke3";
r[1170] = "#4#Ecke3_Bonus2#J";
r[1171] = "#Ecke2#T#BigSlash";
r[1172] = "#3x3_Bonus4#1_Bonus3#Ecke3";
r[1173] = "#3#3x3#T";
r[1174] = "#5#2#Ecke3_Bonus1B";
r[1175] = "#2x2#T#BigSlash";
r[1176] = "#T#3x3_Bonus4#Ecke3";
r[1177] = "#1#Ecke3_Bonus1A#1_Bonus1";
r[1178] = "#X#Ecke3_Bonus2#Slash";
r[1179] = "#2#3#Z";
r[1180] = "#3x3_Bonus4#X_Bonus#1_Bonus3";
r[1181] = "#2#3#1";
r[1182] = "#Ecke2#1#1_Bonus2";
r[1183] = "#Ecke3#3x3#Ecke3_Bonus1B";
r[1184] = "#T#Ecke2#BigSlash";
r[1185] = "#1#1:..........222L2..........";
r[1186] = "#4#1_Bonus1#Ecke3";
r[1187] = "#1_Bonus1#1_Bonus1#4";
r[1188] = "#3x3_Bonus4#4#BigSlash";
r[1189] = "#T#3#L";
r[1190] = "#2x3_Bonus#3x3_Bonus4#1";
r[1191] = "#3#2x2_Bonus#4";
r[1192] = "#4#1_Bonus2#1_Bonus1";
r[1193] = "#Ecke3_Bonus1B#Ecke3_Bonus2#4";
r[1194] = "#2x2_Bonus#4#1_Bonus1";
r[1195] = "#1_Bonus1#Ecke3#1";
r[1196] = "#T#BigSlash#2";
r[1197] = "#1_Bonus1#5#4";
r[1198] = "#3x3#3#3";
r[1199] = "#1#Ecke2#3";
r[1200] = "#Z#Ecke2#4";
r[1201] = "#Slash#1#5";
r[1202] = "#3x3_Bonus2#BigSlash#1_Bonus3";
r[1203] = "#2x3_Bonus#1_Bonus3#3x3_Bonus4";
r[1204] = "#T#2#Ecke3";
r[1205] = "#3#Ecke3_Bonus2#Z";
r[1206] = "#Ecke2#L#L";
r[1207] = "#4#X_Bonus#2x3_Bonus";
r[1208] = "#Slash#3x3_Bonus3#5";
r[1209] = "#Ecke3_Bonus1A#L#Ecke2";
r[1210] = "#4#X_Bonus#2x2";
r[1211] = "#1#Ecke2#4";
r[1212] = "#T#1#Ecke2";
r[1213] = "#4#2x3_Bonus#Ecke3_Bonus2";
r[1214] = "#1#J#2";
r[1215] = "#3x3_Bonus3#L#2x3_Bonus";
r[1216] = "#2x3_Bonus#4#Ecke2";
r[1217] = "#1_Bonus2#X_Bonus#Ecke2";
r[1218] = "#3x3_Bonus1#1_Bonus1#1";
r[1219] = "#3x3_Bonus3:......4....4....44L......#X";
r[1220] = "#2x3_Bonus#2#3x3_Bonus4";
r[1221] = "#Slash#2Dots#X";
r[1222] = "#3#5#Ecke2";
r[1223] = "#3x3_Bonus4#3x3_Bonus1#T";
r[1224] = "#X#4#S";
r[1225] = "#3#5#2";
r[1226] = "#4#4#Ecke3_Bonus1B";
r[1227] = "#4#1_Bonus1#5";
r[1228] = "#Ecke3#1#T";
r[1229] = "#3#Ecke3_Bonus1A#T";
r[1230] = "#Ecke2#T#2Dots";
r[1231] = "#T#2#Ecke2";
r[1232] = "#2#S#3";
r[1233] = "#Ecke2#T#2x3";
r[1234] = "#5#Ecke2#3x3_Bonus1";
r[1235] = "#5#Ecke2#Ecke3";
r[1236] = "#2#3#1";
r[1237] = "#2#Slash#Z";
r[1238] = "#X#X#Ecke3";
r[1239] = "#1#Slash#J";
r[1240] = "#3x3_Bonus1#2x2#1_Bonus1";
r[1241] = "#2#2Dots#J";
r[1242] = "#Ecke2#Ecke2#Ecke2";
r[1243] = "#4#2#Ecke2";
r[1244] = "#3x3_Bonus3#1_Bonus3#2";
r[1245] = "#2#Ecke2#3x3_Bonus3";
r[1246] = ":............S............#T#3";
r[1247] = "#4#2#Z";
r[1248] = "#3x3#2x3_Bonus#T";
r[1249] = "#S#3x3_Bonus1#1";
r[1250] = "#3#3x3#3";
r[1251] = "#3x3_Bonus4#Ecke2#Ecke2";
r[1252] = "#5#3#2";
r[1253] = "#Ecke2:......5.L...4...5.5......#3";
r[1254] = "#1#3#T";
r[1255] = "#3#3#3x3_Bonus2";
r[1256] = "#2x2#4_Bonus#4";
r[1257] = "#3x3_Bonus2#4#5";
r[1258] = "#T#Ecke3#Ecke2";
r[1259] = "#3x3_Bonus3#1_Bonus1#1";
r[1260] = "#Ecke3#J#Ecke2";
r[1261] = "#1_Bonus3#1#T";
r[1262] = "#3x3_Bonus4#2Dots#2";
r[1263] = "#2x2#3#J";
r[1264] = "#4_Bonus#Ecke3_Bonus2#S";
r[1265] = "#2#3#2Dots";
r[1266] = "#3#3x3_Bonus3#Z";
r[1267] = "#5#2#1";
r[1268] = "#J#1_Bonus2:......5....55S...........";
r[1269] = "#Slash#5#4";
r[1270] = "#3x3_Bonus3#3#S";
r[1271] = "#2#1_Bonus1#Ecke2";
r[1272] = "#1_Bonus2#1_Bonus1#3";
r[1273] = "#T#4_Bonus#S";
r[1274] = "#Ecke3_Bonus2#Slash#S";
r[1275] = "#Ecke3#S#3x3_Bonus1";
r[1276] = "#Ecke3_Bonus1B#Ecke3#2x3_Bonus";
r[1277] = "#3x3_Bonus3#2x3#T";
r[1278] = "#Z#2x3#4";
r[1279] = "#4#1#Ecke3";
r[1280] = "#Ecke3_Bonus1A#Ecke2#3";
r[1281] = "#Ecke3#3x3_Bonus2#5";
r[1282] = "#Ecke3#4#Ecke3_Bonus2";
r[1283] = "#4#2#2x3_Bonus";
r[1284] = "#1_Bonus2#T#T";
r[1285] = "#2x3#T#3x3";
r[1286] = "#2#5#X";
r[1287] = "#T:........5...L...5........#3x3_Bonus2";
r[1288] = "#1_Bonus1#T#3x3_Bonus1";
r[1289] = "#3#1_Bonus3#3x3_Bonus1";
r[1290] = "#1#5#X_Bonus";
r[1291] = "#2#T#X";
r[1292] = "#2#Ecke3#4";
r[1293] = "#5#3x3_Bonus2#2";
r[1294] = "#2#3#4";
r[1295] = "#5#1_Bonus2:............S............";
r[1296] = "#2#Slash#2x2_Bonus";
r[1297] = "#Ecke3#2x3#3";
r[1298] = "#Ecke2#3#Slash";
r[1299] = "#3#L#T";
r[1300] = "#2x3#3#2";
r[1301] = "#Ecke3_Bonus2#1_Bonus2#4";
r[1302] = "#X_Bonus#4_Bonus#T";
r[1303] = "#BigSlash#X#Ecke2";
r[1304] = "#5#2x2_Bonus#Ecke2";
r[1305] = "#Ecke3#T#1_Bonus1";
r[1306] = "#5#1_Bonus2#4";
r[1307] = "#2x3_Bonus#Ecke2#L";
r[1308] = "#Z#BigSlash#2x3";
r[1309] = "#Ecke3#2#T";
r[1310] = "#3x3_Bonus3#X#T";
r[1311] = "#5#Ecke3_Bonus2#3";
r[1312] = "#2Dots#Ecke2#2x2";
r[1313] = "#4#1_Bonus1#1_Bonus3";
r[1314] = "#L#Ecke3#Slash";
r[1315] = "#T#1_Bonus1#1_Bonus1";
r[1316] = "#Ecke2#5#Ecke3_Bonus1B";
r[1317] = "#1#2x2#Ecke3";
r[1318] = "#Ecke3#T#3";
r[1319] = "#Ecke3_Bonus1B#Ecke3_Bonus1A:.......5....55...S.......";
r[1320] = "#3x3_Bonus1#3x3_Bonus4#5";
r[1321] = "#3x3_Bonus1#X_Bonus#2x2";
r[1322] = "#4_Bonus#4#Ecke3";
r[1323] = "#4#3#Ecke3_Bonus1B";
r[1324] = "#Ecke3#1_Bonus3#2";
r[1325] = "#Z#5#4";
r[1326] = "#3x3_Bonus1#Ecke2#1_Bonus1";
r[1327] = "#T#2#2Dots";
r[1328] = "#Ecke3#X#Ecke3_Bonus1B";
r[1329] = "#3#T#L";
r[1330] = "#Slash#3x3_Bonus2#T";
r[1331] = "#Ecke2#T#5";
r[1332] = "#2#3x3_Bonus3#3x3_Bonus4";
r[1333] = "#Ecke2#1_Bonus1#2";
r[1334] = "#3#Slash#5";
r[1335] = "#T#4#S";
r[1336] = "#2x2#X_Bonus2#4_Bonus";
r[1337] = "#2#3#1_Bonus2";
r[1338] = "#2#Ecke2#1_Bonus1";
r[1339] = "#Ecke3_Bonus2#1_Bonus3#Ecke3";
r[1340] = "#4_Bonus#2x3_Bonus#1_Bonus3";
r[1341] = "#3#5#5";
r[1342] = "#2#Ecke3_Bonus1B#2x2";
r[1343] = "#X#Ecke3_Bonus1B#X_Bonus2";
r[1344] = "#4#T#1_Bonus3";
r[1345] = "#Ecke3#Slash#2";
r[1346] = "#3x3_Bonus1#4#5";
r[1347] = "#1#4#Ecke3";
r[1348] = "#Ecke3#2x3#T";
r[1349] = "#2#5#2x3_Bonus";
r[1350] = "#Slash#3#4";
r[1351] = "#Ecke3#Ecke2#T";
r[1352] = "#3#1#2x2_Bonus";
r[1353] = "#T#3x3_Bonus4#2x2";
r[1354] = "#T#L#3x3";
r[1355] = ":..........1L11...........#T#1_Bonus1";
r[1356] = "#L#Ecke2#5";
r[1357] = "#3x3_Bonus4#1_Bonus1#1_Bonus3";
r[1358] = "#5#X#Ecke3";
r[1359] = "#2x2_Bonus#X_Bonus#3x3_Bonus3";
r[1360] = "#3x3_Bonus2#J#2x3_Bonus";
r[1361] = "#BigSlash#5#Slash";
r[1362] = "#3#Ecke2#Ecke2";
r[1363] = "#1_Bonus1#1_Bonus2#Ecke3";
r[1364] = "#Ecke3#2x3_Bonus#S";
r[1365] = "#Slash#3x3#Ecke3_Bonus1B";
r[1366] = "#4#Slash#T";
r[1367] = "#1#1_Bonus2#2Dots";
r[1368] = "#4#5#1";
r[1369] = "#BigSlash#2#2";
r[1370] = "#Z#4#1_Bonus1";
r[1371] = "#2Dots#1_Bonus2#Ecke2";
r[1372] = "#Ecke3#2#2x2";
r[1373] = "#5#2#3x3_Bonus4";
r[1374] = "#2#3x3_Bonus4#4";
r[1375] = "#3#2Dots#2Dots";
r[1376] = "#3#1#J";
r[1377] = "#T#T#2";
r[1378] = "#L#5#4";
r[1379] = "#3x3#2Dots#Z";
r[1380] = "#4#Ecke2#L";
r[1381] = "#2x3_Bonus#1#1_Bonus2";
r[1382] = "#4_Bonus#5#Ecke2";
r[1383] = "#X_Bonus2#BigSlash#T";
r[1384] = "#1#1_Bonus2#Ecke3_Bonus1B";
r[1385] = "#X_Bonus2#T#5";
r[1386] = "#1#Ecke2#2";
r[1387] = "#Ecke2#2x2#Ecke3";
r[1388] = "#J#1_Bonus1:......4....L....444......";
r[1389] = "#3#X#1";
r[1390] = "#2#BigSlash#3";
r[1391] = "#Ecke3_Bonus1B#T#3";
r[1392] = "#Ecke2#X#1_Bonus2";
r[1393] = "#Slash#4#3";
r[1394] = "#Z#1_Bonus2#S";
r[1395] = "#Ecke2#1#1";
r[1396] = "#3x3_Bonus1#4#4_Bonus";
r[1397] = "#X_Bonus#X_Bonus2#1_Bonus2";
r[1398] = "#2Dots#1_Bonus3#Ecke3";
r[1399] = "#2x3_Bonus#Ecke2#4";
r[1400] = "#1#1_Bonus2#1";
r[1401] = "#3#Ecke3_Bonus1A#2x2";
r[1402] = "#T#2x2#BigSlash";
r[1403] = "#2#2#T";
r[1404] = "#3#Ecke2#3x3_Bonus2";
r[1405] = "#4#2x2#1";
r[1406] = "#1_Bonus2#3#4";
r[1407] = "#2#5#1";
r[1408] = "#Ecke2#3#3";
r[1409] = "#2x2#BigSlash#2x3_Bonus";
r[1410] = "#1_Bonus1#X_Bonus2#2Dots";
r[1411] = "#X#2#T";
r[1412] = "#Z#Ecke2#5";
r[1413] = "#2Dots#2#1_Bonus2";
r[1414] = "#Ecke3_Bonus1A#Ecke3#Z";
r[1415] = "#Ecke2#Ecke2#4_Bonus";
r[1416] = "#T#Z#4_Bonus";
r[1417] = "#3x3_Bonus3#4#Ecke2";
r[1418] = "#T#2x2#1";
r[1419] = "#Ecke2#2#2x2_Bonus";
r[1420] = "#2#5#Ecke2";
r[1421] = "#Ecke3_Bonus1A#4#3x3";
r[1422] = "#1:............L...44.......#3";
r[1423] = "#3x3_Bonus4#1#1_Bonus2";
r[1424] = "#5#2x2_Bonus#Ecke2";
r[1425] = "#Ecke3#Ecke3#Ecke2";
r[1426] = "#BigSlash#Ecke3_Bonus2#2";
r[1427] = "#2x2_Bonus#S#BigSlash";
r[1428] = "#T#T#Ecke3_Bonus2";
r[1429] = "#2#Ecke3#1_Bonus2";
r[1430] = "#3#T#T";
r[1431] = "#J#Ecke3#X_Bonus";
r[1432] = "#2#Ecke2#1_Bonus1";
r[1433] = "#1#2x2_Bonus#S";
r[1434] = "#Ecke3#5#Ecke3";
r[1435] = "#3#Ecke2#T";
r[1436] = "#2x3_Bonus#BigSlash#Ecke3_Bonus1B";
r[1437] = "#T#1#5";
r[1438] = "#T#1#2Dots";
r[1439] = "#1_Bonus1#5#4";
r[1440] = "#4#Z#T";
r[1441] = "#2Dots#Ecke3#J";
r[1442] = "#2#3#Z";
r[1443] = "#1_Bonus1#Ecke2#Ecke3";
r[1444] = "#4_Bonus#2#2x3_Bonus";
r[1445] = "#X_Bonus#1_Bonus3#1_Bonus3";
r[1446] = "#Ecke2#4#4";
r[1447] = "#L#2#Ecke2";
r[1448] = "#Ecke3_Bonus2#Ecke2#2x2";
r[1449] = "#2x3_Bonus#T#3";
r[1450] = "#3#3#Ecke2";
r[1451] = "#1#3x3_Bonus2#4";
r[1452] = "#4#5#Ecke3_Bonus1B";
r[1453] = "#BigSlash#3x3_Bonus2#Ecke2";
r[1454] = "#5#4#1_Bonus1";
r[1455] = "#4#2#Z";
r[1456] = ":......5.L...4...5.5......#T#T";
r[1457] = "#T#4#1_Bonus2";
r[1458] = "#4_Bonus#4#2";
r[1459] = "#L#3#X";
r[1460] = "#1#2x2_Bonus#Ecke3";
r[1461] = "#Ecke3_Bonus1B#L#2";
r[1462] = "#3x3_Bonus3#2#3";
r[1463] = "#Ecke2#T#1_Bonus2";
r[1464] = "#Ecke2#1#3x3";
r[1465] = "#4_Bonus#1_Bonus2#2";
r[1466] = "#3x3_Bonus2#2#3x3_Bonus3";
r[1467] = "#2x2_Bonus#Ecke2#Slash";
r[1468] = "#4_Bonus#X_Bonus2#Ecke3_Bonus2";
r[1469] = "#4_Bonus#4#Z";
r[1470] = "#1_Bonus2#Slash:......11S..111...........";
r[1471] = "#L#Ecke3#Ecke2";
r[1472] = "#J#S#BigSlash";
r[1473] = "#2x3#T#4";
r[1474] = "#1_Bonus1#3#4";
r[1475] = "#2x3_Bonus#Ecke3#5";
r[1476] = "#T#Slash#Ecke2";
r[1477] = "#4#1_Bonus2#T";
r[1478] = "#T#X#X_Bonus2";
r[1479] = "#3#X#4";
r[1480] = "#4#4#T";
r[1481] = "#Ecke3#Ecke3_Bonus1B#Ecke3_Bonus1A";
r[1482] = "#X_Bonus#2#2x3_Bonus";
r[1483] = "#1#2Dots#Ecke2";
r[1484] = "#Ecke3#3x3_Bonus3#S";
r[1485] = "#5#Ecke3_Bonus2#4";
r[1486] = "#3#Z#1";
r[1487] = "#3#3#Slash";
r[1488] = "#T:.......5....5S...5.......#Ecke3_Bonus1A";
r[1489] = "#3#1#1_Bonus2";
r[1490] = "#3:...........L1............#2Dots";
r[1491] = "#1_Bonus1#T#T";
r[1492] = "#T#4#Ecke3_Bonus1A";
r[1493] = "#2Dots#J#5";
r[1494] = "#Ecke2#1_Bonus2#4";
r[1495] = "#Ecke3_Bonus1A#2Dots#Ecke2";
r[1496] = "#J#Ecke2#Ecke3";
r[1497] = "#1_Bonus1#1#2x3";
r[1498] = "#3x3_Bonus1#S#1_Bonus3";
r[1499] = "#Ecke3_Bonus1A#Ecke2#Ecke3_Bonus1B";
r[1500] = "#4#1_Bonus1#2x2";
r[1501] = "#4#Ecke3#4";
r[1502] = "#4#1_Bonus1#Ecke2";
r[1503] = "#Ecke2#4_Bonus#1_Bonus2";
r[1504] = "#1_Bonus1#X_Bonus2#Ecke3";
r[1505] = "#Ecke3_Bonus1A#2#Ecke2";
r[1506] = "#S#1_Bonus1#BigSlash";
r[1507] = "#Z#X#BigSlash";
r[1508] = "#4_Bonus#Ecke2#T";
r[1509] = "#3#4_Bonus#3x3_Bonus4";
r[1510] = "#2x2_Bonus#J#4";
r[1511] = "#Ecke3_Bonus2#5#Ecke2";
r[1512] = "#Slash#3x3_Bonus3#2";
r[1513] = "#T#2#3x3";
r[1514] = "#T#4#T";
r[1515] = "#Ecke3#X_Bonus2#3x3_Bonus3";
r[1516] = "#X_Bonus#3x3_Bonus4#2";
r[1517] = "#3x3_Bonus2#Ecke3#Ecke3_Bonus1B";
r[1518] = "#2x2#T#Ecke3_Bonus1B";
r[1519] = "#Ecke2#2Dots#3";
r[1520] = "#3#1_Bonus1#2x3_Bonus";
r[1521] = "#Ecke3_Bonus2#3#Ecke2";
r[1522] = "#S:......111..11S...........#1_Bonus2";
r[1523] = "#3#J#3";
r[1524] = "#T:...........L11...........#Ecke2";
r[1525] = "#1#DT#1_Bonus3";
r[1526] = "#Ecke2#S#3x3_Bonus2";
r[1527] = "#1#4_Bonus#1_Bonus1";
r[1528] = "#3x3_Bonus4#1_Bonus1#Ecke2";
r[1529] = "#T#T#4_Bonus";
r[1530] = "#1_Bonus2#3x3_Bonus1#3";
r[1531] = "#3x3#3#Ecke2";
r[1532] = "#Ecke3_Bonus1B#Slash#3x3_Bonus1";
r[1533] = "#2x2#3:............55..5S.......";
r[1534] = "#3#4#Ecke3";
r[1535] = "#2x2_Bonus#T#4";
r[1536] = "#T#Ecke2#5";
r[1537] = "#5#3x3_Bonus1#2x2";
r[1538] = "#T#3x3_Bonus1#3x3_Bonus3";
r[1539] = "#2#X_Bonus2#Ecke3_Bonus2";
r[1540] = "#3#Ecke3_Bonus1B#4";
r[1541] = "#2#X_Bonus#Ecke2";
r[1542] = "#3#BigSlash#T";
r[1543] = "#X_Bonus2#4#Slash";
r[1544] = ":......5.S...4...5.5......#X_Bonus#2x3";
r[1545] = ":............4S....4......#X_Bonus#Ecke3_Bonus2";
r[1546] = "#X_Bonus2#Ecke3_Bonus1A#3x3_Bonus4";
r[1547] = "#T#2x2_Bonus#3x3_Bonus4";
r[1548] = "#5#BigSlash#Ecke2";
r[1549] = "#Ecke3_Bonus2#Ecke2#T";
r[1550] = "#DT#Ecke3#1_Bonus1";
r[1551] = "#S#2#1";
r[1552] = "#3x3_Bonus2#4#T";
r[1553] = "#Ecke3_Bonus1B#1_Bonus1#1_Bonus3";
r[1554] = "#1_Bonus2#J#Ecke2";
r[1555] = "#1_Bonus3#2#3x3_Bonus1";
r[1556] = "#3x3_Bonus2#T#T";
r[1557] = "#Ecke3_Bonus1A#2x3#5";
r[1558] = "#1#1_Bonus3#2Dots";
r[1559] = ":........5...5...L........#4_Bonus#3x3_Bonus1";
r[1560] = "#T#1#S";
r[1561] = "#1_Bonus1#4#3x3_Bonus3";
r[1562] = "#Ecke3_Bonus2#2Dots#Z";
r[1563] = "#X_Bonus2#T#4_Bonus";
r[1564] = "#4#4#Ecke2";
r[1565] = "#X_Bonus2#2x2#5";
r[1566] = "#5#X#3x3_Bonus4";
r[1567] = "#3#3#Ecke3";
r[1568] = "#T#BigSlash#2x3";
r[1569] = "#BigSlash#Ecke2:.......5...55....S.......";
r[1570] = "#4_Bonus#T#T";
r[1571] = "#1_Bonus3#2x2#2x3";
r[1572] = "#4#Ecke3#J";
r[1573] = "#5#3x3_Bonus2#Ecke3_Bonus1A";
r[1574] = "#1#4#Ecke3_Bonus1B";
r[1575] = "#T#3x3_Bonus3#1_Bonus3";
r[1576] = "#BigSlash#Ecke2#5";
r[1577] = "#5#4#Ecke3_Bonus1A";
r[1578] = "#5#2x3_Bonus#1_Bonus1";
r[1579] = "#3x3_Bonus3#BigSlash#Ecke3_Bonus2";
r[1580] = "#1#Ecke3_Bonus2#X";
r[1581] = "#3x3_Bonus1#2#4";
r[1582] = "#J#1_Bonus1#J";
r[1583] = "#Slash#S#4";
r[1584] = "#Ecke3_Bonus2#3x3_Bonus2#BigSlash";
r[1585] = "#T#Ecke3_Bonus1B#Ecke2";
r[1586] = "#4#1_Bonus3#DT";
r[1587] = "#2x2_Bonus#DT#1";
r[1588] = "#Ecke3#3#Ecke2";
r[1589] = "#3x3_Bonus2#DT#3x3";
r[1590] = "#3#2x2_Bonus#5";
r[1591] = "#2#4#4_Bonus";
r[1592] = "#3x3_Bonus3#2#4_Bonus";
r[1593] = ":......111..L11...........#X_Bonus#Ecke3";
r[1594] = "#2Dots#X_Bonus#X";
r[1595] = "#5#3x3_Bonus4#2";
r[1596] = "#4_Bonus#1#T";
r[1597] = "#Ecke2#2x3#Ecke2";
r[1598] = "#1_Bonus1#3#2x2";
r[1599] = "#1#Ecke3#3x3_Bonus2";
return r;
}
}
|
/**
*
*/
package serkantul.canvas_drawer;
/**
* @author serkantul
*
*/
public interface Shape {
/**
*
*/
//public void add(Area area);
public void draw(Area area);
}
|
/*
* Copyright 2017 EIS Ltd and/or one of 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 kraken.model.project.builder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import kraken.el.functionregistry.FunctionHeader;
import kraken.model.FunctionSignature;
import kraken.model.Rule;
import kraken.model.context.ContextDefinition;
import kraken.model.context.external.ExternalContext;
import kraken.model.context.external.ExternalContextDefinition;
import kraken.model.entrypoint.EntryPoint;
import kraken.model.resource.Resource;
import kraken.model.resource.RuleImport;
/**
* Represents merged {@link Resource} for a single namespace with rule imports already processed.
*
* @author mulevicius
*/
class NamespacedResource {
private final String namespace;
private ExternalContext externalContext;
private Map<String, ContextDefinition> contextDefinitions = new HashMap<>();
private Map<String, ExternalContextDefinition> externalContextDefinitions = new HashMap<>();
private Map<String, List<EntryPoint>> entryPoints = new HashMap<>();
private Map<String, List<Rule>> rules = new HashMap<>();
private Set<RuleImport> ruleImports = new HashSet<>();
private Set<String> includes = new HashSet<>();
private Map<FunctionHeader, FunctionSignature> functions = new HashMap<>();
NamespacedResource(String namespace) {
this.namespace = namespace;
}
void addRule(Rule rule) {
rules.putIfAbsent(rule.getName(), new ArrayList<>());
rules.get(rule.getName()).add(rule);
}
void addEntryPoint(EntryPoint entryPoint) {
entryPoints.putIfAbsent(entryPoint.getName(), new ArrayList<>());
entryPoints.get(entryPoint.getName()).add(entryPoint);
}
void addContextDefinition(ContextDefinition contextDefinition) {
contextDefinitions.putIfAbsent(contextDefinition.getName(), contextDefinition);
}
void setExternalContext(ExternalContext externalContext) {
this.externalContext = externalContext;
}
void addExternalContextDefinition(ExternalContextDefinition externalContextDefinition) {
externalContextDefinitions.putIfAbsent(externalContextDefinition.getName(), externalContextDefinition);
}
void addRuleImport(RuleImport ruleImport) {
ruleImports.add(ruleImport);
}
void addInclude(String include) {
includes.add(include);
}
void addFunction(FunctionSignature function) {
var header = new FunctionHeader(function.getName(), function.getParameterTypes().size());
functions.putIfAbsent(header, function);
}
String getNamespace() {
return namespace;
}
public ExternalContext getExternalContext() {
return externalContext;
}
Map<String, ExternalContextDefinition> getExternalContextDefinitions() {
return externalContextDefinitions;
}
Map<String, ContextDefinition> getContextDefinitions() {
return contextDefinitions;
}
Map<String, List<EntryPoint>> getEntryPoints() {
return entryPoints;
}
Map<String, List<Rule>> getRules() {
return rules;
}
Set<RuleImport> getRuleImports() {
return ruleImports;
}
Set<String> getIncludes() {
return includes;
}
public Map<FunctionHeader, FunctionSignature> getFunctions() {
return functions;
}
}
|
package com.nestedworld.nestedworld.analytics;
import android.support.annotation.NonNull;
import com.nestedworld.nestedworld.analytics.sender.Answer;
import com.nestedworld.nestedworld.data.database.entities.session.SessionData;
public final class NestedWorldAnalytics {
/*
* #############################################################################################
* # Constructor
* #############################################################################################
*/
private NestedWorldAnalytics() {
//Private constructor for avoiding this class to be construct
}
/*
* #############################################################################################
* # Public (static) method
* #############################################################################################
*/
public static void setUserInfo(@NonNull final SessionData sessionData) {
Answer.logUser(sessionData);
}
public static void logViewLoaded(@NonNull final String viewType,
@NonNull final String viewName) {
Answer.logViewLoaded(viewType, viewName);
}
}
|
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.hammer.validation.checkers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.archimatetool.hammer.validation.issues.IIssue;
import com.archimatetool.model.IArchimateElement;
import com.archimatetool.model.IArchimateFactory;
import com.archimatetool.model.IArchimateRelationship;
import junit.framework.JUnit4TestAdapter;
public class JunctionsCheckerTests {
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(JunctionsCheckerTests.class);
}
@Test
public void testGetIssues() {
List<IArchimateElement> elements = new ArrayList<IArchimateElement>();
IArchimateElement e1 = IArchimateFactory.eINSTANCE.createBusinessActor();
elements.add(e1);
IArchimateElement junction = IArchimateFactory.eINSTANCE.createJunction();
elements.add(junction);
IArchimateElement e2 = IArchimateFactory.eINSTANCE.createBusinessActor();
elements.add(e2);
IArchimateRelationship rel1 = IArchimateFactory.eINSTANCE.createAssignmentRelationship();
rel1.connect(e1, junction);
IArchimateRelationship rel2 = IArchimateFactory.eINSTANCE.createAssignmentRelationship();
rel2.connect(junction, e2);
JunctionsChecker checker = new JunctionsChecker(elements);
// Should be OK
List<IIssue> issues = checker.getIssues();
assertEquals(0, issues.size());
// Add a different relationship
IArchimateRelationship rel3 = IArchimateFactory.eINSTANCE.createTriggeringRelationship();
rel3.connect(junction, e2);
issues = checker.getIssues();
assertEquals(1, issues.size());
assertSame(junction, issues.get(0).getObject());
}
}
|
/*
* Copyright 2014 - 2021 Blazebit.
*
* 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.blazebit.persistence.impl.function.window.lag;
import com.blazebit.persistence.impl.function.window.AbstractWindowFunction;
import com.blazebit.persistence.spi.DbmsDialect;
import com.blazebit.persistence.spi.FunctionRenderContext;
/**
*
* @author Jan-Willem Gmelig Meyling
* @author Sayra Ranjha
* @since 1.4.0
*/
public class LagFunction extends AbstractWindowFunction {
public static final String FUNCTION_NAME = "LAG";
public LagFunction(DbmsDialect dbmsDialect) {
super(FUNCTION_NAME, dbmsDialect.isNullSmallest(), dbmsDialect.supportsWindowNullPrecedence(), false, true);
}
@Override
protected void renderArgument(FunctionRenderContext context, WindowFunction windowFunction, String caseWhenPre, String caseWhenPost, String argument, int argumentIndex) {
// Only the second argument will not receive the CASE WHEN wrapper
if (caseWhenPre == null || argumentIndex == 1) {
context.addChunk(argument);
} else {
context.addChunk(caseWhenPre);
context.addChunk(argument);
context.addChunk(caseWhenPost);
}
}
@Override
protected boolean requiresOver() {
return true;
}
}
|
package org.netlib.lapack;
import org.netlib.blas.Dscal;
import org.netlib.err.Xerbla;
import org.netlib.util.intW;
public final class Dorgr2
{
public static void dorgr2(int paramInt1, int paramInt2, int paramInt3, double[] paramArrayOfDouble1, int paramInt4, int paramInt5, double[] paramArrayOfDouble2, int paramInt6, double[] paramArrayOfDouble3, int paramInt7, intW paramintW)
{
int i = 0;
int j = 0;
int k = 0;
int m = 0;
paramintW.val = 0;
if ((paramInt1 >= 0 ? 0 : 1) != 0)
{
paramintW.val = -1;
}
else if ((paramInt2 >= paramInt1 ? 0 : 1) != 0)
{
paramintW.val = -2;
}
else
{
if ((paramInt3 >= 0 ? 0 : 1) == 0) {}
if (((paramInt3 <= paramInt1 ? 0 : 1) == 0 ? 0 : 1) != 0) {
paramintW.val = -3;
} else if ((paramInt5 >= Math.max(1, paramInt1) ? 0 : 1) != 0) {
paramintW.val = -5;
}
}
if ((paramintW.val == 0 ? 0 : 1) != 0)
{
Xerbla.xerbla("DORGR2", -paramintW.val);
return;
}
if ((paramInt1 > 0 ? 0 : 1) != 0) {
return;
}
int i1;
if ((paramInt3 >= paramInt1 ? 0 : 1) != 0)
{
k = 1;
for (n = paramInt2 - 1 + 1; n > 0; n--)
{
m = 1;
for (i1 = paramInt1 - paramInt3 - 1 + 1; i1 > 0; i1--)
{
paramArrayOfDouble1[(m - 1 + (k - 1) * paramInt5 + paramInt4)] = 0.0D;
m += 1;
}
if ((k <= paramInt2 - paramInt1 ? 0 : 1) != 0) {}
if (((k > paramInt2 - paramInt3 ? 0 : 1) != 0 ? 1 : 0) != 0) {
paramArrayOfDouble1[(paramInt1 - paramInt2 + k - 1 + (k - 1) * paramInt5 + paramInt4)] = 1.0D;
}
k += 1;
}
}
i = 1;
for (int n = paramInt3 - 1 + 1; n > 0; n--)
{
j = paramInt1 - paramInt3 + i;
paramArrayOfDouble1[(j - 1 + (paramInt2 - paramInt1 + j - 1) * paramInt5 + paramInt4)] = 1.0D;
Dlarf.dlarf("Right", j - 1, paramInt2 - paramInt1 + j, paramArrayOfDouble1, j - 1 + (1 - 1) * paramInt5 + paramInt4, paramInt5, paramArrayOfDouble2[(i - 1 + paramInt6)], paramArrayOfDouble1, paramInt4, paramInt5, paramArrayOfDouble3, paramInt7);
Dscal.dscal(paramInt2 - paramInt1 + j - 1, -paramArrayOfDouble2[(i - 1 + paramInt6)], paramArrayOfDouble1, j - 1 + (1 - 1) * paramInt5 + paramInt4, paramInt5);
paramArrayOfDouble1[(j - 1 + (paramInt2 - paramInt1 + j - 1) * paramInt5 + paramInt4)] = (1.0D - paramArrayOfDouble2[(i - 1 + paramInt6)]);
m = paramInt2 - paramInt1 + j + 1;
for (i1 = paramInt2 - (paramInt2 - paramInt1 + j + 1) + 1; i1 > 0; i1--)
{
paramArrayOfDouble1[(j - 1 + (m - 1) * paramInt5 + paramInt4)] = 0.0D;
m += 1;
}
i += 1;
}
}
}
/* Location: /Users/assaad/Downloads/arpack_combined_all/!/org/netlib/lapack/Dorgr2.class
* Java compiler version: 1 (45.3)
* JD-Core Version: 0.7.1
*/
|
// Template Source: BaseEntityCollectionPage.java.tt
// ------------------------------------------------------------------------------
// 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.requests;
import com.microsoft.graph.models.WorkbookTableColumn;
import com.microsoft.graph.requests.WorkbookTableColumnCollectionRequestBuilder;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.requests.WorkbookTableColumnCollectionResponse;
import com.microsoft.graph.http.BaseCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Workbook Table Column Collection Page.
*/
public class WorkbookTableColumnCollectionPage extends BaseCollectionPage<WorkbookTableColumn, WorkbookTableColumnCollectionRequestBuilder> {
/**
* A collection page for WorkbookTableColumn
*
* @param response the serialized WorkbookTableColumnCollectionResponse from the service
* @param builder the request builder for the next collection page
*/
public WorkbookTableColumnCollectionPage(@Nonnull final WorkbookTableColumnCollectionResponse response, @Nonnull final WorkbookTableColumnCollectionRequestBuilder builder) {
super(response, builder);
}
/**
* Creates the collection page for WorkbookTableColumn
*
* @param pageContents the contents of this page
* @param nextRequestBuilder the request builder for the next page
*/
public WorkbookTableColumnCollectionPage(@Nonnull final java.util.List<WorkbookTableColumn> pageContents, @Nullable final WorkbookTableColumnCollectionRequestBuilder nextRequestBuilder) {
super(pageContents, nextRequestBuilder);
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.4-10/27/2009 06:09 PM(mockbuild)-fcs
// 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: 2009.12.23 at 06:27:19 PM PST
//
package de.aflx.sardine.model;
//import javax.xml.bind.annotation.XmlAccessType;
//import javax.xml.bind.annotation.XmlAccessorType;
//import javax.xml.bind.annotation.XmlRootElement;
//import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
//@XmlAccessorType(XmlAccessType.FIELD)
//@XmlType(name = "")
//@XmlRootElement(name = "shared")
public class Shared {
}
|
package cn.hutool.core.io.resource;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;
/**
* 资源文件或资源不存在异常
*
* @author xiaoleilu
* @since 4.0.2
*/
public class NoResourceException extends IORuntimeException {
private static final long serialVersionUID = -623254467603299129L;
public NoResourceException(Throwable e) {
super(ExceptionUtil.getMessage(e), e);
}
public NoResourceException(String message) {
super(message);
}
public NoResourceException(String messageTemplate, Object... params) {
super(StrUtil.format(messageTemplate, params));
}
public NoResourceException(String message, Throwable throwable) {
super(message, throwable);
}
public NoResourceException(Throwable throwable, String messageTemplate, Object... params) {
super(StrUtil.format(messageTemplate, params), throwable);
}
/**
* 导致这个异常的异常是否是指定类型的异常
*
* @param clazz 异常类
* @return 是否为指定类型异常
*/
@Override
public boolean causeInstanceOf(Class<? extends Throwable> clazz) {
final Throwable cause = this.getCause();
return clazz.isInstance(cause);
}
}
|
package dome2.springcloud.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class DomeParentRestService1Application {
public static void main(String[] args) {
SpringApplication.run(DomeParentRestService1Application.class, args);
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.transaction.support;
import org.springframework.lang.Nullable;
import org.springframework.transaction.NestedTransactionNotSupportedException;
import org.springframework.transaction.SavepointManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionUsageException;
/**
* Abstract base implementation of the
* {@link org.springframework.transaction.TransactionStatus} interface.
*
* <p>Pre-implements the handling of local rollback-only and completed flags, and
* delegation to an underlying {@link org.springframework.transaction.SavepointManager}.
* Also offers the option of a holding a savepoint within the transaction.
*
* <p>Does not assume any specific internal transaction handling, such as an
* underlying transaction object, and no transaction synchronization mechanism.
*
* @author Juergen Hoeller
* @since 1.2.3
* @see #setRollbackOnly()
* @see #isRollbackOnly()
* @see #setCompleted()
* @see #isCompleted()
* @see #getSavepointManager()
* @see SimpleTransactionStatus
* @see DefaultTransactionStatus
*/
public abstract class AbstractTransactionStatus implements TransactionStatus {
private boolean rollbackOnly = false;
private boolean completed = false;
@Nullable
private Object savepoint;
//---------------------------------------------------------------------
// Implementation of TransactionExecution
//---------------------------------------------------------------------
@Override
public void setRollbackOnly() {
this.rollbackOnly = true;
}
/**
* Determine the rollback-only flag via checking both the local rollback-only flag
* of this TransactionStatus and the global rollback-only flag of the underlying
* transaction, if any.
* @see #isLocalRollbackOnly()
* @see #isGlobalRollbackOnly()
*/
@Override
public boolean isRollbackOnly() {
return (isLocalRollbackOnly() || isGlobalRollbackOnly());
}
/**
* Determine the rollback-only flag via checking this TransactionStatus.
* <p>Will only return "true" if the application called {@code setRollbackOnly}
* on this TransactionStatus object.
*/
public boolean isLocalRollbackOnly() {
return this.rollbackOnly;
}
/**
* Template method for determining the global rollback-only flag of the
* underlying transaction, if any.
* <p>This implementation always returns {@code false}.
*/
public boolean isGlobalRollbackOnly() {
return false;
}
/**
* Mark this transaction as completed, that is, committed or rolled back.
*/
public void setCompleted() {
this.completed = true;
}
@Override
public boolean isCompleted() {
return this.completed;
}
//---------------------------------------------------------------------
// Handling of current savepoint state
//---------------------------------------------------------------------
@Override
public boolean hasSavepoint() {
return (this.savepoint != null);
}
/**
* Set a savepoint for this transaction. Useful for PROPAGATION_NESTED.
* @see org.springframework.transaction.TransactionDefinition#PROPAGATION_NESTED
*/
protected void setSavepoint(@Nullable Object savepoint) {
this.savepoint = savepoint;
}
/**
* Get the savepoint for this transaction, if any.
*/
@Nullable
protected Object getSavepoint() {
return this.savepoint;
}
/**
* Create a savepoint and hold it for the transaction.
* @throws org.springframework.transaction.NestedTransactionNotSupportedException
* if the underlying transaction does not support savepoints
*/
public void createAndHoldSavepoint() throws TransactionException {
setSavepoint(getSavepointManager().createSavepoint());
}
/**
* Roll back to the savepoint that is held for the transaction
* and release the savepoint right afterwards.
*/
public void rollbackToHeldSavepoint() throws TransactionException {
// 获取保存点
Object savepoint = getSavepoint();
if (savepoint == null) {
throw new TransactionUsageException(
"Cannot roll back to savepoint - no savepoint associated with current transaction");
}
// 回滚到保存点
getSavepointManager().rollbackToSavepoint(savepoint);
// 释放保存点
getSavepointManager().releaseSavepoint(savepoint);
// 设置当前保存点为null
setSavepoint(null);
}
/**
* Release the savepoint that is held for the transaction.
*/
public void releaseHeldSavepoint() throws TransactionException {
Object savepoint = getSavepoint();
if (savepoint == null) {
throw new TransactionUsageException(
"Cannot release savepoint - no savepoint associated with current transaction");
}
getSavepointManager().releaseSavepoint(savepoint);
setSavepoint(null);
}
//---------------------------------------------------------------------
// Implementation of SavepointManager
//---------------------------------------------------------------------
/**
* This implementation delegates to a SavepointManager for the
* underlying transaction, if possible.
* @see #getSavepointManager()
* @see SavepointManager#createSavepoint()
*/
@Override
public Object createSavepoint() throws TransactionException {
return getSavepointManager().createSavepoint();
}
/**
* This implementation delegates to a SavepointManager for the
* underlying transaction, if possible.
* @see #getSavepointManager()
* @see SavepointManager#rollbackToSavepoint(Object)
*/
@Override
public void rollbackToSavepoint(Object savepoint) throws TransactionException {
getSavepointManager().rollbackToSavepoint(savepoint);
}
/**
* This implementation delegates to a SavepointManager for the
* underlying transaction, if possible.
* @see #getSavepointManager()
* @see SavepointManager#releaseSavepoint(Object)
*/
@Override
public void releaseSavepoint(Object savepoint) throws TransactionException {
getSavepointManager().releaseSavepoint(savepoint);
}
/**
* Return a SavepointManager for the underlying transaction, if possible.
* <p>Default implementation always throws a NestedTransactionNotSupportedException.
* @throws org.springframework.transaction.NestedTransactionNotSupportedException
* if the underlying transaction does not support savepoints
*/
protected SavepointManager getSavepointManager() {
throw new NestedTransactionNotSupportedException("This transaction does not support savepoints");
}
//---------------------------------------------------------------------
// Flushing support
//---------------------------------------------------------------------
/**
* This implementations is empty, considering flush as a no-op.
*/
@Override
public void flush() {
}
}
|
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.segment;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import io.druid.collections.bitmap.ConciseBitmapFactory;
import io.druid.java.util.common.Intervals;
import io.druid.segment.writeout.OffHeapMemorySegmentWriteOutMediumFactory;
import io.druid.segment.writeout.SegmentWriteOutMediumFactory;
import io.druid.segment.writeout.TmpFileSegmentWriteOutMediumFactory;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.segment.column.Column;
import io.druid.segment.incremental.IncrementalIndex;
import io.druid.segment.incremental.IncrementalIndexAdapter;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
@RunWith(Parameterized.class)
public class EmptyIndexTest
{
@Parameterized.Parameters
public static Collection<?> constructorFeeder() throws IOException
{
return ImmutableList.of(
new Object[] {TmpFileSegmentWriteOutMediumFactory.instance()},
new Object[] {OffHeapMemorySegmentWriteOutMediumFactory.instance()}
);
}
private final SegmentWriteOutMediumFactory segmentWriteOutMediumFactory;
public EmptyIndexTest(SegmentWriteOutMediumFactory segmentWriteOutMediumFactory)
{
this.segmentWriteOutMediumFactory = segmentWriteOutMediumFactory;
}
@Test
public void testEmptyIndex() throws Exception
{
File tmpDir = File.createTempFile("emptyIndex", "");
if (!tmpDir.delete()) {
throw new IllegalStateException("tmp delete failed");
}
if (!tmpDir.mkdir()) {
throw new IllegalStateException("tmp mkdir failed");
}
try {
IncrementalIndex emptyIndex = new IncrementalIndex.Builder()
.setSimpleTestingIndexSchema(/* empty */)
.setMaxRowCount(1000)
.buildOnheap();
IncrementalIndexAdapter emptyIndexAdapter = new IncrementalIndexAdapter(
Intervals.of("2012-08-01/P3D"),
emptyIndex,
new ConciseBitmapFactory()
);
TestHelper.getTestIndexMergerV9(segmentWriteOutMediumFactory).merge(
Lists.<IndexableAdapter>newArrayList(emptyIndexAdapter),
true,
new AggregatorFactory[0],
tmpDir,
new IndexSpec()
);
QueryableIndex emptyQueryableIndex = TestHelper.getTestIndexIO(segmentWriteOutMediumFactory).loadIndex(tmpDir);
Assert.assertEquals("getDimensionNames", 0, Iterables.size(emptyQueryableIndex.getAvailableDimensions()));
Assert.assertEquals("getMetricNames", 0, Iterables.size(emptyQueryableIndex.getColumnNames()));
Assert.assertEquals("getDataInterval", Intervals.of("2012-08-01/P3D"), emptyQueryableIndex.getDataInterval());
Assert.assertEquals(
"getReadOnlyTimestamps",
0,
emptyQueryableIndex.getColumn(Column.TIME_COLUMN_NAME).getLength()
);
}
finally {
FileUtils.deleteDirectory(tmpDir);
}
}
}
|
package voogasalad.view.authoringEnvironment.data;
import voogasalad.gameEngine.Engine;
import voogasalad.view.Data;
import voogasalad.view.authoringEnvironment.Editor;
/**
* LevelData keeps track of all the defenses via its super class in handling the interaction with the backend
* @author Gabriela Rodriguez-Florido, Samantha Whitt
*/
public class LevelData extends Data {
public LevelData(Editor view, Engine engine) {
super(view, engine);
}
/**
* @param new_id
*/
@Override
public void updateUI(int new_id) {
// NOT USED: no locally saving and re-editing a level
}
/**
* @param id
*/
@Override
public void load(int id) {
// NOT USED: no locally saving and re-editing a level
}
}
|
/*
* Copyright 2009-2018 Aarhus University
*
* 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 dk.brics.tajs.monitoring.soundness.logfileutilities;
import dk.au.cs.casa.jer.HashUtil;
import dk.au.cs.casa.jer.LogParser;
import dk.au.cs.casa.jer.Logger;
import dk.au.cs.casa.jer.Metadata;
import dk.au.cs.casa.jer.RawLogFile;
import dk.brics.tajs.analysis.KnownUnsoundnesses;
import dk.brics.tajs.options.OptionValues;
import dk.brics.tajs.options.Options;
import dk.brics.tajs.options.SoundnessTesterOptions;
import dk.brics.tajs.options.TAJSEnvironmentConfig;
import dk.brics.tajs.util.AnalysisException;
import dk.brics.tajs.util.Collectors;
import dk.brics.tajs.util.PathAndURLUtils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Utility class for creating, finding, or parsing the log file for a specific application.
*/
public class LogFileHelper {
private final static boolean DEBUG = false;
private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogFileHelper.class);
private static final String logSuffix = ".log";
private static final String gzipSuffix = ".gz";
private static final String loggzipSuffix = logSuffix + gzipSuffix;
private static final Charset logFileEncoding = Charset.forName("UTF-8");
private static WeakHashMap<URL, LogParser> cache = new WeakHashMap<>();
private final OptionValues options;
private final ResourceMap[] sourceToLogMapping = {
new ResourceMap("test-resources/src", "test-resources", "logs"),
new ResourceMap("benchmarks/tajs/src", "benchmarks", "tajs/logs"),
new ResourceMap("out/temp-sources", "test-resources", "logs/temp-sources")
};
public LogFileHelper(OptionValues options) {
this.options = options;
if (Arrays.stream(sourceToLogMapping).map(m -> m.subpath).collect(Collectors.toSet()).size() != sourceToLogMapping.length)
throw new AnalysisException("Subpaths are used by the class loader to resolve the correct resource folder, hence they must be distinct");
}
public static LogParser makeLogParser(URL logFile) {
if (!cache.containsKey(logFile)) {
cache.put(logFile, new LogParser(buildRawLogFileFromURL(logFile)));
}
return cache.get(logFile);
}
private static RawLogFile buildRawLogFileFromURL(URL logFile) {
String path = logFile.getPath();
if (path.endsWith(gzipSuffix)) {
try (GZIPInputStream zis = new GZIPInputStream(logFile.openStream())) {
return buildRawLogFileFromStream(zis);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
try (InputStream inputStream = logFile.openStream()) {
return buildRawLogFileFromStream(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static RawLogFile buildRawLogFileFromStream(InputStream inputStream) {
List<String> logFileLines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream), logFileEncoding))) {
String line;
while ((line = br.readLine()) != null) {
logFileLines.add(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return new RawLogFile(logFileLines);
}
public URL getLogFile() {
return getAllLogFilePositions().runtimeLocation;
}
public URL createOrGetLogFile() {
LogFileLocations logFileLocations = getAllLogFilePositions();
if (options.getSoundnessTesterOptions().isRegenerate()) {
wipeLogFilesIfPossible(logFileLocations);
}
URL runtimeLocation = logFileLocations.runtimeLocation;
boolean isConsumable = false, isEmpty = true;
if ((isConsumable = PathAndURLUtils.isConsumable(runtimeLocation))
&& (!(isEmpty = isEmptyContent(runtimeLocation)))
&& (verifySha(logFileLocations, getMainFile()))) {
return runtimeLocation;
}
boolean canProduceLogForFile = !KnownUnsoundnesses.isUnloggableMainFile(getMainFile());
boolean canProduceLogAtAll = SoundnessTesterOptions.isLogCreationPossible();
boolean isAllowedToProduceLog = options.getSoundnessTesterOptions().isGenerate();
if(DEBUG) {
System.out.println(String.format("Log creation info \n" +
" runtime-path: %s, \n" +
" persistent-path: %s, \n" +
" consumable: %b, empty: %b, unloggable-main-file: %b, log-creation-possible: %b, allowed-to-produce: %b)",
logFileLocations.runtimeLocation, logFileLocations.persistentLocation, isConsumable, isEmpty, canProduceLogForFile, canProduceLogAtAll, isAllowedToProduceLog));
}
boolean createLog = canProduceLogAtAll && canProduceLogForFile && isAllowedToProduceLog;
if (!canProduceLogForFile) {
warn("Could not create value log file: main file is known to be unsupported (limitation of the jalangilogger project)");
} else if (!isAllowedToProduceLog) {
throw new LogFileException("Could not create value log file: creation of new log files is not enabled");
} else if (!canProduceLogAtAll) {
throw new LogFileException("Could not create value log file: missing jalangilogger installation (see README)");
}
if (createLog) {
wipeLogFilesIfPossible(logFileLocations);
RawLogFile rawLogFile = generateLogFile(getMainFile());
Path runtimePath = PathAndURLUtils.toPath(runtimeLocation);
try {
Files.createDirectories(runtimePath.getParent());
if (runtimePath.getFileName().toString().endsWith(gzipSuffix)) {
gzipLogFile(rawLogFile, runtimePath);
} else {
Files.write(runtimePath, rawLogFile.getLines(), logFileEncoding);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if (logFileLocations.persistentLocation.isPresent()) {
Path persistentPath = PathAndURLUtils.toPath(logFileLocations.persistentLocation.get());
if (!persistentPath.equals(runtimePath)) {
try (InputStream persistentStream = runtimeLocation.openStream()) {
Files.createDirectories(persistentPath.getParent());
if (Files.copy(persistentStream, persistentPath, StandardCopyOption.REPLACE_EXISTING) <= 0)
throw new RuntimeException("No byte written when persisting a copy of the log file");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} else {
warn("Creating log file, but not persisting it (a 'tajs' entry in .tajsconfig is needed)");
}
return runtimeLocation;
}
return null;
}
private void wipeLogFilesIfPossible(LogFileLocations logFileLocations) {
wipeFileIfPossible(logFileLocations.runtimeLocation);
if (logFileLocations.persistentLocation.isPresent()) {
wipeFileIfPossible(logFileLocations.persistentLocation.get());
}
}
private boolean isEmptyContent(URL url) {
try (InputStream is = url.openStream()) {
return is.read() == -1;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private LogFileLocations getAllLogFilePositions() {
Optional<Path> slogFile = options.getSoundnessTesterOptions().getExplicitSoundnessLogFile();
if (slogFile.isPresent()) {
URL url = PathAndURLUtils.toURL(slogFile.get());
return new LogFileLocations(Optional.of(url), url);
}
return inferLogFilePosition();
}
public Path getMainFile() {
return options.getArguments().get(Options.get().getArguments().size() - 1);
}
private Metadata getMetaData(URL firstLogFile) {
return makeLogParser(firstLogFile).getMetadata();
}
private void gzipLogFile(RawLogFile logFileLines, Path target) throws IOException {
String fileName = target.getFileName().toString();
if (!fileName.endsWith(gzipSuffix)) {
throw new IllegalArgumentException("Attempting to gzip to non-gzip file: " + target);
}
byte[] newLine = "\n".getBytes(logFileEncoding);
try (FileOutputStream zipFile = new FileOutputStream(target.toFile()); GZIPOutputStream zipOut = new GZIPOutputStream(zipFile)) {
logFileLines.getLines().forEach(line -> {
try {
zipOut.write(line.getBytes(logFileEncoding));
zipOut.write(newLine);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
private void wipeFileIfPossible(URL location) {
cache.remove(location);
Path relativeLogFilePath = PathAndURLUtils.toPath(location);
try {
Files.deleteIfExists(relativeLogFilePath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Infers all the locations of a log file for soundness testing of a JavaScript file using the source to log mapping.
* When invoked in an IDE, both the build folder resource folder and the original resource folder are taken into account.
* If the one in the original resource folder one is not available for any reason, the the only one returned is the one
* accessible through resources.
* <p>
* Examples:
* <pre>
* test-resources/src/bar/baz.js -> test-resources/logs/bar/baz.js.log
* </pre>
*/
private LogFileLocations inferLogFilePosition() {
Path mainFile = getMainFile();
if (mainFile.isAbsolute()) {
mainFile = attemptToRelativizeAbsolutePath(mainFile);
}
String suffix = options.getSoundnessTesterOptions().isUseUncompressedLogFileForInference() ? logSuffix : loggzipSuffix;
Path preMappedLogFile = Paths.get(makeLogFileNameFromPrefix(mainFile, suffix));
List<ResourceMap> mappers = Arrays.stream(sourceToLogMapping)
.filter(m -> m.map(preMappedLogFile).isPresent())
.collect(Collectors.toList());
if(mappers.size() != 1)
throw new AnalysisException("Expected to be able to map " + mainFile + " to its logs location, viable mappers: " + mappers);
Path mappedLogFilePath = mappers.get(0).map(preMappedLogFile).get();
URL runtimeLogFileLocation = mappers.get(0).mapToResource(preMappedLogFile).get();
Optional<URL> persistentLogFileLocation = inferPersistentLogFileLocation(mappedLogFilePath);
return new LogFileLocations(persistentLogFileLocation, runtimeLogFileLocation);
}
private String makeLogFileNameFromPrefix(Path mainFile, String suffix) {
return String.format("%s%s", mainFile, suffix);
}
private Path attemptToRelativizeAbsolutePath(Path mainFile) {
if (TAJSEnvironmentConfig.get().hasProperty("tajs")) {
Path tajs = Paths.get(TAJSEnvironmentConfig.get().getCustom("tajs"));
try {
Path resolved = mainFile.toRealPath(); // resolve symlinks
boolean inTAJSDirectory = resolved.toAbsolutePath().startsWith(tajs.toAbsolutePath());
if (inTAJSDirectory) {
return tajs.relativize(resolved);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
throw new IllegalArgumentException("Only relative paths supported for log file inference (maybe a 'tajs' entry in .tajsconfig would help): " + mainFile);
}
private Optional<URL> inferPersistentLogFileLocation(Path logFile) {
String tajsConfigPropertyName = "tajs";
if (!TAJSEnvironmentConfig.get().hasProperty(tajsConfigPropertyName)) {
return Optional.empty();
}
Path persistentFilePath = Paths.get(TAJSEnvironmentConfig.get().getCustom(tajsConfigPropertyName)).resolve(logFile);
return Optional.of(PathAndURLUtils.toURL(persistentFilePath));
}
private RawLogFile generateLogFile(Path testFile) {
Path jalangilogger = SoundnessTesterOptions.getJalangiLogger();
Path node = TAJSEnvironmentConfig.get().getNode();
Path jjs = Paths.get(TAJSEnvironmentConfig.get().getCustom("jjs"));
Optional<Integer> explicitTimeLimit = options.getSoundnessTesterOptions().getTimeLimitExplicitly();
Optional<Integer> explicitInstrumentationTimeLimit = options.getSoundnessTesterOptions().getInstrumentationTimeLimitExplicitly();
Optional<Logger.Environment> explicitEnvironment = options.getSoundnessTesterOptions().getGeneratorEnvironmentExplicitly();
Logger.Environment environment = explicitEnvironment.orElseGet(() ->
options.isDOMEnabled() ?
(options.getSoundnessTesterOptions().isNonInteractive() ?
Logger.Environment.DRIVEN_BROWSER : Logger.Environment.BROWSER)
:
Options.get().isNodeJS() ? Logger.Environment.NODE : Logger.Environment.NODE_GLOBAL);
Integer timeLimit = explicitTimeLimit.orElse(30);
Integer instrumentationTimeLimit = explicitInstrumentationTimeLimit.orElse(30);
try {
Path customRootDirectory = getCustomRootDirectoryForTest(testFile);
List<Path> preambles = getPreambles();
Optional<Set<Path>> onlyInclude = options.getSoundnessTesterOptions().getOnlyIncludesForInstrumentation();
if (customRootDirectory == null) {
return Logger.makeLoggerForIndependentMainFile(testFile, preambles, onlyInclude, instrumentationTimeLimit, timeLimit, environment, node, jalangilogger, jjs).log();
} else {
Path rootRelativeMain = customRootDirectory.relativize(testFile.toAbsolutePath());
return Logger.makeLoggerForDirectoryWithMainFile(customRootDirectory, rootRelativeMain, preambles, onlyInclude, instrumentationTimeLimit, timeLimit, environment, node, jalangilogger, jjs).log();
}
} catch (IOException e) {
throw new LogFileException("Failed to create new log file", e);
}
}
private List<Path> getPreambles() {
List<Path> args = options.getArguments();
List<Path> preambles = new ArrayList<>();
//The last element in args is the main file
//Everything else is assumed to be a preamble
for (int i = 0; i < args.size() - 1; i++) {
Path preamble = args.get(i).toAbsolutePath();
preambles.add(preamble);
}
return preambles;
}
private Path getCustomRootDirectoryForTest(Path main) {
Path rootDirectoryFromMainDirectory = options.getSoundnessTesterOptions().getRootDirFromMainDirectory();
if (rootDirectoryFromMainDirectory == null) {
return null;
}
return main.getParent().resolve(rootDirectoryFromMainDirectory).toAbsolutePath().normalize();
}
private boolean verifySha(LogFileLocations logFileLocations, Path jsFile) {
Metadata metadata = getMetaData(logFileLocations.runtimeLocation);
String expectedSha = metadata.getSha();
Path rootDirectoryFromMain = getCustomRootDirectoryForTest(jsFile);
String currentSha;
if (Options.get().getSoundnessTesterOptions().getOnlyIncludesForInstrumentation().isPresent()) {
currentSha = HashUtil.shaDirOrFile(Options.get().getSoundnessTesterOptions().getOnlyIncludesForInstrumentation().get());
} else {
if (rootDirectoryFromMain == null) {
currentSha = HashUtil.shaDirOrFile(jsFile);
} else {
currentSha = HashUtil.shaDirOrFile(getCustomRootDirectoryForTest(jsFile));
}
}
if (currentSha.equals(expectedSha)) {
return true;
}
if (options.getSoundnessTesterOptions().isIgnoreShaDifference()) {
warn("Ignoring SHA-mismatch for %s (expected %s, got %s)", metadata.getRoot(), expectedSha, currentSha);
return true;
}
if (options.getSoundnessTesterOptions().isForceUpdateSha()) {
warn("Force-updating SHA-mismatch for %s (expected %s, got %s)", metadata.getRoot(), expectedSha, currentSha);
forceUpdateSha(PathAndURLUtils.toPath(logFileLocations.runtimeLocation), expectedSha, currentSha);
if (logFileLocations.persistentLocation.isPresent()) {
forceUpdateSha(PathAndURLUtils.toPath(logFileLocations.persistentLocation.get()), expectedSha, currentSha);
}
return true;
}
return false;
}
private void warn(String format, Object... args) {
log.warn(String.format(format, args));
}
/**
* Updates the registered SHA in the metadata of a log-file.
*/
private void forceUpdateSha(Path logFile, String oldSha, String newSha) {
try {
RawLogFile rawLogFile = buildRawLogFileFromURL(PathAndURLUtils.toURL(logFile));
List<String> lines = rawLogFile.getLines();
lines.set(0, lines.get(0).replaceAll(oldSha, newSha)); // hacky, but easy
gzipLogFile(rawLogFile, logFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Bean for the location of the log files to make use of.
*/
private class LogFileLocations {
/**
* The persistent location of the log file. This will typically be the TAJS/resources/jalangilogfiles directory.
* This location is used for creating/updating log files, which in turn will be copied to the runtimeLocation during a later build step.
*/
private final Optional<URL> persistentLocation;
/**
* The location of the log file in the current runtime. This will typically be in a build-folder or inside a jar.
*/
private final URL runtimeLocation;
public LogFileLocations(Optional<URL> persistentLocation, URL runtimeLocation) {
this.persistentLocation = persistentLocation;
this.runtimeLocation = runtimeLocation;
}
}
/**
* Exception for situations where there is something wrong with a log file.
*/
public static class LogFileException extends RuntimeException {
public LogFileException(String s) {
super(s);
}
public LogFileException(String s, Throwable t) {
super(s, t);
}
}
private static class ResourceMap {
/**
* The substring of the path that is mapped.
*/
Path originalPathPart;
/**
* Name of resource folder, used when transorming a path of the form
* <p>
* test-resources/subpath...
* <p>
* into a resource path
* <p>
* /subpath...
*/
Path resourceFolder;
/**
* The subpath from the resource folder.
*/
Path subpath;
ResourceMap(String originalPathPart, String resourceFolder, String subpath) {
this.originalPathPart = Paths.get(originalPathPart);
this.resourceFolder = Paths.get(resourceFolder);
this.subpath = Paths.get(subpath);
if (!this.resourceFolder.resolve(this.subpath).normalize().startsWith(resourceFolder))
throw new AnalysisException("Subpath cannot point to a parent of the resource folder");
if (this.resourceFolder.resolve(this.subpath).equals(this.resourceFolder))
throw new AnalysisException("Need to specify a subfolder as subpath");
}
public Optional<Path> map(Path p) {
Path mapping = resourceFolder.resolve(subpath);
if (p.startsWith(originalPathPart)) {
return Optional.of(mapping.resolve(originalPathPart.relativize(p)));
}
return Optional.empty();
}
public Optional<URL> mapToResource(Path p) {
Optional<Path> mapped = map(p);
return mapped.map(m -> {
Path folderInResourceFolder = resourceFolder.resolve(subpath);
URL containing = Thread.currentThread().getContextClassLoader().getResource(subpath + "/");
if (containing == null)
throw new AnalysisException("Could not find folder in resource folder " + subpath);
Path relative = folderInResourceFolder.relativize(m);
try {
return new URL(containing, relative.toString());
} catch (MalformedURLException e) {
throw new AnalysisException("Malformed URL: " + folderInResourceFolder + "/" + relative);
}
});
}
@Override
public String toString() {
return originalPathPart + " -> " + resourceFolder.resolve(subpath);
}
}
}
|
package com.atguigu.gmall.utils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 异常处理器
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年10月27日 下午10:16:19
*/
@Component
public class RRExceptionHandler implements HandlerExceptionResolver {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
R r = new R();
try {
response.setContentType("application/json;charset=utf-8");
response.setCharacterEncoding("utf-8");
if (ex instanceof RRException) {
r.put("code", ((RRException) ex).getCode());
r.put("msg", ((RRException) ex).getMessage());
}else if(ex instanceof DuplicateKeyException){
r = R.error("数据库中已存在该记录");
}else{
r = R.error();
}
//记录异常日志
logger.error(ex.getMessage(), ex);
String json = JSON.toJSONString(r);
response.getWriter().print(json);
} catch (Exception e) {
logger.error("RRExceptionHandler 异常处理失败", e);
}
return new ModelAndView();
}
}
|
/*
* Copyright 2012-2013 Hauser Olsson 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 ch.agent.crnickl.api;
import java.util.Collection;
import ch.agent.crnickl.T2DBException;
/**
* An IncompleteSchema provides common behavior to {@link Schema} and
* {@link SeriesDefinition}. Both can have a number of {@link Attribute}s defined.
*
* @author Jean-Paul Vetterli
*/
public interface IncompleteSchema {
/**
* Return the name of the schema or series definition.
*
* @return the name of the schema or the series definition
*/
String getName();
/**
* Return the collection of all attribute definitions. The collection is sorted by
* attribute number. For a schema, the result does not include any series attribute
* definition.
*
* @return the collection of all attribute definitions
*/
Collection<AttributeDefinition<?>> getAttributeDefinitions();
/**
* Return the attribute definition with the given attribute name. The
* <code>mustExist</code> parameter determines behavior when nothing is
* found: exception or null result.
*
* @param name
* the name of the attribute
* @param mustExist
* if true throw an exception instead of returning null
* @return an attribute definition or null (only when mustExist is false)
* @throws T2DBException
*/
AttributeDefinition<?> getAttributeDefinition(String name, boolean mustExist) throws T2DBException;
/**
* Return the attribute definition with the given attribute number. The
* <code>mustExist</code> parameter determines behavior when nothing is
* found: exception or null result.
*
* @param number
* the number of the attribute
* @param mustExist
* if true throw an exception instead of returning null
* @return an attribute definition or null (only when mustExist is false)
* @throws T2DBException
*/
AttributeDefinition<?> getAttributeDefinition(int number, boolean mustExist) throws T2DBException;
}
|
package io.ztidentity.javaagent.smoketest;
import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;
import java.io.IOException;
import java.util.Collection;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.Test;
class SpringBootSmokeTest extends SmokeTest {
protected String getTargetImage(int jdk) {
return "ghcr.io/open-telemetry/java-test-containers:smoke-springboot-jdk" + jdk
+ "-20210218.577304949";
}
@Test
public void springBootSmokeTestOnJDK() throws IOException, InterruptedException {
startTarget(11);
String url = String.format("http://localhost:%d/greeting", target.getMappedPort(8080));
Request request = new Request.Builder().url(url).get().build();
String currentAgentVersion =
(String) new JarFile(agentPath)
.getManifest()
.getMainAttributes()
.get(Attributes.Name.IMPLEMENTATION_VERSION);
Response response = client.newCall(request).execute();
System.out.println(response.headers().toString());
Collection<ExportTraceServiceRequest> traces = waitForTraces();
/*
Assertions.assertNotNull(response.header("X-server-id"));
Assertions.assertEquals(1, response.headers("X-server-id").size());
Assertions.assertTrue(TraceId.isValid(response.header("X-server-id")));
Assertions.assertEquals("Hi!", response.body().string());
Assertions.assertEquals(1, countSpansByName(traces, "/greeting"));
Assertions.assertEquals(0, countSpansByName(traces, "WebController.greeting"));
Assertions.assertEquals(1, countSpansByName(traces, "WebController.withSpan"));
Assertions.assertEquals(2, countSpansByAttributeValue(traces, "custom", "demo"));
Assertions.assertNotEquals(0,
countResourcesByValue(traces, "telemetry.auto.version", currentAgentVersion));
Assertions.assertNotEquals(0, countResourcesByValue(traces, "custom.resource", "demo"));
*/
stopTarget();
}
}
|
package dev.utils.common;
import java.io.Closeable;
import dev.utils.JCLogUtils;
/**
* detail: 关闭工具类 - (关闭IO流等)
* Created by Ttt
*/
public final class CloseUtils {
private CloseUtils() {
}
// 日志TAG
private static final String TAG = CloseUtils.class.getSimpleName();
/**
* 关闭 IO
* @param closeables closeables
*/
public static void closeIO(final Closeable... closeables) {
if (closeables == null) return;
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
JCLogUtils.eTag(TAG, e, "closeIO");
}
}
}
}
/**
* 安静关闭 IO
* @param closeables closeables
*/
public static void closeIOQuietly(final Closeable... closeables) {
if (closeables == null) return;
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception ignore) {
JCLogUtils.eTag(TAG, ignore, "closeIO");
}
}
}
}
}
|
/*
* Licensed to ObjectStyle LLC under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ObjectStyle LLC 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 io.bootique.aws2;
import io.bootique.aws2.credentials.BasicAwsCredentials;
import io.bootique.junit5.BQTest;
import io.bootique.junit5.BQTestFactory;
import io.bootique.junit5.BQTestTool;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain;
import static org.junit.jupiter.api.Assertions.*;
@BQTest
public class AwsModuleIT {
@BQTestTool
final BQTestFactory testFactory = new BQTestFactory();
@Test
@DisplayName("Credentials provider based on BQ config")
public void testAwsConfig_BootiqueCredentialsProvider() {
AwsConfig config = testFactory
.app()
.autoLoadModules()
.property("bq.aws.accessKey", "xyz")
.property("bq.aws.secretKey", "abc")
.createRuntime()
.getInstance(AwsConfig.class);
AwsCredentials credentials = config.getCredentialsProvider().resolveCredentials();
assertNotNull(credentials);
assertEquals("xyz", credentials.accessKeyId());
assertEquals("abc", credentials.secretAccessKey());
}
@Test
@DisplayName("When no BQ credentials configured, alt provider must take over")
public void testAwsConfig_AltCredentialsProvider() {
AwsConfig config = testFactory
.app()
.autoLoadModules()
.module(b -> AwsModule.extend(b).addCredentialsProvider(new TestCredentialsProvider("tcpa", "tcps"), 5))
.createRuntime()
.getInstance(AwsConfig.class);
assertTrue(config.getCredentialsProvider() instanceof TestCredentialsProvider);
AwsCredentials credentials = config.getCredentialsProvider().resolveCredentials();
assertNotNull(credentials);
assertEquals("tcpa", credentials.accessKeyId());
assertEquals("tcps", credentials.secretAccessKey());
}
@Test
@DisplayName("When no BQ credentials configured, alt provider must take over")
public void testAwsConfig_AltCredentialsProvider_Ordering() {
AwsConfig config = testFactory
.app()
.autoLoadModules()
.module(b -> AwsModule.extend(b).addCredentialsProvider(new TestCredentialsProvider("tcpa1", "tcps1"), 5))
.module(b -> AwsModule.extend(b).addCredentialsProvider(new TestCredentialsProvider("tcpa2", "tcps2"), 2))
.module(b -> AwsModule.extend(b).addCredentialsProvider(new TestCredentialsProvider("tcpa3", "tcps3"), 6))
.createRuntime()
.getInstance(AwsConfig.class);
assertTrue(config.getCredentialsProvider() instanceof AwsCredentialsProviderChain);
AwsCredentials credentials = config.getCredentialsProvider().resolveCredentials();
assertNotNull(credentials);
assertEquals("tcpa2", credentials.accessKeyId());
assertEquals("tcps2", credentials.secretAccessKey());
}
@Test
@DisplayName("When BQ credentials are present, alt provider must be ignored")
public void testAwsConfig_AltCredentialsProvider_BqProviderWins() {
AwsConfig config = testFactory
.app()
.autoLoadModules()
.property("bq.aws.accessKey", "xyz")
.property("bq.aws.secretKey", "abc")
.module(b -> AwsModule.extend(b).addCredentialsProvider(new TestCredentialsProvider("tcpa", "tcps"), 5))
.createRuntime()
.getInstance(AwsConfig.class);
AwsCredentials credentials = config.getCredentialsProvider().resolveCredentials();
assertNotNull(credentials);
assertEquals("xyz", credentials.accessKeyId());
assertEquals("abc", credentials.secretAccessKey());
}
static final class TestCredentialsProvider implements AwsCredentialsProvider {
private final String accessKey;
private final String secretKey;
public TestCredentialsProvider(String accessKey, String secretKey) {
this.accessKey = accessKey;
this.secretKey = secretKey;
}
@Override
public AwsCredentials resolveCredentials() {
return new BasicAwsCredentials(accessKey, secretKey);
}
}
}
|
/*
* This file is part of JSTUN.
*
* Copyright (c) 2005 Thomas King <king@t-king.de> - All rights
* reserved.
*
* This software is licensed under either the GNU Public License (GPL),
* or the Apache 2.0 license. Copies of both license agreements are
* included in this distribution.
*/
package de.javawi.jstun.util;
public class Utility
{
public static final byte integerToOneByte(int value) throws UtilityException
{
if ((value > Math.pow(2, 15)) || (value < 0))
{
throw new UtilityException("Integer value " + value
+ " is larger than 2^15");
}
return (byte) (value & 0xFF);
}
public static final byte[] integerToTwoBytes(int value) throws UtilityException
{
byte[] result = new byte[2];
if ((value > Math.pow(2, 31)) || (value < 0))
{
throw new UtilityException("Integer value " + value
+ " is larger than 2^31");
}
result[0] = (byte) ((value >>> 8) & 0xFF);
result[1] = (byte) (value & 0xFF);
return result;
}
public static final byte[] integerToFourBytes(int value) throws UtilityException
{
byte[] result = new byte[4];
if ((value > Math.pow(2, 63)) || (value < 0))
{
throw new UtilityException("Integer value " + value
+ " is larger than 2^63");
}
result[0] = (byte) ((value >>> 24) & 0xFF);
result[1] = (byte) ((value >>> 16) & 0xFF);
result[2] = (byte) ((value >>> 8) & 0xFF);
result[3] = (byte) (value & 0xFF);
return result;
}
public static final int oneByteToInteger(byte value) throws UtilityException
{
return (int) value & 0xFF;
}
public static final int twoBytesToInteger(byte[] value) throws UtilityException
{
if (value.length < 2)
{
throw new UtilityException("Byte array too short!");
}
int temp0 = value[0] & 0xFF;
int temp1 = value[1] & 0xFF;
return ((temp0 << 8) + temp1);
}
public static final long fourBytesToLong(byte[] value) throws UtilityException
{
if (value.length < 4)
{
throw new UtilityException("Byte array too short!");
}
int temp0 = value[0] & 0xFF;
int temp1 = value[1] & 0xFF;
int temp2 = value[2] & 0xFF;
int temp3 = value[3] & 0xFF;
return (((long) temp0 << 24) + (temp1 << 16) + (temp2 << 8) + temp3);
}
}
|
/*
* generated by Xtext 2.25.0
*/
package science.robbert.scoping;
/**
* This class contains custom scoping description.
*
* See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#scoping
* on how and when to use it.
*/
public class TardisLScopeProvider extends AbstractTardisLScopeProvider {
}
|
/*
* 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.flink.addons.hbase;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.table.sources.BatchTableSource;
import org.apache.flink.table.sources.ProjectableTableSource;
import org.apache.flink.types.Row;
import org.apache.flink.util.Preconditions;
import org.apache.hadoop.conf.Configuration;
import java.util.Map;
/**
* Creates a TableSource to scan an HBase table.
*
* The table name and required HBase configuration is passed during {@link HBaseTableSource} construction.
* Use {@link #addColumn(String, String, Class)} to specify the family, qualifier, and type of columns to scan.
*
* The TableSource returns {@link Row} with nested Rows for each column family.
*
* The HBaseTableSource is used as shown in the example below.
*
* <pre>
* {@code
* HBaseTableSource hSrc = new HBaseTableSource(conf, "hTable");
* hSrc.addColumn("fam1", "col1", byte[].class);
* hSrc.addColumn("fam1", "col2", Integer.class);
* hSrc.addColumn("fam2", "col1", String.class);
*
* tableEnv.registerTableSource("hTable", hSrc);
* Table res = tableEnv.sql("SELECT t.fam2.col1, SUM(t.fam1.col2) FROM hTable AS t GROUP BY t.fam2.col1");
* }
* </pre>
*
*/
public class HBaseTableSource implements BatchTableSource<Row>, ProjectableTableSource<Row> {
private Configuration conf;
private String tableName;
private HBaseTableSchema schema;
/**
* The HBase configuration and the name of the table to read.
*
* @param conf hbase configuration
* @param tableName the tableName
*/
public HBaseTableSource(Configuration conf, String tableName) {
this.conf = conf;
this.tableName = Preconditions.checkNotNull(tableName, "Table name");
this.schema = new HBaseTableSchema();
}
/**
* Adds a column defined by family, qualifier, and type to the table schema.
*
* @param family the family name
* @param qualifier the qualifier name
* @param clazz the data type of the qualifier
*/
public void addColumn(String family, String qualifier, Class<?> clazz) {
this.schema.addColumn(family, qualifier, clazz);
}
/**
* Specifies the charset to parse Strings to HBase byte[] keys and String values.
*
* @param charset Name of the charset to use.
*/
public void setCharset(String charset) {
this.schema.setCharset(charset);
}
@Override
public TypeInformation<Row> getReturnType() {
String[] famNames = schema.getFamilyNames();
TypeInformation<?>[] typeInfos = new TypeInformation[famNames.length];
int i = 0;
for (String family : famNames) {
typeInfos[i] = new RowTypeInfo(schema.getQualifierTypes(family), schema.getQualifierNames(family));
i++;
}
return new RowTypeInfo(typeInfos, famNames);
}
@Override
public DataSet<Row> getDataSet(ExecutionEnvironment execEnv) {
return execEnv.createInput(new HBaseRowInputFormat(conf, tableName, schema), getReturnType());
}
@Override
public HBaseTableSource projectFields(int[] fields) {
String[] famNames = schema.getFamilyNames();
HBaseTableSource newTableSource = new HBaseTableSource(this.conf, tableName);
// Extract the family from the given fields
for(int field : fields) {
String family = famNames[field];
Map<String, TypeInformation<?>> familyInfo = schema.getFamilyInfo(family);
for(String qualifier : familyInfo.keySet()) {
// create the newSchema
newTableSource.addColumn(family, qualifier, familyInfo.get(qualifier).getTypeClass());
}
}
return newTableSource;
}
@Override
public String explainSource() {
return "";
}
}
|
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.egeria.connectors.ibm.ia.clientlibrary.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RuleSetExecutionResult extends AbstractRuleExecutionResult {
@JacksonXmlProperty(isAttribute = true) private Integer nbRules;
@JacksonXmlProperty(isAttribute = true) private Double meanNbFailedRulesPerRecord;
@JacksonXmlProperty(isAttribute = true) private Double stddevNbFailedRulesPerRecord;
@JacksonXmlProperty(isAttribute = true) private Double meanPercentFailedRulesPerRecord;
@JacksonXmlProperty(isAttribute = true) private Double stddevPercentFailedRulesPerRecord;
@JacksonXmlElementWrapper(localName = "RelativeFailureDistribution")
private List<ContinuousDistributionItem> relativeFailureDistribution;
@JacksonXmlElementWrapper(localName = "AbsoluteFailureDistribution")
private List<DiscreteDistributionItem> absoluteFailureDistribution;
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "RuleExecutionResult")
private List<RuleExecutionResult> ruleExecutionResults;
public Integer getNbRules() { return nbRules; }
public void setNbRules(Integer nbRules) { this.nbRules = nbRules; }
public Double getMeanNbFailedRulesPerRecord() { return meanNbFailedRulesPerRecord; }
public void setMeanNbFailedRulesPerRecord(Double meanNbFailedRulesPerRecord) { this.meanNbFailedRulesPerRecord = meanNbFailedRulesPerRecord; }
public Double getStddevNbFailedRulesPerRecord() { return stddevNbFailedRulesPerRecord; }
public void setStddevNbFailedRulesPerRecord(Double stddevNbFailedRulesPerRecord) { this.stddevNbFailedRulesPerRecord = stddevNbFailedRulesPerRecord; }
public Double getMeanPercentFailedRulesPerRecord() { return meanPercentFailedRulesPerRecord; }
public void setMeanPercentFailedRulesPerRecord(Double meanPercentFailedRulesPerRecord) { this.meanPercentFailedRulesPerRecord = meanPercentFailedRulesPerRecord; }
public Double getStddevPercentFailedRulesPerRecord() { return stddevPercentFailedRulesPerRecord; }
public void setStddevPercentFailedRulesPerRecord(Double stddevPercentFailedRulesPerRecord) { this.stddevPercentFailedRulesPerRecord = stddevPercentFailedRulesPerRecord; }
public List<ContinuousDistributionItem> getRelativeFailureDistribution() { return relativeFailureDistribution; }
public void setRelativeFailureDistribution(List<ContinuousDistributionItem> relativeFailureDistribution) { this.relativeFailureDistribution = relativeFailureDistribution; }
public List<DiscreteDistributionItem> getAbsoluteFailureDistribution() { return absoluteFailureDistribution; }
public void setAbsoluteFailureDistribution(List<DiscreteDistributionItem> absoluteFailureDistribution) { this.absoluteFailureDistribution = absoluteFailureDistribution; }
public List<RuleExecutionResult> getRuleExecutionResults() { return ruleExecutionResults; }
public void setRuleExecutionResults(List<RuleExecutionResult> ruleExecutionResults) { this.ruleExecutionResults = ruleExecutionResults; }
@Override
public String toString() {
String parent = super.toString();
return parent.substring(0, parent.length() - 2)
+ ", \"nbRules\": " + nbRules
+ ", \"meanNbFailedRulesPerRecord\": " + meanNbFailedRulesPerRecord
+ ", \"stddevNbFailedRulesPerRecord\": " + stddevNbFailedRulesPerRecord
+ ", \"meanPercentFailedRulesPerRecord\": " + meanPercentFailedRulesPerRecord
+ ", \"stddevPercentFailedRulesPerRecord\": " + stddevPercentFailedRulesPerRecord
+ ", \"RelativeFailureDistribution\": " + (relativeFailureDistribution == null ? "{}" : relativeFailureDistribution.toString())
+ ", \"AbsoluteFailureDistribution\": " + (absoluteFailureDistribution == null ? "{}" : absoluteFailureDistribution.toString())
+ ", \"RuleExecutionResults\": " + (ruleExecutionResults == null ? "[]" : ruleExecutionResults.toString())
+ " }";
}
}
|
/**
* 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.wicketTutorial;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.CompoundPropertyModel;
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
public HomePage(final PageParameters parameters) {
super(parameters);
add(new LoginForm("loginForm"));
}
class LoginForm extends Form{
private String username;
private String password;
private String loginStatus;
public LoginForm(String id) {
super(id);
setDefaultModel(new CompoundPropertyModel(this));
add(new TextField("username"));
add(new PasswordTextField("password"));
add(new Label("loginStatus"));
}
public final void onSubmit() {
if(username.equals("test") && password.equals("test"))
loginStatus = "Congratulations!";
else
loginStatus = "Wrong username or password !";
}
}
}
|
package com.zhazhapan.demo.algorithm.leetcode.contest.before;
/**
* @author pantao
* @since 2019-03-10
*/
public class Contest1006 {
private int met;
private char[] chars = new char[]{'-', '+', '/', '*'};
public int clumsy(int n) {
met = 3;
StringBuilder builder = new StringBuilder().append(n);
for (int i = n - 1; i > 0; i--) {
builder.append(charHelper()).append(i);
}
return 1;
}
private char charHelper() {
if (met < 0) {
met = 3;
}
return chars[met--];
}
}
|
package stellarapi.api.gui.overlay;
import net.minecraft.client.Minecraft;
/**
* The main gui overlay.
*/
public interface IOverlayElement<Settings extends PerOverlaySettings> {
public void initialize(Minecraft mc, Settings settings);
public int getWidth();
public int getHeight();
public float animationOffsetX(float partialTicks);
public float animationOffsetY(float partialTicks);
public void switchMode(EnumOverlayMode mode);
public void updateOverlay();
/** Return true to update settings */
public boolean mouseClicked(int mouseX, int mouseY, int eventButton);
/** Return true to update settings */
public boolean mouseClickMove(int scaledMouseX, int scaledMouseY, int eventButton, long timeSinceLastClick);
/** Return true to update settings */
public boolean mouseReleased(int mouseX, int mouseY, int eventButton);
/** Return true to update settings */
public boolean keyTyped(char eventChar, int eventKey);
public void render(int mouseX, int mouseY, float partialTicks);
}
|
package models;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "warehouse_managers",
uniqueConstraints = {@UniqueConstraint(columnNames = {"warehouse", "user"})})
public class WarehouseManager {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(optional = false)
@JoinColumn(name = "warehouse")
private Warehouse warehouse;
@ManyToOne(optional = false)
@JoinColumn(name = "user")
private User user;
@Column(name = "date_created")
private Date dateCreated;
@PrePersist
public void setCreationDate() {
if (null == id) {
dateCreated = new Date();
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Warehouse getWarehouse() {
return warehouse;
}
public void setWarehouse(Warehouse warehouse) {
this.warehouse = warehouse;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
}
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.amethods;
public class ConfigParameter {
private int index;
private String name;
ConfigParameter() {}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "" + index + "," + name;
}
}
|
/*
* Copyright 2018 Gerald Curley
*
* 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.opsmatters.newrelic.api.model.insights;
import java.util.List;
import com.opsmatters.newrelic.api.util.ResourceList;
/**
* Adds lookup functions to a list of New Relic dashboards.
*
* @author Gerald Curley (opsmatters)
*/
public class DashboardList extends ResourceList<Dashboard>
{
/**
* Default constructor.
*/
public DashboardList()
{
}
/**
* Constructor that takes a list of dashboards.
* @param dashboards The dashboards for the list
*/
public DashboardList(List<Dashboard> dashboards)
{
add(dashboards);
}
}
|
/**
* Copyright 2012-2015 TIKAL-TECHNOLOGY
*
*Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package org.nekorp.workflow.desktop.view;
import java.awt.Color;
import org.nekorp.workflow.desktop.view.binding.Bindable;
import org.nekorp.workflow.desktop.view.binding.BindingManager;
import org.nekorp.workflow.desktop.view.binding.ReadOnlyBinding;
import org.nekorp.workflow.desktop.view.model.bitacora.BitacoraMetaData;
import org.nekorp.workflow.desktop.view.model.cobranza.CobranzaMetadata;
import org.nekorp.workflow.desktop.view.model.cobranza.CobranzaWarningLevel;
import org.nekorp.workflow.desktop.view.model.servicio.ServicioVB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
/**
* @author Nekorp
*/
@Component("servicioDatosGeneralesView")
public class ServicioDatosGeneralesView extends ApplicationView {
@Autowired
private BindingManager<Bindable> bindingManager;
@Autowired
@Qualifier(value="servicio")
private ServicioVB viewServicioModel;
@Autowired
private BitacoraMetaData bitacoraMetaData;
@Autowired
private CobranzaMetadata cobranzaMetadata;
@Override
public void setEditableStatus(boolean value) {
this.setVisible(value);
this.updateUI();
}
@Override
public void iniciaVista() {
initComponents();
bindComponents();
}
public void bindComponents() {
//bindings con el servicio
bindingManager.registerBind(viewServicioModel, "id",(Bindable)this.numeroServicio);
bindingManager.registerBind(viewServicioModel.getAuto(), "placas",(Bindable)this.placas);
//bindings con el cliente
bindingManager.registerBind(viewServicioModel.getCliente(), "nombre",(Bindable)this.nombreCliente);
//bindings con el metadata de la bitacora
bindingManager.registerBind(bitacoraMetaData, "fechaInicioServicio", (Bindable)this.inicioServicio);
bindingManager.registerBind(bitacoraMetaData, "fechaFinServicio", (Bindable)this.finServicio);
bindingManager.registerBind(bitacoraMetaData, "tiempoServicio", (Bindable)this.duracionServicio);
bindingManager.registerBind(bitacoraMetaData, "fechaEntrada", (Bindable)this.ingreso);
bindingManager.registerBind(bitacoraMetaData, "fechaSalidaAuto", (Bindable)this.salida);
bindingManager.registerBind(bitacoraMetaData, "tiempoEstadia", (Bindable)this.tiempo);
//bindings al metadata de cobranza cobranzaMetadata
bindingManager.registerBind(cobranzaMetadata, "saldo", (Bindable)this.saldo);
Bindable saldoDecoratorBind = new ReadOnlyBinding() {
@Override
public void notifyUpdate(Object origen, String property, Object value) {
CobranzaWarningLevel warningLevel = (CobranzaWarningLevel) value;
switch (warningLevel) {
case info:
saldo.setBackground(Color.GREEN);
saldo.setBorder(javax.swing.BorderFactory.createLineBorder(Color.GREEN, 4));
break;
case warn:
saldo.setBackground(Color.YELLOW);
saldo.setBorder(javax.swing.BorderFactory.createLineBorder(Color.YELLOW, 4));
break;
case urgent:
saldo.setBackground(Color.RED);
saldo.setBorder(javax.swing.BorderFactory.createLineBorder(Color.RED, 4));
break;
default:
saldo.setBackground(Color.GREEN);
saldo.setBorder(javax.swing.BorderFactory.createLineBorder(Color.GREEN, 4));
break;
}
}
};
bindingManager.registerBind(cobranzaMetadata.getStatus(), "warningLevel", saldoDecoratorBind);
}
@Override
public ViewValidIndicator getValidInidicator() {
return null;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
datosGenerales = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
numeroServicio = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJLabel();
jLabel1 = new javax.swing.JLabel();
nombreCliente = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel3 = new javax.swing.JLabel();
placas = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel4 = new javax.swing.JLabel();
inicioServicio = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel8 = new javax.swing.JLabel();
finServicio = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel9 = new javax.swing.JLabel();
duracionServicio = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel5 = new javax.swing.JLabel();
ingreso = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel7 = new javax.swing.JLabel();
salida = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel6 = new javax.swing.JLabel();
tiempo = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
jLabel10 = new javax.swing.JLabel();
saldo = new org.nekorp.workflow.desktop.view.binding.SimpleBindableJTextField();
setBackground(new java.awt.Color(255, 255, 255));
datosGenerales.setBackground(new java.awt.Color(51, 51, 51));
datosGenerales.setName(""); // NOI18N
jLabel2.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Servicio");
numeroServicio.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
numeroServicio.setForeground(new java.awt.Color(255, 255, 255));
numeroServicio.setText(" ");
jLabel1.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Nombre o razón social");
nombreCliente.setEditable(false);
nombreCliente.setBackground(new java.awt.Color(102, 102, 102));
nombreCliente.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
nombreCliente.setForeground(new java.awt.Color(255, 255, 255));
nombreCliente.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel3.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Placas");
placas.setEditable(false);
placas.setBackground(new java.awt.Color(102, 102, 102));
placas.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
placas.setForeground(new java.awt.Color(255, 255, 255));
placas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel4.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Inicio del servicio");
inicioServicio.setEditable(false);
inicioServicio.setBackground(new java.awt.Color(102, 102, 102));
inicioServicio.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
inicioServicio.setForeground(new java.awt.Color(255, 255, 255));
inicioServicio.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel8.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Fin del servicio");
finServicio.setEditable(false);
finServicio.setBackground(new java.awt.Color(102, 102, 102));
finServicio.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
finServicio.setForeground(new java.awt.Color(255, 255, 255));
finServicio.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel9.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("Duración del servicio");
duracionServicio.setEditable(false);
duracionServicio.setBackground(new java.awt.Color(102, 102, 102));
duracionServicio.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
duracionServicio.setForeground(new java.awt.Color(255, 255, 255));
duracionServicio.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel5.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Fecha de ingreso del auto");
ingreso.setEditable(false);
ingreso.setBackground(new java.awt.Color(102, 102, 102));
ingreso.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
ingreso.setForeground(new java.awt.Color(255, 255, 255));
ingreso.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel7.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Fecha de salida del auto");
salida.setEditable(false);
salida.setBackground(new java.awt.Color(102, 102, 102));
salida.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
salida.setForeground(new java.awt.Color(255, 255, 255));
salida.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel6.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Estadia del auto");
tiempo.setEditable(false);
tiempo.setBackground(new java.awt.Color(102, 102, 102));
tiempo.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
tiempo.setForeground(new java.awt.Color(255, 255, 255));
tiempo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
jLabel10.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("Saldo");
saldo.setEditable(false);
saldo.setBackground(new java.awt.Color(102, 102, 102));
saldo.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
saldo.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
saldo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102), 4));
javax.swing.GroupLayout datosGeneralesLayout = new javax.swing.GroupLayout(datosGenerales);
datosGenerales.setLayout(datosGeneralesLayout);
datosGeneralesLayout.setHorizontalGroup(
datosGeneralesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(datosGeneralesLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(datosGeneralesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nombreCliente)
.addComponent(placas)
.addComponent(inicioServicio)
.addComponent(finServicio)
.addComponent(duracionServicio)
.addComponent(ingreso)
.addComponent(salida)
.addComponent(tiempo)
.addComponent(saldo)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(datosGeneralesLayout.createSequentialGroup()
.addGroup(datosGeneralesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel8)
.addComponent(jLabel9)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel10)
.addComponent(jLabel1)
.addGroup(datosGeneralesLayout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numeroServicio, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(20, 20, 20))
);
datosGeneralesLayout.setVerticalGroup(
datosGeneralesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(datosGeneralesLayout.createSequentialGroup()
.addContainerGap()
.addGroup(datosGeneralesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(numeroServicio))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nombreCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(placas, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(inicioServicio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(finServicio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(duracionServicio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ingreso, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(salida, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tiempo, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(saldo, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(41, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(datosGenerales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(datosGenerales, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel datosGenerales;
private javax.swing.JTextField duracionServicio;
private javax.swing.JTextField finServicio;
private javax.swing.JTextField ingreso;
private javax.swing.JTextField inicioServicio;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JTextField nombreCliente;
private javax.swing.JLabel numeroServicio;
private javax.swing.JTextField placas;
private javax.swing.JTextField saldo;
private javax.swing.JTextField salida;
private javax.swing.JTextField tiempo;
// End of variables declaration//GEN-END:variables
}
|
package org.support.project.web.util;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import java.util.Map;
import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
/**
* Webアプリの一つのリクエストは1つのThreadに入る その一つのリクエスト内で何か情報を保持しておきたい場合に、 このクラスを利用する
*
* @author Koda
*
*/
@DI(instance = Instance.Singleton)
public class ThredUserPool {
private static final Log LOG = LogFactory.getLog(MethodHandles.lookup());
private Map<Thread, Map<String, Object>> infoMap;
public static ThredUserPool get() {
return Container.getComp(ThredUserPool.class);
}
public ThredUserPool() {
super();
infoMap = new HashMap<>();
}
public void setInfo(String key, Object info) {
if (info == null) {
return;
}
synchronized (infoMap) {
if (LOG.isTraceEnabled()) {
LOG.trace("set request infomation" + info.toString());
}
Thread t = Thread.currentThread();
if (!infoMap.containsKey(t)) {
infoMap.put(t, new HashMap<>());
}
}
}
public Object getInfo(String key) {
synchronized (infoMap) {
Thread t = Thread.currentThread();
if (infoMap.containsKey(t)) {
return infoMap.get(t).get(key);
}
return null;
}
}
public void clearInfo() {
synchronized (infoMap) {
if (LOG.isTraceEnabled()) {
LOG.trace("clear request infomation");
}
Thread t = Thread.currentThread();
if (infoMap.containsKey(t)) {
infoMap.remove(t);
}
}
}
}
|
/*
* Copyright 2017-2022 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.chimesdkidentity.model;
import javax.annotation.Generated;
/**
* <p>
* The client is permanently forbidden from making the request.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ForbiddenException extends com.amazonaws.services.chimesdkidentity.model.AmazonChimeSDKIdentityException {
private static final long serialVersionUID = 1L;
private String code;
/**
* Constructs a new ForbiddenException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public ForbiddenException(String message) {
super(message);
}
/**
* @param code
* @see ErrorCode
*/
@com.fasterxml.jackson.annotation.JsonProperty("Code")
public void setCode(String code) {
this.code = code;
}
/**
* @return
* @see ErrorCode
*/
@com.fasterxml.jackson.annotation.JsonProperty("Code")
public String getCode() {
return this.code;
}
/**
* @param code
* @return Returns a reference to this object so that method calls can be chained together.
* @see ErrorCode
*/
public ForbiddenException withCode(String code) {
setCode(code);
return this;
}
/**
* @param code
* @return Returns a reference to this object so that method calls can be chained together.
* @see ErrorCode
*/
public ForbiddenException withCode(ErrorCode code) {
this.code = code.toString();
return this;
}
}
|
package com.packtpub.fragmentcommunication;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MasterFragment extends ListFragment {
public interface OnMasterSelectedListener {
public void onItemSelected(String countryName);
}
private OnMasterSelectedListener mOnMasterSelectedListener=null;
public void setOnMasterSelectedListener(OnMasterSelectedListener listener) {
mOnMasterSelectedListener=listener;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String[] countries = new String[]{"China", "France",
"Germany", "India", "Russia", "United Kingdom",
"United States"};
ListAdapter countryAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
countries);
setListAdapter(countryAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View
view, int position, long id) {
if (mOnMasterSelectedListener != null) {
mOnMasterSelectedListener.onItemSelected(((
TextView) view).getText().toString());
}
}
});
}
}
|
/*
* The MIT License
*
* Copyright (c) 2017 aoju.org All rights reserved.
*
* 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 org.aoju.bus.core.utils;
/**
* @author Kimi Liu
* @version 5.2.5
* @since JDK 1.8+
*/
public class ByteUtils {
public static int bytesToVR(byte[] bytes, int off) {
return bytesToUShortBE(bytes, off);
}
public static int bytesToUShort(byte[] bytes, int off, boolean bigEndian) {
return bigEndian ? bytesToUShortBE(bytes, off)
: bytesToUShortLE(bytes, off);
}
public static int bytesToUShortBE(byte[] bytes, int off) {
return ((bytes[off] & 255) << 8) + (bytes[off + 1] & 255);
}
public static int bytesToUShortLE(byte[] bytes, int off) {
return ((bytes[off + 1] & 255) << 8) + (bytes[off] & 255);
}
public static int bytesToShort(byte[] bytes, int off, boolean bigEndian) {
return bigEndian ? bytesToShortBE(bytes, off)
: bytesToShortLE(bytes, off);
}
public static int bytesToShortBE(byte[] bytes, int off) {
return (bytes[off] << 8) + (bytes[off + 1] & 255);
}
public static int bytesToShortLE(byte[] bytes, int off) {
return (bytes[off + 1] << 8) + (bytes[off] & 255);
}
public static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian) {
if (bigEndian)
bytesToShortsBE(b, s, off, len);
else
bytesToShortsLE(b, s, off, len);
}
public static void bytesToShortsLE(byte[] b, short[] s, int off, int len) {
int boff = 0;
for (int j = 0; j < len; j++) {
int b0 = b[boff + 1];
int b1 = b[boff] & 0xff;
s[off + j] = (short) ((b0 << 8) | b1);
boff += 2;
}
}
public static void bytesToShortsBE(byte[] b, short[] s, int off, int len) {
int boff = 0;
for (int j = 0; j < len; j++) {
int b0 = b[boff];
int b1 = b[boff + 1] & 0xff;
s[off + j] = (short) ((b0 << 8) | b1);
boff += 2;
}
}
public static int bytesToInt(byte[] bytes, int off, boolean bigEndian) {
return bigEndian ? bytesToIntBE(bytes, off) : bytesToIntLE(bytes, off);
}
public static int bytesToIntBE(byte[] bytes, int off) {
return (bytes[off] << 24) + ((bytes[off + 1] & 255) << 16)
+ ((bytes[off + 2] & 255) << 8) + (bytes[off + 3] & 255);
}
public static int bytesToIntLE(byte[] bytes, int off) {
return (bytes[off + 3] << 24) + ((bytes[off + 2] & 255) << 16)
+ ((bytes[off + 1] & 255) << 8) + (bytes[off] & 255);
}
public static int bytesToTag(byte[] bytes, int off, boolean bigEndian) {
return bigEndian ? bytesToTagBE(bytes, off) : bytesToTagLE(bytes, off);
}
public static int bytesToTagBE(byte[] bytes, int off) {
return bytesToIntBE(bytes, off);
}
public static int bytesToTagLE(byte[] bytes, int off) {
return (bytes[off + 1] << 24) + ((bytes[off] & 255) << 16)
+ ((bytes[off + 3] & 255) << 8) + (bytes[off + 2] & 255);
}
public static float bytesToFloat(byte[] bytes, int off, boolean bigEndian) {
return bigEndian ? bytesToFloatBE(bytes, off)
: bytesToFloatLE(bytes, off);
}
public static float bytesToFloatBE(byte[] bytes, int off) {
return Float.intBitsToFloat(bytesToIntBE(bytes, off));
}
public static float bytesToFloatLE(byte[] bytes, int off) {
return Float.intBitsToFloat(bytesToIntLE(bytes, off));
}
public static long bytesToLong(byte[] bytes, int off, boolean bigEndian) {
return bigEndian ? bytesToLongBE(bytes, off)
: bytesToLongLE(bytes, off);
}
public static long bytesToLongBE(byte[] bytes, int off) {
return ((long) bytes[off] << 56)
+ ((long) (bytes[off + 1] & 255) << 48)
+ ((long) (bytes[off + 2] & 255) << 40)
+ ((long) (bytes[off + 3] & 255) << 32)
+ ((long) (bytes[off + 4] & 255) << 24)
+ ((bytes[off + 5] & 255) << 16)
+ ((bytes[off + 6] & 255) << 8)
+ (bytes[off + 7] & 255);
}
public static long bytesToLongLE(byte[] bytes, int off) {
return ((long) bytes[off + 7] << 56)
+ ((long) (bytes[off + 6] & 255) << 48)
+ ((long) (bytes[off + 5] & 255) << 40)
+ ((long) (bytes[off + 4] & 255) << 32)
+ ((long) (bytes[off + 3] & 255) << 24)
+ ((bytes[off + 2] & 255) << 16)
+ ((bytes[off + 1] & 255) << 8)
+ (bytes[off] & 255);
}
public static double bytesToDouble(byte[] bytes, int off, boolean bigEndian) {
return bigEndian ? bytesToDoubleBE(bytes, off)
: bytesToDoubleLE(bytes, off);
}
public static double bytesToDoubleBE(byte[] bytes, int off) {
return Double.longBitsToDouble(bytesToLongBE(bytes, off));
}
public static double bytesToDoubleLE(byte[] bytes, int off) {
return Double.longBitsToDouble(bytesToLongLE(bytes, off));
}
public static byte[] shortToBytes(int i, byte[] bytes, int off,
boolean bigEndian) {
return bigEndian ? shortToBytesBE(i, bytes, off)
: shortToBytesLE(i, bytes, off);
}
public static byte[] shortToBytesBE(int i, byte[] bytes, int off) {
bytes[off] = (byte) (i >> 8);
bytes[off + 1] = (byte) i;
return bytes;
}
public static byte[] shortToBytesLE(int i, byte[] bytes, int off) {
bytes[off + 1] = (byte) (i >> 8);
bytes[off] = (byte) i;
return bytes;
}
public static byte[] intToBytes(int i, byte[] bytes, int off,
boolean bigEndian) {
return bigEndian ? intToBytesBE(i, bytes, off)
: intToBytesLE(i, bytes, off);
}
public static byte[] intToBytesBE(int i, byte[] bytes, int off) {
bytes[off] = (byte) (i >> 24);
bytes[off + 1] = (byte) (i >> 16);
bytes[off + 2] = (byte) (i >> 8);
bytes[off + 3] = (byte) i;
return bytes;
}
public static byte[] intToBytesLE(int i, byte[] bytes, int off) {
bytes[off + 3] = (byte) (i >> 24);
bytes[off + 2] = (byte) (i >> 16);
bytes[off + 1] = (byte) (i >> 8);
bytes[off] = (byte) i;
return bytes;
}
public static byte[] tagToBytes(int i, byte[] bytes, int off,
boolean bigEndian) {
return bigEndian ? tagToBytesBE(i, bytes, off)
: tagToBytesLE(i, bytes, off);
}
public static byte[] tagToBytesBE(int i, byte[] bytes, int off) {
return intToBytesBE(i, bytes, off);
}
public static byte[] tagToBytesLE(int i, byte[] bytes, int off) {
bytes[off + 1] = (byte) (i >> 24);
bytes[off] = (byte) (i >> 16);
bytes[off + 3] = (byte) (i >> 8);
bytes[off + 2] = (byte) i;
return bytes;
}
public static byte[] floatToBytes(float f, byte[] bytes, int off,
boolean bigEndian) {
return bigEndian ? floatToBytesBE(f, bytes, off)
: floatToBytesLE(f, bytes, off);
}
public static byte[] floatToBytesBE(float f, byte[] bytes, int off) {
return intToBytesBE(Float.floatToIntBits(f), bytes, off);
}
public static byte[] floatToBytesLE(float f, byte[] bytes, int off) {
return intToBytesLE(Float.floatToIntBits(f), bytes, off);
}
public static byte[] doubleToBytes(double d, byte[] bytes, int off,
boolean bigEndian) {
return bigEndian ? doubleToBytesBE(d, bytes, off)
: doubleToBytesLE(d, bytes, off);
}
public static byte[] doubleToBytesBE(double d, byte[] bytes, int off) {
return longToBytesBE(Double.doubleToLongBits(d), bytes, off);
}
public static byte[] doubleToBytesLE(double d, byte[] bytes, int off) {
return longToBytesLE(Double.doubleToLongBits(d), bytes, off);
}
public static byte[] longToBytes(long l, byte[] bytes, int off,
boolean bigEndian) {
return bigEndian ? longToBytesBE(l, bytes, off)
: longToBytesLE(l, bytes, off);
}
public static byte[] longToBytesBE(long l, byte[] bytes, int off) {
bytes[off] = (byte) (l >> 56);
bytes[off + 1] = (byte) (l >> 48);
bytes[off + 2] = (byte) (l >> 40);
bytes[off + 3] = (byte) (l >> 32);
bytes[off + 4] = (byte) (l >> 24);
bytes[off + 5] = (byte) (l >> 16);
bytes[off + 6] = (byte) (l >> 8);
bytes[off + 7] = (byte) l;
return bytes;
}
public static byte[] longToBytesLE(long l, byte[] bytes, int off) {
bytes[off + 7] = (byte) (l >> 56);
bytes[off + 6] = (byte) (l >> 48);
bytes[off + 5] = (byte) (l >> 40);
bytes[off + 4] = (byte) (l >> 32);
bytes[off + 3] = (byte) (l >> 24);
bytes[off + 2] = (byte) (l >> 16);
bytes[off + 1] = (byte) (l >> 8);
bytes[off] = (byte) l;
return bytes;
}
public static byte[][] swapShorts(byte[][] bs) {
int carry = 0;
for (int i = 0; i < bs.length; i++) {
byte[] b = bs[i];
if (carry != 0)
swapLastFirst(bs[i - 1], b);
int len = b.length - carry;
swapShorts(b, carry, len & ~1);
carry = len & 1;
}
return bs;
}
public static byte[] swapShorts(byte[] b, int off, int len) {
checkLength(len, 2);
for (int i = off, n = off + len; i < n; i += 2)
swap(b, i, i + 1);
return b;
}
public static byte[] swapInts(byte[] b, int off, int len) {
checkLength(len, 4);
for (int i = off, n = off + len; i < n; i += 4) {
swap(b, i, i + 3);
swap(b, i + 1, i + 2);
}
return b;
}
public static byte[] swapLongs(byte[] b, int off, int len) {
checkLength(len, 8);
for (int i = off, n = off + len; i < n; i += 8) {
swap(b, i, i + 7);
swap(b, i + 1, i + 6);
swap(b, i + 2, i + 5);
swap(b, i + 3, i + 4);
}
return b;
}
private static void checkLength(int len, int numBytes) {
if (len < 0 || (len % numBytes) != 0)
throw new IllegalArgumentException("length: " + len);
}
private static void swap(byte[] bytes, int a, int b) {
byte t = bytes[a];
bytes[a] = bytes[b];
bytes[b] = t;
}
private static void swapLastFirst(byte[] b1, byte[] b2) {
int last = b1.length - 1;
byte t = b2[0];
b2[0] = b1[last];
b1[last] = t;
}
public static byte[] intsToBytesLE(int... values) {
byte[] ret = new byte[4 * values.length];
for (int i = 0; i < values.length; i++) {
intToBytesLE(values[i], ret, 4 * i);
}
return ret;
}
}
|
/*
* 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.solr.analytics.value;
import java.time.Instant;
import java.util.Date;
import java.util.function.Consumer;
/**
* A multi-valued analytics value that can be represented as a date.
* <p>
* The back-end production of the value can change inbetween calls to {@link #streamDates},
* resulting in different values on each call.
* <p>
* NOTE: Most date expressions work with the {@code long} representation of the date, so that less
* objects need to be created during execution.
*/
public interface DateValueStream extends LongValueStream {
/**
* Stream the date representations of all current values, if any exist.
*
* @param cons The consumer to accept the values
*/
void streamDates(Consumer<Date> cons);
/**
* An interface that represents all of the types a {@link DateValueStream} should be able to cast to.
*/
public static interface CastingDateValueStream extends DateValueStream, LongValueStream, StringValueStream {}
/**
* An abstract base for {@link CastingDateValueStream} that automatically casts to all types if {@link #streamLongs} is implemented.
*/
public static abstract class AbstractDateValueStream implements CastingDateValueStream {
@Override
public void streamDates(Consumer<Date> cons) {
streamLongs((long val) -> cons.accept(new Date(val)));
}
@Override
public void streamStrings(Consumer<String> cons) {
streamLongs((long val) -> cons.accept(Instant.ofEpochMilli(val).toString()));
}
@Override
public void streamObjects(Consumer<Object> cons) {
streamLongs((long val) -> cons.accept(new Date(val)));
}
}
}
|
package org.mathiasgarnier.wintime.sktranslate;
public class CanHold {
}
|
/*
* Copyright 2012-2014 Netherlands eScience Center.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at the following location:
*
* 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.
*
* For the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vbrowser.vrs.webrs;
import nl.esciencecenter.vbrowser.vrs.VRS;
import nl.esciencecenter.vbrowser.vrs.VRSContext;
import nl.esciencecenter.vbrowser.vrs.VResourceSystemFactory;
import nl.esciencecenter.vbrowser.vrs.exceptions.VrsException;
import nl.esciencecenter.vbrowser.vrs.registry.ResourceConfigInfo;
import nl.esciencecenter.vbrowser.vrs.vrl.VRL;
public class WebRSFactory implements VResourceSystemFactory {
public static String webSchemes[] = { VRS.HTTP_SCHEME, VRS.HTTPS_SCHEME };
@Override
public String[] getSchemes() {
return webSchemes;
}
@Override
public String createResourceSystemId(VRL vrl) {
int port = vrl.getPort();
if (port <= 0) {
port = VRS.getDefaultPort(vrl.getScheme());
}
return vrl.getScheme() + ":" + vrl.getHostname() + ":" + port;
}
@Override
public ResourceConfigInfo updateResourceInfo(VRSContext context, ResourceConfigInfo info, VRL vrl) {
return info;
}
@Override
public nl.esciencecenter.vbrowser.vrs.VResourceSystem createResourceSystemFor(VRSContext context,
ResourceConfigInfo info, VRL vrl) throws VrsException {
return new WebResourceSystem(context, info);
}
}
|
package com.dandelion.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* 第三方配置信息
*
* @author jiekechoo
*
*/
@Entity
public class ThirdParty {
@Id
private String config;
private String value;
public String getConfig() {
return config;
}
public void setConfig(String config) {
this.config = config;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void createConfig(String config, String value) {
this.config = config;
this.value = value;
}
}
|
/*
* Copyright 2012-2017 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.kms.model.transform;
import java.io.ByteArrayInputStream;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.kms.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.json.*;
/**
* DisableKeyRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DisableKeyRequestMarshaller implements Marshaller<Request<DisableKeyRequest>, DisableKeyRequest> {
private final SdkJsonMarshallerFactory protocolFactory;
public DisableKeyRequestMarshaller(SdkJsonMarshallerFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DisableKeyRequest> marshall(DisableKeyRequest disableKeyRequest) {
if (disableKeyRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DisableKeyRequest> request = new DefaultRequest<DisableKeyRequest>(disableKeyRequest, "AWSKMS");
request.addHeader("X-Amz-Target", "TrentService.DisableKey");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = protocolFactory.createGenerator();
jsonGenerator.writeStartObject();
if (disableKeyRequest.getKeyId() != null) {
jsonGenerator.writeFieldName("KeyId").writeValue(disableKeyRequest.getKeyId());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length", Integer.toString(content.length));
request.addHeader("Content-Type", protocolFactory.getContentType());
} catch (Throwable t) {
throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.