hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
ad215105eec2955cc6bce3f77688dacb94d27b61 | 2,527 | package automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class CodilitySteps {
private final WebDriver driver;
@FindBy(id = "email-input")
private WebElement emailField;
@FindBy(id = "password-input")
private WebElement passwordField;
@FindBy(id = "login-button")
private WebElement loginButton;
public CodilitySteps(WebDriver commonDriver) {
driver = commonDriver;
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
PageFactory.initElements(driver, this);
driver.manage().window().maximize();
}
public void land() throws Throwable
{
driver.get("https://codility-frontend-prod.s3.amazonaws.com/media/task_static/qa_login_page/9a83bda125cd7398f9f482a3d6d45ea4/static/attachments/reference_page.html");
Thread.sleep(500);
}
public void login(String email, String password) throws Throwable
{
emailField.clear();
if(email != null)
{
emailField.sendKeys(email);
}
passwordField.clear();
if(password != null)
{
passwordField.sendKeys(password);
}
loginButton.click();
Thread.sleep(500);
}
public void textVerify(String loginType, String text)
{
WebElement theMessage;
switch(loginType)
{
case "successful":
theMessage = driver.findElement(By.cssSelector(".message.success"));
assertEquals("the messages don't match", theMessage.getText(), text);
break;
case "incorrect":
theMessage = driver.findElement(By.cssSelector(".message.error"));
assertEquals("the messages don't match", theMessage.getText(), text);
break;
case "invalid":
theMessage = driver.findElement(By.cssSelector(".validation.error"));
assertEquals("the messages don't match", theMessage.getText(), text);
break;
}
}
public void verifyElementsDisplayed()
{
assertTrue(emailField.isDisplayed());
assertTrue(passwordField.isDisplayed());
assertTrue(loginButton.isDisplayed());
assertTrue(loginButton.isEnabled());
}
}
| 31.5875 | 174 | 0.634745 |
db8c86cc7e5a552889bd39e3b0f3f6a7675a4f4b | 4,189 | package examples;
import java.util.Arrays;
import java.util.List;
import com.groupdocs.cloud.parser.api.StorageApi;
import com.groupdocs.cloud.parser.api.TemplateApi;
import com.groupdocs.cloud.parser.model.CreateTemplateOptions;
import com.groupdocs.cloud.parser.model.DetectorParameters;
import com.groupdocs.cloud.parser.model.Field;
import com.groupdocs.cloud.parser.model.FieldPosition;
import com.groupdocs.cloud.parser.model.Point;
import com.groupdocs.cloud.parser.model.Rectangle;
import com.groupdocs.cloud.parser.model.Size;
import com.groupdocs.cloud.parser.model.Table;
import com.groupdocs.cloud.parser.model.Template;
import com.groupdocs.cloud.parser.model.requests.CreateTemplateRequest;
import com.groupdocs.cloud.parser.model.requests.ObjectExistsRequest;
import examples.Common;
public class TemplateUtils{
public static void CreateIfNotExist(String path) {
StorageApi storageApi = new StorageApi(Common.GetConfiguration());
TemplateApi templateApi = new TemplateApi(Common.GetConfiguration());
try {
ObjectExistsRequest request = new ObjectExistsRequest(path,Common.MyStorage, null);
if(storageApi.objectExists(request).getExists()) {
return;
}
CreateTemplateOptions options = new CreateTemplateOptions();
Template template = GetTemplate();
options.setTemplate(template);
options.setStorageName(Common.MyStorage);
options.setTemplatePath(path);
CreateTemplateRequest createRequest = new CreateTemplateRequest(options);
templateApi.createTemplate(createRequest);
}catch (Exception e) {
System.err.println("Exception while calling TemplateApi:");
e.printStackTrace();
}
}
public static Template GetTemplate() {
Field field1 = new Field();
field1.setFieldName("Address");
FieldPosition fieldPosition1 = new FieldPosition();
fieldPosition1.setFieldPositionType("Regex");
fieldPosition1.setRegex("Company address:");
field1.setFieldPosition(fieldPosition1);
Field field2 = new Field();
field2.setFieldName("CompanyAddress");
FieldPosition fieldPosition2 = new FieldPosition();
fieldPosition2.setFieldPositionType("Linked");
fieldPosition2.setLinkedFieldName("ADDRESS");
fieldPosition2.setIsRightLinked(true);
Size size2 = new Size();
size2.setWidth(100d);
size2.setHeight(10d);
fieldPosition2.setSearchArea(size2);
fieldPosition2.setAutoScale(true);
field2.setFieldPosition(fieldPosition2);
Field field3 = new Field();
field3.setFieldName("Company");
FieldPosition fieldPosition3 = new FieldPosition();
fieldPosition3.setFieldPositionType("Regex");
fieldPosition3.setRegex("Company name:");
field3.setFieldPosition(fieldPosition3);
Field field4 = new Field();
field4.setFieldName("CompanyName");
FieldPosition fieldPosition4 = new FieldPosition();
fieldPosition4.setFieldPositionType("Linked");
fieldPosition4.setLinkedFieldName("Company");
fieldPosition4.setIsRightLinked(true);
Size size4 = new Size();
size4.setWidth(100d);
size4.setHeight(10d);
fieldPosition4.setSearchArea(size4);
fieldPosition4.setAutoScale(true);
field4.setFieldPosition(fieldPosition4);
Table table = new Table();
table.setTableName("Companies");
DetectorParameters detectorparams = new DetectorParameters();
Rectangle rect = new Rectangle();
Size size = new Size();
size.setHeight(60d);
size.setWidth(480d);
Point position = new Point();
position.setX(77d);
position.setY(279d);
rect.setSize(size);
rect.setPosition(position);
detectorparams.setRectangle(rect);
table.setDetectorParameters(detectorparams);
List<Field> fields = Arrays.asList(new Field[] { field1, field2, field3, field4 });
List<Table> tables = Arrays.asList(new Table[] { table });
Template template = new Template();
template.setFields(fields);
template.setTables(tables);
return template;
}
} | 37.070796 | 91 | 0.709 |
71d3c5913546a05d98241066633933d0b6b6f8ed | 6,363 | /*
* Copyright (c) 2017 Zhang Hai <[email protected]>
* All Rights Reserved.
*/
package me.zhanghai.android.douya.util;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Pair;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Type adapter for Android Bundle. It only stores the actual properties set in the bundle
*
* @author Inderjeet Singh
* @author Zhang Hai
*/
public class BundleTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
if (!Bundle.class.isAssignableFrom(type.getRawType())) {
return null;
}
return (TypeAdapter<T>) new TypeAdapter<Bundle>() {
@Override
public void write(JsonWriter out, Bundle bundle) throws IOException {
if (bundle == null) {
out.nullValue();
return;
}
out.beginObject();
for (String key : bundle.keySet()) {
out.name(key);
Object value = bundle.get(key);
if (value == null) {
out.nullValue();
} else {
gson.toJson(value, value.getClass(), out);
}
}
out.endObject();
}
@Override
public Bundle read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
case BEGIN_OBJECT:
return toBundle(readObject(in));
default:
throw new IOException("Expecting object: " + in.getPath());
}
}
private Bundle toBundle(List<Pair<String, Object>> values) throws IOException {
Bundle bundle = new Bundle();
for (Pair<String, Object> entry : values) {
String key = entry.first;
Object value = entry.second;
if (value instanceof String) {
bundle.putString(key, (String) value);
} else if (value instanceof Boolean) {
bundle.putBoolean(key, (Boolean) value);
} else if (value instanceof Integer) {
bundle.putInt(key, (Integer) value);
} else if (value instanceof Long) {
bundle.putLong(key, (Long) value);
} else if (value instanceof Double) {
bundle.putDouble(key, (Double) value);
} else if (value instanceof Parcelable) {
bundle.putParcelable(key, (Parcelable) value);
} else if (value instanceof List) {
List<Pair<String, Object>> objectValues =
(List<Pair<String, Object>>) value;
Bundle subBundle = toBundle(objectValues);
bundle.putParcelable(key, subBundle);
} else {
throw new IOException("Unparcelable key, value: " + key + ", "+ value);
}
}
return bundle;
}
private List<Pair<String, Object>> readObject(JsonReader in) throws IOException {
List<Pair<String, Object>> object = new ArrayList<>();
in.beginObject();
while (in.peek() != JsonToken.END_OBJECT) {
switch (in.peek()) {
case NAME:
String name = in.nextName();
Object value = readValue(in);
object.add(new Pair<>(name, value));
break;
case END_OBJECT:
break;
default:
throw new IOException("Expecting object: " + in.getPath());
}
}
in.endObject();
return object;
}
private Object readValue(JsonReader in) throws IOException {
switch (in.peek()) {
case BEGIN_ARRAY:
return readArray(in);
case BEGIN_OBJECT:
return readObject(in);
case BOOLEAN:
return in.nextBoolean();
case NULL:
in.nextNull();
return null;
case NUMBER:
return readNumber(in);
case STRING:
return in.nextString();
default:
throw new IOException("Expecting value: " + in.getPath());
}
}
private Object readNumber(JsonReader in) throws IOException {
double doubleValue = in.nextDouble();
if (doubleValue - Math.ceil(doubleValue) == 0) {
long longValue = (long) doubleValue;
if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
return (int) longValue;
}
return longValue;
}
return doubleValue;
}
private List<Object> readArray(JsonReader in) throws IOException {
List<Object> list = new ArrayList<>();
in.beginArray();
while (in.peek() != JsonToken.END_ARRAY) {
Object element = readValue(in);
list.add(element);
}
in.endArray();
return list;
}
};
}
}
| 37.875 | 95 | 0.467704 |
e5197f4f29049e28ae3e982bcb5f71fe5ba283ab | 191 | package com.github.vicianm.stickyviewpager.demo.validation;
import java.util.Collection;
public interface ValidationCallback {
void validated(Collection<ValidationResult> results);
}
| 19.1 | 59 | 0.811518 |
75e4e45d11c17de480c54db6d17d304ceb6816f4 | 1,506 | package com.backend.carrental.dto;
import com.backend.carrental.domain.Car;
import com.backend.carrental.domain.FileDB;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.HashSet;
import java.util.Set;
@Setter
@Getter
@NoArgsConstructor
public class CarDTO {
private Long id;
private String model;
private Integer doors;
private Integer seats;
private Integer luggage;
private String transmission;
private Boolean airConditioning;
private Integer age;
private Double pricePerHour;
private String fuelType;
private Set<String> image;
private Boolean builtIn;
public CarDTO(Car car) {
this.id = car.getId();
this.model = car.getModel();
this.doors = car.getDoors();
this.seats = car.getSeats();
this.luggage = car.getLuggage();
this.transmission = car.getTransmission();
this.airConditioning = car.getAirConditioning();
this.age = car.getAge();
this.pricePerHour = car.getPricePerHour();
this.fuelType = car.getFuelType();
this.image = getImageId(car.getImage());
this.builtIn = car.getBuiltIn();
}
public Set<String> getImageId(Set<FileDB> images) {
Set<String> img = new HashSet<>();
FileDB[] fileDB = images.toArray(new FileDB[images.size()]);
for (int i = 0; i < images.size(); i++) {
img.add(fileDB[i].getId());
}
return img;
}
}
| 22.818182 | 68 | 0.644754 |
a2d57a0841b384013dc24b5df6a6915c525bf7cc | 420 | package cn.dustlight.datacenter.elasticsearch;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "dustlight.datacenter.elasticsearch")
public class DatacenterElasticsearchProperties {
private String formPrefix = "datacenter.form";
private String recordPrefix = "datacenter.form_record";
}
| 28 | 75 | 0.821429 |
afad55b4ae7a89abda1705abe73fed2bdd02f97f | 1,083 | package com.android_mvc.framework.ui.view;
import java.util.HashMap;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Buttonのラッパークラス。
* @author id:language_and_engineering
*
*/
public class MButton extends Button implements IFWView
{
public MButton(Context context) {
super(context);
}
// パラメータ保持
HashMap<String, Object> view_params = new HashMap<String, Object>();
@Override
public Object getViewParam(String key) {
return view_params.get(key);
}
@Override
public void setViewParam(String key, Object val) {
view_params.put(key, val);
}
// 以下は属性操作
public MButton text( String s )
{
setText(s);
return this;
}
public MButton click(OnClickListener l) {
setOnClickListener(l);
return this;
}
public MButton widthFillParent() {
setViewParam("layout_width", ViewGroup.LayoutParams.FILL_PARENT );
return this;
}
}
| 18.355932 | 75 | 0.614035 |
86ca894dfc601b17790eb1edc3a70c677dab9545 | 3,385 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|log4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|log4j
operator|.
name|PatternLayout
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_class
DECL|class|TestContainerLogAppender
specifier|public
class|class
name|TestContainerLogAppender
block|{
annotation|@
name|Test
DECL|method|testAppendInClose ()
specifier|public
name|void
name|testAppendInClose
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|ContainerLogAppender
name|claAppender
init|=
operator|new
name|ContainerLogAppender
argument_list|()
decl_stmt|;
name|claAppender
operator|.
name|setName
argument_list|(
literal|"testCLA"
argument_list|)
expr_stmt|;
name|claAppender
operator|.
name|setLayout
argument_list|(
operator|new
name|PatternLayout
argument_list|(
literal|"%-5p [%t]: %m%n"
argument_list|)
argument_list|)
expr_stmt|;
name|claAppender
operator|.
name|setContainerLogDir
argument_list|(
literal|"target/testAppendInClose/logDir"
argument_list|)
expr_stmt|;
name|claAppender
operator|.
name|setContainerLogFile
argument_list|(
literal|"syslog"
argument_list|)
expr_stmt|;
name|claAppender
operator|.
name|setTotalLogFileSize
argument_list|(
literal|1000
argument_list|)
expr_stmt|;
name|claAppender
operator|.
name|activateOptions
argument_list|()
expr_stmt|;
specifier|final
name|Logger
name|claLog
init|=
name|Logger
operator|.
name|getLogger
argument_list|(
literal|"testAppendInClose-catergory"
argument_list|)
decl_stmt|;
name|claLog
operator|.
name|setAdditivity
argument_list|(
literal|false
argument_list|)
expr_stmt|;
name|claLog
operator|.
name|addAppender
argument_list|(
name|claAppender
argument_list|)
expr_stmt|;
name|claLog
operator|.
name|info
argument_list|(
operator|new
name|Object
argument_list|()
block|{
specifier|public
name|String
name|toString
parameter_list|()
block|{
name|claLog
operator|.
name|info
argument_list|(
literal|"message1"
argument_list|)
expr_stmt|;
return|return
literal|"return message1"
return|;
block|}
block|}
argument_list|)
expr_stmt|;
name|claAppender
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
block|}
end_class
end_unit
| 18.396739 | 814 | 0.799705 |
f6f7efecd921fdca1828106be69ae1a5b149f0eb | 2,718 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 外部合作机构数据推送
*
* @author auto create
* @since 1.0, 2017-05-11 14:09:08
*/
public class MybankCreditLoanapplyDataUploadModel extends AlipayObject {
private static final long serialVersionUID = 4576699572394455325L;
/**
* 业务单编号。在申请场景下,就是申请单编号,唯一标识一笔贷款授信申请,获取方式:前提,和网商对接业务消息,biz_no是申请成功消息applicationEvent中的applicationCode字段,必填项。在其他场景,比如订单交易场景下,就是订单号。
*/
@ApiField("biz_no")
private String bizNo;
/**
* 业务场景码。根据不同的合作模式,业务场景码不同,标识这笔数据是在哪个业务场景下产生的,由网商银行系统生成。目前只有两种场景,1:申请场景,2:交易订单场景。以后可根据业务发展增加场景码。默认为申请场景。
*/
@ApiField("biz_type")
private String bizType;
/**
* 数据类型。收单行业:PARTNER_SETTLE_BILL_DATA;货运行业:PARTNER_TRANSPORT_DATA。该值网商系统会校验,请按约定填写。必填项。
*/
@ApiField("category")
private String category;
/**
* json格式的数据。根据合作协议约定的数据内容,把数据组装成json格式。参考isv数据接入文档,须保证数据通过校验。必填项。
*/
@ApiField("data")
private String data;
/**
* 数据提供方的标识,一般取合作机构的英文名或中文拼音。例如,如果合作机构是滴滴,则该值就可以填didi。该值网商系统不校验。必填项。
*/
@ApiField("data_provider")
private String dataProvider;
/**
* 贷款申请人的唯一标识,个人客户一般为身份证号码或者支付宝ID,公司客户为工商注册号。全局唯一,用来唯一标识一个客户。如果身份证号包含字母,则字母必须大写。必填项。客户身份证号码可以从网商银行发送给机构的授信申请消息中获取,也可以是客户在机构注册时登记的信息。
*/
@ApiField("entity_code")
private String entityCode;
/**
* 数据所属的实体名称,一般为客户姓名或者公司名,作为客户的标识,不唯一,用来做申请单的校验。必填项。客户姓名可以从网商银行发送给机构的授信申请消息中获取,也可以是客户在机构注册时登记的信息。
*/
@ApiField("entity_name")
private String entityName;
/**
* 客户的身份类型,由具体的合作场景决定。当个人客户以身份证为标识时是PERSON,企业是COMPAY。如果以会员ID标识客户,则支付宝会员填ALIPAY,网商银行会员填MYBANK。非必填项。
*/
@ApiField("entity_type")
private String entityType;
public String getBizNo() {
return this.bizNo;
}
public void setBizNo(String bizNo) {
this.bizNo = bizNo;
}
public String getBizType() {
return this.bizType;
}
public void setBizType(String bizType) {
this.bizType = bizType;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public String getData() {
return this.data;
}
public void setData(String data) {
this.data = data;
}
public String getDataProvider() {
return this.dataProvider;
}
public void setDataProvider(String dataProvider) {
this.dataProvider = dataProvider;
}
public String getEntityCode() {
return this.entityCode;
}
public void setEntityCode(String entityCode) {
this.entityCode = entityCode;
}
public String getEntityName() {
return this.entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public String getEntityType() {
return this.entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
}
| 22.46281 | 133 | 0.750552 |
a1936d78e7ed25d5fce6e1e04218bc270d29b067 | 6,097 | package no.uio.ifi.vizpub.peersim.pastry;
import java.math.BigInteger;
//__________________________________________________________________________________________________
/**
* Some utility and mathematical function to work with numbers and strings.
* <p>Title: MSPASTRY</p>
*
* <p>Description: MsPastry implementation for PeerSim</p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: The Pastry Group</p>
*
* @author Elisa Bisoffi, Manuel Cortella
* @version 1.0
*/
public class Util {
//______________________________________________________________________________________________
/**
* Given two numbers, returns the length of the common prefix, i.e. how
* many digits (in the given base) have in common from the leftmost side of
* the number
* @param b1 BigInteger
* @param b2 BigInteger
* @return int
*/
public static final int prefixLen(BigInteger b1, BigInteger b2) {
String s1 = Util.put0(b1);
String s2 = Util.put0(b2);
int i = 0;
for(i = 0; i<s1.length(); i++) {
if (s1.charAt(i)!=s2.charAt(i))
return i;
}
return i;
}
//______________________________________________________________________________________________
/**
* return true if b (normalized) starts with c
* @param b BigInteger
* @param c char
* @return boolean
*/
public static final boolean startsWith(BigInteger b, char c) {
String s1 = put0(b);
return (s1.charAt(0)==c);
}
//______________________________________________________________________________________________
/**
* return the distance between two number, that is |a-b|.
* no checking is done.
* @param a BigInteger
* @param b BigInteger
* @return BigInteger
*/
public static final BigInteger distance(BigInteger a, BigInteger b) {
return a.subtract(b).abs();
}
//______________________________________________________________________________________________
/**
* given a point (center), returns true if the second parameter (near) has less distance from
* the center respect with the 3rd point (far)
* @param center BigInteger
* @param near BigInteger
* @param far BigInteger
* @return boolean
*/
public static final boolean nearer(BigInteger center, BigInteger near, BigInteger far) {
return distance(center,near) .compareTo( distance(center,far) ) < 0;
}
//______________________________________________________________________________________________
/**
* Given b, normalize it and check if char c is at specified position
* @param b BigInteger
* @param position int
* @param c char
* @return boolean
*/
public static final boolean hasDigitAt(BigInteger b, int position, char c) {
String s1 = Util.put0(b);
return (s1.charAt(position)==c);
}
//______________________________________________________________________________________________
/**
* max between a and b
* @param a int
* @param b int
* @return int
*/
public static final int max(int a, int b) {
return a>b?a:b;
}
//______________________________________________________________________________________________
/**
* min between a and b
* @param a int
* @param b int
* @return int
*/
public static final int min(int a, int b) {
return a<b?a:b;
}
//______________________________________________________________________________________________
/**
* convert a BigInteger into a String, by considering the current BASE, and by leading all
* needed non-significative zeroes in order to reach the canonical length of a nodeid
* @param b BigInteger
* @return String
*/
public static final String put0(BigInteger b) {
if (b==null) return null;
String s = b.toString(MSPastryCommonConfig.BASE).toLowerCase();
while (s.length() < MSPastryCommonConfig.DIGITS ) s = "0" + s;
return s;
}
//______________________________________________________________________________________________
public static final char[] DIGITS = new char[] {'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* convert a cipher in the equivalent int value '0'-->0, ... 'f' --> 15
* @param c char
* @return int
*/
public static final int charToIndex(char c) {
switch (c) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A': return 10;
case 'a': return 10;
case 'B': return 11;
case 'b': return 11;
case 'C': return 12;
case 'c': return 12;
case 'D': return 13;
case 'd': return 13;
case 'E': return 14;
case 'F': return 15;
case 'e': return 14;
case 'f': return 15;
}
return 0;
}
//_____________________________________________________________________________________________
/**
* 2^i
* @param i int i must be a non-negative number
* @return int 2^i
*/
public static final int pow2(int i) {
if (i<0) return 0;
int result = 1;
for (int k = 0; k < i; k++)
result *= 2;
return result;
}
//_____________________________________________________________________________________________
} // End of class
//______________________________________________________________________________________________
| 31.921466 | 101 | 0.609316 |
6bfb4c462970a034a2ceac3ea1c09adc2ac9fd35 | 2,360 | package com.github.annasajkh;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import java.util.ArrayList;
import java.util.List;
public class Game extends ApplicationAdapter
{
static ShapeRenderer shapeRenderer;
static List<Pillar> pillars;
static int index = 0;
static int pillarCount = 600;
static float different;
public static Pillar getSmallest(List<Pillar> pillars, int index)
{
Pillar smallest = pillars.get(index);
for (int i = index; i < pillarCount; i++)
{
if (pillars.get(i).value < smallest.value)
{
smallest = pillars.get(i);
}
}
return smallest;
}
public static void shuffling(Pillar a, Pillar b)
{
Pillar tempB = b.copy();
pillars.set(pillars.indexOf(b), a);
pillars.set(pillars.indexOf(a), tempB);
}
@Override
public void create()
{
shapeRenderer = new ShapeRenderer();
pillars = new ArrayList<>();
different = Gdx.graphics.getWidth() / (float) pillarCount;
for (int i = 0; i < pillarCount; i++)
{
pillars.add(new Pillar(i + 1, different * i, different));
}
for (int i = 0; i < 5000; i++)
{
shuffling(pillars.get(MathUtils.random(pillarCount - 1)), pillars.get(MathUtils.random(pillarCount - 1)));
}
}
@Override
public void render()
{
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (index < pillarCount)
{
Pillar smallest = getSmallest(pillars, index);
pillars.remove(smallest);
pillars.add(0, smallest);
index++;
}
for (int i = 0; i < pillarCount; i++)
{
pillars.get(i).positionX = i * different;
}
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
for (Pillar pillar : pillars)
{
pillar.render(shapeRenderer, Color.WHITE);
}
shapeRenderer.end();
}
@Override
public void dispose()
{
shapeRenderer.dispose();
}
}
| 26.818182 | 118 | 0.583898 |
1cbf7955697b6a00277ddb53694ca2278dbc644a | 6,193 | /***********************************************************************
* Copyright (c) 2000-2004 The Apache Software Foundation. *
* 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. *
***********************************************************************/
package org.apache.james.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* A utility class to allow creation of RFC822 date strings from Dates
* and dates from RFC822 strings<br>
* It provides for conversion between timezones,
* And easy manipulation of RFC822 dates<br>
* example - current timestamp: String nowdate = new RFC822Date().toString()<br>
* example - convert into java.util.Date: Date usedate = new RFC822Date("3 Oct 2001 08:32:44 -0000").getDate()<br>
* example - convert to timezone: String yourdate = new RFC822Date("3 Oct 2001 08:32:44 -0000", "GMT+02:00").toString()<br>
* example - convert to local timezone: String mydate = new RFC822Date("3 Oct 2001 08:32:44 -0000").toString()<br>
*
* @deprecated Use java.util.Date in combination with org.apache.james.util.RFC822DateFormat.
*/
public class RFC822Date {
private static SimpleDateFormat df;
private static SimpleDateFormat dx;
private static SimpleDateFormat dy;
private static SimpleDateFormat dz;
private Date d;
private RFC822DateFormat rfc822Format = new RFC822DateFormat();
static {
df = new SimpleDateFormat("EE, d MMM yyyy HH:mm:ss", Locale.US);
dx = new SimpleDateFormat("EE, d MMM yyyy HH:mm:ss zzzzz", Locale.US);
dy = new SimpleDateFormat("EE d MMM yyyy HH:mm:ss zzzzz", Locale.US);
dz = new SimpleDateFormat("d MMM yyyy HH:mm:ss zzzzz", Locale.US);
}
/**
* creates a current timestamp
* using this machines system timezone<br>
*
*/
public RFC822Date(){
d = new Date();
}
/**
* creates object using date supplied
* and this machines system timezone<br>
* @param da java.util.Date, A date object
*/
public RFC822Date(Date da) {
d = da;
}
/**
* creates object using date supplied
* and the timezone string supplied<br>
* useTZ can be either an abbreviation such as "PST",
* a full name such as "America/Los_Angeles",<br>
* or a custom ID such as "GMT-8:00".<br>
* Note that this is dependant on java.util.TimeZone<br>
* Note that the support of abbreviations is for
* JDK 1.1.x compatibility only and full names should be used.<br>
* @param da java.util.Date, a date object
* @param useTZ java.lang.Sting, a timezone string such as "America/Los_Angeles" or "GMT+02:00"
*/
public RFC822Date(Date da, String useTZ){
d = da;
}
/**
* creates object from
* RFC822 date string supplied
* and the system default time zone <br>
* In practice it converts RFC822 date string to the local timezone<br>
* @param rfcdate java.lang.String - date in RFC822 format "3 Oct 2001 08:32:44 -0000"
*/
public RFC822Date(String rfcdate) {
setDate(rfcdate);
}
/**
* creates object from
* RFC822 date string supplied
* using the supplied time zone string<br>
* @param rfcdate java.lang.String - date in RFC822 format
* @param useTZ java.lang.String - timezone string *doesn't support Z style or UT*
*/
public RFC822Date(String rfcdate, String useTZ) {
setDate(rfcdate);
setTimeZone(useTZ);
}
public void setDate(Date da){
d = da;
}
/**
* The following styles of rfc date strings can be parsed<br>
* Wed, 3 Oct 2001 06:42:27 GMT+02:10<br>
* Wed 3 Oct 2001 06:42:27 PST <br>
* 3 October 2001 06:42:27 +0100 <br>
* the military style timezones, ZM, ZA, etc cannot (yet) <br>
* @param rfcdate java.lang.String - date in RFC822 format
*/
public void setDate(String rfcdate) {
try {
synchronized (dx) {
d= dx.parse(rfcdate);
}
} catch(ParseException e) {
try {
synchronized (dz) {
d= dz.parse(rfcdate);
}
} catch(ParseException f) {
try {
synchronized (dy) {
d = dy.parse(rfcdate);
}
} catch(ParseException g) {
d = new Date();
}
}
}
}
public void setTimeZone(TimeZone useTZ) {
rfc822Format.setTimeZone(useTZ);
}
public void setTimeZone(String useTZ) {
setTimeZone(TimeZone.getTimeZone(useTZ));
}
/**
* returns the java.util.Date object this RFC822Date represents.
* @return java.util.Date - the java.util.Date object this RFC822Date represents.
*/
public Date getDate() {
return d;
}
/**
* returns the date as a string formated for RFC822 compliance
* ,accounting for timezone and daylight saving.
* @return java.lang.String - date as a string formated for RFC822 compliance
*
*/
public String toString() {
return rfc822Format.format(d);
}
}
| 36.005814 | 123 | 0.574843 |
db0ebff8ba4e698315cde9dd203c38759541cee5 | 5,397 | package org.adempiere.webui.apps.form;
import java.util.Vector;
import java.util.logging.Level;
import org.adempiere.webui.apps.AEnv;
import org.adempiere.webui.component.Checkbox;
import org.adempiere.webui.component.Grid;
import org.adempiere.webui.component.GridFactory;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.Row;
import org.adempiere.webui.component.Rows;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WSearchEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.compiere.grid.CreateFromBBMPlan;
import org.compiere.model.GridTab;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.util.CLogger;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Center;
import org.zkoss.zul.Space;
import org.zkoss.zul.Vlayout;
public class WCreateFromBBMPlan extends CreateFromBBMPlan implements EventListener<Event>, ValueChangeListener{
public WCreateFromBBMPlan(GridTab gridTab) {
super(gridTab);
log.info(getGridTab().toString());
window = new WCreateFromWindow(this, getGridTab().getWindowNo());
p_WindowNo = getGridTab().getWindowNo();
try
{
if (!dynInit())
return;
zkInit();
setInitOK(true);
}
catch(Exception e)
{
log.log(Level.SEVERE, "", e);
setInitOK(false);
}
AEnv.showWindow(window);
}
protected Label tripLabel = new Label();
protected WEditor tripField ;
protected Checkbox deleteActivityCb = new Checkbox();
private WCreateFromWindow window;
/** Window No */
private int p_WindowNo;
int HBC_Trip_ID=0;
//private boolean m_actionActive = false;
/** Logger */
private CLogger log = CLogger.getCLogger(getClass());
protected void zkInit() throws Exception{
tripLabel.setText(Msg.getElement(Env.getCtx(),"HBC_Trip_ID"));
deleteActivityCb.setText(Msg.getMsg(Env.getCtx(), "DeleteBBMActivity", true));
deleteActivityCb.setTooltiptext(Msg.getMsg(Env.getCtx(), "DeleteBBMActivity", false));
Vlayout vlayout = new Vlayout();
vlayout.setVflex("1");
vlayout.setWidth("100%");
Borderlayout parameterLayout = new Borderlayout();
parameterLayout.setHeight("50px");
parameterLayout.setWidth("100%");
Panel parameterPanel = window.getParameterPanel();
parameterPanel.appendChild(parameterLayout);
Grid parameterStdLayout = GridFactory.newGridLayout();
Panel parameterStdPanel = new Panel();
parameterStdPanel.appendChild(parameterStdLayout);
Center center = new Center();
parameterLayout.appendChild(center);
center.appendChild(parameterStdPanel);
Rows rows = (Rows) parameterStdLayout.newRows();
Row row = rows.newRow();
row.appendChild(tripLabel.rightAlign());
row.appendChild(tripField.getComponent());
row.appendChild(deleteActivityCb);
}
/**
* Dynamic Init
* @throws Exception if Lookups cannot be initialized
* @return true if initialized
*/
public boolean dynInit() throws Exception
{
log.config("");
super.dynInit();
window.setTitle(getTitle());
deleteActivityCb.setSelected(false);
deleteActivityCb.addActionListener(this);
//initBPartner(true);
initTrip(false);
return true;
} // dynInit
protected void initTrip(boolean isDelete) throws Exception
{
int AD_Column_ID=1101895;
MLookup lookupTrip = MLookupFactory.get (Env.getCtx(), p_WindowNo, 0, AD_Column_ID, DisplayType.Search);
tripField = new WSearchEditor("HBC_Trip_ID",true,false,true,lookupTrip);
//
int HBC_Trip_ID = Env.getContextAsInt(Env.getCtx(), p_WindowNo, "HBC_Trip_ID");
loadActivity(HBC_Trip_ID, isDelete);
tripField.setValue(HBC_Trip_ID);
tripField.addValueChangeListener(this);
}
protected void loadActivity (int HBC_Trip_ID, boolean isDelete)
{
loadTableOIS(getActivity(HBC_Trip_ID, isDelete));
}
protected void loadTableOIS (Vector<?> data)
{
window.getWListbox().clear();
// Remove previous listeners
window.getWListbox().getModel().removeTableModelListener(window);
// Set Model
ListModelTable model = new ListModelTable(data);
model.addTableModelListener(window);
window.getWListbox().setData(model, getOISColumnNames());
//
configureMiniTable(window.getWListbox());
} // loadOrder
@Override
public Object getWindow() {
return window;
}
@Override
public void valueChange(ValueChangeEvent evt) {
if (log.isLoggable(Level.CONFIG)) log.config(evt.getPropertyName() + "=" + evt.getNewValue());
if (evt.getPropertyName().equals("HBC_Trip_ID"))
{
if (evt.getNewValue() != null){
HBC_Trip_ID = ((Integer)evt.getNewValue()).intValue();
}
loadActivity(HBC_Trip_ID,deleteActivityCb.isChecked());
}
//TODO: Add condition for deleteActivity checkbox
window.tableChanged(null);
}
@Override
public void onEvent(Event arg0) throws Exception {
/*
if (m_actionActive)
return;
m_actionActive = true;
*/
//TODO: Add condition for deleteActivity checkbox
initTrip(deleteActivityCb.isChecked());
}
}
| 27.395939 | 111 | 0.738373 |
4ffa9ef79d54efd2dbdc46a59d5cb3d76a3409cd | 615 | package com.flightbooking.ws.FlightBookingService.CancelBooking;
import java.sql.Connection;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import com.flightbooking.beans.Booking;
import com.flightbooking.conn.ConnectionUtils;
import com.flightbooking.utils.DBUtils;
public class CalculateRefundDelegate implements JavaDelegate {
@Override
public void execute(DelegateExecution execution) throws Exception {
Booking booking = (Booking) execution.getVariable("BookingDetail");
execution.setVariable("Refund", booking.getTotalPrice());
}
}
| 29.285714 | 69 | 0.82439 |
aa0836fdae07fb8e4d8eee7ae1155bd572fbe460 | 10,928 | package com.tyutyutyu.oo4j.core.query;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.tyutyutyu.oo4j.core.query.OracleProcedure.Type.*;
@RequiredArgsConstructor
@Slf4j
public class MetadataQuery {
private static final String OWNERS_KEY = "owners";
private final NamedParameterJdbcTemplate jdbcTemplate;
public Map<String, OracleType> queryTypes(Collection<String> schemas, Collection<String> typeExcludes) {
log.debug("queryType - schemas: {}", schemas);
Map<String, ?> parameters = Map.of(
OWNERS_KEY, schemas
);
List<AllTypesExtended> allTypesExtendedRows = jdbcTemplate.query(
SqlFactory.sql(SqlFactory.Sql.TYPES),
new MapSqlParameterSource(parameters),
(rs, rowNum) -> new AllTypesExtended(
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6)
)
);
allTypesExtendedRows = allTypesExtendedRows
.stream()
.filter(row -> !typeExcludes.contains(row.getOwner() + "." + row.getTypeName()))
.collect(Collectors.toUnmodifiableList());
Collection<List<AllTypesExtended>> temp = allTypesExtendedRows
.stream()
.collect(Collectors.groupingBy(r -> r.getOwner() + "." + r.getTypeName()))
.values()
.stream()
.sorted((a, b) -> b.get(0).getTypeCode().compareTo(a.get(0).getTypeCode()))
.collect(Collectors.toUnmodifiableList());
Map<String, OracleType> result = new HashMap<>();
for (List<AllTypesExtended> list : temp) {
OracleType oracleType = finisher(result).apply(list);
if (oracleType instanceof OracleComplexType) {
result.put(((OracleComplexType) oracleType).getFullyQualifiedName(), oracleType);
}
}
return result;
}
private Function<List<AllTypesExtended>, OracleType> finisher(Map<String, OracleType> accumulator) {
return typesQueryResults -> {
AllTypesExtended first = typesQueryResults.get(0);
return getType(first.getOwner(), first.getTypeCode(), first.getTypeName(), typesQueryResults, accumulator);
};
}
private OracleType getType(
String schema,
String typeCode,
String typeName,
List<AllTypesExtended> allTypesExtendedRows,
Map<String, OracleType> accumulator
) {
if (accumulator.containsKey(schema + "." + typeName)) {
return accumulator.get(schema + "." + typeName);
}
Class<? extends OracleType> fieldType = OracleType.getTypeByDataType(typeCode, typeName);
OracleType type;
if (fieldType == OracleBasicType.class) {
type = OracleBasicType.valueOf(typeName);
} else if (fieldType == OracleObjectType.class) {
type = new OracleObjectType(
schema,
typeName,
getObjectTypeAttributes(schema, typeName, allTypesExtendedRows, accumulator)
);
} else if (fieldType == OracleTableType.class) {
type = createTableType(schema, typeName, allTypesExtendedRows, accumulator);
} else if (fieldType == OracleCursorType.class) {
type = new OracleCursorType();
} else {
throw new IllegalStateException();
}
return type;
}
private List<OracleTypeField> getObjectTypeAttributes(
String schema,
String typeName,
List<AllTypesExtended> allTypesExtendedRows,
Map<String, OracleType> accumulator
) {
return allTypesExtendedRows
.stream()
.filter(allTypesExtended -> allTypesExtended.getOwner().equals(schema)
&& allTypesExtended.getTypeName().equals(typeName))
.map(allTypesExtended -> new OracleTypeField(
allTypesExtended.getAttrName(),
getType(
allTypesExtended.getOwner(),
allTypesExtended.getTypeCode(),
allTypesExtended.getAttrTypeName(),
allTypesExtendedRows,
accumulator)
))
.collect(Collectors.toUnmodifiableList());
}
private OracleTableType createTableType(String schema, String typeName, List<AllTypesExtended> allTypesExtendedRows, Map<String, OracleType> accumulator) {
log.debug("queryTableType - schema: {}, typeName: {}", schema, typeName);
return allTypesExtendedRows
.stream()
.filter(allTypesExtended -> allTypesExtended.getOwner().equals(schema)
&& allTypesExtended.getTypeName().equals(typeName))
.findAny()
.map(AllTypesExtended::getElemTypeName)
.map(elemTypeName -> new OracleTableType(
schema,
typeName,
getTypeX(schema, elemTypeName, accumulator)
))
.orElseThrow(() ->
new NoPrivilegeException(
String.format(
"The database user has no privilege to query information about %s.%s type from ALL_COLL_TYPES.",
schema, typeName
)
)
);
}
private static OracleType getTypeX(String schema, String typeName, Map<String, OracleType> accumulator) {
if (OracleType.isBasicType(typeName)) {
return OracleBasicType.valueOf(typeName);
}
return accumulator.get(schema + "." + typeName);
}
public List<OracleProcedure> queryProcedures(Collection<String> schemas, Map<String, OracleType> typesMap) {
log.debug("queryProcedures - schemas: {}", schemas);
Map<String, ?> parameters = Map.of(
OWNERS_KEY, schemas
);
List<AllProcedures> query = jdbcTemplate.query(
SqlFactory.sql(SqlFactory.Sql.PROCEDURES),
new MapSqlParameterSource(parameters),
(rs, rowNum) -> new AllProcedures(
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getObject(5) == null
? null
: rs.getInt(5)
)
);
return queryProcedureFields(schemas, query, typesMap);
}
private List<OracleProcedure> queryProcedureFields(Collection<String> schemas, Collection<AllProcedures> allProcedures, Map<String, OracleType> typesMap) {
log.debug("queryProcedureFields - allProcedures.size: {}", allProcedures.size());
Map<String, Object> parameters = Map.of(OWNERS_KEY, schemas);
List<AllArguments> allArgumentsRows = jdbcTemplate.query(
SqlFactory.sql(SqlFactory.Sql.ARGUMENTS),
new MapSqlParameterSource(parameters),
(rs, rowNum) -> new AllArguments(
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getString(7),
rs.getObject(8) == null ? null : rs.getInt(8)
)
)
.stream()
.collect(Collectors.toUnmodifiableList());
return allProcedures
.stream()
.map(allProcedureRow -> new OracleProcedure(
allProcedureRow.getOwner(),
allProcedureRow.getObjectName(),
allProcedureRow.getProcedureName(),
allProcedureRow.getObjectType().equals("PACKAGE") ? IN_PACKAGE : STANDALONE,
allProcedureRow.getOverload(),
mapProcedureFields(allProcedureRow, allArgumentsRows, typesMap)
)
)
.collect(Collectors.toUnmodifiableList());
}
private List<OracleProcedureField> mapProcedureFields(AllProcedures allProcedureRow, List<AllArguments> queryResult, Map<String, OracleType> typesMap) {
return queryResult
.stream()
.filter(allArgumentsRow -> "PROCEDURE".equals(allProcedureRow.getObjectType())
? allArgumentsRow.getPackageName() == null
&& allArgumentsRow.getObjectName().equals(allProcedureRow.getObjectName())
: allArgumentsRow.getPackageName() != null
&& allArgumentsRow.getPackageName().equals(allProcedureRow.getObjectName())
&& allArgumentsRow.getObjectName().equals(allProcedureRow.getProcedureName())
)
.filter(allArgumentsRow -> allArgumentsRow.getOverload() == null || allArgumentsRow.getOverload().equals(allProcedureRow.getOverload()))
.map(mapProcedureField(typesMap))
.collect(Collectors.toUnmodifiableList());
}
private Function<AllArguments, OracleProcedureField> mapProcedureField(Map<String, OracleType> typesMap) {
return allArgumentsRow -> {
OracleType type;
if (allArgumentsRow.getTypeName() == null && OracleType.isBasicType(allArgumentsRow.getDataType())) {
type = OracleBasicType.valueOf(allArgumentsRow.getDataType());
} else if ("REF CURSOR".equals(allArgumentsRow.getDataType())) {
type = new OracleCursorType();
} else {
type = typesMap.get(allArgumentsRow.getOwner() + "." + allArgumentsRow.getTypeName());
}
return new OracleProcedureField(
allArgumentsRow.getArgumentName(),
allArgumentsRow.getInOut(),
type
);
};
}
}
| 41.869732 | 159 | 0.559297 |
04411775f90827bd97db47f94c048d4e9ccea130 | 168 | package com.msc.node.distributednode;
public interface AbstractRequestHandler extends AbstractMessageHandler {
void sendRequest(MessageCreator channelMessage);
}
| 24 | 72 | 0.839286 |
2aa5a1f36a5c8e8974901b4107cc9ebe803dcac2 | 1,585 | package code;
/**
* @Author K
* @Description 面试题19. 正则表达式匹配
* @Mark 调试半天 bug一堆,真难,i j得分清,还有就是循环的次数要算准
* @Date 2022/2/4 14:31
* @EndTime 15.23
**/
public class JZ19 {
public boolean isMatch(String s, String p) {
char[] sArr = s.toCharArray();
char[] pArr = p.toCharArray();
boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
dp[0][0] = true;
for (int i = 2; i < dp[0].length; i++) {
if (dp[0][i - 2] && pArr[i - 1] == '*') {
dp[0][i] = true;
}
}
for (int i = 1; i < sArr.length + 1; i++) {
for (int j = 1; j < pArr.length + 1; j++) {
int di = i + 1;
int dj = j + 1;
if (pArr[j - 1] == '*') {
if (dp[di - 1][dj - 3]) {
dp[di - 1][dj - 1] = true;
}
if (dp[di - 2][dj - 1] && sArr[i - 1] == pArr[j - 2]) {
dp[di - 1][dj - 1] = true;
}
if (dp[di - 2][dj - 1] && pArr[j - 2] == '.') {
dp[di - 1][dj - 1] = true;
}
} else {
if (dp[di - 2][dj - 2] && sArr[i - 1] == pArr[j - 1]) {
dp[di - 1][dj - 1] = true;
}
if (dp[di - 2][dj - 2] && pArr[j - 1] == '.') {
dp[di - 1][dj - 1] = true;
}
}
}
}
return dp[s.length()][p.length()];
}
} | 33.723404 | 75 | 0.319243 |
9d9fbf90d38e46906851440ec612da54c11e6820 | 1,197 | package com.meti.feature.block.function;
import com.meti.feature.evaluate.process.Processable;
import com.meti.process.State;
import com.meti.feature.render.Field;
import com.meti.feature.render.Node;
import com.meti.stack.CallStack;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public abstract class FunctionLoader implements Processable {
protected final State previous;
public FunctionLoader(State previous) {
this.previous = previous;
}
@Override
public Optional<State> evaluate() {
return previous.foldStackByNode(this::test, this::defineFields);
}
protected abstract boolean test(Node node);
private CallStack defineFields(Node node, CallStack stack) {
List<Field> fields = node.streamFields().collect(Collectors.toList());
CallStack withIdentity = defineIdentity(fields, stack);
return after(fields, withIdentity);
}
protected abstract CallStack after(List<Field> fields, CallStack withIdentity);
private CallStack defineIdentity(List<Field> fields, CallStack stack) {
Field identity = fields.get(0);
return stack.define(identity);
}
}
| 29.925 | 83 | 0.730159 |
f31edf8019d2505fc1b310c76ca7515de4265192 | 625 | package p000_Lab_RPG.models;
import p000_Lab_RPG.enums.LogType;
import p000_Lab_RPG.interfaces.Handler;
import p000_Lab_RPG.interfaces.observer.ObservableTarget;
public class Warrior extends AbstractHero {
private static final String ATTACK_MESSAGE = "%s damages %s for %s";
public Warrior(String id, int dmg, Handler logger) {
super(id, dmg, logger);
}
@Override
protected void executeClassSpecificAttack(ObservableTarget target, int dmg, Handler logger) {
logger.handle(LogType.ATTACK, String.format(ATTACK_MESSAGE, this, target, dmg));
target.receiveDamage(dmg);
}
}
| 27.173913 | 97 | 0.736 |
726e2c322911f8a4631e370d37e4f8d2a1ce9f11 | 2,053 | package com.ankushgrover.problems;
import java.util.Stack;
/**
* Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the
* program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using
* strings.
*
* <p>
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is
* valid.
* An input string is valid if:
* - Open brackets are closed by the same type of brackets.
* - Open brackets are closed in the correct order.
* - Note that an empty string is also considered valid.
* <p>
* Example:
* Input: "((()))"
* Output: True
* <p>
* Input: "[()]{}"
* Output: True
* <p>
* Input: "({[)]"
* Output: False
*
* *********************************************** AND *********************************************************
*
* https://leetcode.com/problems/valid-parentheses/submissions/
*/
public class P08ValidBracketString {
public static void main(String[] args) {
System.out.println(isValid(""));
}
private static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '}' || ch == ')' || ch == ']') {
if (stack.isEmpty())
return false;
char pop = stack.pop();
switch (ch) {
case ')':
if (pop != '(')
return false;
break;
case ']':
if (pop != '[')
return false;
break;
case '}':
if (pop != '{')
return false;
break;
}
} else {
stack.push(ch);
}
}
return stack.size() == 0;
}
}
| 27.743243 | 119 | 0.446663 |
33a080d583e080cf4084f57ca4c47a0a568e3212 | 402 | package com.kailang.bubblechat.ui.person;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.kailang.bubblechat.network.client.MsgDataSource;
public class PersonViewModel extends ViewModel {
private MsgDataSource msgDataSource;
public PersonViewModel() {
msgDataSource=MsgDataSource.getInstance();
}
} | 25.125 | 59 | 0.798507 |
773d6c41a4264bd23ddc0412323d95666a12104d | 2,916 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.druid.bvt.sql.mysql.select;
import com.alibaba.polardbx.druid.sql.MysqlTest;
import com.alibaba.polardbx.druid.sql.SQLUtils;
import com.alibaba.polardbx.druid.sql.ast.SQLStatement;
import com.alibaba.polardbx.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.polardbx.druid.sql.parser.SQLParserFeature;
import com.alibaba.polardbx.druid.sql.visitor.ParameterizedOutputVisitorUtils;
import com.alibaba.polardbx.druid.sql.visitor.VisitorFeature;
import com.alibaba.polardbx.druid.util.JdbcConstants;
import java.util.List;
public class MySqlSelectTest_155 extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT SQL_NO_CACHE ((layer_0_right_tb.integer_test) is TRUE)FROM corona_select_multi_db_multi_tb AS layer_0_left_tb LEFT JOIN corona_select_one_db_one_tb AS layer_0_right_tb ON layer_0_right_tb.decimal_test=layer_0_left_tb.varchar_test WHERE '18015376320243458'=18015376320243458 NOT BETWEEN layer_0_right_tb.tinyint_1bit_test AND 'x-3'";
//
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL, SQLParserFeature.TDDLHint);
SQLSelectStatement stmt = (SQLSelectStatement)statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("SELECT SQL_NO_CACHE layer_0_right_tb.integer_test IS true\n" +
"FROM corona_select_multi_db_multi_tb layer_0_left_tb\n" +
"\tLEFT JOIN corona_select_one_db_one_tb layer_0_right_tb ON layer_0_right_tb.decimal_test = layer_0_left_tb.varchar_test\n" +
"WHERE '18015376320243458' = 18015376320243458 NOT BETWEEN layer_0_right_tb.tinyint_1bit_test AND 'x-3'", stmt.toString());
assertEquals("SELECT SQL_NO_CACHE layer_0_right_tb.integer_test IS true\n" +
"FROM corona_select_multi_db_multi_tb layer_0_left_tb\n" +
"\tLEFT JOIN corona_select_one_db_one_tb layer_0_right_tb ON layer_0_right_tb.decimal_test = layer_0_left_tb.varchar_test\n" +
"WHERE ? = ? NOT BETWEEN layer_0_right_tb.tinyint_1bit_test AND ?"
, ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL, VisitorFeature.OutputParameterizedZeroReplaceNotUseOriginalSql));
}
} | 54 | 361 | 0.766461 |
767ba08d7d7c19625fd1dc28e4bc99a4a8aba507 | 377 | package Messages;
public class NullMessage extends Message {
private final String error;
NullMessage(String error) {
super();
this.error = error;
}
@Override
public String toString() {
return "NullMessage: " + this.error;
}
@Override
public Message process(MessageProcessor processor) {
return this;
}
}
| 17.136364 | 56 | 0.615385 |
a7fd09c6110494c3507fda66509393cf21d7a0f8 | 416 | package com.bootdo.common.controller;
import org.springframework.stereotype.Controller;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.SysUserDO;
@Controller
public class BaseController {
public SysUserDO getUser() {
return ShiroUtils.getUser();
}
public Long getUserId() {
return getUser().getUserId();
}
public String getUsername() {
return getUser().getUsername();
}
} | 19.809524 | 49 | 0.759615 |
6415053c70d30872ea2e74a5441bbcabb14a58a4 | 1,424 | package com.minminaya.library.util;
import android.text.TextUtils;
import android.util.Log;
/**
* Description: 通用的Log管理
* 开发阶段LOGLEVEL = 6
* 发布阶段LOGLEVEL = -1
*/
public class Logger {
private static int LOGLEVEL = 6;
private static int VERBOSE = 1;
private static int DEBUG = 2;
private static int INFO = 3;
private static int WARN = 4;
private static int ERROR = 5;
/**
* 设置当前log开关
* @param flag true为开发阶段打开log,false为发布阶段关闭log
* */
public static void setDevelopMode(boolean flag) {
if(flag) {
LOGLEVEL = 6;
} else {
LOGLEVEL = -1;
}
}
public static void v(String tag, String msg) {
if(LOGLEVEL > VERBOSE && !TextUtils.isEmpty(msg)) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if(LOGLEVEL > DEBUG && !TextUtils.isEmpty(msg)) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if(LOGLEVEL > INFO && !TextUtils.isEmpty(msg)) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if(LOGLEVEL > WARN && !TextUtils.isEmpty(msg)) {
Log.w(tag, msg);
}
}
public static void e(String tag, String msg) {
if(LOGLEVEL > ERROR && !TextUtils.isEmpty(msg)) {
Log.e(tag, msg);
}
}
}
| 22.25 | 59 | 0.550562 |
e14e1f0b6f1a786094df44b396de45e0ec818f62 | 1,663 | package com.app.tbd.ui.Model.Receive;
import java.util.ArrayList;
import java.util.List;
public class NewsletterLanguageReceive {
private String Status;
private String Message;
private List<NewsletterLanguage> CultureList = new ArrayList<NewsletterLanguage>();
public class NewsletterLanguage {
private String CountryCode;
private String CultureCode;
private String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getCountryCode() {
return CountryCode;
}
public void setCountryCode(String countryCode) {
CountryCode = countryCode;
}
public String getCultureCode() {
return CultureCode;
}
public void setCultureCode(String cultureCode) {
CultureCode = cultureCode;
}
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public NewsletterLanguageReceive(NewsletterLanguageReceive returnData) {
Status = returnData.getStatus();
Message = returnData.getMessage();
CultureList = returnData.getCultureList();
}
public List<NewsletterLanguage> getCultureList() {
return CultureList;
}
public void setCultureList(List<NewsletterLanguage> cultureList) {
CultureList = cultureList;
}
}
| 21.320513 | 87 | 0.622369 |
5eba042d0c328232f75dbdec05596fe2558bbdb8 | 1,657 | package com.omisoft.vitafu.utils.plugins.akkaGuice;
import static com.omisoft.vitafu.utils.plugins.akkaGuice.GuiceExtension.GuiceProvider;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import play.libs.Akka;
import akka.actor.Actor;
import akka.actor.Props;
/**
* Created by bkoprinski on 15-1-23.
*/
public class PropsContext {
private static Map<String, ActorHolder> map = new HashMap<String, ActorHolder>();
public static Props get(Class<? extends Actor> clazz) {
return GuiceProvider.get(Akka.system()).props(clazz);
}
public static Props get(String name) {
ActorHolder actorHolder = map.get(name);
if(actorHolder.isSingleton()) {
return GuiceProvider.get(Akka.system()).props(map.get(name).getActor());
} else {
return GuiceProvider.get(Akka.system()).props(map.get(name).getActor());
}
}
//Do not resolve the Props at this point. The injector might change. Do it on the get methods above
protected static void put(String key, Class<? extends Actor> actor, boolean isSingleton) {
map.put(key, new ActorHolder(actor, isSingleton));
}
protected static void put(String key, ActorHolder actorHolder) {
map.put(key, actorHolder);
}
protected static boolean containsKey(String key) {
return map.containsKey(key);
}
protected static Class<? extends Actor> remove(String key) {
return map.remove(key).getActor();
}
protected static Set<String> keySet() {
return map.keySet();
}
protected static boolean isEmpty() {
return map.isEmpty();
}
}
| 29.589286 | 103 | 0.67411 |
b64ef97a63c6cbd60e6267e4528413680e8ef7ee | 2,072 | /*
* Copyright (C) 2017 Dremio Corporation
*
* 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.dremio.exec.planner.fragment;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import com.dremio.exec.proto.CoordinationProtos.NodeEndpoint;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ListMultimap;
/**
* Holds the mapping of execution nodes available in the cluster.
*/
public class ExecutionNodeMap {
// We use multimap because more than one node can run in the same cluster.
private final ListMultimap<String, NodeEndpoint> nodeMap = ArrayListMultimap.create();
private final List<NodeEndpoint> endpoints;
public ExecutionNodeMap(Iterable<NodeEndpoint> endpoints){
this.endpoints = FluentIterable.from(endpoints).toList();
for(NodeEndpoint ep : endpoints){
nodeMap.put(ep.getAddress(), ep);
}
}
public NodeEndpoint getEndpoint(String address){
List<NodeEndpoint> endpoints = nodeMap.get(address);
if(endpoints == null || endpoints.isEmpty()){
return null;
}
if(endpoints.size() == 1){
return endpoints.get(0);
} else {
// if there is more than one endpoint on the same host, pick a random one.
return endpoints.get(ThreadLocalRandom.current().nextInt(endpoints.size()));
}
}
public Collection<String> getHosts() {
return nodeMap.keySet();
}
public List<NodeEndpoint> getExecutors(){
return endpoints;
}
}
| 32.375 | 88 | 0.732143 |
402366af85258b6ce173bdf90a6f79df0cc43e0d | 594 | package ca.carsonbrown.android.runon;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
/**
* Created by carson on 2013-08-24.
*/
public class BackupAgent extends BackupAgentHelper {
static final String PREFS_DEFAULT = "ca.carsonbrown.android.runon_preferences";
static final String PREFS_BACKUP_KEY = "preferences_backup_key";
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS_DEFAULT);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
| 28.285714 | 102 | 0.767677 |
c913932fb9d66ce986f50aa1b33f8ac453f5a138 | 8,860 | package nam.model.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import nam.model.Operation;
import nam.model.Parameter;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.aries.Assert;
import org.aries.util.BaseUtil;
import org.aries.util.NameUtil;
import org.aries.util.ObjectUtil;
import org.aries.util.TypeMap;
import org.aries.util.Validator;
public class ParameterUtil extends BaseUtil {
public static Object getKey(Parameter parameter) {
return parameter.getType();
}
public static String getLabel(Parameter parameter) {
return parameter.getName();
}
public static String getLabel(Collection<Parameter> parameterList) {
return null;
}
public static boolean isEmpty(Parameter parameter) {
if (parameter == null)
return true;
boolean status = false;
status |= StringUtils.isEmpty(parameter.getName());
status |= StringUtils.isEmpty(parameter.getType());
return status;
}
public static boolean isEmpty(Collection<Parameter> parameterList) {
if (parameterList == null || parameterList.size() == 0)
return true;
Iterator<Parameter> iterator = parameterList.iterator();
while (iterator.hasNext()) {
Parameter parameter = iterator.next();
if (!isEmpty(parameter))
return false;
}
return true;
}
public static String toString(Parameter parameter) {
if (isEmpty(parameter))
return "Parameter: [uninitialized] "+parameter.toString();
String text = parameter.toString();
return text;
}
public static String toString(Collection<Parameter> parameterList) {
if (isEmpty(parameterList))
return "";
StringBuffer buf = new StringBuffer();
Iterator<Parameter> iterator = parameterList.iterator();
for (int i=0; iterator.hasNext(); i++) {
Parameter parameter = iterator.next();
if (i > 0)
buf.append(", ");
String text = toString(parameter);
buf.append(text);
}
String text = StringEscapeUtils.escapeJavaScript(buf.toString());
return text;
}
public static Parameter create() {
Parameter parameter = new Parameter();
initialize(parameter);
return parameter;
}
public static void initialize(Parameter parameter) {
if (parameter.getRequired() == null)
parameter.setRequired(false);
}
public static boolean validate(Parameter parameter) {
if (parameter == null)
return false;
Validator validator = Validator.getValidator();
validator.notEmpty(parameter.getName(), "\"Name\" must be specified");
validator.notEmpty(parameter.getType(), "\"Type\" must be specified");
boolean isValid = validator.isValid();
return isValid;
}
public static boolean validate(Collection<Parameter> parameterList) {
Validator validator = Validator.getValidator();
Iterator<Parameter> iterator = parameterList.iterator();
while (iterator.hasNext()) {
Parameter parameter = iterator.next();
//TODO break or accumulate?
validate(parameter);
}
boolean isValid = validator.isValid();
return isValid;
}
public static void sortRecords(List<Parameter> parameterList) {
Collections.sort(parameterList, createParameterComparator());
}
public static Collection<Parameter> sortRecords(Collection<Parameter> parameterCollection) {
List<Parameter> list = new ArrayList<Parameter>(parameterCollection);
Collections.sort(list, createParameterComparator());
return list;
}
public static Comparator<Parameter> createParameterComparator() {
return new Comparator<Parameter>() {
public int compare(Parameter parameter1, Parameter parameter2) {
Object key1 = getKey(parameter1);
Object key2 = getKey(parameter2);
String text1 = key1.toString();
String text2 = key2.toString();
int status = text1.compareTo(text2);
return status;
}
};
}
public static Parameter clone(Parameter parameter) {
if (parameter == null)
return null;
Parameter clone = create();
clone.setName(ObjectUtil.clone(parameter.getName()));
clone.setType(ObjectUtil.clone(parameter.getType()));
clone.setKey(ObjectUtil.clone(parameter.getKey()));
clone.setConstruct(ObjectUtil.clone(parameter.getConstruct()));
clone.setRequired(ObjectUtil.clone(parameter.getRequired()));
return clone;
}
public static List<Parameter> clone(List<Parameter> parameterList) {
if (parameterList == null)
return null;
List<Parameter> newList = new ArrayList<Parameter>();
Iterator<Parameter> iterator = parameterList.iterator();
while (iterator.hasNext()) {
Parameter parameter = iterator.next();
Parameter clone = clone(parameter);
newList.add(clone);
}
return newList;
}
public static String getConstruct(Parameter parameter) {
String construct = parameter.getConstruct();
if (construct == null) {
construct = "item";
parameter.setConstruct(construct);
}
return construct;
}
public static String getTypeSignature(Parameter parameter) {
String className = TypeUtil.getClassName(parameter.getType());
String structure = parameter.getConstruct();
if (structure.equals("item")) {
return className;
} else if (structure.equals("list")) {
return "List<"+className+">";
} else if (structure.equals("set")) {
return "Set<"+className+">";
} else if (structure.equals("map")) {
String keyClassName = TypeUtil.getClassName(parameter.getKey());
return "Map<"+keyClassName+", "+className+">";
}
return null;
}
public static Class<?> getParameterType(Parameter parameter) {
if (parameter != null && parameter.getType() != null)
return TypeMap.INSTANCE.getTypeClassByTypeName(parameter.getType());
//TODO get this outta here
return null;
}
/*
* Parameter factory methods
* -------------------------
*/
public static Parameter createParameter(Class<?> parameterType) {
Parameter parameter = new Parameter();
String parameterName = parameterType.getCanonicalName();
String simpleName = NameUtil.getSimpleName(parameterName);
parameter.setName(NameUtil.uncapName(simpleName));
String typeName = TypeUtil.getTypeFromClass(parameterType);
//Assert.notNull(typeName, "ParameterType for method \""+methodName+"\" not found: "+parameterType.getCanonicalName());
parameter.setType(typeName);
return parameter;
}
public static Parameter createParameter(String packageName, String className, String name, String structure) {
Parameter parameter = new Parameter();
parameter.setConstruct(structure);
parameter.setType(TypeUtil.getTypeFromPackageAndClass(packageName, className));
parameter.setName(name);
return parameter;
}
public static String getArgumentString(Operation operation) {
return getParameterString(operation.getParameters(), false);
}
public static String getParameterString(Operation operation) {
return getParameterString(operation.getParameters(), true);
}
public static String getParameterString(List<Parameter> parameters, boolean includeType) {
StringBuffer buf = new StringBuffer();
Iterator<Parameter> iterator = parameters.iterator();
for (int i=0; iterator.hasNext(); i++) {
Parameter parameter = iterator.next();
String parameterName = parameter.getName();
String parameterType = parameter.getType();
String parameterClassName = TypeUtil.getLocalPart(parameterType);
if (parameterClassName.endsWith("Message") && !parameterName.endsWith("Message"))
parameterName += "Message";
if (i > 0)
buf.append(", ");
if (includeType) {
buf.append(parameterClassName);
buf.append(" ");
}
buf.append(parameterName);
}
return buf.toString();
}
public static boolean equals(Parameter parameter1, Parameter parameter2) {
Assert.notNull(parameter1, "Parameter1 must be specified");
Assert.notNull(parameter2, "Parameter2 must be specified");
Assert.notNull(parameter1.getName(), "Parameter1 name must be specified");
Assert.notNull(parameter2.getName(), "Parameter2 name must be specified");
Assert.notNull(parameter1.getType(), "Parameter1 type must be specified");
Assert.notNull(parameter2.getType(), "Parameter2 type must be specified");
if (!parameter1.getName().equals(parameter2.getName()))
return false;
if (!parameter1.getType().equals(parameter2.getType()))
return false;
return true;
}
public static boolean equals(List<Parameter> parameters1, List<Parameter> parameters2) {
Assert.notNull(parameters1, "Parameter1 list must be specified");
Assert.notNull(parameters2, "Parameter2 list must be specified");
if (parameters1.size() != parameters2.size())
return false;
for (int i=0; i < parameters1.size(); i++) {
Parameter parameter1 = parameters1.get(i);
Parameter parameter2 = parameters1.get(i);
if (!equals(parameter1, parameter2))
return false;
}
return true;
}
}
| 31.642857 | 121 | 0.72912 |
f7bdc2f75f3ac628a072aeee0bdb6bd779edc02e | 1,856 | package com.example.scsidecar.grayrelease.config;
import com.example.scsidecar.grayrelease.loadbalance.RequestHolder;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import java.util.Optional;
/**
* @author Create by Brian on 2019/12/6 16:10
*/
@Slf4j
@Configuration
@AutoConfigureBefore(RibbonClientConfiguration.class)
@ConditionalOnClass(reactor.core.publisher.Mono.class)
@ConditionalOnProperty(value = "ribbon.filter.metadata.enabled", matchIfMissing = true)
public class WebfluxFilterAutoConfiguration {
@Bean
RequestInterceptor webfluxRequestTokenBearerInterceptor() {
return requestTemplate -> {
Object request = RequestHolder.get();
Optional.ofNullable(request).ifPresent(serverHttpRequest -> {
if(serverHttpRequest instanceof ServerHttpRequest) {
HttpHeaders headers = ((ServerHttpRequest) serverHttpRequest).getHeaders();
Optional.ofNullable(headers).ifPresent(
(headMap) -> {
log.info("Reactive Accessing Version {}", headMap.get("version"));
requestTemplate.header("VERSION", headMap.get("version"));
}
);
}
});
};
}
}
| 40.347826 | 98 | 0.702586 |
0ab2254d6a034b5086142dae3dc997f525160dc9 | 821 | package com.jvms.i18neditor.editor.menu;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import com.jvms.i18neditor.editor.Editor;
import com.jvms.i18neditor.util.MessageBundle;
/**
* This class represents a menu item for renaming a translation key.
*
* @author Jacob van Mourik
*/
public class RenameTranslationMenuItem extends JMenuItem {
private final static long serialVersionUID = 907122077814626286L;
public RenameTranslationMenuItem(Editor editor, boolean enabled) {
super(MessageBundle.get("menu.edit.rename.title"));
setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
addActionListener(e -> editor.renameSelectedTranslation());
setEnabled(enabled);
}
} | 31.576923 | 116 | 0.784409 |
d53af0a3b5ae6cfc25ddfc6b2560e2aca054fc38 | 11,823 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* Test suit for data engine.
*/
public class AllTests
{
/**
* @return
*/
public static Test suite( )
{
TestSuite suite = new TestSuite( "Test for org.eclipse.birt.data.engine" );
/* in package: org.eclipse.birt.data.engine.aggregation */
suite.addTestSuite( org.eclipse.birt.data.engine.aggregation.FinanceTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.aggregation.TotalTest.class );
/* in package org.eclipse.birt.data.engine.reg */
suite.addTestSuite( org.eclipse.birt.data.engine.regre.DataSourceTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.regre.FeatureTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.regre.SortTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.regre.SortHintTest.class);
/* in package org.eclipse.birt.data.engine.api */
suite.addTestSuite( org.eclipse.birt.data.engine.api.ClobAndBlobTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.DataSetCacheTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.DteLevelDataSetCacheTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.GroupLevelTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.ScriptedDSTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.ScriptTest.class );
// ?? suite.addTestSuite( org.eclipse.birt.data.engine.api.StoredProcedureTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.UsesDetailFalseTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.ProgressiveViewingTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.api.NoUpdateAggrFilterTest.class );
/* in package org.eclipse.birt.data.engine.binding */
suite.addTestSuite( org.eclipse.birt.data.engine.binding.ColumnBindingTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.ColumnHintTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.ComputedColumnTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.DataSetCacheTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.DefineDataSourceTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.DistinctValueTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.FeaturesTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.FilterByRowTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.GroupOnRowTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.InputParameterTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.MaxRowsTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.MultiplePassTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.NestedQueryTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.QueryCacheTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.SubQueryTest.class );
/* in package org.eclipse.birt.data.engine.binding.newbinding */
suite.addTestSuite( org.eclipse.birt.data.engine.binding.newbinding.MultiplePassTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.binding.newbinding.ColumnBindingTest.class );
/* in package org.eclipse.birt.data.engine.executor.cache */
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.CacheClobAndBlobTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.CacheComputedColumnTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.CachedMultiplePassTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.CacheFeaturesTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.CacheNestedQueryTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.CacheSortTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.CacheSubqueryTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.executor.cache.MemoryCacheTest.class );
/* in package org.eclipse.birt.data.engine.executor.transform */
suite.addTestSuite( org.eclipse.birt.data.engine.executor.transform.CachedResultSetTest.class );
/* in package org.eclipse.birt.data.engine.executor.transform.group */
suite.addTestSuite( org.eclipse.birt.data.engine.executor.transform.group.GroupByDistinctValueTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.executor.transform.group.GroupByRowKeyCountTest.class);
/* in package org.eclipse.birt.data.engine.expression */
suite.addTestSuite( org.eclipse.birt.data.engine.expression.ComplexExpressionCompilerTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.expression.ExpressionCompilerTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.expression.ExpressionCompilerUtilTest.class);
/* in package org.eclipse.birt.data.engine.impl.rd */
suite.addTestSuite( org.eclipse.birt.data.engine.impl.rd.ViewingTest2.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.rd.ReportDocumentTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.rd.ReportDocumentTest2.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.rd.ViewingTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.rd.SummaryIVTest.class);
/* in package org.eclipse.birt.data.engine.impl */
suite.addTestSuite( org.eclipse.birt.data.engine.impl.AggregationTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.ExprManagerUtilTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.JointDataSetTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.ResultMetaDataTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.ScriptEvalTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.impl.ConfigFileParserTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.impl.IncreCacheDataSetTest.class);
/* in package org.eclipse.birt.data.engine.impl.binding */
suite.addTestSuite( org.eclipse.birt.data.engine.impl.binding.AggregationTest.class );
/* in package org.eclipse.birt.data.engine.impl.document */
suite.addTestSuite( org.eclipse.birt.data.engine.impl.document.GroupInfoUtilTest.class);
/* in package org.eclipse.birt.data.engine.impl */
suite.addTestSuite( org.eclipse.birt.data.engine.impl.util.DirectedGraphTest.class );
/* in package org.eclipse.birt.data.engine.olap.api */
suite.addTestSuite( org.eclipse.birt.data.engine.olap.api.CubeFeaturesTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.olap.api.CubeIVTest.class);
suite.addTestSuite( org.eclipse.birt.data.engine.olap.api.CubeDrillFeatureTest.class);
/* in package org.eclipse.birt.data.engine.olap.data.document*/
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.document.BufferedRandomAccessObjectTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.document.CachedDocumentObjectManagerTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.document.DocumentManagerTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.document.FileDocumentManagerTest.class );
/* in package org.eclipse.birt.data.engine.olap.data.impl*/
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.CubeAggregationTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.DimensionKeyTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.LevelMemberTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.TraversalorTest.class );
/* in package org.eclipse.birt.data.engine.olap.data.impl.aggregation.function*/
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.aggregation.function.MonthToDateTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.aggregation.function.YearToDateFunctionTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.aggregation.function.QuarterToDateFunctionTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.aggregation.function.PreviousNPeriodsFunctionTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.aggregation.function.WeekToDateTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.aggregation.function.TrailingTest.class );
/* in package org.eclipse.birt.data.engine.olap.data.impl.dimension */
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.dimension.DimensionTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.dimension.DimensionTest2.class );
/* in package org.eclipse.birt.data.engine.olap.data.impl.facttable */
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.facttable.DimensionSegmentsTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.facttable.FactTableHelperTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.facttable.FactTableHelperTest2.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.facttable.FactTableRowTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.impl.facttable.FactTableRowIteratorWithFilterTest.class );
/* in package org.eclipse.birt.data.engine.olap.data.util */
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.BufferedPrimitiveDiskArrayTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.BufferedRandomAccessFileTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.BufferedStructureArrayTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.DiskIndexTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.DiskSortedStackTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.ObjectArrayUtilTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.PrimaryDiskArrayTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.PrimarySortedStackTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.SetUtilTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.data.util.StructureDiskArrayTest.class );
/* in package org.eclipse.birt.data.engine.olap.util.filter */
suite.addTestSuite( org.eclipse.birt.data.engine.olap.util.filter.CubePosFilterTest.class );
/* in package org.eclipse.birt.data.engine.olap.cursor */
suite.addTestSuite( org.eclipse.birt.data.engine.olap.cursor.CursorNavigatorTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.cursor.CursorModelTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.cursor.MirrorCursorModelTest.class );
suite.addTestSuite( org.eclipse.birt.data.engine.olap.cursor.MirrorCursorNavigatorTest.class );
/* in package org.eclipse.birt.data.engine.olap.util */
suite.addTestSuite( org.eclipse.birt.data.engine.olap.util.OlapExpressionUtilTest.class );
return suite;
}
} | 63.908108 | 124 | 0.782458 |
89103ecd9bf3c4556c59aac39a0852c92eea665c | 1,916 | package com.wxq.apsv.worker;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
/**
* 保存各个抓取任务的定时器
*/
public final class ApsvTimerManager {
private static Map<String, Timer> timerMap = new HashMap<>();
public static void AddTimer(Timer timer, int taskId) {
timerMap.put(Integer.toString(taskId), timer);
}
public static Timer GetTimer(int taskId) {
return timerMap.get(Integer.toString(taskId));
}
// 任务开始时间戳Map
private static Map<String, Date> startTimeMap = new HashMap<>();
public static void RecordStartTime(int taskId) {
Date date = new Date();
startTimeMap.put(Integer.toString(taskId), date);
}
public static void ClearStartTime(int taskId) {
startTimeMap.remove(Integer.toString(taskId));
}
/**
* 计算任务的运行时间并格式化为友好的字符串
* @param taskId int
* @return String
*/
public static String GetElapseTime(int taskId) {
Date date = startTimeMap.get(Integer.toString(taskId));
if (date == null) {
return "";
}
Date now = new Date();
long seconds = (now.getTime() - date.getTime()) / 1000;
if (seconds < 60) {
return seconds + " 秒";
} else if (seconds < 3600) {
return (int)(seconds / 60) + " 分 " + (int)(seconds % 60) + " 秒";
} else if (seconds < 3600 * 24) {
int hours = (int)(seconds / 3600);
int minutes = (int)(seconds % 3600 / 60);
return hours + " 小时 " + minutes + " 分钟 " + (int)(seconds % 60) + " 秒";
} else {
int days = (int)(seconds / 3600 / 24);
int hours = (int)(seconds % (3600 * 24) / 3600);
int minutes = (int)(seconds % (3600 * 24) % 3600 / 60);
return days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + (int)(seconds % 60) + " 秒";
}
}
} | 31.409836 | 97 | 0.557933 |
0f6a4ff482b3317139d1265b2db790717975f196 | 169 | public static boolean isSorted(int[] a) {
for(int i = 1; i < a.length; i++) {
if(a[i] < a[i - 1]) return false;
}
return true;
}
| 24.142857 | 45 | 0.449704 |
6ca8fe21c163d6f77607215097e1d2e720688f67 | 1,416 | /*
* 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 singletonPattern;
/**
*
* @author Steve
*/
public class Singleton {
// volatile ensure multiple threads handle the variable correctly
// static so that it belongs to the class, not the object
private volatile static Singleton uniqueInstance = null;
// use private constructor to force the use of getInstance()
private Singleton() {
};
// static method to get the singleton - uses lazy instantiation
public static Singleton getInstance() {
if ( uniqueInstance == null ) {
// use double-checked locking to
// ensure single threading through the creation code
// but minimize the overhead of synchronization
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton(); // create the instance
}
}
}
return uniqueInstance;
}
// add other methods here!
private int counter = 0;
public int getCounter() {
return counter;
}
public int incrementCounter() {
counter++;
return counter;
}
}
| 28.897959 | 80 | 0.587571 |
86c9f938d214b29f63ea7f3c85a088a74fe76081 | 15,742 | package com.example.rajan.coinprice;
import android.app.ActivityManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.rajan.coinprice.Model.CoinMarketCapObject;
import com.example.rajan.coinprice.Model.Currency;
import com.example.rajan.coinprice.Model.Prices;
import com.example.rajan.coinprice.Model.koinexTicker.KoinexTickerObject;
import com.example.rajan.coinprice.data.CoinPriceDbHelper;
import com.example.rajan.coinprice.data.KoinexCurrentPricesContract;
import com.example.rajan.coinprice.network.NetworkCallIntentService;
import com.example.rajan.coinprice.utilities.DbUtils;
import com.example.rajan.coinprice.utilities.JobSchedulerUtils;
import com.example.rajan.coinprice.utilities.NotificationUtils;
import com.example.rajan.coinprice.utilities.PreferenceUtilities;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private final static String KOINEX_API_TICKER = "https://koinex.in/api/ticker";
private final static String COINMARKETCAP_API_TICKER = "https://api.coinmarketcap.com/v1/ticker/?convert=INR&limit=6";
private static final String TAG = "MainActivity";
private TextView mResultTextView;
private RecyclerView mRecyclerView;
private String[] mPriceData;
private Button mRefreshButton;
private Button mTestButton;
private ProgressBar mLoadingIndicator;
private MenuItem mRefreshItem;
private final Gson gson = new Gson();
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResultTextView = (TextView) findViewById(R.id.result_textview);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_coinprice);
mRefreshButton = (Button) findViewById(R.id.refresh_action);
mTestButton = (Button) findViewById(R.id.test_action);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
mRefreshItem = (MenuItem) findViewById(R.id.action_refresh);
mRefreshButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationUtils.dummyNotification(getApplicationContext());
if (isNetworkAvailable()) {
showLoading();
Intent service = new Intent(getApplicationContext(), NetworkCallIntentService.class);
service.setAction(NetworkCallTask.ACTION_TRIGGER_API_CALL);
startService(service);
Log.d(TAG, "onClick: service started");
// volleyCall();
} else {
mPriceData = new String[1];
mPriceData[0] = "Empty Data";
CurrencyPriceAdapter adapter = new CurrencyPriceAdapter();
adapter.setPriceData(mPriceData);
mRecyclerView.swapAdapter(adapter, true);
Toast.makeText(getApplicationContext(), "Unable to get data, No Internet Connection...", Toast.LENGTH_SHORT).show();
}
}
});
mTestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent(getApplicationContext(), NetworkCallIntentService.class);
service.setAction(NetworkCallTask.ACTION_TRIGGER_API_CALL);
startService(service);
Log.d(TAG, "onClick: service started");
}
});
mPriceData = new String[1];
mPriceData[0] = "Empty Data";
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
CurrencyPriceAdapter adapter = new CurrencyPriceAdapter();
adapter.setPriceData(mPriceData);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(false);
JobSchedulerUtils.scheduleNetworkCallCustomInterval(this);
DbUtils.getAllKoinexTickerRaw(this);
DbUtils.getAllCoinMarketcapTickerRaw(this);
}
@Override
protected void onStart() {
Log.d(TAG, "onStart: Preference Change Listener Regisetered");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
super.onStart();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: Preference Change Listener Unregistered");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
String response = null;
if (hasInput) {
response = scanner.next();
}
scanner.close();
return response;
} finally {
urlConnection.disconnect();
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(PreferenceUtilities.KEY_SUCCESSFUL_REQUEST_COUNT)) {
if (PreferenceUtilities.isCoinMarketCapJsonSet(this) && PreferenceUtilities.isKoinexJsonSet(this)) {
String koinexJson = PreferenceUtilities.getKoinexJson(this);
String coinMarketCapJson = PreferenceUtilities.getCoinMarketCapJson(this);
Log.d(TAG, "onSharedPreferenceChanged: " + koinexJson + "\n" + coinMarketCapJson);
generateUI(koinexJson, coinMarketCapJson);
} else {
Log.d(TAG, "onSharedPreferenceChanged: key is " + key);
mPriceData = new String[1];
mPriceData[0] = "Empty Data";
CurrencyPriceAdapter adapter = new CurrencyPriceAdapter();
adapter.setPriceData(mPriceData);
mRecyclerView.swapAdapter(adapter, true);
// hideLoading();
}
hideLoading();
} else if (key.equals(PreferenceUtilities.KEY_FAILURE_REQUEST_COUNT)) {
Toast.makeText(getApplicationContext(), key + " api request Failed", Toast.LENGTH_SHORT).show();
mPriceData = new String[1];
mPriceData[0] = "Empty Data";
CurrencyPriceAdapter adapter = new CurrencyPriceAdapter();
adapter.setPriceData(mPriceData);
mRecyclerView.swapAdapter(adapter, true);
hideLoading();
}
}
private void showLoading() {
mRecyclerView.setVisibility(View.INVISIBLE);
mLoadingIndicator.setVisibility(View.VISIBLE);
mRefreshButton.setEnabled(false);
mRefreshItem.setEnabled(false);
}
private void hideLoading() {
mRecyclerView.setVisibility(View.VISIBLE);
mLoadingIndicator.setVisibility(View.INVISIBLE);
mRefreshButton.setEnabled(true);
mRefreshItem.setEnabled(true);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void generateUI(KoinexTickerObject koinexTickerObject, ArrayList<CoinMarketCapObject> coinMarketCapObjects) {
mPriceData = new String[6];
mPriceData[0] = "" + Currency.BITCOIN.name() + "(" + Currency.BITCOIN.getText() + ") : " + koinexTickerObject.getPrices().getBTC() + " ; " + coinMarketCapObjects.get(0).getPriceInr();
mPriceData[1] = "" + Currency.ETHERIUM.name() + "(" + Currency.ETHERIUM.getText() + ") : " + koinexTickerObject.getPrices().getETH() + " ; " + coinMarketCapObjects.get(1).getPriceInr();
mPriceData[2] = "" + Currency.BITCOINCASH.name() + "(" + Currency.BITCOINCASH.getText() + ") : " + koinexTickerObject.getPrices().getBCH() + " ; " + coinMarketCapObjects.get(2).getPriceInr();
mPriceData[3] = "" + Currency.MIOTA.name() + "(" + Currency.MIOTA.getText() + ") : " + koinexTickerObject.getPrices().getMIOTA() + " ; " + coinMarketCapObjects.get(3).getPriceInr();
mPriceData[4] = "" + Currency.RIPPLE.name() + "(" + Currency.RIPPLE.getText() + ") : " + koinexTickerObject.getPrices().getXRP() + " ; " + coinMarketCapObjects.get(4).getPriceInr();
mPriceData[5] = "" + Currency.LITECOIN.name() + "(" + Currency.LITECOIN.getText() + ") : " + koinexTickerObject.getPrices().getLTC() + " ; " + coinMarketCapObjects.get(5).getPriceInr();
Log.d(TAG, "generateUI: Hua kuch");
CurrencyPriceAdapter adapter = new CurrencyPriceAdapter();
adapter.setPriceData(mPriceData);
mRecyclerView.swapAdapter(adapter, true);
}
private TreeMap<String, CoinMarketCapObject> getCoinMarketCapObjects(String json) {
ArrayList<CoinMarketCapObject> coinMarketCapObjects = new ArrayList<>();
TreeMap<String, CoinMarketCapObject> mapCoinMarketCapObjects = new TreeMap<>();
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
CoinMarketCapObject object = gson.fromJson(jsonArray.get(i).toString(), CoinMarketCapObject.class);
Log.d(TAG, "Response is: " + object.toString());
coinMarketCapObjects.add(object);
mapCoinMarketCapObjects.put(object.getSymbol(), object);
}
} catch (JSONException e) {
e.printStackTrace();
}
return mapCoinMarketCapObjects;
}
private KoinexTickerObject getKoinexTickerObject(String json) {
KoinexTickerObject koinexTickerObject = gson.fromJson(json, KoinexTickerObject.class);
Log.d(TAG, "Response is: " + koinexTickerObject.toString());
return koinexTickerObject;
}
private void generateUI(String koinexJson, String coinMarketCapJson) {
KoinexTickerObject koinexTickerObject = getKoinexTickerObject(koinexJson);
Map<String, CoinMarketCapObject> coinMarketCapObjects = getCoinMarketCapObjects(coinMarketCapJson);
mPriceData = new String[6];
mPriceData[0] = "" + Currency.BITCOIN.name() + "(" + Currency.BITCOIN.getText() + ") : " + koinexTickerObject.getPrices().getBTC() + " ; " + coinMarketCapObjects.get(Currency.BITCOIN.getText()).getPriceInr();
mPriceData[1] = "" + Currency.ETHERIUM.name() + "(" + Currency.ETHERIUM.getText() + ") : " + koinexTickerObject.getPrices().getETH() + " ; " + coinMarketCapObjects.get(Currency.ETHERIUM.getText()).getPriceInr();
mPriceData[2] = "" + Currency.BITCOINCASH.name() + "(" + Currency.BITCOINCASH.getText() + ") : " + koinexTickerObject.getPrices().getBCH() + " ; " + coinMarketCapObjects.get(Currency.BITCOINCASH.getText()).getPriceInr();
mPriceData[3] = "" + Currency.MIOTA.name() + "(" + Currency.MIOTA.getText() + ") : " + koinexTickerObject.getPrices().getMIOTA() + " ; " + coinMarketCapObjects.get(Currency.MIOTA.getText()).getPriceInr();
mPriceData[4] = "" + Currency.RIPPLE.name() + "(" + Currency.RIPPLE.getText() + ") : " + koinexTickerObject.getPrices().getXRP() + " ; " + coinMarketCapObjects.get(Currency.RIPPLE.getText()).getPriceInr();
mPriceData[5] = "" + Currency.LITECOIN.name() + "(" + Currency.LITECOIN.getText() + ") : " + koinexTickerObject.getPrices().getLTC() + " ; " + coinMarketCapObjects.get(Currency.LITECOIN.getText()).getPriceInr();
Log.d(TAG, "generateUI: Hua kuch");
CurrencyPriceAdapter adapter = new CurrencyPriceAdapter();
adapter.setPriceData(mPriceData);
mRecyclerView.swapAdapter(adapter, true);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.coinprice_menu, menu);
mRefreshItem = menu.findItem(R.id.action_refresh);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
if (!isMyServiceRunning(NetworkCallIntentService.class)) {
if (isNetworkAvailable()) {
showLoading();
Intent service = new Intent(getApplicationContext(), NetworkCallIntentService.class);
service.setAction(NetworkCallTask.ACTION_TRIGGER_API_CALL);
startService(service);
item.setEnabled(false);
Log.d(TAG, "Fetching ticker details...");
} else {
mPriceData = new String[1];
mPriceData[0] = "Empty Data";
CurrencyPriceAdapter adapter = new CurrencyPriceAdapter();
adapter.setPriceData(mPriceData);
mRecyclerView.swapAdapter(adapter, true);
Toast.makeText(getApplicationContext(), "Unable to get data, No Internet Connection...", Toast.LENGTH_SHORT).show();
}
} else {
Log.d(TAG, "Request is processing...");
}
return true;
} else if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
| 46.85119 | 230 | 0.662686 |
ee5c06254d2871bc7500fb91770f12f0be177a24 | 1,574 | /**
* Copyright © 2019 hebelala ([email protected])
*
* 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.github.hebelala.tasking.actor.task.entity;
import com.github.hebelala.tasking.api.Response;
/**
* @author hebelala
*/
public class Business {
private String threadName;
private long startTime;
private long endTime;
private Response response;
private String message; // exception, etc
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getEndTime() {
return endTime;
}
public void setEndTime(long endTime) {
this.endTime = endTime;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| 21.861111 | 75 | 0.729352 |
c607768ca45ca32d6351b1544ec5b63d67d6f578 | 5,539 | package com.suchgame.stackz.gl.scenegraph.interaction;
import java.util.Stack;
import android.view.MotionEvent;
import com.suchgame.stackz.gl.RenderConfig;
import com.suchgame.stackz.gl.math.Vector;
/**
* InteractionEvents are used and generated when some interaction on
* the GL surface happens.
*
* @author Matthias Schicker
*
*/
public class InteractionEvent {
private static final int MAX_INTERACTION_EVENT_POOL_SIZE = 30;
public static final int MAX_POINTER_COUNT = 5;
public static final int LONG_CLICK = -1;
private static Stack<InteractionEvent> interactionEventPool = new Stack<InteractionEvent>();
private long time;
private int pointerCount = 0;
private float[][] pointers;
private int[] pointerIDs;
private float[][] downPoints;
private long downTime;
private int action = MotionEvent.ACTION_DOWN;
private boolean canceledByPointerCountChange;
private boolean tapRangeLeft = false;
public static InteractionEvent obtain(long frameNanoTime){
if (!interactionEventPool.isEmpty()){
InteractionEvent pop = interactionEventPool.pop();
pop.setTime(frameNanoTime);
return pop;
}
InteractionEvent ret = new InteractionEvent();
ret.setTime(frameNanoTime);
return ret;
}
private void setTime(long frameNanoTime) {
time = frameNanoTime;
}
/**
* Not directly creatable. Get one by calling "obtain". Always remember
* to recycle no longer used events.
*/
private InteractionEvent(){
pointers = new float[MAX_POINTER_COUNT][];
downPoints = new float[MAX_POINTER_COUNT][];
pointerIDs = new int[MAX_POINTER_COUNT];
for (int i = 0; i < MAX_POINTER_COUNT; i++){
pointers[i] = new float[2];
downPoints[i] = new float[2];
}
}
public void recycle() {
if (interactionEventPool.size() <= MAX_INTERACTION_EVENT_POOL_SIZE){
reset();
interactionEventPool.push(this);
}
}
public void set(InteractionEvent from) {
if (from == null) return;
downTime = from.downTime;
this.downPoints = from.downPoints.clone();
pointerCount = from.pointerCount;
for (int i = 0; i < MAX_POINTER_COUNT; i++){
Vector.set2(pointers[i], from.pointers[i]);
Vector.set2(downPoints[i], from.downPoints[i]);
pointerIDs[i] = from.pointerIDs[i];
}
action = from.action;
canceledByPointerCountChange = from.canceledByPointerCountChange;
tapRangeLeft = from.tapRangeLeft;
}
public void reset() {
time = 0;
}
public boolean isUpOrCancel() {
return action==MotionEvent.ACTION_UP || action==MotionEvent.ACTION_CANCEL;
}
public int getPointerCount() {
return pointerCount;
}
/**
* The framework will translate a pointer count change into a cancel
* event for the old pointer count, and a new down event for the new pointer
* count. Query this method, to check whether this just happened. Only
* valid results when getAction() delviders ACTION_CANCEL.
*/
public boolean isCanceledByPointerCountChange() {
return canceledByPointerCountChange;
}
public void setCanceledEvent() {
canceledByPointerCountChange = true;
tapRangeLeft = true;
action = MotionEvent.ACTION_CANCEL;
}
public void setPointerCountChangeDownEvent(MotionEvent me) {
pointerCount = Math.min(MAX_POINTER_COUNT, me.getPointerCount());
for (int i = pointerCount; i < MAX_POINTER_COUNT; i++) pointerIDs[i] = -1;
setPointers(downPoints, pointerCount, me);
setPointers(pointers, pointerCount, me);
tapRangeLeft = true;
downTime = System.currentTimeMillis();
action = MotionEvent.ACTION_DOWN;
}
private void setPointers(float[][] toSet, int pointerCount, MotionEvent me){
int i = 0;
for (; i < pointerCount; i++){
toSet[i][0] = me.getX(i);
toSet[i][1] = me.getY(i);
pointerIDs[i] = me.getPointerId(i);
}
for (; i < MAX_POINTER_COUNT; i++) pointerIDs[i] = -1;
}
/**
* The last down in System.millis
*/
public long getDownTime() {
return downTime;
}
public float[][] getPointers() {
return pointers;
}
public int[] getPointerIDs(){
return pointerIDs;
}
public float[][] getDownPoints() {
return downPoints;
}
public void set(MotionEvent me) {
pointerCount = Math.min(MAX_POINTER_COUNT, me.getPointerCount());
setPointers(pointers, pointerCount, me);
action = me.getAction();
if (action == MotionEvent.ACTION_DOWN){
downTime = System.currentTimeMillis();
setPointers(downPoints, pointerCount, me);
}
}
@Override
public String toString() {
return actionToString() + ", " + pointerCount + " pointers";
}
private String actionToString() {
switch (action) {
case MotionEvent.ACTION_DOWN:
return "DOWN";
case MotionEvent.ACTION_UP:
return "UP";
case MotionEvent.ACTION_CANCEL:
return "CANCEL";
case MotionEvent.ACTION_MOVE:
return "MOVE";
case LONG_CLICK:
return "LONG_CLICK";
}
return "??";
}
public void setLongClick() {
this.action = LONG_CLICK;
}
public void setAction(int action2) {
this.action = action2;
}
public int getAction() {
return action;
}
public boolean wasTapRangeLeft() {
return tapRangeLeft;
}
/**
* Call this after the construction and setting of an interaction event is done.
* This will trigger some computations to decide, whether this might still be a tap
* or is (possibly) even a double tap.
*/
public void compute() {
for (int i = 0; i < pointerCount; i++){
tapRangeLeft |= Vector.distance2(downPoints[i], pointers[i]) > RenderConfig.TAP_DISTANCE;
}
}
public long getTime() {
return time;
}
public void setTapRangeLeft() {
tapRangeLeft = true;
}
}
| 24.50885 | 93 | 0.709153 |
3320fe4728740a70eb3aa33a2945c22dc8a43a97 | 1,565 | package com.company.sampler.web.screens;
import com.company.sampler.entity.*;
import com.haulmont.cuba.gui.model.CollectionContainer;
import com.haulmont.cuba.gui.screen.Screen;
import com.haulmont.cuba.gui.screen.Subscribe;
import com.haulmont.cuba.gui.screen.UiController;
import com.haulmont.cuba.gui.screen.UiDescriptor;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
@UiController("sampler_PivotSampleScreen")
@UiDescriptor("pivot-sample-screen.xml")
public class PivotSampleScreen extends Screen {
@Inject
private CollectionContainer<Tip> tipsDc;
@Subscribe
protected void onInit(InitEvent event) {
List<Tip> items = new ArrayList<>();
items.add(tips(1, 16.99, 1.01, Sex.FEMALE, Smoker.NO, Day.FRI, Time.DINNER, 2));
items.add(tips(2, 10.34, 1.66, Sex.FEMALE, Smoker.YES, Day.THU, Time.LUNCH, 3));
items.add(tips(3, 21.01, 3.5, Sex.MALE, Smoker.YES, Day.FRI, Time.LUNCH, 3));
items.add(tips(4, 23.68, 3.31, Sex.FEMALE, Smoker.NO, Day.MON, Time.DINNER, 2));
items.add(tips(5, 24.59, 3.61, Sex.MALE, Smoker.NO, Day.TUE, Time.LUNCH, 4));
tipsDc.setItems(items);
}
private Tip tips(int row, double totalBill, double tip, Sex sex, Smoker smoker, Day day, Time time, int size) {
Tip tips = new Tip();
tips.setRow(row);
tips.setTotalBill(totalBill);
tips.setTip(tip);
tips.setSex(sex);
tips.setSmoker(smoker);
tips.setDay(day);
tips.setTime(time);
tips.setSize(size);
return tips;
}
}
| 34.777778 | 114 | 0.68115 |
cf315b6ed183bf433c717bfc8a694bf93c3600b0 | 3,293 | /*-
* #%L
* CosmosDB Persistence Testing
* %%
* Copyright (C) 2005 - 2021 Daniel Sagenschneider
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.officefloor.nosql.cosmosdb.test;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Method;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManagerFactory;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.implementation.Configs;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
/**
* Allows use of self signed certificate for connecting to Cosmos.
*
* @author Daniel Sagenschneider
*/
public class CosmosSelfSignedCertificate extends Configs {
/**
* Avoid Open SSL due to Cosmos incompatibilities with Netty.
*/
public static void noOpenSsl() {
System.setProperty("io.netty.handler.ssl.noOpenSsl", "true");
}
/**
* Initialises the {@link CosmosClientBuilder}.
*
* @param clientBuilder {@link CosmosClientBuilder} to initialise.
* @param certificate Certificate to Cosmos DB emulator.
* @throws Exception If fails to create {@link SslContext}.
*/
public static void initialise(CosmosClientBuilder clientBuilder, String certificate) throws Exception {
Method configs = CosmosClientBuilder.class.getDeclaredMethod("configs", new Class[] { Configs.class });
configs.setAccessible(true);
configs.invoke(clientBuilder, new CosmosSelfSignedCertificate(certificate));
}
/**
* {@link SslContext}.
*/
private final SslContext sslContext;
/**
* Initialise.
*
* @param certificate Certificate to Cosmos DB emulator.
* @throws Exception If fails to create {@link SslContext}.
*/
private CosmosSelfSignedCertificate(String certificate) throws Exception {
// Create the key store
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
X509Certificate x509Certificate = (X509Certificate) CertificateFactory.getInstance("X509")
.generateCertificate(new ByteArrayInputStream(certificate.getBytes()));
keyStore.setCertificateEntry("Cosmos DB Emulator", x509Certificate);
// Create the trust store for the certificate
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// Create the SSL context
this.sslContext = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustManagerFactory)
.build();
}
/*
* ======================== Configs =======================
*/
@Override
public SslContext getSslContext() {
return this.sslContext;
}
}
| 31.361905 | 112 | 0.746128 |
fe1cebd8577f774aba197edaff7f25c272e1a580 | 1,352 | package org.devgateway.toolkit.forms.wicket.page.validator;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import org.devgateway.toolkit.persistence.dao.FileMetadata;
import java.util.Set;
public class InputFileValidator implements IValidator<Set<FileMetadata>> {
private static final long serialVersionUID = -2412508063601996929L;
public static final int FILENAME_LENGTH = 50;
private String errorFileNotAdded;
private String errorFilenameError;
public InputFileValidator(String errorFileNotAdded, String errorFilenameError) {
this.errorFileNotAdded = errorFileNotAdded;
this.errorFilenameError = errorFilenameError;
}
@Override
public void validate(final IValidatable<Set<FileMetadata>> validatable) {
if (validatable.getValue().isEmpty()) {
ValidationError error = new ValidationError(errorFileNotAdded);
validatable.error(error);
} else {
validatable.getValue().stream().forEach(file -> {
if (file.getName().length() > FILENAME_LENGTH) {
ValidationError error = new ValidationError(errorFilenameError);
validatable.error(error);
}
});
}
}
} | 35.578947 | 84 | 0.697485 |
e70ec087e4259ce35cd9f41af38592224e5e5120 | 1,293 | /*
* Created on Jan 3, 2005
*/
package com.fruits.netstle.aop.framework;
import com.fruits.netstle.aop.AroundAdvice;
/**
* @author [email protected]
*/
public class AroundAdviceNode {
private AroundAdvice aroundAdvice;
private AroundAdviceNode nextNode;
public AroundAdviceNode() {
}
public AroundAdviceNode(AroundAdvice aroundAdvice) {
this.aroundAdvice = aroundAdvice;
}
public void setAroundAdvice(AroundAdvice currentNode) {
aroundAdvice = currentNode;
}
public AroundAdvice getAroundAdvice() {
return aroundAdvice;
}
public void setNextNode(AroundAdviceNode nextNode) {
this.nextNode = nextNode;
}
public AroundAdviceNode getNextNode() {
return nextNode;
}
private static AroundAdviceNode head = null;
private static AroundAdviceNode lastNode = null;
public static AroundAdviceNode getLastNode() {
if (lastNode == null) {
lastNode = head;
return lastNode;
}
lastNode = lastNode.getNextNode();
return lastNode;
}
public static void addAroundAdvice(AroundAdvice aroundAdvice) {
if (null == head) {
head = new AroundAdviceNode(aroundAdvice);
} else {
AroundAdviceNode tmp = head;
while (null != tmp.getNextNode()) {
tmp = tmp.getNextNode();
}
tmp.setNextNode(new AroundAdviceNode(aroundAdvice));
}
}
}
| 20.854839 | 64 | 0.730085 |
d8ed675339162f213e37a8f97459e3776cf2e396 | 909 | package kr.msleague.mslibrary.customitem.impl.node;
import kr.msleague.mslibrary.customitem.api.ItemElement;
import kr.msleague.mslibrary.customitem.api.ItemNode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class MSLItemData implements kr.msleague.mslibrary.customitem.api.MSItemData {
@Getter
final ItemNode nodes;
@Override
public int getID() {
ItemElement element = nodes.get("id");
if (element == null)
throw new IllegalArgumentException("this item have not id");
else
return element.asValue().getAsInt();
}
@Override
public long getVersion() {
ItemElement element = nodes.get("version");
if (element == null)
throw new IllegalArgumentException("this item have not version");
else
return element.asValue().getAsInt();
}
}
| 27.545455 | 85 | 0.678768 |
edf00538c0c5834d1af1e2cb4fa9eb9d5c006421 | 2,688 | package ru.job4j.generic.container.array.simple;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Generic wrapper for container.
*/
public class SimpleArray<T> implements Iterable<T> {
/**
* Storing data.
*/
private Object[] data;
/**
* Current index position.
*/
private int cursor = 0;
/**
* Constructor.
* @param n - number of elements in container (data member);
*/
public SimpleArray(int n) {
data = new Object[n];
}
/**
* Add element in container.
* @param e - new element.
*/
public void add(T e) {
if (cursor == data.length) {
throw new ArrayStoreException();
}
data[cursor++] = e;
}
/**
* Number of elements in container.
* @return - number of elements.
*/
public int getSize() {
return cursor;
}
/**
* Reserved size.
* @return - reserved size.
*/
public int capacity() {
return data.length;
}
/**
* Set element in [index] place.
* @param index - index of element ini container.
* @param e - element.
*/
public void set(int index, T e) {
if (index > cursor - 1) {
throw new IndexOutOfBoundsException();
}
data[index] = e;
}
/**
* Delete element at index place.
*/
public void delete(int index) {
if (index > cursor - 1) {
throw new IndexOutOfBoundsException();
}
if (index < cursor - 1) {
for (int i = index + 1; i < cursor; i++) {
data[i - 1] = data[i];
}
}
cursor--;
}
/**
* Get element from container at index position.
* @param index - index of element.
* @return element.
*/
public T get(int index) {
if (index > cursor) {
throw new IndexOutOfBoundsException();
}
return (T) data[index];
}
@Override
public Iterator<T> iterator() {
return new SimpleArrayIterator<T>(this);
}
/**
* Simple container iterator.
* @param <T>
*/
class SimpleArrayIterator<T> implements Iterator<T> {
SimpleArray<T> array;
int cursor = 0;
SimpleArrayIterator(SimpleArray<T> array) {
this.array = array;
}
@Override
public boolean hasNext() {
return cursor < array.getSize();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return array.get(cursor++);
}
}
}
| 21 | 64 | 0.508557 |
2371f2a6b2e6159d754c630315162eb22f2c95a2 | 1,187 | /*
* Copyright 2014, Armenak Grigoryan, and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package com.strider.datadefender.requirement.registry;
import com.strider.datadefender.database.IDbFactory;
/**
* Configures a member variable IDbFactory in a concrete 'initialize' method.
*
* @author Zaahid Bateson <[email protected]>
*/
public abstract class DatabaseAwareRequirementFunction extends RequirementFunction {
protected IDbFactory dbFactory;
public final void initialize(IDbFactory dbFactory) {
this.dbFactory = dbFactory;
}
}
| 35.969697 | 84 | 0.764954 |
a568d4210081458a2754a950efca49126bb5f250 | 274 | package gov.nist.drmf.interpreter.common.cas;
import java.util.Collection;
/**
* @author Andre Greiner-Petter
*/
public class GenericCommandBuilder {
public static String makeListWithDelimiter(Collection<String> els) {
return String.join(", ", els);
}
}
| 21.076923 | 72 | 0.711679 |
8200b9c72ce0d4ce5040b030afa1622003a8cfbc | 1,113 | package org.pcsoft.plugins.intellij.iss.language.parser.psi.element;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.pcsoft.plugins.intellij.iss.language.IssFileType;
import org.pcsoft.plugins.intellij.iss.language.IssLanguage;
import javax.swing.*;
/**
* Created by Christoph on 30.09.2016.
*/
public class IssFile extends PsiFileBase {
public IssFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, IssLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() {
return IssFileType.INSTANCE;
}
@Override
public String toString() {
return "Inno Setup Script File";
}
@Override
public Icon getIcon(int flags) {
return super.getIcon(flags);
}
@Nullable
public IssSection[] getSections() {
return PsiTreeUtil.getChildrenOfType(this, IssSection.class);
}
}
| 25.883721 | 69 | 0.727763 |
fb45b5dd325da59bba27880ead60f337ba10895f | 1,380 | package samebutdifferent.ecologics.data;
import com.google.common.collect.ImmutableList;
import com.mojang.datafixers.util.Pair;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.loot.LootTableProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.ValidationContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class LootTableGenerator extends LootTableProvider {
List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>> table = ImmutableList.of(Pair.of(samebutdifferent.ecologics.data.ModBlockLoot::new, LootContextParamSets.BLOCK));
public LootTableGenerator(DataGenerator generator) {
super(generator);
}
@Override
protected List<Pair<Supplier<Consumer<BiConsumer<ResourceLocation, LootTable.Builder>>>, LootContextParamSet>> getTables() {
return this.table;
}
@Override
protected void validate(Map<ResourceLocation, LootTable> map, ValidationContext validationtracker) {
}
}
| 39.428571 | 218 | 0.805797 |
44429393b0c1a408cecad33338c0dd9489cf6067 | 3,958 | package com.obsidiandynamics.meteor;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.stream.*;
import org.junit.*;
import com.hazelcast.config.*;
import com.hazelcast.core.*;
import com.hazelcast.ringbuffer.*;
import com.hazelcast.test.*;
public final class AddAsyncOrderTest {
@Test
public void test() throws InterruptedException, ExecutionException {
assumeTrue(false);
final int numInstances = 4; // only fails with multiple instances
final int iterations = 10; // sometimes takes a few iterations to fail
final int itemsPerIteration = 100; // how many items will be added to the buffer
for (int iteration = 0; iteration < iterations; iteration++) {
System.out.println("iteration=" + iteration);
// configure and prestart a bunch of instances
final List<HazelcastInstance> instances = new ArrayList<>(numInstances);
final Config config = new Config()
.setProperty("hazelcast.logging.type", "none")
.addRingBufferConfig(new RingbufferConfig().setName("default").setBackupCount(3).setCapacity(itemsPerIteration));
final TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory();
IntStream.range(0, numInstances).parallel().forEach(i -> instances.add(factory.newHazelcastInstance(config)));
// get a ringbuffer from one of the instances
final HazelcastInstance instance = instances.get(iteration % numInstances);
final Ringbuffer<Integer> ring = instance.getRingbuffer("buffer-" + iteration);
// send all the items and await all callbacks with a countdown latch
final CountDownLatch latch = new CountDownLatch(itemsPerIteration);
final AtomicReference<AssertionError> error = new AtomicReference<>();
final int _iteration = iteration;
for (int item = 0; item < itemsPerIteration; item++) {
// send each item one by one and compare its queued number with the allocated sequence number
final ICompletableFuture<Long> writeFuture = ring.addAsync(item, OverflowPolicy.FAIL);
final int _item = item;
writeFuture.andThen(new ExecutionCallback<Long>() {
@Override
public void onResponse(Long sequence) {
// the callback may be called out of order, which is perfectly fine; but the sequence numbers
// must match the order in which the items were enqueued
try {
assertEquals(_item, (long) sequence);
} catch (AssertionError e) {
// if we detect a problem, save the AssertionError as the unit test is running in a different thread
System.err.println("SEQUENCE OUT OF ORDER: item=" + _item + ", sequence=" + sequence + ", iteration=" + _iteration);
error.set(e);
} finally {
latch.countDown();
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
}
// wait for all callbacks
latch.await();
// assert correct order by reading from the buffer
final ICompletableFuture<ReadResultSet<Integer>> readFuture = ring.readManyAsync(0, itemsPerIteration, 1000, null);
final ReadResultSet<Integer> readResultSet = readFuture.get();
assertEquals(itemsPerIteration, readResultSet.size());
for (int itemIndex = 0; itemIndex < itemsPerIteration; itemIndex++) {
final int readItem = readResultSet.get(itemIndex);
assertEquals(itemIndex, readItem);
}
// clean up
instances.forEach(inst -> inst.getLifecycleService().terminate());
// check if any assertion errors were observed during the run
if (error.get() != null) {
throw error.get();
}
}
}
}
| 42.106383 | 130 | 0.660182 |
7e98304d8ab9bbe55d659875f7f0807327ed60a7 | 3,089 | package core;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* GroupStatistics computes statistics for multiple sets of data. It keeps track of values for multiple
* sets of values. The only thing required is that the number of values per set is exactly the same.
*
* It does not keep record in memory of each value added for computation. The statistics are computed on
* the fly and, therefore, the collection of statistics that can be performed is limited to the ones that
* can be computed incrementally.
*/
public class GroupStatistics {
private final List<SummaryStatistics> itemsStatistics;
/**
* Creates a GroupStatistics with a specified number of data sets.
*
* @param dataSetCount the number of different data sets to compute for.
*/
public GroupStatistics(int dataSetCount) {
itemsStatistics = new ArrayList<>(dataSetCount);
for (int i = 0; i < dataSetCount; i++) {
itemsStatistics.add(new SummaryStatistics());
}
}
/**
* Adds a new entry of values for each data set. The input values must be always in the same order.
*
* @param values the list with the values for each data set, not null.
*/
public void addEntry(List<Double> values) {
if (values.size() != itemsStatistics.size()) {
throw new IllegalArgumentException("Group statistics expected " + itemsStatistics.size() + " " +
"items but got " + values.size());
}
for (int i = 0; i < values.size(); i++) {
itemsStatistics.get(i).addValue(values.get(i)); // there is not ned to check the get method call!
}
}
/**
* Returns the number of values in each data set.
*
* @return the number of values in each data set.
*/
public long getCount() {
return itemsStatistics.get(0).getN();
}
/**
* Returns a list with the means for each data set. The returned list includes the means in the same
* order as the values added to the GroupStatistics.
*
* @return the list with the means for each data set, not null.
*/
public List<Double> getMeans() {
return itemsStatistics.stream()
.map(SummaryStatistics::getMean)
.collect(Collectors.toList());
}
/**
* Returns a list with the standard deviations for each data set. The returned list includes the standard
* deviations in the same order as the values added to the GroupStatistics.
*
* @return the list with the standard deviations for each data set, not null.
*/
public List<Double> getStandardDeviations() {
return itemsStatistics.stream()
.map(SummaryStatistics::getStandardDeviation)
.collect(Collectors.toList());
}
/**
* Clears all statistics for all data sets.
*/
public void clear() {
itemsStatistics.forEach(SummaryStatistics::clear);
}
}
| 33.215054 | 109 | 0.64843 |
7bb43018047757cc4e5a81504a2871b77864d023 | 1,262 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.library.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.service.TreeService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.library.entity.SelfLibrary;
import com.thinkgem.jeesite.modules.library.dao.SelfLibraryDao;
/**
* 图书馆楼层分布Service
* @author wp
* @version 2018-04-08
*/
@Service
@Transactional(readOnly = true)
public class SelfLibraryService extends TreeService<SelfLibraryDao, SelfLibrary> {
public SelfLibrary get(String id) {
return super.get(id);
}
public List<SelfLibrary> findList(SelfLibrary selfLibrary) {
if (StringUtils.isNotBlank(selfLibrary.getParentIds())){
selfLibrary.setParentIds(","+selfLibrary.getParentIds()+",");
}
return super.findList(selfLibrary);
}
@Transactional(readOnly = false)
public void save(SelfLibrary selfLibrary) {
super.save(selfLibrary);
}
@Transactional(readOnly = false)
public void delete(SelfLibrary selfLibrary) {
super.delete(selfLibrary);
}
} | 27.434783 | 108 | 0.770998 |
333a5c0e0f5076f747c9b0e52c96cbc2754cfd84 | 2,223 | package andexam.ver4_1.c21_actionbar;
import android.app.*;
import android.app.ActionBar.Tab;
import android.os.*;
import android.view.*;
import android.widget.*;
import andexam.ver4_1.*;
public class ActionTab extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actiontab);
ActionBar ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=0;i<3;i++) {
ActionBar.Tab tab = ab.newTab();
String Cap = "Tab" + (i + 1);
tab.setText(Cap);
TabFragment frag = TabFragment.newInstance(Cap);
tab.setTabListener(new TabListener(frag));
ab.addTab(tab);
}
if (savedInstanceState != null) {
int seltab = savedInstanceState.getInt("seltab");
ab.setSelectedNavigationItem(seltab);
}
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("seltab", getActionBar().getSelectedNavigationIndex());
}
private class TabListener implements ActionBar.TabListener {
private Fragment mFragment;
public TabListener(Fragment fragment) {
mFragment = fragment;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.tabparent, mFragment, "tag");
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(mFragment);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
public static class TabFragment extends Fragment {
public static TabFragment newInstance(String text) {
TabFragment frag = new TabFragment();
Bundle args = new Bundle();
args.putString("text", text);
frag.setArguments(args);
return frag;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String text = "";
Bundle args = getArguments();
if (args != null) {
text = args.getString("text");
}
View linear = inflater.inflate(R.layout.actiontabfragment, container, false);
TextView textview = (TextView)linear.findViewById(R.id.content);
textview.setText(text);
return linear;
}
}
}
| 25.848837 | 81 | 0.692758 |
296b40cd16ba69ce4319457c889062cba3f14d72 | 9,812 | package com.smart.smarthome.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.smart.smarthome.R;
import com.smart.smarthome.base.BaseActivity;
import com.smart.smarthome.helper.AlarmTaskHelper;
import com.smart.smarthome.model.MenuModel;
import com.smart.smarthome.service.AlarmService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MenuShow extends BaseActivity {
@BindView(R.id.btn_onoff)
Button btn_onoff;
@BindView(R.id.txt_seekbar)
TextView txt_seekbar;
@BindView(R.id.seekbar)
SeekBar seekbar;
DatabaseReference db;
ArrayList<MenuModel> list;
AlarmTaskHelper alarmTaskHelper;
int button_value, seeksingle = 0, seekbars;
private String menuid,choosetime,menuname;
int value_seekbar;
Calendar takvim;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_show);
ButterKnife.bind(this);
menuid = getIntent().getStringExtra("menuid");
db = FirebaseDatabase.getInstance().getReference("menuler").child(menuid);
getValueMenu();
alarmTaskHelper = new AlarmTaskHelper(this);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
txt_seekbar.setText("%" + progress);
seekbars = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
list = new ArrayList<MenuModel>();
//Log.d("authorize","MenuShow: getList"+alarmTaskHelper.alarmSaveShared.getAlarm());
}
@OnClick(R.id.btn_onoff)
void btn_onoffClick() {
if (button_value == 1) {
db.child("onoff").setValue(0);
buttonControlBorder(0);
} else {
db.child("onoff").setValue(1);
buttonControlBorder(1);
}
}
@OnClick(R.id.btn_alarm_add) void btn_alarm_addClick(){
// Şimdiki zaman bilgilerini alıyoruz. güncel saat, güncel dakika.
takvim = Calendar.getInstance();
int saat = takvim.get(Calendar.HOUR_OF_DAY);
int dakika = takvim.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if(minute<10){
choosetime = hourOfDay+":0"+minute;
} else {
choosetime = hourOfDay+":"+minute;
}
setAlarmDialog(choosetime);
takvim.set(takvim.get(Calendar.YEAR),takvim.get(Calendar.MONTH),
takvim.get(Calendar.DAY_OF_MONTH),
hourOfDay,minute,0);
}
}, saat, dakika, true);
timePickerDialog.setButton(TimePickerDialog.BUTTON_POSITIVE, "Seç", timePickerDialog);
timePickerDialog.setButton(TimePickerDialog.BUTTON_NEGATIVE, "İptal", timePickerDialog);
timePickerDialog.show();
}
@OnClick(R.id.btn_save1)
void btn_save1Click() {
db.child("seekbar").setValue(seekbars);
message("Kayıt Edildi");
seekbarControlBorder(seekbars);
}
@OnClick(R.id.btn_menu_delete)
void btn_menu_deleteClick(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Menüyü silmek mi istiyorsunuz?");
builder.setPositiveButton("Sil", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
db.removeValue();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
});
builder.setNegativeButton("Hayır", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
private void getValueMenu() {
db.addValueEventListener(new ValueEventListener() {
MenuModel menuModel;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
menuModel = dataSnapshot.getValue(MenuModel.class);
getSupportActionBar().setTitle(menuModel.getMenuad()+" (Menu id="+menuid+")");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
menuname = menuModel.getMenuad();
if (seeksingle == 0) {
seeksingle++;
seekbar.setProgress(menuModel.getSeekbar());
txt_seekbar.setText("%" + menuModel.getSeekbar());
}
button_value = menuModel.getOnoff();
if (menuModel.getOnoff() == 1) {
btn_onoff.setText("Açık");
btn_onoff.setBackground(getResources().getDrawable(R.drawable.button_bg_on));
} else {
btn_onoff.setText("Kapalı");
btn_onoff.setBackground(getResources().getDrawable(R.drawable.button_bg_off));
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void setAlarmDialog(String hour){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_set_alarm);
Button btn_onoff1 = dialog.findViewById(R.id.btn_onoff1);
TextView txt_seekbar1 = dialog.findViewById(R.id.txt_seekbar1);
Button btn_save1 = dialog.findViewById(R.id.btn_save1);
SeekBar seekbar1 = dialog.findViewById(R.id.seekbar1);
seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
value_seekbar = progress;
txt_seekbar1.setText("%"+progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
btn_onoff1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message("Açık olmak zorunda");
}
});
btn_save1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(alarmTaskHelper.getAlarmList()!=null){
list = alarmTaskHelper.getAlarmList();
}
MenuModel menuModel = new MenuModel();
menuModel.setHour(hour);
menuModel.setMenuid(menuid);
menuModel.setMenuad(menuname);
menuModel.setOnoff(1);
menuModel.setSeekbar(value_seekbar);
list.add(menuModel);
alarmTaskHelper.setAlarmList(list);
message("Kayıt Edildi...");
setAlarm(takvim.getTimeInMillis());
dialog.dismiss();
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
public void setAlarm(long timemillies){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
Objects.requireNonNull(alarmManager).set(AlarmManager.RTC_WAKEUP,timemillies,pendingIntent);
}
private void seekbarControlBorder(int seekbar_val){
if(seekbar_val == 255){
db.child("onoff").setValue(1);
} else if(seekbar_val == 0){
db.child("onoff").setValue(0);
}
}
private void buttonControlBorder(int button_val){
if(button_val==1){
db.child("seekbar").setValue(255);
seekbar.setProgress(255);
txt_seekbar.setText("%" + 255);
} else{
db.child("seekbar").setValue(0);
seekbar.setProgress(0);
txt_seekbar.setText("%" + 0);
}
}
}
| 37.88417 | 113 | 0.618223 |
89b0c027fdcd24bef885817d975b4d3109fd6700 | 2,241 | /*
* Copyright 2017 Cycorp, Inc..
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyc.query.client.explanations;
/*
* #%L
* File: ProofViewImpl.java
* Project: Query Client
* %%
* Copyright (C) 2013 - 2018 Cycorp, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.cyc.query.ProofView;
import com.cyc.query.ProofViewNode;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author daves
*/
public class ProofViewImpl extends ProofViewNodeImpl implements ProofView {
// Construction
public ProofViewImpl(com.cyc.xml.query.ProofViewEntry entryJaxb, ProofViewGeneratorImpl proofView) {
super (null, entryJaxb, proofView);
}
// Public
public Map<ProofViewNodePath, ProofViewNode> toMap() {
final Map<ProofViewNodePath, ProofViewNode> results = new HashMap();
addNodeToMap(this, results);
return results;
}
// Private
private void addNodeToMap(ProofViewNode node, Map<ProofViewNodePath, ProofViewNode> nodeMap) {
final ProofViewNodePath id = new ProofViewNodePathImpl(node);
nodeMap.put(id, node);
for (ProofViewNode child : node.getChildren()) {
addNodeToMap(child, nodeMap);
}
}
}
| 29.103896 | 102 | 0.719322 |
ce449a31343f710cac6e188fb88ccc086a44a51f | 1,553 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.datafactory.v2018_06_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for TeradataPartitionOption.
*/
public final class TeradataPartitionOption extends ExpandableStringEnum<TeradataPartitionOption> {
/** Static value None for TeradataPartitionOption. */
public static final TeradataPartitionOption NONE = fromString("None");
/** Static value Hash for TeradataPartitionOption. */
public static final TeradataPartitionOption HASH = fromString("Hash");
/** Static value DynamicRange for TeradataPartitionOption. */
public static final TeradataPartitionOption DYNAMIC_RANGE = fromString("DynamicRange");
/**
* Creates or finds a TeradataPartitionOption from its string representation.
* @param name a name to look for
* @return the corresponding TeradataPartitionOption
*/
@JsonCreator
public static TeradataPartitionOption fromString(String name) {
return fromString(name, TeradataPartitionOption.class);
}
/**
* @return known TeradataPartitionOption values
*/
public static Collection<TeradataPartitionOption> values() {
return values(TeradataPartitionOption.class);
}
}
| 34.511111 | 98 | 0.750161 |
4d10d6463b92c4b5457ecb659d5f179dbcb01c36 | 503 | package com.example.deserialization.springdeserializationdemo.Models;
public class AdminUser extends User{
public AdminUser(String username, String avatarFileName) {
super(username, avatarFileName);
}
@Override
public String listStatistics(){
// Fetch all user statistics from Database
return "\nuser1, Wins: 5, losses: 6, remis: 1,\n" +
"user2, Wins: 7, losses: 1, remis: 4,\n" +
"user3, Wins: 2, losses: 7, remis: 0";
}
}
| 31.4375 | 69 | 0.628231 |
e64ff1fa2d4e332a230694a7af872eeb22f15370 | 8,102 | /* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.server.utilities;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.fcrepo.server.errors.InconsistentTableSpecException;
import org.fcrepo.utilities.XmlTransformUtility;
/**
* A holder of table specification information that helps in producing
* RDBMS-generic DDL "CREATE TABLE" commands.
*
* <p>An application constructs a TableSpec without regard to the underlying
* database kind, and then the TableSpec is converted to a DB-specific CREATE
* TABLE DDL command by a DDLConverter before the command is issued via JDBC.
*
* @author Chris Wilper
*/
public class TableSpec {
private final String m_name;
private final List<ColumnSpec> m_columnSpecs;
private final String m_primaryColumnName;
private String m_type;
/**
* Constructs a TableSpec given a name, a set of ColumnSpecs, and the name
* of the primary key column.
*
* @param name
* The table name.
* @param columnSpecs
* ColumnSpec objects describing columns in the table.
* @param primaryColumnName
* The column that is the primary key for the table.
* @throws InconsistentTableSpecException
* if inconsistencies are detected in table specifications.
*/
public TableSpec(String name, List<ColumnSpec> columnSpecs, String primaryColumnName)
throws InconsistentTableSpecException {
m_name = name;
m_columnSpecs = columnSpecs;
m_primaryColumnName = primaryColumnName;
assertConsistent();
}
/**
* Constructs a TableSpec given a name, a set of ColumnSpecs, the name of
* the primary key column, and a table type. Table type specification is not
* supported by all RDBMS software, and is usually software-specific. When a
* tableSpec is used to create a table, if the type is understood it is
* used. Otherwise it is ignored.
*
* @param name
* The table name.
* @param columnSpecs
* ColumnSpec objects describing columns in the table.
* @param primaryColumnName
* The column that is the primary key for the table.
* @param type
* The table type.
* @throws InconsistentTableSpecException
* if inconsistencies are detected in table specifications.
*/
public TableSpec(String name,
List<ColumnSpec> columnSpecs,
String primaryColumnName,
String type)
throws InconsistentTableSpecException {
m_name = name;
m_columnSpecs = columnSpecs;
m_primaryColumnName = primaryColumnName;
m_type = type;
assertConsistent();
}
/**
* Gets a TableSpec for each table element in the stream, where the stream
* contains a valid XML document containing one or more table elements,
* wrapped in the root element.
*
* <p>
* Input is of the form:
*
* <pre>
* <database>
* <table name="<i>tableName</i>" primaryKey="<i>primaryColumnName</i>" type="<i>tableType</i>">
* <column name="<i>columnName</i>"
* type="<i>typeSpec</i>"
* autoIncrement="<i>isAutoIncremented</i>"
* index="<i>indexName</i>"
* notNull="<i>isNotNull</i>"
* unique="<i>isUnique</i>"
* default="<i>defaultValue</i>"
* foreignKey="<i>foreignTableName.columnName onDeleteAction</i>"/>
* </table>
* </database>
* </pre>
*
* About the attributes:
* <ul>
* <li> <b>tableName</b> - The desired name of the table.
* <li> <b>primaryColumnName</b> - Identifies column that is the primary
* key for the table. A column that is a primary key must be notNull, and
* can't be a foreign key.
* <li> <b>type</b> - The table type, which is RDBMS-specific. See
* TableSpec(String, Set, String, String) for detail.
* <li> <b>columnName</b> - The name of the column.
* <li> <b>typeSpec</b> - The value type of the column. For instance,
* varchar(255). This is not checked for validity. See <a
* href="ColumnSpec.html">ColumnSpec javadoc</a> for detail.
* <li> <b>isAutoIncremented</b> - (true|false) Whether values in the
* column should be automatically generated by the database upon insert.
* This requires that the type be some numeric variant, and is
* RDBMS-specific. NUMERIC will generally work.
* <li> <b>indexName</b> - Specifies that an index should be created on
* this column and provides the column name.
* <li> <b>isNotNull</b> - (true|false) Whether input should be limited to
* actual values.
* <li> <b>isUnique</b> - (true|false) Whether input should be limited such
* that all values in the column are unique.
* <li> <b>default</b> - The value to be used when inserts don't specify a
* value for the column. This cannot be specified with autoIncrement true.
* <li> <b>foreignTableName.column</b> - Specifies that this is a foreign
* key column and identifies the (primary key) column in the database
* containing the rows that values in this column refer to. This cannot be
* specified with autoIncrement true.
* <li> <b>onDeleteAction</b> - Optionally specifies a "CASCADE" or "SET
* NULL" action to be taken on matching rows in this table when a row from
* the parent (foreign) table is deleted. If "CASCADE", matching rows in
* this table are automatically deleted. If "SET NULL", this column's value
* will be set to NULL for all matching rows. This value is not checked for
* validity.
* </ul>
*
* @param in
* The xml-encoded table specs.
* @return TableSpec objects.
* @throws InconsistentTableSpecException
* if inconsistencies are detected in table specifications.
* @throws IOException
* if an IO error occurs.
*/
public static List<TableSpec> getTableSpecs(InputStream in)
throws InconsistentTableSpecException, IOException {
try {
TableSpecDeserializer tsd = new TableSpecDeserializer();
XmlTransformUtility.parseWithoutValidating(in, tsd);
tsd.assertTableSpecsConsistent();
return tsd.getTableSpecs();
} catch (InconsistentTableSpecException itse) {
throw itse;
} catch (Exception e) {
throw new IOException("Error parsing XML: " + e.getMessage());
}
}
/**
* Ensures that the TableSpec is internally consistent.
*
* @throws InconsistentTableSpecException
* If it's inconsistent.
*/
@SuppressWarnings("unused")
public void assertConsistent() throws InconsistentTableSpecException {
if (1 == 2) {
throw new InconsistentTableSpecException("hmm");
}
}
/**
* Gets the name of the table.
*
* @return The name.
*/
public String getName() {
return m_name;
}
/**
* Gets the name of the primary key column.
*
* @return The name.
*/
public String getPrimaryColumnName() {
return m_primaryColumnName;
}
/**
* Gets the type of the table.
*
* @return The name.
*/
public String getType() {
return m_type;
}
/**
* Gets an iterator over the columns.
*
* @return An Iterator over ColumnSpec objects.
*/
public Iterator<ColumnSpec> columnSpecIterator() {
return m_columnSpecs.iterator();
}
}
| 36.995434 | 138 | 0.632807 |
8ea3e31b2b651343da840a3e1999e551704d4cdc | 1,619 | // -----------------------------------------------------------------------
// <copyright file="CustomerLicensesInsightsBase.java" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
package com.microsoft.store.partnercenter.models.analytics;
/**
* Class that represents the currency related information.
*/
public abstract class CustomerLicensesInsightsBase
{
/**
* Gets or sets The customer identifier.
*/
private String customerId;
public String getCustomerId()
{
return customerId;
}
public void setCustomerId( String value )
{
customerId = value;
}
/**
* Gets or sets the Customer Name.
*/
private String customerName;
public String getCustomerName()
{
return customerName;
}
public void setCustomerName( String value )
{
customerName = value;
}
/**
* Gets or sets the product/plan name of the given service. (Example: OFFICE 365 BUSINESS ESSENTIALS).
*/
private String productName;
public String getProductName()
{
return productName;
}
public void setProductName( String value )
{
productName = value;
}
/**
* Gets or sets the Service Code of the License. Example (Office 365 : O365).
*/
private String serviceCode;
public String getServiceCode()
{
return serviceCode;
}
public void setServiceCode( String value )
{
serviceCode = value;
}
} | 22.178082 | 106 | 0.572576 |
27c678a00f8d1c9804b2cc0969105e946cf00c31 | 2,370 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|contrib
operator|.
name|udaf
operator|.
name|example
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|Lists
import|;
end_import
begin_class
specifier|public
class|class
name|TestUDAFExampleMaxMinNUtil
block|{
annotation|@
name|Test
argument_list|(
name|timeout
operator|=
literal|5000
argument_list|)
specifier|public
name|void
name|testSortedMerge
parameter_list|()
block|{
name|List
name|li1
init|=
name|Lists
operator|.
name|newArrayList
argument_list|(
literal|1
argument_list|,
literal|2
argument_list|,
literal|3
argument_list|,
literal|4
argument_list|,
literal|5
argument_list|)
decl_stmt|;
name|List
name|li2
init|=
name|Lists
operator|.
name|newArrayList
argument_list|(
literal|1
argument_list|,
literal|2
argument_list|,
literal|3
argument_list|,
literal|4
argument_list|,
literal|5
argument_list|)
decl_stmt|;
name|UDAFExampleMaxMinNUtil
operator|.
name|sortedMerge
argument_list|(
name|li1
argument_list|,
name|li2
argument_list|,
literal|true
argument_list|,
literal|5
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
| 18.230769 | 813 | 0.789451 |
b8a39773f899b2126ed819372b83308315b7c16a | 11,586 | /*
Copyright 2012-2013, Polyvi Inc. (http://polyvi.github.io/openxface)
This program is distributed under the terms of the GNU General Public License.
This file is part of xFace.
xFace is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
xFace is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with xFace. If not, see <http://www.gnu.org/licenses/>.
*/
package com.polyvi.xface;
import java.io.IOException;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.polyvi.xface.app.XAppInfo;
import com.polyvi.xface.app.XApplication;
import com.polyvi.xface.app.XApplicationCreator;
import com.polyvi.xface.app.XIApplication;
import com.polyvi.xface.configXml.XTagNotFoundException;
import com.polyvi.xface.core.XConfiguration;
import com.polyvi.xface.core.XISystemContext;
import com.polyvi.xface.event.XEvent;
import com.polyvi.xface.event.XEventType;
import com.polyvi.xface.event.XSystemEventCenter;
import com.polyvi.xface.ssl.XSSLManager;
import com.polyvi.xface.util.XConstant;
import com.polyvi.xface.util.XLog;
import com.polyvi.xface.util.XNotification;
import com.polyvi.xface.util.XUtils;
import com.polyvi.xface.view.XAppWebView;
import com.polyvi.xface.view.XIceCreamWebViewClient;
import com.polyvi.xface.view.XStartAppView;
import com.polyvi.xface.view.XWebChromeClient;
import com.polyvi.xface.view.XWebViewClient;
/**
* 该类是android程序的主activity,也是整个程序的入口. 主要管理整个程序的生命周期以及执行程序的初始化操作
*/
public class XFaceMainActivity extends CordovaActivity implements
XISystemContext {
private static final String CLASS_NAME = XFaceMainActivity.class.getName();
private static final int ANDROID4_2_API_LEVEL = 17;
protected TextView mVersionText;
protected LinearLayout.LayoutParams mVersionParams;
private XNotification mWaitingNotification = new XNotification(this);;
private XStartParams mStartParams;
private XSecurityPolicy mSecurityPolicy;
/** App生成器 */
private XApplicationCreator mCreator;
/**
* 标示startapp
*/
private XApplication mStartApp;
private XApplication mCurrentApp;
private XSystemEventCenter mEventCenter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
systemBoot();
}
@Override
public XSystemEventCenter getEventCenter() {
return mEventCenter;
}
/**
* 初始化startapp
*
* @param appInfo
* startapp的信息
* @return
*/
public boolean initStartApp(XAppInfo appInfo) {
XIApplication app = mCreator.create(appInfo);
mStartApp = XApplicationCreator.toWebApp(app);
return true;
}
private void setCurrentAppView(XAppWebView curAppView) {
if (curAppView == null) {
this.appView = null;
this.webViewClient = null;
return;
}
this.appView = curAppView;
this.webViewClient = curAppView.getWebViewClient();
this.cancelLoadUrl = false;
this.appView.requestFocus();
}
@Override
public XApplication getStartApp() {
return mStartApp;
}
@Override
protected CordovaWebView makeWebView() {
XAppWebView webView = this.appView == null ? new XStartAppView(this) : new XAppWebView(this);
mCurrentApp.setView(webView);
return webView;
}
@Override
protected CordovaWebViewClient makeWebViewClient(CordovaWebView webView) {
CordovaWebViewClient webViewClient;
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
webViewClient = new XWebViewClient(this, webView);
} else {
webViewClient = new XIceCreamWebViewClient(this, webView);
}
return webViewClient;
}
@Override
protected CordovaChromeClient makeChromeClient(CordovaWebView webView) {
XWebChromeClient chrom = new XWebChromeClient(this, webView);
webView.setWebChromeClient(chrom);
return chrom;
}
public XApplicationCreator getAppFactory() {
return mCreator;
}
@Override
public Object onMessage(String id, Object data) {
if ("exit".equals(id)) {
XAppWebView xAppView = ((XAppWebView) appView);
int viewId = xAppView.getViewId();
XEvent evt = XEvent.createEvent(XEventType.CLOSE_APP, viewId);
mEventCenter.sendEventSync(evt);
return true;
} else if ("exit_engine".equals(id)) {
endActivity();
return true;
}
return super.onMessage(id, data);
}
/**
* 初始化系统事件处理器
*/
private void initSystemEventCenter() {
mEventCenter = new XSystemEventCenter(this);
}
/**
* 创建app安全策略
*
* @return 安全策略
*/
protected XSecurityPolicy createSecurityPolicy() {
return new XDefaultSecurityPolicy(this);
}
/**
* 创建系统启动组件
*
* @return
*/
protected XSystemBootstrap createSystemBootstrap() {
return new XSystemInitializer(this);
}
/**
* 创建管理与https有关证书库对象
*/
protected void createSSLManager() {
XSSLManager.createInstance(this);
}
/**
* 程序的入口函数
*/
private void systemBoot() {
initSystemEventCenter();
mCreator = new XApplicationCreator(this);
createSSLManager();
mSecurityPolicy = createSecurityPolicy();
XConfiguration.getInstance().loadPlatformStrings(getContext());
mStartParams = XStartParams.parse(getIntent().getStringExtra(
XConstant.TAG_APP_START_PARAMS));
// 解析系统配置
try {
initSystemConfig();
} catch (IOException e) {
this.toast("Loading System Config Failure.");
XLog.e(CLASS_NAME, "Loading system config failure!");
e.printStackTrace();
return;
} catch (XTagNotFoundException e) {
this.toast("Loading System Config Failure.");
XLog.e(CLASS_NAME, "parse config.xml error:" + e.getMessage());
e.printStackTrace();
return;
}
// 启动splash
startSplashScreen();
// 配置系统LOG等级
XLog.setLogLevel(XConfiguration.getInstance().readLogLevel());
// 配置系统的工作目录
XConfiguration.getInstance()
.configWorkDirectory(this, getWorkDirName());
XSystemBootstrap bootstrap = createSystemBootstrap();
new XPrepareWorkEnvronmentTask(bootstrap).execute();
}
/**
* 开始splash操作
*/
protected void startSplashScreen() {
this.splashscreenTime = this.getIntegerProperty("SplashScreenDelay",
this.splashscreenTime);
if (this.splashscreenTime > 0) {
this.splashscreen = this.getIntegerProperty("SplashScreen", 0);
if (this.splashscreen != 0) {
showSplashScreen(this.splashscreenTime);
}
}
}
@Override
public void unloadView(XAppWebView view) {
view.loadUrl("about:blank");
removeView(view);
}
/**
* 解析系统配置
*
* @throws IOException
* @throws XTagNotFoundException
*/
private void initSystemConfig() throws IOException, XTagNotFoundException {
XConfiguration.getInstance().readConfig(this);
}
/**
* 获得手机的deviceId
*
* @return
*/
protected String getKey() {
if (Build.VERSION.SDK_INT == ANDROID4_2_API_LEVEL) {
return null;
}
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String deviceID = tm.getDeviceId();
return deviceID;
}
/**
* 添加一个子视图到Activity的content view,如果view是可见的,则view会被显示在屏幕上
*
* @param view
* 子视图
*/
public void addView(XAppWebView view) {
if (view instanceof View) {
View subView = (View) view;
subView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 1.0F));
setCurrentAppView(view);
root.addView(subView);
}
}
@Override
public XAppWebView getCurAppView() {
return (XAppWebView) this.appView;
}
@Override
public void loadView(XApplication app, String url) {
mCurrentApp = app;
if (this.appView != null) {
this.init();
}
loadUrl(url);
}
public void loadUrl(String url) {
if (this.appView == null) {
this.init();
}
if (mCurrentApp.getAppInfo().getRunModeConfig().equals("online")
&& !XUtils.isOnline(this)) {
mCurrentApp.clearCache(false);
}
super.loadUrl(url);
}
/**
* 从Activity的content view中remove掉一个子视图
*
* @param view
* 子视图
*/
public void removeView(XAppWebView view) {
if (view instanceof View) {
root.removeView((View) view);
View pView = root.getChildAt(root.getChildCount() - 1);
if (pView != null && pView instanceof XAppWebView) {
XAppWebView pWebView = (XAppWebView) pView;
setCurrentAppView(pWebView);
} else {
setCurrentAppView(null);
}
}
}
/**
* 获取工作目录的名字
*
* @return
*/
protected String getWorkDirName() {
String packageName = getPackageName();
String workDir = XConfiguration.getInstance().getWorkDirectory(this,
packageName)
+ XConstant.PRE_INSTALL_SOURCE_ROOT;
return workDir;
}
@Override
public void runStartApp() {
getStartApp().start(getStartParams());
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public Context getContext() {
return this;
}
@Override
public void toast(String message) {
mWaitingNotification.toast(message);
}
@Override
public XStartParams getStartParams() {
return mStartParams;
}
@Override
protected void showSplashScreen(int time) {
if (splashDialog != null && splashDialog.isShowing()) {
return;
}
super.showSplashScreen(time);
}
@Override
public Activity getActivity() {
return this;
}
@Override
public XSecurityPolicy getSecurityPolicy() {
return mSecurityPolicy;
}
@Override
public CordovaInterface getCordovaInterface() {
return this;
}
}
| 27.850962 | 102 | 0.64086 |
2f1724a23bbf69acf855b91fa2f6453eebe4dda7 | 3,324 | package com.evil.devreminder.service.impl;
import com.evil.devreminder.domain.Word;
import com.evil.devreminder.service.DictionaryService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class DictionaryServiceImpl implements DictionaryService {
private static final String HTTPS_DEX_REST = "https://dexonline.ro";
private final RestTemplate restTemplate;
@Override
public Word getRomanianWordOfTheDay() {
ResponseEntity<String> response = restTemplate.getForEntity(HTTPS_DEX_REST + "/cuvantul-zilei/" +
LocalDate.now().format(
DateTimeFormatter.ofPattern(
"yyyy/MM/dd")) + "/json",
String.class);
try {
JsonNode root = new ObjectMapper().readTree(response.getBody());
return new Word(
root.path("requested").path("record").path("word").asText(),
root.path("requested").path("record").path("definition").path("internalRep").asText());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return new Word("unknown", "unknown");
}
@Override
public Word getRomanianDefinitionFor(String term) {
ResponseEntity<String> response = restTemplate.getForEntity(HTTPS_DEX_REST + "/definitie/" +
term + "/json", String.class);
try {
JsonNode root = new ObjectMapper().readTree(response.getBody());
return new Word(
root.path("word").asText(),
root.path("definitions").path(0).path("internalRep").asText());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return new Word("unknown", "unknown");
}
@Override
public Word getEnglishWordOfTheDay() {
Document root = null;
try {
root = Jsoup.connect("https://www.merriam-webster.com/word-of-the-day").get();
final String word = root.select("div.word-and-pronunciation > h1").html();
String definition = Jsoup.parse(root.select("div.wod-definition-container > p").html()).text();
return new Word(word, definition + "\n https://www.merriam-webster.com/dictionary/forfend");
} catch (IOException e) {
e.printStackTrace();
}
return new Word("unknown", "unknown");
}
}
| 43.168831 | 117 | 0.59657 |
11135084fcf2931bb569e4cbe6cc89fd94ff45f5 | 4,993 | /*
* Copyright 2017 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.server;
import static java.util.Objects.requireNonNull;
import java.io.OutputStream;
import java.util.function.Function;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.base.MoreObjects;
import com.linecorp.armeria.common.Flags;
import com.linecorp.armeria.common.Request;
import com.linecorp.armeria.common.Response;
import com.linecorp.armeria.common.metric.MeterId;
import com.linecorp.armeria.internal.metric.CaffeineMetricSupport;
import com.linecorp.armeria.server.composition.CompositeServiceEntry;
import io.micrometer.core.instrument.MeterRegistry;
/**
* See {@link Flags#routeCacheSpec()} to configure this {@link RouteCache}.
*/
final class RouteCache {
private static final Cache<PathMappingContext, ServiceConfig> CACHE =
Flags.routeCacheSpec().map(RouteCache::<ServiceConfig>buildCache)
.orElse(null);
/**
* Returns a {@link Router} which is wrapped with a {@link Cache} layer in order to improve the
* performance of the {@link ServiceConfig} search.
*/
static Router<ServiceConfig> wrapVirtualHostRouter(Router<ServiceConfig> delegate) {
return CACHE == null ? delegate
: new CachingRouter<>(delegate, CACHE, ServiceConfig::pathMapping);
}
/**
* Returns a {@link Router} which is wrapped with a {@link Cache} layer in order to improve the
* performance of the {@link CompositeServiceEntry} search.
*/
static <I extends Request, O extends Response>
Router<CompositeServiceEntry<I, O>> wrapCompositeServiceRouter(
Router<CompositeServiceEntry<I, O>> delegate) {
final Cache<PathMappingContext, CompositeServiceEntry<I, O>> cache =
Flags.compositeServiceCacheSpec().map(RouteCache::<CompositeServiceEntry<I, O>>buildCache)
.orElse(null);
if (cache == null) {
return delegate;
}
return new CachingRouter<>(delegate, cache, CompositeServiceEntry::pathMapping);
}
private static <T> Cache<PathMappingContext, T> buildCache(String spec) {
return Caffeine.from(spec).recordStats().build();
}
private RouteCache() {}
/**
* A {@link Router} which is wrapped with a {@link Cache} layer.
*/
private static final class CachingRouter<V> implements Router<V> {
private final Router<V> delegate;
private final Cache<PathMappingContext, V> cache;
private final Function<V, PathMapping> pathMappingResolver;
CachingRouter(Router<V> delegate, Cache<PathMappingContext, V> cache,
Function<V, PathMapping> pathMappingResolver) {
this.delegate = requireNonNull(delegate, "delegate");
this.cache = requireNonNull(cache, "cache");
this.pathMappingResolver = requireNonNull(pathMappingResolver, "pathMappingResolver");
}
@Override
public PathMapped<V> find(PathMappingContext mappingCtx) {
final V cached = cache.getIfPresent(mappingCtx);
if (cached != null) {
// PathMappingResult may be different to each other for every requests, so we cannot
// use it as a cache value.
final PathMapping mapping = pathMappingResolver.apply(cached);
final PathMappingResult mappingResult = mapping.apply(mappingCtx);
return PathMapped.of(mapping, mappingResult, cached);
}
final PathMapped<V> result = delegate.find(mappingCtx);
if (result.isPresent()) {
cache.put(mappingCtx, result.value());
}
return result;
}
@Override
public boolean registerMetrics(MeterRegistry registry, MeterId id) {
CaffeineMetricSupport.setup(registry, id, cache);
return true;
}
@Override
public void dump(OutputStream output) {
delegate.dump(output);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("delegate", delegate)
.add("cache", cache)
.toString();
}
}
}
| 37.541353 | 106 | 0.656719 |
397ee74fed7b4757277cf2c2eb0916c13cda79bd | 598 | package _02Blobs.core.commands;
import _02Blobs.core.BaseCommand;
import _02Blobs.interfaces.Blob;
public class AttackCommand extends BaseCommand {
@Override
public String execute() {
if (super.getRepository().findByName(super.getParams()[1]) != null &&
super.getRepository().findByName(super.getParams()[2]) != null ){
Blob attacker = super.getRepository().findByName(super.getParams()[1]);
Blob target = super.getRepository().findByName(super.getParams()[2]);
attacker.attack(target);
}
return null;
}
}
| 29.9 | 83 | 0.647157 |
bc200ab0deb00a7671e1ab68af8dd4c264045736 | 997 | package ar.edu.itba.cep.api_gateway.security;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.List;
/**
* An extension of an {@link AnonymousAuthenticationToken}.
*/
public class AnonymousAccess extends AnonymousAuthenticationToken {
/**
* Anonymous.
*/
private static final String ANONYMOUS = "ANONYMOUS";
/**
* The unique instance.
*/
private static final AnonymousAccess SINGLETON = new AnonymousAccess();
/**
* Private constructor.
* Use {@link #getInstance()} instead.
*/
private AnonymousAccess() {
super(ANONYMOUS, ANONYMOUS, List.of(new SimpleGrantedAuthority(ANONYMOUS)));
}
/**
* Access the unique instance of an {@link AnonymousAccess}.
*
* @return The unique instance.
*/
public static AnonymousAccess getInstance() {
return SINGLETON;
}
}
| 24.925 | 84 | 0.685055 |
11cc6b2b33d222c803e706000ba2c0a5a18d9ca2 | 5,011 | package com.therandomlabs.randomportals;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import com.therandomlabs.randomlib.TRLUtils;
import com.therandomlabs.randomlib.config.ConfigManager;
import com.therandomlabs.randomportals.advancements.RPOCriteriaTriggers;
import com.therandomlabs.randomportals.api.config.FrameSizes;
import com.therandomlabs.randomportals.api.config.PortalTypes;
import com.therandomlabs.randomportals.config.RPOConfig;
import com.therandomlabs.randomportals.frame.endportal.EndPortalFrames;
import com.therandomlabs.randomportals.handler.EndPortalActivationHandler;
import com.therandomlabs.randomportals.handler.FrameHeadVillagerHandler;
import com.therandomlabs.randomportals.handler.NetherPortalActivationHandler;
import com.therandomlabs.randomportals.handler.NetherPortalFrameBreakHandler;
import com.therandomlabs.randomportals.handler.NetherPortalTeleportHandler;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraftforge.common.MinecraftForge;
public class CommonProxy {
public void preInit() {
if (RandomPortals.INSPIRATIONS_INSTALLED) {
try {
handleInspirations();
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ex) {
RandomPortals.LOGGER.error("Failed to fix Inspirations compatibility", ex);
}
}
ConfigManager.register(RPOConfig.class);
}
public void init() {
RPOConfig.reload();
if (RandomPortals.MOVINGWORLD_INSTALLED) {
try {
handleMovingWorld();
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException |
IllegalAccessException | InvocationTargetException ex) {
RandomPortals.LOGGER.error("Failed to fix MovingWorld compatibility", ex);
}
}
if (RPOConfig.EndPortals.enabled) {
MinecraftForge.EVENT_BUS.register(EndPortalActivationHandler.class);
MinecraftForge.EVENT_BUS.register(FrameHeadVillagerHandler.class);
}
if (RPOConfig.NetherPortals.enabled) {
MinecraftForge.EVENT_BUS.register(NetherPortalTeleportHandler.class);
MinecraftForge.EVENT_BUS.register(NetherPortalFrameBreakHandler.class);
MinecraftForge.EVENT_BUS.register(NetherPortalActivationHandler.class);
}
EndPortalFrames.registerSizes();
FrameSizes.reload();
RPOCriteriaTriggers.register();
}
public void postInit() {
try {
PortalTypes.reload();
} catch (IOException ex) {
TRLUtils.crashReport("Error while reloading Nether portal types", ex);
}
}
private void handleInspirations()
throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
final Class<?> config = Class.forName("knightminer.inspirations.common.Config");
final Field customPortalColor = config.getDeclaredField("customPortalColor");
customPortalColor.set(null, false);
}
private void handleMovingWorld() throws ClassNotFoundException, NoSuchFieldException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException {
//https://github.com/elytra/MovingWorld/blob/1c547d75d9e681473cbc04a58dc6b803d5ef19fa/
//src/main/java/com/elytradev/movingworld/common/config/priority/
//AssemblePriorityConfig.java
//MovingWorld loads Blocks.PORTAL and Blocks.END_PORTAL in preInit before
//RandomPortals can register its replacements
//It then uses the vanilla portal and End portal in init, causing an NPE
final Class<?> movingWorldMod = Class.forName("com.elytradev.movingworld.MovingWorldMod");
final Object movingWorldInstance = movingWorldMod.getDeclaredField("INSTANCE").get(null);
final Object localConfigInstance =
movingWorldMod.getDeclaredMethod("getLocalConfig").invoke(movingWorldInstance);
final Class<?> mainConfig = localConfigInstance.getClass();
final Object sharedConfigInstance =
mainConfig.getDeclaredMethod("getShared").invoke(localConfigInstance);
final Class<?> sharedConfig = sharedConfigInstance.getClass();
final Object config =
sharedConfig.getDeclaredField("assemblePriorityConfig").get(sharedConfigInstance);
final Class<?> clazz = config.getClass();
final Field defaultHighPriorityAssemblyBlocks =
clazz.getDeclaredField("defaultHighPriorityAssemblyBlocks");
final Field defaultLowPriorityDisassemblyBlocks =
clazz.getDeclaredField("defaultLowPriorityDisassemblyBlocks");
defaultHighPriorityAssemblyBlocks.setAccessible(true);
defaultLowPriorityDisassemblyBlocks.setAccessible(true);
final Block[] blocks1 = (Block[]) defaultHighPriorityAssemblyBlocks.get(config);
final Block[] blocks2 = (Block[]) defaultLowPriorityDisassemblyBlocks.get(config);
replace(blocks1);
replace(blocks2);
}
private void replace(Block[] blocks) {
for (int i = 0; i < blocks.length; i++) {
final String registryName = blocks[i].getRegistryName().toString();
if (registryName.equals("minecraft:portal")) {
blocks[i] = Blocks.PORTAL;
} else if (registryName.equals("minecraft:end_portal")) {
blocks[i] = Blocks.END_PORTAL;
}
}
}
}
| 38.844961 | 92 | 0.796248 |
5e0dbb19e3f7c52347aa1ce8deb4a23066404ce7 | 1,211 | package LCTlang.CustomJava;
public class Value extends Throwable {
public static Value VOID = new Value(new Object());
final Object value;
public Value(Object value) {
this.value = value;
}
public Boolean asBoolean() {
return (Boolean)value;
}
public Double asDouble() {
return (Double)value;
}
public String asString() {
return String.valueOf(value);
}
public boolean isDouble() {
return value instanceof Double;
}
public boolean isString() { return value instanceof String; }
public boolean isBoolean() {
return value instanceof Boolean;
}
@Override
public int hashCode() {
if(value == null) {
return 0;
}
return this.value.hashCode();
}
@Override
public boolean equals(Object o) {
if(value == o) {
return true;
}
if(value == null || o == null || o.getClass() != value.getClass()) {
return false;
}
Value that = (Value)o;
return this.value.equals(that.value);
}
@Override
public String toString() {
return String.valueOf(value);
}
} | 19.222222 | 76 | 0.559042 |
8b49e488872b5023dfada5e0d8a8a12fb17d094f | 795 | package com.szyh.captcha.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.szyh.captcha.utils.CaptchaUtil;
/**
* 验证码servlet
*/
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = -90304944339413093L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CaptchaUtil.out(request, response, CaptchaUtil.CAPTCHA_TYPE_ALPHANUMERIC);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| 29.444444 | 119 | 0.792453 |
4d786fbf2ad231cfa9b319253c2498fd32b590e6 | 13,269 | /**
* This software is provided by NOAA for full, free and open release. It is
* understood by the recipient/user that NOAA assumes no liability for any
* errors contained in the code. Although this software is released without
* conditions or restrictions in its use, it is expected that appropriate
* credit be given to its author and to the National Oceanic and Atmospheric
* Administration should the software be included by the recipient as an
* element in other product development.
*/
package gov.noaa.pmel.tmap.iosp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.LoggerFactory;
/**
* This is the Tool class (based on the Anagram Tool class) that runs Ferret so it can do work for the IOSP.
* @author rhs
*
*/
public class FerretTool extends Tool{
private final static Logger log = LoggerFactory.getLogger(FerretTool.class.getName());
//private final static Logger log = LoggerFactory.getLogger(FerretTool.class.getName());
FerretConfig ferretConfig;
String scriptDir;
String tempDir;
String dataDir;
/**
* The default constructor that reads the config file and readies the tool to be used.
* @throws Exception
*/
public FerretTool() throws Exception {
// Set up the Java Properties Object
String configFilePath = getResourcePath("resources/iosp/FerretConfig.xml");
File configFile;
if ( configFilePath != null ) {
configFile = new File(configFilePath);
} else {
throw new Exception("Ferret config file resources/iosp/FerretConfig.xml not found.");
}
ferretConfig = new FerretConfig();
try {
JDOMUtils.XML2JDOM(configFile, ferretConfig);
} catch (Exception e) {
throw new Exception("Could not parse Ferret config file: " + e.toString());
}
log.debug("config file parsed.");
scriptDir = ferretConfig.getIOSPScriptDir();
if ( scriptDir == "" ) {
scriptDir = getResourcePath("resources/iosp/scripts");
} else if ( !scriptDir.startsWith("/") ) {
scriptDir = getResourcePath(scriptDir);
}
log.debug("Setting script dir to: "+ scriptDir);
tempDir = ferretConfig.getIOSPTempDir();
if ( tempDir == "" ) {
tempDir = getResourcePath("resources/iosp/temp");
} else if ( !tempDir.startsWith("/") ) {
tempDir = getResourcePath(tempDir);
}
log.debug("Setting temp dir to: "+ tempDir);
dataDir = ferretConfig.getIOSPDataDir();
if ( dataDir == "" ) {
dataDir = getResourcePath("resources/iosp/data");
} else if ( !dataDir.startsWith("/") ) {
dataDir = getResourcePath(dataDir);
}
log.debug("Setting data dir to: "+ dataDir);
}
/**
* This runs the tool and captures the output to a debug file.
* @param driver the command to run (ferret in this case).
* @param jnl the command file.
* @param cacheKey the cache key (should be removed since we don't need it)
* @param output_filename where to write STDOUT, can be a debug file or the header.xml file.
* @throws Exception
*/
public void run (String driver, String jnl, String cacheKey, String temporary_filename, String output_filename) throws Exception {
log.debug("Running the FerretTool.");
// Set up the runtime environment.
log.debug("iosp base dir in="+ferretConfig.getIOSPBaseDir());
log.debug("iosp base dir="+getResourcePath(ferretConfig.getIOSPBaseDir()));
ferretConfig.setIOSPBaseDir(getResourcePath(ferretConfig.getIOSPBaseDir()));
log.debug("base dir set");
HashMap<String, String> envMap = ferretConfig.getEnvironment();
log.debug("got enviroment.");
RuntimeEnvironment runTimeEnv = new RuntimeEnvironment();
log.debug("Constructed new runTimeEnv.");
runTimeEnv.setParameters(envMap);
log.debug("Setting up the Ferret journal file.");
String journalName = null;
synchronized(this) {
journalName = "ferret_operation"
+ "_" + System.currentTimeMillis();
}
if ( tempDir.contains("../") || tempDir.contains("/..") || cacheKey.contains("../") || cacheKey.contains("/..") || journalName.contains("../") || journalName.contains("/..") ) {
throw new Exception("Illegal file name.");
}
File jnlFile = new File(tempDir +File.separator+ cacheKey + File.separator + journalName + ".jnl");
log.debug("Creating Ferret journal file in " + jnlFile.getAbsolutePath() );
createJournal(jnl, jnlFile);
log.debug("Finished creating Ferret journal file.");
String args[] = new String[]{driver, jnlFile.getAbsolutePath(), temporary_filename};
log.debug("Creating Ferret task.");
Task ferretTask=null;
long timeLimit = ferretConfig.getTimeLimit();
try {
ferretTask = task(runTimeEnv, args, timeLimit, scriptDir, tempDir);
} catch (Exception e) {
log.error("Could not create Ferret task. "+e.toString());
}
log.debug("Running Ferret task.");
if ( temporary_filename.contains("../") || temporary_filename.contains("/..") ) {
throw new Exception("Illegal temporary file name.");
}
if ( output_filename.contains("../") || output_filename.contains("/..") ) {
throw new Exception("Illegal output file name.");
}
File temp_file = new File(temporary_filename);
File out_file = new File(output_filename);
try {
if ( ferretTask != null ) {
temp_file.createNewFile();
ferretTask.run();
}
} catch (Exception e) {
log.error("Ferret did not run correctly. "+e.toString());
}
log.debug("Ferret Task finished.");
log.debug("Checking for errors.");
String output = ferretTask.getOutput();
String stderr = ferretTask.getStderr();
if ( output.contains("/..") || output.contains("../") || stderr.contains("/..") || stderr.contains("../") ) {
throw new Exception("Illegal file name.");
}
if ( !ferretTask.getHasError() || stderr.contains("**ERROR: regridding") ) {
// Everything worked. Create output.
log.debug("Ferret task completed without error.");
log.debug("Output:\n"+output);
temp_file.renameTo(out_file);
if ( output_filename != null && !output_filename.equals("") ) {
String logfile = output_filename+".log";
if ( logfile.contains("../") || logfile.contains("/..") ) {
throw new Exception("Illegal log file name.");
}
log.debug("Writing output to "+output_filename);
PrintWriter logwriter = new PrintWriter(new FileOutputStream(logfile));
logwriter.println(output);
logwriter.println(stderr);
logwriter.flush();
logwriter.close();
}
}
else {
// Error was generated. Make error page instead.
log.error("Ferret generated an error.");
String errorMessage = ferretTask.getErrorMessage();
log.error(errorMessage+"\n"+stderr+"\n");
log.error(output);
File bad = new File(out_file.getAbsoluteFile()+".bad");
temp_file.renameTo(bad);
}
log.debug("Finished running the FerretTool.");
}
/**
* Run Ferret and capture STDOUT into the header.xml file for this data set.
* @param driver which command to run (ferret in this case).
* @param jnl the file with the commands to run.
* @param cacheKey not used, should be removed.
* @return return the full path to the STDOUT file (header.xml in this case).
* @throws Exception
*/
public String run_header(String driver, String jnl, String cacheKey) throws Exception {
log.debug("Entering method.");
String tempDir = ferretConfig.getIOSPTempDir();
if ( tempDir == "" ) {
tempDir = getResourcePath("resources/ferret/temp");
} else if ( !tempDir.startsWith(File.separator) ) {
tempDir = getResourcePath(tempDir);
}
tempDir = tempDir+cacheKey;
File cacheDir = new File (tempDir);
String header_filename = tempDir+File.separator+"header.xml";
String header_temp_filename = header_filename+".tmp";
if ( header_filename.contains("../") || header_filename.contains("/..") ) {
throw new Exception("Illegal header file name.");
}
if ( !cacheDir.isDirectory() ) {
cacheDir.mkdir();
} else {
File header = new File(header_filename);
if ( header.exists() ) {
log.debug("The header file already exists. It's a cache hit. Return now.");
return header_filename;
}
}
log.debug("Generating the XML header for this data source using "+header_filename);
run(driver, jnl, cacheKey, header_temp_filename, header_filename);
return header_filename;
}
/**
* Create a journal file that Ferret will use to perform a task.
* @param jnl
* @param jnlFile
* @throws Exception
*/
private void createJournal(String jnl, File jnlFile) throws Exception {
PrintWriter jnlWriter = null;
try {
jnlWriter = new PrintWriter(new FileOutputStream(jnlFile));
}
catch(Exception e) {
// We need to package these and send them back to the UI.
}
if ( jnlWriter != null ) {
jnlWriter.println(jnl);
jnlWriter.flush();
jnlWriter.close();
}
}
/**
* The construct a Task which is the definition of the command line arguments for particular invocation of the Tool.
* @param runTimeEnv the Java instantiation of the shell run time environment for the invocation of this command.
* @param args the command line arguments
* @param timeLimit how long to let it run
* @param scriptDir where to look for the "driver" script.
* @param tempDir where to write temp files if you need it.
* @return the task object
* @throws Exception
*/
public Task task(RuntimeEnvironment runTimeEnv, String[] args, long timeLimit, String scriptDir, String tempDir) throws Exception {
String[] errors = { "**ERROR", " **ERROR"," **TMAP ERR", "STOP -script mode", "Segmentation fault", "No such"};
File scriptFile = new File(scriptDir, "data.jnl");
if (!scriptFile.exists()) {
throw new Exception("Missing controller script data.jnl");
}
scriptFile = new File(scriptDir, "header.jnl");
if (!scriptFile.exists()) {
throw new Exception("Missing controller script header.jnl");
}
StringBuffer argBuffer = new StringBuffer();
for (int i = 0; i < args.length; i++) {
argBuffer.append(args[i]);
argBuffer.append(" ");
}
/*
* There are two sets of arguments that come into the task.
* fargs aref from the configuration -gif -script stuff like that.
* args are those arguments that need to be passed to the [py]ferret command line
* which in the case of making the header or the name of the script to make the headers,
* the name of the script to initialize the data set and the name of the XML file to receive the info.
*
*/
boolean useNice = ferretConfig.getUseNice();
String ferretBinary = ferretConfig.getFerret();
List<String> fargs = ferretConfig.getArgs();
int offset = (useNice) ? 1 : 0;
String[] cmd;
// We've never used the "nice" feature
cmd = new String[offset + fargs.size() + args.length + 1];
if (useNice) {
cmd[0] = "nice";
}
cmd[offset] = ferretBinary;
for (int i = 0; i < fargs.size(); i++) {
cmd[offset + i+1] = fargs.get(i);
}
for (int i = 0; i < args.length; i++) {
cmd[offset + fargs.size()+1+i] = args[i];
}
String env[] = runTimeEnv.getEnv();
File workDirFile = null;
if (tempDir != null) {
workDirFile = new File(tempDir);
}
Task task = new Task(cmd, env, workDirFile, timeLimit, errors);
log.debug("command line for task is:\n"
+ task.getCmd());
return task;
}
public String getDataDir() {
return dataDir;
}
public String getTempDir() {
return tempDir;
}
public String getScriptDir() {
return scriptDir;
}
}
| 35.862162 | 185 | 0.593564 |
f4df008fa0e78f043909bfc6585785de165512f3 | 4,298 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.management.graphrbac;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.Map;
/** The ResourceAccess model. */
@Fluent
public final class ResourceAccess {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ResourceAccess.class);
/*
* The unique identifier for one of the OAuth2Permission or AppRole
* instances that the resource application exposes.
*/
@JsonProperty(value = "id", required = true)
private String id;
/*
* Specifies whether the id property references an OAuth2Permission or an
* AppRole. Possible values are "scope" or "role".
*/
@JsonProperty(value = "type")
private String type;
/*
* Specifies an OAuth 2.0 permission scope or an app role that an
* application requires. The resourceAccess property of the
* RequiredResourceAccess type is a collection of ResourceAccess.
*/
@JsonIgnore private Map<String, Object> additionalProperties;
/**
* Get the id property: The unique identifier for one of the OAuth2Permission or AppRole instances that the resource
* application exposes.
*
* @return the id value.
*/
public String id() {
return this.id;
}
/**
* Set the id property: The unique identifier for one of the OAuth2Permission or AppRole instances that the resource
* application exposes.
*
* @param id the id value to set.
* @return the ResourceAccess object itself.
*/
public ResourceAccess withId(String id) {
this.id = id;
return this;
}
/**
* Get the type property: Specifies whether the id property references an OAuth2Permission or an AppRole. Possible
* values are "scope" or "role".
*
* @return the type value.
*/
public String type() {
return this.type;
}
/**
* Set the type property: Specifies whether the id property references an OAuth2Permission or an AppRole. Possible
* values are "scope" or "role".
*
* @param type the type value to set.
* @return the ResourceAccess object itself.
*/
public ResourceAccess withType(String type) {
this.type = type;
return this;
}
/**
* Get the additionalProperties property: Specifies an OAuth 2.0 permission scope or an app role that an application
* requires. The resourceAccess property of the RequiredResourceAccess type is a collection of ResourceAccess.
*
* @return the additionalProperties value.
*/
@JsonAnyGetter
public Map<String, Object> additionalProperties() {
return this.additionalProperties;
}
/**
* Set the additionalProperties property: Specifies an OAuth 2.0 permission scope or an app role that an application
* requires. The resourceAccess property of the RequiredResourceAccess type is a collection of ResourceAccess.
*
* @param additionalProperties the additionalProperties value to set.
* @return the ResourceAccess object itself.
*/
public ResourceAccess withAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
@JsonAnySetter
void withAdditionalProperties(String key, Object value) {
if (additionalProperties == null) {
additionalProperties = new HashMap<>();
}
additionalProperties.put(key, value);
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (id() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property id in model ResourceAccess"));
}
}
}
| 33.061538 | 120 | 0.679153 |
f19801cfe4e9558cb28b4cffe21632eed23bdf92 | 3,809 | package com.example.hansheng.simplecard.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.example.hansheng.simplecard.utils.Press;
import java.util.HashMap;
/**
* Created by hansheng on 2016/4/23.
*/
public class ScaleFrameLayout extends FrameLayout{
/**
* scale属性的key值
*/
protected static final String KEY_SCALE = "scale";
/**
* View的高宽比例,默认是1,也就是高宽相等,当等于-1时,根据bitmap的比例设置宽高比
*/
protected float mScale = 1;
public ScaleFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTextAttribute(getTextAttributeMap(attrs));
}
public ScaleFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setTextAttribute(getTextAttributeMap(attrs));
}
public ScaleFrameLayout(Context context) {
super(context);
}
/**
* 描述:根据text属性设置高宽比例
*
* @param
* @updateInfo (此处输入修改内容, 若无修改可不写.)
*/
protected void setTextAttribute(HashMap<String, String> attributeMap) {
setScale(attributeMap);
}
/**
* 描述:解析text为键值对
*
* @param attrs
* @updateInfo (此处输入修改内容, 若无修改可不写.)
*/
private HashMap<String, String> getTextAttributeMap(AttributeSet attrs) {
String str = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "text");
if (str == null) {
return null;
}
String[] splits = str.split(",");
HashMap<String, String> keyValueMap = null;
if (splits != null && splits.length > 0) {
keyValueMap = new HashMap<String, String>();
for (String split : splits) {
String[] keyValue = split.split(":");
keyValueMap.put(keyValue[0], keyValue[1]);
}
}
return keyValueMap;
}
/**
* 描述:根据属性设置高宽比
*
* @param attributeMap
* @updateInfo (此处输入修改内容, 若无修改可不写.)
*/
private void setScale(HashMap<String, String> attributeMap) {
if (attributeMap != null) {
String str = attributeMap.get(KEY_SCALE);
if (str != null) {
mScale = Float.parseFloat(str);
}
}
}
/**
* 描述:设置高宽比例
*
* @param scale
* @updateInfo (此处输入修改内容, 若无修改可不写.)
*/
public void setScale(float scale, boolean toInvalidate) {
mScale = scale;
if (toInvalidate) {
invalidate();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w > 0) {
ViewGroup.LayoutParams params = getLayoutParams();
params.width = w;
params.height = (int) (w * getScale());
setLayoutParams(params);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childWidthSize = getMeasuredWidth();
int childHeightSize = (int) (childWidthSize * getScale());
// 重设高度
setMeasuredDimension(childWidthSize, childHeightSize);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
Press.press(this, canvas);
}
boolean isPressed = false;
@Override
public void refreshDrawableState() {
this.isPressed = Press.refreshDrawableState(this, this.isPressed);
super.refreshDrawableState();
}
/**
* 描述:判断并且返回比例
* @updateInfo (此处输入修改内容, 若无修改可不写.)
*/
protected float getScale() {
return mScale;
}
}
| 25.911565 | 99 | 0.599895 |
f8bcef323af0acc1b5b2f1af76e3dbee9b64f359 | 3,080 | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.vod20170321.models;
import com.aliyun.tea.*;
public class GetCategoriesResponse extends TeaModel {
@NameInMap("RequestId")
@Validation(required = true)
public String requestId;
@NameInMap("SubTotal")
@Validation(required = true)
public Long subTotal;
@NameInMap("SubCategories")
@Validation(required = true)
public GetCategoriesResponseSubCategories subCategories;
@NameInMap("Category")
@Validation(required = true)
public GetCategoriesResponseCategory category;
public static GetCategoriesResponse build(java.util.Map<String, ?> map) throws Exception {
GetCategoriesResponse self = new GetCategoriesResponse();
return TeaModel.build(map, self);
}
public static class GetCategoriesResponseSubCategoriesCategory extends TeaModel {
@NameInMap("CateId")
@Validation(required = true)
public Long cateId;
@NameInMap("CateName")
@Validation(required = true)
public String cateName;
@NameInMap("Level")
@Validation(required = true)
public Long level;
@NameInMap("ParentId")
@Validation(required = true)
public Long parentId;
@NameInMap("SubTotal")
@Validation(required = true)
public Long subTotal;
@NameInMap("Type")
@Validation(required = true)
public String type;
public static GetCategoriesResponseSubCategoriesCategory build(java.util.Map<String, ?> map) throws Exception {
GetCategoriesResponseSubCategoriesCategory self = new GetCategoriesResponseSubCategoriesCategory();
return TeaModel.build(map, self);
}
}
public static class GetCategoriesResponseSubCategories extends TeaModel {
@NameInMap("Category")
@Validation(required = true)
public java.util.List<GetCategoriesResponseSubCategoriesCategory> category;
public static GetCategoriesResponseSubCategories build(java.util.Map<String, ?> map) throws Exception {
GetCategoriesResponseSubCategories self = new GetCategoriesResponseSubCategories();
return TeaModel.build(map, self);
}
}
public static class GetCategoriesResponseCategory extends TeaModel {
@NameInMap("CateId")
@Validation(required = true)
public Long cateId;
@NameInMap("CateName")
@Validation(required = true)
public String cateName;
@NameInMap("Level")
@Validation(required = true)
public Long level;
@NameInMap("ParentId")
@Validation(required = true)
public Long parentId;
@NameInMap("Type")
@Validation(required = true)
public String type;
public static GetCategoriesResponseCategory build(java.util.Map<String, ?> map) throws Exception {
GetCategoriesResponseCategory self = new GetCategoriesResponseCategory();
return TeaModel.build(map, self);
}
}
}
| 30.49505 | 119 | 0.668506 |
03de72d9e3f4084d92792867c07db23fd3661a8a | 8,138 | /*
* 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.statefun.sdk.java.storage;
import static org.apache.flink.statefun.sdk.java.storage.StateValueContexts.StateValueContext;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.flink.statefun.sdk.java.AddressScopedStorage;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
import org.junit.Test;
public class ConcurrentAddressScopedStorageTest {
@Test
public void exampleUsage() {
final ValueSpec<Integer> stateSpec1 = ValueSpec.named("state_1").withIntType();
final ValueSpec<Boolean> stateSpec2 = ValueSpec.named("state_2").withBooleanType();
final List<StateValueContext<?>> testStateValues =
testStateValues(stateValue(stateSpec1, 91), stateValue(stateSpec2, true));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
assertThat(storage.get(stateSpec1), is(Optional.of(91)));
assertThat(storage.get(stateSpec2), is(Optional.of(true)));
}
@Test
public void getNullValueCell() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, null));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
assertThat(storage.get(stateSpec), is(Optional.empty()));
}
@Test
public void setCell() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.set(stateSpec, 1111);
assertThat(storage.get(stateSpec), is(Optional.of(1111)));
}
@Test
public void setMutableTypeCell() {
final ValueSpec<TestMutableType.Type> stateSpec =
ValueSpec.named("state").withCustomType(new TestMutableType());
final List<StateValueContext<?>> testStateValues =
testStateValues(stateValue(stateSpec, new TestMutableType.Type("hello")));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
final TestMutableType.Type newValue = new TestMutableType.Type("hello again!");
storage.set(stateSpec, newValue);
// mutations after a set should not have any effect
newValue.mutate("this value should not be written to storage!");
assertThat(storage.get(stateSpec), is(Optional.of(new TestMutableType.Type("hello again!"))));
}
@Test
public void clearCell() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.remove(stateSpec);
assertThat(storage.get(stateSpec), is(Optional.empty()));
}
@Test
public void clearMutableTypeCell() {
final ValueSpec<TestMutableType.Type> stateSpec =
ValueSpec.named("state").withCustomType(new TestMutableType());
List<StateValueContext<?>> testStateValues =
testStateValues(stateValue(stateSpec, new TestMutableType.Type("hello")));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.remove(stateSpec);
assertThat(storage.get(stateSpec), is(Optional.empty()));
}
@Test(expected = IllegalStorageAccessException.class)
public void getNonExistingCell() {
final AddressScopedStorage storage =
new ConcurrentAddressScopedStorage(Collections.emptyList());
storage.get(ValueSpec.named("does_not_exist").withIntType());
}
@Test(expected = IllegalStorageAccessException.class)
public void setNonExistingCell() {
final AddressScopedStorage storage =
new ConcurrentAddressScopedStorage(Collections.emptyList());
storage.set(ValueSpec.named("does_not_exist").withIntType(), 999);
}
@Test(expected = IllegalStorageAccessException.class)
public void clearNonExistingCell() {
final AddressScopedStorage storage =
new ConcurrentAddressScopedStorage(Collections.emptyList());
storage.remove(ValueSpec.named("does_not_exist").withIntType());
}
@Test(expected = IllegalStorageAccessException.class)
public void setToNull() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.set(stateSpec, null);
}
@Test(expected = IllegalStorageAccessException.class)
public void getWithWrongType() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.get(ValueSpec.named("state").withBooleanType());
}
@Test(expected = IllegalStorageAccessException.class)
public void setWithWrongType() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.set(ValueSpec.named("state").withBooleanType(), true);
}
@Test(expected = IllegalStorageAccessException.class)
public void clearWithWrongType() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.remove(ValueSpec.named("state").withBooleanType());
}
private static List<StateValueContext<?>> testStateValues(StateValueContext<?>... testValues) {
return Arrays.asList(testValues);
}
private static <T> StateValueContext<T> stateValue(ValueSpec<T> spec, T value) {
final ToFunction.PersistedValue protocolValue =
ToFunction.PersistedValue.newBuilder()
.setStateName(spec.name())
.setStateValue(
TypedValue.newBuilder()
.setTypename(value == null ? "" : spec.type().typeName().asTypeNameString())
.setHasValue(value != null)
.setValue(toByteString(spec.type(), value)))
.build();
return new StateValueContext<>(spec, protocolValue);
}
private static <T> ByteString toByteString(Type<T> type, T value) {
if (value == null) {
return ByteString.EMPTY;
}
return ByteString.copyFrom(type.typeSerializer().serialize(value).toByteArray());
}
}
| 39.31401 | 100 | 0.746867 |
216ec8c7cc2bf16c883ad549cad19a0b1dac6305 | 12,144 | /**
* Copyright (c) 2011 Martin M Reed
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hardisonbrewing.signingserver;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.StreamConnection;
import net.hardisonbrewing.signingserver.model.OptionProperties;
import net.hardisonbrewing.signingserver.model.PushNotification;
import net.hardisonbrewing.signingserver.service.icon.IconService;
import net.hardisonbrewing.signingserver.service.network.AbstractRadioStatusListener;
import net.hardisonbrewing.signingserver.service.push.PushPPGService;
import net.hardisonbrewing.signingserver.service.push.PushSIGService;
import net.hardisonbrewing.signingserver.service.store.OptionsStore;
import net.hardisonbrewing.signingserver.service.store.push.PushPPGStatusChangeListener;
import net.hardisonbrewing.signingserver.service.store.push.PushPPGStatusChangeListenerStore;
import net.rim.blackberry.api.push.PushApplication;
import net.rim.blackberry.api.push.PushApplicationDescriptor;
import net.rim.blackberry.api.push.PushApplicationRegistry;
import net.rim.blackberry.api.push.PushApplicationStatus;
import net.rim.device.api.io.http.PushInputStream;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;
import org.apache.commons.threadpool.DefaultThreadPool;
import org.apache.commons.threadpool.ThreadPool;
import org.metova.mobile.util.io.IOUtility;
import org.metova.mobile.util.time.Dates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SigservPushApplication extends Application implements PushApplication, PushPPGStatusChangeListener {
private static final Logger log = LoggerFactory.getLogger( SigservPushApplication.class );
private final ThreadPool threadPool = new DefaultThreadPool( 1 );
private AbstractRadioStatusListener radioStatusListener;
private TimerTask networkRequiredTimerTask;
private TimerTask registerServ;
public SigservPushApplication() {
PushPPGStatusChangeListenerStore.put( this );
radioStatusListener = new MyRadioStatusListener();
addRadioListener( radioStatusListener );
WLANInfo.addListener( radioStatusListener );
}
public static boolean isSupported() {
return !DeviceInfo.isSimulator();
}
public static void mainAutoRegister( String[] args ) {
if ( !isSupported() ) {
log.info( "PUSH not supported. Skipping registration." );
return;
}
log.info( "Running auto register PUSH application" );
if ( !OptionsStore.getBoolean( OptionProperties.PUSH_ENABLED ) ) {
log.info( "Push notifications disabled. Skipping registration." );
return;
}
mainRegister( args );
}
public static void mainRegister( String[] args ) {
if ( !isSupported() ) {
log.info( "PUSH not supported. Skipping registration." );
return;
}
log.info( "Registering PUSH application" );
PushApplicationDescriptor pushApplicationDescriptor = PushPPGService.getPushApplicationDescriptor();
PushApplicationStatus status = PushApplicationRegistry.getStatus( pushApplicationDescriptor );
SigservApplication.logEvent( "Status before registration: " + PushSIGService.getStatusText( status.getStatus() ) );
switch (status.getStatus()) {
case PushApplicationStatus.STATUS_ACTIVE: {
SigservApplication.logEvent( "Push status active. Skipping registration." );
PushPPGService.updateStoredStatus( status.getStatus() );
break;
}
case PushApplicationStatus.STATUS_PENDING: {
SigservApplication.logEvent( "Push status pending. Skipping registration." );
PushPPGService.updateStoredStatus( status.getStatus() );
break;
}
case PushApplicationStatus.STATUS_FAILED:
case PushApplicationStatus.STATUS_NOT_REGISTERED:
default: {
SigservApplication.logEvent( "Registering push application" );
PushApplicationRegistry.registerApplication( pushApplicationDescriptor );
status = PushApplicationRegistry.getStatus( pushApplicationDescriptor );
SigservApplication.logEvent( "Status after registration: " + PushSIGService.getStatusText( status.getStatus() ) );
break;
}
}
}
public static void mainUnregister( String[] args ) {
log.info( "Unregistering PUSH application" );
PushPPGService.unregister();
}
public static void mainStartup( String[] args ) {
log.info( "Running PUSH application" );
try {
SigservPushApplication application = new SigservPushApplication();
application.enterEventDispatcher();
}
catch (Exception e) {
mainAutoRegister( new String[] { SigservApplication.PUSH_REGISTER } );
}
}
public void onMessage( final PushInputStream inputStream, final StreamConnection conn ) {
log.info( "Recieved new PUSH message" );
threadPool.invokeLater( new Runnable() {
public void run() {
handleMessage( inputStream, conn );
}
} );
}
public static void handleMessage( PushInputStream inputStream, StreamConnection conn ) {
log.info( "Reading new PUSH message" );
PushNotification pushNotification = null;
try {
pushNotification = PushSIGService.parse( inputStream );
}
catch (Throwable t) {
log.error( "Exception while parsing new push message", t );
}
finally {
try {
inputStream.accept();
}
catch (Throwable t) {
// do nothing
}
IOUtility.safeClose( inputStream );
IOUtility.safeClose( conn );
}
Hashtable latest = pushNotification == null ? null : (Hashtable) pushNotification.message;
SigservApplication.updateStoredStatus( latest );
IconService.updateIcon();
PushSIGService.confirm( pushNotification == null ? null : pushNotification.pid );
}
public void onStatusChange( PushApplicationStatus status ) {
String errorText = status.getError();
String statusText = PushSIGService.getStatusText( status.getStatus() );
String reasonText = PushSIGService.getReasonText( status.getReason() );
SigservApplication.logEvent( "PushApplicationStatus status[" + statusText + "], error[" + errorText + "], reason[" + reasonText + "]" );
PushPPGService.updateStoredStatus( status.getStatus() );
}
public void onStatusChange( byte status ) {
switch (status) {
case PushApplicationStatus.STATUS_ACTIVE: {
startRegisterServTask();
break;
}
case PushApplicationStatus.STATUS_FAILED:
case PushApplicationStatus.STATUS_NOT_REGISTERED: {
cancelRegisterServTask();
PushSIGService.register( false );
break;
}
case PushApplicationStatus.STATUS_PENDING:
default: {
break;
}
}
}
private void cancelNetworkRequiredTask() {
if ( networkRequiredTimerTask != null ) {
networkRequiredTimerTask.cancel();
networkRequiredTimerTask = null;
}
}
private void startNetworkRequiredTask() {
cancelNetworkRequiredTask();
Timer timer = new Timer();
networkRequiredTimerTask = new NetworkRequiredTimerTask();
timer.schedule( networkRequiredTimerTask, 0, Dates.SECOND * 10 );
}
private void cancelRegisterServTask() {
if ( registerServ != null ) {
registerServ.cancel();
registerServ = null;
}
}
private void startRegisterServTask() {
cancelRegisterServTask();
Timer timer = new Timer();
registerServ = new RegisterServTimerTask();
timer.schedule( registerServ, 0, Dates.DAY );
}
public boolean requestClose() {
log.info( "Closing PUSH application" );
if ( radioStatusListener != null ) {
WLANInfo.removeListener( radioStatusListener );
removeRadioListener( radioStatusListener );
radioStatusListener = null;
}
cancelNetworkRequiredTask();
cancelRegisterServTask();
System.exit( 0 );
return true;
}
private final class RegisterServTimerTask extends TimerTask {
public void run() {
PushSIGService.register( true );
}
}
private final class NetworkRequiredTimerTask extends TimerTask {
public void run() {
log.info( "Checking PUSH registration from task" );
if ( !PushPPGService.shouldRegister() ) {
synchronized (radioStatusListener) {
log.info( "PUSH registration no longer required, canceling task" );
cancelNetworkRequiredTask();
return;
}
}
log.info( "Checking coverage for PUSH registration" );
if ( SigservApplication.hasSufficientCoverage() ) {
log.info( "Sufficient coverage, running auto PUSH registration" );
mainAutoRegister( new String[] { SigservApplication.PUSH_REGISTER } );
}
else {
log.info( "Coverage not sufficient, skipping auto PUSH registration" );
}
}
}
private final class MyRadioStatusListener extends AbstractRadioStatusListener {
private void checkRegistration() {
log.info( "Checking PUSH registration" );
if ( !PushPPGService.shouldRegister() || networkRequiredTimerTask != null ) {
synchronized (radioStatusListener) {
if ( !PushPPGService.shouldRegister() || networkRequiredTimerTask != null ) {
log.info( "PUSH registration not required or task already running" );
return;
}
}
}
log.info( "PUSH registration required, running task" );
startNetworkRequiredTask();
}
public void networkStarted( int networkId, int service ) {
super.networkStarted( networkId, service );
if ( ( service & RadioInfo.NETWORK_SERVICE_DATA ) == RadioInfo.NETWORK_SERVICE_DATA ) {
checkRegistration();
}
}
public void networkServiceChange( int networkId, int service ) {
super.networkServiceChange( networkId, service );
if ( ( service & RadioInfo.NETWORK_SERVICE_DATA ) == RadioInfo.NETWORK_SERVICE_DATA ) {
checkRegistration();
}
}
public void networkStateChange( int state ) {
super.networkStateChange( state );
checkRegistration();
}
public void networkConnected() {
super.networkConnected();
checkRegistration();
}
public void networkDisconnected( int reason ) {
super.networkDisconnected( reason );
checkRegistration();
}
}
}
| 33 | 146 | 0.641057 |
c5927fb4b6a4c8779cd7ab6e19d2ee63735271eb | 3,454 | package madgik.exareme.master.engine.iterations.scheduler;
import madgik.exareme.master.engine.iterations.scheduler.events.algorithmCompletion.AlgorithmCompletionEventHandler;
import madgik.exareme.master.engine.iterations.scheduler.events.newAlgorithm.NewAlgorithmEventHandler;
import madgik.exareme.master.engine.iterations.scheduler.events.newAlgorithm.NewAlgorithmEventListener;
import madgik.exareme.master.engine.iterations.scheduler.events.phaseCompletion.PhaseCompletionEventHandler;
import madgik.exareme.master.engine.iterations.scheduler.events.phaseCompletion.PhaseCompletionEventListener;
import madgik.exareme.master.engine.iterations.state.IterationsStateManager;
import madgik.exareme.master.engine.iterations.state.IterationsStateManagerImpl;
import madgik.exareme.utils.eventProcessor.EventProcessor;
/**
* @author Christos Aslanoglou <br> [email protected] <br> University of Athens / Department of
* Informatics and Telecommunications.
*/
class IterationsSchedulerState {
// Instance fields --------------------------------------------------------------------------
private final EventProcessor eventProcessor;
private final IterationsStateManager iterationsStateManager;
private final IterationsDispatcher iterationsDispatcher;
// Listeners & Handlers =============================
private NewAlgorithmEventHandler newAlgorithmEventHandler;
private NewAlgorithmEventListener newAlgorithmEventListener;
private PhaseCompletionEventHandler phaseCompletionEventHandler;
private PhaseCompletionEventListener phaseCompletionEventListener;
private AlgorithmCompletionEventHandler algorithmCompletionEventHandler;
IterationsSchedulerState(IterationsScheduler iterationsScheduler) {
iterationsStateManager = IterationsStateManagerImpl.getInstance();
iterationsDispatcher = IterationsDispatcher.getInstance(iterationsScheduler);
eventProcessor = new EventProcessor(1);
eventProcessor.start();
createHandlers();
createListeners();
}
private void createHandlers() {
newAlgorithmEventHandler = new NewAlgorithmEventHandler(
iterationsStateManager, iterationsDispatcher);
phaseCompletionEventHandler = new PhaseCompletionEventHandler(
iterationsStateManager, iterationsDispatcher);
algorithmCompletionEventHandler = new AlgorithmCompletionEventHandler(
iterationsStateManager, iterationsDispatcher);
}
private void createListeners() {
newAlgorithmEventListener = new NewAlgorithmEventListener();
phaseCompletionEventListener = new PhaseCompletionEventListener();
}
// Getters ----------------------------------------------------------------------------------
EventProcessor getEventProcessor() {
return eventProcessor;
}
NewAlgorithmEventHandler getNewAlgorithmEventHandler() {
return newAlgorithmEventHandler;
}
NewAlgorithmEventListener getNewAlgorithmEventListener() {
return newAlgorithmEventListener;
}
PhaseCompletionEventHandler getPhaseCompletionEventHandler() {
return phaseCompletionEventHandler;
}
PhaseCompletionEventListener getPhaseCompletionEventListener() {
return phaseCompletionEventListener;
}
AlgorithmCompletionEventHandler getAlgorithmCompletionEventHandler() {
return algorithmCompletionEventHandler;
}
}
| 45.447368 | 116 | 0.750724 |
1aa7731355a21d1e03bcddfd6ea28ad4ecef0763 | 1,361 | /*
* Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @(#)SpaceCleanedException.java 1.0 09/12/2003 12:32:02
*/
package com.j_spaces.core.exception;
/**
* This exception is thrown in case where there is an attempt to perform another space operation
* such as write, read or take while "clean" is still in progress.
*
* @author Igor Goldenberg
* @version 3.2
**/
public class SpaceCleanedException extends SpaceUnavailableException {
private static final long serialVersionUID = 6080728928804933215L;
/**
* Constructs a <code>SpaceCleanedException</code> with the specified detail message.
*
* @param s - the detail message
*/
public SpaceCleanedException(String spaceName, String s) {
super(spaceName, s);
}
} | 31.651163 | 96 | 0.720059 |
4c72301810fbb9b37f08b13ddc71730267814695 | 475 | package com.ywh.im.common.protocol.request;
import com.ywh.im.common.protocol.BasePacket;
import com.ywh.im.common.constant.Constant;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 查看群组成员请求协议包
*
* @author ywh
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ListGroupMembersRequestPacket extends BasePacket {
private String groupName;
@Override
public Byte getCommand() {
return Constant.LIST_GROUP_MEMBERS_REQUEST;
}
}
| 19 | 63 | 0.749474 |
6496b40d2a8fc565dd982e98bae905a19e8af497 | 2,645 | package com.tiny.demo.firstlinecode.stetho.httphelper;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by tiny on 17/2/22.
*/
public class OkHttpClientUtils {
private static boolean showLog = false;
private OkHttpClientUtils() {
}
/**
* 暂时未实现单例。只是简单的封装,为了方便打印log.
*
* @return
*/
public static OkHttpClient getInstance() {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
// .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
// .addHeader("Accept-Encoding", "gzip, deflate")
// .addHeader("Connection", "keep-alive")
// .addHeader("Accept", "*/*")
// .addHeader("Cookie", "add cookies here")
.build();
return chain.proceed(request);
}
});
builder = addParamsToClient(builder);
//stetho
builder.addNetworkInterceptor(new StethoInterceptor());
OkHttpClient httpClient = builder.build();
return httpClient;
}
/**
* 给okhttp添加一些数据。
*
* @param builder
* @return
*/
public static OkHttpClient.Builder addParamsToClient(OkHttpClient.Builder builder) {
return builder.cookieJar(new MyCookieManager());
}
public static void setShowLog(boolean showLog) {
OkHttpClientUtils.showLog = showLog;
}
/**
* log拦截器
*/
private static class LogInterceptor implements Interceptor {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
okhttp3.Response response = chain.proceed(chain.request());
long t2 = System.nanoTime();
okhttp3.MediaType mediaType = response.body().contentType();
String content = response.body().string();
return response.newBuilder()
.body(okhttp3.ResponseBody.create(mediaType, content))
.build();
}
}
}
| 30.056818 | 112 | 0.561437 |
874e6c8bcc4c80401b2c834d5ed9cbe84dab6659 | 1,757 | package io.growing.gateway.grpc;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import io.growing.gateway.grpc.finder.TaggedChannel;
import io.growing.gateway.meta.ServerNode;
import io.growing.gateway.meta.Upstream;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.Objects;
public final class ChannelFactory {
private static final LoadingCache<ServerNode, ManagedChannel> CHANNELS = Caffeine.newBuilder()
.expireAfterAccess(Duration.ofMinutes(5)).removalListener((key, value, cause) -> {
final ManagedChannel channel = (ManagedChannel) value;
channel.shutdown();
}).build(new CacheLoader<>() {
@Override
public @Nullable
ManagedChannel load(ServerNode key) throws Exception {
return ManagedChannelBuilder.forAddress(key.host(), key.port()).usePlaintext().build();
}
});
private ChannelFactory() {
}
public static TaggedChannel get(final ServerNode node) {
final ManagedChannel channel = CHANNELS.get(node);
assert Objects.nonNull(channel);
if (channel.isShutdown() || channel.isTerminated()) {
CHANNELS.invalidate(node);
return TaggedChannel.from(CHANNELS.get(node), node);
}
return TaggedChannel.from(channel, node);
}
public static TaggedChannel get(final Upstream upstream, final Object context) {
final ServerNode node = upstream.balancer().select(upstream.getAvailableNodes(), context);
return get(node);
}
}
| 35.857143 | 103 | 0.697211 |
b54716b6809ad688db48004c83097d7864038b1b | 1,809 | /**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2021 Ruhr University Bochum, Paderborn University, Hackmanit GmbH
*
* Licensed under Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package de.rub.nds.tlsattacker.core.workflow.task;
import de.rub.nds.tlsattacker.core.state.State;
import de.rub.nds.tlsattacker.core.workflow.DefaultWorkflowExecutor;
import de.rub.nds.tlsattacker.core.workflow.WorkflowExecutor;
import java.util.concurrent.Callable;
/**
* Do not use this Task if you want to rely on the socket state
*/
public class StateExecutionTask extends TlsTask {
private final State state;
private Callable<Integer> beforeConnectCallback = () -> {
return 0;
};
public StateExecutionTask(State state, int reexecutions) {
super(reexecutions);
this.state = state;
}
@Override
public boolean execute() {
beforeConnectAction();
WorkflowExecutor executor = new DefaultWorkflowExecutor(state);
executor.executeWorkflow();
if (state.getTlsContext().isReceivedTransportHandlerException()) {
throw new RuntimeException("TransportHandler exception received.");
}
return true;
}
private void beforeConnectAction() {
try {
beforeConnectCallback.call();
} catch (Exception ex) {
}
}
public Callable<Integer> getBeforeConnectCallback() {
return beforeConnectCallback;
}
public void setBeforeConnectCallback(Callable<Integer> beforeConnectCallback) {
this.beforeConnectCallback = beforeConnectCallback;
}
public State getState() {
return state;
}
@Override
public void reset() {
state.reset();
}
}
| 26.602941 | 83 | 0.681039 |
b677247a9ac51259162cef61bcaab65eb2f6647c | 506 | package com.zmlcoder.rpcx.events;
import java.util.HashMap;
import java.util.Map;
public class RpcxEvent {
private String type = "";
private Map<String, Object> params = new HashMap<>();
public RpcxEvent(String eventType) {
type = eventType;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
}
| 16.322581 | 54 | 0.6917 |
de1028b0e839faf0c0b27258530753fa594c4a6f | 2,051 | /*
* Copyright (c) 2016. Matsuda, Akihit (akihito104)
*
* 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.freshdigitable.udonroad.subscriber;
import android.support.annotation.NonNull;
import com.freshdigitable.udonroad.R;
import com.freshdigitable.udonroad.ffab.IndicatableFFAB.OnIffabItemSelectedListener;
import java.util.Arrays;
import javax.inject.Inject;
import io.reactivex.Observable;
/**
* StatusRequestWorker creates twitter request for status resources and subscribes its response
* with user feedback.
* <p>
* Created by akihit on 2016/08/01.
*/
public class StatusRequestWorker implements RequestWorker {
private static final String TAG = StatusRequestWorker.class.getSimpleName();
private StatusRepository repository;
@Inject
StatusRequestWorker(@NonNull StatusRepository repository) {
this.repository = repository;
}
@Override
public OnIffabItemSelectedListener getOnIffabItemSelectedListener(long selectedId) {
return item -> {
final int itemId = item.getItemId();
if (itemId == R.id.iffabMenu_main_fav) {
repository.createFavorite(selectedId);
} else if (itemId == R.id.iffabMenu_main_rt) {
repository.retweetStatus(selectedId);
} else if (itemId == R.id.iffabMenu_main_favRt) {
Observable.concatDelayError(Arrays.asList(
repository.observeCreateFavorite(selectedId).toObservable(),
repository.observeRetweetStatus(selectedId).toObservable())
).subscribe(s -> {}, e -> {});
}
};
}
}
| 33.080645 | 95 | 0.734276 |
b7f95a16fdbe77608370b15b960260205141b4f7 | 2,378 | package com.uddernetworks.mspaint.code.languages.java;
import com.uddernetworks.code.lexer.java.Java9Lexer;
import com.uddernetworks.code.lexer.java.Java9Parser;
import com.uddernetworks.mspaint.code.languages.HighlightData;
import com.uddernetworks.mspaint.code.languages.Language;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.TokenStream;
import java.util.Arrays;
import java.util.Map;
public class JavaHighlightData extends HighlightData {
{
this.tokenMap = Map.of(
Arrays.asList("'open'", "'module'", "'requires'", "'exports'", "'to'", "'opens'", "'uses'", "'provides'", "'with'", "'transitive'", "'abstract'", "'assert'", "'boolean'", "'break'", "'byte'", "'case'", "'catch'", "'char'", "'class'", "'const'", "'continue'", "'default'", "'do'", "'double'", "'else'", "'enum'", "'extends'", "'final'", "'finally'", "'float'", "'for'", "'if'", "'goto'", "'implements'", "'import'", "'instanceof'", "'int'", "'interface'", "'long'", "'native'", "'new'", "'package'", "'private'", "'protected'", "'public'", "'return'", "'short'", "'static'", "'strictfp'", "'super'", "'switch'", "'synchronized'", "'this'", "'throw'", "'throws'", "'transient'", "'try'", "'void'", "'volatile'", "'while'", "BooleanLiteral", "CharacterLiteral", "'null'"), 0xCC7832, // Orange
Arrays.asList("StringLiteral"), 0x6A8759, // Green
Arrays.asList("IntegerLiteral", "FloatingPointLiteral"), 0x6897BB, // Blue
Arrays.asList("'_'", "'('", "')'", "'{'", "'}'", "'['", "']'", "';'", "','", "'.'", "'...'", "'@'", "'::'", "'='", "'>'", "'<'", "'!'", "'~'", "'?'", "':'", "'->'", "'=='", "'<='", "'>='", "'!='", "'&&'", "'||'", "'++'", "'--'", "'+'", "'-'", "'*'", "'/'", "'&'", "'|'", "'^'", "'%'", "'+='", "'-='", "'*='", "'/='", "'&='", "'|='", "'^='", "'%='", "'<<='", "'>>='", "'>>>='", "Identifier", "WS"), 0x000000, // Black
Arrays.asList("COMMENT", "LINE_COMMENT"), 0x808080 // Gray
);
}
public JavaHighlightData(Language language) {
super(language);
}
@Override
public Lexer getLexer(CharStream inputStream) {
return new Java9Lexer(inputStream);
}
@Override
public Parser getParser(TokenStream input) {
return new Java9Parser(input);
}
}
| 58 | 805 | 0.526913 |
f14282ecac7f97d91fb2183998127c18d410e832 | 18,152 | package client.controllers;
import client.HandleInput;
import client.Main;
import client.data.GroupAndChannel;
import client.data.User;
import com.jfoenix.controls.*;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class ListController
{
private JFXDialog dialog;
private JFXDialog dialog2;
private StackPane stackPane;
public DrawerController drawerController;
@FXML private JFXListView<VBox> sendRequestListView;
@FXML private JFXListView<VBox> receiveRequestListView;
@FXML public JFXListView<VBox> contactsListView;
@FXML private JFXListView<VBox> blockedListView;
@FXML private JFXListView<VBox> allUsersListView;
@FXML private JFXListView<VBox> channelsListView;
@FXML private JFXListView<VBox> groupsListView;
public static HashMap<VBox, User> map = new HashMap<>();
public static HashMap<VBox, GroupAndChannel> conversations = new HashMap<>();
public void setFirstVariable(DrawerController drawerController, JFXDialog dialog, StackPane stackPane)
{
this.drawerController = drawerController;
this.dialog = dialog;
this.stackPane = stackPane;
HandleInput.listController = this;
}
public void updateList(String doWhat)
{
Main.client.getUsersList(doWhat);
}
public void closeDialog()
{
if (dialog.isOverlayClose())
{
dialog.close();
}
}
public void onAllUsersListViewClicked()
{
if (! allUsersListView.getSelectionModel().isEmpty())
{
JFXDialogLayout layout = new JFXDialogLayout();
layout.setHeading(new Text("Request"));
layout.setBody(new Text("Are You Sure To Send Request To This User ???"));
JFXButton button = new JFXButton("OK");
button.setOnMouseClicked(e ->
{
Main.client.sendRequest(
map.get(allUsersListView.getSelectionModel().getSelectedItem()));
allUsersListView.getSelectionModel().clearSelection();
dialog2.close();
});
layout.setActions(button);
dialog2 = new JFXDialog(stackPane, layout, JFXDialog.DialogTransition.CENTER);
dialog2.show();
}
}
public void onBlockedListViewClicked()
{
if (! blockedListView.getSelectionModel().isEmpty())
{
JFXDialogLayout layout = new JFXDialogLayout();
layout.setHeading(new Text("UnBlock"));
layout.setBody(new Text("Are You Sure You Want To Unblock This User ???"));
JFXButton button = new JFXButton("OK");
button.setOnMouseClicked(e ->
{
Main.client.unblock(
map.get(blockedListView.getSelectionModel().getSelectedItem()));
blockedListView.getSelectionModel().clearSelection();
dialog2.close();
});
layout.setActions(button);
dialog2 = new JFXDialog(stackPane, layout, JFXDialog.DialogTransition.CENTER);
dialog2.show();
}
}
public void onChannelsListViewClicked()
{
if (! channelsListView.getSelectionModel().isEmpty())
{
JFXDialogLayout layout = new JFXDialogLayout();
layout.setHeading(new Text("Join"));
layout.setBody(new Text("Are You Sure To Join To This Channel ???"));
JFXButton button = new JFXButton("OK");
button.setOnMouseClicked(e ->
{
Main.client.join(
conversations.get(channelsListView.getSelectionModel().getSelectedItem()), "Channel");
dialog2.close();
VBox vBox = channelsListView.getSelectionModel().getSelectedItem();
drawerController.controller.chatController.openDrawer(vBox, false);
channelsListView.getSelectionModel().clearSelection();
dialog.close();
drawerController.controller.listView.getItems().add(vBox);
});
layout.setActions(button);
dialog2 = new JFXDialog(stackPane, layout, JFXDialog.DialogTransition.CENTER);
dialog2.show();
}
}
public void onContactsListViewClicked()
{
if (! contactsListView.getSelectionModel().isEmpty())
{
VBox vBox = contactsListView.getSelectionModel().getSelectedItem();
drawerController.controller.chatController.openDrawer(vBox, true);
contactsListView.getSelectionModel().clearSelection();
dialog.close();
if (! drawerController.controller.listView.getItems().contains(vBox))
{
drawerController.controller.listView.getItems().add(vBox);
}
}
}
public void onGroupsListViewClicked()
{
if (! groupsListView.getSelectionModel().isEmpty())
{
JFXDialogLayout layout = new JFXDialogLayout();
layout.setHeading(new Text("Join"));
layout.setBody(new Text("Are You Sure To Send Request To This Group ???"));
JFXButton button = new JFXButton("OK");
button.setOnMouseClicked(e ->
{
Main.client.join(
conversations.get(groupsListView.getSelectionModel().getSelectedItem()), "Group");
dialog2.close();
VBox vBox = groupsListView.getSelectionModel().getSelectedItem();
drawerController.controller.chatController.openDrawer(vBox, false);
groupsListView.getSelectionModel().clearSelection();
dialog.close();
drawerController.controller.listView.getItems().add(vBox);
});
layout.setActions(button);
dialog2 = new JFXDialog(stackPane, layout, JFXDialog.DialogTransition.CENTER);
dialog2.show();
}
}
public void onReceiveRequestListViewClicked(MouseEvent event)
{
if (! receiveRequestListView.getSelectionModel().isEmpty())
{
JFXPopup popup = new JFXPopup();
JFXButton accept = new JFXButton("Accept");
accept.setOnMouseClicked(event1 ->
{
Main.client.manageRequests(
map.get(receiveRequestListView.getSelectionModel().getSelectedItem()),
"Accept"
);
receiveRequestListView.getSelectionModel().clearSelection();
popup.hide();
});
JFXButton block = new JFXButton("Block");
block.setOnMouseClicked(event1 ->
{
Main.client.manageRequests(
map.get(receiveRequestListView.getSelectionModel().getSelectedItem()),
"Block"
);
receiveRequestListView.getSelectionModel().clearSelection();
popup.hide();
});
JFXButton reject = new JFXButton("Reject");
reject.setOnMouseClicked(event1 ->
{
Main.client.manageRequests(
map.get(receiveRequestListView.getSelectionModel().getSelectedItem()),
"Reject"
);
receiveRequestListView.getSelectionModel().clearSelection();
popup.hide();
});
VBox vBox = new VBox(accept, block, reject);
popup.setPopupContent(vBox);
popup.show(
receiveRequestListView, JFXPopup.PopupVPosition.TOP, JFXPopup.PopupHPosition.LEFT, event.getX(),
event.getY()
);
}
}
public void onSendRequestListViewClicked()
{
if (! sendRequestListView.getSelectionModel().isEmpty())
{
JFXDialogLayout layout = new JFXDialogLayout();
layout.setHeading(new Text("Cancel"));
layout.setBody(new Text("Do You Want To Cancel The Request ???"));
JFXButton button = new JFXButton("OK");
button.setOnMouseClicked(e ->
{
Main.client.manageRequests(
map.get(sendRequestListView.getSelectionModel().getSelectedItem()),
"Cancel"
);
dialog2.close();
sendRequestListView.getItems().remove(
sendRequestListView.getSelectionModel().getSelectedItem());
sendRequestListView.getSelectionModel().clearSelection();
});
layout.setActions(button);
dialog2 = new JFXDialog(stackPane, layout, JFXDialog.DialogTransition.CENTER);
dialog2.show();
}
}
public void send()
{
updateList("SendRequests");
}
public void receive()
{
updateList("ReceiveRequests");
}
public void blocked()
{
updateList("Blocked");
}
public void contacts()
{
updateList("Contacts");
}
public void allUsers()
{
updateList("AllUsers");
}
public void channels()
{
updateList("Channels");
}
public void groups()
{
updateList("Groups");
}
public class UpdateList extends Task
{
private ArrayList<User> list;
private String doWhat;
private ArrayList<GroupAndChannel> groupAndChannels;
private boolean flag;
public UpdateList(ArrayList<User> list, String doWhat)
{
this.list = list;
this.doWhat = doWhat;
flag = true;
}
public UpdateList(String doWhat, ArrayList<GroupAndChannel> groupAndChannels)
{
this.doWhat = doWhat;
this.groupAndChannels = groupAndChannels;
flag = false;
}
@Override protected Object call()
{
VBox[] vBoxes;
if (flag)
{
vBoxes = new VBox[list.size()];
for (int i = 0; i < list.size(); i++)
{
try
{
FXMLLoader listLoader = new FXMLLoader();
listLoader.setLocation(Main.class.getResource(Main.assets + "FXML/List.fxml"));
vBoxes[i] = listLoader.load();
((Label) (((VBox) (((HBox) (vBoxes[i].getChildren().get(0))).getChildren().get(
2))).getChildren().get(0))).setText(list.get(i).getName());
((Label) (((VBox) (((HBox) (vBoxes[i].getChildren().get(0))).getChildren().get(
2))).getChildren().get(1))).setText(list.get(i).isOnline() ? "Online" : "Offline");
ImageView imageView = ((ImageView) (((HBox) (vBoxes[i].getChildren().get(0))).getChildren().get(
0)));
imageView.setImage(new Image(new FileInputStream(list.get(i).getProfilePhotoUrl())));
imageView.setClip(new Circle(40, 40, 40));
map.put(vBoxes[i], list.get(i));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else
{
vBoxes = new VBox[groupAndChannels.size()];
System.out.println(groupAndChannels.size());
for (int i = 0; i < groupAndChannels.size(); i++)
{
try
{
FXMLLoader listLoader = new FXMLLoader();
listLoader.setLocation(Main.class.getResource(Main.assets + "FXML/List.fxml"));
vBoxes[i] = listLoader.load();
((Label) (((VBox) (((HBox) (vBoxes[i].getChildren().get(0))).getChildren().get(
2))).getChildren().get(0))).setText(groupAndChannels.get(i).getName());
((Label) (((VBox) (((HBox) (vBoxes[i].getChildren().get(0))).getChildren().get(
2))).getChildren().get(1))).setText(
String.format("%d Members", groupAndChannels.get(i).getMembers()));
ImageView imageView = ((ImageView) (((HBox) (vBoxes[i].getChildren().get(0))).getChildren().get(
0)));
imageView.setImage(
new Image(new FileInputStream(groupAndChannels.get(i).getProfilePhotoUrl())));
imageView.setClip(new Circle(40, 40, 40));
conversations.put(vBoxes[i], groupAndChannels.get(i));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
switch (doWhat)
{
case "SendRequest":
Platform.runLater(() ->
{
sendRequestListView.getItems().clear();
sendRequestListView.getItems().addAll(vBoxes);
}
);
break;
case "ReceiveRequest":
Platform.runLater(() ->
{
receiveRequestListView.getItems().clear();
receiveRequestListView.getItems().addAll(vBoxes);
}
);
break;
case "Contacts":
Platform.runLater(() ->
{
contactsListView.getItems().clear();
contactsListView.getItems().addAll(vBoxes);
}
);
break;
case "Blocked":
Platform.runLater(() ->
{
blockedListView.getItems().clear();
blockedListView.getItems().addAll(vBoxes);
});
break;
case "AllUsers":
Platform.runLater(() ->
{
allUsersListView.getItems().clear();
allUsersListView.getItems().addAll(vBoxes);
}
);
break;
case "Groups":
Platform.runLater(() ->
{
groupsListView.getItems().clear();
groupsListView.getItems().addAll(vBoxes);
}
);
break;
case "Channels":
Platform.runLater(() ->
{
channelsListView.getItems().clear();
channelsListView.getItems().addAll(vBoxes);
}
);
break;
}
return null;
}
}
}
| 39.036559 | 135 | 0.452292 |
7d60b634ed3a016822239ef77d28c1236866308c | 464 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package cn.com.fmsh.tsm.business.constants;
// Referenced classes of package cn.com.fmsh.tsm.business.constants:
// Constants
public static interface Constants$PayChannel
{
public static final byte ONEKEY = 1;
public static final byte SECURITY = 2;
public static final byte UNIONPAY = 3;
}
| 25.777778 | 68 | 0.75431 |
c24340f19c4fe1483533a95feffe5dd957cfecd0 | 2,464 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.apps.muzei.featuredart.FeaturedArtSource;
/**
* Broadcast receiver used to watch for changes to installed packages on the device. This triggers
* a cleanup of sources (in case one was uninstalled), or a data update request to a source
* if it was updated (its package was replaced).
*/
public class SourcePackageChangeReceiver extends WakefulBroadcastReceiver {
private static final String TAG = "SourcePackageChangeRcvr";
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getData() == null) {
return;
}
String packageName = intent.getData().getSchemeSpecificPart();
ComponentName selectedComponent = SourceManager.getSelectedSource(context);
if (selectedComponent == null ||
!TextUtils.equals(packageName, selectedComponent.getPackageName())) {
return;
}
try {
context.getPackageManager().getServiceInfo(selectedComponent, 0);
} catch (PackageManager.NameNotFoundException e) {
Log.i(TAG, "Selected source " + selectedComponent
+ " is no longer available; switching to default.");
SourceManager.selectSource(context,
new ComponentName(context, FeaturedArtSource.class));
return;
}
// Some other change.
Log.i(TAG, "Source package changed or replaced. Re-subscribing to " + selectedComponent);
SourceManager.subscribeToSelectedSource(context);
}
}
| 37.907692 | 98 | 0.702922 |
9d303dccb75b86208c48cb7c80bffef9b88d273e | 6,220 | package com.jaiwo99.cards.rest.api;
import com.jaiwo99.cards.AbstractControllerTest;
import com.jaiwo99.cards.domain.CardDeal;
import com.jaiwo99.cards.domain.Jiang;
import com.jaiwo99.cards.repository.CardDealRepository;
import com.jaiwo99.cards.repository.JiangRepository;
import com.jaiwo99.cards.util.EntityGenerator;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import static com.jaiwo99.cards.domain.CardStatus.PICKED;
import static com.jayway.jsonpath.JsonPath.read;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
public class JiangDealRestControllerTest extends AbstractControllerTest {
@Autowired
private RestTemplate restTemplate;
@Autowired
private CardDealRepository cardDealRepository;
@Autowired
private JiangRepository jiangRepository;
@Autowired
private EntityGenerator entityGenerator;
@Value("${jiang.picking.count}")
private String chooseCount;
@Test
public void reset_should_remove_all_jiang_in_jiangPicking_repo() throws Exception {
final Jiang jiang = entityGenerator.generateJiang();
cardDealRepository.save(new CardDeal(jiang.getId(), PICKED));
assertThat(cardDealRepository.findAll().size(), is(1));
restTemplate.postForEntity(urlWrapper("/rest/jiang/reset"), new HttpEntity<Void>(null, jsonHeader()), String.class);
assertThat(cardDealRepository.findAll().size(), is(0));
}
@Test
public void listNew_should_only_list_available_jiang() throws Exception {
entityGenerator.generateJiang(10);
final Jiang jiang = entityGenerator.generateJiang();
assertThat(jiangRepository.findAll().size(), is(11));
final ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlWrapper("/rest/jiang/listNew"), String.class);
final List<Jiang> jiangList = read(responseEntity.getBody(), "$.payload[*]");
assertThat(jiangList.size(), is(11));
cardDealRepository.save(new CardDeal(jiang.getId(), PICKED));
final ResponseEntity<String> responseEntityAfterPicking = restTemplate.getForEntity(urlWrapper("/rest/jiang/listNew"), String.class);
final List<Jiang> jiangListAfterPicking = read(responseEntityAfterPicking.getBody(), "$.payload[*]");
assertThat(jiangListAfterPicking.size(), is(10));
}
@Test
public void listChosen_should_not_list_picked_jiang() throws Exception {
final Jiang jiangToBePicked = entityGenerator.generateJiang();
assertThat(jiangRepository.findAll().size(), is(1));
final ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlWrapper("/rest/jiang/listChosen"), String.class);
final List<Jiang> jiangList = read(responseEntity.getBody(), "$.payload[*]");
assertThat(jiangList.size(), is(0));
restTemplate.postForEntity(urlWrapper("/rest/jiang/pick/"+ jiangToBePicked.getId()), new HttpEntity<Void>(null, jsonHeader()), String.class);
final ResponseEntity<String> responseEntityAfterPick = restTemplate.getForEntity(urlWrapper("/rest/jiang/listChosen"), String.class);
final List<Jiang> jiangListAfterPick = read(responseEntityAfterPick.getBody(), "$.payload[*]");
assertThat(jiangListAfterPick.size(), is(0));
}
@Test
public void listChosen_should_list_chosen_jiang() throws Exception {
entityGenerator.generateJiang(10);
final ResponseEntity<String> chooseEntity = restTemplate.postForEntity(urlWrapper("/rest/jiang/choose"), new HttpEntity<Void>(null, jsonHeader()), String.class);
final List<Jiang> chosenList = read(chooseEntity.getBody(), "$.payload[*]");
final ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlWrapper("/rest/jiang/listChosen"), String.class);
final List<Jiang> jiangList = read(responseEntity.getBody(), "$.payload[*]");
assertThat(jiangList.size(), is(Integer.valueOf(chooseCount)));
assertThat(jiangList.size(), equalTo(chosenList.size()));
assertThat(jiangList.containsAll(chosenList), is(true));
}
@Test
public void listPicked_should_list_all_picked_jiang() throws Exception {
final Jiang jiang = entityGenerator.generateJiang();
assertThat(jiangRepository.findAll().size(), is(1));
assertThat(cardDealRepository.findAll().size(), is(0));
cardDealRepository.save(new CardDeal(jiang.getId(), PICKED));
final ResponseEntity<String> responseEntityAfterPicking = restTemplate.getForEntity(urlWrapper("/rest/jiang/listPicked"), String.class);
final List<Jiang> jiangListAfterPicking = read(responseEntityAfterPicking.getBody(), "$.payload[*]");
assertThat(jiangListAfterPicking.size(), is(1));
}
@Test
public void choose_should_return_defined_count_of_jiang() throws Exception {
entityGenerator.generateJiang(10);
final ResponseEntity<String> responseEntity = restTemplate.postForEntity(urlWrapper("/rest/jiang/choose"), new HttpEntity<Void>(null, jsonHeader()), String.class);
final List<Jiang> jiangListAfterPicking = read(responseEntity.getBody(), "$.payload[*]");
assertThat(jiangListAfterPicking.size(), is(Integer.valueOf(chooseCount)));
}
@Test
public void pick_should_create_entity_in_jiang_picking_repo() throws Exception {
entityGenerator.generateJiang(10);
final Jiang jiang = entityGenerator.generateJiang();
assertThat(cardDealRepository.findAll().size(), is(0));
restTemplate.postForEntity(urlWrapper("/rest/jiang/pick/" + jiang.getId()), new HttpEntity<Void>(null, jsonHeader()), String.class);
assertThat(cardDealRepository.findAll().size(), is(1));
assertThat(cardDealRepository.findByCard(jiang.getId()), is(notNullValue()));
}
} | 39.871795 | 171 | 0.732476 |
9556922077ce1bd87336125226e0cdb04de693cf | 2,202 | package com.rms.reservationservice.service;
import com.rms.reservationservice.entity.ReservationEntity;
import com.rms.reservationservice.model.Reservation;
import com.rms.reservationservice.repository.ReservationRepository;
import org.springframework.stereotype.Service;
import static com.rms.reservationservice.utils.IdGenerator.generateId;
@Service
public class ReservationServiceImpl implements ReservationService {
private final ReservationRepository reservationRepository;
public ReservationServiceImpl(ReservationRepository reservationRepository) {
this.reservationRepository = reservationRepository;
}
private static final int LARGE_GROUP_OF_GUESTS = 6;
private static final int ONE_HOUR = 1;
private static final int TWO_HOURS = 2;
@Override
public Reservation saveReservation(Reservation reservation) {
Reservation.ReservationBuilder reservationBuilder = reservation.toBuilder();
if (reservation.getId() == null) {
reservationBuilder.id(generateId(reservation.getFirstName(), reservation.getLastName()));
}
if (reservation.getNumberOfGuests() < LARGE_GROUP_OF_GUESTS) {
reservationBuilder.duration(ONE_HOUR);
} else {
reservationBuilder.duration(TWO_HOURS);
}
Reservation updatedReservation = reservationBuilder.build();
ReservationEntity reservationEntity = ReservationEntity.from(updatedReservation);
ReservationEntity savedEntity = reservationRepository.save(reservationEntity);
return Reservation.from(savedEntity);
}
@Override
public Reservation getReservationById(String reservationId) {
return reservationRepository.findById(reservationId)
.map(Reservation::from)
.get();
}
@Override
public Reservation updateReservation(String reservationId, Reservation reservation) {
Reservation reservationWithId = reservation.toBuilder().id(reservationId).build();
return saveReservation(reservationWithId);
}
@Override
public void deleteReservation(String reservationId) {
reservationRepository.deleteById(reservationId);
}
}
| 37.965517 | 101 | 0.743869 |
41d007c6ca2f6f539c4221ff638dc8466221c2bb | 5,196 | package org.infinispan.api;
import javax.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.distribution.MagicKey;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.CountingRpcManager;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* @author Pedro Ruivo
* @since 6.0
*/
@Test(groups = "functional", testName = "api.RepeatableReadRemoteGetCountTest")
public class RepeatableReadRemoteGetCountTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
builder.clustering().hash().numOwners(1);
createClusteredCaches(2, builder);
}
public void testOnKeyInitialized() throws Exception {
doTest(true);
}
public void testOnKeyNonInitialized() throws Exception {
doTest(false);
}
public void testWithoutReading() throws Exception {
final Object key = new MagicKey("key", cache(0));
final Cache<Object, Object> cache = cache(1);
final TransactionManager tm = tm(1);
final CountingRpcManager rpcManager = replaceRpcManager(cache);
cache(0).put(key, "v0");
tm.begin();
rpcManager.resetStats();
cache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put(key, "v1");
AssertJUnit.assertEquals("Wrong number of gets after put.", 0, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong value read.", "v1", cache.get(key));
AssertJUnit.assertEquals("Wrong number of gets after read.", 0, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong put return value.", "v1", cache.put(key, "v2"));
AssertJUnit.assertEquals("Wrong number of gets after put.", 0, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong replace return value.", "v2", cache.replace(key, "v3"));
AssertJUnit.assertEquals("Wrong number of gets after replace.", 0, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong conditional replace return value.", true, cache.replace(key, "v3", "v4"));
AssertJUnit.assertEquals("Wrong number of gets after conditional replace.", 0, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong conditional remove return value.", true, cache.remove(key, "v4"));
AssertJUnit.assertEquals("Wrong number of gets after conditional remove.", 0, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong conditional put return value.", null, cache.putIfAbsent(key, "v5"));
AssertJUnit.assertEquals("Wrong number of gets after conditional put.", 0, rpcManager.clusterGet);
tm.commit();
}
private void doTest(boolean initialized) throws Exception {
final Object key = new MagicKey("key", cache(0));
final Cache<Object, Object> cache = cache(1);
final TransactionManager tm = tm(1);
final CountingRpcManager rpcManager = replaceRpcManager(cache);
if (initialized) {
cache(0).put(key, "v1");
}
tm.begin();
rpcManager.resetStats();
AssertJUnit.assertEquals("Wrong value read.", initialized ? "v1" : null, cache.get(key));
AssertJUnit.assertEquals("Wrong number of gets after read.", 1, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong put return value.", initialized ? "v1" : null, cache.put(key, "v2"));
AssertJUnit.assertEquals("Wrong number of gets after put.", 1, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong replace return value.", "v2", cache.replace(key, "v3"));
AssertJUnit.assertEquals("Wrong number of gets after replace.", 1, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong conditional replace return value.", true, cache.replace(key, "v3", "v4"));
AssertJUnit.assertEquals("Wrong number of gets after conditional replace.", 1, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong conditional remove return value.", true, cache.remove(key, "v4"));
AssertJUnit.assertEquals("Wrong number of gets after conditional remove.", 1, rpcManager.clusterGet);
AssertJUnit.assertEquals("Wrong conditional put return value.", null, cache.putIfAbsent(key, "v5"));
AssertJUnit.assertEquals("Wrong number of gets after conditional put.", 1, rpcManager.clusterGet);
tm.commit();
}
private CountingRpcManager replaceRpcManager(Cache cache) {
RpcManager current = TestingUtil.extractComponent(cache, RpcManager.class);
if (current instanceof CountingRpcManager) {
return (CountingRpcManager) current;
}
CountingRpcManager countingRpcManager = new CountingRpcManager(current);
TestingUtil.replaceComponent(cache, RpcManager.class, countingRpcManager, true);
return countingRpcManager;
}
}
| 45.182609 | 112 | 0.72883 |
b2422ed9df2bf9f6b68437a72d2548a2aa658f18 | 152 | public class Main {
public static void main(String[] args) {
System.out.println("main starts");
C c = new C(1);
System.out.println("yeah~");
}
} | 21.714286 | 41 | 0.644737 |
57dc261b1d719176454dd68ba40a63299c4a6619 | 8,057 | package android.support.transition;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.p000v4.view.C0646w;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import java.lang.reflect.Method;
import java.util.ArrayList;
/* renamed from: android.support.transition.fa */
/* compiled from: ViewOverlayApi14 */
class C0364fa implements C0369ha {
/* renamed from: a */
protected C0365a f1237a;
/* renamed from: android.support.transition.fa$a */
/* compiled from: ViewOverlayApi14 */
static class C0365a extends ViewGroup {
/* renamed from: a */
static Method f1238a;
/* renamed from: b */
ViewGroup f1239b;
/* renamed from: c */
View f1240c;
/* renamed from: d */
ArrayList<Drawable> f1241d = null;
/* renamed from: e */
C0364fa f1242e;
static {
try {
f1238a = ViewGroup.class.getDeclaredMethod("invalidateChildInParentFast", new Class[]{Integer.TYPE, Integer.TYPE, Rect.class});
} catch (NoSuchMethodException e) {
}
}
C0365a(Context context, ViewGroup hostView, View requestingView, C0364fa viewOverlay) {
super(context);
this.f1239b = hostView;
this.f1240c = requestingView;
setRight(hostView.getWidth());
setBottom(hostView.getHeight());
hostView.addView(this);
this.f1242e = viewOverlay;
}
public boolean dispatchTouchEvent(MotionEvent ev) {
return false;
}
/* renamed from: a */
public void mo4814a(Drawable drawable) {
if (this.f1241d == null) {
this.f1241d = new ArrayList<>();
}
if (!this.f1241d.contains(drawable)) {
this.f1241d.add(drawable);
invalidate(drawable.getBounds());
drawable.setCallback(this);
}
}
/* renamed from: b */
public void mo4817b(Drawable drawable) {
ArrayList<Drawable> arrayList = this.f1241d;
if (arrayList != null) {
arrayList.remove(drawable);
invalidate(drawable.getBounds());
drawable.setCallback(null);
}
}
/* access modifiers changed from: protected */
public boolean verifyDrawable(Drawable who) {
if (!super.verifyDrawable(who)) {
ArrayList<Drawable> arrayList = this.f1241d;
if (arrayList == null || !arrayList.contains(who)) {
return false;
}
}
return true;
}
/* renamed from: a */
public void mo4815a(View child) {
if (child.getParent() instanceof ViewGroup) {
ViewGroup parent = (ViewGroup) child.getParent();
if (!(parent == this.f1239b || parent.getParent() == null || !C0646w.m2986t(parent))) {
int[] parentLocation = new int[2];
int[] hostViewLocation = new int[2];
parent.getLocationOnScreen(parentLocation);
this.f1239b.getLocationOnScreen(hostViewLocation);
C0646w.m2948a(child, parentLocation[0] - hostViewLocation[0]);
C0646w.m2965b(child, parentLocation[1] - hostViewLocation[1]);
}
parent.removeView(child);
if (child.getParent() != null) {
parent.removeView(child);
}
}
super.addView(child, getChildCount() - 1);
}
/* renamed from: b */
public void mo4818b(View view) {
super.removeView(view);
if (mo4816a()) {
this.f1239b.removeView(this);
}
}
/* access modifiers changed from: 0000 */
/* renamed from: a */
public boolean mo4816a() {
if (getChildCount() == 0) {
ArrayList<Drawable> arrayList = this.f1241d;
if (arrayList == null || arrayList.size() == 0) {
return true;
}
}
return false;
}
public void invalidateDrawable(Drawable drawable) {
invalidate(drawable.getBounds());
}
/* access modifiers changed from: protected */
public void dispatchDraw(Canvas canvas) {
int[] contentViewLocation = new int[2];
int[] hostViewLocation = new int[2];
this.f1239b.getLocationOnScreen(contentViewLocation);
this.f1240c.getLocationOnScreen(hostViewLocation);
int numDrawables = 0;
canvas.translate((float) (hostViewLocation[0] - contentViewLocation[0]), (float) (hostViewLocation[1] - contentViewLocation[1]));
canvas.clipRect(new Rect(0, 0, this.f1240c.getWidth(), this.f1240c.getHeight()));
super.dispatchDraw(canvas);
ArrayList<Drawable> arrayList = this.f1241d;
if (arrayList != null) {
numDrawables = arrayList.size();
}
for (int i = 0; i < numDrawables; i++) {
((Drawable) this.f1241d.get(i)).draw(canvas);
}
}
/* access modifiers changed from: protected */
public void onLayout(boolean changed, int l, int t, int r, int b) {
}
/* renamed from: a */
private void m1905a(int[] offset) {
int[] contentViewLocation = new int[2];
int[] hostViewLocation = new int[2];
this.f1239b.getLocationOnScreen(contentViewLocation);
this.f1240c.getLocationOnScreen(hostViewLocation);
offset[0] = hostViewLocation[0] - contentViewLocation[0];
offset[1] = hostViewLocation[1] - contentViewLocation[1];
}
public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
if (this.f1239b != null) {
dirty.offset(location[0], location[1]);
if (this.f1239b instanceof ViewGroup) {
location[0] = 0;
location[1] = 0;
int[] offset = new int[2];
m1905a(offset);
dirty.offset(offset[0], offset[1]);
return super.invalidateChildInParent(location, dirty);
}
invalidate(dirty);
}
return null;
}
}
C0364fa(Context context, ViewGroup hostView, View requestingView) {
this.f1237a = new C0365a(context, hostView, requestingView, this);
}
/* renamed from: d */
static ViewGroup m1902d(View view) {
View parent = view;
while (parent != null) {
if (parent.getId() == 16908290 && (parent instanceof ViewGroup)) {
return (ViewGroup) parent;
}
if (parent.getParent() instanceof ViewGroup) {
parent = (ViewGroup) parent.getParent();
}
}
return null;
}
/* renamed from: c */
static C0364fa m1901c(View view) {
ViewGroup contentView = m1902d(view);
if (contentView == null) {
return null;
}
int numChildren = contentView.getChildCount();
for (int i = 0; i < numChildren; i++) {
View child = contentView.getChildAt(i);
if (child instanceof C0365a) {
return ((C0365a) child).f1242e;
}
}
return new C0349X(contentView.getContext(), contentView, view);
}
/* renamed from: a */
public void mo4803a(Drawable drawable) {
this.f1237a.mo4814a(drawable);
}
/* renamed from: b */
public void mo4804b(Drawable drawable) {
this.f1237a.mo4817b(drawable);
}
}
| 34.579399 | 143 | 0.545613 |
69b1c7b77e18265b8a81c93426f74da1ebd9a475 | 4,686 | package com.baidubce.services.bos.demo;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 简单拷贝、分块拷贝的demo
*/
public class CopyObjectDemo {
// 小于5G的文件直接简单拷贝
public static void copyObjectSimple() {
String ACCESS_KEY_ID = "akxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 用户的Access Key ID
String SECRET_ACCESS_KEY = "skxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 用户的Secret Access Key
String ENDPOINT = "bj.bcebos.com"; // 用户自己指定的域名,参考说明文档
// 初始化一个BosClient
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
config.setEndpoint(ENDPOINT);
BosClient client = new BosClient(config);
// 创建CopyObjectRequest对象
CopyObjectRequest copyObjectRequest =
new CopyObjectRequest("srcBucketName", "srcKey", "destBucketName", "destKey");
// 也可以设置新的Metadata
Map<String, String> userMetadata = new HashMap<String, String>();
userMetadata.put("user-meta-key", "user-meta-value");
ObjectMetadata meta = new ObjectMetadata();
meta.setUserMetadata(userMetadata);
copyObjectRequest.setNewObjectMetadata(meta);
// 复制Object
CopyObjectResponse copyObjectResponse = client.copyObject(copyObjectRequest);
System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified());
// 关闭客户端
client.shutdown();
}
// 大于5G的文件、网络差、需要支持断点拷贝的建议使用分块拷贝
public static void copyObjectMultipart() {
String ACCESS_KEY_ID = "akxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 用户的Access Key ID
String SECRET_ACCESS_KEY = "skxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 用户的Secret Access Key
String ENDPOINT = "bj.bcebos.com"; // 用户自己指定的域名,参考说明文档
// 初始化一个BosClient
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
config.setEndpoint(ENDPOINT);
BosClient client = new BosClient(config);
// 第一步 init
InitiateMultipartUploadRequest initiateMultipartUploadRequest =
new InitiateMultipartUploadRequest("targetBucketName","targetObjectName");
InitiateMultipartUploadResponse initiateMultipartUploadResponse =
client.initiateMultipartUpload(initiateMultipartUploadRequest);
// 第二步 分块拷贝
long left_size=client.getObjectMetadata("sourceBucketName","sourceObjectName").getContentLength();
long skipBytes = 0;
int partNumber = 1;
List<PartETag> partETags = new ArrayList<PartETag>();
while (left_size > 0) {
long partSize = 1024 * 1024 * 1L;
if (left_size < partSize) {
partSize = left_size;
}
UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest();
uploadPartCopyRequest.setBucketName("targetBucketName");
uploadPartCopyRequest.setKey("targetObjectName");
uploadPartCopyRequest.setSourceBucketName("sourceBucketName");
uploadPartCopyRequest.setSourceKey("sourceObjectName");
uploadPartCopyRequest.setUploadId(initiateMultipartUploadResponse.getUploadId());
uploadPartCopyRequest.setPartSize(partSize);
uploadPartCopyRequest.setOffSet(skipBytes);
uploadPartCopyRequest.setPartNumber(partNumber);
UploadPartCopyResponse uploadPartCopyResponse = client.uploadPartCopy(uploadPartCopyRequest);
// 将返回的PartETag保存到List中
PartETag partETag = new PartETag(partNumber,uploadPartCopyResponse.getETag());
partETags.add(partETag);
left_size -= partSize;
skipBytes += partSize;
partNumber+=1;
}
// 第三步 complete
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest("targetBucketName", "targetObjectName", initiateMultipartUploadResponse.getUploadId(), partETags);
CompleteMultipartUploadResponse completeMultipartUploadResponse =
client.completeMultipartUpload(completeMultipartUploadRequest);
// 关闭客户端
client.shutdown();
}
}
| 44.207547 | 149 | 0.681605 |
be68c211d9a418ea55b017a449991ea41b03c1d3 | 873 | package ExampleWithClient;
import com.xendit.exception.XenditException;
import com.xendit.model.FixedVirtualAccountPayment;
import com.xendit.XenditClient;
public class ExampleGetVAPayment {
public static void main(String[] args) {
//create xendit client which holds value of apikey
XenditClient xenditClient = new XenditClient.Builder()
.setApikey("xnd_development_...")
.build();
String virtualAccountPaymentId = "random_1560763705544";
try {
/**
* Get VA payment from payment ID
*/
FixedVirtualAccountPayment virtualAccountPayment = xenditClient.fixedVirtualAccount.getPayment(virtualAccountPaymentId);
System.out.println(virtualAccountPayment);
} catch (XenditException e) {
e.printStackTrace();
}
}
}
| 31.178571 | 132 | 0.658648 |
3d42a23a27819c98e04b14893637fa5351f3d9f8 | 3,329 | /*
* Copyright 2021 DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.fallout.service.artifacts;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import io.dropwizard.servlets.tasks.Task;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import com.datastax.fallout.service.core.DeletedTestRun;
import com.datastax.fallout.service.db.TestRunDAO;
import com.datastax.fallout.util.Exceptions;
public class ArtifactUsageAdminTask extends Task
{
private final TestRunDAO testRunDAO;
public ArtifactUsageAdminTask(TestRunDAO testRunDAO)
{
super("artifact-usage", "text/csv");
this.testRunDAO = testRunDAO;
}
@Override
public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception
{
writeArtifactUsage(output, parameters.containsKey("includeFiles"));
}
public void writeArtifactUsage(Appendable output, boolean includeFiles) throws IOException
{
final var testRuns = testRunDAO.getAllEvenIfDeleted();
final var headers = new ArrayList<>(List.of("deleted", "owner", "test", "testrun", "finished"));
if (includeFiles)
{
headers.addAll(List.of("dir", "file"));
}
headers.add("size");
try (CSVPrinter csvOutput =
new CSVPrinter(output, CSVFormat.DEFAULT.withHeader(headers.toArray(new String[] {}))))
{
testRuns.forEach(testRun -> {
if (includeFiles)
{
testRun.getArtifacts().forEach((artifact, size) -> {
final var path = Paths.get(artifact);
Exceptions.runUncheckedIO(() -> csvOutput
.printRecord(testRun instanceof DeletedTestRun,
testRun.getOwner(), testRun.getTestName(), testRun.getTestRunId(),
Optional.ofNullable(testRun.getFinishedAt()).map(Date::toInstant).orElse(null),
path.getParent(), path.getFileName(), size));
});
}
else
{
Exceptions.runUncheckedIO(() -> csvOutput
.printRecord(testRun instanceof DeletedTestRun,
testRun.getOwner(), testRun.getTestName(), testRun.getTestRunId(),
Optional.ofNullable(testRun.getFinishedAt()).map(Date::toInstant).orElse(null),
testRun.getArtifactsSizeBytes().orElse(0L)));
}
});
}
}
}
| 36.582418 | 111 | 0.626615 |
9e2d189860021a8e66639c8377d09b37f0aacfa8 | 7,767 | /*
* Copyright 2019 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.smallrye.openapi.runtime.scanner;
import java.io.IOException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.jboss.jandex.Index;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.json.JSONException;
import org.junit.Test;
/**
* @author Michael Edgar {@literal <[email protected]>}
*/
public class ApiResponseTests extends IndexScannerTestBase {
private static void test(String expectedResource, Class<?>... classes) throws IOException, JSONException {
Index index = indexOf(classes);
OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(emptyConfig(), index);
OpenAPI result = scanner.scan();
printToConsole(result);
assertJsonEquals(expectedResource, result);
}
@Test
public void testResponseGenerationSuppressedByApiResourcesAnnotation() throws IOException, JSONException {
test("responses.generation-suppressed-by-api-responses-annotation.json",
ResponseGenerationSuppressedByApiResourcesAnnotationTestResource.class,
Pet.class);
}
@Test
public void testResponseGenerationSuppressedBySuppliedDefaultApiResource() throws IOException, JSONException {
test("responses.generation-suppressed-by-supplied-default-api-response.json",
ResponseGenerationSuppressedBySuppliedDefaultApiResourceTestResource.class,
Pet.class);
}
@Test
public void testResponseGenerationSuppressedByStatusOmission() throws IOException, JSONException {
test("responses.generation-suppressed-by-status-omission.json",
ResponseGenerationSuppressedByStatusOmissionTestResource.class,
Pet.class);
}
@Test
public void testResponseGenerationEnabledByIncompleteApiResponse() throws IOException, JSONException {
test("responses.generation-enabled-by-incomplete-api-response.json",
ResponseGenerationEnabledByIncompleteApiResponseTestResource.class,
Pet.class);
}
@Test
public void testResponseMultipartGeneration() throws IOException, JSONException {
test("responses.multipart-generation.json",
ResponseMultipartGenerationTestResource.class);
}
@Test
public void testVoidPostResponseGeneration() throws IOException, JSONException {
test("responses.void-post-response-generation.json",
VoidPostResponseGenerationTestResource.class,
Pet.class);
}
@Test
public void testVoidNonPostResponseGeneration() throws IOException, JSONException {
test("responses.void-nonpost-response-generation.json",
VoidNonPostResponseGenerationTestResource.class);
}
@Test
public void testVoidAsyncResponseGeneration() throws IOException, JSONException {
test("responses.void-async-response-generation.json",
VoidAsyncResponseGenerationTestResource.class);
}
/***************** Test models and resources below. ***********************/
public static class Pet {
String id;
String name;
}
@Path("pets")
static class ResponseGenerationSuppressedByApiResourcesAnnotationTestResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@APIResponses(/* Intentionally left blank */)
public Pet createOrUpdatePet(Pet pet) {
return pet;
}
}
@Path("pets")
static class ResponseGenerationSuppressedBySuppliedDefaultApiResourceTestResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@APIResponse(responseCode = "200", content = {}, description = "Description 200")
@APIResponse(responseCode = "204", description = "Description 204")
@APIResponse(responseCode = "400", description = "Description 400")
public Pet createOrUpdatePet(Pet pet) {
return pet;
}
}
@Path("pets")
static class ResponseGenerationSuppressedByStatusOmissionTestResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@APIResponse(responseCode = "204", description = "Description 204")
@APIResponse(responseCode = "400", description = "Description 400")
public Pet createOrUpdatePet(Pet pet) {
return pet;
}
}
@Path("pets")
static class ResponseGenerationEnabledByIncompleteApiResponseTestResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@APIResponse(responseCode = "200")
@APIResponse(responseCode = "204", description = "Description 204")
@APIResponse(responseCode = "400", description = "Description 400")
public Pet createOrUpdatePet(Pet pet) {
return pet;
}
}
@Path("pets")
static class ResponseMultipartGenerationTestResource {
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces("multipart/mixed")
@APIResponse(responseCode = "200")
@APIResponse(responseCode = "400", description = "Description 400")
public MultipartOutput getPetWithPicture() {
return null;
}
}
@Path("pets")
static class VoidPostResponseGenerationTestResource {
@SuppressWarnings("unused")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@APIResponse(responseCode = "201")
@APIResponse(responseCode = "400", description = "Description 400")
public void createOrUpdatePet(Pet pet) {
}
}
@Path("pets")
static class VoidNonPostResponseGenerationTestResource {
@SuppressWarnings("unused")
@Path("{id}")
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@APIResponse(responseCode = "204")
@APIResponse(responseCode = "400", description = "Description 400")
public void deletePet(@PathParam("id") String id) {
}
}
@Path("pets")
static class VoidAsyncResponseGenerationTestResource {
@SuppressWarnings("unused")
@Path("{id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@APIResponse(responseCode = "200")
@APIResponse(responseCode = "400", description = "Description 400")
public void getPet(@PathParam("id") String id, @Suspended AsyncResponse response) {
}
}
}
| 36.810427 | 114 | 0.68894 |
0eeefc56c0a90ed3c12e8bbfa8069655dbad322b | 52,964 | package com.jd.blockchain.tools.cli;
import com.jd.binaryproto.BinaryProtocol;
import com.jd.blockchain.ca.CertificateRole;
import com.jd.blockchain.ca.CertificateUtils;
import com.jd.blockchain.crypto.*;
import com.jd.blockchain.ledger.*;
import com.jd.blockchain.sdk.client.GatewayBlockchainServiceProxy;
import com.jd.blockchain.sdk.client.GatewayServiceFactory;
import com.jd.blockchain.transaction.*;
import org.apache.commons.io.FilenameUtils;
import picocli.CommandLine;
import utils.Bytes;
import utils.crypto.sm.GmSSLProvider;
import utils.PropertiesUtils;
import utils.StringUtils;
import utils.codec.Base58Utils;
import utils.io.BytesUtils;
import utils.io.FileUtils;
import utils.net.SSLSecurity;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
/**
* @description: traction operations
* @author: imuge
* @date: 2021/7/23
**/
@CommandLine.Command(name = "tx",
mixinStandardHelpOptions = true,
showDefaultValues = true,
description = "Build, sign or send transaction.",
subcommands = {
TxLedgerCAUpdate.class,
TxUserRegister.class,
TxUserCAUpdate.class,
TxUserStateUpdate.class,
TxRoleConfig.class,
TxAuthorziationConfig.class,
TxDataAccountRegister.class,
TxDataAccountPermission.class,
TxKVSet.class,
TxEventAccountRegister.class,
TxEventAccountPermission.class,
TxEventPublish.class,
TxEventSubscribe.class,
TxContractDeploy.class,
TxContractAccountPermission.class,
TxContractCall.class,
TxContractStateUpdate.class,
TxSign.class,
TxSend.class,
TxTestKV.class,
TxConsensusSwitch.class,
TxHashAlgorithmSwitch.class,
CommandLine.HelpCommand.class
}
)
public class Tx implements Runnable {
@CommandLine.ParentCommand
JDChainCli jdChainCli;
@CommandLine.Option(names = "--gw-host", defaultValue = "127.0.0.1", description = "Set the gateway host. Default: 127.0.0.1", scope = CommandLine.ScopeType.INHERIT)
String gwHost;
@CommandLine.Option(names = "--gw-port", defaultValue = "8080", description = "Set the gateway port. Default: 8080", scope = CommandLine.ScopeType.INHERIT)
int gwPort;
@CommandLine.Option(names = "--gw-secure", description = "Secure of the gateway service.", defaultValue = "false", scope = CommandLine.ScopeType.INHERIT)
boolean gwSecure;
@CommandLine.Option(names = "--ssl.key-store", description = "Set ssl.key-store for SSL.", scope = CommandLine.ScopeType.INHERIT)
String keyStore;
@CommandLine.Option(names = "--ssl.key-store-type", description = "Set ssl.key-store-type for SSL.", scope = CommandLine.ScopeType.INHERIT)
String keyStoreType;
@CommandLine.Option(names = "--ssl.key-alias", description = "Set ssl.key-alias for SSL.", scope = CommandLine.ScopeType.INHERIT)
String keyAlias;
@CommandLine.Option(names = "--ssl.key-store-password", description = "Set ssl.key-store-password for SSL.", scope = CommandLine.ScopeType.INHERIT)
String keyStorePassword;
@CommandLine.Option(names = "--ssl.trust-store", description = "Set ssl.trust-store for SSL.", scope = CommandLine.ScopeType.INHERIT)
String trustStore;
@CommandLine.Option(names = "--ssl.trust-store-password", description = "Set trust-store-password for SSL.", scope = CommandLine.ScopeType.INHERIT)
String trustStorePassword;
@CommandLine.Option(names = "--ssl.trust-store-type", description = "Set ssl.trust-store-type for SSL.", scope = CommandLine.ScopeType.INHERIT)
String trustStoreType;
@CommandLine.Option(names = "--ssl.protocol", description = "Set ssl.protocol for SSL.", scope = CommandLine.ScopeType.INHERIT)
String protocol;
@CommandLine.Option(names = "--ssl.enabled-protocols", description = "Set ssl.enabled-protocols for SSL.", scope = CommandLine.ScopeType.INHERIT)
String enabledProtocols;
@CommandLine.Option(names = "--ssl.ciphers", description = "Set ssl.ciphers for SSL.", scope = CommandLine.ScopeType.INHERIT)
String ciphers;
@CommandLine.Option(names = "--ssl.host-verifier", defaultValue = "NO-OP", description = "Set host verifier for SSL. NO-OP or Default", scope = CommandLine.ScopeType.INHERIT)
String hostNameVerifier;
@CommandLine.Option(names = "--export", description = "Transaction export directory", scope = CommandLine.ScopeType.INHERIT)
String export;
@CommandLine.Spec
CommandLine.Model.CommandSpec spec;
GatewayBlockchainServiceProxy blockchainService;
GatewayBlockchainServiceProxy getChainService() {
if (null == blockchainService) {
if (gwSecure) {
GmSSLProvider.enableGMSupport(protocol);
blockchainService = (GatewayBlockchainServiceProxy) GatewayServiceFactory.connect(gwHost, gwPort, gwSecure, new SSLSecurity(keyStoreType, keyStore, keyAlias, keyStorePassword,
trustStore, trustStorePassword, trustStoreType, protocol, enabledProtocols, ciphers, hostNameVerifier)).getBlockchainService();
} else {
blockchainService = (GatewayBlockchainServiceProxy) GatewayServiceFactory.connect(gwHost, gwPort, gwSecure).getBlockchainService();
}
}
return blockchainService;
}
HashDigest selectLedger() {
HashDigest[] ledgers = getChainService().getLedgerHashs();
System.out.printf("select ledger, input the index: %n%-7s\t%s%n", "INDEX", "LEDGER");
for (int i = 0; i < ledgers.length; i++) {
System.out.printf("%-7s\t%s%n", i, ledgers[i]);
}
if (ledgers.length == 1) {
System.out.printf("> 0 (use default ledger)%n");
return ledgers[0];
}
int index = ScannerUtils.readRangeInt(0, ledgers.length - 1);
return ledgers[index];
}
TransactionTemplate newTransaction() {
return getChainService().newTransaction(selectLedger());
}
TransactionTemplate newTransaction(HashDigest ledger) {
return getChainService().newTransaction(ledger);
}
boolean sign(PreparedTransaction ptx) {
DigitalSignature signature = sign(ptx.getTransactionHash());
if (null != signature) {
ptx.addSignature(signature);
return true;
} else {
return false;
}
}
boolean sign(TxRequestMessage tx) {
DigitalSignature signature = sign(tx.getTransactionHash());
if (null != signature) {
tx.addEndpointSignatures(signature);
return true;
} else {
return false;
}
}
protected String getKeysHome() {
try {
return jdChainCli.path.getCanonicalPath() + File.separator + Keys.KEYS_HOME;
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
DigitalSignature sign(HashDigest txHash) {
File keysHome = new File(getKeysHome());
File[] pubs = keysHome.listFiles((dir, name) -> {
return name.endsWith(".priv");
});
if (null == pubs || pubs.length == 0) {
System.err.printf("no signer in path [%s]%n", keysHome.getAbsolutePath());
return null;
} else {
System.out.printf("select keypair to sign tx: %n%-7s\t%s\t%s%n", "INDEX", "KEY", "ADDRESS");
BlockchainKeypair[] keypairs = new BlockchainKeypair[pubs.length];
String[] passwords = new String[pubs.length];
for (int i = 0; i < pubs.length; i++) {
String key = FilenameUtils.removeExtension(pubs[i].getName());
String keyPath = FilenameUtils.removeExtension(pubs[i].getAbsolutePath());
String privkey = FileUtils.readText(new File(keyPath + ".priv"));
String pwd = FileUtils.readText(new File(keyPath + ".pwd"));
String pubkey = FileUtils.readText(new File(keyPath + ".pub"));
keypairs[i] = new BlockchainKeypair(KeyGenUtils.decodePubKey(pubkey), KeyGenUtils.decodePrivKey(privkey, pwd));
passwords[i] = pwd;
System.out.printf("%-7s\t%s\t%s%n", i, key, keypairs[i].getAddress());
}
int keyIndex = ScannerUtils.readRangeInt(0, pubs.length - 1);
System.out.println("input password of the key: ");
String pwd = ScannerUtils.read();
if (KeyGenUtils.encodePasswordAsBase58(pwd).equals(passwords[keyIndex])) {
return SignatureUtils.sign(txHash, keypairs[keyIndex]);
} else {
System.err.println("password wrong");
return null;
}
}
}
BlockchainKeypair signer() {
File keysHome = new File(getKeysHome());
File[] pubs = keysHome.listFiles((dir, name) -> {
return name.endsWith(".priv");
});
if (null == pubs || pubs.length == 0) {
System.err.printf("no signer in path [%s]%n", keysHome.getAbsolutePath());
return null;
} else {
System.out.printf("select keypair to sign tx: %n%-7s\t%s\t%s%n", "INDEX", "KEY", "ADDRESS");
BlockchainKeypair[] keypairs = new BlockchainKeypair[pubs.length];
String[] passwords = new String[pubs.length];
for (int i = 0; i < pubs.length; i++) {
String key = FilenameUtils.removeExtension(pubs[i].getName());
String keyPath = FilenameUtils.removeExtension(pubs[i].getAbsolutePath());
String privkey = FileUtils.readText(new File(keyPath + ".priv"));
String pwd = FileUtils.readText(new File(keyPath + ".pwd"));
String pubkey = FileUtils.readText(new File(keyPath + ".pub"));
keypairs[i] = new BlockchainKeypair(KeyGenUtils.decodePubKey(pubkey), KeyGenUtils.decodePrivKey(privkey, pwd));
passwords[i] = pwd;
System.out.printf("%-7s\t%s\t%s%n", i, key, keypairs[i].getAddress());
}
int keyIndex = ScannerUtils.readRangeInt(0, pubs.length - 1);
System.out.println("input password of the key: ");
String pwd = ScannerUtils.read();
if (KeyGenUtils.encodePasswordAsBase58(pwd).equals(passwords[keyIndex])) {
return keypairs[keyIndex];
} else {
System.err.println("password wrong");
return null;
}
}
}
String export(PreparedTransaction ptx) {
if (null != export) {
File txPath = new File(export);
txPath.mkdirs();
File txFile = new File(txPath.getAbsolutePath() + File.separator + ptx.getTransactionHash());
TxRequestMessage tx = new TxRequestMessage(ptx.getTransactionHash(), ptx.getTransactionContent());
FileUtils.writeBytes(BinaryProtocol.encode(tx, TransactionRequest.class), txFile);
return txFile.getAbsolutePath();
} else {
return null;
}
}
@Override
public void run() {
spec.commandLine().usage(System.err);
}
}
@CommandLine.Command(name = "root-ca", mixinStandardHelpOptions = true, header = "Update ledger root certificates.")
class TxLedgerCAUpdate implements Runnable {
@CommandLine.Option(names = "--crt", description = "File of the X509 certificate", scope = CommandLine.ScopeType.INHERIT)
String caPath;
@CommandLine.Option(names = "--operation", required = true, description = "Operation for this certificate. Optional values: ADD,UPDATE,REMOVE", scope = CommandLine.ScopeType.INHERIT)
Operation operation;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
if (StringUtils.isEmpty(caPath)) {
System.err.println("crt path cannot be empty");
return;
}
TransactionTemplate txTemp = txCommand.newTransaction();
X509Certificate certificate = CertificateUtils.parseCertificate(FileUtils.readText(caPath));
CertificateUtils.checkCertificateRolesAny(certificate, CertificateRole.ROOT, CertificateRole.CA);
CertificateUtils.checkValidity(certificate);
if (operation == Operation.ADD) {
txTemp.metaInfo().ca().add(certificate);
} else if (operation == Operation.UPDATE) {
txTemp.metaInfo().ca().update(certificate);
} else {
txTemp.metaInfo().ca().remove(certificate);
}
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.out.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
String pubkey = KeyGenUtils.encodePubKey(CertificateUtils.resolvePubKey(certificate));
if (response.isSuccess()) {
System.out.printf("ledger ca: [%s](pubkey) updated%n", pubkey);
} else {
System.err.printf("update ledger ca: [%s](pubkey) failed: [%s]!%n", pubkey, response.getExecutionState());
}
}
}
}
private enum Operation {
ADD,
UPDATE,
REMOVE
}
}
@CommandLine.Command(name = "user-register", mixinStandardHelpOptions = true, header = "Register new user.")
class TxUserRegister implements Runnable {
@CommandLine.Option(names = "--pubkey", description = "Pubkey of the user", scope = CommandLine.ScopeType.INHERIT)
String pubkey;
@CommandLine.Option(names = "--crt", description = "File of the X509 certificate", scope = CommandLine.ScopeType.INHERIT)
String caPath;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
PubKey pubKey = null;
X509Certificate certificate = null;
if (!StringUtils.isEmpty(caPath)) {
certificate = CertificateUtils.parseCertificate(FileUtils.readText(caPath));
} else if (!StringUtils.isEmpty(pubkey)) {
pubKey = Crypto.resolveAsPubKey(Base58Utils.decode(pubkey));
} else {
System.err.println("public key and certificate file can not be empty at the same time");
return;
}
TransactionTemplate txTemp = txCommand.newTransaction();
if (null != certificate) {
CertificateUtils.checkCertificateRolesAny(certificate, CertificateRole.PEER, CertificateRole.GW, CertificateRole.USER);
CertificateUtils.checkValidity(certificate);
pubKey = CertificateUtils.resolvePubKey(certificate);
txTemp.users().register(certificate);
} else {
txTemp.users().register(new BlockchainIdentityData(pubKey));
}
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.out.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("register user: [%s]%n", AddressEncoding.generateAddress(pubKey));
} else {
System.err.printf("register user failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "user-ca", mixinStandardHelpOptions = true, header = "Update user certificate.")
class TxUserCAUpdate implements Runnable {
@CommandLine.Option(names = "--crt", description = "File of the X509 certificate", scope = CommandLine.ScopeType.INHERIT)
String caPath;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
X509Certificate certificate;
Bytes address;
if (!StringUtils.isEmpty(caPath)) {
certificate = CertificateUtils.parseCertificate(new File(caPath));
address = AddressEncoding.generateAddress(CertificateUtils.resolvePubKey(certificate));
} else {
System.err.println("certificate file can not be empty");
return;
}
CertificateUtils.checkCertificateRolesAny(certificate, CertificateRole.PEER, CertificateRole.GW, CertificateRole.USER);
// CertificateUtils.checkValidity(certificate);
txTemp.user(address).ca(certificate);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.out.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("user: [%s] ca updated%n", address);
} else {
System.err.printf("update user failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "user-state", mixinStandardHelpOptions = true, header = "Update user(certificate) state.")
class TxUserStateUpdate implements Runnable {
@CommandLine.Option(names = "--address", required = true, description = "User address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--state", required = true, description = "User state, Optional values: FREEZE,NORMAL,REVOKE", scope = CommandLine.ScopeType.INHERIT)
AccountState state;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
txTemp.user(address).state(state);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.out.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("change user: [%s] state to:[%s]%n", address, state);
} else {
System.err.printf("change user state failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "data-account-register", mixinStandardHelpOptions = true, header = "Register new data account.")
class TxDataAccountRegister implements Runnable {
@CommandLine.Option(names = "--pubkey", description = "The pubkey of the exist data account", scope = CommandLine.ScopeType.INHERIT)
String pubkey;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
BlockchainIdentity account;
if (null == pubkey) {
account = BlockchainKeyGenerator.getInstance().generate().getIdentity();
} else {
account = new BlockchainIdentityData(KeyGenUtils.decodePubKey(pubkey));
}
txTemp.dataAccounts().register(account);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("register data account: [%s]%n", account.getAddress());
} else {
System.err.printf("register data account failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "contract-deploy", mixinStandardHelpOptions = true, header = "Deploy or update contract.")
class TxContractDeploy implements Runnable {
@CommandLine.Option(names = "--code", required = true, description = "The car file path", scope = CommandLine.ScopeType.INHERIT)
File code;
@CommandLine.Option(names = "--lang", required = true, description = "The contract language", defaultValue = "Java", scope = CommandLine.ScopeType.INHERIT)
ContractLang lang;
@CommandLine.Option(names = "--pubkey", description = "The pubkey of the exist contract", scope = CommandLine.ScopeType.INHERIT)
String pubkey;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
BlockchainIdentity account;
if (null == pubkey) {
account = BlockchainKeyGenerator.getInstance().generate().getIdentity();
} else {
account = new BlockchainIdentityData(KeyGenUtils.decodePubKey(pubkey));
}
txTemp.contracts().deploy(account, FileUtils.readBytes(code), lang);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("deploy contract: [%s]%n", account.getAddress());
} else {
System.err.printf("deploy contract failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "event-account-register", mixinStandardHelpOptions = true, header = "Register event account.")
class TxEventAccountRegister implements Runnable {
@CommandLine.Option(names = "--pubkey", description = "The pubkey of the exist event account", scope = CommandLine.ScopeType.INHERIT)
String pubkey;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
BlockchainIdentity account;
if (null == pubkey) {
account = BlockchainKeyGenerator.getInstance().generate().getIdentity();
} else {
account = new BlockchainIdentityData(KeyGenUtils.decodePubKey(pubkey));
}
txTemp.eventAccounts().register(account);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("register event account: [%s]%n", account.getAddress());
} else {
System.err.printf("register event account failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "kv", mixinStandardHelpOptions = true, header = "Set key-value.")
class TxKVSet implements Runnable {
@CommandLine.Option(names = "--address", required = true, description = "Data account address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--key", required = true, description = "Key to set", scope = CommandLine.ScopeType.INHERIT)
String key;
@CommandLine.Option(names = "--value", required = true, description = "Value to set", scope = CommandLine.ScopeType.INHERIT)
String value;
@CommandLine.Option(names = "--ver", defaultValue = "-1", description = "Version of the key-value", scope = CommandLine.ScopeType.INHERIT)
long version;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
txTemp.dataAccount(address).setText(key, value, version);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.println("set kv success");
} else {
System.err.printf("set kv failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "event", mixinStandardHelpOptions = true, header = "Publish event.")
class TxEventPublish implements Runnable {
@CommandLine.Option(names = "--address", required = true, description = "Contract address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--name", required = true, description = "Event name", scope = CommandLine.ScopeType.INHERIT)
String name;
@CommandLine.Option(names = "--content", required = true, description = "Event content", scope = CommandLine.ScopeType.INHERIT)
String value;
@CommandLine.Option(names = "--sequence", defaultValue = "-1", description = "Sequence of the event", scope = CommandLine.ScopeType.INHERIT)
long sequence;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
txTemp.eventAccount(address).publish(name, value, sequence);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.println("event publish success");
} else {
System.err.printf("event publish failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "event-listen", mixinStandardHelpOptions = true, header = "Subscribe event.")
class TxEventSubscribe implements Runnable {
@CommandLine.Option(names = "--address", description = "Event address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--name", required = true, description = "Event name", scope = CommandLine.ScopeType.INHERIT)
String name;
@CommandLine.Option(names = "--sequence", defaultValue = "0", description = "Sequence of the event", scope = CommandLine.ScopeType.INHERIT)
long sequence;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
// 事件监听会创建子线程,为阻止子线程被直接关闭,加入等待
CountDownLatch cdl = new CountDownLatch(1);
if (StringUtils.isEmpty(address)) {
txCommand.getChainService().monitorSystemEvent(txCommand.selectLedger(),
SystemEvent.NEW_BLOCK_CREATED, sequence, (eventMessages, eventContext) -> {
for (Event eventMessage : eventMessages) {
// content中存放的是当前链上最新高度
System.out.println("New block:" + eventMessage.getSequence() + ":" + BytesUtils.toLong(eventMessage.getContent().getBytes().toBytes()));
}
});
} else {
txCommand.getChainService().monitorUserEvent(txCommand.selectLedger(), address, name, sequence, (eventMessage, eventContext) -> {
BytesValue content = eventMessage.getContent();
switch (content.getType()) {
case TEXT:
case XML:
case JSON:
System.out.println(eventMessage.getName() + ":" + eventMessage.getSequence() + ":" + content.getBytes().toUTF8String());
break;
case INT64:
case TIMESTAMP:
System.out.println(eventMessage.getName() + ":" + eventMessage.getSequence() + ":" + BytesUtils.toLong(content.getBytes().toBytes()));
break;
default: // byte[], Bytes
System.out.println(eventMessage.getName() + ":" + eventMessage.getSequence() + ":" + content.getBytes().toBase58());
break;
}
});
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@CommandLine.Command(name = "contract", mixinStandardHelpOptions = true, header = "Call contract method.")
class TxContractCall implements Runnable {
@CommandLine.Option(names = "--address", required = true, description = "Contract address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--method", required = true, description = "Contract method", scope = CommandLine.ScopeType.INHERIT)
String method;
@CommandLine.Option(names = "--args", split = ",", description = "Method arguments", scope = CommandLine.ScopeType.INHERIT)
String[] args;
@CommandLine.Option(names = "--ver", defaultValue = "-1", description = "Contract version", scope = CommandLine.ScopeType.INHERIT)
long version;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
TypedValue[] tvs;
if (null != args) {
tvs = new TypedValue[args.length];
for (int i = 0; i < args.length; i++) {
tvs[i] = TypedValue.fromText(args[i]);
}
} else {
tvs = new TypedValue[]{};
}
txTemp.contract(Bytes.fromBase58(address)).invoke(method, new BytesDataList(tvs), version);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.println("call contract success");
for (int i = 0; i < response.getOperationResults().length; i++) {
BytesValue content = response.getOperationResults()[i].getResult();
switch (content.getType()) {
case TEXT:
case JSON:
System.out.println("return string: " + content.getBytes().toUTF8String());
break;
case INT64:
System.out.println("return long: " + BytesUtils.toLong(content.getBytes().toBytes()));
break;
case BOOLEAN:
System.out.println("return boolean: " + BytesUtils.toBoolean(content.getBytes().toBytes()[0]));
break;
default: // byte[], Bytes
System.out.println("return bytes: " + content.getBytes().toBase58());
break;
}
}
} else {
System.err.println("call contract failed: " + response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "contract-state", mixinStandardHelpOptions = true, header = "Update contract state.")
class TxContractStateUpdate implements Runnable {
@CommandLine.Option(names = "--address", required = true, description = "Contract address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--state", required = true, description = "Contract state, Optional values: FREEZE,NORMAL,REVOKE", scope = CommandLine.ScopeType.INHERIT)
AccountState state;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
txTemp.contract(address).state(state);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.out.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("change contract: [%s] state to:[%s]%n", address, state);
} else {
System.err.printf("change contract state failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "role", mixinStandardHelpOptions = true, header = "Create or config role.")
class TxRoleConfig implements Runnable {
@CommandLine.Option(names = "--name", required = true, description = "Role name", scope = CommandLine.ScopeType.INHERIT)
String role;
@CommandLine.Option(names = "--enable-ledger-perms", split = ",", description = "Enable ledger permissions", scope = CommandLine.ScopeType.INHERIT)
LedgerPermission[] enableLedgerPerms;
@CommandLine.Option(names = "--disable-ledger-perms", split = ",", description = "Disable ledger permissions", scope = CommandLine.ScopeType.INHERIT)
LedgerPermission[] disableLedgerPerms;
@CommandLine.Option(names = "--enable-transaction-perms", split = ",", description = "Enable transaction permissions", scope = CommandLine.ScopeType.INHERIT)
TransactionPermission[] enableTransactionPerms;
@CommandLine.Option(names = "--disable-transaction-perms", split = ",", description = "Disable transaction permissions", scope = CommandLine.ScopeType.INHERIT)
TransactionPermission[] disableTransactionPerms;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
RolePrivilegeConfigurer configure = txTemp.security().roles().configure(role);
if (null != enableLedgerPerms && enableLedgerPerms.length > 0) {
configure.enable(enableLedgerPerms);
}
if (null != disableLedgerPerms && disableLedgerPerms.length > 0) {
configure.disable(disableLedgerPerms);
}
if (null != enableTransactionPerms && enableTransactionPerms.length > 0) {
configure.enable(enableTransactionPerms);
}
if (null != disableTransactionPerms && disableTransactionPerms.length > 0) {
configure.disable(disableTransactionPerms);
}
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.err.println("Role config success!");
} else {
System.err.printf("Role config failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "authorization", mixinStandardHelpOptions = true, header = "User role authorization.")
class TxAuthorziationConfig implements Runnable {
@CommandLine.Option(names = "--address", required = true, description = "User address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--authorize", split = ",", description = "Authorize roles", scope = CommandLine.ScopeType.INHERIT)
String[] authorizeRoles;
@CommandLine.Option(names = "--unauthorize", split = ",", description = "Unauthorize roles", scope = CommandLine.ScopeType.INHERIT)
String[] unauthorizeRoles;
@CommandLine.Option(names = "--policy", description = "Role policy", scope = CommandLine.ScopeType.INHERIT)
RolesPolicy policy;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
TransactionTemplate txTemp = txCommand.newTransaction();
UserRolesAuthorizer userRolesAuthorizer = txTemp.security().authorziations().forUser(Bytes.fromBase58(address));
if (null != authorizeRoles && authorizeRoles.length > 0) {
userRolesAuthorizer.authorize(authorizeRoles);
}
if (null != unauthorizeRoles && unauthorizeRoles.length > 0) {
userRolesAuthorizer.unauthorize(unauthorizeRoles);
}
if (null == policy) {
policy = RolesPolicy.UNION;
}
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.err.println("Authorization config success!");
} else {
System.err.printf("Authorization config failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "sign", mixinStandardHelpOptions = true, header = "Sign transaction.")
class TxSign implements Runnable {
@CommandLine.Option(names = "--tx", description = "Local transaction file", scope = CommandLine.ScopeType.INHERIT)
File txFile;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
if (!txFile.exists()) {
System.err.println("Transaction file not exist!");
return;
}
TxRequestMessage tx = new TxRequestMessage(BinaryProtocol.decode(FileUtils.readBytes(txFile), TransactionRequest.class));
if (txCommand.sign(tx)) {
FileUtils.writeBytes(BinaryProtocol.encode(tx), txFile);
System.out.println("Sign transaction success!");
} else {
System.err.println("Sign transaction failed!");
}
}
}
@CommandLine.Command(name = "send", mixinStandardHelpOptions = true, header = "Send transaction.")
class TxSend implements Runnable {
@CommandLine.Option(names = "--tx", description = "Local transaction file", scope = CommandLine.ScopeType.INHERIT)
File txFile;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
if (!txFile.exists()) {
System.err.println("Transaction file not exist!");
return;
}
TxRequestMessage tx = new TxRequestMessage(BinaryProtocol.decode(FileUtils.readBytes(txFile), TransactionRequest.class));
GatewayBlockchainServiceProxy chainService = txCommand.getChainService();
try {
Method method = GatewayBlockchainServiceProxy.class.getDeclaredMethod("getTransactionService", HashDigest.class);
method.setAccessible(true);
TransactionService txService = (TransactionService) method.invoke(chainService, txCommand.selectLedger());
TransactionResponse response = txService.process(tx);
if (response.isSuccess()) {
System.out.println("Send transaction success: " + tx.getTransactionHash());
} else {
System.err.printf("Send transaction failed: [%s]!%n", response.getExecutionState());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@CommandLine.Command(name = "testkv", mixinStandardHelpOptions = true, header = "Send kv set transaction for testing.")
class TxTestKV implements Runnable {
@CommandLine.Option(names = "--address", required = true, description = "Data account address", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--thread", required = true, description = "Thread number", defaultValue = "1", scope = CommandLine.ScopeType.INHERIT)
int thread;
@CommandLine.Option(names = "--interval", required = true, description = "Interval millisecond per single thread", defaultValue = "0", scope = CommandLine.ScopeType.INHERIT)
int interval;
@CommandLine.Option(names = "--silence", required = true, description = "Do not log tx detail", defaultValue = "false", scope = CommandLine.ScopeType.INHERIT)
boolean silence;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
HashDigest ledger = txCommand.selectLedger();
BlockchainKeypair signer = txCommand.signer();
CountDownLatch cdl = new CountDownLatch(1);
AtomicLong count = new AtomicLong(0);
final long startTime = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(startTime);
for (int i = 0; i < thread; i++) {
final int index = i + 1;
new Thread(() -> {
System.out.println("start thread " + index + " to set kv");
while (true) {
TransactionTemplate txTemp = txCommand.newTransaction(ledger);
txTemp.dataAccount(address).setInt64(UUID.randomUUID().toString(), System.currentTimeMillis(), -1);
PreparedTransaction prepare = txTemp.prepare();
prepare.addSignature(SignatureUtils.sign(prepare.getTransactionHash(), signer));
try {
TransactionResponse response = prepare.commit();
if (!silence) {
System.out.println(prepare.getTransactionHash() + ": " + response.getExecutionState());
}
long l = count.incrementAndGet();
if (l % 1000 == 0) {
long t = System.currentTimeMillis();
date.setTime(t);
t -= startTime;
System.out.printf("current time: %s, total txs: %d, time: %d ms, tps: %d \n", sdf.format(date), l, t, l * 1000 / t);
}
if (interval > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
}
}
} catch (Exception e) {
if (!silence) {
System.out.println(prepare.getTransactionHash() + ": " + e.getMessage());
}
}
}
}).start();
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@CommandLine.Command(name = "data-account-permission", mixinStandardHelpOptions = true, header = "Update data account permission.")
class TxDataAccountPermission implements Runnable {
@CommandLine.Option(names = "--address", description = "Address of the data account", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--role", description = "Role of the data account", scope = CommandLine.ScopeType.INHERIT)
String role;
@CommandLine.Option(names = "--mode", description = "Mode value of the data account", defaultValue = "-1", scope = CommandLine.ScopeType.INHERIT)
int mode;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
if (StringUtils.isEmpty(role) && mode == -1) {
System.err.println("both role and mode are empty!");
return;
}
TransactionTemplate txTemp = txCommand.newTransaction();
AccountPermissionSetOperationBuilder builder = txTemp.dataAccount(address).permission();
if (!StringUtils.isEmpty(role)) {
builder.role(role);
}
if (mode > -1) {
builder.mode(mode);
}
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("update data account: [%s] permission\n", address);
} else {
System.err.printf("update data account permission failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "event-account-permission", mixinStandardHelpOptions = true, header = "Update event account permission.")
class TxEventAccountPermission implements Runnable {
@CommandLine.Option(names = "--address", description = "Address of the event account", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--role", description = "Role of the event account", scope = CommandLine.ScopeType.INHERIT)
String role;
@CommandLine.Option(names = "--mode", description = "Mode value of the event account", defaultValue = "-1", scope = CommandLine.ScopeType.INHERIT)
int mode;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
if (StringUtils.isEmpty(role) && mode == -1) {
System.err.println("both role and mode are empty!");
return;
}
TransactionTemplate txTemp = txCommand.newTransaction();
AccountPermissionSetOperationBuilder builder = txTemp.eventAccount(address).permission();
if (!StringUtils.isEmpty(role)) {
builder.role(role);
}
if (mode > -1) {
builder.mode(mode);
}
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("update event account: [%s] permission\n", address);
} else {
System.err.printf("update event account permission failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "contract-permission", mixinStandardHelpOptions = true, header = "Update contract permission.")
class TxContractAccountPermission implements Runnable {
@CommandLine.Option(names = "--address", description = "Address of the contract", scope = CommandLine.ScopeType.INHERIT)
String address;
@CommandLine.Option(names = "--role", description = "Role of the contract", scope = CommandLine.ScopeType.INHERIT)
String role;
@CommandLine.Option(names = "--mode", description = "Mode value of the contract", defaultValue = "-1", scope = CommandLine.ScopeType.INHERIT)
int mode;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
if (StringUtils.isEmpty(role) && mode == -1) {
System.err.println("both role and mode are empty!");
return;
}
TransactionTemplate txTemp = txCommand.newTransaction();
AccountPermissionSetOperationBuilder builder = txTemp.contract(address).permission();
if (!StringUtils.isEmpty(role)) {
builder.role(role);
}
if (mode > -1) {
builder.mode(mode);
}
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.printf("update contract: [%s] permission\n", address);
} else {
System.err.printf("update contract permission failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "consensus-switch", mixinStandardHelpOptions = true, header = "Switch consensus type.")
class TxConsensusSwitch implements Runnable {
@CommandLine.Option(names = "--consensus", required = true, description = "New consensus type. Options: `BFTSMART`,`RAFT`,`MQ`", scope = CommandLine.ScopeType.INHERIT)
ConsensusTypeEnum consensus;
@CommandLine.Option(names = "--config", required = true, description = "Set new consensus config file", scope = CommandLine.ScopeType.INHERIT)
String config;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
Properties properties;
if (ConsensusTypeEnum.UNKNOWN.equals(consensus)) {
System.err.println("unknown consensus type!");
return;
}
if (StringUtils.isEmpty(config)) {
System.err.println("config file path are empty!");
return;
}
TransactionTemplate txTemp = txCommand.newTransaction();
try (InputStream in = new FileInputStream(config)) {
properties = FileUtils.readProperties(in);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
txTemp.consensus().update(consensus.getProvider(), PropertiesUtils.getOrderedValues(properties));
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.println("switch consensus type success");
} else {
System.err.printf("switch consensus type failed: [%s]!%n", response.getExecutionState());
}
}
}
}
}
@CommandLine.Command(name = "hash-algo-switch", mixinStandardHelpOptions = true, header = "Switch crypto hash algo.")
class TxHashAlgorithmSwitch implements Runnable {
@CommandLine.Option(names = {"-a", "--algorithm"}, required = true, description = "New crypto hash algo. Options:'SHA256','RIPEMD160','SM3'", scope = CommandLine.ScopeType.INHERIT)
String newHashAlgo;
@CommandLine.ParentCommand
private Tx txCommand;
@Override
public void run() {
if (StringUtils.isEmpty(newHashAlgo)) {
System.err.println("new hash algorithm is empty!");
return;
}
TransactionTemplate txTemp = txCommand.newTransaction();
txTemp.settings().hashAlgorithm(newHashAlgo);
PreparedTransaction ptx = txTemp.prepare();
String txFile = txCommand.export(ptx);
if (null != txFile) {
System.err.println("export transaction success: " + txFile);
} else {
if (txCommand.sign(ptx)) {
TransactionResponse response = ptx.commit();
if (response.isSuccess()) {
System.out.println("switch new hash algorithm success");
} else {
System.err.printf("switch new hash algorithm failed: [%s]!%n", response.getExecutionState());
}
}
}
}
} | 42.068308 | 191 | 0.610754 |
88974ff230ab0f4f2e532796622ebe34bfd04c68 | 144 | package validation.leaf.is.of.format.url;
final public class Code
{
public String value()
{
return "url-wrong-format";
}
}
| 14.4 | 41 | 0.631944 |
e0d1de633a31005998973accfb83ac84ed84ff7c | 912 | package com.aj.leetcode.q38;
/**
* @author zhangqingyue
* @date 2020/11/4
*/
public class Solution {
/**
* @param n
* @return
*/
public String countAndSay(int n) {
if (n <= 0) {
return "";
}
String[] seq = new String[n];
seq[0] = "1";
for (int i = 1; i < n; i++) {
seq[i] = convert(seq[i - 1]);
}
return seq[n - 1];
}
/**
* @param str
* @return
*/
public String convert(String str) {
StringBuilder ans = new StringBuilder();
int count = 1;
for (int i = 0; i < str.length(); i++) {
if (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
} else {
ans.append(count).append(str.charAt(i));
count = 1;
}
}
return new String(ans);
}
}
| 21.714286 | 77 | 0.417763 |
83a1b7ac11b445623273ef7bc523e5c828b3b079 | 5,248 | package br.com.jpo.dao.impl;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import br.com.jpo.bean.DynamicBean;
import br.com.jpo.connection.impl.JdbcWrapper;
import br.com.jpo.dao.EntityDAO;
import br.com.jpo.dao.KeyGenerateEvent;
import br.com.jpo.dao.KeyGenerator;
import br.com.jpo.dao.PersistenceException;
import br.com.jpo.metadata.entity.EntityColumnMetadata;
import br.com.jpo.metadata.entity.EntityKeyMetadata;
import br.com.jpo.metadata.entity.EntityMetadata;
import br.com.jpo.transaction.JPOTransactionLock;
import br.com.jpo.transaction.JPOTransactionLockContext;
import br.com.jpo.transaction.impl.JPOTransactionLockContextImpl;
import br.com.jpo.utils.BigDecimalUtils;
import br.com.jpo.utils.JdbcUtils;
import br.com.jpo.utils.StringUtils;
public class TableKeyGenerator implements KeyGenerator {
private StringBuffer sqlCommandLastKey;
private StringBuffer sqlCommandPreviousKey;
private StringBuffer sqlCommandUpdateKey;
@Override
public Object generateKey(KeyGenerateEvent event) throws PersistenceException {
Object key = null;
PreparedStatement pstmLastKey = null;
PreparedStatement pstmPreviousKey = null;
ResultSet rset = null;
try {
registryLock(event);
DynamicBean dynamicBean = event.getDynamicBean();
EntityDAO entityDAO = event.getEntityDAO();
JdbcWrapper jdbcWrapper = event.getJdbcWrapper();
initializeSQLCommand(entityDAO);
EntityMetadata entityMetadata = entityDAO.getInstanceMetadata().getEntityMetadata();
EntityKeyMetadata entityKeyMetadata = entityMetadata.getEntityKeyMetadata();
EntityColumnMetadata columnMetadata = entityMetadata.getEntityColumnMetadata(entityKeyMetadata.getKeyField());
pstmLastKey = jdbcWrapper.getPreparedStatementForSearch(sqlCommandLastKey.toString());
pstmLastKey.setString(1, entityMetadata.getName());
BigDecimal previousKey = BigDecimal.ZERO;
BigDecimal lastKey = BigDecimal.ZERO;
rset = pstmLastKey.executeQuery();
if(rset.next()) {
lastKey = BigDecimalUtils.getBigDecimalOrZero(rset.getBigDecimal(EntityKeyMetadata.ULTIMACHAVE));
}
previousKey = lastKey.add(BigDecimal.ONE);
pstmPreviousKey = jdbcWrapper.getPreparedStatementForSearch(sqlCommandPreviousKey.toString());
key = getPreviousKey(previousKey, pstmPreviousKey);
updateLastKey(jdbcWrapper, entityDAO, (BigDecimal) key);
dynamicBean.setAttribute(columnMetadata.getName(), key);
} catch(Exception ex) {
PersistenceException.throwMe(ex);
} finally {
JdbcUtils.close(rset);
JdbcUtils.close(pstmLastKey);
JdbcUtils.close(pstmPreviousKey);
}
return key;
}
private void initializeSQLCommand(EntityDAO entityDAO) throws Exception {
EntityMetadata entityMetadata = entityDAO.getInstanceMetadata().getEntityMetadata();
EntityKeyMetadata entityKeyMetadata = entityMetadata.getEntityKeyMetadata();
EntityColumnMetadata columnMetadata = entityMetadata.getEntityColumnMetadata(entityKeyMetadata.getKeyField());
sqlCommandLastKey = new StringBuffer();
sqlCommandLastKey.append("SELECT ULTIMACHAVE FROM TDDCHAVE WHERE NOMETABELA = ?");
sqlCommandPreviousKey = new StringBuffer();
sqlCommandPreviousKey.append("SELECT DISTINCT ${nomeCampo} FROM ${nomeTabela} WHERE ${nomeCampo} IS NOT NULL AND ${nomeCampo} >= ?");
StringUtils.replaceString("${nomeTabela}", entityMetadata.getName(), sqlCommandPreviousKey, true);
StringUtils.replaceString("${nomeCampo}", columnMetadata.getName(), sqlCommandPreviousKey, true);
sqlCommandUpdateKey = new StringBuffer();
sqlCommandUpdateKey.append("UPDATE TDDCHAVE SET ULTIMACHAVE = ? WHERE NOMETABELA = ?");
}
private BigDecimal getPreviousKey(BigDecimal previous, PreparedStatement pstm) throws Exception {
laco: do {
pstm.setBigDecimal(1, previous);
pstm.setMaxRows(100);
ResultSet rsetConfere = pstm.executeQuery();
if (rsetConfere.next()) {
do {
if (rsetConfere.getBigDecimal(1).compareTo(previous) != 0) {
break laco;
}
previous = previous.add(BigDecimal.ONE);
} while (rsetConfere.next());
} else {
break laco;
}
rsetConfere.close();
} while (true);
return previous;
}
private void updateLastKey(JdbcWrapper jdbcWrapper, EntityDAO entityDAO, BigDecimal key) throws Exception {
PreparedStatement pstm = null;
try {
EntityMetadata entityMetadata = entityDAO.getInstanceMetadata().getEntityMetadata();
pstm = jdbcWrapper.getPreparedStatementForSearch(sqlCommandUpdateKey.toString());
pstm.setBigDecimal(1, key);
pstm.setString(2, entityMetadata.getName());
pstm.executeUpdate();
} finally {
JdbcUtils.close(pstm);
}
}
private void registryLock(KeyGenerateEvent event) throws Exception {
String resourceName = "TableKeyGenerator:TDDCHAVE:"+event.getDynamicBean().getName();
JPOTransactionLock transactionLock = event.getTransactionLock();
JPOTransactionLockContext context = new JPOTransactionLockContextImpl(resourceName, true);
transactionLock.lockResource(context);
}
} | 35.459459 | 136 | 0.745998 |
aa4cc04e48e21e08d3fd4315889c12c9a156bc51 | 631 | package org.endeavourhealth.imapi.workflow.repository;
import org.endeavourhealth.imapi.workflow.domain.FileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class FileUploadRepository {
private static final Logger LOG = LoggerFactory.getLogger(FileUploadRepository.class);
public FileUpload getOne(Long id) {
FileUpload result = new FileUpload();
result.setId(id);
return result;
}
public FileUpload save(FileUpload fileUpload) {
LOG.debug("***** SAVE *****");
return fileUpload;
}
}
| 27.434783 | 90 | 0.721078 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.