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
521f6def5ee7b98916cdd4a6991f62920f21c74e
319
package com.multi.thread.chapter6.section1.example1; /** * @Description * @Author dongzonglei * @Date 2018/12/23 上午10:45 */ public class MyObject { private static MyObject myObject = new MyObject(); private MyObject() { } public static MyObject getInstance() { return myObject; } }
15.95
54
0.658307
aa95e908245dc40960b653898b50684df685db52
4,679
package com.whoyao.venue; import java.io.File; import java.util.ArrayList; import org.taptwo.widget.CircleFlowIndicator; import org.taptwo.widget.ViewFlow; import com.whoyao.AppContext; import com.whoyao.R; import com.whoyao.activity.BasicActivity; import com.whoyao.model.EventPhotoModel; import com.whoyao.venue.engine.VenueDetialManager; import com.whoyao.venue.engine.VenuePhotosAdapter; import com.whoyao.venue.model.VenueDetialModel; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class VenueMoeInfoActivity extends BasicActivity implements OnClickListener { protected ArrayList<EventPhotoModel> mListImage; private TextView tvTitle; protected int userID; private ViewFlow vfPhoto; private TextView tvDesc; private TextView tvSuppleNone; private TextView tvTrans; private TextView[] tvSupples; private Drawable[] mSuppleIcons; private CircleFlowIndicator mIndicator; public static ArrayList<String> photos; // private static final int[] SUPPLE_ICONS = AppContext.getRes().getIntArray(R.array.venue_supple_icon); private static final int[] SUPPLE_ICONS = { R.drawable.venue_supple_park, R.drawable.venue_supple_taxi, R.drawable.venue_supple_box, R.drawable.venue_supple_rest, R.drawable.venue_supple_bath, R.drawable.venue_supple_sell }; private static final String[] SUPPLE_NAMES = AppContext.getRes().getStringArray(R.array.venue_supple_name); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_venue_more_info); initView(); initData(); } private void initView() { photos = new ArrayList<String>(); findViewById(R.id.page_btn_back).setOnClickListener(this); tvTitle = (TextView) findViewById(R.id.page_tv_title); vfPhoto = (ViewFlow) findViewById(R.id.venue_info_vp); mIndicator = (CircleFlowIndicator) findViewById(R.id.venue_info_ci); vfPhoto.setFlowIndicator(mIndicator); tvDesc = (TextView) findViewById(R.id.venue_info_tv_desc); tvSuppleNone = (TextView) findViewById(R.id.venue_info_tv_none_supple); tvSupples = new TextView[6]; tvSupples[0] = (TextView) findViewById(R.id.venue_info_tv_supple_0); tvSupples[1] = (TextView) findViewById(R.id.venue_info_tv_supple_1); tvSupples[2] = (TextView) findViewById(R.id.venue_info_tv_supple_2); tvSupples[3] = (TextView) findViewById(R.id.venue_info_tv_supple_3); tvSupples[4] = (TextView) findViewById(R.id.venue_info_tv_supple_4); tvSupples[5] = (TextView) findViewById(R.id.venue_info_tv_supple_5); tvTrans = (TextView) findViewById(R.id.venue_info_tv_transport); Resources res = getResources(); int length = SUPPLE_ICONS.length; mSuppleIcons = new Drawable[length]; for (int i = 0; i < length; i++) { Drawable dr = res.getDrawable(SUPPLE_ICONS[i]); dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight()); mSuppleIcons[i] = dr; Log.i("互邀!!!", ""+dr); } } private void initData() { VenueDetialModel data = VenueDetialManager.getInstance().getData(); if(data != null){ tvTitle.setText(data.getFullname()); if (data.getDescription()==null||TextUtils.equals(data.getDescription(), "")) { tvDesc.setText("商家很忙,还没有顾上填写信息呢!"); }else { tvDesc.setText(data.getDescription()); } if (data.getDescription()==null||TextUtils.equals(data.getDescription(), "")) { tvTrans.setText("商家很忙,还没有顾上填写信息呢!"); }else { tvTrans.setText(data.getTransportline()); } int[] supples = data.getSuppleinfolist(); if(supples == null || supples.length == 0 ){ tvSuppleNone.setVisibility(View.VISIBLE); }else{ tvSuppleNone.setVisibility(View.GONE); for(int i = 0; i < supples.length; i++){ Drawable left = mSuppleIcons[supples[i] - 1]; tvSupples[i].setCompoundDrawables(left, null, null, null); tvSupples[i].setText(SUPPLE_NAMES[supples[i] - 1]); tvSupples[i].setVisibility(View.VISIBLE); } for(int i = supples.length;i< SUPPLE_ICONS.length;i++){ tvSupples[i].setVisibility(View.INVISIBLE); } } for (int i = 0; i < data.getVenuephotolist().size(); i++) { photos.add(data.getVenuephotolist().get(i).getPhotopath()); } vfPhoto.setAdapter(new VenuePhotosAdapter(context, data.getVenuephotolist())); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.page_btn_back: finish(); break; case R.id.topic_detial_tv_nick: case R.id.topic_detial_iv_face: default: break; } } }
35.180451
108
0.743108
6867e312b49033c9cf6ea51f84ebf7015bba026c
6,603
package com.fijosilo.ecommerce.authentication; import com.fijosilo.ecommerce.KeyValueMap; import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.*; import org.springframework.test.context.ActiveProfiles; import org.springframework.util.LinkedMultiValueMap; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertTrue; @Tag("IntegrationTest") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ClientControllerIntegrationTest { @LocalServerPort private int port; @Value("${com.fijosilo.ecommerce.admin_email}") private String adminEmail; @Value("${com.fijosilo.ecommerce.admin_password}") private String adminPassword; private TestRestTemplate testRestTemplate = new TestRestTemplate(); private String sessionCookie; private String firstName; private String lastName; @BeforeAll void init() { // request HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); LinkedMultiValueMap<String, String> body= new LinkedMultiValueMap<>(); body.add("email", adminEmail); body.add("password", adminPassword); HttpEntity<LinkedMultiValueMap<String, String>> request = new HttpEntity<>(body, headers); // response ResponseEntity<HashMap> response = testRestTemplate.exchange( "http://localhost:" + port + "/login", HttpMethod.POST, request, HashMap.class ); // tests assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode(), "Failed to login."); // save session cookie assertNotNull(response.getHeaders().getFirst(HttpHeaders.SET_COOKIE), "Failed to read the session cookie"); sessionCookie = response.getHeaders().getFirst(HttpHeaders.SET_COOKIE); } @Test @Order(1) void readClient() { // request HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.add(HttpHeaders.COOKIE, sessionCookie); LinkedMultiValueMap<String, String> body= new LinkedMultiValueMap<>(); HttpEntity<LinkedMultiValueMap<String, String>> request = new HttpEntity<>(body, headers); // response ResponseEntity<HashMap> response = testRestTemplate.exchange( "http://localhost:" + port + "/client", HttpMethod.GET, request, HashMap.class ); // tests assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode(), "Failed to read the client addresses"); assertTrue(response.getBody().containsKey("client"), "Response object must contain a property called 'client' with the client object."); HashMap<String, String> clientMap = KeyValueMap.fromString(response.getBody().get("client").toString()); assertTrue(clientMap.containsKey("firstName"), "'client' must contain a property called 'firstName'."); firstName = clientMap.get("firstName"); assertTrue(clientMap.containsKey("lastName"), "'client' must contain a property called 'lastName'."); lastName = clientMap.get("lastName"); } @Test @Order(2) void updateClient() { // request HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.add(HttpHeaders.COOKIE, sessionCookie); String updatedFirstName = "Updated" + firstName.toLowerCase(); String updatedLastName = "Updated" + lastName.toLowerCase(); LinkedMultiValueMap<String, String> body= new LinkedMultiValueMap<>(); body.add("first_name", updatedFirstName); body.add("last_name", updatedLastName); HttpEntity<LinkedMultiValueMap<String, String>> request = new HttpEntity<>(body, headers); // response ResponseEntity<HashMap> response = testRestTemplate.exchange( "http://localhost:" + port + "/client", HttpMethod.PUT, request, HashMap.class ); // test assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode(), "Failed to update the client."); // read the updated address headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.add(HttpHeaders.COOKIE, sessionCookie); body= new LinkedMultiValueMap<>(); request = new HttpEntity<>(body, headers); response = testRestTemplate.exchange( "http://localhost:" + port + "/client", HttpMethod.GET, request, HashMap.class ); // test the updated address assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode(), "Failed to read the updated client."); assertTrue(response.getBody().containsKey("client"), "Response object must contain a property called 'client' with the client object."); HashMap<String, String> clientMap = KeyValueMap.fromString(response.getBody().get("client").toString()); assertTrue(clientMap.containsKey("firstName"), "'client' must contain a property called 'firstName'."); assertEquals(updatedFirstName, clientMap.get("firstName"), "'firstName' property does not match."); assertTrue(clientMap.containsKey("lastName"), "'client' must contain a property called 'lastName'."); assertEquals(updatedLastName, clientMap.get("lastName"), "'lastName' property does not match."); } }
39.777108
115
0.6806
272b749700e144ba2f30658516d9ac80a833d387
3,647
package org.usfirst.frc.team3499.robot; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { // Digital IO ports public static int DIO0 = 0; public static int DIO1 = 1; public static int DIO2 = 2; public static int DIO3 = 3; public static int DIO4 = 4; public static int DIO5 = 5; public static int DIO6 = 6; public static int DIO7 = 7; public static int DIO8 = 8; public static int DIO9 = 9; // PWM ports public static int PWM0 = 0; public static int PWM1 = 1; public static int PWM2 = 2; public static int PWM3 = 3; public static int PWM4 = 4; public static int PWM5 = 5; public static int PWM6 = 6; public static int PWM7 = 7; public static int PWM8 = 8; public static int PWM9 = 9; // Analog ports public static int ANALOG0 = 0; public static int ANALOG1 = 1; public static int ANALOG2 = 2; public static int ANALOG3 = 3; // Relay ports public static int RELAY0 = 0; public static int RELAY1 = 1; public static int RELAY2 = 2; public static int RELAY3 = 3; // Solenoid Ports (PCM) public static int SOL0 = 0; public static int SOL1 = 1; public static int SOL2 = 2; public static int SOL3 = 3; public static int SOL4 = 4; public static int SOL5 = 5; public static int SOL6 = 6; public static int SOL7 = 7; // USB ports public static int USB0 = 0; public static int USB1 = 1; // Joytick ports (Driver Station) public static int JOY0 = 0; public static int JOY1 = 1; public static int JOY2 = 2; public static int JOY3 = 3; public static int JOY4 = 4; public static int JOY5 = 5; public static int JOY6 = 6; public static int JOY7 = 7; // Joystick buttons public static int TRIGGER = 1; public static int HAT2 = 2; public static int HAT3 = 3; public static int HAT4 = 4; public static int HAT5 = 5; public static int BASE6 = 6; public static int BASE7 = 7; public static int BASE8 = 8; public static int BASE9 = 9; public static int BASE10 = 10; public static int BASE11 = 11; //////////////////////////////////////////////////////////// // Joystick port assignments from Drive Station public static int driveStickPort = JOY0; public static int liftStickPort = JOY1; // Drive motor PWM assignments public static int driveMotorLFPort = PWM2; public static int driveMotorLRPort = PWM3; public static int driveMotorRFPort = PWM4; public static int driveMotorRRPort = PWM5; // TalonSRX assignment public static int liftMotorMasterCanId = 50; public static int liftMotorFollowerCanId = 51; // Tote proximity sensor assignments public static int toteProximitySensorLeftPort = DIO0; public static int toteProximitySensorCenterPort = DIO1; public static int toteProximitySensorRightPort = DIO2; // Ramp proximity sensor assignments public static int rampProximitySensorLeftPort = DIO3; public static int rampProximitySensorRightPort = DIO4; // LED Arduino public static int ledArduinoPort = PWM9; // Debug LED public static int debugLedPort = DIO9; // PCM (pneumatics) assignments public static int pControlCAN = 60; public static int pControlPortLift = SOL1; public static int pControlPortPush = SOL0; }
30.647059
80
0.656978
75ea5dd1c43eb346b7fd0a19e6203e9e08dfbea0
973
package algorithms.cutthesticks; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; class Solution { public static void main(String[] args) { List<Integer> sticks = readInput(); while (sticks.size() > 0) { System.out.println(sticks.size()); sticks = reduceSticks(sticks); } } private static List<Integer> reduceSticks(List<Integer> sticks) { int smallestStick = sticks.stream().min(Integer::compareTo).orElse(0); return sticks .stream() .map(length -> length - smallestStick) .filter(length -> length > 0) .collect(Collectors.toList()); } private static ArrayList<Integer> readInput() { Scanner scanner = new Scanner(System.in); int sticksCount = scanner.nextInt(); ArrayList<Integer> sticks = new ArrayList<>(); for (int i = 0; i < sticksCount; i++) { sticks.add(scanner.nextInt()); } return sticks; } }
24.325
74
0.656732
57bbd632540bb56c170856c41b2259c2225b667c
379
package io.quarkus.rest.client.reactive.error.clientexceptionmapper; import java.util.concurrent.atomic.AtomicInteger; public class DummyException2 extends RuntimeException { static final AtomicInteger executionCount = new AtomicInteger(0); public DummyException2() { executionCount.incrementAndGet(); setStackTrace(new StackTraceElement[0]); } }
27.071429
69
0.76781
f7e56bf36ecab31d23206a573b7e93eccb3e96f2
162
package com.github.osphuhula.gitrepositorygenerator.beans; public interface Team { String getOrganization(); String getName(); String getDescription(); }
13.5
58
0.771605
99b55f300f64231c2d3e2b6125ddfadebab054d1
901
package org.deletethis.hardcode.objects; import java.util.Collection; public interface NodeDefinition { Class<?> getType(); CodeGenerator getConstructionStrategy(); Collection<NodeParameter> getParameters(); /** * Returns list of checked exceptions constructor can throw. Statement will be wrappend in try..catch block */ Collection<Class<? extends Throwable>> getFatalExceptions(); /** * Returns true if current class is a * <a href='https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html'>value-based</a> * class. * * Such values are never searched for additional references, and will be simply duplicated if multiple references * point to the same object. * * @return {@code true} if current node is value-based otherwise {@code false} */ boolean isValueBased(); String toString(); }
32.178571
117
0.691454
dea28409ac0afef2f630b6e0be0a255b6b4deed2
8,565
/* * Fixture Monkey * * Copyright (c) 2021-present NAVER Corp. * * 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.navercorp.fixturemonkey.javax.validation.introspector; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Optional; import javax.validation.constraints.DecimalMax; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.Digits; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Negative; import javax.validation.constraints.NegativeOrZero; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Positive; import javax.validation.constraints.PositiveOrZero; import javax.validation.constraints.Size; import org.apiguardian.api.API; import org.apiguardian.api.API.Status; import com.navercorp.fixturemonkey.api.generator.ArbitraryGeneratorContext; @API(since = "0.4.0", status = Status.EXPERIMENTAL) public class JavaxValidationConstraintGenerator { public JavaxValidationStringConstraint generateStringConstraint(ArbitraryGeneratorContext context) { BigInteger min = null; BigInteger max = null; boolean digits = false; boolean notBlank = context.findAnnotation(NotBlank.class).isPresent(); if (notBlank || context.findAnnotation(NotEmpty.class).isPresent()) { min = BigInteger.ONE; } Optional<Size> size = context.findAnnotation(Size.class); if (size.isPresent()) { int minValue = size.map(Size::min).get(); if (min == null) { min = BigInteger.valueOf(minValue); } else if (minValue > 1) { min = BigInteger.valueOf(minValue); } max = BigInteger.valueOf(size.map(Size::max).get()); } // TODO: support fraction Optional<Digits> digitsAnnotation = context.findAnnotation(Digits.class); if (digitsAnnotation.isPresent()) { digits = true; notBlank = true; BigInteger maxValue = digitsAnnotation.map(Digits::integer).map(BigInteger::valueOf).get(); if (max == null) { max = maxValue; } else if (max.compareTo(maxValue) > 0) { max = maxValue; } } return new JavaxValidationStringConstraint(min, max, digits, notBlank); } public JavaxValidationIntegerConstraint generateIntegerConstraint(ArbitraryGeneratorContext context) { BigInteger min = null; BigInteger max = null; Optional<Digits> digits = context.findAnnotation(Digits.class); if (digits.isPresent()) { BigInteger value = BigInteger.ONE; int integer = digits.get().integer(); if (integer > 1) { value = BigInteger.TEN.pow(integer - 1); } max = value.multiply(BigInteger.TEN).subtract(BigInteger.ONE); min = max.negate(); } Optional<Min> minAnnotation = context.findAnnotation(Min.class); if (minAnnotation.isPresent()) { BigInteger minValue = minAnnotation.map(Min::value).map(BigInteger::valueOf).get(); if (min == null) { min = minValue; } else if (min.compareTo(minValue) > 0) { min = minValue; } } Optional<DecimalMin> decimalMinAnnotation = context.findAnnotation(DecimalMin.class); if (decimalMinAnnotation.isPresent()) { BigInteger decimalMin = decimalMinAnnotation .map(DecimalMin::value) .map(BigInteger::new) .get(); if (!decimalMinAnnotation.map(DecimalMin::inclusive).get()) { decimalMin = decimalMin.add(BigInteger.ONE); } if (min == null) { min = decimalMin; } else if (min.compareTo(decimalMin) < 0) { min = decimalMin; } } Optional<Max> maxAnnotation = context.findAnnotation(Max.class); if (maxAnnotation.isPresent()) { BigInteger maxValue = maxAnnotation.map(Max::value).map(BigInteger::valueOf).get(); if (max == null) { max = maxValue; } else if (max.compareTo(maxValue) > 0) { max = maxValue; } } Optional<DecimalMax> decimalMaxAnnotation = context.findAnnotation(DecimalMax.class); if (decimalMaxAnnotation.isPresent()) { BigInteger decimalMax = decimalMaxAnnotation .map(DecimalMax::value) .map(BigInteger::new) .get(); if (!decimalMaxAnnotation.map(DecimalMax::inclusive).get()) { decimalMax = decimalMax.subtract(BigInteger.ONE); } if (max == null) { max = decimalMax; } else if (max.compareTo(decimalMax) > 0) { max = decimalMax; } } if (context.findAnnotation(Negative.class).isPresent()) { if (max == null || max.compareTo(BigInteger.ZERO) > 0) { max = BigInteger.valueOf(-1); } } if (context.findAnnotation(NegativeOrZero.class).isPresent()) { if (max == null || max.compareTo(BigInteger.ZERO) > 0) { max = BigInteger.ZERO; } } if (context.findAnnotation(Positive.class).isPresent()) { if (min == null || min.compareTo(BigInteger.ZERO) < 0) { min = BigInteger.ONE; } } if (context.findAnnotation(PositiveOrZero.class).isPresent()) { if (min == null || min.compareTo(BigInteger.ZERO) < 0) { min = BigInteger.ZERO; } } return new JavaxValidationIntegerConstraint(min, max); } public JavaxValidationDecimalConstraint generateDecimalConstraint(ArbitraryGeneratorContext context) { BigDecimal min = null; Boolean minInclusive = null; BigDecimal max = null; Boolean maxInclusive = null; Optional<Digits> digits = context.findAnnotation(Digits.class); if (digits.isPresent()) { BigDecimal value = BigDecimal.ONE; int integer = digits.get().integer(); if (integer > 1) { value = BigDecimal.TEN.pow(integer - 1); } max = value.multiply(BigDecimal.TEN).subtract(BigDecimal.ONE); min = max.negate(); } Optional<Min> minAnnotation = context.findAnnotation(Min.class); if (minAnnotation.isPresent()) { BigDecimal minValue = minAnnotation.map(Min::value).map(BigDecimal::valueOf).get(); if (min == null) { min = minValue; } else if (min.compareTo(minValue) > 0) { min = minValue; } } Optional<DecimalMin> decimalMinAnnotation = context.findAnnotation(DecimalMin.class); if (decimalMinAnnotation.isPresent()) { BigDecimal decimalMin = decimalMinAnnotation .map(DecimalMin::value) .map(BigDecimal::new) .get(); if (!decimalMinAnnotation.map(DecimalMin::inclusive).get()) { minInclusive = false; } if (min == null) { min = decimalMin; } else if (min.compareTo(decimalMin) < 0) { min = decimalMin; } } Optional<Max> maxAnnotation = context.findAnnotation(Max.class); if (maxAnnotation.isPresent()) { BigDecimal maxValue = maxAnnotation.map(Max::value).map(BigDecimal::valueOf).get(); if (max == null) { max = maxValue; } else if (max.compareTo(maxValue) > 0) { max = maxValue; } } Optional<DecimalMax> decimalMaxAnnotation = context.findAnnotation(DecimalMax.class); if (decimalMaxAnnotation.isPresent()) { BigDecimal decimalMax = decimalMaxAnnotation .map(DecimalMax::value) .map(BigDecimal::new) .get(); if (!decimalMaxAnnotation.map(DecimalMax::inclusive).get()) { maxInclusive = false; } if (max == null) { max = decimalMax; } else if (max.compareTo(decimalMax) > 0) { max = decimalMax; } } if (context.findAnnotation(Negative.class).isPresent()) { if (max == null || max.compareTo(BigDecimal.ZERO) > 0) { max = BigDecimal.ZERO; maxInclusive = false; } } if (context.findAnnotation(NegativeOrZero.class).isPresent()) { if (max == null || max.compareTo(BigDecimal.ZERO) > 0) { max = BigDecimal.ZERO; } } if (context.findAnnotation(Positive.class).isPresent()) { if (min == null || min.compareTo(BigDecimal.ZERO) < 0) { min = BigDecimal.ZERO; minInclusive = false; } } if (context.findAnnotation(PositiveOrZero.class).isPresent()) { if (min == null || min.compareTo(BigDecimal.ZERO) < 0) { min = BigDecimal.ZERO; } } if (min != null && minInclusive == null) { minInclusive = true; } if (max != null && maxInclusive == null) { maxInclusive = true; } return new JavaxValidationDecimalConstraint(min, minInclusive, max, maxInclusive); } }
29.332192
103
0.695038
4c6ce8404ac0104a65d428a49ca7b761233e676b
1,980
package com.yuxie.demo; import lombok.Data; /** * @author by 心涯 * @package com.yuxie.demo * @classname RequestLimiter * @description 请求限流器,限制某个时间区间内允许的最大请求数 * @date 2019/12/3 10:33 */ @Data public class RequestLimiter { /** * 节点 用于维护链表 */ @Data static class Node { /** * 时间戳 */ private long timestamp; /** * 下一个节点 */ private Node next; public Node(long timestamp, Node next) { this.timestamp = timestamp; this.next = next; } } /** * 限流器限流阈值 * 假定时间区间内最多允许10个请求 */ public static final int N = 10; /** * 时间区间长度 * 单位:毫秒 */ public static final long MS = 1000; /** * 头节点 * 存储最老的节点 */ private Node head; /** * 尾节点 * 存储最新的节点 */ private Node last; /** * 链表长度 初始为0 */ private volatile int length = 0; /** * 新传入的请求是否允许向下传递 * @param timestamp 最新一次请求的的时间戳(这个请求参数是否是必须要调用方传入的?) * @return 该请求是否允许向下传递 */ public synchronized boolean canBeAccepted (long timestamp) { // 第一次调用时,链表为空 if (this.length == 0) { Node newNode = new Node(timestamp , null); this.head = newNode; this.last = newNode; this.length++; return true; } // 链表已满且最老的元素与最新的请求之间的时间还未超出时间区间限制,不接受请求 // 除链表未满时的几个请求外,其余请求均必定会判断最老节点是否过期 // 故优先判断是否过期能更为有效的利用熔断机制减少总体所需进行的判断数量 if ((timestamp - this.head.timestamp) < MS && this.length == N) { return false; } // 1、先添加新节点 Node newNode = new Node(timestamp , null); this.last.next = newNode; this.last = newNode; // 2、然后再清除过期元素,避免链表长度为1时而刚好唯一的旧节点过期了的情况 if ((timestamp - this.head.timestamp) >= MS) { this.head = this.head.next; } else { this.length++; } return true; } }
21.290323
73
0.518182
97bd26ba6cfb795b8959740b50807a8969699551
4,655
/* * Copyright 2006-2009, 2017, 2020 United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA World Wind Java (WWJ) platform is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * 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. * * NASA World Wind Java (WWJ) also contains the following 3rd party Open Source * software: * * Jackson Parser – Licensed under Apache 2.0 * GDAL – Licensed under MIT * JOGL – Licensed under Berkeley Software Distribution (BSD) * Gluegen – Licensed under Berkeley Software Distribution (BSD) * * A complete listing of 3rd Party software notices and licenses included in * NASA World Wind Java (WWJ) can be found in the WorldWindJava-v2.2 3rd-party * notices and licenses PDF found in code directory. */ package gov.nasa.worldwind.ogc.collada.impl; import gov.nasa.worldwind.ogc.collada.ColladaRoot; import gov.nasa.worldwind.render.*; import gov.nasa.worldwind.util.Logging; /** * Executes the mapping from COLLADA to WorldWind. Traverses a parsed COLLADA document and creates the appropriate * WorldWind object to represent the COLLADA model. * * @author pabercrombie * @version $Id: ColladaController.java 661 2012-06-26 18:02:23Z pabercrombie $ */ public class ColladaController implements Renderable, PreRenderable { /** Collada document rendered by this controller. */ protected ColladaRoot colladaRoot; /** Traversal context used to render the document. */ protected ColladaTraversalContext tc; /** * Create a new controller to render a COLLADA document. * * @param root Parsed COLLADA document to render. */ public ColladaController(ColladaRoot root) { this.setColladaRoot(root); this.setTraversalContext(new ColladaTraversalContext()); } /** * Indicates the COLLADA document that this controller will render. * * @return The COLLADA document referenced by this controller. */ public ColladaRoot getColladaRoot() { return this.colladaRoot; } /** * Specifies the COLLADA document that this controller will render. * * @param colladaRoot New COLLADA document to render. */ public void setColladaRoot(ColladaRoot colladaRoot) { if (colladaRoot == null) { String msg = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.colladaRoot = colladaRoot; } /** * Indicates the traversal context used to render the COLLADA document. * * @return The active traversal context. */ public ColladaTraversalContext getTraversalContext() { return this.tc; } /** * Specifies a traversal context to use while rendering the COLLADA document. * * @param tc New traversal context. */ public void setTraversalContext(ColladaTraversalContext tc) { if (tc == null) { String msg = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.tc = tc; } /** {@inheritDoc} */ public void preRender(DrawContext dc) { this.initializeTraversalContext(this.getTraversalContext()); this.colladaRoot.preRender(this.getTraversalContext(), dc); } /** {@inheritDoc} */ public void render(DrawContext dc) { this.initializeTraversalContext(this.getTraversalContext()); this.colladaRoot.render(this.getTraversalContext(), dc); } /** * Initializes this COLLADA controller's traversal context to its default state. A COLLADA traversal context must be * initialized prior to use during preRendering or rendering, to ensure that state from the previous pass does not * affect the current pass. * * @param tc the COLLADA traversal context to initialize. */ protected void initializeTraversalContext(ColladaTraversalContext tc) { tc.initialize(); } }
33.25
120
0.686574
9671ecb6135498e4fa45559451512d16b6624881
236
package fr.jeudelavie.controleur; import fr.jeudelavie.vue.FenetrePrincipale; public class Lanceur { /** * @param args */ public static void main(final String[] args) { FenetrePrincipale.getInstance().nouvellePartie(); } }
15.733333
51
0.724576
60573d0b3781725e4a3ac88cf8797cab0441653a
3,835
package org.riverframework.wrapper.org.openntf.domino; import org.openntf.domino.Base; import org.openntf.domino.ViewColumn; import org.riverframework.River; import org.riverframework.wrapper.Document; import org.riverframework.wrapper.DocumentIterator; import org.riverframework.wrapper.View; class DefaultView extends AbstractBaseOrgOpenntfDomino<org.openntf.domino.View> implements org.riverframework.wrapper.View<org.openntf.domino.View> { // private static final Logger log = River.LOG_WRAPPER_ORG_OPENNTF_DOMINO; protected DefaultView(org.riverframework.wrapper.Session<org.openntf.domino.Session> _session, org.openntf.domino.View __native) { super(_session, __native); } @Override public String calcObjectId(org.openntf.domino.View __view) { String objectId = ""; if (__view != null) { org.openntf.domino.Database __database = __view.getParent(); StringBuilder sb = new StringBuilder(); sb.append(__database.getServer()); sb.append(River.ID_SEPARATOR); sb.append(__database.getFilePath()); sb.append(River.ID_SEPARATOR); sb.append(__view.getName()); objectId = sb.toString(); } return objectId; } @Override public Document<org.openntf.domino.Base<?>> getDocumentByKey(String key) { org.openntf.domino.Document __doc = null; __doc = __native.getDocumentByKey(key, true); @SuppressWarnings("unchecked") Document<org.openntf.domino.Base<?>> doc = (Document<Base<?>>) _factory.getDocument(__doc); return doc; } @Override public boolean isOpen() { return __native != null; } @Override public DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> getAllDocuments() { org.openntf.domino.ViewEntryCollection __col; __col = __native.getAllEntries(); @SuppressWarnings("unchecked") DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> result = (DocumentIterator<Base<?>, org.openntf.domino.Document>) _factory.getDocumentIterator(__col); return result; } @Override public DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> getAllDocumentsByKey(Object key) { org.openntf.domino.DocumentCollection _col; _col = __native.getAllDocumentsByKey(key, true); @SuppressWarnings("unchecked") DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> result = (DocumentIterator<Base<?>, org.openntf.domino.Document>) _factory.getDocumentIterator(_col); return result; } @Override public View<org.openntf.domino.View> refresh() { __native.refresh(); return this; } @Override public void delete() { if (__native != null) { __native.remove(); __native = null; } } @Override public DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> search(String query) { DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> _iterator = search(query, 0); return _iterator; } @Override public DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> search(String query, int max) { org.openntf.domino.View __temp = null; __temp = __native.getParent().getView(__native.getName()); __temp.FTSearch(query, max); @SuppressWarnings("unchecked") DocumentIterator<org.openntf.domino.Base<?>,org.openntf.domino.Document> _iterator = (DocumentIterator<Base<?>, org.openntf.domino.Document>) _factory.getDocumentIterator(__temp); return _iterator; } @Override public View<org.openntf.domino.View> addColumn(String name, String value, boolean isSorted) { ViewColumn __col = __native.createColumn(__native.getColumnCount(), name, value); __col.setSorted(isSorted); return this; } @Override public void close() { // Don't recycle or close it. Let the server do that. } @Override public String toString() { return getClass().getName() + "(" + objectId + ")"; } }
30.19685
149
0.74837
eba64e1306881e41f118ddd5afb88441ff3df943
1,333
package gov.tubitak.xoola.core; import gov.tubitak.xoola.transport.Invocation; import java.util.Properties; import gov.tubitak.xoola.exception.XCommunicationException; import gov.tubitak.xoola.tcpcom.connmanager.client.NettyClient; import gov.tubitak.xoola.transport.Invocation; import gov.tubitak.xoola.util.ObjectUtils; public class XoolaClientInvocationHandler extends XoolaInvocationHandler { private NettyClient nettyClient; private String id; public XoolaClientInvocationHandler(Properties properties) { super(properties); this.nettyClient = new NettyClient(properties, this); this.id = ObjectUtils.getOrDefault(properties.get(XoolaProperty.CLIENTID), "xoolaClient"); } @Override protected void sendMessage(String remoteName, Invocation message) { nettyClient.send(remoteName, message); } @Override public <T> T get(Class<T> interfaze, String remoteName, String remoteObjectName, boolean async) { if (nettyClient.isAvailable()) { return createProxyForClass(interfaze, remoteName, remoteObjectName, async); } throw new XCommunicationException("Not connected to any servers"); } @Override public String getId() { return id; } @Override public void stop() { nettyClient.stop(); } @Override public void start() { nettyClient.start(); } }
26.66
99
0.754689
44f23d7aa05e3a2b9749d38626eda2b20cc0b568
1,326
package io.github.jiezhi.lc; import java.util.List; import java.util.stream.Collectors; /** * CREATED AT: 2022/3/7 * <p> * PROJECT: LCOF-Java * <p> * https://github.com/Jiezhi/LCOF-Java * <p> * Difficulty: * <p> * SEE: * <p> * DES: * <p> */ public class LC2193 { /** * 执行用时:22 ms, 在所有 Java 提交中击败了27.33%的用户 * 内存消耗:41.1 MB, 在所有 Java 提交中击败了37.33%的用户 * 通过测试用例:129 / 129 * * @param s 1 <= s.length <= 2000 * s 只包含小写英文字母。 * s 可以通过有限次操作得到一个回文串。 * @return */ public int minMovesToMakePalindrome(String s) { // 先把字符串转换成列表 // 方法一 // List<Character> list = new ArrayList<>(s.length()); // for (char c : s.toCharArray()) { // list.add(c); // } // 方法二 List<Character> list = s.chars().mapToObj(c -> (char) c).collect(Collectors.toList()); int len; int pos; int ret = 0; while (!list.isEmpty()) { len = list.size(); pos = list.indexOf(list.get(len - 1)); if (pos == len - 1) { ret += pos / 2; list.remove(len - 1); } else { ret += pos; list.remove(len - 1); list.remove(pos); } } return ret; } }
22.1
94
0.463801
aeefedc97c766525b03127360308a8d81c211713
12,926
/* * Copyright (C) 2015 Baidu, Inc. All Rights Reserved. */ package online.himakeit.baidumapdemo; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.BDNotifyListener; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.VersionInfo; import online.himakeit.baidumapdemo.cloud.CloudSearchDemo; import online.himakeit.baidumapdemo.map.BaseMapDemo; import online.himakeit.baidumapdemo.map.FavoriteDemo; import online.himakeit.baidumapdemo.map.GeometryDemo; import online.himakeit.baidumapdemo.map.HeatMapDemo; import online.himakeit.baidumapdemo.map.IndoorMapDemo; import online.himakeit.baidumapdemo.map.LayersDemo; import online.himakeit.baidumapdemo.map.LocationDemo; import online.himakeit.baidumapdemo.map.MapControlDemo; import online.himakeit.baidumapdemo.map.MapFragmentDemo; import online.himakeit.baidumapdemo.map.MarkerClusterDemo; import online.himakeit.baidumapdemo.map.MultiMapViewDemo; import online.himakeit.baidumapdemo.map.OfflineDemo; import online.himakeit.baidumapdemo.map.OpenglDemo; import online.himakeit.baidumapdemo.map.OverlayDemo; import online.himakeit.baidumapdemo.map.TextureMapViewDemo; import online.himakeit.baidumapdemo.map.TileOverlayDemo; import online.himakeit.baidumapdemo.map.TrackShowDemo; import online.himakeit.baidumapdemo.map.UISettingDemo; import online.himakeit.baidumapdemo.radar.RadarDemo; import online.himakeit.baidumapdemo.search.BusLineSearchDemo; import online.himakeit.baidumapdemo.search.DistrictSearchDemo; import online.himakeit.baidumapdemo.search.GeoCoderDemo; import online.himakeit.baidumapdemo.search.IndoorSearchDemo; import online.himakeit.baidumapdemo.search.PoiSearchDemo; import online.himakeit.baidumapdemo.search.RoutePlanDemo; import online.himakeit.baidumapdemo.search.ShareDemo; import online.himakeit.baidumapdemo.util.OpenBaiduMap; /** * @author:LiXueLong * @date:2018/2/28-14:09 * @mail1:skylarklxlong@outlook.com * @mail2:li_xuelong@126.com * @des:BMapApiDemoMain */ public class BMapApiDemoMain extends AppCompatActivity { private static final String LTAG = BMapApiDemoMain.class.getSimpleName(); /** * 构造广播监听类,监听 SDK key 验证以及网络异常广播 */ public class SDKReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String s = intent.getAction(); Log.d(LTAG, "action: " + s); TextView text = (TextView) findViewById(R.id.text_Info); text.setTextColor(Color.RED); if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) { text.setText("key 验证出错! 错误码 :" + intent.getIntExtra (SDKInitializer.SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE, 0) + " ; 请在 AndroidManifest.xml 文件中检查 key 设置"); } else if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) { text.setText("key 验证成功! 功能可以正常使用"); text.setTextColor(Color.YELLOW); } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) { text.setText("网络出错"); } } } private SDKReceiver mReceiver; public static LocationService locationService; public static String locationStr; public static double latitude; // 纬度 public static double lontitude; // 经度 public static String city; public static String province; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView text = (TextView) findViewById(R.id.text_Info); text.setTextColor(Color.YELLOW); text.setText("欢迎使用百度地图Android SDK v" + VersionInfo.getApiVersion()); setTitle(getTitle() + " v" + VersionInfo.getApiVersion()); ListView mListView = (ListView) findViewById(R.id.listView); // 添加ListItem,设置事件响应 mListView.setAdapter(new DemoListAdapter()); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int index, long arg3) { onListItemClick(index); } }); // 注册 SDK 广播监听者 IntentFilter iFilter = new IntentFilter(); iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK); iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR); iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR); mReceiver = new SDKReceiver(); registerReceiver(mReceiver, iFilter); } void onListItemClick(int index) { Intent intent; intent = new Intent(BMapApiDemoMain.this, DEMOS[index].demoClass); this.startActivity(intent); } private static final DemoInfo[] DEMOS = { new DemoInfo(R.string.demo_title_basemap, R.string.demo_desc_basemap, BaseMapDemo.class), new DemoInfo(R.string.demo_title_map_fragment, R.string.demo_desc_map_fragment, MapFragmentDemo.class), new DemoInfo(R.string.demo_title_layers, R.string.demo_desc_layers, LayersDemo.class), new DemoInfo(R.string.demo_title_multimap, R.string.demo_desc_multimap, MultiMapViewDemo.class), new DemoInfo(R.string.demo_title_control, R.string.demo_desc_control, MapControlDemo.class), new DemoInfo(R.string.demo_title_ui, R.string.demo_desc_ui, UISettingDemo.class), new DemoInfo(R.string.demo_title_location, R.string.demo_desc_location, LocationDemo.class), new DemoInfo(R.string.demo_title_geometry, R.string.demo_desc_geometry, GeometryDemo.class), new DemoInfo(R.string.demo_title_overlay, R.string.demo_desc_overlay, OverlayDemo.class), new DemoInfo(R.string.demo_title_heatmap, R.string.demo_desc_heatmap, HeatMapDemo.class), new DemoInfo(R.string.demo_title_geocode, R.string.demo_desc_geocode, GeoCoderDemo.class), new DemoInfo(R.string.demo_title_poi, R.string.demo_desc_poi, PoiSearchDemo.class), new DemoInfo(R.string.demo_title_route, R.string.demo_desc_route, RoutePlanDemo.class), new DemoInfo(R.string.demo_title_districsearch, R.string.demo_desc_districsearch, DistrictSearchDemo.class), new DemoInfo(R.string.demo_title_bus, R.string.demo_desc_bus, BusLineSearchDemo.class), new DemoInfo(R.string.demo_title_share, R.string.demo_desc_share, ShareDemo.class), new DemoInfo(R.string.demo_title_offline, R.string.demo_desc_offline, OfflineDemo.class), new DemoInfo(R.string.demo_title_radar, R.string.demo_desc_radar, RadarDemo.class), new DemoInfo(R.string.demo_title_open_baidumap, R.string.demo_desc_open_baidumap, OpenBaiduMap.class), new DemoInfo(R.string.demo_title_favorite, R.string.demo_desc_favorite, FavoriteDemo.class), new DemoInfo(R.string.demo_title_cloud, R.string.demo_desc_cloud, CloudSearchDemo.class), new DemoInfo(R.string.demo_title_opengl, R.string.demo_desc_opengl, OpenglDemo.class), new DemoInfo(R.string.demo_title_cluster, R.string.demo_desc_cluster, MarkerClusterDemo.class), new DemoInfo(R.string.demo_title_tileoverlay, R.string.demo_desc_tileoverlay, TileOverlayDemo.class), new DemoInfo(R.string.demo_desc_texturemapview, R.string.demo_desc_texturemapview, TextureMapViewDemo.class), new DemoInfo(R.string.demo_title_indoor, R.string.demo_desc_indoor, IndoorMapDemo.class), new DemoInfo(R.string.demo_title_indoorsearch, R.string.demo_desc_indoorsearch, IndoorSearchDemo.class), new DemoInfo(R.string.demo_track_show, R.string.demo_desc_track_show, TrackShowDemo.class) }; @Override protected void onResume() { super.onResume(); } @Override protected void onStart() { super.onStart(); locationService = new LocationService(getApplicationContext()); locationService.registerListener(mListener); locationService.registerNotify(notifyListener); notifyListener.SetNotifyLocation(30.429502f, 114.469785f, 3000, locationService.getDefaultLocationClientOption().getCoorType()); locationService.setLocationOption(locationService.getDefaultLocationClientOption()); locationService.start();// 定位SDK } @Override protected void onDestroy() { super.onDestroy(); // 取消监听 SDK 广播 unregisterReceiver(mReceiver); } /** * 位置提醒 */ private BDNotifyListener notifyListener = new BDNotifyListener() { @Override public void onNotify(BDLocation bdLocation, float v) { Log.e(LTAG, "到达目的地:武汉市江夏区富五路"); Toast.makeText(BMapApiDemoMain.this, "到达目的地:武汉市江夏区富五路", Toast.LENGTH_SHORT).show(); locationService.removeNotifyEvent(notifyListener); } }; /** * 监听位置 */ private BDLocationListener mListener = new BDLocationListener() { @Override public void onReceiveLocation(BDLocation location) { if (null != location && location.getLocType() != BDLocation.TypeServerError) { StringBuffer sb = new StringBuffer(256); sb.append("latitude : ");// 纬度 sb.append(location.getLatitude()); latitude = location.getLatitude(); sb.append("\nlontitude : ");// 经度 sb.append(location.getLongitude()); lontitude = location.getLongitude(); sb.append("\nCity : "); //所在城市 sb.append(location.getCity()); city = location.getCity(); province = location.getProvince(); sb.append("\naddr : ");// 地址信息 sb.append(location.getAddrStr()); locationStr = sb.toString(); Toast.makeText(BMapApiDemoMain.this, locationStr, Toast.LENGTH_SHORT).show(); Log.e(LTAG, "locationStr" + locationStr); locationService.unregisterListener(mListener); //注销掉监听 locationService.stop(); //停止定位服务 } } }; private class DemoListAdapter extends BaseAdapter { public DemoListAdapter() { super(); } @Override public View getView(int index, View convertView, ViewGroup parent) { convertView = View.inflate(BMapApiDemoMain.this, R.layout.demo_info_item, null); TextView title = (TextView) convertView.findViewById(R.id.title); TextView desc = (TextView) convertView.findViewById(R.id.desc); title.setText(DEMOS[index].title); desc.setText(DEMOS[index].desc); if (index >= 25) { title.setTextColor(Color.YELLOW); } return convertView; } @Override public int getCount() { return DEMOS.length; } @Override public Object getItem(int index) { return DEMOS[index]; } @Override public long getItemId(int id) { return id; } } private static class DemoInfo { private final int title; private final int desc; private final Class<? extends Activity> demoClass; public DemoInfo(int title, int desc, Class<? extends Activity> demoClass) { this.title = title; this.desc = desc; this.demoClass = demoClass; } } }
41.034921
136
0.660761
2cf5248cd058536e24d094352541b81b1821dff9
143
package me.vmamakers.practice; public class VeggiePizza implements Pizza { @Override public String getType() { return "Veggie"; } }
13
43
0.713287
3e8077ab1a213fa82588dc42075b1ad30adf0400
573
package com.faxi.cloudmall.coupon.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.faxi.cloudmall.coupon.entity.SeckillSkuNotice; import com.faxi.cloudmall.coupon.mapper.SeckillSkuNoticeMapper; import com.faxi.cloudmall.coupon.service.SeckillSkuNoticeService; import org.springframework.stereotype.Service; /** * 秒杀商品通知订阅 * * @author faxi * @date 2021-07-05 21:58:42 */ @Service public class SeckillSkuNoticeServiceImpl extends ServiceImpl<SeckillSkuNoticeMapper, SeckillSkuNotice> implements SeckillSkuNoticeService { }
30.157895
139
0.827225
3e35898a08282eb3991e960a172bb9ccf3793269
25,626
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.sql.implementation; import com.microsoft.azure.management.apigeneration.LangDefinition; import com.microsoft.azure.management.resources.fluentcore.arm.Region; import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils; import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.ExternalChildResourceImpl; import com.microsoft.azure.management.resources.fluentcore.dag.TaskGroup; import com.microsoft.azure.management.sql.ElasticPoolActivity; import com.microsoft.azure.management.sql.ElasticPoolDatabaseActivity; import com.microsoft.azure.management.sql.ElasticPoolEditions; import com.microsoft.azure.management.sql.ElasticPoolState; import com.microsoft.azure.management.sql.SqlDatabase; import com.microsoft.azure.management.sql.SqlDatabaseMetric; import com.microsoft.azure.management.sql.SqlDatabaseMetricDefinition; import com.microsoft.azure.management.sql.SqlDatabaseStandardServiceObjective; import com.microsoft.azure.management.sql.SqlElasticPool; import com.microsoft.azure.management.sql.SqlElasticPoolBasicEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolBasicMaxEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolBasicMinEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolOperations; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumMaxEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumMinEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolPremiumSorage; import com.microsoft.azure.management.sql.SqlElasticPoolStandardEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolStandardMaxEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolStandardMinEDTUs; import com.microsoft.azure.management.sql.SqlElasticPoolStandardStorage; import com.microsoft.azure.management.sql.SqlServer; import org.joda.time.DateTime; import rx.Completable; import rx.Observable; import rx.functions.Func1; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Implementation for SqlElasticPool. */ @LangDefinition public class SqlElasticPoolImpl extends ExternalChildResourceImpl<SqlElasticPool, ElasticPoolInner, SqlServerImpl, SqlServer> implements SqlElasticPool, SqlElasticPool.SqlElasticPoolDefinition<SqlServer.DefinitionStages.WithCreate>, SqlElasticPoolOperations.DefinitionStages.WithCreate, SqlElasticPool.Update, SqlElasticPoolOperations.SqlElasticPoolOperationsDefinition { private SqlServerManager sqlServerManager; private String resourceGroupName; private String sqlServerName; private String sqlServerLocation; private SqlDatabasesAsExternalChildResourcesImpl sqlDatabases; /** * Creates an instance of external child resource in-memory. * * @param name the name of this external child resource * @param parent reference to the parent of this external child resource * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ SqlElasticPoolImpl(String name, SqlServerImpl parent, ElasticPoolInner innerObject, SqlServerManager sqlServerManager) { super(name, parent, innerObject); Objects.requireNonNull(parent); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; this.resourceGroupName = parent.resourceGroupName(); this.sqlServerName = parent.name(); this.sqlServerLocation = parent.regionName(); this.sqlDatabases = null; } /** * Creates an instance of external child resource in-memory. * * @param resourceGroupName the resource group name * @param sqlServerName the parent SQL server name * @param sqlServerLocation the parent SQL server location * @param name the name of this external child resource * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ SqlElasticPoolImpl(String resourceGroupName, String sqlServerName, String sqlServerLocation, String name, ElasticPoolInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; this.sqlServerLocation = sqlServerLocation; this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } /** * Creates an instance of external child resource in-memory. * * @param name the name of this external child resource * @param innerObject reference to the inner object representing this external child resource * @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations */ SqlElasticPoolImpl(String name, ElasticPoolInner innerObject, SqlServerManager sqlServerManager) { super(name, null, innerObject); Objects.requireNonNull(sqlServerManager); this.sqlServerManager = sqlServerManager; this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } @Override public String id() { return this.inner().id(); } @Override public String resourceGroupName() { return this.resourceGroupName; } @Override public String sqlServerName() { return this.sqlServerName; } @Override public DateTime creationDate() { return this.inner().creationDate(); } @Override public ElasticPoolState state() { return this.inner().state(); } @Override public ElasticPoolEditions edition() { return this.inner().edition(); } @Override public int dtu() { return this.inner().dtu(); } @Override public int databaseDtuMax() { return this.inner().databaseDtuMax(); } @Override public int databaseDtuMin() { return this.inner().databaseDtuMin(); } @Override public int storageMB() { return this.inner().storageMB(); } @Override public int storageCapacityInMB() { return this.inner().storageMB(); } @Override public String parentId() { return ResourceUtils.parentResourceIdFromResourceId(this.id()); } @Override public String regionName() { return this.sqlServerLocation; } @Override public Region region() { return Region.findByLabelOrName(this.regionName()); } @Override public List<ElasticPoolActivity> listActivities() { List<ElasticPoolActivity> elasticPoolActivities = new ArrayList<>(); List<ElasticPoolActivityInner> elasticPoolActivityInners = this.sqlServerManager.inner() .elasticPoolActivities().listByElasticPool(this.resourceGroupName, this.sqlServerName, this.name()); if (elasticPoolActivityInners != null) { for (ElasticPoolActivityInner inner : elasticPoolActivityInners) { elasticPoolActivities.add(new ElasticPoolActivityImpl(inner)); } } return Collections.unmodifiableList(elasticPoolActivities); } @Override public Observable<ElasticPoolActivity> listActivitiesAsync() { return this.sqlServerManager.inner() .elasticPoolActivities().listByElasticPoolAsync(this.resourceGroupName, this.sqlServerName, this.name()) .flatMap(new Func1<List<ElasticPoolActivityInner>, Observable<ElasticPoolActivityInner>>() { @Override public Observable<ElasticPoolActivityInner> call(List<ElasticPoolActivityInner> elasticPoolActivityInners) { return Observable.from(elasticPoolActivityInners); } }) .map(new Func1<ElasticPoolActivityInner, ElasticPoolActivity>() { @Override public ElasticPoolActivity call(ElasticPoolActivityInner elasticPoolActivityInner) { return new ElasticPoolActivityImpl(elasticPoolActivityInner); } }); } @Override public List<ElasticPoolDatabaseActivity> listDatabaseActivities() { List<ElasticPoolDatabaseActivity> elasticPoolDatabaseActivities = new ArrayList<>(); List<ElasticPoolDatabaseActivityInner> elasticPoolDatabaseActivityInners = this.sqlServerManager.inner() .elasticPoolDatabaseActivities().listByElasticPool(this.resourceGroupName, this.sqlServerName, this.name()); if (elasticPoolDatabaseActivityInners != null) { for (ElasticPoolDatabaseActivityInner inner : elasticPoolDatabaseActivityInners) { elasticPoolDatabaseActivities.add(new ElasticPoolDatabaseActivityImpl(inner)); } } return Collections.unmodifiableList(elasticPoolDatabaseActivities); } @Override public Observable<ElasticPoolDatabaseActivity> listDatabaseActivitiesAsync() { return this.sqlServerManager.inner() .elasticPoolDatabaseActivities().listByElasticPoolAsync(this.resourceGroupName, this.sqlServerName, this.name()) .flatMap(new Func1<List<ElasticPoolDatabaseActivityInner>, Observable<ElasticPoolDatabaseActivityInner>>() { @Override public Observable<ElasticPoolDatabaseActivityInner> call(List<ElasticPoolDatabaseActivityInner> elasticPoolDatabaseActivityInners) { return Observable.from(elasticPoolDatabaseActivityInners); } }).map(new Func1<ElasticPoolDatabaseActivityInner, ElasticPoolDatabaseActivity>() { @Override public ElasticPoolDatabaseActivity call(ElasticPoolDatabaseActivityInner elasticPoolDatabaseActivityInner) { return new ElasticPoolDatabaseActivityImpl(elasticPoolDatabaseActivityInner); } }); } @Override public List<SqlDatabaseMetric> listDatabaseMetrics(String filter) { List<SqlDatabaseMetric> databaseMetrics = new ArrayList<>(); List<MetricInner> inners = this.sqlServerManager.inner().elasticPools().listMetrics(this.resourceGroupName, this.sqlServerName, this.name(), filter); if (inners != null) { for (MetricInner inner : inners) { databaseMetrics.add(new SqlDatabaseMetricImpl(inner)); } } return Collections.unmodifiableList(databaseMetrics); } @Override public Observable<SqlDatabaseMetric> listDatabaseMetricsAsync(String filter) { return this.sqlServerManager.inner().elasticPools().listMetricsAsync(this.resourceGroupName, this.sqlServerName, this.name(), filter) .flatMap(new Func1<List<MetricInner>, Observable<MetricInner>>() { @Override public Observable<MetricInner> call(List<MetricInner> metricInners) { return Observable.from(metricInners); } }).map(new Func1<MetricInner, SqlDatabaseMetric>() { @Override public SqlDatabaseMetric call(MetricInner metricInner) { return new SqlDatabaseMetricImpl(metricInner); } }); } @Override public List<SqlDatabaseMetricDefinition> listDatabaseMetricDefinitions() { List<SqlDatabaseMetricDefinition> databaseMetricDefinitions = new ArrayList<>(); List<MetricDefinitionInner> inners = this.sqlServerManager.inner().elasticPools().listMetricDefinitions(this.resourceGroupName, this.sqlServerName, this.name()); if (inners != null) { for (MetricDefinitionInner inner : inners) { databaseMetricDefinitions.add(new SqlDatabaseMetricDefinitionImpl(inner)); } } return Collections.unmodifiableList(databaseMetricDefinitions); } @Override public Observable<SqlDatabaseMetricDefinition> listDatabaseMetricDefinitionsAsync() { return this.sqlServerManager.inner().elasticPools().listMetricDefinitionsAsync(this.resourceGroupName, this.sqlServerName, this.name()) .flatMap(new Func1<List<MetricDefinitionInner>, Observable<MetricDefinitionInner>>() { @Override public Observable<MetricDefinitionInner> call(List<MetricDefinitionInner> metricDefinitionInners) { return Observable.from(metricDefinitionInners); } }).map(new Func1<MetricDefinitionInner, SqlDatabaseMetricDefinition>() { @Override public SqlDatabaseMetricDefinition call(MetricDefinitionInner metricDefinitionInner) { return new SqlDatabaseMetricDefinitionImpl(metricDefinitionInner); } }); } @Override public List<SqlDatabase> listDatabases() { List<SqlDatabase> databases = new ArrayList<>(); List<DatabaseInner> databaseInners = this.sqlServerManager.inner().databases() .listByElasticPool(this.resourceGroupName, this.sqlServerName, this.name()); if (databaseInners != null) { for (DatabaseInner inner : databaseInners) { databases.add(new SqlDatabaseImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, inner.name(), inner, this.sqlServerManager)); } } return Collections.unmodifiableList(databases); } @Override public Observable<SqlDatabase> listDatabasesAsync() { final SqlElasticPoolImpl self = this; return this.sqlServerManager.inner().databases() .listByElasticPoolAsync(self.resourceGroupName, self.sqlServerName, this.name()) .flatMap(new Func1<List<DatabaseInner>, Observable<DatabaseInner>>() { @Override public Observable<DatabaseInner> call(List<DatabaseInner> databaseInners) { return Observable.from(databaseInners); } }).map(new Func1<DatabaseInner, SqlDatabase>() { @Override public SqlDatabase call(DatabaseInner databaseInner) { return new SqlDatabaseImpl(self.resourceGroupName, self.sqlServerName, self.sqlServerLocation, databaseInner.name(), databaseInner, self.sqlServerManager); } }); } @Override public SqlDatabase getDatabase(String databaseName) { DatabaseInner databaseInner = this.sqlServerManager.inner().databases() .get(this.resourceGroupName, this.sqlServerName, databaseName); return databaseInner != null ? new SqlDatabaseImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, databaseName, databaseInner, this.sqlServerManager) : null; } @Override public SqlDatabase addNewDatabase(String databaseName) { return this.sqlServerManager.sqlServers().databases() .define(databaseName) .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation) .withExistingElasticPool(this) .create(); } @Override public SqlDatabase addExistingDatabase(String databaseName) { return this.getDatabase(databaseName) .update() .withExistingElasticPool(this) .apply(); } @Override public SqlDatabase addExistingDatabase(SqlDatabase database) { return database .update() .withExistingElasticPool(this) .apply(); } @Override public SqlDatabase removeDatabase(String databaseName) { return this.getDatabase(databaseName) .update() .withoutElasticPool() .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .apply(); } @Override public void delete() { this.sqlServerManager.inner().elasticPools().delete(this.resourceGroupName, this.sqlServerName, this.name()); } @Override public Completable deleteAsync() { return this.deleteResourceAsync().toCompletable(); } @Override protected Observable<ElasticPoolInner> getInnerAsync() { return this.sqlServerManager.inner().elasticPools().getAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @Override public Observable<SqlElasticPool> createResourceAsync() { final SqlElasticPoolImpl self = this; this.inner().withLocation(this.sqlServerLocation); return this.sqlServerManager.inner().elasticPools() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.inner()) .map(new Func1<ElasticPoolInner, SqlElasticPool>() { @Override public SqlElasticPool call(ElasticPoolInner inner) { self.setInner(inner); return self; } }); } @Override public Observable<SqlElasticPool> updateResourceAsync() { final SqlElasticPoolImpl self = this; return this.sqlServerManager.inner().elasticPools() .createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.inner()) .map(new Func1<ElasticPoolInner, SqlElasticPool>() { @Override public SqlElasticPool call(ElasticPoolInner inner) { self.setInner(inner); return self; } }); } void addParentDependency(TaskGroup.HasTaskGroup parentDependency) { this.addDependency(parentDependency); } @Override public void beforeGroupCreateOrUpdate() { } @Override public Completable afterPostRunAsync(boolean isGroupFaulted) { if (this.sqlDatabases != null) { this.sqlDatabases.clear(); } return Completable.complete(); } @Override public Observable<Void> deleteResourceAsync() { return this.sqlServerManager.inner().elasticPools().deleteAsync(this.resourceGroupName, this.sqlServerName, this.name()); } @Override public Update update() { super.prepareUpdate(); return this; } @Override public SqlElasticPoolImpl withExistingSqlServer(String resourceGroupName, String sqlServerName, String location) { this.resourceGroupName = resourceGroupName; this.sqlServerName = sqlServerName; this.sqlServerLocation = location; return this; } @Override public SqlElasticPoolImpl withExistingSqlServer(SqlServer sqlServer) { this.resourceGroupName = sqlServer.resourceGroupName(); this.sqlServerName = sqlServer.name(); this.sqlServerLocation = sqlServer.regionName(); return this; } @Override public SqlElasticPoolImpl withEdition(ElasticPoolEditions edition) { this.inner().withEdition(edition); return this; } @Override public SqlElasticPoolImpl withBasicPool() { this.inner().withEdition(ElasticPoolEditions.BASIC); return this; } @Override public SqlElasticPoolImpl withStandardPool() { this.inner().withEdition(ElasticPoolEditions.STANDARD); return this; } @Override public SqlElasticPoolImpl withPremiumPool() { this.inner().withEdition(ElasticPoolEditions.PREMIUM); return this; } @Override public SqlElasticPoolImpl withReservedDtu(SqlElasticPoolBasicEDTUs eDTU) { this.inner().withDtu(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs eDTU) { this.inner().withDatabaseDtuMax(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs eDTU) { this.inner().withDatabaseDtuMin(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withReservedDtu(SqlElasticPoolStandardEDTUs eDTU) { this.inner().withDtu(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs eDTU) { this.inner().withDatabaseDtuMax(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs eDTU) { this.inner().withDatabaseDtuMin(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withStorageCapacity(SqlElasticPoolStandardStorage storageCapacity) { this.inner().withStorageMB(storageCapacity.capacityInMB()); return this; } @Override public SqlElasticPoolImpl withReservedDtu(SqlElasticPoolPremiumEDTUs eDTU) { this.inner().withDtu(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs eDTU) { this.inner().withDatabaseDtuMax(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs eDTU) { this.inner().withDatabaseDtuMin(eDTU.value()); return this; } @Override public SqlElasticPoolImpl withStorageCapacity(SqlElasticPoolPremiumSorage storageCapacity) { this.inner().withStorageMB(storageCapacity.capacityInMB()); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMin(int databaseDtuMin) { this.inner().withDatabaseDtuMin(databaseDtuMin); return this; } @Override public SqlElasticPoolImpl withDatabaseDtuMax(int databaseDtuMax) { this.inner().withDatabaseDtuMax(databaseDtuMax); return this; } @Override public SqlElasticPoolImpl withDtu(int dtu) { this.inner().withDtu(dtu); return this; } @Override public SqlElasticPoolImpl withStorageCapacity(int storageMB) { this.inner().withStorageMB(storageMB); return this; } @Override public SqlElasticPoolImpl withNewDatabase(String databaseName) { if (this.sqlDatabases == null) { this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases .defineInlineDatabase(databaseName).withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)) .attach(); } @Override public SqlElasticPoolImpl withExistingDatabase(String databaseName) { if (this.sqlDatabases == null) { this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases .patchUpdateDatabase(databaseName).withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)) .attach(); } @Override public SqlElasticPoolImpl withExistingDatabase(SqlDatabase database) { if (this.sqlDatabases == null) { this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases .patchUpdateDatabase(database.name()).withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)) .attach(); } @Override public SqlDatabaseForElasticPoolImpl defineDatabase(String databaseName) { if (this.sqlDatabases == null) { this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase"); } return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases .defineInlineDatabase(databaseName).withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)); } @Override public SqlElasticPoolImpl withTags(Map<String, String> tags) { this.inner().withTags(new HashMap<>(tags)); return this; } @Override public SqlElasticPoolImpl withTag(String key, String value) { if (this.inner().getTags() == null) { this.inner().withTags(new HashMap<String, String>()); } this.inner().getTags().put(key, value); return this; } @Override public SqlElasticPoolImpl withoutTag(String key) { if (this.inner().getTags() != null) { this.inner().getTags().remove(key); } return this; } @Override public SqlServerImpl attach() { return parent(); } }
38.70997
186
0.694061
7fb18f48f5fd7abc978a43834a71c2fa4bd4335e
4,485
package com.bct.gpstracker.pojo; import java.io.Serializable; import android.content.Context; import org.json.JSONArray; import org.json.JSONObject; import com.bct.gpstracker.common.CommonRestPath; import com.bct.gpstracker.inter.BctClientCallback; import com.bct.gpstracker.util.BctClient; import com.bct.gpstracker.util.JsonHttpResponseHelper; import com.bct.gpstracker.vo.Session; /** * 生活助手实体 * * @author huangfei */ public class AlarmEntity implements Serializable { /** * */ private static final long serialVersionUID = -7728007301828306604L; /** * "id":1, * “name":"小新的朗读", * "termId": 3, * "startTime": "0900", * "endTime": "1400", * "weeks": "1,2,0,4,5,0,0", * "imei": "012207000691838", * "fileName": "ls,012207000691838,012207000691838,0001", * "voiceFile":"" * "content":闹钟的内容 * audioSeq :铃声位置 1-10 */ private int id = 0; private int termId = 0; private String time = ""; private String weeks = ""; private String name = ""; private String imei = ""; private String voiceUrl = ""; private String content = ""; //闹钟的内容(新加的字段) private int audioSeq = 0; //铃声位置 1-10 public AlarmEntity() { } ; public AlarmEntity(JSONObject json) { try { if (json.has("id")) id = json.getInt("id"); if (json.has("termId")) termId = json.getInt("termId"); if (json.has("startTime")) time = json.getString("startTime"); if (json.has("weeks")) weeks = json.getString("weeks"); if (json.has("name")) name = json.getString("name"); if (json.has("imei")) imei = json.getString("imei"); if (json.has("voiceUrl")) voiceUrl = json.getString("voiceUrl"); if (json.has("content")) content = json.getString("content"); if (json.has("audioSeq")) audioSeq = json.getInt("audioSeq"); } catch (Exception e) { e.printStackTrace(); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getWeeks() { return weeks; } public void setWeeks(String weeks) { this.weeks = weeks; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTermId() { return termId; } public void setTermId(int termId) { this.termId = termId; } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public int getAudioSeq() { return audioSeq; } public void setAudioSeq(int audioSeq) { this.audioSeq = audioSeq; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getVoiceUrl() { return voiceUrl; } public void setVoiceUrl(String voiceUrl) { this.voiceUrl = voiceUrl; } public static void getList(Context context, final BctClientCallback callback) { try { JSONObject json = new JSONObject(); json.put("imei", Session.getInstance().getSetupDevice().getImei()); BctClient.getInstance().POST(context, CommonRestPath.alarmQuery(),json,new JsonHttpResponseHelper(callback).getHandler()); } catch (Exception ex) { ex.printStackTrace(); } } public static void add(Context context, JSONObject json, final BctClientCallback callback) { try { BctClient.getInstance().POST(context, CommonRestPath.alarmAdd(), json, new JsonHttpResponseHelper(callback).getHandler()); } catch (Exception ex) { ex.printStackTrace(); } } public void delete(Context context, final BctClientCallback callback) { try { JSONArray json = new JSONArray(); json.put(this.getId()); JSONObject data = new JSONObject(); data.put("ids", json); BctClient.getInstance().POST(context, CommonRestPath.alarmDelete(), data, new JsonHttpResponseHelper(callback).getHandler()); } catch (Exception ex) { ex.printStackTrace(); } } }
25.628571
137
0.589075
57aeca5355397f5e74c4f4490bd230c1eb0c321d
997
package js.converter; import js.lang.BugError; /** * Character values converter. * * @author Iulian Rotaru * @version final */ @SuppressWarnings("unchecked") final class CharactersConverter implements Converter { /** Package default constructor. */ CharactersConverter() { } /** * Return the first character from given string. * * @throws ConverterException if given string has more than one single character. */ @Override public <T> T asObject(String string, Class<T> valueType) throws BugError { // at this point value type is guaranteed to be char or Character if (string.length() > 1) { throw new ConverterException("Trying to convert a larger string into a single character."); } return (T) (Character) string.charAt(0); } /** Return a single character string. */ @Override public String asString(Object object) { // at this point object is guaranteed to be instance of Character return object.toString(); } }
26.236842
95
0.689067
6bc47563c6543ccf354940ccf2d4b5bd7665461e
2,679
/* * 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 sample.addressbook.adbclient; import sample.addressbook.stub.AddressBookServiceStub; public class AddressBookADBClient { private static String URL = "http://127.0.0.1:8080/axis2/services/AddressBookService"; public static void main(String[] args) { try { AddressBookServiceStub stub; if (args != null && args.length != 0) { stub = new AddressBookServiceStub(args[0]); } else { stub = new AddressBookServiceStub(URL); } AddressBookServiceStub.AddEntry addEntry = new AddressBookServiceStub.AddEntry(); AddressBookServiceStub.Entry entry = new AddressBookServiceStub.Entry(); entry.setName("Abby Cadabby"); entry.setStreet("Sesame Street"); entry.setCity("Sesame City"); entry.setState("Sesame State"); entry.setPostalCode("11111"); addEntry.setArgs0(entry); stub.addEntry(addEntry); AddressBookServiceStub.FindEntry findEntry = new AddressBookServiceStub.FindEntry(); findEntry.setArgs0("Abby Cadabby"); AddressBookServiceStub.FindEntryResponse response = stub.findEntry(findEntry); AddressBookServiceStub.Entry responseEntry = response.get_return(); System.out.println("Name :" + responseEntry.getName()); System.out.println("Street :" + responseEntry.getStreet()); System.out.println("City :" + responseEntry.getCity()); System.out.println("State :" + responseEntry.getState()); System.out.println("Postal Code :" + responseEntry.getPostalCode()); } catch (Exception ex) { ex.printStackTrace(); } } }
37.208333
96
0.637925
a36ebcde57594f644713a2480148bd3f047c14cc
4,834
package com.kakao.adt.test.worker; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kakao.adt.parallel.AbstractIOIExecutor; import static org.junit.Assert.*; public class ParallelExecutorTest { private static final Logger LOGGER = LoggerFactory.getLogger(ParallelExecutorTest.class); @Test public void ioi_pool_size_1_test() throws Exception{ testAbstractIOIExecutor(1, 10); } @Test public void ioi_pool_size_2_test() throws Exception{ testAbstractIOIExecutor(2, 20); } @Test public void ioi_pool_size_4_test() throws Exception{ testAbstractIOIExecutor(4, 20); } @Test public void ioi_pool_size_8_test() throws Exception{ testAbstractIOIExecutor(8, 20); } public void testAbstractIOIExecutor(int poolSize, int runtimeInSec) throws Exception{ final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(poolSize, poolSize, 10, TimeUnit.MINUTES, new LinkedBlockingQueue<>(10000)); final AbstractIOIExecutor<Long, String> executor = new AbstractIOIExecutor<Long, String>(1000*1000*10, threadPool) { private volatile long assertValue = 1; @Override public String process(Long input) { return Long.toString(input); } @Override public void completeHandler(String output) { long outputLong = Long.parseLong(output); if(outputLong != assertValue){ System.out.printf("Expected: %d, Actual: %d\n", assertValue, outputLong); throw new IllegalStateException("Assertion Fail"); } assertValue ++; outputComplete(); } @Override public int getMaxWorkerCount() { return this.threadPool.getMaximumPoolSize(); } @Override public void onException(Exception e) { LOGGER.error(e.getMessage(), e); assertFalse(true); } }; // INPUT THREAD final AtomicBoolean running = new AtomicBoolean(true); final Thread inputThread = new Thread(()->{ long i = 0L; try { while(running.get()){ i++; while(!executor.input(i)){ Thread.sleep(1); } } } catch (Exception e) { e.printStackTrace(); } }); inputThread.start(); long startTime = System.currentTimeMillis(); long exInputCnt = 0; long exExecuteCnt = 0; long exOutputCnt = 0; for(int i=0; i<runtimeInSec; i++){ Thread.sleep(1000); long deltaTime = System.currentTimeMillis() - startTime; long curInputCnt = executor.getInputCount(); long curExecuteCnt = executor.getExecuteCount(); long curOutputCnt = executor.getOutputCount(); System.out.println(String.format("%d, %d, %d", curInputCnt, curExecuteCnt, curOutputCnt)); System.out.println(String.format( "AVG %d i/msec, %d e/msec %d o/msec", curInputCnt/deltaTime, curExecuteCnt/deltaTime, curOutputCnt/deltaTime)); assertTrue(exInputCnt <= curInputCnt); assertTrue(exExecuteCnt <= curExecuteCnt); assertTrue(exOutputCnt <= curOutputCnt); exInputCnt = curInputCnt; exExecuteCnt = curExecuteCnt; exOutputCnt = curOutputCnt; } running.set(false); inputThread.join(); System.out.println("Input thread is joined."); while(true){ long curInputCnt = executor.getInputCount(); long curExecuteCnt = executor.getExecuteCount(); long curOutputCnt = executor.getOutputCount(); System.out.println(String.format("%d, %d, %d", curInputCnt, curExecuteCnt, curOutputCnt)); if(curInputCnt == curExecuteCnt && curInputCnt == curOutputCnt){ break; } Thread.sleep(1000); } threadPool.shutdown(); } }
33.569444
145
0.544683
aca47c7fd518237232652b6427fc1a6199bfbda5
815
package net; import cc.novoline.utils.Timer; public class alj { private static int b; public static void a(Timer var0) { var0.reset(); } public static double b(Timer var0) { return var0.getLastDelay(); } public static boolean a(Timer var0, double var1) { return var0.delay(var1); } public static boolean a(Timer var0, float var1) { return var0.check(var1); } public static long c(Timer var0) { return var0.getCurrentMS(); } public static long d(Timer var0) { return var0.getLastMS(); } public static void b(int var0) { b = var0; } public static int b() { return b; } public static int c() { int var0 = b(); return 115; } static { if(b() != 0) { b(46); } } }
15.673077
53
0.561963
9419312b7cdeeb1dfd36916cd2531756fab16c26
1,104
package mage.cards.m; import java.util.UUID; import mage.MageInt; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.HasteAbility; import mage.abilities.keyword.VigilanceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; /** * * @author LevelX2 */ public final class MantisRider extends CardImpl { public MantisRider(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{U}{R}{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.MONK); this.power = new MageInt(3); this.toughness = new MageInt(3); // Flying this.addAbility(FlyingAbility.getInstance()); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // Haste this.addAbility(HasteAbility.getInstance()); } public MantisRider(final MantisRider card) { super(card); } @Override public MantisRider copy() { return new MantisRider(this); } }
24.533333
77
0.682065
67a654f5f85e42fe216041d8a91b2da3bb0fa249
5,124
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.services.taskassigning.planning.util; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Test; import org.kie.server.api.model.taskassigning.OrganizationalEntity; import org.kie.server.api.model.taskassigning.TaskData; import org.kie.server.api.model.taskassigning.UserType; import org.kie.server.services.taskassigning.core.model.Group; import org.kie.server.services.taskassigning.core.model.Task; import org.kie.server.services.taskassigning.core.model.User; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.kie.server.services.taskassigning.core.model.DefaultLabels.AFFINITIES; import static org.kie.server.services.taskassigning.core.model.DefaultLabels.SKILLS; public class TaskUtilTest { private static final String SKILLS_ATTRIBUTE = "skills"; private static final String AFFINITIES_ATTRIBUTE = "affinities"; private static final long TASK_ID = 0L; private static final long PROCESS_INSTANCE_ID = 1L; private static final String PROCESS_ID = "PROCESS_ID"; private static final String CONTAINER_ID = "CONTAINER_ID"; private static final String NAME = "NAME"; private static final int PRIORITY = 2; private static final String STATUS = "Ready"; private static final Map<String, Object> INPUT_DATA = new HashMap<>(); private static final OrganizationalEntity OE_1 = OrganizationalEntity.builder().type(UserType.USER).name("OE1").build(); private static final OrganizationalEntity OE_2 = OrganizationalEntity.builder().type(UserType.GROUP).name("OE2").build(); private static final String SKILL1 = "skill1"; private static final String SKILL2 = "skill2"; private static final String SKILL3 = "skill3"; private static final String AFFINITY1 = "affinity1"; private static final String AFFINITY2 = "affinity2"; @Test public void fromTaskData() { fromTaskData(INPUT_DATA, Collections.emptySet(), Collections.emptySet()); } @Test public void fromTaskDataWithSkillsAndAffinities() { Map<String, Object> inputData = new HashMap<>(); inputData.put(SKILLS_ATTRIBUTE, String.format("%s, %s,%s", SKILL2, SKILL1, SKILL3)); inputData.put(AFFINITIES_ATTRIBUTE, String.format(" %s, %s", AFFINITY2, AFFINITY1)); fromTaskData(inputData, new HashSet<>(Arrays.asList(SKILL3, SKILL2, SKILL1)), new HashSet<>(Arrays.asList(AFFINITY1, AFFINITY2))); } private void fromTaskData(Map<String, Object> inputData, Set<Object> expectedSkills, Set<Object> expectedAffinities) { Set<OrganizationalEntity> potentialOwners = new HashSet<>(); potentialOwners.add(OE_1); potentialOwners.add(OE_2); TaskData taskData = TaskData.builder() .taskId(TASK_ID) .processInstanceId(PROCESS_INSTANCE_ID) .processId(PROCESS_ID) .containerId(CONTAINER_ID) .name(NAME) .priority(PRIORITY) .status(STATUS) .inputData(inputData) .potentialOwners(potentialOwners) .build(); Task task = TaskUtil.fromTaskData(taskData); assertEquals(TASK_ID, task.getId(), 0); assertEquals(PROCESS_INSTANCE_ID, task.getProcessInstanceId(), 0); assertEquals(PROCESS_ID, task.getProcessId()); assertEquals(CONTAINER_ID, task.getContainerId()); assertEquals(NAME, task.getName()); assertEquals(PRIORITY, task.getPriority(), 0); assertEquals(STATUS, task.getStatus()); assertEquals(inputData, task.getInputData()); assertEquals(potentialOwners.size(), task.getPotentialOwners().size(), 2); User user = task.getPotentialOwners().stream() .filter(u -> OE_1.getName().equals(u.getEntityId()) && u.isUser()) .map(u -> (User) u) .findFirst().orElse(null); assertNotNull(user); Group group = task.getPotentialOwners().stream() .filter(g -> OE_2.getName().equals(g.getEntityId()) && !g.isUser()) .map(g -> (Group) g) .findFirst().orElse(null); assertNotNull(group); assertEquals(expectedSkills, task.getLabelValues(SKILLS.name())); assertEquals(expectedAffinities, task.getLabelValues(AFFINITIES.name())); } }
45.345133
138
0.695355
6d693fce3a1b694deebb95061869cf3d898edc09
192
package com.palscash.wallet.database.common.exception; @SuppressWarnings("serial") public class WalletException extends Exception { public WalletException(String msg) { super(msg); } }
17.454545
54
0.776042
9e1909e0566e07667c9987345c6696f572d7f968
5,744
/* * BSD 2-Clause License * * Copyright (c) 2020,2022, Vladimír Ulman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.mpicbg.ulman.fusion.ng.extract; import net.imglib2.IterableInterval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.IntegerType; import net.imglib2.Cursor; import java.util.HashMap; import org.scijava.log.Logger; /** * Detects labels in input images (of voxel type IT -- Input Type) that match given marker, * which is to be found in the marker image (of voxel type LT -- Label Type); and extracts * the input markers into some (possibly) other image (of voxel type ET -- Extract_as Type). * * @param <IT> voxel type of input images (with labels to be fused together) * @param <LT> voxel type of the marker/label image (on which the labels are synchronized) * @param <ET> voxel type of the output image (into which the input labels are extracted) */ public interface LabelExtractor<IT extends RealType<IT>, LT extends IntegerType<LT>, ET extends RealType<ET>> { /** * Just returns the value of the matching label. Typically this could be the label * that overlaps the 'inMarker' the most (compared to other overlapping markers). * * @param inII Sweeper of the input image (from which label is to be returned) * @param markerII Sweeper of the input marker image * @param markerValue Marker (from the input marker image) in question... */ float findMatchingLabel(final IterableInterval<IT> inII, final IterableInterval<LT> markerII, final int markerValue); /** * Just returns the all matching labels together with their overlap ratios. * * The default implementation works as follows: * Sweeps over 'markerValue' labelled voxels inside the marker image * 'markerII', checks labels found in the corresponding voxels in the * input image 'inII', and returns all labels that overlap in at least * one voxel. The function returns -1 if no such label is found. * * @param inII Sweeper of the input image (from which label is to be returned) * @param markerII Sweeper of the input marker image * @param markerValue Marker (from the input marker image) in question... */ static <IT extends RealType<IT>, LT extends IntegerType<LT>> HashMap<Float,Float> findAllMatchingLabels(final IterableInterval<IT> inII, final IterableInterval<LT> markerII, final int markerValue) { //keep frequencies of labels discovered across the marker volume final HashMap<Float,Float> labelCounter = new HashMap<>(); final Cursor<IT> inCursor = inII.cursor(); final Cursor<LT> markerCursor = markerII.cursor(); int markerSize = 0; //find relevant label(s), if any while (markerCursor.hasNext()) { //advance both cursors in synchrony inCursor.next(); if (markerCursor.next().getInteger() == markerValue) { //we are over the original marker in the marker image, ++markerSize; //check what value is in the input image //and update the counter of found values final float inVal = inCursor.get().getRealFloat(); labelCounter.put(inVal, labelCounter.getOrDefault(inVal,0.f)+1); } } //now, compute the ratios //(except for the background..., NB: remove() does not comlain if key does not exist) labelCounter.remove(0.f); for (float lbl : labelCounter.keySet()) labelCounter.put(lbl, labelCounter.get(lbl)/(float)markerSize); return labelCounter; } /** * Just finds pixels of 'wantedLabel' value and sets the corresponding pixels * to 'saveAsLabel' value in the output image. */ void isolateGivenLabel(final RandomAccessibleInterval<IT> sourceRAI, final float wantedLabel, final RandomAccessibleInterval<ET> outputRAI, final ET saveAsLabel); /** * Just finds pixels of 'wantedLabel' value and increases the value of the * corresponding pixels with 'addThisLabel' value in the output image. */ void addGivenLabel(final RandomAccessibleInterval<IT> sourceRAI, final float wantedLabel, final RandomAccessibleInterval<ET> outputRAI, final ET addThisLabel); // ---------------- logging ---------------- void useNowThisLog(final Logger log); }
43.18797
109
0.705084
14ed5de16363dac2794d5815ad48d7a1c244fb87
3,447
package com.xmobileapp.cammonitor.core; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; /** * A CameraSource implementation that obtains its bitmaps via an HTTP request * to a URL. * * @author Tom Gibara * */ public class HttpCamera implements CameraSource { private static final int CONNECT_TIMEOUT = 1000; private static final int SOCKET_TIMEOUT = 1000; private final String url; private final Rect bounds; private final boolean preserveAspectRatio; private final Paint paint = new Paint(); public HttpCamera(String url, int width, int height, boolean preserveAspectRatio) { this.url = url; bounds = new Rect(0, 0, width, height); this.preserveAspectRatio = preserveAspectRatio; paint.setFilterBitmap(true); paint.setAntiAlias(true); } public int getWidth() { return bounds.right; } public int getHeight() { return bounds.bottom; } public boolean open() { /* nothing to do */ return true; } public boolean capture(Canvas canvas) { if (canvas == null) throw new IllegalArgumentException("null canvas"); try { Bitmap bitmap = null; InputStream in = null; int response = -1; try { //we use URLConnection because it's anticipated that it is lighter-weight than HttpClient //NOTE: At this time, neither properly support connect timeouts //as a consequence, this implementation will hang on a failure to connect URL url = new URL(this.url); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection."); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setConnectTimeout(CONNECT_TIMEOUT); httpConn.setReadTimeout(SOCKET_TIMEOUT); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); bitmap = BitmapFactory.decodeStream(in); } } finally { if (in != null) try { in.close(); } catch (IOException e) { /* ignore */ } } if (bitmap == null) throw new IOException("Response Code: " + response); //render it to canvas, scaling if necessary if ( bounds.right == bitmap.getWidth() && bounds.bottom == bitmap.getHeight()) { canvas.drawBitmap(bitmap, 0, 0, null); } else { Rect dest; if (preserveAspectRatio) { dest = new Rect(bounds); dest.bottom = bitmap.getHeight() * bounds.right / bitmap.getWidth(); dest.offset(0, (bounds.bottom - dest.bottom)/2); } else { dest = bounds; } canvas.drawBitmap(bitmap, null, dest, paint); } } catch (RuntimeException e) { Log.i(LOG_TAG, "Failed to obtain image over network", e); return false; } catch (IOException e) { Log.i(LOG_TAG, "Failed to obtain image over network", e); return false; } return true; } public void close() { /* nothing to do */ } public boolean saveImage(String savePath, String fileName) { // TODO Auto-generated method stub return false; } }
26.72093
95
0.696258
8357ada197bfae466d145717d133b6f7cc223943
1,144
package com.evangel.redis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; @Repository("redisDataSource") public class RedisDataSourceImpl implements RedisDataSource { private static final Logger log = LoggerFactory .getLogger(RedisDataSourceImpl.class); @Autowired private ShardedJedisPool shardedJedisPool; // 取得redis的客户端,可以执行命令了 public ShardedJedis getRedisClient() { try { ShardedJedis shardJedis = shardedJedisPool.getResource(); return shardJedis; } catch (Exception e) { log.error("getRedisClent error", e); } return null; } // 将资源返还给pool public void returnResource(ShardedJedis shardedJedis) { shardedJedisPool.returnResource(shardedJedis); } // 出现异常后,将资源返还给pool (其实不需要第二个方法) public void returnResource(ShardedJedis shardedJedis, boolean broken) { if (broken) { shardedJedisPool.returnBrokenResource(shardedJedis); } else { shardedJedisPool.returnResource(shardedJedis); } } }
27.238095
72
0.787587
408c337405034316abf7b5b58c8eee25454af589
4,426
package de.geeksfactory.opacclient.apis; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.Collection; import java.util.List; import de.geeksfactory.opacclient.networking.NotReachableException; import de.geeksfactory.opacclient.objects.Copy; import de.geeksfactory.opacclient.objects.DetailedItem; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(Parameterized.class) public class BibliothecaSearchTest extends BaseHtmlTest { private String file; public BibliothecaSearchTest(String file) { this.file = file; } private static final String[] FILES = new String[]{"mannheim.html"}; @Parameterized.Parameters(name = "{0}") public static Collection<String[]> files() { List<String[]> files = new ArrayList<>(); for (String file : FILES) { files.add(new String[]{file}); } return files; } @Test public void testParseSearch() throws OpacApi.OpacErrorException, JSONException, NotReachableException { String html = readResource("/bibliotheca/resultlist/" + file); if (html == null) return; // we may not have all files for all libraries int page = 1; SearchRequestResult result = Bibliotheca.parseSearch(html, page, getData(file)); assertTrue(result.getPage_count() > 0 || result.getTotal_result_count() > 0); assertTrue(result.getPage_index() == page); for (SearchResult item : result.getResults()) { assertNotNull(item.getId()); assertNotNull(item.getType()); } SearchResult firstItem = result.getResults().get(0); assertEquals(firstItem.getInnerhtml(), getFirstResultHtml(file)); } @Test public void testParseResult() throws OpacApi.OpacErrorException, JSONException, NotReachableException { String html = readResource("/bibliotheca/result_detail/" + file); if (html == null) return; // we may not have all files for all libraries DetailedItem result = Bibliotheca.parseResult(html, getData(file)); for (Copy copy : result.getCopies()) { assertContainsData(copy.getStatus()); assertNullOrNotEmpty(copy.getBarcode()); assertNullOrNotEmpty(copy.getBranch()); assertNullOrNotEmpty(copy.getDepartment()); assertNullOrNotEmpty(copy.getLocation()); assertNullOrNotEmpty(copy.getReservations()); assertNullOrNotEmpty(copy.getShelfmark()); assertNullOrNotEmpty(copy.getUrl()); if (copy.getStatus().equals("Entliehen")) assertNotNull(copy.getReturnDate()); } assertContainsData(result.getReservation_info()); assertEquals(result.getTitle(), getDetailTitle(file)); } private JSONObject getData(String file) throws JSONException { JSONObject json = new JSONObject(); JSONObject copiestable = new JSONObject(); switch (file) { case "mannheim.html": copiestable.put("barcode", 0); copiestable.put("branch", 1); copiestable.put("department", 2); copiestable.put("location", 3); copiestable.put("reservations", 6); copiestable.put("returndate", 5); copiestable.put("status", 4); break; } json.put("copiestable", copiestable); return json; } private String getFirstResultHtml(String file) { switch (file) { case "mannheim.html": return "Anelli, Melissa:<br>Das Phänomen <b><b>Harry</b></b> <b><b>Potter</b></b>" + " : alles über einen jungen Zauberer, seine Fans und eine magische " + "Erfolgsgeschichte / Melissa Anelli - 2009"; } return null; } private String getDetailTitle(String file) { switch (file) { case "mannheim.html": return "Harry Potter und der Stein der Weisen"; } return null; } }
37.508475
100
0.639629
0122af5d479b407f1f2b04dc53f2de8db872854d
1,294
/* * Derived from Example/Tutorial Play-Rest-Security * (https://github.com/jamesward/play-rest-security) * by James Ward */ package controllers.security; import models.User; import play.mvc.Http; import play.mvc.Http.Context; import play.mvc.Result; import play.mvc.Security; import views.html.index; import views.html.components.login; public class Secured extends Security.Authenticator { @Override public String getUsername(Context ctx) { Http.Cookie authTokenHeaderValues = ctx.request().cookies().get(SecurityController.AUTH_TOKEN); if ((authTokenHeaderValues != null)) { //Finds User in DB with authToken same as contained in cookie User user = User.findByAuthToken(authTokenHeaderValues.value()); //If no User exists i.e. authToken is null or no user with same authToken //returns null. If User isn't null i.e. authToken matches a Users auth_token in DB, //returns the User's email_address. if (user != null) { ctx.args.put("user", user); return user.getEmailAddress(); } } return null; } @Override public Result onUnauthorized(Context ctx) { return unauthorized(index.render(login.render())); } }
29.409091
103
0.659969
3d75ba893dcd4c68e1bb458bb7d148bd3ff9fa8c
359
package com.cqx.uboost; import org.springframework.context.annotation.Configuration; /** * @desc: * @version: 1.0.0 * @author: cqx * @Date: 2019/9/8 */ @Configuration //@ConditionalOnClass(Feign.class) //@EnableConfigurationProperties({ FeignClientProperties.class, // FeignHttpClientProperties.class }) public class UBoostAutoConfiguration { }
21.117647
63
0.740947
b3d494c971ad6eab4e40d5cdcd8f8efbbde7cb2c
1,621
package myapp.lenovo.viewpager.dialog; import android.app.Dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import myapp.lenovo.viewpager.R; /** * Created by Lenovo on 2016/11/13. */ public class MyDialogRecognize extends Dialog{ private TextView dialogTitle; private TextView dialogLine; private TextView dialogExit; private Button dialogEdit; private EditText dialogContent; private LayoutInflater inflater; public MyDialogRecognize(Context context,String content){ super(context, R.style.MyDialog); inflater=LayoutInflater.from(getContext()); View view=inflater.inflate(R.layout.recognize_dialog,null); dialogTitle=(TextView) view.findViewById(R.id.title_tv); dialogExit=(TextView) view.findViewById(R.id.exit_tv); dialogLine=(TextView) view.findViewById(R.id.line_tv); dialogContent=(EditText) view.findViewById(R.id.word_et); dialogEdit= (Button) view.findViewById(R.id.edit_btn); dialogContent.setText(content); super.setContentView(view); } public EditText getDialogContent() { return dialogContent; } public Button getDialogEdit() { return dialogEdit; } public void setOnClickExitListener(View.OnClickListener listener){ dialogExit.setOnClickListener(listener); } public void setOnClickEditListener(View.OnClickListener listener){ dialogEdit.setOnClickListener(listener); } }
27.948276
70
0.726712
c2762dcdf8dd9128909801462ee5eec427b6e1d2
870
package com.github.privacystreams.commons.time; import com.github.privacystreams.commons.ItemFunction; import com.github.privacystreams.core.Item; import com.github.privacystreams.core.UQI; import com.github.privacystreams.utils.Assertions; /** * Created by yuanchun on 28/12/2016. * Process the location field in an item. */ abstract class TimeProcessor<Tout> extends ItemFunction<Tout> { private final String timestampField; TimeProcessor(String timestampField) { this.timestampField = Assertions.notNull("timestampField", timestampField); this.addParameters(timestampField); } @Override public final Tout apply(UQI uqi, Item input) { long timestamp = input.getValueByField(this.timestampField); return this.processTimestamp(timestamp); } protected abstract Tout processTimestamp(long timestamp); }
30
83
0.752874
c4d8917c3143aed4a7266345ecdd8f724662a256
754
package org.observertc.observer.sources; import jakarta.inject.Inject; import jakarta.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Singleton public class SampleSources { private static final Logger logger = LoggerFactory.getLogger(SampleSources.class); @Inject SamplesWebsocketController websocketController; @Inject SamplesRestApiController restApiController; @PostConstruct void init() { logger.info("Initialized, supported schema versions \n{}", String.join("\n", SamplesVersionVisitor.getSupportedVersions())); } @PreDestroy void teardown() { logger.info("Deinitialized"); } }
24.322581
132
0.748011
bbaf2744d96dc6ad00a9222d50c7839450081c9c
1,297
package goplaces.models; /** * This object is used as an exchange message between SelectWaypointsResource the background task boxrouteworker. */ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) // This is to include only the fields we want in the generated JSON public class CustomizeRouteQuery { private String[] keywords; private int radius; private String routeID; public CustomizeRouteQuery(String routeID, String[] keywords, int radius) { this.setKeywords(keywords); this.setRouteID(routeID); this.setRadius(radius); } public CustomizeRouteQuery() { } @XmlElement public int getRadius() { return radius; } @XmlElement public void setRadius(int radius) { this.radius = radius; } @XmlElement public String[] getKeywords() { return keywords; } public void setKeywords(String[] keywords) { this.keywords = new String[keywords.length]; int i = 0; for(String keyword : keywords) this.keywords[i++] = keyword; } @XmlElement public String getRouteID() { return routeID; } public void setRouteID(String routeID) { this.routeID = routeID; } }
21.616667
113
0.748651
78bce8479507d76ed9402f42a83c9b0bc4d90481
2,114
package com.xiaoliu.learn.client; import com.xiaoliu.learn.entity.User; import com.xiaoliu.learn.service.UserServiceApi; import feign.hystrix.FallbackFactory; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @description: 提供者服务A客户端 * @author: liufb * @create: 2020/7/31 12:17 **/ @FeignClient(name = "provider-service-a", fallbackFactory = ProviderAClient.ProviderAClientFallbackFactory.class) public interface ProviderAClient extends UserServiceApi { @Component class ProviderAClientFallbackFactory implements FallbackFactory<ProviderAClient> { private static ProviderAClient fallback = new ProviderAClient() { @Override public User getById(Long id) { System.out.println("getById()方法的降级机制"); return createDefaultUser(); } @Override public void save(User user) { System.out.println("save()方法的降级机制"); } @Override public void update(User user) { System.out.println("update()方法的降级机制"); } @Override public void deleteById(Long id) { System.out.println("deleteById()方法的降级机制"); } @Override public List<User> getByIds(List<Long> ids) { System.out.println("getByIds()方法的降级机制"); List<User> users = new ArrayList<>(1); users.add(createDefaultUser()); return users; } }; private static User createDefaultUser() { User user = new User(); user.setId(0L); user.setUsername("默认用户"); user.setPassword("123456"); user.setSex(0); user.setCreateTime(new Date()); return user; } @Override public ProviderAClient create(Throwable cause) { // 这里可以根据异常类型选择不同的降级策略 return fallback; } } }
29.774648
113
0.59035
933c17324240c0e62a5407f062d53c38387ef34e
887
// Java implementation of simple // algorithm to find smaller // element on left side import java.io.*; class GFG { // Prints smaller elements on // left side of every element static void printPrevSmaller( int []arr, int n) { // Always print empty or '_' // for first element System.out.print( "_, " ); // Start from second element for ( int i = 1 ; i < n; i++) { // look for smaller // element on left of 'i' int j; for (j = i - 1 ; j >= 0 ; j--) { if (arr[j] < arr[i]) { System.out.print(arr[j] + ", " ); break ; } } // If there is no smaller // element on left of 'i' if (j == - 1 ) System.out.print( "_, " ) ; } } // Driver Code public static void main (String[] args) { int []arr = { 1 , 3 , 0 , 2 , 5 }; int n = arr.length; printPrevSmaller(arr, n); } } // This code is contributed by anuj_67.
7.270492
40
0.553551
98f3c66fc35cfcee6c96ff3f2cf29bd892e62093
3,090
package com.huanmedia.videochat.common.service.socket; import android.util.Log; import com.google.gson.Gson; import com.huanmedia.ilibray.utils.GsonUtils; import com.orhanobut.logger.Logger; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; import java.nio.channels.NotYetConnectedException; import java.util.Map; /** * Create by Administrator * time: 2017/11/28. * Email:eric.yang@huanmedia.com * version: ${VERSION} */ public class WSocketClent extends WebSocketClient { private WSocketLisenter mWSocketLisenter; private Gson mGson = GsonUtils.getDefGsonBulder().create(); public WSocketClent(URI serverUri) { this(serverUri, null); } public WSocketClent(URI serverUri, Draft protocolDraft) { this(serverUri, protocolDraft, null, 10); } public WSocketClent(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders, int connectTimeout) { super(serverUri, protocolDraft, httpHeaders, connectTimeout); } public void send(WMessage message) throws NotYetConnectedException { send(mGson.toJson(message)); } @Override public void send(String text) throws NotYetConnectedException { super.send(text); Logger.i("WSocketClent:\n%s:%s", "send", text); } @Override public void onOpen(ServerHandshake handshakedata) { Logger.i("WSocketClent:\n%s:%s", "onOpen:", handshakedata.toString()); if (mWSocketLisenter != null) { mWSocketLisenter.onOpen(handshakedata); } } @Override public void onMessage(String message) { Logger.i("WSocketClent:\n%s:%s", "onMessage", message); WMessage oMsg = mGson.fromJson(message, WMessage.class); if (oMsg.getType().equals("ping")) { send("{\"type\":\"pong\"}"); } else { if (mWSocketLisenter != null) { mWSocketLisenter.onMessage(oMsg); } } } @Override public void onClose(int code, String reason, boolean remote) { Logger.i("WSocketClent:\n%s:%d", "onClose", code); if (mWSocketLisenter != null) { mWSocketLisenter.onClose(code, reason, remote); } } @Override public void onError(Exception ex) { Logger.i("WSocketClent:\n%s", Log.getStackTraceString(ex)); if (mWSocketLisenter != null) { mWSocketLisenter.onError(ex); } } public void setWSocketLisenter(WSocketLisenter WSocketLisenter) { mWSocketLisenter = WSocketLisenter; } public static interface WSocketLisenter { public void onOpen(ServerHandshake handshakedata); /** * UI线程调用 * * @param message */ public void onMessage(WMessage message); public void onClose(int code, String reason, boolean remote); /** * UI线程调用 * * @param ex */ public void onError(Exception ex); } }
27.837838
114
0.6411
b5fc9b174cbb19973fd28e221e01c6ec32edf54d
4,367
/* * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others. * * 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. * * Contributors: * Sun Seng David TAN * Florent Guillaume */ package org.nuxeo.functionaltests.pages; import org.nuxeo.functionaltests.Required; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; /** * Nuxeo default login page. */ public class LoginPage extends AbstractPage { public static final String FEEDBACK_MESSAGE_DIV_XPATH = "//div[contains(@class,'feedbackMessage')]"; public static final String LOGIN_DIV_XPATH = "//div[@class='login']"; @Required @FindBy(id = "username") WebElement usernameInputTextBox; @Required @FindBy(id = "password") WebElement passwordInputTextBox; @Required @FindBy(name = "Submit") WebElement submitButton; public LoginPage(WebDriver driver) { super(driver); } /** * Fills in the login form with the username, password and language. * * @param username the username * @param password the password * @param language value of one of the options in the language select box. For example, English (United States) * @deprecated since 9.1 not used anymore, use {@link #login(String, String)} insted. */ @Deprecated public void login(String username, String password, String language) { login(username, password); } /** * Fills in the login form with the username and password. Uses the default language. * * @param username the username * @param password the password */ public void login(String username, String password) { JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; usernameInputTextBox.sendKeys(username); passwordInputTextBox.sendKeys(password); jsExecutor.executeScript("document.getElementById('username').blur();return true;"); jsExecutor.executeScript("document.getElementById('password').blur();return true;"); submitButton.click(); } /** * Logs in and returns the next page. * * @param username the username * @param password the password * @param pageClassToProxy the next page's class * @return the next page */ public <T> T login(String username, String password, Class<T> pageClassToProxy) { try { login(username, password); return asPage(pageClassToProxy); } catch (NoSuchElementException | TimeoutException exc) { try { // Try once again because of problem described in NXP-12835. // find the real cause of NXP-12835 and remove second login // attempt if (hasElement(By.xpath(LOGIN_DIV_XPATH))) { login(username, password); return asPage(pageClassToProxy); } else { throw exc; } } catch (NoSuchElementException e) { if (hasElement(By.xpath(LOGIN_DIV_XPATH))) { // Means we are still on login page. if (hasElement(By.xpath(FEEDBACK_MESSAGE_DIV_XPATH))) { throw new NoSuchElementException("Login failed. Application said : " + driver.findElement(By.xpath(FEEDBACK_MESSAGE_DIV_XPATH)).getText(), e); } else { throw new NoSuchElementException("Login failed", e); } } else { throw e; } } } } }
35.217742
115
0.634532
d03b00bcfc85a9821b983f5dea75a47604c399d2
4,040
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.glwallpaper; import static android.opengl.GLES20.GL_FRAGMENT_SHADER; import static android.opengl.GLES20.GL_VERTEX_SHADER; import static android.opengl.GLES20.glAttachShader; import static android.opengl.GLES20.glCompileShader; import static android.opengl.GLES20.glCreateProgram; import static android.opengl.GLES20.glCreateShader; import static android.opengl.GLES20.glGetAttribLocation; import static android.opengl.GLES20.glGetUniformLocation; import static android.opengl.GLES20.glLinkProgram; import static android.opengl.GLES20.glShaderSource; import static android.opengl.GLES20.glUseProgram; import android.content.Context; import android.content.res.Resources; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * This class takes charge of linking shader codes and then return a handle for OpenGL ES program. */ class ImageGLProgram { private static final String TAG = ImageGLProgram.class.getSimpleName(); private Context mContext; private int mProgramHandle; ImageGLProgram(Context context) { mContext = context.getApplicationContext(); } private int loadShaderProgram(int vertexId, int fragmentId) { final String vertexSrc = getShaderResource(vertexId); final String fragmentSrc = getShaderResource(fragmentId); final int vertexHandle = getShaderHandle(GL_VERTEX_SHADER, vertexSrc); final int fragmentHandle = getShaderHandle(GL_FRAGMENT_SHADER, fragmentSrc); return getProgramHandle(vertexHandle, fragmentHandle); } private String getShaderResource(int shaderId) { Resources res = mContext.getResources(); StringBuilder code = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(res.openRawResource(shaderId)))) { String nextLine; while ((nextLine = reader.readLine()) != null) { code.append(nextLine).append("\n"); } } catch (IOException | Resources.NotFoundException ex) { Log.d(TAG, "Can not read the shader source", ex); code = null; } return code == null ? "" : code.toString(); } private int getShaderHandle(int type, String src) { final int shader = glCreateShader(type); if (shader == 0) { Log.d(TAG, "Create shader failed, type=" + type); return 0; } glShaderSource(shader, src); glCompileShader(shader); return shader; } private int getProgramHandle(int vertexHandle, int fragmentHandle) { final int program = glCreateProgram(); if (program == 0) { Log.d(TAG, "Can not create OpenGL ES program"); return 0; } glAttachShader(program, vertexHandle); glAttachShader(program, fragmentHandle); glLinkProgram(program); return program; } boolean useGLProgram(int vertexResId, int fragmentResId) { mProgramHandle = loadShaderProgram(vertexResId, fragmentResId); glUseProgram(mProgramHandle); return true; } int getAttributeHandle(String name) { return glGetAttribLocation(mProgramHandle, name); } int getUniformHandle(String name) { return glGetUniformLocation(mProgramHandle, name); } }
34.827586
98
0.699257
c3a6418e93c2215dcd7bebd67c74bbd09498e049
13,380
package org.cowjumping.guiUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.cowjumping.FitsUtils.ImageContainer; import org.cowjumping.FitsUtils.odiCentroidSupport; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.geom.Point2D; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.WritableRaster; import java.util.Vector; /** * A component that is designed to draw guide star video data, with an overlay * of a mean central position and a current position. * * Data are internally stored in an unsigned short BufferedImage. New video * images are accepted as either short[] or float[] arrays. Other data types can * easily be added. * * The class can also mark other data points in the video. * * @author Daniel Harbeck * */ @SuppressWarnings("serial") public class GuideStarDisplayComponent extends org.cowjumping.guiUtils.CooSysComponent implements MouseMotionListener, zScaleListener { private final static Logger myLogger = LogManager.getLogger(); public ImageContainer gs = null; /** Internal buffer for the raw image */ public BufferedImage RawImage = null; /** Internal image for a z-scaled (i.e., luminosity cut applied) image */ protected BufferedImage zScaledImage = null; /** Container for <x,y> location of object markers */ Vector<Point2D.Float> markers = null; /** Size of the image in X dimension */ protected int imageX = 0; /** Size of the image in Y dimension */ protected int imageY = 0; // public GuideStarContainer gs = null; /** Image rescaling parameter: scaling of the image */ float zscale = 1; // data scaling parameters float zoffset = 0; float z1 = 0; float z2 = 1; /** Data value used for auto set bias */ float zExtraOffset = 0; public void setMyZscaleSelector(ZScaleSelectorComponent myZscaleSelector) { this.myZscaleSelector = myZscaleSelector; } ZScaleSelectorComponent myZscaleSelector = null; /** marker for the current location of the guide star */ protected Point2D currentCenter = new Point2D.Float(); Point2D centerOnScreen = new Point2D.Float(); /** marker for the mean (or intial) position of the guide star */ protected Point2D meanCenter = new Point2D.Float(); private float fwhm = 0; float flux = 0; static final int SHORTMAX = Short.MAX_VALUE - 1; /** Image Operator to do z-scaling of the image */ private zScaleTransformOp myZScaleOp = null; /** * Image Operator to expand/shrink the guide star image onto the component's * area */ private AffineTransformOp myMagnification = null; // magnifying the image /** Color of the current position marker */ public final static Color MarkerColor_Good = Color.green; public final static Color MarkerColor_Bad = Color.orange; private BufferedImage lookupImage; public double DonutRadius = 0; public GuideStarDisplayComponent() { this(150, 150, 0, SHORTMAX); } public GuideStarDisplayComponent(int displaySizeX, int displaySizeY, int z1, int z2) { this.drawsCooSys = false; setZScale(z1, z2); this.setBorders(5, 5, 5, 5); this.updateSize(displaySizeX, displaySizeY); this.updateRange(0, 10, 0, 10); this.initForSize(); addMouseMotionListener(this); } /** * Check if a requested image size is compatible with the currently * allocated buffers. If it is not, reallocate the internal buffers. * * @param imageX * requested Image width. * @param imageY * requested Image height. */ protected void updateImageSize(int imageX, int imageY) { boolean update = (RawImage == null || imageX != this.imageX || imageY != this.imageY); this.imageX = imageX; this.imageY = imageY; minX = 0; minY = 0; maxX = imageX; maxY = imageY; if (update) initForSize(); } /** * Initialize the component to display images of a new size. * * This is always called if either the screen size or the iamge size is * changed * */ public void initForSize() { // this will take care of internal buffers and the AffineTransformation // classes used. super.initForSize(); // Here we have to take special precautions since we have an image // buffer and an image manipulation chain set up. All that information // needs to be updated if we change any size. if (imageX > 0 && imageY > 0) { // Allocating buffers makes only sense if the image size is >0. It // can be ==0 if there wasn't a proper initialisation yet if (RawImage != null) { RawImage = null; } RawImage = new BufferedImage(imageX, imageY, BufferedImage.TYPE_USHORT_GRAY); // Recalculate the image magnification operators if (forwardTransform != null && myZScaleOp != null) { // the magnification is based on the affine transform we use myMagnification = null; myMagnification = new AffineTransformOp(forwardTransform, AffineTransformOp.TYPE_BILINEAR); zScaledImage = null; zScaledImage = myZScaleOp.createCompatibleDestImage(RawImage, RawImage.getColorModel()); } else myMagnification = null; } } public void updateObjectCenter(float centerX, float centerY, float fwhm) { currentCenter.setLocation(centerX, centerY); this.setFwhm(fwhm); } public void setMeanCenter(float x, float y) { this.meanCenter.setLocation(x, y); } public void clear() { clearMarkers(); this.updateObjectCenter(0, 0, 0); this.RawImage = null; this.invokeRepaint(); } /** * Add a marker to the image The guide star display has the capability to * draw markers on, e.g., objects. * */ public void addMarker(float f, float g) { if (markers == null) markers = new Vector<Point2D.Float>(); markers.add(new Point2D.Float(f, g)); } /** * Clear all markers in the Image * */ public void clearMarkers() { if (this.markers != null) this.markers.clear(); this.markers = null; } /** * Override the inherited background image The super class would draw a * coordinate system. Here we draw the image of the guide star. * */ protected void drawBackGround(Graphics2D g2) { clearBackground(g2); if (RawImage == null || forwardTransform == null) { // there is no image loaded yet,or we are not properly initialized g2.setColor(Color.black); g2.fillRect(0, 0, drawX, drawY); g2.setColor(Color.red); g2.drawLine(0, 0, drawX, drawY); g2.drawLine(drawX, 0, 0, drawY); return; } myZScaleOp.filter(RawImage, zScaledImage); // do magnification & draw g2.drawImage(zScaledImage, myMagnification, 0, 0); // g2.drawImage (zScaledImage, null, 0, 0); } /** * Draw additional meta-information on top of the image * */ public void drawData(Graphics2D g) { if (forwardTransform == null) return; g.setColor(this.MarkerColor_Good); g.setColor(this.MarkerColor_Good); // draw the current center if (currentCenter.getX() > 0 && currentCenter.getY() > 0) { centerOnScreen = forwardTransform.transform(currentCenter, null); float markerOuterDiameter = 20; if (DonutRadius > 0) { Point2D calcPoint = forwardTransform.transform( new Point2D.Double(DonutRadius, 0), null); markerOuterDiameter = (int) calcPoint.getX() * 2; } g.drawOval( (int) (centerOnScreen.getX() - markerOuterDiameter / 2. ), (int) (centerOnScreen.getY() - markerOuterDiameter / 2. ), (int) (markerOuterDiameter+1), (int)(markerOuterDiameter+1)); } // draw object markers if (markers != null) { g.setColor(Color.magenta); for (java.util.Iterator<Point2D.Float> it = markers.iterator(); it .hasNext();) { Point2D.Float p = it.next(); Point2D p1 = new Point2D.Double(p.x, p.y); forwardTransform.transform(p1, p1); ((Graphics2D) g).drawOval((int) (p1.getX() - 4 + 0.5), (int) (p1.getY() - 4 + 0.5), 8, 8); } } if (this.meanCenter.getX() > 0 && this.meanCenter.getY() > 0) { drawMeanCenter(g, meanCenter.getX(), meanCenter.getY(), 2); } } public void drawMeanCenter(Graphics2D g2, double x, double y, double extent) { g2.setColor(Color.red); // draw the mean center Point2D.Double p1 = new Point2D.Double(); Point2D.Double p2 = new Point2D.Double(); this.drawLine(g2, x - extent, y, x - extent / 2, y, p1, p2); this.drawLine(g2, x + extent / 2, y, x + extent, y, p1, p2); this.drawLine(g2, x, y - extent, x, y - extent / 2, p1, p2); this.drawLine(g2, x, y + extent / 2, x, y + extent, p1, p2); } // /////////////////////////////// // /// Image update interfaces /** * Update the image to be displayed. * * @param data * an array of floats or shorts * * @param imageX * @param imageY * @param centerX * @param centerY * @param fwhm */ public void updateImage(Object data, int imageX, int imageY, float centerX, float centerY, float fwhm) { if (!this.lockData()) { myLogger.warn("GuideStarDisplay is busy; ignoring image update."); SoundSignal.fail2(); return; } if (data == null) return; if (this.RawImage == null || this.imageX != imageX || this.imageY != imageY) updateImageSize(imageX, imageY); updateObjectCenter(centerX, centerY, fwhm); if (data.getClass().getComponentType() == short.class) updateImage((short[]) data, imageX, imageY); else if (data.getClass().getComponentType() == float.class) updateImage((float[]) data, imageX, imageY); else myLogger.error("updateImage: Guide star display: Unsupported data type"); this.releaseData(); this.invokeRepaint(); } /** * Update the image to be displayed from a buffer of unsigned shorts * * @param data * Array of shorts[] that will be interpreted as ushorts. * @param imageX * Image dimension in X * @param imageY * Image dimension in Y */ private void updateImage(short[] data, int imageX, int imageY) { WritableRaster ras = RawImage.getRaster(); ras.setDataElements(0, 0, imageX, imageY, data); } /** * Update the image dot be displayed from a buffer of floats * * @param data * @param imageX * @param imageY */ private void updateImage(float[] data, int imageX, int imageY) { DataBuffer db = RawImage.getRaster().getDataBuffer(); // convert pixel by pixel to shorts. Not that fastest way of doing this! for (int ii = 0; ii < imageX * imageY; ii++) db.setElemFloat(ii, data[ii]); } /** * Modify the z-scaling of the images. * * This procedure will need to reset the internal ReScaleOp image operator. * * @param z1 * @param z2 */ public void setZScale(float z1, float z2) { this.z1 = z1; this.z2 = z2; updateScaleing(); if (this.myZscaleSelector != null) myZscaleSelector.setZScale((int) z1, (int) z2,false); } protected void updateScaleing() { this.myZScaleOp = new zScaleTransformOp(z1, z2, 1); this.invokeRepaint(); } public void mouseDragged(MouseEvent e) { // Intentionally left blank } /** * Provide a method to display the actual image value at the mouse location * */ public void mouseMoved(MouseEvent e) { Point p = e.getPoint(); Point2D P = new Point2D.Float(p.x, p.y); if (backwardTransform == null && RawImage != null) return; backwardTransform.transform(P, P); int x = (int) P.getX(); int y = (int) P.getY(); if (x < 0 || x >= imageX || y < 0 || y >= imageY) return; int val = 0; if (RawImage != null) val = (int) (RawImage.getRaster().getSample(x, y, 0) & 0xffff); } public float getZExtraOffset() { return zExtraOffset; } public void setZExtraOffset(float extraOffset) { zExtraOffset = extraOffset; } public void autoSetExtraZOffset(boolean set) { float[] outData = null; // centroidResults results = new centroidResults (); if (set == false || this.RawImage == null) { this.zExtraOffset = 0; } else { DataBuffer db = this.RawImage.getRaster().getDataBuffer(); outData = new float[RawImage.getWidth() * RawImage.getHeight()]; for (int ii = 0; ii < outData.length; ii++) { outData[ii] = (short) Math.round(db.getElemFloat(ii)); } if (outData == null) { myLogger.warn("autoSetExtraZOffset: got a null pointer from RawImage data!"); return; } ImageContainer tempgs = new ImageContainer(); tempgs.setImage(outData, RawImage.getWidth(), RawImage.getHeight()); odiCentroidSupport.findSkyandPeak(tempgs, 3, 1); this.zExtraOffset = tempgs.getBackground() - 50; } if (myLogger.isDebugEnabled()) myLogger.debug("Extra Offset set to: " + this.zExtraOffset); this.updateScaleing(); } public void setAutoBias(boolean b) { // TODO Auto-generated method stub } public float getFlux() { return flux; } public void setFlux(float flux) { this.flux = flux; } public void setFwhm(float fwhm) { this.fwhm = fwhm; } public float getFwhm() { return fwhm; } } class GSToolTip extends JToolTip { RadialPlotComponent rPlot = null; public GSToolTip() { rPlot = new RadialPlotComponent(100, 100); this.add(rPlot); } public void update(ImageContainer gs, Object image, int dimX, int dimY) { if (gs.rawImageBuffer == null && image != null) gs.rawImageBuffer = (float[]) image; rPlot.updateData(gs); } }
24.505495
88
0.676682
ff12b07636aea8eaf5965fbc100a9cfb0de28326
6,690
package hu.akarnokd.reactive; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import hu.akarnokd.reactive4java.util.Functions; import io.reactivex.disposables.*; import io.reactivex.internal.util.OpenHashSet; import rx.internal.util.RxThreadFactory; public final class SingleResourceScheduler extends ResourceScheduler { final ExecutorService executor; public SingleResourceScheduler() { executor = Executors.newSingleThreadExecutor(new RxThreadFactory("RxSingleResourceScheduler")); } @Override public Disposable scheduleDirect(ResourceTask task) { DirectTask dt = new DirectTask(task); Future<?> f = executor.submit(dt); dt.setFuture(f); return dt; } @Override public void shutdown() { executor.shutdownNow(); } @Override public ResourceWorker createWorker() { return new SingleResourceWorker(); } final class SingleResourceWorker extends ResourceWorker { volatile boolean disposed; OpenHashSet<WorkerTask> tasks; SingleResourceWorker() { this.tasks = new OpenHashSet<>(); } @Override public void dispose() { if (!disposed) { OpenHashSet<WorkerTask> set; synchronized (this) { if (disposed) { return; } disposed = true; set = tasks; tasks = null; } Object[] o = set.keys(); for (Object e : o) { if (e instanceof WorkerTask) { WorkerTask wt = (WorkerTask) e; wt.dispose(); } } } } @Override public boolean isDisposed() { return disposed; } @Override public Disposable schedule(ResourceTask task) { if (!disposed) { WorkerTask wt = new WorkerTask(task); if (add(wt)) { Future<?> f = executor.submit(wt); wt.setFuture(f); return wt; } } task.onCancel(); return Disposables.disposed(); } boolean add(WorkerTask task) { synchronized (this) { OpenHashSet<WorkerTask> set = tasks; if (set != null) { set.add(task); return true; } } return false; } void delete(WorkerTask task) { synchronized (this) { OpenHashSet<WorkerTask> set = tasks; if (set != null) { set.remove(task); } } } final class WorkerTask extends AtomicBoolean implements Callable<Void>, Disposable { private static final long serialVersionUID = 2906995671043870792L; final ResourceTask task; final AtomicReference<Future<?>> future; WorkerTask(ResourceTask task) { this.task = task; this.future = new AtomicReference<>(); } @Override public Void call() throws Exception { if (compareAndSet(false, true)) { try { task.run(); } finally { Future<?> f = future.get(); if (f != CANCELLED) { future.compareAndSet(f, FINISHED); delete(this); } } } return null; } @Override public void dispose() { if (compareAndSet(false, true)) { Future<?> f = future.getAndSet(CANCELLED); if (f != null) { f.cancel(true); } if (f != FINISHED) { delete(this); } task.onCancel(); } } @Override public boolean isDisposed() { Future<?> f = future.get(); return f == CANCELLED || f == FINISHED; } public void setFuture(Future<?> future) { if (this.future.compareAndSet(null, future)) { Future<?> f = this.future.get(); if (f == CANCELLED) { future.cancel(true); } } } } } static final FutureTask<Object> CANCELLED; static final FutureTask<Object> FINISHED; static { CANCELLED = new FutureTask<>(Functions.EMPTY_RUNNABLE, null); CANCELLED.cancel(false); FINISHED = new FutureTask<>(Functions.EMPTY_RUNNABLE, null); FINISHED.cancel(false); } static final class DirectTask extends AtomicBoolean implements Callable<Void>, Disposable { private static final long serialVersionUID = 2906995671043870792L; final ResourceTask task; final AtomicReference<Future<?>> future; DirectTask(ResourceTask task) { this.task = task; this.future = new AtomicReference<>(); } @Override public Void call() throws Exception { if (compareAndSet(false, true)) { try { task.run(); } finally { Future<?> f = future.get(); if (f != CANCELLED) { future.compareAndSet(f, FINISHED); } } } return null; } @Override public void dispose() { if (compareAndSet(false, true)) { Future<?> f = future.getAndSet(CANCELLED); if (f != null) { f.cancel(true); } task.onCancel(); } } @Override public boolean isDisposed() { Future<?> f = future.get(); return f == CANCELLED || f == FINISHED; } public void setFuture(Future<?> future) { if (this.future.compareAndSet(null, future)) { Future<?> f = this.future.get(); if (f == CANCELLED) { future.cancel(true); } } } } }
27.759336
103
0.456951
cd5affa36d69f4ef1636198a1eeb5b252148d050
2,385
package com.aiit.byh.service.common.utils.compress; import com.github.junrar.Archive; import com.github.junrar.exception.RarException; import com.github.junrar.rarfile.FileHeader; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * Created by pjwang2 on 2019\4\28 0028. */ public class RarUtil { /** * 解压rar文件 * * @param fileName * @param outputDirectory * @throws IOException */ public static boolean uncompress(String fileName, String outputDirectory) throws IOException, RarException { File destDiretory = new File(outputDirectory); if (!destDiretory.exists() && !destDiretory.mkdirs()) { return false; } File file = new File(fileName); Archive archive = new Archive(new FileInputStream(file)); FileHeader fh = null; File destFileName = null; FileOutputStream fos = null; try { while ((fh = archive.nextFileHeader()) != null) { String dirName = StringUtils.isBlank(fh.getFileNameW()) ? fh.getFileNameString() : fh.getFileNameW(); destFileName = new File(outputDirectory + File.separator + dirName); if (fh.isDirectory()) {// 文件夹 if (!destFileName.exists()) { destFileName.mkdirs(); } } else {// 文件 if (!destFileName.getParentFile().exists()) { destFileName.getParentFile().mkdirs(); } fos = new FileOutputStream(destFileName); archive.extractFile(fh, fos); fos.close(); } } } finally { if (null != fos) { fos.close(); } if (null != archive) { archive.close(); } } return true; } public static void main(String[] args) { try { RarUtil.uncompress("C:\\Users\\Administrator\\Desktop\\test\\test.rar", "C:\\Users\\Administrator\\Desktop\\test"); } catch (IOException e) { e.printStackTrace(); } catch (RarException e) { e.printStackTrace(); } } }
31.8
117
0.543396
a247fa099682bb8d4e39e28aa04f2ba2e63f90f8
693
package ai.datagym.application.labelIteration.models.viewModels.geometry; public class PointPojoViewModel { private String id; private Double x; private Double y; public PointPojoViewModel() { } public PointPojoViewModel(String id, Double x, Double y) { this.id = id; this.x = x; this.y = y; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } }
16.902439
73
0.55267
a71f7a1a744cf96fbbb5429756c11f1008d731d1
33,534
/* * 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 kr.co.bitnine.octopus.frame; import java.io.PrintWriter; import kr.co.bitnine.octopus.conf.OctopusConfiguration; import kr.co.bitnine.octopus.meta.MetaContext; import kr.co.bitnine.octopus.meta.MetaStore; import kr.co.bitnine.octopus.meta.MetaStoreService; import kr.co.bitnine.octopus.meta.MetaStores; import kr.co.bitnine.octopus.meta.logs.StdoutUpdateLoggerFactory; import kr.co.bitnine.octopus.meta.model.MetaUser; import kr.co.bitnine.octopus.meta.privilege.SystemPrivilege; import kr.co.bitnine.octopus.schema.SchemaManager; import kr.co.bitnine.octopus.testutils.MemoryDatabase; import kr.co.bitnine.octopus.util.NetUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.net.InetSocketAddress; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Properties; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runners.MethodSorters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SessionServerTest { private static final Log LOG = LogFactory.getLog(SchemaManager.class); private static MemoryDatabase metaMemDb; private static MemoryDatabase dataMemDb; private static MetaStoreService metaStoreService; private static ConnectionManager connectionManager; private static SchemaManager schemaManager; private static SessionServer sessionServer; @Rule public ExpectedException exception = ExpectedException.none(); @Rule public TestWatcher watchman = new TestWatcher() { @Override protected void starting(Description description) { LOG.info("start JUnit test: " + description.getDisplayName()); } @Override protected void finished(Description description) { LOG.info("finished. JUnit test: " + description.getDisplayName()); } }; @BeforeClass public static void setUpClass() throws Exception { Class.forName("kr.co.bitnine.octopus.Driver"); //DriverManager.setLogWriter(new PrintWriter(System.out)); } @Before public void setUp() throws Exception { metaMemDb = new MemoryDatabase("meta"); metaMemDb.start(); dataMemDb = new MemoryDatabase("data"); dataMemDb.start(); dataMemDb.importJSON(SessionServerTest.class.getClass(), "/sample.json"); Configuration conf = new OctopusConfiguration(); conf.set("metastore.jdo.connection.drivername", MemoryDatabase.DRIVER_NAME); conf.set("metastore.jdo.connection.URL", metaMemDb.connectionString); conf.set("metastore.jdo.connection.username", ""); conf.set("metastore.jdo.connection.password", ""); MetaStore metaStore = MetaStores.newInstance(conf.get("metastore.class")); metaStoreService = new MetaStoreService(metaStore, new StdoutUpdateLoggerFactory()); metaStoreService.init(conf); metaStoreService.start(); MetaContext metaContext = metaStore.getMetaContext(); MetaUser user = metaContext.createUser("octopus", "bitnine"); metaContext.addSystemPrivileges(Arrays.asList(SystemPrivilege.values()), Arrays.asList(user.getName())); connectionManager = new ConnectionManager(metaStore); connectionManager.init(conf); connectionManager.start(); schemaManager = SchemaManager.getSingletonInstance(metaStore); schemaManager.init(conf); schemaManager.start(); SessionFactory sessFactory = new SessionFactoryImpl( metaStore, connectionManager, schemaManager); sessionServer = new SessionServer(sessFactory); sessionServer.init(conf); sessionServer.start(); Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + dataMemDb.name + "\" CONNECT TO '" + dataMemDb.connectionString + "' USING '" + MemoryDatabase.DRIVER_NAME + "'"); stmt.close(); conn.close(); } @After public void tearDown() throws Exception { sessionServer.stop(); schemaManager.stop(); connectionManager.stop(); metaStoreService.stop(); dataMemDb.stop(); metaMemDb.stop(); } private static Connection getConnection(String user, String password) throws Exception { InetSocketAddress addr = NetUtils.createSocketAddr("127.0.0.1:58000"); String url = "jdbc:octopus://" + NetUtils.getHostPortString(addr); Properties info = new Properties(); info.setProperty("user", user); info.setProperty("password", password); // info.setProperty("prepareThreshold", "-1"); info.setProperty("prepareThreshold", "1"); // info.setProperty("binaryTransfer", "true"); return DriverManager.getConnection(url, info); } @Test public void testAddDataSourceExists() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); exception.expect(SQLException.class); stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + dataMemDb.name + "\" CONNECT TO '" + dataMemDb.connectionString + "' USING '" + MemoryDatabase.DRIVER_NAME + "'"); stmt.close(); conn.close(); } private boolean existDataSource(DatabaseMetaData metaData, String name) throws SQLException { ResultSet rs = metaData.getCatalogs(); while (rs.next()) { String dsName = rs.getString("TABLE_CAT"); System.out.println(" *** " + dsName); if (dsName.equals(name)) return true; } return false; } private boolean existTable(DatabaseMetaData metaData, String dsName, String name) throws SQLException { ResultSet rs = metaData.getTables(dsName, "%DEFAULT", "%", null); while (rs.next()) { String tblName = rs.getString("TABLE_NAME"); System.out.println(" *** " + tblName); if (tblName.equals(name)) return true; } return false; } private int checkNumRows(Statement stmt, String tblName) throws SQLException { ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM \"" + tblName + '"'); if (!rs.next()) return 0; int numRows = rs.getInt(1); rs.close(); return numRows; } @Test public void testDropDataSource1() throws Exception { /* add a new dataSource and populate some data */ MemoryDatabase newMemDb = new MemoryDatabase("DATA2"); newMemDb.start(); final String tblName = "TMP"; newMemDb.runExecuteUpdate("CREATE TABLE \"" + tblName + "\" (ID INTEGER, NAME STRING)"); Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + newMemDb.name + "\" CONNECT TO '" + newMemDb.connectionString + "' USING '" + MemoryDatabase.DRIVER_NAME + "'"); DatabaseMetaData metaData = conn.getMetaData(); assertTrue(existDataSource(metaData, newMemDb.name)); assertTrue(existTable(metaData, newMemDb.name, tblName)); stmt.execute("ALTER SYSTEM DROP DATASOURCE \"" + newMemDb.name + '"'); assertFalse(existDataSource(metaData, newMemDb.name)); assertFalse(existTable(metaData, newMemDb.name, tblName)); /* cleanup */ stmt.close(); conn.close(); newMemDb.stop(); } @Test public void testDropDataSource2() throws Exception { MemoryDatabase newMemDb = new MemoryDatabase("DATA2"); newMemDb.start(); newMemDb.runExecuteUpdate("CREATE TABLE \"TMP\" (\"ID\" INTEGER, \"NAME\" STRING)"); Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + newMemDb.name + "\" CONNECT TO '" + newMemDb.connectionString + "' USING '" + MemoryDatabase.DRIVER_NAME + "'"); stmt.execute("CREATE USER \"yjchoi\" IDENTIFIED BY 'piggy'"); stmt.execute("GRANT SELECT ON \"" + newMemDb.name + "\".\"__DEFAULT\" TO \"yjchoi\""); ResultSet rs = stmt.executeQuery("SHOW OBJECT PRIVILEGES FOR \"yjchoi\""); int numRows = 0; while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("PRIVILEGE")); ++numRows; } rs.close(); assertEquals(numRows, 1); stmt.execute("ALTER SYSTEM DROP DATASOURCE \"" + newMemDb.name + '"'); rs = stmt.executeQuery("SHOW OBJECT PRIVILEGES FOR \"yjchoi\""); numRows = 0; while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("PRIVILEGE")); ++numRows; } rs.close(); assertEquals(numRows, 0); stmt.execute("DROP USER \"yjchoi\""); stmt.close(); conn.close(); newMemDb.stop(); } @Test public void testUpdateDataSource1() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); final String tblName = "TMP"; dataMemDb.runExecuteUpdate("CREATE TABLE \"" + tblName + "\" (\"ID\" INTEGER, \"NAME\" STRING)"); dataMemDb.runExecuteUpdate("INSERT INTO \"" + tblName + "\" VALUES (1, 'yjchoi')"); boolean exceptionCaught = false; try { checkNumRows(stmt, tblName); } catch (SQLException e) { exceptionCaught = true; } assertTrue(exceptionCaught); int rows = checkNumRows(stmt, "employee"); assertEquals(rows, 10); DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs = metaData.getTables(dataMemDb.name, "%DEFAULT", "%", null); while (rs.next()) System.out.println(" *** " + rs.getString("TABLE_NAME")); stmt.execute("ALTER SYSTEM UPDATE DATASOURCE \"" + dataMemDb.name + '"'); metaData = conn.getMetaData(); rs = metaData.getTables(dataMemDb.name, "%DEFAULT", "%", null); while (rs.next()) System.out.println(" *** " + rs.getString("TABLE_NAME")); rows = checkNumRows(stmt, tblName); assertEquals(rows, 1); stmt.close(); conn.close(); } @Test public void testUpdateDataSource2() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("CREATE USER \"yjchoi\" IDENTIFIED BY 'piggy'"); stmt.execute("GRANT SELECT ON \"" + dataMemDb.name + "\".\"__DEFAULT\" TO \"yjchoi\""); Connection conn2 = getConnection("yjchoi", "piggy"); Statement stmt2 = conn.createStatement(); int rows = checkNumRows(stmt2, "employee"); assertEquals(rows, 10); ResultSet rs; DatabaseMetaData metaData = conn.getMetaData(); System.out.println("* Columns"); rs = metaData.getColumns(dataMemDb.name, "%DEFAULT", "employee", "%"); while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("COLUMN_NAME") + ", " + rs.getString("REMARKS")); } rs.close(); stmt.execute("ALTER SYSTEM UPDATE DATASOURCE \"" + dataMemDb.name + '"'); metaData = conn.getMetaData(); System.out.println("* Columns"); rs = metaData.getColumns(dataMemDb.name, "%DEFAULT", "employee", "%"); while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("COLUMN_NAME") + ", " + rs.getString("REMARKS")); } rs.close(); /* privileges should be preserved after update dataSource */ rows = checkNumRows(stmt2, "employee"); assertEquals(rows, 10); stmt2.close(); conn2.close(); stmt.close(); conn.close(); } @Test public void testUpdateDataSource3() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); final String comment = "commentOnTable"; final String tblName = "employee"; stmt.execute("COMMENT ON TABLE \"" + dataMemDb.name + "\".\"__DEFAULT\".\"" + tblName + "\" IS '" + comment + "'"); DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs = metaData.getTables(dataMemDb.name, "%DEFAULT", tblName, null); while (rs.next()) { if (rs.getString("TABLE_NAME").equals(tblName)) assertTrue(rs.getString("REMARKS").equals(comment)); System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("REMARKS")); } rs.close(); stmt.execute("ALTER SYSTEM UPDATE DATASOURCE \"" + dataMemDb.name + '"'); rs = metaData.getTables(dataMemDb.name, "%DEFAULT", tblName, null); while (rs.next()) { if (rs.getString("TABLE_NAME").equals(tblName)) assertTrue(rs.getString("REMARKS").equals(comment)); System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("REMARKS")); } rs.close(); stmt.close(); conn.close(); } @Test public void testUpdateDataSource4() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); dataMemDb.runExecuteUpdate("CREATE TABLE AA1 (ID INTEGER, NAME STRING)"); dataMemDb.runExecuteUpdate("CREATE TABLE AA2 (ID INTEGER, NAME STRING)"); dataMemDb.runExecuteUpdate("CREATE TABLE BB1 (ID INTEGER, NAME STRING)"); dataMemDb.runExecuteUpdate("INSERT INTO AA1 VALUES (1, 'yjchoi')"); boolean exceptionCaught = false; try { checkNumRows(stmt, "AA1"); } catch (SQLException e) { exceptionCaught = true; } assertTrue(exceptionCaught); stmt.execute("ALTER SYSTEM UPDATE TABLE \"" + dataMemDb.name + "\".\"__DEFAULT\".'AA%'"); int rows = checkNumRows(stmt, "AA1"); assertEquals(1, rows); rows = checkNumRows(stmt, "AA2"); assertEquals(0, rows); exceptionCaught = false; try { checkNumRows(stmt, "BB1"); } catch (SQLException e) { exceptionCaught = true; } assertTrue(exceptionCaught); dataMemDb.runExecuteUpdate("DROP TABLE AA1"); dataMemDb.runExecuteUpdate("DROP TABLE AA2"); dataMemDb.runExecuteUpdate("DROP TABLE BB1"); stmt.close(); conn.close(); } @Test public void testSelect() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); try { stmt.executeQuery("SELECT ID, NAME FROM BIT9"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT \"id\", \"name\" FROM \"employee\""); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("id=" + id + ", name=" + name); } rs.close(); stmt.close(); // conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement("SELECT \"id\", \"name\" FROM \"employee\" WHERE \"id\" >= ?"); pstmt.setMaxRows(3); // pstmt.setFetchSize(3); pstmt.setInt(1, 7); for (int i = 0; i < 2; i++) { rs = pstmt.executeQuery(); rs.next(); rs.close(); } rs = pstmt.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("id=" + id + ", name=" + name); } rs.close(); pstmt.close(); conn.close(); } /* * Calcite has a problem that Connection for Data source in Octopus is not closed in a right way. * This is because ResultSetEnumerator.close() is not called. * So, if we test complex queries, the next test case has a problem that the Sqlite DB is not destroyed. * For now, we temporarily decide not to conduct test cases for complex queries. */ /* @Test public void testComplexSelect() throws Exception { MemoryDatabase newMemDb = new MemoryDatabase("DATA2"); newMemDb.start(); newMemDb.runExecuteUpdate("CREATE TABLE \"TMP2\" (\"ID\" TEXT, \"NAME\" TEXT)"); newMemDb.runExecuteUpdate("INSERT INTO \"TMP2\" VALUES (1, 'bitnine')"); newMemDb.runExecuteUpdate("INSERT INTO \"TMP2\" VALUES (1, 'bitnine')"); newMemDb.runExecuteUpdate("INSERT INTO \"TMP2\" VALUES (1, 'bitnine')"); newMemDb.selectFrom("SELECT * FROM \"TMP2\""); Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + newMemDb.name + "\" CONNECT TO '" + newMemDb.connectionString + "' USING '" + MemoryDatabase.DRIVER_NAME + "'"); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT \"EM\".\"name\" " + "FROM \"employee\" \"EM\", " + "\"DATA2\".\"__DEFAULT\".\"TMP2\" \"TM\" " + "WHERE \"EM\".\"id\" = \"TM\".\"ID\""); while (rs.next()) { System.out.println(rs.getString(1)); } rs.close(); stmt.close(); conn.close(); newMemDb.stop(); } */ @Test public void testUser() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009'"); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); assertFalse(conn.isClosed()); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("ALTER USER \"jsyang\" IDENTIFIED BY 'jsyang' REPLACE '0009'"); stmt.close(); conn.close(); conn = getConnection("jsyang", "jsyang"); assertFalse(conn.isClosed()); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("DROP USER \"jsyang\""); stmt.close(); conn.close(); } @Test public void testRole() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("CREATE ROLE rnd"); stmt.execute("DROP ROLE rnd"); stmt.close(); conn.close(); } @Test public void testSystemPrivileges() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009'"); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); stmt = conn.createStatement(); try { stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + dataMemDb.name + "\" CONNECT TO '" + dataMemDb.connectionString + "' USING '" + MemoryDatabase.DRIVER_NAME + "'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("CREATE USER \"kskim\" IDENTIFIED BY 'vp'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("ALTER USER \"jsyang\" IDENTIFIED BY 'jsyang' REPLACE '0009'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("DROP USER \"jsyang\""); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("GRANT CREATE USER TO \"jsyang\""); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("REVOKE CREATE USER FROM \"octopus\""); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("COMMENT ON TABLE \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\" IS 'test'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("SET DATACATEGORY ON COLUMN \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\".\"name\" IS 'category'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } stmt.close(); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("GRANT ALL PRIVILEGES TO \"jsyang\""); String query = "REVOKE ALTER SYSTEM, " + "SELECT ANY TABLE, " + "ALTER USER, DROP USER, " + "COMMENT ANY, " + "GRANT ANY OBJECT PRIVILEGE, GRANT ANY PRIVILEGE " + "FROM \"jsyang\""; stmt.execute(query); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); stmt = conn.createStatement(); stmt.execute("CREATE USER \"kskim\" IDENTIFIED BY 'vp'"); try { stmt.execute("DROP USER \"kskim\""); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } stmt.close(); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("REVOKE CREATE USER FROM \"jsyang\""); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); stmt = conn.createStatement(); try { stmt.execute("CREATE USER \"bitnine\" IDENTIFIED BY 'password'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } stmt.close(); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("DROP USER \"kskim\""); stmt.execute("DROP USER \"jsyang\""); stmt.close(); conn.close(); } @Test public void testSelectPrivilege() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009'"); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); stmt = conn.createStatement(); try { stmt.executeQuery("SELECT \"id\", \"name\" FROM \"employee\";"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("GRANT SELECT ON \"" + dataMemDb.name + "\".\"__DEFAULT\" TO \"jsyang\""); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); stmt = conn.createStatement(); stmt.executeQuery("SELECT \"id\", \"name\" FROM \"employee\"").close(); stmt.close(); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("DROP USER \"jsyang\""); stmt.close(); conn.close(); } @Test public void testShow() throws Exception { Connection conn = getConnection("octopus", "bitnine"); System.out.println("* Transaction isolation level"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SHOW TRANSACTION ISOLATION LEVEL"); while (rs.next()) System.out.println(" " + rs.getString("transaction_isolation")); rs.close(); System.out.println("* DataSources"); DatabaseMetaData metaData = conn.getMetaData(); rs = metaData.getCatalogs(); while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("REMARKS")); } rs.close(); System.out.println("* Schemas"); rs = metaData.getSchemas(dataMemDb.name, "%DEFAULT"); while (rs.next()) { System.out.println(" " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_CATALOG") + ", " + rs.getString("REMARKS") + ", " + rs.getString("TABLE_CAT_REMARKS")); } rs.close(); System.out.println("* Tables"); rs = metaData.getTables(dataMemDb.name, "%DEFAULT", "employee", null); while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("REMARKS") + ", " + rs.getString("TABLE_CAT_REMARKS") + ", " + rs.getString("TABLE_SCHEM_REMARKS")); } rs.close(); System.out.println("* Columns"); rs = metaData.getColumns(dataMemDb.name, "%DEFAULT", "employee", "%"); while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("COLUMN_NAME") + ", " + rs.getString("REMARKS") + ", " + rs.getString("TABLE_CAT_REMARKS") + ", " + rs.getString("TABLE_SCHEM_REMARKS") + ", " + rs.getString("TABLE_NAME_REMARKS")); } rs.close(); System.out.println("* Users"); rs = stmt.executeQuery("SHOW ALL USERS"); while (rs.next()) { System.out.println(" " + rs.getString("USER_NAME") + ", " + rs.getString("REMARKS")); } rs.close(); stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009'"); stmt.execute("GRANT ALL ON \"" + dataMemDb.name + "\".\"__DEFAULT\" TO \"jsyang\""); rs = stmt.executeQuery("SHOW OBJECT PRIVILEGES FOR \"jsyang\""); while (rs.next()) { System.out.println(" " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("PRIVILEGE")); } rs.close(); stmt.execute("DROP USER \"jsyang\""); stmt.close(); conn.close(); } @Test public void testShowComments() throws Exception { Connection conn = getConnection("octopus", "bitnine"); System.out.println("* Comments"); Statement stmt = conn.createStatement(); stmt.execute("COMMENT ON DATASOURCE \"" + dataMemDb.name + "\" IS 'DS_COMMENT'"); stmt.execute("COMMENT ON SCHEMA \"" + dataMemDb.name + "\".\"__DEFAULT\" IS 'SCHEMA_COMMENT'"); stmt.execute("COMMENT ON TABLE \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\" IS 'TABLE_COMMENT'"); stmt.execute("COMMENT ON COLUMN \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\".\"name\" IS 'COLUMN_COMMENT_EXTRA'"); ResultSet rs = stmt.executeQuery("SHOW COMMENTS '%COMMENT' TABLE 'emp%' "); int rowCnt = 0; while (rs.next()) { ++rowCnt; System.out.println(" " + rs.getString("OBJECT_TYPE") + ", " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("COLUMN_NAME") + ", " + rs.getString("TABLE_CAT_REMARKS") + ", " + rs.getString("TABLE_SCHEM_REMARKS") + ", " + rs.getString("TABLE_NAME_REMARKS") + ", " + rs.getString("COLUMN_NAME_REMARKS")); } rs.close(); assertEquals(rowCnt, 3); stmt.close(); conn.close(); } @Test public void testComment() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("COMMENT ON DATASOURCE \"" + dataMemDb.name + "\" IS 'dataSource'"); stmt.execute("COMMENT ON SCHEMA \"" + dataMemDb.name + "\".\"__DEFAULT\" IS 'schema'"); stmt.execute("COMMENT ON TABLE \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\" IS 'table'"); stmt.execute("COMMENT ON COLUMN \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\".\"name\" IS 'column'"); stmt.execute("COMMENT ON USER \"octopus\" IS 'superuser'"); stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009';"); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); stmt = conn.createStatement(); try { stmt.execute("COMMENT ON DATASOURCE \"" + dataMemDb.name + "\" IS 'dataSource'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("COMMENT ON USER \"octopus\" IS 'superuser'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } try { stmt.execute("COMMENT ON SCHEMA \"" + dataMemDb.name + "\".\"__DEFAULT\" IS 'schema'"); } catch (SQLException e) { System.out.println("expected exception - " + e.getMessage()); } stmt.close(); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("GRANT COMMENT ON \"" + dataMemDb.name + "\".\"__DEFAULT\" TO \"jsyang\""); stmt.close(); conn.close(); conn = getConnection("jsyang", "0009"); stmt = conn.createStatement(); stmt.execute("COMMENT ON SCHEMA \"" + dataMemDb.name + "\".\"__DEFAULT\" IS 'schema'"); stmt.execute("COMMENT ON TABLE \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\" IS 'table'"); stmt.execute("COMMENT ON COLUMN \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\".\"name\" IS 'column'"); stmt.close(); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("DROP USER \"jsyang\""); stmt.close(); conn.close(); } }
36.569248
132
0.572404
abbd8b5aad14e9a26d8d37e169f5cfaf618bc021
3,431
package uk.co.omegaprime.mdbi; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.*; /** * A convenience wrapper around the {@link Reads#list(Collection)} functionality that avoids you having to track column indexes. * <p> * <pre> * RowReadBuilder rrb = RowReadBuilder.create(); * Supplier&lt;String&gt; names = rrb.add(sql("name"), String.class); * IntSupplier ages = rrb.addInt(sql("age")); * * for (List&lt;Object&gt; row : mdbi.queryList(sql("select ", columns, " from people"), rrb.build())) { * rrb.bindSuppliers(row); * System.out.println("Hello " + names.get() + " of age " + ages.get()); * } * </pre> */ public class RowReadBuilder { private final List<SQL> columns = new ArrayList<>(); private final List<Read<?>> reads = new ArrayList<>(); private final List<CompletableSupplier<?>> suppliers = new ArrayList<>(); private static class CompletableSupplier<T> implements Supplier<T> { public T value; @Override public T get() { if (value == null) { throw new IllegalStateException("You must bindSuppliers on the corresponding RowReadBuilder before invoking a Supplier that it returns"); } return value; } } private RowReadBuilder() {} public static RowReadBuilder create() { return new RowReadBuilder(); } /** Use the supplied row to bind all the {@code Supplier} objects that we have returned. */ @SuppressWarnings("unchecked") public void bindSuppliers(List<?> row) { for (int i = 0; i < row.size(); i++) { ((CompletableSupplier<Object>)suppliers.get(i)).value = row.get(i); } } /** Returns comma delimited column list */ public SQL buildColumns() { return SQL.commaSeparate(columns.iterator()); } /** Returns how to interpret a {@code ResultSet} as a row */ public Read<List<Object>> build() { return Reads.list(reads); } public <T> Supplier<T> add(SQL column, Class<T> klass) { return add(column, Reads.useContext(klass)); } private <T> CompletableSupplier<T> add(SQL column, Read<T> read) { columns.add(column); reads.add(read); final CompletableSupplier<T> supplier = new CompletableSupplier<>(); suppliers.add(supplier); return supplier; } // Very boring repetitive code below this line to deal with each prim type public BooleanSupplier addBoolean(SQL column) { return addBoolean(column, Reads.useContext(boolean.class)); } private BooleanSupplier addBoolean(SQL column, Read<Boolean> read) { return add(column, read)::get; } public IntSupplier addInt(SQL column) { return addInt(column, Reads.useContext(int.class)); } private IntSupplier addInt(SQL column, Read<Integer> read) { return add(column, read)::get; } public LongSupplier addLong(SQL column) { return addLong(column, Reads.useContext(long.class)); } private LongSupplier addLong(SQL column, Read<Long> read) { return add(column, read)::get; } public DoubleSupplier addDouble(SQL column) { return addDouble(column, Reads.useContext(double.class)); } private DoubleSupplier addDouble(SQL column, Read<Double> read) { return add(column, read)::get; } }
30.90991
153
0.640921
6885aae82a684eb22388de31eb971ed083539e91
973
package me.stuarthicks.xquery; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import javax.xml.transform.stream.StreamSource; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; public class ResourceURIResolverTest { private static final String HREF = "http://example"; private ResourceURIResolver underTest; @Before public void before () { this.underTest = new ResourceURIResolver(); } @Test public void itReturnsNullIfFileNotThere () throws Exception { assertNull(this.underTest.resolve(HREF, "/nothing-to-see-here.txt")); } @Test public void itReturnsStreamOfFileIfThere () throws Exception { String expected = "why not zoidberg?"; StreamSource actual = (StreamSource) this.underTest.resolve(HREF, "/something-here.txt"); assertEquals(expected, IOUtils.toString(actual.getInputStream()).trim()); } }
26.297297
97
0.717369
b9889342d35d5ea40a0868722e5f2498340fee24
340
package base; import global.wrappers.BinaryFileWrapper; import global.wrappers.DirectoryWrapper; import global.wrappers.FileWrapper; /** * Created by Arsen on 11.09.2016. */ public interface ElementVisitor { void visit(DirectoryWrapper wrapper); void visit(FileWrapper wrapper); void visit(BinaryFileWrapper wrapper); }
17.894737
42
0.764706
1073b2ecd8b450674ade497daeedf238d77715c2
4,340
package com.crowdin.cli.commands.actions; import com.crowdin.cli.client.ProjectClient; import com.crowdin.cli.commands.NewAction; import com.crowdin.cli.commands.Outputter; import com.crowdin.cli.commands.functionality.RequestBuilder; import com.crowdin.cli.properties.ProjectProperties; import com.crowdin.client.core.model.PatchOperation; import com.crowdin.client.core.model.PatchRequest; import com.crowdin.client.labels.model.Label; import com.crowdin.client.sourcestrings.model.SourceString; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static com.crowdin.cli.BaseCli.RESOURCE_BUNDLE; import static com.crowdin.cli.utils.console.ExecutionStatus.OK; class StringEditAction implements NewAction<ProjectProperties, ProjectClient> { private final boolean noProgress; private final Long id; private final String identifier; private final String newText; private final String newContext; private final Integer newMaxLength; private final List<String> labelNames; private final Boolean isHidden; public StringEditAction( boolean noProgress, Long id, String identifier, String newText, String newContext, Integer newMaxLength, List<String> labelNames, Boolean isHidden ) { this.noProgress = noProgress; this.id = id; this.identifier = identifier; this.newText = newText; this.newContext = newContext; this.newMaxLength = newMaxLength; this.labelNames = labelNames; this.isHidden = isHidden; } @Override public void act(Outputter out, ProjectProperties pb, ProjectClient client) { List<SourceString> sourceStrings = client.listSourceString(null, null, null, null, null); List<Long> labelIds = (labelNames != null && !labelNames.isEmpty()) ? this.prepareLabelIds(client) : null; Long foundStringId; if (id != null) { foundStringId = sourceStrings.stream() .filter(ss -> id.equals(ss.getId())) .findAny() .orElseThrow(() -> new RuntimeException(RESOURCE_BUNDLE.getString("error.source_string_not_found"))) .getId(); } else if (identifier != null) { foundStringId = sourceStrings.stream() .filter(ss -> identifier.equals(ss.getIdentifier())) .findAny() .orElseThrow(() -> new RuntimeException(RESOURCE_BUNDLE.getString("error.source_string_not_found"))) .getId(); } else { throw new RuntimeException("Unexpected error: no 'id' or 'identifier' specified"); } List<PatchRequest> requests = new ArrayList<>(); if (newText != null) { PatchRequest request = RequestBuilder.patch(newText, PatchOperation.REPLACE, "/text"); requests.add(request); } if (newContext != null) { PatchRequest request = RequestBuilder.patch(newContext, PatchOperation.REPLACE, "/context"); requests.add(request); } if (newMaxLength != null) { PatchRequest request = RequestBuilder.patch(newMaxLength, PatchOperation.REPLACE, "/maxLength"); requests.add(request); } if (isHidden != null) { PatchRequest request = RequestBuilder.patch(isHidden, PatchOperation.REPLACE, "/isHidden"); requests.add(request); } if (labelIds != null) { PatchRequest request = RequestBuilder.patch(labelIds, PatchOperation.REPLACE, "/labelIds"); requests.add(request); } client.editSourceString(foundStringId, requests); out.println(OK.withIcon(String.format(RESOURCE_BUNDLE.getString("message.source_string_updated"), foundStringId))); } private List<Long> prepareLabelIds(ProjectClient client) { Map<String, Long> labels = client.listLabels().stream() .collect(Collectors.toMap(Label::getTitle, Label::getId)); labelNames.stream() .distinct() .forEach(labelName -> labels.computeIfAbsent(labelName, (title) -> client.addLabel(RequestBuilder.addLabel(title)).getId())); return labelNames.stream() .map(labels::get) .collect(Collectors.toList()); } }
40.943396
154
0.665668
2da99ee57da941ca11335a5ddd9c4f082449f7a6
1,379
/* * 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.connector.base.source.hybrid; /** The state of hybrid source enumerator. */ public class HybridSourceEnumeratorState { private final int currentSourceIndex; private final Object wrappedState; HybridSourceEnumeratorState(int currentSourceIndex, Object wrappedState) { this.currentSourceIndex = currentSourceIndex; this.wrappedState = wrappedState; } public int getCurrentSourceIndex() { return this.currentSourceIndex; } public Object getWrappedState() { return wrappedState; } }
35.358974
78
0.741842
092e633f2fcb588ea93dcd72f1ff57ba1e8e4b13
3,250
package com.ibyte.framework.support; import com.ibyte.common.constant.NamingConstant; import com.ibyte.framework.meta.MetaEntity; import com.ibyte.framework.meta.MetaModule; import com.ibyte.framework.support.domain.MetaEntityImpl; import com.ibyte.framework.support.domain.MetaModuleImpl; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @author li.Shangzhi * @Description: <元数据上下文> * @Date: 2019-10-17 */ public class LocalMetaContextHolder { private final static LocalMetaContextHolder INSTANCE = new LocalMetaContextHolder(); public final static LocalMetaContextHolder get() { return INSTANCE; } private volatile boolean locked = false; private Map<String, MetaModule> modules = new HashMap<>(); /** 锁定前,获取模块列表 */ public Map<String, MetaModule> getModules() { if (locked) { return null; } return modules; } /** 获取模块 */ public MetaModule getModule(String name) { return modules.get(name); } /** 获取模块,在锁定前没有该模块则创建 */ public MetaModule getOrCreateModule(String name) { MetaModuleImpl module = (MetaModuleImpl) modules.get(name); if (module == null && !locked) { module = new MetaModuleImpl(); module.setName(name); modules.put(name, module); } return module; } /** 获取某个类所属的模块 */ public String matchModule(String className) { if (!className.startsWith(NamingConstant.BASE_PACKAGE)) { return null; } String[] paths = className.toLowerCase().split("\\."); StringBuilder sb = new StringBuilder(); String moduleName = null; for (int i = NamingConstant.BASE_PACKAGE_DEEP; i < paths.length - 1; i++) { if (sb.length() > 0) { sb.append('-'); } sb.append(paths[i]); String name = sb.toString(); if (modules.containsKey(name)) { moduleName = name; } else { if (moduleName != null) { return moduleName; } } } return moduleName; } private Map<String, MetaEntity> entities = new HashMap<>(); /** 锁定前 获取表列表 */ public Map<String, MetaEntity> getEntities() { if (locked) { return null; } return entities; } /** 获取表 */ public MetaEntity getEntity(String name) { return entities.get(name); } /** 获取表,在锁定前没有该表则创建 */ public MetaEntity getOrCreateEntity(String name) { MetaEntityImpl entity = (MetaEntityImpl) entities.get(name); if (entity == null && !locked) { entity = new MetaEntityImpl(); entity.setEntityName(name); entities.put(name, entity); } return entity; } /** 锁定 */ public void lock() { if (locked) { return; } locked = true; for (MetaEntity e : entities.values()) { MetaEntityImpl entity = (MetaEntityImpl) e; entity.setProperties( Collections.unmodifiableMap(entity.getProperties())); } } }
26.639344
88
0.572308
44bbd5e0bb8ddb765c43cf85ddc74172b185f57f
262
package com.unidev.parsers.model; /** * Parser service implementation. */ public interface Parser { /** * Parser id. */ String parserId(); /** * Process request. */ ParserResponse process(ParserRequest parserRequest); }
13.789474
56
0.60687
364cc952f6a6b5bbef296d09913b245efd03ebdb
2,828
/** * Copyright [2013] Gaurav Gupta * * 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.netbeans.modeler.core.scene.vmd; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.netbeans.modeler.specification.model.document.IRootElement; import org.netbeans.modeler.specification.model.document.property.ElementPropertySet; import org.netbeans.modeler.specification.model.document.widget.IBaseElementWidget; import org.netbeans.modeler.specification.model.document.widget.IFlowElementWidget; /** * DefaultPModelerScene is the default implementation of PModelerScene. You * should implement your own modeler scene implementation if you want to modify * the storage structure of flowElements widget (e.g divide flowElements widget * into multiple collection , as in BPMN module Conversation and Artifacts * element are stored in different collection) * * @author Gaurav Gupta * @param <E> */ public abstract class DefaultPModelerScene<E extends IRootElement> extends PModelerScene<E> { private final Map<String, IFlowElementWidget> flowElements = new LinkedHashMap<>(); @Override public void onConnection() { } @Override public IBaseElementWidget getBaseElement(String id) { return flowElements.get(id); } @Override public List<IBaseElementWidget> getBaseElements() { return new ArrayList<>(flowElements.values()); } @Override public void removeBaseElement(IBaseElementWidget baseElementWidget) { if (baseElementWidget instanceof IFlowElementWidget) { this.flowElements.remove(baseElementWidget.getId()); } } @Override public void addBaseElement(IBaseElementWidget baseElementWidget) { if (baseElementWidget instanceof IFlowElementWidget) { this.flowElements.put(baseElementWidget.getId(), (IFlowElementWidget) baseElementWidget); } } @Override public void createPropertySet(ElementPropertySet set) { set.createPropertySet(this, this.getBaseElementSpec(), getPropertyChangeListeners()); } @Override public void createVisualPropertySet(ElementPropertySet elementPropertySet) { } }
35.35
102
0.728076
b5f6446534dd2fe7e00d2262f796f6276094897d
10,848
// Generated by OABuilder package com.cdi.model.oa; import java.util.logging.*; import java.sql.*; import com.viaoa.object.*; import com.viaoa.hub.*; import com.viaoa.util.*; import com.viaoa.annotation.*; import com.cdi.delegate.oa.*; import com.cdi.model.oa.filter.*; import com.cdi.model.oa.propertypath.*; import com.viaoa.util.OADateTime; @OAClass( shortName = "aul", displayName = "App User Login", isProcessed = true, displayProperty = "appUser.displayName", filterClasses = {AppUserLoginConnectedFilter.class, AppUserLoginLastDayFilter.class}, rootTreePropertyPaths = { "[AppUser]."+AppUser.P_AppUserLogins } ) @OATable( indexes = { @OAIndex(name = "AppUserLoginAppUser", fkey = true, columns = { @OAIndexColumn(name = "AppUserId") }) } ) public class AppUserLogin extends OAObject { private static final long serialVersionUID = 1L; private static Logger LOG = Logger.getLogger(AppUserLogin.class.getName()); public static final String PROPERTY_Id = "Id"; public static final String P_Id = "Id"; public static final String PROPERTY_Created = "Created"; public static final String P_Created = "Created"; public static final String PROPERTY_Location = "Location"; public static final String P_Location = "Location"; public static final String PROPERTY_ComputerName = "ComputerName"; public static final String P_ComputerName = "ComputerName"; public static final String PROPERTY_Disconnected = "Disconnected"; public static final String P_Disconnected = "Disconnected"; public static final String PROPERTY_ConnectionId = "ConnectionId"; public static final String P_ConnectionId = "ConnectionId"; public static final String PROPERTY_HostName = "HostName"; public static final String P_HostName = "HostName"; public static final String PROPERTY_IpAddress = "IpAddress"; public static final String P_IpAddress = "IpAddress"; public static final String PROPERTY_TotalMemory = "TotalMemory"; public static final String P_TotalMemory = "TotalMemory"; public static final String PROPERTY_FreeMemory = "FreeMemory"; public static final String P_FreeMemory = "FreeMemory"; public static final String PROPERTY_AppServers = "AppServers"; public static final String P_AppServers = "AppServers"; public static final String PROPERTY_AppUser = "AppUser"; public static final String P_AppUser = "AppUser"; public static final String PROPERTY_AppUserErrors = "AppUserErrors"; public static final String P_AppUserErrors = "AppUserErrors"; protected volatile int id; protected volatile OADateTime created; protected volatile String location; protected volatile String computerName; protected volatile OADateTime disconnected; protected volatile int connectionId; protected volatile String hostName; protected volatile String ipAddress; protected volatile long totalMemory; protected volatile long freeMemory; // Links to other objects. protected volatile transient AppUser appUser; protected transient Hub<AppUserError> hubAppUserErrors; public AppUserLogin() { if (!isLoading()) { setCreated(new OADateTime()); } } public AppUserLogin(int id) { this(); setId(id); } @OAProperty(isUnique = true, displayLength = 6) @OAId() @OAColumn(sqlType = java.sql.Types.INTEGER) public int getId() { return id; } public void setId(int newValue) { int old = id; fireBeforePropertyChange(P_Id, old, newValue); this.id = newValue; firePropertyChange(P_Id, old, this.id); } @OAProperty(defaultValue = "new OADateTime()", displayLength = 15, isProcessed = true) @OAColumn(sqlType = java.sql.Types.TIMESTAMP) public OADateTime getCreated() { return created; } public void setCreated(OADateTime newValue) { OADateTime old = created; fireBeforePropertyChange(P_Created, old, newValue); this.created = newValue; firePropertyChange(P_Created, old, this.created); } @OAProperty(maxLength = 50, displayLength = 20, columnLength = 15, isProcessed = true) @OAColumn(maxLength = 50) public String getLocation() { return location; } public void setLocation(String newValue) { String old = location; fireBeforePropertyChange(P_Location, old, newValue); this.location = newValue; firePropertyChange(P_Location, old, this.location); } @OAProperty(displayName = "Computer Name", maxLength = 32, displayLength = 20, columnLength = 15, isProcessed = true) @OAColumn(maxLength = 32) public String getComputerName() { return computerName; } public void setComputerName(String newValue) { String old = computerName; fireBeforePropertyChange(P_ComputerName, old, newValue); this.computerName = newValue; firePropertyChange(P_ComputerName, old, this.computerName); } @OAProperty(displayLength = 15, isProcessed = true) @OAColumn(sqlType = java.sql.Types.TIMESTAMP) public OADateTime getDisconnected() { return disconnected; } public void setDisconnected(OADateTime newValue) { OADateTime old = disconnected; fireBeforePropertyChange(P_Disconnected, old, newValue); this.disconnected = newValue; firePropertyChange(P_Disconnected, old, this.disconnected); } @OAProperty(displayName = "Connection Id", displayLength = 6, columnLength = 13, isProcessed = true) @OAColumn(sqlType = java.sql.Types.INTEGER) public int getConnectionId() { return connectionId; } public void setConnectionId(int newValue) { int old = connectionId; fireBeforePropertyChange(P_ConnectionId, old, newValue); this.connectionId = newValue; firePropertyChange(P_ConnectionId, old, this.connectionId); } @OAProperty(displayName = "Host Name", maxLength = 35, displayLength = 20, columnLength = 15, isProcessed = true) @OAColumn(maxLength = 35) public String getHostName() { return hostName; } public void setHostName(String newValue) { String old = hostName; fireBeforePropertyChange(P_HostName, old, newValue); this.hostName = newValue; firePropertyChange(P_HostName, old, this.hostName); } @OAProperty(displayName = "Ip Address", maxLength = 20, displayLength = 20, columnLength = 15, isProcessed = true) @OAColumn(maxLength = 20) public String getIpAddress() { return ipAddress; } public void setIpAddress(String newValue) { String old = ipAddress; fireBeforePropertyChange(P_IpAddress, old, newValue); this.ipAddress = newValue; firePropertyChange(P_IpAddress, old, this.ipAddress); } @OAProperty(displayName = "Total Memory", displayLength = 6, columnLength = 7, columnName = "Tot Mem", isProcessed = true) @OAColumn(sqlType = java.sql.Types.BIGINT) public long getTotalMemory() { return totalMemory; } public void setTotalMemory(long newValue) { long old = totalMemory; fireBeforePropertyChange(P_TotalMemory, old, newValue); this.totalMemory = newValue; firePropertyChange(P_TotalMemory, old, this.totalMemory); } @OAProperty(displayName = "Free Memory", displayLength = 6, columnLength = 8, columnName = "Free Mem", isProcessed = true) @OAColumn(sqlType = java.sql.Types.BIGINT) public long getFreeMemory() { return freeMemory; } public void setFreeMemory(long newValue) { long old = freeMemory; fireBeforePropertyChange(P_FreeMemory, old, newValue); this.freeMemory = newValue; firePropertyChange(P_FreeMemory, old, this.freeMemory); } @OAMany( displayName = "App Servers", toClass = AppServer.class, reverseName = AppServer.P_AppUserLogin, isProcessed = true, createMethod = false ) private Hub<AppServer> getAppServers() { // oamodel has createMethod set to false, this method exists only for annotations. return null; } @OAOne( displayName = "App User", reverseName = AppUser.P_AppUserLogins, required = true, allowCreateNew = false ) @OAFkey(columns = {"AppUserId"}) public AppUser getAppUser() { if (appUser == null) { appUser = (AppUser) getObject(P_AppUser); } return appUser; } public void setAppUser(AppUser newValue) { AppUser old = this.appUser; fireBeforePropertyChange(P_AppUser, old, newValue); this.appUser = newValue; firePropertyChange(P_AppUser, old, this.appUser); } @OAMany( displayName = "App User Errors", toClass = AppUserError.class, owner = true, reverseName = AppUserError.P_AppUserLogin, cascadeSave = true, cascadeDelete = true ) public Hub<AppUserError> getAppUserErrors() { if (hubAppUserErrors == null) { hubAppUserErrors = (Hub<AppUserError>) getHub(P_AppUserErrors); } return hubAppUserErrors; } public void load(ResultSet rs, int id) throws SQLException { this.id = id; java.sql.Timestamp timestamp; timestamp = rs.getTimestamp(2); if (timestamp != null) this.created = new OADateTime(timestamp); this.location = rs.getString(3); this.computerName = rs.getString(4); timestamp = rs.getTimestamp(5); if (timestamp != null) this.disconnected = new OADateTime(timestamp); this.connectionId = (int) rs.getInt(6); if (rs.wasNull()) { OAObjectInfoDelegate.setPrimitiveNull(this, AppUserLogin.P_ConnectionId, true); } this.hostName = rs.getString(7); this.ipAddress = rs.getString(8); this.totalMemory = (long) rs.getLong(9); if (rs.wasNull()) { OAObjectInfoDelegate.setPrimitiveNull(this, AppUserLogin.P_TotalMemory, true); } this.freeMemory = (long) rs.getLong(10); if (rs.wasNull()) { OAObjectInfoDelegate.setPrimitiveNull(this, AppUserLogin.P_FreeMemory, true); } int appUserFkey = rs.getInt(11); if (!rs.wasNull() && appUserFkey > 0) { setProperty(P_AppUser, new OAObjectKey(appUserFkey)); } if (rs.getMetaData().getColumnCount() != 11) { throw new SQLException("invalid number of columns for load method"); } changedFlag = false; newFlag = false; } }
36.897959
126
0.663072
6bf4bcf3f29100ca9157fa15450911e9cd1bffc2
1,861
/** * 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.hadoop.io.file.tfile; import java.io.IOException; import java.io.Serializable; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.WritableComparator; /** * * Byte arrays test case class using GZ compression codec, base class of none * and LZO compression classes. * */ public class TestTFileJClassComparatorByteArrays extends TestDTFileByteArrays { /** * Test non-compression codec, using the same test cases as in the ByteArrays. */ @Override public void setUp() throws IOException { init(Compression.Algorithm.GZ.getName(), "jclass: org.apache.hadoop.io.file.tfile.MyComparator"); super.setUp(); } } class MyComparator implements RawComparator<byte[]>, Serializable { @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return WritableComparator.compareBytes(b1, s1, l1, b2, s2, l2); } @Override public int compare(byte[] o1, byte[] o2) { return WritableComparator.compareBytes(o1, 0, o1.length, o2, 0, o2.length); } }
31.542373
80
0.732939
fdf12a7146d272cbe31e3b4410fbff67c8dda443
97
package fr.lteconsulting.hexa.databinding.test.dto; public class B { public String firstName; }
16.166667
51
0.793814
6c429b7f5712a58e35ea44c3b7fcad62d95dcdce
617
package inc.troll.hydra.modules.discord.commands; public class HelpCommand implements ICommand { @Override public void handle(CommandContext ctx) { ctx.getChannel() .sendMessage("use:\n") .append("* `.play <YouTube link>` - plays song of given YouTube link\n") .append("* `.ping` - current latency in ms for REST and WebSocket\n") .append("* `.help` - displays this text") .queue(); } @Override public String getName() { return "help"; } @Override public String getHelp() { return null; } }
22.851852
84
0.572123
767ee041e33eda7ef47ede91a8f6c7c4ba453088
713
package br.com.onebr.controller.response; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ContributorsRes { @JsonProperty("contributors") private List<ContributorRes> contributors; @Data @Builder @NoArgsConstructor @AllArgsConstructor public static class ContributorRes { @JsonProperty("order") private short order; @JsonProperty("name") private String name; @JsonProperty("description") private String description; } }
20.371429
53
0.726508
6a87aaf6cab546486c8cb47020dae136a9f5714d
659
package com.test.filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 禁用缓存: 以下三种都可以禁用缓存 */ public class NoCacheFilter extends HttpFilter{ @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { response.setDateHeader("Expires", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); chain.doFilter(request, response); } }
28.652174
140
0.748103
08f0b559bdd36a6ac1954ab53332350eed9bc00d
295
package it.unitn.web.centodiciotto.persistence.dao; import it.unitn.web.centodiciotto.persistence.base.DAO; import it.unitn.web.centodiciotto.persistence.entities.ExamType; /** * DAO interface for a {@link ExamType} entity. */ public interface ExamTypeDAO extends DAO<ExamType, Integer> { }
26.818182
64
0.786441
83b79f563a2272308e986899cf32e57af4d22ec5
8,054
package org.infinispan.remoting.inboundhandler; import static org.infinispan.factories.KnownComponentNames.REMOTE_COMMAND_EXECUTOR; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutorService; import org.infinispan.IllegalLifecycleStateException; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.remote.CacheRpcCommand; import org.infinispan.commons.CacheException; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.ComponentName; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.remoting.responses.CacheNotFoundResponse; import org.infinispan.remoting.responses.ExceptionResponse; import org.infinispan.remoting.responses.Response; import org.infinispan.remoting.responses.SuccessfulResponse; import org.infinispan.remoting.transport.Address; import org.infinispan.util.ByteString; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.infinispan.xsite.BackupReceiver; import org.infinispan.xsite.BackupReceiverRepository; import org.infinispan.xsite.XSiteReplicateCommand; /** * {@link org.infinispan.remoting.inboundhandler.InboundInvocationHandler} implementation that handles all the {@link * org.infinispan.commands.ReplicableCommand}. * <p/> * This component handles the {@link org.infinispan.commands.ReplicableCommand} from local and remote site. The remote * site {@link org.infinispan.commands.ReplicableCommand} are sent to the {@link org.infinispan.xsite.BackupReceiver} to * be handled. * <p/> * Also, the non-{@link org.infinispan.commands.remote.CacheRpcCommand} are processed directly and the {@link * org.infinispan.commands.remote.CacheRpcCommand} are processed in the cache's {@link * org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler} implementation. * * @author Pedro Ruivo * @since 7.1 */ @Scope(Scopes.GLOBAL) public class GlobalInboundInvocationHandler implements InboundInvocationHandler { private static final Log log = LogFactory.getLog(GlobalInboundInvocationHandler.class); private static final boolean trace = log.isTraceEnabled(); private ExecutorService remoteCommandsExecutor; private BackupReceiverRepository backupReceiverRepository; private GlobalComponentRegistry globalComponentRegistry; private static Response shuttingDownResponse() { return CacheNotFoundResponse.INSTANCE; } private static ExceptionResponse exceptionHandlingCommand(Throwable throwable) { return new ExceptionResponse(new CacheException("Problems invoking command.", throwable)); } @Inject public void injectDependencies(@ComponentName(REMOTE_COMMAND_EXECUTOR) ExecutorService remoteCommandsExecutor, GlobalComponentRegistry globalComponentRegistry, BackupReceiverRepository backupReceiverRepository) { this.remoteCommandsExecutor = remoteCommandsExecutor; this.globalComponentRegistry = globalComponentRegistry; this.backupReceiverRepository = backupReceiverRepository; } @Override public void handleFromCluster(Address origin, ReplicableCommand command, Reply reply, DeliverOrder order) { command.setOrigin(origin); try { if (command instanceof CacheRpcCommand) { handleCacheRpcCommand(origin, (CacheRpcCommand) command, reply, order); } else { handleReplicableCommand(origin, command, reply, order); } } catch (Throwable t) { log.exceptionHandlingCommand(command, t); reply.reply(exceptionHandlingCommand(t)); } } @Override public void handleFromRemoteSite(String origin, XSiteReplicateCommand command, Reply reply, DeliverOrder order) { if (trace) { log.tracef("Handling command %s from remote site %s", command, origin); } BackupReceiver receiver = backupReceiverRepository.getBackupReceiver(origin, command.getCacheName().toString()); if (order.preserveOrder()) { runXSiteReplicableCommand(command, receiver, reply); } else { //the remote site commands may need to be forwarded to the appropriate owners remoteCommandsExecutor.execute(() -> runXSiteReplicableCommand(command, receiver, reply)); } } private void handleCacheRpcCommand(Address origin, CacheRpcCommand command, Reply reply, DeliverOrder mode) { if (trace) { log.tracef("Attempting to execute CacheRpcCommand: %s [sender=%s]", command, origin); } ByteString cacheName = command.getCacheName(); ComponentRegistry cr = globalComponentRegistry.getNamedComponentRegistry(cacheName); if (cr == null) { if (trace) { log.tracef("Silently ignoring that %s cache is not defined", cacheName); } reply.reply(CacheNotFoundResponse.INSTANCE); return; } initializeCacheRpcCommand(command, cr); PerCacheInboundInvocationHandler handler = cr.getPerCacheInboundInvocationHandler(); handler.handle(command, reply, mode); } private void initializeCacheRpcCommand(CacheRpcCommand command, ComponentRegistry componentRegistry) { CommandsFactory commandsFactory = componentRegistry.getCommandsFactory(); // initialize this command with components specific to the intended cache instance commandsFactory.initializeReplicableCommand(command, true); } private void runXSiteReplicableCommand(XSiteReplicateCommand command, BackupReceiver receiver, Reply reply) { try { reply.reply(command.performInLocalSite(receiver)); } catch (InterruptedException e) { log.shutdownHandlingCommand(command); reply.reply(shuttingDownResponse()); } catch (Throwable throwable) { log.exceptionHandlingCommand(command, throwable); reply.reply(exceptionHandlingCommand(throwable)); } } private void handleReplicableCommand(Address origin, ReplicableCommand command, Reply reply, DeliverOrder order) { if (trace) { log.tracef("Attempting to execute non-CacheRpcCommand: %s [sender=%s]", command, origin); } if (order.preserveOrder() || !command.canBlock()) { runReplicableCommand(command, reply, order.preserveOrder()); } else { remoteCommandsExecutor.execute(() -> runReplicableCommand(command, reply, order.preserveOrder())); } } private void runReplicableCommand(ReplicableCommand command, Reply reply, boolean preserveOrder) { try { invokeReplicableCommand(command, reply, preserveOrder); } catch (Throwable throwable) { if (throwable.getCause() != null && throwable instanceof CompletionException) { throwable = throwable.getCause(); } if (throwable instanceof InterruptedException || throwable instanceof IllegalLifecycleStateException) { log.shutdownHandlingCommand(command); reply.reply(shuttingDownResponse()); } else { log.exceptionHandlingCommand(command, throwable); reply.reply(exceptionHandlingCommand(throwable)); } } } private void invokeReplicableCommand(ReplicableCommand command, Reply reply, boolean preserveOrder) throws Throwable { globalComponentRegistry.wireDependencies(command); CompletableFuture<Object> future = command.invokeAsync(); if (preserveOrder) { future.join(); } else { future.whenComplete((retVal, throwable) -> { if (retVal != null && !(retVal instanceof Response)) { retVal = SuccessfulResponse.create(retVal); } reply.reply(retVal); }); } } }
43.069519
120
0.733549
1c4677a9d1356100e50112ca64aac4605a36002c
1,564
package edu.neu.cs6510.dto; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import edu.neu.cs6510.model.Location; import edu.neu.cs6510.model.LookUpData; import edu.neu.cs6510.model.primeKey.LookUpPK; import static org.junit.Assert.*; public class LocationInfoDTOTest { LocationInfoDTO locationInfoDTO; List<LookUpData> lookUpDataList; LookUpData lookUpData; Location location; LookUpPK lookUpPK; @Before public void setUp() throws Exception { locationInfoDTO = new LocationInfoDTO(new Location()); lookUpDataList = new ArrayList<>(); lookUpPK = new LookUpPK(); lookUpPK.setAttribute_mapping_id(1); lookUpPK.setLocation_id(1); lookUpPK.setYear(2019); lookUpData = new LookUpData(); lookUpData.setLookUpPK(lookUpPK); lookUpDataList.add(lookUpData); location = new Location(); location.setFips_code_state(1); location.setName("Test"); location.setFips_county(1); location.setFips_place(1); location.setFyenddate(1); location.setId(1); location.setLatitude(1.0); location.setLongitude(1.0); location.setParent_id("1"); location.setType_code(1); } @Test public void getLocation() { locationInfoDTO.setLocation(location); Assert.assertEquals(location, locationInfoDTO.getLocation()); } @Test public void getAttributeValues() { locationInfoDTO.setAttributeValues(lookUpDataList); Assert.assertEquals(lookUpDataList, locationInfoDTO.getAttributeValues()); } }
25.225806
78
0.737212
417928e8b9d4dd0d0d10763659bcef55084bbd2c
195
package fr.flavi1.gravitree.Tools; import java.util.Random; /** * Created by Flavien on 20/06/2015. */ public class Randomizer { public static Random random = new Random(); }
16.25
48
0.661538
e4ac42afeed1bcfa16e119f27e8c12a8a87198e0
375
package xyz.guqing.app.dao.message; import xyz.guqing.app.bean.entity.message.MessageTemplate; import xyz.guqing.app.dao.BaseRepository; import java.util.List; public interface MessagetemplateRepository extends BaseRepository<MessageTemplate,Long> { MessageTemplate findByCode(String code); List<MessageTemplate> findByIdMessageSender(Long idMessageSender); }
23.4375
89
0.816
efb53f5cd5f2a3ae7bf7f4f4586ce136251ddf54
56
package sample.ifs; public interface IResult { }
9.333333
27
0.678571
867da3d518c5f67e020d08bdadd1bc7f9fffa31e
1,086
package Comparisons; import Model.Result; import Model.TestBase; import org.apache.commons.text.similarity.JaroWinklerSimilarity; import java.util.List; public class JaroWinklerComparison extends BaseComparison{ private final JaroWinklerSimilarity jaroWinklerSimilarity; public JaroWinklerComparison() { super(); this.jaroWinklerSimilarity = new JaroWinklerSimilarity(); } private Double getResult(StringBuffer str1, StringBuffer str2){ return jaroWinklerSimilarity.apply(str1,str2); } @Override protected int normalizeValue(int value) { return 0; } @Override protected int normalizeValue(double value) { return this.percertToScale.convertM(value); } @Override protected void calculate(TestBase testBase) { StringBuffer str1 = new StringBuffer(testBase.getStr1()); StringBuffer str2 = new StringBuffer(testBase.getStr2()); double result = this.getResult(str1, str2); this.addResult(new Result(testBase.getId(), this.normalizeValue(result))); } }
25.857143
82
0.710866
e245c4f5c502db9eafb25e54769318c4d8f96fce
2,091
package ch.hslu.hashTabelle; import java.util.Arrays; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class HashTable<E> implements HashArrayInterface<Integer> { static private final Logger LOG = LogManager.getLogger(HashTable.class); Integer[] hashArray = new Integer[10]; private int size; final private int maxSize = 10; @Override public void add(Integer e) { if (this.isFull() == true) { LOG.error("This HashTable is full. Value has NOT been saved!"); return; } int i = 0; while ((hashArray[this.hash(e) + i]) != null) { if (this.hash(e) + i + 1 == this.maxSize) { i = -this.hash(e); } else { i++; if (this.hash(e) + i == this.hash(e)) { return; } } } hashArray[this.hash(e) + i] = e; size++; } @Override public Integer search(Integer e) { int i = 0; while ((hashArray[this.hash(e) + i]) != e) { if (this.hash(e) + i + 1 == this.maxSize) { i = -this.hash(e); } else { i++; if (this.hash(e) + i == this.hash(e)) { return null; } } } return hashArray[this.hash(e)+i]; } @Override public void remove(Integer e) { int i = 0; while ((hashArray[this.hash(e) + i]) != e) { if (this.hash(e) + i + 1 == this.maxSize) { i = -this.hash(e); } else { i++; if (this.hash(e) + i == this.hash(e)) { return; } } } hashArray[this.hash(e) + i] = null; --size; } @Override public String toString() { return "HashTable [hashArray=" + Arrays.toString(hashArray) + ", size=" + size + ", maxSize=" + maxSize + "]"; } private boolean exists(Integer e) { int i = 0; while ((hashArray[this.hash(e) + i]) != e) { if (this.hash(e) + i + 1 == this.maxSize) { i = -this.hash(e); } else { i++; if (this.hash(e) + i == this.hash(e)) { return false; } } } return true; } public boolean isFull() { if (size != maxSize) { return false; } else return true; } public int size() { return this.size; } private int hash(Integer e) { return e % 10; } }
18.837838
112
0.565758
1c0defe46f0edc0f16c9bbb6af3ac8929e30925e
445
package com.dandelion.communication.me.router; import androidx.fragment.app.Fragment; import com.alibaba.android.arouter.launcher.ARouter; /** * 我的组件服务工具类 * 其他组件使用此类,即可跳转我的组件相关页面、调用故事组件服务 * Created by lin.wang on 2021/6/24. */ public class MeServiceUtil { public static Fragment navigateMePage(){ return (Fragment) ARouter.getInstance() .build(MeRouterTable.PATH_PAGE_ME) .navigation(); } }
23.421053
52
0.696629
72a08dbc7dc15c18716d68f8a6d00e53a511cd56
1,989
/** * Copyright 2014-2019 the original author or authors. * * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package org.fisco.bcos.sdk.transaction.mock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import lombok.EqualsAndHashCode; import org.fisco.bcos.sdk.model.TransactionReceipt; import org.fisco.bcos.sdk.model.callback.TransactionCallback; /** * TransactionCallback @Description: TransactionCallback * * @author maojiayu * @data Mar 23, 2020 9:53:42 PM */ @EqualsAndHashCode(callSuper = false) public class TransactionCallbackMock extends TransactionCallback { private TransactionReceipt transactionReceipt; private ReentrantLock reentrantLock = new ReentrantLock(); private Condition condition; public TransactionCallbackMock() { condition = reentrantLock.newCondition(); } public TransactionReceipt getResult() { try { reentrantLock.lock(); while (transactionReceipt == null) { condition.awaitUninterruptibly(); } return transactionReceipt; } finally { reentrantLock.unlock(); } } @Override public void onResponse(TransactionReceipt transactionReceipt) { try { reentrantLock.lock(); this.transactionReceipt = transactionReceipt; condition.signal(); } finally { reentrantLock.unlock(); } } }
32.606557
99
0.695324
2b542fc9f3409b3c3957f396b3b730b587b7ed2c
1,665
/* * 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.guacamole.auth.cas; import org.apache.guacamole.auth.sso.SSOAuthenticationProvider; import org.apache.guacamole.auth.sso.SSOResource; /** * Guacamole authentication backend which authenticates users using an * arbitrary external system implementing CAS. No storage for connections is * provided - only authentication. Storage must be provided by some other * extension. */ public class CASAuthenticationProvider extends SSOAuthenticationProvider { /** * Creates a new CASAuthenticationProvider that authenticates users * against an CAS service */ public CASAuthenticationProvider() { super(AuthenticationProviderService.class, SSOResource.class, new CASAuthenticationProviderModule()); } @Override public String getIdentifier() { return "cas"; } }
34.6875
76
0.741141
d37c15e7f9b707292b55a2a09bb64d0186831fed
869
package yuku.alkitab.base.util; import android.os.Environment; import java.io.File; public class AddonManager { public static final String TAG = AddonManager.class.getSimpleName(); public static String getYesPath() { return new File(Environment.getExternalStorageDirectory(), "bible/yes").getAbsolutePath(); } /** * @param yesName an added yes filename without the path. */ public static String getVersionPath(String yesName) { String yesPath = getYesPath(); File yes = new File(yesPath, yesName); return yes.getAbsolutePath(); } public static boolean hasVersion(String yesName) { File f = new File(getVersionPath(yesName)); return f.exists() && f.canRead(); } public static boolean mkYesDir() { File dir = new File(getYesPath()); if (!dir.exists()) { return new File(getYesPath()).mkdirs(); } else { return true; } } }
22.868421
92
0.706559
96535cd363293a8393a09b1040ef7dcc1737262b
9,883
package de.uniks.networkparser.test; import org.junit.Assert; import org.junit.Test; import de.uniks.networkparser.graph.Clazz; import de.uniks.networkparser.graph.DataType; import de.uniks.networkparser.graph.GraphList; import de.uniks.networkparser.graph.Method; import de.uniks.networkparser.graph.MethodSet; import de.uniks.networkparser.graph.Modifier; public class GetMethodsTest { @Test public void testAbstract() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").with(Modifier.create(Modifier.ABSTRACT)); Method method = person.createMethod("think").with(DataType.BOOLEAN); method.with(Modifier.create(Modifier.ABSTRACT)); Clazz student = model.createClazz("Student").withSuperClazz(person); MethodSet methods = student.getMethods(); Assert.assertEquals(1, methods.size()); Assert.assertEquals(method, methods.get(0)); } @Test public void testInterface() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").enableInterface(); Clazz student = model.createClazz("Student").withSuperClazz(person); Method method = person.createMethod("think").with(DataType.BOOLEAN); MethodSet methods = student.getMethods(); Assert.assertEquals(1, methods.size()); Assert.assertEquals(method, methods.get(0)); } @Test public void testAbstractToNormal() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").with(Modifier.create(Modifier.ABSTRACT)); Clazz human = model.createClazz("Human").withSuperClazz(person); Clazz student = model.createClazz("Student").withSuperClazz(human); Method method = person.createMethod("think").with(DataType.BOOLEAN); MethodSet humanMethods = human.getMethods(); Assert.assertEquals(0, humanMethods.size()); method.with(Modifier.ABSTRACT); humanMethods = human.getMethods(); Assert.assertEquals(1, humanMethods.size()); Assert.assertEquals(method, humanMethods.get(0)); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(0, studentMethods.size()); } @Test public void testAbstractToAbstract() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").with(Modifier.create(Modifier.ABSTRACT)); Method method = person.createMethod("think").with(DataType.BOOLEAN); Clazz human = model.createClazz("Human").withSuperClazz(person).with(Modifier.create(Modifier.ABSTRACT)); Clazz student = model.createClazz("Student").withSuperClazz(human); MethodSet humanMethods = human.getMethods(); Assert.assertEquals(0, humanMethods.size()); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(0, studentMethods.size()); method.with(Modifier.ABSTRACT); studentMethods = student.getMethods(); Assert.assertEquals(1, studentMethods.size()); Assert.assertEquals(method, studentMethods.get(0)); } @Test public void testAbstractToNormalToAbstract() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").with(Modifier.create(Modifier.ABSTRACT)); Clazz human = model.createClazz("Human").withSuperClazz(person); Clazz student = model.createClazz("Student").withSuperClazz(human); Clazz pupil = model.createClazz("Pupil").withSuperClazz(student).with(Modifier.create(Modifier.ABSTRACT)); Method method = person.createMethod("think").with(DataType.BOOLEAN).with(Modifier.create(Modifier.ABSTRACT)); MethodSet humanMethods = human.getMethods(); Assert.assertEquals(1, humanMethods.size()); Assert.assertEquals(method, humanMethods.get(0)); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(0, studentMethods.size()); MethodSet pupilMethods = pupil.getMethods(); Assert.assertEquals(0, pupilMethods.size()); } @Test public void testAbstractToAbstractToNormal() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").with(Modifier.create(Modifier.ABSTRACT)); Method method = person.createMethod("think").with(DataType.BOOLEAN).with(Modifier.ABSTRACT); Clazz human = model.createClazz("Human").withSuperClazz(person).with(Modifier.create(Modifier.ABSTRACT)); Clazz student = model.createClazz("Student").withSuperClazz(human); Clazz pupil = model.createClazz("Pupil").withSuperClazz(student); MethodSet humanMethods = human.getMethods(); Assert.assertEquals(0, humanMethods.size()); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(1, studentMethods.size()); Assert.assertEquals(method, studentMethods.get(0)); MethodSet pupilMethods = pupil.getMethods(); Assert.assertEquals(0, pupilMethods.size()); } @Test public void testAbstractToAbstractToNormalToAbstract() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").with(Modifier.create(Modifier.ABSTRACT)); Clazz human = model.createClazz("Human").withSuperClazz(person).with(Modifier.create(Modifier.ABSTRACT)); Clazz student = model.createClazz("Student").withSuperClazz(human); Clazz pupil = model.createClazz("Pupil").withSuperClazz(student); Clazz subPupil = model.createClazz("SubPupil").withSuperClazz(pupil).with(Modifier.create(Modifier.ABSTRACT)); Method method = person.createMethod("think").with(DataType.BOOLEAN).with(Modifier.ABSTRACT); MethodSet humanMethods = human.getMethods(); Assert.assertEquals(0, humanMethods.size()); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(1, studentMethods.size()); Assert.assertEquals(method, studentMethods.get(0)); MethodSet pupilMethods = pupil.getMethods(); Assert.assertEquals(0, pupilMethods.size()); MethodSet subPupilMethods = subPupil.getMethods(); Assert.assertEquals(0, subPupilMethods.size()); } @Test public void testAbstractToNormalToAbstractToNormal() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").with(Modifier.create(Modifier.ABSTRACT)); Clazz human = model.createClazz("Human").withSuperClazz(person); Clazz student = model.createClazz("Student").withSuperClazz(human); Clazz pupil = model.createClazz("Pupil").withSuperClazz(student).with(Modifier.create(Modifier.ABSTRACT)); Clazz subPupil = model.createClazz("SubPupil").withSuperClazz(pupil); Method method = person.createMethod("think").with(DataType.BOOLEAN).with(Modifier.ABSTRACT); MethodSet humanMethods = human.getMethods(); Assert.assertEquals(1, humanMethods.size()); Assert.assertEquals(method, humanMethods.get(0)); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(0, studentMethods.size()); MethodSet pupilMethods = pupil.getMethods(); Assert.assertEquals(0, pupilMethods.size()); MethodSet subPupilMethods = subPupil.getMethods(); Assert.assertEquals(0, subPupilMethods.size()); } @Test public void testInterfaceToAbstractToNormal() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").enableInterface(); Clazz student = model.createClazz("Student").withSuperClazz(person).with(Modifier.create(Modifier.ABSTRACT)); Clazz pupil = model.createClazz("Pupil").withSuperClazz(student); Method method = person.createMethod("think").with(DataType.BOOLEAN); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(0, studentMethods.size()); MethodSet pupilMethods = pupil.getMethods(); Assert.assertEquals(1, pupilMethods.size()); Assert.assertEquals(method, pupilMethods.get(0)); } @Test public void testInterfaceToNormalToAbstract() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").enableInterface(); Clazz student = model.createClazz("Student").withSuperClazz(person); Clazz pupil = model.createClazz("Pupil").withSuperClazz(student).withSuperClazz(student).with(Modifier.create(Modifier.ABSTRACT)); Method method = person.createMethod("think").with(DataType.BOOLEAN); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(1, studentMethods.size()); Assert.assertEquals(method, studentMethods.get(0)); MethodSet pupilMethods = pupil.getMethods(); Assert.assertEquals(0, pupilMethods.size()); } @Test public void testInterfaceAndAbstract() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").enableInterface(); Clazz teacher = model.createClazz("Teacher").with(Modifier.create(Modifier.ABSTRACT)); Clazz student = model.createClazz("Student").withSuperClazz(person, teacher); Method method = person.createMethod("think").with(DataType.BOOLEAN); Method method2 = teacher.createMethod("walk").with(DataType.INT).with(Modifier.create(Modifier.ABSTRACT)); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(2, studentMethods.size()); Assert.assertTrue(studentMethods.contains(method)); Assert.assertTrue(studentMethods.contains(method2)); } @Test public void testInterfaceAndAbstractToNormal() { GraphList model = new GraphList().with("de.uniks"); Clazz person = model.createClazz("Person").enableInterface(); Clazz teacher = model.createClazz("Teacher").with(Modifier.create(Modifier.ABSTRACT)); Clazz student = model.createClazz("Student").withSuperClazz(person, teacher); Clazz pupil = model.createClazz("Pupil").withSuperClazz(student); Method method = person.createMethod("think").with(DataType.BOOLEAN); Method method2 = teacher.createMethod("walk").with(DataType.INT).with(Modifier.create(Modifier.ABSTRACT)); MethodSet studentMethods = student.getMethods(); Assert.assertEquals(2, studentMethods.size()); Assert.assertTrue(studentMethods.contains(method)); Assert.assertTrue(studentMethods.contains(method2)); MethodSet pupilMethods = pupil.getMethods(); Assert.assertEquals(0, pupilMethods.size()); } }
45.127854
132
0.762825
bfd3e3975aefbffe2b64132fab1442289fd664e8
5,312
/* * Copyright 2014 Guillaume Masclet <guillaume.masclet@yahoo.fr>. * * 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.elasticlib.common.model; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Collections.unmodifiableSortedSet; import java.util.Map; import static java.util.Objects.hash; import static java.util.Objects.requireNonNull; import java.util.SortedSet; import java.util.TreeSet; import org.elasticlib.common.hash.Hash; import org.elasticlib.common.mappable.MapBuilder; import org.elasticlib.common.mappable.Mappable; import static org.elasticlib.common.mappable.MappableUtil.putRevisions; import static org.elasticlib.common.mappable.MappableUtil.revisions; import org.elasticlib.common.util.EqualsBuilder; import org.elasticlib.common.value.Value; /** * Actual result of a command. */ public final class CommandResult implements Mappable { private static final String OPERATION = "operation"; private static final String NO_OP = "noOp"; private static final String CONTENT = "content"; private static final String REVISIONS = "revisions"; private final Operation operation; private final Hash content; private final SortedSet<Hash> revisions; private CommandResult(Operation operation, Hash content, SortedSet<Hash> revisions) { this.operation = operation; this.content = content; this.revisions = unmodifiableSortedSet(new TreeSet<>(revisions)); } /** * Static factory method. * * @param operation Operation executed. * @param content Associated content hash. * @param revisions New head revisions after command execution. * @return A new instance. */ public static CommandResult of(Operation operation, Hash content, SortedSet<Hash> revisions) { return new CommandResult(requireNonNull(operation), content, revisions); } /** * Specific static factory method for no-op command result. * * @param content Associated content hash. * @param revisions Head revisions after (and before) command execution. * @return A new instance. */ public static CommandResult noOp(Hash content, SortedSet<Hash> revisions) { return new CommandResult(null, content, revisions); } /** * Checks if command actually lead to a concrete operation. * * @return true if no operation actually took place. */ public boolean isNoOp() { return operation == null; } /** * Provides operation actually executed. Fails if this is a no-op. * * @return An operation. */ public Operation getOperation() { if (isNoOp()) { throw new IllegalStateException(); } return operation; } /** * Provides this command associated content hash. * * @return A hash. */ public Hash getContent() { return content; } /** * Provides revision hashes after command execution. * * @return A sorted set of revision hashes. */ public SortedSet<Hash> getRevisions() { return revisions; } @Override public Map<String, Value> toMap() { MapBuilder builder = new MapBuilder() .put(OPERATION, isNoOp() ? NO_OP : operation.toString()) .put(CONTENT, content); return putRevisions(builder, revisions).build(); } /** * Read a new instance from supplied map of values. * * @param map A map of values. * @return A new instance. */ public static CommandResult fromMap(Map<String, Value> map) { Hash content = map.get(CONTENT).asHash(); SortedSet<Hash> revisions = revisions(map); String opCode = map.get(OPERATION).asString(); if (opCode.equals(NO_OP)) { return CommandResult.noOp(content, revisions); } else { return CommandResult.of(Operation.fromString(opCode), content, revisions); } } @Override public int hashCode() { return hash(operation, content, revisions); } @Override public boolean equals(Object obj) { if (!(obj instanceof CommandResult)) { return false; } CommandResult other = (CommandResult) obj; return new EqualsBuilder() .append(operation, other.operation) .append(content, other.content) .append(revisions, other.revisions) .build(); } @Override public String toString() { return toStringHelper(this) .add(OPERATION, operation == null ? NO_OP : operation) .add(CONTENT, content) .add(REVISIONS, revisions) .toString(); } }
31.808383
98
0.655685
cd9a401c6a012ef7dbb2666de8cc02035c4f4c85
2,116
package ponyquest.sprites; import java.awt.*; import pwnee.image.*; import pwnee.sprites.Sprite; import ponyquest.PonyMain; import ponyquest.maps.Layer; /** * Any kind of sprite that resides in a Layer in an AreaMap. This class * provides support for maintaining the sprite's layer state and moving the sprite * to other layers if necessary. */ public abstract class LayerSprite extends Sprite { /** The layer this Sprite currently is residing in. */ public Layer curLayer; /** Does this sprite count as an obstacle for the player's movement? */ public boolean isObstacle = false; public LayerSprite(double x, double y) { super(x,y); } /** When the sprite is destroyed, remove it from its layer. */ public void destroy() { super.destroy(); if(curLayer != null) { curLayer.remove(this); } } // Gets a placeholder for images not loaded in the game's ImageLibrary. public static Image getBadImage() { if(PonyMain.imageLib.get("tile:badTile") == null) { System.out.println("loading badTile"); ImageLoader il = new ImageLoader(); Image img = il.loadResource("graphics/tiles/badTile.png"); PonyMain.imageLib.put("tile:badTile", img); il.addImage(img); il.waitForAll(); } return PonyMain.imageLib.get("tile:badTile"); } /** Obtains the layer that this sprite is in. */ public Layer getLayer() { return curLayer; } /** Safely changes the layer that this sprite currently resides in. */ public void setLayer(Layer newLayer) { if(curLayer != null) { curLayer.remove(this); } curLayer = newLayer; newLayer.add(this); } /** Returns true iff this and another sprite are in the same layer. */ public boolean inSameLayer(LayerSprite other) { return (this.curLayer == other.curLayer); } /** See if this sprite is colliding with another sprite in the same layer. */ public boolean collideWith(LayerSprite other) { return (this.inSameLayer(other) && this.getCollisionPoly().intersects(other.getCollisionPoly())); } }
25.804878
101
0.66966
3b4c34ab0e8bd75bc1e6711334ccf533fdb7d082
4,899
class B { } class y { } class y2RkIk_qA0 { public static void GDnvQQ (String[] isTR9tUY) { { void _JMTw; uiUDY().n(); void[][] AlPtscOSo4; boolean oQ3TYh2L6HqY; M7s6dBOPY[] e2k; int ZESWYO8; yz_8[][] KnVSw3G; int LOCED; { oEQWkG3c[] slM; } boolean PTqppzJMGqqt5E; return; void[] qU29; void P3sO9e1VMZtH; DN3nhVAw0K_lC yWaubXhkQSzg; int WG3czcKB; if ( -true[ 152201017[ true[ 790542[ this.z9d1dAeru]]]]) -!2873[ PBYUg0lsy59[ ( !-null.D1TxhuZot3JSx())[ !false.y]]]; } while ( --187.yvtXA) ; ; void gw4od165C; vkNuFZN nR3rRR; void tuVNuev2H4WI = new void[ this.eOXhTy][ null[ !new FwuyMP().DSn]] = this.G4cazbG7Y; while ( true.N9BoIY5uE1U()) return; iD ZHwnW; } public static void QAnqcOVDu_Z (String[] Yy0nJx) { boolean vmjTv; int k1NHeTar; int y5AzUVs6kWP; EnB5xIkax_lL2 KGZ6uEXOyA5 = false.UoMy1k() = new _PDAc().Q8zlIb(); int[] xy; !kqxm1ortaR1ry().FPL6XoPy; if ( new boolean[ !--!j8yulrHSd().KL9Eie2LqV()][ !--null[ !OmNx8Ty[ null[ --402.YYY5]]]]) if ( -!new void[ !--new UrT().P0A1krsQwYDPk()].RgAi4cX) ;else { if ( this[ ---i709v.FnAEqYyfTTvF()]) ; } while ( qMs6Hyt.WT7E7t_()) null[ -!!Vt7yF89.vqtWnqHBL3f8Mt]; ; void ta7q; if ( --this[ null.MooYMoZ4]) ; l6ELs[][][][][][][] mjfrYRO; --!vnTrkGTs().jt(); while ( new p()[ ( true.GUYjnXV())[ -this.r]]) return; return -KDKrt8YJWg()[ !this.z]; boolean[][][][][] PtLxrF; if ( this.BXQjahmqOSGn()) --false[ i7RgEANF().IOqAomx7MuFj()];else !0417985.vyfOdYlY; { void vuA; } } public void x79gv3q73FF; public void mg; public static void yu2U75D (String[] XNb4) throws y { if ( ( true.XxuBWa1wlTV).zxDABfU_RmC) if ( -_TBKoWcZzZ_()[ _t22sFcH()[ FT()[ -!!false.WTi()]]]) ;else while ( rXGto[ new o[ qmtOL38IJw7w[ this[ this.hJpiKX7UI9qg4()]]][ ( -!!-!!-!( Z.Oou06beUApKiNN).D4).DKRVnlAi6nk]]) ; boolean[][][] a4QugeC5hTC47Y = ( this[ 809319.w])[ !new RNbrBD()[ !F1GYTr.kum5()]] = h9Zl4Vrcsb().HtDhERGYn(); void l; { if ( !-null[ -null[ -!ohL.gndrxAioJ1R]]) { di ARj_3UyUcQA3Y; } return; ; return; boolean[][] KF4JazX_Fs7; yNJK6i().DaW8S47kzo; while ( 7921673.JlEYRz) ( -this.h)[ new int[ !( -true._())[ Ej8ACfC5fB9CQ().cs7dHQh()]][ !-!false.wlDBsfVjUI5]]; { ; } while ( !5.r9zn05()) 791[ !( new DsGPrF8ccl().Viu9cZjPHPlNh()).pNmOmHuVlu()]; I fnfR8R969; e8ez[] o; int[][][] xfJCqQECcWhQ; if ( null._a()) return; } this.SSMSJlBvbjSG(); while ( -null.IuK5) !---fTMZot_DKy7Ku.zN; { while ( null.e4lc5()) while ( true[ this[ 782881601.fBe2y5kQAh8Da()]]) while ( false.Ar()) return; ; if ( !( !!new int[ w().bzCS].weaCcrhr23Kx5())[ !-Le8KCE9doW[ kQ1.U1YgVtB3yyCQ]]) ; } { while ( this.T9aCab) while ( !new cSshmiGx().W9HQgdpMH()) 47874[ -!!true.bfFB]; int[] Ko79Qp; WPUDvdPkq uATtiiRP4; void MwDYt; return; YzRPlDbYhjU[] TXe; ; while ( new u7jhEh1()[ !!-new void[ -aynXQ2NGwsDIjc().OKB()].GlS842S]) { boolean PxIHhLQ0Vdrhr; } { return; } void z0; int k5w095ZTXq5G48; if ( !-null[ this.dkas()]) if ( !Q8().r2NVXDrIvV1N_()) return; int Uxzq; int[] NurY0ocKj2il; bOhxdW3G8ksAxH[] p; int KEkttS3UddRY5K; int WEcNUZ4gpFiRR; while ( J437nOij().Pqs86zSQpmpK) return; void wi30; boolean[][][][] UwiEXeNFq; } if ( !-null.rq1()) !!!JPi4k13RyNxfb.J0K; ; } public tatI0PSgy[][] BH () throws MDESXX { if ( new boolean[ this.Bw].fMRVxuR()) ; new grt[ -s6rTddDCc2[ !!new Ic5qFlQ()[ !!-!-!!null.nfpQ]]][ ( -!!new void[ !false[ -!Z8().vEgc()]][ eSoVDECzo4().AXrcH]).AM5Ym8YM()]; if ( !djw0sbdJxT7zpd.kBFGPxJ) { boolean[] bIRNI; } boolean dVu1vmhuMtp; { null.YyoTzpcwLyk; } sn_D159SWMo7LD Ud_A2FAZ = -tso9bWG_UU.xx6SS7L7x5_ = null[ -!new int[ !-( -null.QnLuVjPnx_Pp()).zuQ8].GZ4nnMp8yGV()]; int vddK0; while ( !--kpB6qa5_.xT2dXX2domRx) { !--!-null._thSRJH; } } }
34.744681
227
0.482956
8565376af8bdfd65056586b49751fe42a99dc63d
1,386
/* * Copyright 2017 dmfs GmbH * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dmfs.httpessentials.executors.authorizing; import org.dmfs.httpessentials.types.Token; /** * The interface of an authentication challenge. See <a href="https://tools.ietf.org/html/rfc7235#section-2.1">RFC 7235, section 2.1</a>. * * @author Marten Gajda */ public interface Challenge { /** * The scheme {@link Token} of the challenge. * * @return a {@link Token}. */ Token scheme(); /** * Returns the actual challenge {@link CharSequence}. The value will be trimmed, i.e. will not contain any leading or trailing spaces. Though the value may * be of length {@code 0}. * <p> * Note, in most cases this is subject to further parsing. * * @return A {@link CharSequence} */ CharSequence challenge(); }
29.489362
159
0.683983
f9f19238372a60803121eb0900d0a8c77954d210
656
package com.czechyuan.imageedit; import android.graphics.Bitmap; public interface GraffitiListener { /** * 保存图片 * * @param bitmap 涂鸦后的图片 * @param bitmapEraser 橡皮擦底图 */ void onSaved(Bitmap bitmap, Bitmap bitmapEraser); /** * 出错 * * @param i * @param msg */ void onError(int i, String msg); /** * 准备工作已经完成 */ void onReady(); /** * 选中 * * @param selected 是否选中,false表示从选中变成不选中 */ void onSelectedItem(GraffitiSelectableItem selectableItem, boolean selected); void onCreateSelectableItem(GraffitiView.Pen pen, float x, float y); }
16.820513
81
0.591463
33144ffcb22c1f07469e40c542ac4918b1127c2e
2,452
package medical.monitor; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.android.myapplication.R; import medical.utils.DefaultCallback; public class DateAdapter extends RecyclerView.Adapter<DateAdapter.DateHolder> { private AgentPulso agent; private MonitorActivity activity; public DateAdapter(AgentPulso agent, MonitorActivity activity) { this.agent = agent; this.activity = activity; } @NonNull @Override public DateHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_date, parent, false); return new DateHolder(view); } @Override public void onBindViewHolder(@NonNull DateHolder holder, int position) { holder.position = position; holder.textView.setText(agent.dates.get(position) + ""); } @Override public int getItemCount() { return agent.dates.size(); } public class DateHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public int position; private TextView textView; public DateHolder(@NonNull View itemView) { super(itemView); textView = itemView.findViewById(R.id.date); itemView.setOnClickListener(this); } @Override public void onClick(View v) { agent.fecha = agent.dates.get(position); agent.getDataMonitorDate(agent.dates.get(position), new DefaultCallback() { @Override public void onFinishProcess(final boolean hasSucceeded, Object result) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (hasSucceeded) { Intent in = new Intent(activity, SummaryActivity.class); activity.startActivity(in); } else Toast.makeText(activity, "Get Data Fail", Toast.LENGTH_SHORT); } }); } }); } } }
29.190476
104
0.61093
cdfbe408d241dcdd148e79b066603e55c2951f3e
191
package io.clickhandler.web.reactGwt.client.event; import jsinterop.annotations.JsFunction; /** * */ @JsFunction public interface FocusEventHandler { void handle(FocusEvent event); }
15.916667
50
0.764398
5d5b2abbef6fc30afd0690b367b5ac7431ceb20d
1,027
package com.eligible.exception; import lombok.Getter; /** * Invalid or Incomplete request exception. */ public class InvalidRequestException extends EligibleException { private static final long serialVersionUID = 1L; /** * Param name. */ @Getter private final String param; /** * Create InvalidRequestException. * * @param message message */ public InvalidRequestException(String message) { this(message, null); } /** * Create InvalidRequestException. * * @param message message * @param param param name */ public InvalidRequestException(String message, String param) { super(message); this.param = param; } /** * Create InvalidRequestException. * * @param message message * @param param param name * @param e cause */ public InvalidRequestException(String message, String param, Throwable e) { super(message, e); this.param = param; } }
20.137255
79
0.618306
cff3416e629543836c85fe676cea1c67d66f9721
8,330
/* * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package texture.spi; import java.io.*; import java.net.*; import com.jogamp.opengl.GLProfile; import texture.TextureData; /** Plug-in interface to TextureIO to support reading OpenGL textures from new file formats. For all methods, either internalFormat or pixelFormat may be 0 in which case they must be inferred as e.g. RGB or RGBA depending on the file contents. */ public interface TextureProvider { /** * Produces a TextureData object from a file, or returns null if the * file format was not supported by this TextureProvider. Does not * do any OpenGL-related work. The resulting TextureData can be * converted into an OpenGL texture in a later step. * * @param glp the OpenGL Profile this texture data should be * created for. * @param file the file from which to read the texture data * * @param internalFormat the OpenGL internal format to be used for * the texture, or 0 if it should be inferred * from the file's contents * * @param pixelFormat the OpenGL pixel format to be used for * the texture, or 0 if it should be inferred * from the file's contents * * @param mipmap whether mipmaps should be produced for this * texture either by autogenerating them or * reading them from the file. Some file formats * support multiple mipmaps in a single file in * which case those mipmaps will be used rather * than generating them. * * @param fileSuffix the file suffix to be used as a hint to the * provider to more quickly decide whether it * can handle the file, or null if the * provider should infer the type from the * file's contents * * @throws IOException if an error occurred while reading the file */ public TextureData newTextureData(GLProfile glp, File file, int internalFormat, int pixelFormat, boolean mipmap, String fileSuffix) throws IOException; /** * Produces a TextureData object from a stream, or returns null if * the file format was not supported by this TextureProvider. Does * not do any OpenGL-related work. The resulting TextureData can be * converted into an OpenGL texture in a later step. * * @param glp the OpenGL Profile this texture data should be * created for. * @param stream the stream from which to read the texture data * * @param internalFormat the OpenGL internal format to be used for * the texture, or 0 if it should be inferred * from the file's contents * * @param pixelFormat the OpenGL pixel format to be used for * the texture, or 0 if it should be inferred * from the file's contents * * @param mipmap whether mipmaps should be produced for this * texture either by autogenerating them or * reading them from the file. Some file formats * support multiple mipmaps in a single file in * which case those mipmaps will be used rather * than generating them. * * @param fileSuffix the file suffix to be used as a hint to the * provider to more quickly decide whether it * can handle the file, or null if the * provider should infer the type from the * file's contents * * @throws IOException if an error occurred while reading the stream */ public TextureData newTextureData(GLProfile glp, InputStream stream, int internalFormat, int pixelFormat, boolean mipmap, String fileSuffix) throws IOException; /** * Produces a TextureData object from a URL, or returns null if the * file format was not supported by this TextureProvider. Does not * do any OpenGL-related work. The resulting TextureData can be * converted into an OpenGL texture in a later step. * * @param glp the OpenGL Profile this texture data should be * created for. * @param url the URL from which to read the texture data * * @param internalFormat the OpenGL internal format to be used for * the texture, or 0 if it should be inferred * from the file's contents * * @param pixelFormat the OpenGL pixel format to be used for * the texture, or 0 if it should be inferred * from the file's contents * * @param mipmap whether mipmaps should be produced for this * texture either by autogenerating them or * reading them from the file. Some file formats * support multiple mipmaps in a single file in * which case those mipmaps will be used rather * than generating them. * * @param fileSuffix the file suffix to be used as a hint to the * provider to more quickly decide whether it * can handle the file, or null if the * provider should infer the type from the * file's contents * * @throws IOException if an error occurred while reading the URL */ public TextureData newTextureData(GLProfile glp, URL url, int internalFormat, int pixelFormat, boolean mipmap, String fileSuffix) throws IOException; }
48.430233
76
0.597599
c460f316a427f3c8cf7b27f2f268d1eb880e7b64
4,263
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.internal.xjc.generator.bean; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import com.sun.codemodel.internal.JClass; import com.sun.codemodel.internal.JCodeModel; import com.sun.codemodel.internal.JExpr; import com.sun.codemodel.internal.JExpression; import com.sun.codemodel.internal.JFieldVar; import com.sun.codemodel.internal.JInvocation; import com.sun.codemodel.internal.JMethod; import com.sun.codemodel.internal.JMod; import com.sun.codemodel.internal.JType; import com.sun.tools.internal.xjc.model.CElementInfo; import com.sun.tools.internal.xjc.outline.Aspect; import com.sun.tools.internal.xjc.outline.ElementOutline; /** * {@link ElementOutline} implementation. * * @author Kohsuke Kawaguchi */ final class ElementOutlineImpl extends ElementOutline { private final BeanGenerator parent; public BeanGenerator parent() { return parent; } /*package*/ ElementOutlineImpl(BeanGenerator parent, CElementInfo ei) { super(ei, parent.getClassFactory().createClass( parent.getContainer( ei.parent, Aspect.EXPOSED ), ei.shortName(), ei.getLocator() )); this.parent = parent; parent.elements.put(ei,this); JCodeModel cm = parent.getCodeModel(); implClass._extends( cm.ref(JAXBElement.class).narrow( target.getContentInMemoryType().toType(parent,Aspect.EXPOSED).boxify())); if(ei.hasClass()) { JType implType = ei.getContentInMemoryType().toType(parent,Aspect.IMPLEMENTATION); JExpression declaredType = JExpr.cast(cm.ref(Class.class),implType.boxify().dotclass()); // why do we have to cast? JClass scope=null; if(ei.getScope()!=null) scope = parent.getClazz(ei.getScope()).implRef; JExpression scopeClass = scope==null?JExpr._null():scope.dotclass(); JFieldVar valField = implClass.field(JMod.PROTECTED|JMod.FINAL|JMod.STATIC,QName.class,"NAME",createQName(cm,ei.getElementName())); // take this opportunity to generate a constructor in the element class JMethod cons = implClass.constructor(JMod.PUBLIC); cons.body().invoke("super") .arg(valField) .arg(declaredType) .arg(scopeClass) .arg(cons.param(implType,"value")); // generate no-arg constructor in the element class (bug #391; section 5.6.2 in JAXB spec 2.1) JMethod noArgCons = implClass.constructor(JMod.PUBLIC); noArgCons.body().invoke("super") .arg(valField) .arg(declaredType) .arg(scopeClass) .arg(JExpr._null()); } } /** * Generates an expression that evaluates to "new QName(...)" */ private JInvocation createQName(JCodeModel codeModel,QName name) { return JExpr._new(codeModel.ref(QName.class)).arg(name.getNamespaceURI()).arg(name.getLocalPart()); } }
40.6
143
0.685902
0240ed6d93b4355f47b4b1fbc550b2b4e1650100
2,145
package seleniumBasics; import io.github.bonigarcia.wdm.WebDriverManager; import java.lang.Thread; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ElementVisibilityTest { public static void main(String[] args) throws InterruptedException { // using WebDriverManager to setup chrome diver instead of System.setProperty(). WebDriverManager.chromedriver().setup(); WebDriver chrome = new ChromeDriver(); // maximize window & delete all cookies. chrome.manage().window().maximize(); chrome.manage().deleteAllCookies(); // dynamic wait added. chrome.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); chrome.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // open URL. chrome.get("https://getbootstrap.com/docs/5.0/components/buttons/"); // isDisplayed() - It is suitable for all elements. It is used to verify the presence of WebElement. boolean b1 = chrome.findElement(By.xpath("//button[@class='btn btn-lg btn-primary' and text()='Primary button']")).isDisplayed(); System.out.println("Is the button displayed : " + b1); // isEnabled() - it is mostly used to check if a button is enabled or not. boolean b2 = chrome.findElement(By.xpath("//button[@class='btn btn-lg btn-primary' and text()='Primary button']")).isEnabled(); System.out.println("Is the button enabled : " + b2); // move to a different URL. Thread.sleep(3000); chrome.navigate().to("https://getbootstrap.com/docs/5.0/forms/checks-radios/"); // isSelected() - It is only applicable for checkboxes, radiobuttons and dropdowns. It checks if these elements are selected or not. boolean b3 = chrome.findElement(By.xpath("//input[@id='flexCheckDefault']")).isSelected(); System.out.println("Is the checkbox selected : " + b3); boolean b4 = chrome.findElement(By.xpath("//input[@id='flexCheckChecked']")).isSelected(); System.out.println("Is another checkbox selected : " + b4); // close the browser after 5 seconds. Thread.sleep(5000); chrome.quit(); } }
38.303571
134
0.719347
87fdc7649231cd7a5383db6bdeb17c846e5db143
3,610
/** * Copyright 2012 Cloudera Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.hadoop.hdfs.nfs.nfs4; import java.io.IOException; import java.net.InetAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.ietf.jgss.GSSManager; import com.cloudera.hadoop.hdfs.nfs.nfs4.requests.CompoundRequest; import com.cloudera.hadoop.hdfs.nfs.nfs4.responses.CompoundResponse; import com.cloudera.hadoop.hdfs.nfs.rpc.RPCServer; import com.cloudera.hadoop.hdfs.nfs.security.SecurityConfiguration; import com.cloudera.hadoop.hdfs.nfs.security.SecurityHandlerFactory; import com.cloudera.hadoop.hdfs.nfs.security.SessionSecurityHandlerGSSFactory; import com.google.common.base.Supplier; /** * Class used to start the NFS Server. Uses NFS4Handler * and RPCServer to start the server and then blocks * until the RPCServer has died. Implements Configured * so it can be configured from the command line. */ public class NFS4Server extends Configured implements Tool { NFS4Handler mNFSServer; RPCServer<CompoundRequest, CompoundResponse> mRPCServer; static{ Configuration.addDefaultResource("hdfs-nfs-site.xml"); } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); SecurityConfiguration secConf = new SecurityConfiguration(conf); secConf.configure(); System.exit(ToolRunner.run(conf, new NFS4Server(), args)); } public int getPort() { return mRPCServer.getPort(); } public boolean isAlive() { return mRPCServer.isAlive(); } @Override public int run(String[] args) throws Exception { int port; try { port = Integer.parseInt(args[0]); } catch(Exception e) { System.err.println(this.getClass().getName() + " port"); GenericOptionsParser.printGenericCommandUsage(System.err); return 1; } start(null, port); while(mRPCServer.isAlive()) { Thread.sleep(10000L); } return 0; } public void shutdown() throws IOException { mRPCServer.interrupt(); mRPCServer.shutdown(); mNFSServer.shutdown(); } public void start(InetAddress address, int port) throws IOException { SecurityHandlerFactory securityHandlerFactory = new SecurityHandlerFactory(getConf(), new Supplier<GSSManager>() { @Override public GSSManager get() { return GSSManager.getInstance(); } }, new SessionSecurityHandlerGSSFactory()); mNFSServer = new NFS4Handler(getConf(),securityHandlerFactory); mRPCServer = new RPCServer<CompoundRequest, CompoundResponse>(mNFSServer, getConf(), securityHandlerFactory, address, port); mRPCServer.start(); } }
34.056604
128
0.740443
96b2326e3175925817bf1f137caf8287fe613e9d
3,442
/* * Copyright (c) 2017-2021 Hugo Dupanloup (Yeregorix) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.smoofyuniverse.common.util; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.control.Hyperlink; import javafx.scene.text.TextAlignment; import javafx.scene.text.TextFlow; import net.smoofyuniverse.common.platform.OperatingSystem; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; public class TextUtil { public static TextFlow justify(double lineLength, Node... children) { TextFlow t = new TextFlow(children); t.setTextAlignment(TextAlignment.JUSTIFY); t.setPrefWidth(lineLength); return t; } public static TextFlow justify(Node... children) { TextFlow t = new TextFlow(children); t.setTextAlignment(TextAlignment.JUSTIFY); return t; } public static TextFlow join(double lineLength, Node... children) { TextFlow t = new TextFlow(children); t.setPrefWidth(lineLength); return t; } public static TextFlow join(Node... children) { return new TextFlow(children); } public static Hyperlink openLink(String text, String link) { Hyperlink l = openLink(link); l.setText(text); return l; } public static Hyperlink openLink(String link) { try { return openLink(new URI(link)); } catch (URISyntaxException e) { return new Hyperlink(); } } public static Hyperlink openLink(URI link) { Hyperlink l = new Hyperlink(); l.setOnAction(e -> OperatingSystem.CURRENT.browse(link)); return l; } public static Hyperlink openLink(ObservableValue<String> text, String link) { Hyperlink l = openLink(link); l.textProperty().bind(text); return l; } public static Hyperlink openLink(String text, URL link) { Hyperlink l = openLink(link); l.setText(text); return l; } public static Hyperlink openLink(URL link) { try { return openLink(link.toURI()); } catch (URISyntaxException e) { return new Hyperlink(); } } public static Hyperlink openLink(ObservableValue<String> text, URL link) { Hyperlink l = openLink(link); l.textProperty().bind(text); return l; } public static Hyperlink openLink(String text, URI link) { Hyperlink l = openLink(link); l.setText(text); return l; } public static Hyperlink openLink(ObservableValue<String> text, URI link) { Hyperlink l = openLink(link); l.textProperty().bind(text); return l; } }
28.92437
81
0.738524
ee0296590db005ff362b2b3fccecd4812546546b
1,133
package com.wym.springboot01.ESbean; import org.springframework.data.elasticsearch.annotations.Document; import java.io.Serializable; /** * * @author yongmao.wu * */ @Document(indexName = "testgoods",type = "goods") //indexName索引名称 可以理解为数据库名 必须为小写 不然会报org.elasticsearch.indices.InvalidIndexNameException异常 //type类型 可以理解为表名 public class GoodsInfo implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Long id; private String name; private String description; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public GoodsInfo(Long id, String name, String description) { this.id = id; this.name = name; this.description = description; } public GoodsInfo() { } }
19.877193
89
0.647838
ef3f759a91e01e897e51f3a30bd90f7d680076b4
543
package com.mkmonkey.sell.service; import com.mkmonkey.sell.Bo.ProductCategory; import com.mkmonkey.sell.dto.CartDTO; import java.util.List; /** * @Class Name: ProductCategoryService * @Description: TODO * @Company bgy: MK monkey * @create: 2018-01-25 20:23 **/ public interface ProductCategoryService { ProductCategory findOne(Integer categoryId); List<ProductCategory> findAll(); List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList); ProductCategory save(ProductCategory productCategory); }
23.608696
79
0.764273
576b66bd24332946dc8681a30f278a3a255e4626
1,482
package com.hjq.http.model; import com.hjq.http.EasyConfig; import java.util.HashMap; import java.util.Set; /** * author : Android 轮子哥 * github : https://github.com/getActivity/EasyHttp * time : 2019/07/20 * desc : 请求参数封装 */ public final class HttpParams { private HashMap<String, Object> mParams = EasyConfig.getInstance().getParams(); /** 是否有流参数 */ private boolean mMultipart; public void put(String key, Object value) { if (key != null && value != null) { if (mParams == EasyConfig.getInstance().getParams()) { mParams = new HashMap<>(mParams); } mParams.put(key, value); } } public void remove(String key) { if (key != null) { if (mParams == EasyConfig.getInstance().getParams()) { mParams = new HashMap<>(mParams); } mParams.remove(key); } } public Object get(String key) { return mParams.get(key); } public boolean isEmpty() { return mParams == null || mParams.isEmpty(); } public Set<String> getNames() { return mParams.keySet(); } public HashMap<String, Object> getParams() { return mParams; } public boolean isMultipart() { return mMultipart; } public void setMultipart(boolean multipart) { mMultipart = multipart; } }
23.903226
84
0.544534
3b0bf15c933ca4e7dafadaa80b995af97f624bbc
10,241
package com.benefitj.mybatisplus.aop; import com.alibaba.fastjson.JSON; import com.benefitj.core.EventLoop; import com.benefitj.core.TimeUtils; import com.benefitj.core.local.LocalCache; import com.benefitj.core.local.LocalCacheFactory; import com.benefitj.mybatisplus.controller.vo.HttpResult; import com.benefitj.mybatisplus.model.SysLogEntity; import com.benefitj.mybatisplus.service.SysLogService; import com.benefitj.spring.ServletUtils; import com.benefitj.spring.aop.AopAdvice; import com.benefitj.spring.aop.web.WebPointCutHandler; import com.benefitj.spring.mvc.matcher.AntPathRequestMatcher; import com.benefitj.spring.mvc.matcher.OrRequestMatcher; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 日志保存 */ @Slf4j @Component public class SysLogHandler implements InitializingBean, WebPointCutHandler { @Autowired private SysLogService logService; /** * 管理切面类和方法 */ private final LogManager logManager = new LogManager(); /** * 缓存日志信息 */ private final LocalCache<SysLogEntity> cache = LocalCacheFactory.newCache(SysLogEntity::new); private OrRequestMatcher matcher; @Value("#{@environment['spring.aop.operation-log.save'] ?: false}") private boolean save; /** * 是否支持GET请求 */ @Value("#{@environment['spring.aop.operation-log.ignore-get'] ?: true}") private boolean ignoreGet; /** * 操作日志 */ @Value("#{@environment['spring.aop.operation-log.ignore-urls'] ?: ''}") private String ignoreUrls; @Override public void afterPropertiesSet() throws Exception { if (StringUtils.isNotBlank(ignoreUrls)) { String[] split = ignoreUrls.split(","); matcher = new OrRequestMatcher( Stream.of(split) .map(String::trim) .filter(StringUtils::isNotBlank) .map(AntPathRequestMatcher::new) .collect(Collectors.toList()) ); } } /** * 方法执行之前 * * @param joinPoint 方法切入点 */ @Override public void doBefore(AopAdvice advice, JoinPoint joinPoint) { if (!support(joinPoint)) { return; } MethodInfo mi = getMethodInfo(joinPoint); // 开始记录 SysLogEntity sle = cache.get(); sle.setCreateTime(new Date()); /*JwtToken token = JwtTokenManager.currentToken(true); if (token != null) { sle.setOrgId(token.getOrgId()); sle.setCreatorId(token.getUserId()); }*/ // 模块 sle.setModule(mi.getModule()); // 操作 sle.setOpDesc(mi.getOperation()); HttpServletRequest req = getRequest(); Object[] args = joinPoint.getArgs(); List<Object> argList = new ArrayList<>(args.length); for (Object arg : args) { if (arg instanceof ServletRequest) { argList.add("req"); } else if (arg instanceof ServletResponse) { argList.add("response"); } else if (arg instanceof MultipartFile) { MultipartFile f = (MultipartFile) arg; argList.add("file: " + String.format("(%s, %d)", f.getOriginalFilename(), f.getSize())); } else if (arg instanceof MultipartFile[]) { argList.add("files: " + Arrays.stream(((MultipartFile[]) arg)) .map(f -> String.format("(%s, %d)", f.getOriginalFilename(), f.getSize())) .collect(Collectors.joining(", "))); } else { argList.add(arg); } } // 保存请求参数 Method method = mi.getMethod(); if (method.getParameterCount() > 0 && argList.size() == method.getParameterCount()) { Parameter[] parameters = method.getParameters(); Map<String, Object> parameterMap = new LinkedHashMap<>(); for (int i = 0; i < parameters.length; i++) { parameterMap.put(parameters[i].getName(), argList.get(i)); } sle.setParameters(JSON.toJSONString(parameterMap)); } else { sle.setParameters(""); } // URI sle.setUrl(req.getRequestURI()); // IP sle.setIpAddr(ServletUtils.getIp(req)); // METHOD sle.setHttpMethod(req.getMethod()); // 方法名 sle.setClassMethod(method.getDeclaringClass().getSimpleName() + "." + method.getName()); } @Override public void doAfter(AopAdvice advice, JoinPoint joinPoint, AtomicReference<Object> returnValue) { if (!support(joinPoint)) { return; } // 成功返回 SysLogEntity sle = cache.get(); if (returnValue.get() instanceof HttpResult) { // 返回 HttpResult HttpResult r = (HttpResult) returnValue.get(); sle.setResult(r.getMsg()); sle.setStatusCode(r.getCode()); } else { HttpServletResponse resp = getResponse(); sle.setResult("SUCCESS"); sle.setStatusCode(resp.getStatus()); } } @Override public void doAfterThrowing(AopAdvice advice, JoinPoint joinPoint, Throwable ex) { if (!support(joinPoint)) { return; } // 抛异常了 SysLogEntity sle = cache.get(); sle.setResult(ex.getMessage()); sle.setStatusCode(500); } @Override public void doAfterReturning(AopAdvice advice, JoinPoint joinPoint) { if (!support(joinPoint)) { return; } // 保存 final SysLogEntity sle = cache.getAndRemove(); sle.setElapsed(TimeUtils.diffNow(sle.getCreateTime().getTime())); EventLoop.io().execute(() -> { try { logService.insert(sle); } catch (Throwable ex) { log.error("保存操作日志失败: {}", ex.getMessage()); } }); } private MethodInfo getMethodInfo(JoinPoint joinPoint) { return logManager.getMethodInfo(joinPoint); } public boolean support(JoinPoint joinPoint) { if (!save) { return false; } HttpServletRequest request = getRequest(); if (request != null) { // 不支持GET,且是GET请求 if (ignoreGet && HttpMethod.GET.matches(request.getMethod())) { return false; } if (matcher != null) { return !matcher.matches(request); } } MethodInfo mi = getMethodInfo(joinPoint); return mi.isSupport(); } /** * 解析并缓存切面中调用过的Class及其Method信息,方便之后直接获取 */ static final class LogManager { /** * 存储解析的ClassInfo */ private final Map<Class<?>, ClassInfo> classInfoMap = new ConcurrentHashMap<>(); /** * 解析Method的信息 * * @param point 切入点 * @return 返回MethodInfo */ public MethodInfo getMethodInfo(JoinPoint point) { ClassInfo classInfo = getClassInfo(point); Method method = ((MethodSignature) point.getSignature()).getMethod(); return parseMethodInfo(classInfo, method); } private MethodInfo parseMethodInfo(ClassInfo classInfo, Method method) { MethodInfo methodInfo = classInfo.getMethodInfo(method); if (methodInfo != null) { return methodInfo; } methodInfo = new MethodInfo(method); // 设置模块名 methodInfo.setModule(classInfo.getName()); if (method.isAnnotationPresent(ApiOperation.class)) { ApiOperation ap = getAnnotation(method, ApiOperation.class); // 操作 methodInfo.setOperation(ap.value()); // 描述 methodInfo.setRemarks(ap.notes()); } classInfo.addMethodInfo(method, methodInfo); methodInfo.setSupport(true); return methodInfo; } /** * 解析Class的信息 */ private ClassInfo getClassInfo(JoinPoint point) { Class clazz = point.getSignature().getDeclaringType(); ClassInfo classInfo = classInfoMap.get(clazz); if (classInfo == null) { // 解析Class类 classInfo = new ClassInfo(); classInfo.setClazz(clazz); Api api = getAnnotation(clazz, Api.class); if (api != null) { classInfo.setName(api.tags()[0]); } classInfoMap.put(clazz, classInfo); } return classInfo; } private <A extends Annotation> A getAnnotation(AnnotatedElement obj, Class<A> annotationClass) { return obj.getAnnotation(annotationClass); } } /** * 类信息 */ @NoArgsConstructor @AllArgsConstructor @Data static final class ClassInfo { /** * 声明的类 */ private Class clazz; /** * 方法 */ private final Map<Method, MethodInfo> methodInfoMap = new ConcurrentHashMap<>(); /** * 模块名 */ private String name; @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(Object obj) { return clazz.equals(obj); } public void addMethodInfo(Method method, MethodInfo info) { methodInfoMap.put(method, info); } public MethodInfo getMethodInfo(Method method) { return methodInfoMap.get(method); } } /** * 方法信息 */ @NoArgsConstructor @AllArgsConstructor @Data static final class MethodInfo { private Method method; /** * 模块 */ private String module; /** * 操作 */ private String operation; /** * 描述 */ private String remarks; /** * 是否支持 */ private boolean support = false; public MethodInfo(Method method) { this.method = method; } public <T extends Annotation> T[] getAnnotations(Class<T> annotationClass) { return getMethod().getAnnotationsByType(annotationClass); } } }
27.164456
100
0.657065
6d5a7091b91bfce87dead1d0545429aff473582a
1,601
// Copyright (c) 2003-2012, Jodd Team (jodd.org). All Rights Reserved. package jodd.typeconverter; import jodd.typeconverter.impl.IntegerArrayConverter; import org.junit.Test; import static jodd.typeconverter.TypeConverterTestHelper.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class IntegerArrayConverterTest { @Test public void testConversion() { IntegerArrayConverter integerArrayConverter = (IntegerArrayConverter) TypeConverterManager.lookup(int[].class); assertNull(integerArrayConverter.convert(null)); assertEq(arri(173, 234), integerArrayConverter.convert("173, 234")); assertEq(arri(173), integerArrayConverter.convert(Double.valueOf(173))); assertEq(arri(1, 7, 3), integerArrayConverter.convert(arri(1, 7, 3))); assertEq(arri(1, 7, 3), integerArrayConverter.convert(arrl(1, 7, 3))); assertEq(arri(1, 7, 3), integerArrayConverter.convert(arrf(1, 7, 3))); assertEq(arri(1, 7, 3), integerArrayConverter.convert(arrd(1.1, 7.99, 3))); assertEq(arri(173, 1022), integerArrayConverter.convert(arrs("173", "1022"))); assertEq(arri(173, 10), integerArrayConverter.convert(arro("173", Integer.valueOf(10)))); assertEq(arri(111, 777, 333), integerArrayConverter.convert(arrs("111", " 777 ", "333"))); assertEq(arri(111, 777, 333), integerArrayConverter.convert("111, 777, 333")); } private void assertEq(int[] arr1, int[] arr2) { assertEquals(arr1.length, arr2.length); for (int i = 0; i < arr1.length; i++) { assertEquals(arr1[i], arr2[i]); } } }
37.232558
114
0.709557
2c1cef4e7bc44c213d5d824f9837ca9f97d5d4dc
3,097
package com.winterwell.bob.tasks; import java.io.File; import java.util.ArrayList; import java.util.List; import com.winterwell.bob.Bob; import com.winterwell.bob.BobConfig; import com.winterwell.bob.BuildTask; import com.winterwell.utils.StrUtils; import com.winterwell.utils.io.FileUtils; import com.winterwell.utils.log.Log; import com.winterwell.utils.time.TUnit; /** * This task runs a child Bob in a separate Java process * * FIXME It does not preserve the file settings * Maybe send an xstream aml blob via a temp file?? * * @author daniel * @testedby ForkJVMTaskTest */ public class ForkJVMTask extends BuildTask { /** * NB: String 'cos the class might not be on the classpath for this JVM */ final String target; public ForkJVMTask(Class<? extends BuildTask> target) { this(target.getName()); } public ForkJVMTask() { this(""); // find it! } public ForkJVMTask(String target) { this.target = target; // odds are, you don't need to repeat these every time setSkipGap(TUnit.HOUR.dt); } Classpath classpath = Classpath.getSystemClasspath(); public ForkJVMTask setDir(File dir) { this.dir = dir; return this; } /** * working dir for task */ private File dir; public Classpath getClasspath() { return classpath; } public void setClasspath(Classpath classpath) { this.classpath = classpath; } @Override protected void doTask() throws Exception { // TODO pass on Bob settings like -clean // BUT we dont want to rebuild utils n times in one build -- so use cleanBefore List<String> options = new ArrayList(); BobConfig config = Bob.getSingleton().getConfig(); if (config.cleanBefore != null) { options.add("-cleanBefore "+config.cleanBefore.getTime()); } else if (config.clean) { options.add("-cleanBefore "+Bob.getRunStart().getTime()); } if (config.ignoreAllExceptions) { options.add("-ignore "+config.ignoreAllExceptions); } options.add("-label "+config.label); options.add("-depth "+(config.depth+1)); if (config.maxDepth > 0) { options.add("-maxDepth "+config.maxDepth); } String soptions = StrUtils.join(options, " ")+" "; String command = "java -cp "+classpath+" com.winterwell.bob.Bob " +soptions +target; Log.d(LOGTAG, "fork "+target+" Full command: "+command); // child call to Bob ProcessTask proc = null; try { proc = new ProcessTask(command); if (maxTime!=null) proc.setMaxTime(maxTime); proc.setDirectory(dir); proc.setEcho(true); Log.i(LOGTAG, "Child-Bob: "+proc.getCommand()+" \r\n[in dir "+dir+"]"); proc.run(); Log.d(LOGTAG, "Success: "+command+" [in dir "+dir+"]"); // for debug - what did it try to build? // String out = proc.getOutput(); // #bob Auto-build: found file /home/daniel/winterwell/open-code/winterwell.utils/builder/com/winterwell/bob/wwjobs/BuildUtils.java // maybe the child bob did some tasks for us :( Bob.loadTaskHistory(); } finally { long pid = proc.getProcessID(); FileUtils.close(proc); // paranoia Log.d(LOGTAG, "closed process "+pid); } } }
26.245763
133
0.682273
92d89a0a04819f7031666a7b8db1964ddf487b6a
2,888
/* * Copyright 2021 - 2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.sbm.actions.spring.xml.migration; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.MethodSpec; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import javax.lang.model.element.Modifier; @Component @RequiredArgsConstructor public class GenericBeanHandler implements BeanHandler { private final Helper helper; private final BeanPropertySetterStatementFactory beanPropertySetterStatementFactory; private final BeanConstructorCallFactory beanConstructorCallFactory; @Override public MethodSpec createBeanDefinitionMethod(MigrationContext migrationContext, XmlBeanDef xmlBeanDefinition) throws ClassNotFoundException { String methodName = Helper.calculateMethodName(xmlBeanDefinition.getName()); MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(methodName) .addAnnotation(Bean.class) .addModifiers(Modifier.PUBLIC); String beanClassName = xmlBeanDefinition.getBeanDefinition().getBeanClassName(); String beanVariableName = Helper.calculateVariableName(xmlBeanDefinition);// firstToLower(beanClassName); CodeBlock constructorCallStatement = beanConstructorCallFactory.createConstructorCall(migrationContext, beanVariableName, xmlBeanDefinition.getBeanDefinition(), beanClassName); CodeBlock beanInitStatements = beanPropertySetterStatementFactory.createSetterCalls(migrationContext, beanVariableName, xmlBeanDefinition.getBeanDefinition(), xmlBeanDefinition); CodeBlock methodBody = CodeBlock.builder() .addStatement(constructorCallStatement) .add(beanInitStatements) .addStatement(CodeBlock.of("return " + beanVariableName)) .build(); Class<?> returnType = migrationContext.getClass(xmlBeanDefinition.getBeanDefinition().getBeanClassName()); // Class<?> returnType = Class.forName(beanDefinition.getBeanDefinition().getBeanClassName()); methodSpec .returns(returnType) .addCode(methodBody); return methodSpec.build(); } }
43.757576
186
0.74446
81714c7542a370a96f8baa7c0bf1ef41e41749eb
3,633
package edu.ucla.cs.process.extension; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Map; import org.apache.commons.lang3.tuple.MutablePair; import edu.ucla.cs.mine.ExtendedPatternMiner; import edu.ucla.cs.model.APISeqItem; import edu.ucla.cs.utils.FileUtils; public class BatchMiner { public static void main(String[] args) { // Config this first!!! boolean isContinueRun = true; // boolean start = false; String rootPath = "/media/troy/Disk2/Boa/apis"; File rootDir = new File(rootPath); for(File apiDir : rootDir.listFiles()) { String name = apiDir.getName(); // if(name.equals("PreparedStatement.setString")) { // start = true; // } // // if(!start) { // continue; // } if(name.equals("File.mkdir") || name.equals("Activity.setContentView") // || name.equals("SimpleDateFormat.SimpleDateFormat") // || name.equals("StringBuilder.append") // || name.equals("String.indexOf") // || name.equals("Pattern.matcher") || name.equals("String.substring") // || name.equals("String.getBytes") // || name.equals("String.replaceAll") || name.equals("SortedMap.firstKey") // || name.equals("Matcher.group") // || name.equals("Map.put") // || name.equals("PreparedStatement.setString") // || name.equals("Integer.parseInt") || name.equals("Toast.makeText")){ continue; } if(!name.equals("ByteBuffer.get")) { continue; } String boa_raw = apiDir.getAbsolutePath() + File.separator + "1-clean.txt"; String processed = apiDir.getAbsolutePath() + File.separator + "large-output-resolved.txt"; File file1 = new File(boa_raw); File file2 = new File(processed); if(!file1.exists() || !file2.exists()) { continue; } if(isContinueRun && new File(apiDir.getAbsolutePath() + File.separator + "patterns.txt").exists()) { continue; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date) + " start mining for " + apiDir); String[] ss = name.split("\\."); String className = ss[0]; String methodName; if(ss.length == 2) { methodName = ss[1]; } else { methodName = ss[2]; } ArrayList<String> classNames = new ArrayList<String>(); for(String s : className.split("-")) { classNames.add(s); } ArrayList<String> methodNames = new ArrayList<String>(); for(String s : methodName.split("-")) { if(classNames.contains(s)) { s = "new " + s; } methodNames.add(s); } HashSet<HashSet<String>> queries = new HashSet<HashSet<String>>(); HashSet<String> q1 = new HashSet<String>(); q1.addAll(methodNames); queries.add(q1); int size = FileUtils.countLines(processed); double sigma = 0.2; double theta = 0.2; long startTime = System.currentTimeMillis(); Map<ArrayList<APISeqItem>, MutablePair<Double, Double>> patterns = ExtendedPatternMiner.mine( boa_raw, processed, queries, sigma, size, theta); long estimatedTime = System.currentTimeMillis() - startTime; if(patterns.size() != 0) { String s = "Total Code Examples: " + size + System.lineSeparator(); s += "Mining time (millis) : " + estimatedTime + System.lineSeparator(); for (ArrayList<APISeqItem> sp : patterns.keySet()) { s += sp + ":" + patterns.get(sp) + System.lineSeparator(); } FileUtils.writeStringToFile(s, apiDir.getAbsolutePath() + File.separator + "patterns.txt"); } } } }
31.051282
103
0.645472
ae284687d197870dea669cb8e1f5956c709198b0
2,035
/* * Copyright (C) 2020 Wigo Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.moara.translate.example; import org.moara.translate.IntoKoreanTranslate; import org.moara.translate.TranslateResult; import org.moara.translate.detect.KoreanLanguageDetection; /** * @author macle */ public class IntoKoreanTranslateExample { public static void main(String[] args) { String text ="離地鐵站超級近而且一號出口有手扶梯\n" + "不管是要去機場還是要去各個景點都很方便\n" + "一進飯店就聞到舒服的香味\n" + "因為疫情關係\n" + "只要進飯店就會量體溫\n" + "飯店職員也很盡責把關\n" + "對面就是弘大商圈\n" + "要逛街買東西有相當方便\n" + "如果買東西太重也能先拿回飯店放\uD83D\uDE02\n" + "21樓就可換錢且匯率蠻好的\n" + "還有提供行李秤\n" + "房間裡的床蠻舒服的\n" + "空間雖然有點小但五臟具全\n" + "該有的都有\n" + "除了每天都有補礦泉水外\n" + "走廊也有飲水機"; // System.out.println(Remove); TranslateResult translateResult = IntoKoreanTranslate.translation(text); System.out.println(KoreanLanguageDetection.isKorean(text) ); //번역여부 if(translateResult.isTranslate()){ //번역됨 //한국어이면 번영되지않음 System.out.println("번역됨"); }else{ System.out.println("한국어"); } System.out.println("감지언어코드: " + translateResult.getLangCodeDetection() +", 번역언어코드: " +translateResult.getLangCodeTranslate() +", 번역내용: " + translateResult.getTranslate() ); } }
33.916667
180
0.608845
90b1182bd4de6456920f4d854e79284aae3ed56f
14,309
/* * Copyright 2020-2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package com.google.cloud.healthcare.fdamystudies.common; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.verify; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.matching.ContainsPattern; import com.google.cloud.healthcare.fdamystudies.beans.AuditLogEventRequest; import com.google.cloud.healthcare.fdamystudies.config.CommonModuleConfiguration; import com.google.cloud.healthcare.fdamystudies.config.WireMockInitializer; import com.google.cloud.healthcare.fdamystudies.service.AuditEventService; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.ServletContext; import javax.servlet.http.Cookie; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInfo; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.http.HttpHeaders; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @ContextConfiguration(initializers = {WireMockInitializer.class}) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @ActiveProfiles("mockit") @TestPropertySource({ "classpath:application-mockit.properties", "classpath:application-mockit-common.properties" }) @ComponentScan(basePackages = {"com.google.cloud.healthcare.fdamystudies"}) public class BaseMockIT { private XLogger logger = XLoggerFactory.getXLogger(BaseMockIT.class.getName()); protected static final String VALID_BEARER_TOKEN = "Bearer 7fd50c2c-d618-493c-89d6-f1887e3e4bb8"; protected static final String VALID_TOKEN = "7fd50c2c-d618-493c-89d6-f1887e3e4bb8"; protected static final String INVALID_BEARER_TOKEN = "Bearer cd57710c-1d19-4058-8bfe-a6aac3a39e35"; protected static final String INVALID_TOKEN = "cd57710c-1d19-4058-8bfe-a6aac3a39e35"; protected static final String AUTH_CODE_VALUE = "28889b79-d7c6-4fe3-990c-bd239c6ce199"; protected static final ResultMatcher OK = status().isOk(); protected static final ResultMatcher BAD_REQUEST = status().isBadRequest(); protected static final ResultMatcher UNAUTHORIZED = status().isUnauthorized(); protected static final ResultMatcher CREATED = status().isCreated(); protected static final ResultMatcher NOT_FOUND = status().isNotFound(); @Autowired private WireMockServer wireMockServer; @Autowired protected MockMvc mockMvc; @Autowired protected ServletContext servletContext; @Autowired protected AuditEventService mockAuditService; @Autowired protected JavaMailSender emailSender; @Autowired private TestRestTemplate restTemplate; protected List<AuditLogEventRequest> auditRequests = new ArrayList<>(); @LocalServerPort int randomServerPort; @PostConstruct public void logServerPort() { logger.debug(String.format("server port=%d", randomServerPort)); } protected WireMockServer getWireMockServer() { return wireMockServer; } protected String getContextPath() { return servletContext.getContextPath(); } protected String getEncodedAuthorization(String clientId, String clientSecret) { String credentials = clientId + ":" + clientSecret; return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes()); } protected MvcResult performGet( String path, HttpHeaders headers, String expectedTextInResponseBody, ResultMatcher httpStatusMatcher, Cookie... cookies) throws Exception { MockHttpServletRequestBuilder reqBuilder = get(path).contextPath(servletContext.getContextPath()).headers(headers); if (cookies.length > 0) { reqBuilder.cookie(cookies); } return mockMvc .perform(reqBuilder) .andDo(print()) .andExpect(httpStatusMatcher) .andExpect(content().string(containsString(expectedTextInResponseBody))) .andReturn(); } protected MvcResult performPost( String path, String requestBody, HttpHeaders headers, String expectedTextInResponseBody, ResultMatcher httpStatusMatcher, Cookie... cookies) throws Exception { MockHttpServletRequestBuilder reqBuilder = post(path) .contextPath(servletContext.getContextPath()) .content(requestBody) .headers(headers); if (cookies.length > 0) { reqBuilder.cookie(cookies); } return mockMvc .perform(reqBuilder) .andDo(print()) .andExpect(httpStatusMatcher) .andExpect(content().string(containsString(expectedTextInResponseBody))) .andReturn(); } /** * @param assertOptionalFieldsForEvent is a {@link Map} collection that contains {@link eventCode} * as key and {@link AuditLogEventRequest} with optional field values as value. * @param auditEvents audit event enums */ protected void verifyAuditEventCall( Map<String, AuditLogEventRequest> assertOptionalFieldsForEvent, AuditLogEvent... auditEvents) { verifyAuditEventCall(auditEvents); Map<String, AuditLogEventRequest> auditRequestByEventCode = auditRequests .stream() .collect(Collectors.toMap(AuditLogEventRequest::getEventCode, Function.identity())); assertOptionalFieldsForEvent.forEach( (eventCode, expectedAuditRequest) -> { AuditLogEventRequest auditRequest = auditRequestByEventCode.get(eventCode); assertEquals(expectedAuditRequest.getUserId(), auditRequest.getUserId()); assertEquals(expectedAuditRequest.getParticipantId(), auditRequest.getParticipantId()); assertEquals(expectedAuditRequest.getStudyId(), auditRequest.getStudyId()); assertEquals(expectedAuditRequest.getStudyVersion(), auditRequest.getStudyVersion()); }); } protected void verifyAuditEventCall(AuditLogEvent... auditEvents) { ArgumentCaptor<AuditLogEventRequest> argument = ArgumentCaptor.forClass(AuditLogEventRequest.class); verify(mockAuditService, atLeastOnce()).postAuditLogEvent(argument.capture()); Map<String, AuditLogEventRequest> auditRequestByEventCode = auditRequests .stream() .collect(Collectors.toMap(AuditLogEventRequest::getEventCode, Function.identity())); for (AuditLogEvent auditEvent : auditEvents) { AuditLogEventRequest auditRequest = auditRequestByEventCode.get(auditEvent.getEventCode()); assertEquals(auditEvent.getEventCode(), auditRequest.getEventCode()); if (auditEvent.getDestination() != null) { assertEquals(auditEvent.getDestination().getValue(), auditRequest.getDestination()); } // Use enum value where specified, otherwise, use 'source' header value. if (auditEvent.getSource().isPresent()) { assertEquals(auditEvent.getSource().get().getValue(), auditRequest.getSource()); } else if (StringUtils.isNotEmpty(auditRequest.getSource())) { PlatformComponent platformComponent = PlatformComponent.fromValue(auditRequest.getSource()); assertNotNull(platformComponent); } if (auditEvent.getResourceServer().isPresent()) { assertEquals( auditEvent.getResourceServer().get().getValue(), auditRequest.getResourceServer()); } if (auditEvent.getUserAccessLevel().isPresent()) { assertEquals( auditEvent.getUserAccessLevel().get().getValue(), auditRequest.getUserAccessLevel()); } assertFalse( StringUtils.contains(auditRequest.getDescription(), "{") && StringUtils.contains(auditRequest.getDescription(), "}")); assertNotNull(auditRequest.getCorrelationId()); assertNotNull(auditRequest.getOccurred()); assertNotNull(auditRequest.getPlatformVersion()); assertNotNull(auditRequest.getAppId()); assertNotNull(auditRequest.getAppVersion()); assertNotNull(auditRequest.getMobilePlatform()); } } protected void clearAuditRequests() { auditRequests.clear(); } protected void verifyDoesNotContain(String text, String... searchValues) { for (String value : searchValues) { assertFalse(StringUtils.contains(text, value)); } } @BeforeEach void setUp(TestInfo testInfo) { logger.entry(String.format("TEST STARTED: %s", testInfo.getDisplayName())); WireMock.resetAllRequests(); Mockito.reset(mockAuditService); auditRequests.clear(); doAnswer( invocation -> auditRequests.add( SerializationUtils.clone((AuditLogEventRequest) invocation.getArguments()[0]))) .when(mockAuditService) .postAuditLogEvent(Mockito.any(AuditLogEventRequest.class)); WireMock.resetAllRequests(); } @AfterEach void tearDown(TestInfo testInfo) { logger.exit(String.format("TEST FINISHED: %s", testInfo.getDisplayName())); } @TestConfiguration @Import(CommonModuleConfiguration.class) static class BaseMockITConfiguration {} protected void verifyTokenIntrospectRequest() { verifyTokenIntrospectRequest(1); } protected void verifyTokenIntrospectRequest(int times) { verify( times, postRequestedFor(urlEqualTo("/auth-server/oauth2/introspect")) .withRequestBody(new ContainsPattern(VALID_TOKEN))); } protected MimeMessage verifyMimeMessage( String toEmail, String fromEmail, String subject, String body) throws MessagingException, IOException { ArgumentCaptor<MimeMessage> mailCaptor = ArgumentCaptor.forClass(MimeMessage.class); verify(emailSender, atLeastOnce()).send(mailCaptor.capture()); MimeMessage mail = mailCaptor.getValue(); assertThat(mail.getFrom()).containsExactly(new InternetAddress(fromEmail)); assertThat(mail.getRecipients(Message.RecipientType.TO)) .containsExactly(new InternetAddress(toEmail)); assertThat(mail.getRecipients(Message.RecipientType.CC)).isNull(); assertThat(mail.getSubject()).isEqualToIgnoringCase(subject); assertThat(mail.getContent().toString()).contains(body); assertThat(mail.getDataHandler().getContentType()) .isEqualToIgnoringCase("text/html; charset=utf-8"); return mail; } protected String generateApiDocs() throws IOException { // get swagger json String apiDocs = this.restTemplate.getForObject("/v2/api-docs", String.class); // format the json ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); ObjectNode jsonObjNode = mapper.readValue(apiDocs, ObjectNode.class); jsonObjNode.put("host", "localhost:8080"); // prepare the filepath String documentPath = Paths.get("").toAbsolutePath().toString(); if (StringUtils.contains(documentPath, "fda-mystudies")) { documentPath = documentPath.substring(0, documentPath.indexOf("fda-mystudies")) + "fda-mystudies/documentation/API"; } documentPath += servletContext.getContextPath() + "/openapi.json"; documentPath = documentPath.replace(" ", "_"); // write api-docs json to a file FileUtils.write(new File(documentPath), jsonObjNode.toPrettyString(), Charset.defaultCharset()); logger.info(String.format("Open API documentation created at %s", documentPath)); return documentPath; } }
38.568733
100
0.756657
d5dfe9ef2235769485e81c18895fc7ea98dbc231
3,381
/** * */ package com.inc.user.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.inc.user.model.User; /** * @author Ananthan * */ @Controller public class LoginController { @RequestMapping(value = "/", method = RequestMethod.GET) public String onEntry(Model model, HttpServletRequest request) { User user = new User(); return "Login"; } @RequestMapping(value = "/welcome", method = RequestMethod.GET) public String defaultPage(Model model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String welcomeMessage = "Welcome "+authentication.getName()+"!!"; model.addAttribute("title", "Spring Security Login Form - Database Authentication"); model.addAttribute("message", "This is default page!"); return "hello"; } @RequestMapping("/error") public String error(Model model) { model.addAttribute("error", "true"); return "Login"; } @RequestMapping("/403") @ResponseBody public String accessDenied(Model model) { model.addAttribute("error", "true"); return "Access Denied page"; } @RequestMapping("/logout") public String logout(Model model){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); authentication.setAuthenticated(false); model.addAttribute("logout", "true"); return "Login"; } @RequestMapping(value = "/readFile", method = RequestMethod.GET) @ResponseBody public String readFile(Model model) { return "Read File completed"; } /*@RequestMapping(value = "/admin**", method = RequestMethod.GET) public ModelAndView adminPage() { ModelAndView model = new ModelAndView(); model.addObject("title", "Spring Security Login Form - Database Authentication"); model.addObject("message", "This page is for ROLE_ADMIN only!"); model.setViewName("admin"); return model; }*/ /* @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login(@RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView(); if (error != null) { model.addObject("error", "Invalid username and password!"); } if (logout != null) { model.addObject("msg", "You've been logged out successfully."); } model.setViewName("login"); return model; }*/ //for 403 access denied page /*@RequestMapping(value = "/403", method = RequestMethod.GET) public ModelAndView accesssDenied() { ModelAndView model = new ModelAndView(); //check if user is login Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { UserDetails userDetail = (UserDetails) auth.getPrincipal(); model.addObject("username", userDetail.getUsername()); } model.setViewName("403"); return model; }*/ }
29.146552
95
0.713398
acb5046f608e405c64d727547034bc0195197b21
7,262
package org.wso2.developerstudio.eclipse.capp.maven.utils; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.maven.model.Parent; import org.apache.maven.model.Repository; import org.apache.maven.project.MavenProject; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.wso2.developerstudio.eclipse.capp.core.artifacts.manager.CAppEnvironment; import org.wso2.developerstudio.eclipse.capp.maven.Activator; import org.wso2.developerstudio.eclipse.capp.maven.IMavenPluginContributorProvider; import org.wso2.developerstudio.eclipse.capp.maven.MavenPluginContributor; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.maven.util.MavenUtils; import org.wso2.developerstudio.eclipse.utils.file.FileUtils; public class MavenPomGenPluginUtils { private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID); private static final String MAVEN_DEFINITION_HANDLER_EXTENSION = "org.wso2.developerstudio.eclipse.capp.maven.artifact.mavenplugin.generator"; private static Map<String, MavenPluginContributor> archeTypeDefinitions; static { loadMavenDefinitionExtensionPoint(); } public static Map<String, String> getArtifactTypeExtensionMap() { Map<String, MavenPluginContributor> pluginContributors=getPluginContributors(); Map<String, String> artifactTypeExtensionMap = new HashMap<String, String>(); for (MavenPluginContributor contributor : pluginContributors.values()) { artifactTypeExtensionMap.put(contributor.getArtifactType(), contributor.getExtension()); } return artifactTypeExtensionMap; } public static Map<String, MavenPluginContributor> getPluginContributors() { if (archeTypeDefinitions == null) { archeTypeDefinitions = new HashMap<String, MavenPluginContributor>(); } return archeTypeDefinitions; } private static void loadMavenDefinitionExtensionPoint() { getPluginContributors().clear(); IConfigurationElement[] config = Platform .getExtensionRegistry() .getConfigurationElementsFor(MAVEN_DEFINITION_HANDLER_EXTENSION); for (IConfigurationElement e : config) { try { if (e.getName().equals("plugin")) { MavenPluginContributor mavenPluginContributor = new MavenPluginContributor(); String id = e.getAttribute("id"); String type = e.getAttribute("type"); String extension = e.getAttribute("extension"); IMavenPluginContributorProvider provider = (IMavenPluginContributorProvider) e .createExecutableExtension("class"); mavenPluginContributor.setArtifactType(type); mavenPluginContributor.setExtension(extension); mavenPluginContributor.setId(id); mavenPluginContributor.setProvider(provider); getPluginContributors().put(type, mavenPluginContributor); } } catch (Exception ex) { log.error("Error loading extension point element: " + e.getName(), ex); } } } public static void updateAndSaveMavenCAppProject(MavenProject cappBuildMavenProject,IProject eclipseProject, File projectPOM, String parentPomArtifactId) throws Exception{ //Buid the CAR Repository repo = new Repository(); repo.setUrl("http://dist.wso2.org/maven2"); repo.setId("wso2-maven2-repository-1"); cappBuildMavenProject.getModel().addRepository(repo); // Modified the name to different value to support maven 3 Repository repo1 = new Repository(); repo1.setUrl("http://dist.wso2.org/maven2"); repo1.setId("wso2-maven2-plugin-repository-1"); cappBuildMavenProject.getModel().addPluginRepository(repo1); Map<String, MavenPluginContributor> pluginContributors = MavenPomGenPluginUtils.getPluginContributors(); Map<String, String> artifactTypeExtensionMap = MavenPomGenPluginUtils.getArtifactTypeExtensionMap(); for (MavenPluginContributor contributor : pluginContributors.values()) { contributor.getProvider().addMavenPlugin(cappBuildMavenProject, eclipseProject, artifactTypeExtensionMap); } File cAppBuilderMavenProjectLocation = CAppEnvironment.getcAppManager().getCAppBuilderMavenProjectLocation(eclipseProject).getLocation().toFile(); //Build the JAR File mavenProjectSaveLocation=CAppEnvironment.getcAppManager().getJarBuilderMavenProjectLocation(eclipseProject).getLocation().toFile(); mavenProjectSaveLocation.getParentFile().mkdirs(); MavenProject jarBuildMavenProject; if (mavenProjectSaveLocation.exists()){ jarBuildMavenProject = MavenUtils.updateMavenProjectWithJarBuilderPlugin(eclipseProject, MavenUtils.getMavenProject(mavenProjectSaveLocation), mavenProjectSaveLocation); }else{ jarBuildMavenProject = MavenUtils.updateMavenProjectWithJarBuilderPlugin(eclipseProject, cappBuildMavenProject.getGroupId(), eclipseProject.getName()+".jarbuilder", "1.0.0", mavenProjectSaveLocation); } //Build the parent File mavenRootPomSaveLocation = CAppEnvironment.getcAppManager().getCAppParentBuilderMavenProjectLocation(eclipseProject).getLocation().toFile(); MavenProject rootMavenProject=null; if(!mavenRootPomSaveLocation.exists()){ rootMavenProject = MavenUtils.createMavenProject(cappBuildMavenProject.getGroupId(), parentPomArtifactId, "1.0.0", "pom"); }else{ rootMavenProject = MavenUtils.getMavenProject(mavenRootPomSaveLocation); } MavenUtils.addMavenModulesToMavenProject(rootMavenProject, mavenRootPomSaveLocation, new File[] {cAppBuilderMavenProjectLocation, mavenProjectSaveLocation}); //Set parent pom & target directories File parentTargetDir = new File(mavenRootPomSaveLocation.getParentFile(),"target"); Parent parent = new Parent(); parent.setGroupId(rootMavenProject.getGroupId()); parent.setArtifactId(rootMavenProject.getArtifactId()); parent.setVersion(rootMavenProject.getVersion()); cappBuildMavenProject.getModel().setParent(parent); cappBuildMavenProject.getBuild().setDirectory(FileUtils.getRelativePath(cAppBuilderMavenProjectLocation.getParentFile(),parentTargetDir)+"/capp"); jarBuildMavenProject.getModel().setParent(parent); jarBuildMavenProject.getBuild().setDirectory(FileUtils.getRelativePath(mavenProjectSaveLocation.getParentFile(),parentTargetDir)+"/jar"); MavenUtils.saveMavenProject(cappBuildMavenProject, cAppBuilderMavenProjectLocation); MavenUtils.saveMavenProject(jarBuildMavenProject, mavenProjectSaveLocation); MavenUtils.saveMavenProject(rootMavenProject, mavenRootPomSaveLocation); eclipseProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } public static MavenProject createMavenCAppProject(String groupId, String artifactId, String version,String packagingType,IProject eclipseProject,File projectPOM, String parentPomArtifactId) throws CoreException, Exception{ MavenProject selectedProject= MavenUtils.createMavenProject(groupId, artifactId, version, packagingType); updateAndSaveMavenCAppProject(selectedProject, eclipseProject, projectPOM, parentPomArtifactId); return selectedProject; } }
47.776316
223
0.809694
634b61936bd4732accd7f6f0f8b0d67750433c92
4,700
package de.fraunhofer.iem.secucheck.InternalFluentTQL.ValidCases.tests; import de.fraunhofer.iem.secucheck.InternalFluentTQL.dsl.MethodSet; import de.fraunhofer.iem.secucheck.InternalFluentTQL.dsl.QueriesSet; import de.fraunhofer.iem.secucheck.InternalFluentTQL.fluentInterface.FluentTQLSpecification; import de.fraunhofer.iem.secucheck.InternalFluentTQL.fluentInterface.InputOutput.*; import de.fraunhofer.iem.secucheck.InternalFluentTQL.fluentInterface.MethodPackage.Method; import de.fraunhofer.iem.secucheck.InternalFluentTQL.fluentInterface.Query.TaintFlowQuery; import de.fraunhofer.iem.secucheck.InternalFluentTQL.fluentInterface.TaintFlowPackage.FlowParticipant; import de.fraunhofer.iem.secucheck.InternalFluentTQL.fluentInterface.TaintFlowPackage.TaintFlow; import java.util.List; public class PrintTaintFlowForDebugging { private void displayMethod(Method method) { System.out.println("\t" + method.getSignature()); if (method.getInputDeclaration() != null && method.getInputDeclaration().getInputs() != null) { List<Input> inputs = method.getInputDeclaration().getInputs(); System.out.println("\t\tInputDeclaration : " + inputs.size()); for (Input input : inputs) { if (input instanceof Parameter) { System.out.println("\t\t\tParameter " + ((Parameter) input).getParameterId()); } else if (input instanceof ThisObject) { System.out.println("\t\t\tThisObject"); } } } if (method.getOutputDeclaration() != null && method.getOutputDeclaration().getOutputs() != null) { List<Output> outputs = method.getOutputDeclaration().getOutputs(); System.out.println("\t\tOutputDeclaration : " + outputs.size()); for (Output output : outputs) { if (output instanceof Parameter) { System.out.println("\t\t\tParameter " + ((Parameter) output).getParameterId()); } else if (output instanceof ThisObject) { System.out.println("\t\t\tThisObject"); } else if (output instanceof Return) { System.out.println("\t\t\tReturnValue"); } } } } private void displayFlowParticipant(FlowParticipant flowParticipant) { if (flowParticipant instanceof Method) { displayMethod((Method) flowParticipant); } else if (flowParticipant instanceof MethodSet) { for (Method method : ((MethodSet) flowParticipant).getMethods()) { displayMethod(method); } } } private void displayTaintFlowQuery(TaintFlowQuery taintFlowQuery) { System.out.println("Report Message = " + taintFlowQuery.getReportMessage()); System.out.println("Report Location = " + taintFlowQuery.getReportLocation()); List<TaintFlow> taintFlows = taintFlowQuery.getTaintFlows(); for (TaintFlow taintFlow : taintFlows) { if (taintFlow.getFrom() != null) { System.out.println("Source : "); displayFlowParticipant(taintFlow.getFrom()); } if (taintFlow.getNotThrough() != null) { System.out.println("Required Propagator : "); for (FlowParticipant flowParticipant : taintFlow.getThrough()) { displayFlowParticipant(flowParticipant); } } if (taintFlow.getThrough() != null) { for (FlowParticipant flowParticipant : taintFlow.getNotThrough()) { System.out.println("Sanitizer : "); displayFlowParticipant(flowParticipant); } } if (taintFlow.getTo() != null) { System.out.println("Sink : "); displayFlowParticipant(taintFlow.getTo()); } } } // Use this to print the FluentTQL Specifications for debugging public void printFluentTQLSpecifications(List<FluentTQLSpecification> fluentTQLSpecifications) { for (FluentTQLSpecification fluentTQLSpecification : fluentTQLSpecifications) { if (fluentTQLSpecification instanceof TaintFlowQuery) { displayTaintFlowQuery((TaintFlowQuery) fluentTQLSpecification); } else if (fluentTQLSpecification instanceof QueriesSet) { for (TaintFlowQuery taintFlowQuery : ((QueriesSet) fluentTQLSpecification).getTaintFlowQueries()) { displayTaintFlowQuery(taintFlowQuery); } } } } }
45.631068
115
0.628723