hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1c302f7d5d4c773e51bf1b718bd157b53d662f | 374 | java | Java | src/main/java/com/alexrnv/calcite/adapter/pilosa/commons/Timer.java | alex-rnv/calcite-pilosa | 7e4e239154d6cd63dc8a007d75a42146f71e28cf | [
"Apache-2.0"
] | 2 | 2020-07-01T07:38:56.000Z | 2020-07-21T02:45:52.000Z | src/main/java/com/alexrnv/calcite/adapter/pilosa/commons/Timer.java | alex-rnv/calcite-pilosa | 7e4e239154d6cd63dc8a007d75a42146f71e28cf | [
"Apache-2.0"
] | 1 | 2022-02-16T01:12:17.000Z | 2022-02-16T01:12:17.000Z | src/main/java/com/alexrnv/calcite/adapter/pilosa/commons/Timer.java | alex-rnv/calcite-pilosa | 7e4e239154d6cd63dc8a007d75a42146f71e28cf | [
"Apache-2.0"
] | null | null | null | 20.777778 | 54 | 0.657754 | 11,947 | package com.alexrnv.calcite.adapter.pilosa.commons;
public class Timer {
private final long startTime;
private Timer(long startTime) {
this.startTime = startTime;
}
public static Timer start() {
return new Timer(System.currentTimeMillis());
}
public long elapsed() {
return System.currentTimeMillis() - startTime;
}
}
|
3e1c3106a785fd099e6641c063f9778e4d7c090d | 1,203 | java | Java | Test.java | pokeguys/ITP4510_Assignment | c5be1667d0cdebb7ba82ca63552fe143d1917547 | [
"MIT"
] | null | null | null | Test.java | pokeguys/ITP4510_Assignment | c5be1667d0cdebb7ba82ca63552fe143d1917547 | [
"MIT"
] | null | null | null | Test.java | pokeguys/ITP4510_Assignment | c5be1667d0cdebb7ba82ca63552fe143d1917547 | [
"MIT"
] | null | null | null | 27.976744 | 56 | 0.627598 | 11,948 | package testPackage;
import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
class Test {
public static void main(String[] args) {
byte b = 100;
short s = 10000;
int i = 100000;
int hexVal = 0x1a;
int binVal = 0b11010;
double d1 = 123.4;
double d2 = 1.234e2;
float f1 = 123.4f;
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;
String a = "test";
char a = 't';
String a = "test + test = testtest?";
char a = '\u0108';
String hello = "Hello", lo = "lo";
String a = "test\"\"test";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("H;e;l"+lo).intern());
if (hello && null || null)
System.out.println(0x00FF00FF + " " + 3_1_415);
}
}
class Other { static String hello = "Hello", $a = "Bye";
int _b = 999;}
|
3e1c314405adf386d06ec8746325db6616d02ef7 | 4,255 | java | Java | core/src/test/java/org/dozer/functional_tests/builder/CollectionWithNullTest.java | smuryginim/dozer | 43862ab41d54faf8c52ee3715a64685bdfef469b | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/dozer/functional_tests/builder/CollectionWithNullTest.java | smuryginim/dozer | 43862ab41d54faf8c52ee3715a64685bdfef469b | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/dozer/functional_tests/builder/CollectionWithNullTest.java | smuryginim/dozer | 43862ab41d54faf8c52ee3715a64685bdfef469b | [
"Apache-2.0"
] | null | null | null | 23.379121 | 87 | 0.647474 | 11,949 | package org.dozer.functional_tests.builder;
import org.dozer.DozerBeanMapper;
import org.dozer.DozerConverter;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.TypeMappingOptions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.hamcrest.CoreMatchers.equalTo;
/**
* @author dmitry buzdin
* @since 09.10.2011
*/
public class CollectionWithNullTest extends Assert {
private DozerBeanMapper mapper;
private Foo foo;
private Bar bar;
@Before
public void setUp() {
mapper = new DozerBeanMapper(Collections.singletonList("collectionsWithNull.xml"));
foo = new Foo();
bar = new Bar();
}
@Test
public void shouldMapNullAsListFirstElement() {
mapper.addMapping(new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Foo.class, Bar.class, TypeMappingOptions.mapNull(false))
.fields("wheeIds", "wheeList");
}
});
bar.getWheeList().add(null);
bar.getWheeList().add(new Whee("1"));
Foo result = mapper.map(bar, Foo.class);
assertThat(result.getWheeIds().size(), equalTo(1));
assertThat(result.getWheeIds().get(0), equalTo("1"));
}
@Test
public void shouldMapNullAsListSecondElement() {
mapper.addMapping(new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Foo.class, Bar.class, TypeMappingOptions.mapNull(false))
.fields("wheeIds", "wheeList");
}
});
bar.getWheeList().add(new Whee("1"));
bar.getWheeList().add(null);
Foo result = mapper.map(bar, Foo.class);
assertThat(result.getWheeIds().size(), equalTo(1));
assertThat(result.getWheeIds().get(0), equalTo("1"));
}
@Test
public void shouldMapNullAsSetSecondElement() {
mapper.addMapping(new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Foo.class, Bar.class, TypeMappingOptions.mapNull(false))
.fields("wheeIds", "wheeSet");
}
});
bar.getWheeSet().add(new Whee("1"));
bar.getWheeSet().add(null);
Foo result = mapper.map(bar, Foo.class);
assertThat(result.getWheeIds().size(), equalTo(1));
assertThat(result.getWheeIds().get(0), equalTo("1"));
}
@Test
public void shouldMapNullAsSetSecondElement_Reverse() {
mapper.addMapping(new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(Foo.class, Bar.class, TypeMappingOptions.mapNull(false))
.fields("wheeIds", "wheeSet");
}
});
foo.getWheeIds().add("1");
foo.getWheeIds().add(null);
Bar result = mapper.map(foo, Bar.class);
assertThat(result.getWheeSet().size(), equalTo(1));
assertThat(result.getWheeSet().iterator().next().getId(), equalTo("1"));
}
public static class Foo {
List<String> wheeIds = new ArrayList<String>();
public List<String> getWheeIds() {
return wheeIds;
}
public void setWheeIds(List<String> wheeIds) {
this.wheeIds = wheeIds;
}
}
public static class Bar {
List<Whee> wheeList = new ArrayList<Whee>();
Set<Whee> wheeSet = new HashSet<Whee>();
public List<Whee> getWheeList() {
return wheeList;
}
public void setWheeList(List<Whee> wheeList) {
this.wheeList = wheeList;
}
public Set<Whee> getWheeSet() {
return wheeSet;
}
public void setWheeSet(Set<Whee> wheeSet) {
this.wheeSet = wheeSet;
}
}
public static class Whee {
String id;
public Whee(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public static class WheeConverter extends DozerConverter<String, Whee> {
public WheeConverter() {
super(String.class, Whee.class);
}
@Override
public Whee convertTo(String source, Whee destination) {
return new Whee(source);
}
@Override
public String convertFrom(Whee source, String destination) {
return source.getId();
}
}
}
|
3e1c317949d2b5c2deac30816e3438b13914b0fc | 4,235 | java | Java | src/main/java/org/elasticsearch/common/util/LongHash.java | Acidburn0zzz/elasticsearch | e0fbd5df52449d7caeb7eeb7392a595d35b10ef3 | [
"Apache-2.0"
] | 1 | 2019-12-17T02:19:11.000Z | 2019-12-17T02:19:11.000Z | src/main/java/org/elasticsearch/common/util/LongHash.java | Acidburn0zzz/elasticsearch | e0fbd5df52449d7caeb7eeb7392a595d35b10ef3 | [
"Apache-2.0"
] | 1 | 2021-06-04T03:02:56.000Z | 2021-06-04T03:02:56.000Z | src/main/java/org/elasticsearch/common/util/LongHash.java | Acidburn0zzz/elasticsearch | e0fbd5df52449d7caeb7eeb7392a595d35b10ef3 | [
"Apache-2.0"
] | null | null | null | 31.604478 | 124 | 0.595277 | 11,950 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.common.util;
import org.elasticsearch.common.lease.Releasables;
/**
* Specialized hash table implementation similar to BytesRefHash that maps
* long values to ids. Collisions are resolved with open addressing and linear
* probing, growth is smooth thanks to {@link BigArrays} and capacity is always
* a multiple of 2 for faster identification of buckets.
* This class is not thread-safe.
*/
// IDs are internally stored as id + 1 so that 0 encodes for an empty slot
public final class LongHash extends AbstractHash {
private LongArray keys;
// Constructor with configurable capacity and default maximum load factor.
public LongHash(long capacity, BigArrays bigArrays) {
this(capacity, DEFAULT_MAX_LOAD_FACTOR, bigArrays);
}
//Constructor with configurable capacity and load factor.
public LongHash(long capacity, float maxLoadFactor, BigArrays bigArrays) {
super(capacity, maxLoadFactor, bigArrays);
keys = bigArrays.newLongArray(capacity, false);
}
/**
* Return the key at <code>0 <e; index <e; capacity()</code>. The result is undefined if the slot is unused.
*/
public long get(long id) {
return keys.get(id);
}
/**
* Get the id associated with <code>key</code>
*/
public long find(long key) {
final long slot = slot(hash(key), mask);
for (long index = slot; ; index = nextSlot(index, mask)) {
final long id = id(index);
if (id == -1 || keys.get(id) == key) {
return id;
}
}
}
private long set(long key, long id) {
assert size < maxSize;
final long slot = slot(hash(key), mask);
for (long index = slot; ; index = nextSlot(index, mask)) {
final long curId = id(index);
if (curId == -1) { // means unset
id(index, id);
append(id, key);
++size;
return id;
} else if (keys.get(curId) == key) {
return -1 - curId;
}
}
}
private void append(long id, long key) {
keys = bigArrays.grow(keys, id + 1);
keys.set(id, key);
}
private void reset(long key, long id) {
final long slot = slot(hash(key), mask);
for (long index = slot; ; index = nextSlot(index, mask)) {
final long curId = id(index);
if (curId == -1) { // means unset
id(index, id);
append(id, key);
break;
}
}
}
/**
* Try to add <code>key</code>. Return its newly allocated id if it wasn't in the hash table yet, or </code>-1-id</code>
* if it was already present in the hash table.
*/
public long add(long key) {
if (size >= maxSize) {
assert size == maxSize;
grow();
}
assert size < maxSize;
return set(key, size);
}
@Override
protected void removeAndAdd(long index) {
final long id = id(index, -1);
assert id >= 0;
final long key = keys.set(id, 0);
reset(key, id);
}
@Override
public boolean release() {
boolean success = false;
try {
super.release();
success = true;
} finally {
Releasables.release(success, keys);
}
return true;
}
}
|
3e1c31a70c8c352387c5c4d85f54aff202060769 | 292 | java | Java | src/distributed/file/system/MessageNotFoundException.java | gavrilaopris/Proiect-DFS | 2c65ca6836696481f4a1a5288d9d5afa0d6d58cc | [
"MIT"
] | null | null | null | src/distributed/file/system/MessageNotFoundException.java | gavrilaopris/Proiect-DFS | 2c65ca6836696481f4a1a5288d9d5afa0d6d58cc | [
"MIT"
] | null | null | null | src/distributed/file/system/MessageNotFoundException.java | gavrilaopris/Proiect-DFS | 2c65ca6836696481f4a1a5288d9d5afa0d6d58cc | [
"MIT"
] | null | null | null | 17.176471 | 57 | 0.729452 | 11,951 | package distributed.file.system;
public class MessageNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
private int[] msgNum = null;
public int[] getMsgNum() {
return msgNum;
}
public void setMsgNum(int[] msgNum) {
this.msgNum = msgNum;
}
}
|
3e1c31d896d78a2a79cbccf22b084dd2a852844a | 353 | java | Java | src/main/java/com/harambase/pioneer/server/dao/repository/TempCourseRepository.java | harambase/pioneer | 4be3abc5b227bba6de8d5ff16ab225095483e40a | [
"MIT"
] | null | null | null | src/main/java/com/harambase/pioneer/server/dao/repository/TempCourseRepository.java | harambase/pioneer | 4be3abc5b227bba6de8d5ff16ab225095483e40a | [
"MIT"
] | 10 | 2017-11-14T07:17:05.000Z | 2021-12-09T20:17:40.000Z | src/main/java/com/harambase/pioneer/server/dao/repository/TempCourseRepository.java | harambase/pioneer | 4be3abc5b227bba6de8d5ff16ab225095483e40a | [
"MIT"
] | null | null | null | 32.090909 | 82 | 0.835694 | 11,952 | package com.harambase.pioneer.server.dao.repository;
import com.harambase.pioneer.server.pojo.base.TempCourse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TempCourseRepository extends JpaRepository<TempCourse, Integer> {
int countById(Integer id);
}
|
3e1c33f31be9778e756ab0c9f9ff21045f3bc21c | 3,471 | java | Java | user-service/src/main/java/net/explorviz/security/server/main/Application.java | ExplorViz/explorviz-backend | 7cd4b189797a5f0117bab0d33834aea8237cd321 | [
"Apache-2.0"
] | 5 | 2018-12-11T07:47:36.000Z | 2022-02-05T12:21:19.000Z | user-service/src/main/java/net/explorviz/security/server/main/Application.java | ExplorViz/explorviz-backend | 7cd4b189797a5f0117bab0d33834aea8237cd321 | [
"Apache-2.0"
] | 84 | 2018-01-09T10:13:41.000Z | 2020-04-21T09:07:25.000Z | user-service/src/main/java/net/explorviz/security/server/main/Application.java | ExplorViz/explorviz-backend | 7cd4b189797a5f0117bab0d33834aea8237cd321 | [
"Apache-2.0"
] | 8 | 2017-12-11T22:53:28.000Z | 2021-11-14T09:39:23.000Z | 41.321429 | 94 | 0.805532 | 11,953 | package net.explorviz.security.server.main;
import net.explorviz.security.model.UserBatchRequest;
import net.explorviz.security.server.providers.GenericJsonApiPaginationWriter;
import net.explorviz.security.server.providers.UserJsonApiDeserializer;
import net.explorviz.security.server.resources.*;
import net.explorviz.security.user.Role;
import net.explorviz.security.user.User;
import net.explorviz.settings.model.UserPreference;
import net.explorviz.shared.common.jsonapi.ResourceConverterFactory;
import net.explorviz.shared.common.provider.GenericTypeFinder;
import net.explorviz.shared.common.provider.JsonApiListProvider;
import net.explorviz.shared.common.provider.JsonApiProvider;
import net.explorviz.shared.exceptions.mapper.GeneralExceptionMapper;
import net.explorviz.shared.exceptions.mapper.InvalidJsonApiResourceExceptionMapper;
import net.explorviz.shared.exceptions.mapper.UnregisteredTypeExceptionMapper;
import net.explorviz.shared.exceptions.mapper.WebApplicationExceptionMapper;
import net.explorviz.shared.querying.PaginationJsonApiWriter;
import net.explorviz.shared.querying.PaginationParameterFilter;
import net.explorviz.shared.security.filters.AuthenticationFilter;
import net.explorviz.shared.security.filters.AuthorizationFilter;
import net.explorviz.shared.security.filters.CorsResponseFilter;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
/**
* JAX-RS application. This class is responsible for registering all types of classes, e.g.,
* resource classes or exception mappers
*/
public class Application extends ResourceConfig {
/**
* JAX-RS application. This class is responsible for registering all types of classes, e.g.,
* resource classes or exception mappers
*/
public Application() { // NOPMD
GenericTypeFinder.getTypeMap().put("User", User.class);
GenericTypeFinder.getTypeMap().put("Role", Role.class);
GenericTypeFinder.getTypeMap().put("UserBatchRequest", UserBatchRequest.class);
GenericTypeFinder.getTypeMap().put("UserPreference", UserPreference.class);
// register CDI
this.register(new DependencyInjectionBinder());
// this.register(AuthenticationFilter.class);
this.register(CorsResponseFilter.class);
this.register(PaginationParameterFilter.class);
this.register(AuthenticationFilter.class);
this.register(AuthorizationFilter.class);
// exception handling (mind the order !)
this.register(InvalidJsonApiResourceExceptionMapper.class);
this.register(UnregisteredTypeExceptionMapper.class);
this.register(WebApplicationExceptionMapper.class);
this.register(GeneralExceptionMapper.class);
this.register(SetupApplicationListener.class);
// necessary for plain Json provider, e.g., messagebodyreader in TokenResource
this.register(JacksonFeature.class);
this.register(GenericJsonApiPaginationWriter.class);
this.register(UserJsonApiDeserializer.class);
this.register(PaginationJsonApiWriter.class);
this.register(JsonApiProvider.class);
this.register(JsonApiListProvider.class);
this.register(ResourceConverterFactory.class);
// register all resources
this.register(TokenResource.class);
this.register(UserResource.class);
this.register(RoleResource.class);
this.register(BatchRequestResource.class);
this.register(EntryPointResource.class);
this.packages("io.swagger.v3.jaxrs2.integration.resources");
}
}
|
3e1c34061ab1654279e319a666fd866a17c1cb69 | 1,175 | java | Java | src/main/java/com/baidubce/services/dugo/video/AlarmVideoInfoListResponse.java | ap6108/bce-sdk-java | fcd295fc5b90427e74cb43767bcbcc42a9a8d2e9 | [
"Apache-2.0"
] | 59 | 2015-07-30T08:04:17.000Z | 2022-02-24T01:17:44.000Z | src/main/java/com/baidubce/services/dugo/video/AlarmVideoInfoListResponse.java | ap6108/bce-sdk-java | fcd295fc5b90427e74cb43767bcbcc42a9a8d2e9 | [
"Apache-2.0"
] | 16 | 2017-03-30T06:05:19.000Z | 2022-03-31T20:08:30.000Z | src/main/java/com/baidubce/services/dugo/video/AlarmVideoInfoListResponse.java | ap6108/bce-sdk-java | fcd295fc5b90427e74cb43767bcbcc42a9a8d2e9 | [
"Apache-2.0"
] | 68 | 2015-09-14T04:00:50.000Z | 2022-03-24T12:49:41.000Z | 34.558824 | 118 | 0.755745 | 11,954 | /*
* Copyright 2019 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.baidubce.services.dugo.video;
import java.util.List;
import com.baidubce.model.AbstractBceResponse;
/**
* alarm video info list response
*
* @Author: shihuike
* @Date: Created in 2019-08-01 17:05
*/
public class AlarmVideoInfoListResponse extends AbstractBceResponse {
List<AlarmVideoInfo> alarmVideoInfoList;
public List<AlarmVideoInfo> getAlarmVideoInfoList() {
return alarmVideoInfoList;
}
public void setAlarmVideoInfoList(List<AlarmVideoInfo> alarmVideoInfoList) {
this.alarmVideoInfoList = alarmVideoInfoList;
}
}
|
3e1c34d8dc5e1dce97ee00cbf6f6810ece064074 | 421 | java | Java | src/main/java/com/sokolov/lang/java/importDef/ImportFromString.java | sokolyaka/decoratorsIdeaPlugin | 0820537051afdae7b01beddab0b620577f666548 | [
"MIT"
] | 1 | 2018-09-21T09:04:25.000Z | 2018-09-21T09:04:25.000Z | src/main/java/com/sokolov/lang/java/importDef/ImportFromString.java | sokolyaka/decoratorsIdeaPlugin | 0820537051afdae7b01beddab0b620577f666548 | [
"MIT"
] | null | null | null | src/main/java/com/sokolov/lang/java/importDef/ImportFromString.java | sokolyaka/decoratorsIdeaPlugin | 0820537051afdae7b01beddab0b620577f666548 | [
"MIT"
] | null | null | null | 21.05 | 51 | 0.667458 | 11,955 | package com.sokolov.lang.java.importDef;
public class ImportFromString implements IImport {
private final String fullClassPath;
public ImportFromString(String fullClassPath) {
this.fullClassPath = fullClassPath;
}
@Override
public String asString() {
return fullClassPath;
}
@Override
public String asFullDef() {
return "import " + fullClassPath + ";";
}
}
|
3e1c352d2a9745816bfff51d48e5429f2daab6c7 | 4,228 | java | Java | core/src/main/java/io/zero88/qwe/eventbus/EventListenerExecutorImpl.java | zero88/blueprint | ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b | [
"Apache-2.0"
] | 3 | 2021-07-27T15:38:40.000Z | 2022-02-16T04:09:13.000Z | core/src/main/java/io/zero88/qwe/eventbus/EventListenerExecutorImpl.java | zero88/blueprint | ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b | [
"Apache-2.0"
] | 34 | 2021-05-12T06:12:58.000Z | 2022-03-31T04:10:39.000Z | core/src/main/java/io/zero88/qwe/eventbus/EventListenerExecutorImpl.java | zero88/qwe | ee30dc3bbda7f8cfd91b00d7e9003ee16bee044b | [
"Apache-2.0"
] | null | null | null | 43.587629 | 120 | 0.663671 | 11,956 | package io.zero88.qwe.eventbus;
import io.github.zero88.exceptions.ReflectionException;
import io.github.zero88.repl.ReflectionMethod;
import io.github.zero88.utils.Functions;
import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.zero88.qwe.SharedDataLocalProxy;
import io.zero88.qwe.auth.UserInfo;
import io.zero88.qwe.eventbus.output.AnyToFuture;
import io.zero88.qwe.eventbus.refl.MethodMeta;
import io.zero88.qwe.exceptions.ImplementationError;
import io.zero88.qwe.exceptions.ServiceNotFoundException;
import io.zero88.qwe.exceptions.ServiceUnavailable;
import io.zero88.qwe.exceptions.UnsupportedException;
import lombok.Getter;
import lombok.experimental.Accessors;
@Accessors(fluent = true)
@SuppressWarnings({"rawtypes", "unchecked"})
public class EventListenerExecutorImpl implements EventListenerExecutor {
@Getter
private final EventListener listener;
@Getter
private final SharedDataLocalProxy sharedData;
EventListenerExecutorImpl(EventListener listener, SharedDataLocalProxy sharedData) {
this.listener = listener;
this.sharedData = sharedData;
}
@Override
public Future<EventMessage> execute(Message message) {
final EventMessage msg = messageConverter().from(message);
if (msg.getUserInfo() == null) {
msg.setUserInfo(UserInfo.parse(sharedData.getVertx().getOrCreateContext().getLocal(UserInfo.USER_KEY)));
}
final String addr = message.address();
debug("Received message", msg.getAction(), addr);
return sharedData.getVertx().executeBlocking(promise -> execute(msg, addr).onComplete(promise));
}
private Future<EventMessage> execute(EventMessage msg, String address) {
final EventAction action = msg.getAction();
debug("Execute", action, address, "...");
Future<EventMessage> future;
try {
final MethodMeta methodMeta = annotationProcessor().lookup(listener.getClass(), action);
future = this.securityInterceptor()
.validate(sharedData, msg, methodMeta.method())
.flatMap(i -> executeMethod(methodMeta, paramParser().extract(msg, methodMeta.params())))
.map(outputSerializer())
.onSuccess(data -> debug("Succeed when handling", action, address))
.map(data -> EventMessage.replySuccess(action, data));
} catch (ImplementationError e) {
future = Future.failedFuture(new ServiceUnavailable(e));
} catch (UnsupportedException e) {
future = Future.failedFuture(new ServiceNotFoundException(e));
} catch (IllegalArgumentException e) {
future = Future.failedFuture(e);
}
return future.onFailure(t -> debugError(action, address, t)).otherwise(t -> EventMessage.replyError(action, t));
}
private Future<Object> executeMethod(MethodMeta methodMeta, Object[] inputs) {
try {
final Object response = ReflectionMethod.execute(listener, methodMeta.method(), inputs);
return outputToFuture().stream()
.filter(h -> Functions.getOrDefault(false, () -> h.verify(methodMeta)))
.findFirst()
.orElseGet(AnyToFuture::new)
.transform(methodMeta, response);
} catch (ReflectionException e) {
return Future.failedFuture(e.getCause());
}
}
private void debug(String lifecycleMsg, EventAction action, String address) {
debug(lifecycleMsg, action, address, "");
}
private void debug(String lifecycleMsg, EventAction action, String address, String suffix) {
debug(lifecycleMsg, action, address, suffix, null);
}
private void debugError(EventAction action, String address, Throwable t) {
debug("Error when handling", action, address, "", t);
}
private void debug(String lifecycleMsg, EventAction action, String address, String suffix, Throwable t) {
listener.logger().debug(listener.decor("{} [{}][{}]{}"), lifecycleMsg, address, action, suffix, t);
}
}
|
3e1c353247e38ad090d7ca60f33fe27febb0ef89 | 806 | java | Java | ad_demo/src/main/java/com/union_test/toutiao/activity/FullScreenVideoView.java | RowgerGo/flutter_pangolin | 6ee416853f2bab3b9ef7e760821e884fd39bbc69 | [
"Apache-2.0"
] | 1 | 2020-07-01T04:01:41.000Z | 2020-07-01T04:01:41.000Z | ad_demo/src/main/java/com/union_test/toutiao/activity/FullScreenVideoView.java | RowgerGo/flutter_pangolin | 6ee416853f2bab3b9ef7e760821e884fd39bbc69 | [
"Apache-2.0"
] | null | null | null | ad_demo/src/main/java/com/union_test/toutiao/activity/FullScreenVideoView.java | RowgerGo/flutter_pangolin | 6ee416853f2bab3b9ef7e760821e884fd39bbc69 | [
"Apache-2.0"
] | null | null | null | 28.785714 | 87 | 0.728288 | 11,957 | package ad_demo.src.main.java.com.union_test.toutiao.activity;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;
public class FullScreenVideoView extends VideoView {
public FullScreenVideoView(Context context) {
super(context);
}
public FullScreenVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FullScreenVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(0, widthMeasureSpec);
int height = getDefaultSize(0, heightMeasureSpec);
setMeasuredDimension(width, height);
}
}
|
3e1c357377223604811b561d96384a92b3c83113 | 161 | java | Java | src/main/java/com/eway/payment/rapid/sdk/beans/internal/package-info.java | noojee/eway-rapid-java | 94c787c8b69ba0ec58da5123f03ca03e6f684c11 | [
"MIT"
] | 4 | 2015-08-20T23:13:48.000Z | 2019-05-24T02:52:35.000Z | src/main/java/com/eway/payment/rapid/sdk/beans/internal/package-info.java | Shlomi295/eway-rapid-java | 226ac11aa9962183159a2d0e0f2cbcc5cd868157 | [
"MIT"
] | 15 | 2015-12-17T00:17:47.000Z | 2022-01-27T00:05:02.000Z | src/main/java/com/eway/payment/rapid/sdk/beans/internal/package-info.java | Shlomi295/eway-rapid-java | 226ac11aa9962183159a2d0e0f2cbcc5cd868157 | [
"MIT"
] | 11 | 2015-10-29T04:53:07.000Z | 2021-11-10T02:08:03.000Z | 26.833333 | 74 | 0.745342 | 11,958 | /**
* This package contains internal bean definition for eWAY Rapid (used for
* sending data to Rapid).
*/
package com.eway.payment.rapid.sdk.beans.internal;
|
3e1c358da81d21b4e18750e2f33963f5872b96ce | 781 | java | Java | zheng-upms/zheng-upms-rpc-service/src/main/java/com/zheng/upms/rpc/ZhengUpmsRpcServiceApplication.java | lxlx704034204/zheng-master-diy0 | b00ba3294641cc084586be36d15428c0a96ae63a | [
"MIT"
] | null | null | null | zheng-upms/zheng-upms-rpc-service/src/main/java/com/zheng/upms/rpc/ZhengUpmsRpcServiceApplication.java | lxlx704034204/zheng-master-diy0 | b00ba3294641cc084586be36d15428c0a96ae63a | [
"MIT"
] | null | null | null | zheng-upms/zheng-upms-rpc-service/src/main/java/com/zheng/upms/rpc/ZhengUpmsRpcServiceApplication.java | lxlx704034204/zheng-master-diy0 | b00ba3294641cc084586be36d15428c0a96ae63a | [
"MIT"
] | null | null | null | 30.038462 | 92 | 0.754161 | 11,959 | package com.zheng.upms.rpc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 服务启动类
* Created by ZhangShuzheng on 2017/2/3.
*
* http://upms.zhangshuzheng.cn:1111/manage/index
* http://upms.zhangshuzheng.cn:1111/manage/index;jsessionid=vj7oxrinmgzy1kfzymrvryi4n
* http://upms.zhangshuzheng.cn:1111/sso/login
*/
public class ZhengUpmsRpcServiceApplication {
private static Logger _log = LoggerFactory.getLogger(ZhengUpmsRpcServiceApplication.class);
public static void main(String[] args) {
_log.info(">>>>> zheng-upms-rpc-service 正在启动 <<<<<");
new ClassPathXmlApplicationContext("classpath:META-INF/spring/*.xml");
_log.info(">>>>> zheng-upms-rpc-service 启动完成 <<<<<");
}
}
|
3e1c35d32d530d572d87014bec9ebfd3c4b484b7 | 2,379 | java | Java | app/src/main/java/com/aishang/app/data/model/JHotelDetailParam.java | find-happiness/android-aishang | 7fe454fddcb75d2f7de4a01a0a01925901476b43 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/aishang/app/data/model/JHotelDetailParam.java | find-happiness/android-aishang | 7fe454fddcb75d2f7de4a01a0a01925901476b43 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/aishang/app/data/model/JHotelDetailParam.java | find-happiness/android-aishang | 7fe454fddcb75d2f7de4a01a0a01925901476b43 | [
"Apache-2.0"
] | null | null | null | 19.032 | 67 | 0.736864 | 11,960 | package com.aishang.app.data.model;
/**
* /mobile/hotel/hotelDetail.ashx version: 1
*
* @author wang
*
*/
public class JHotelDetailParam {
// {hotelID:int, bGallery:int, bSelectImage:int, bRoomCat:int,
// bPriceList:int}
// checkInDate:string(yyyy-mm-dd), checkOutDate:string(yyyy-mm-dd)
// bHotelFaclilite:int, bHotelService:int, bRoomFacilite:int,
// bRoomService:int,
private int hotelID;
private int bGallery;
private int bSelectImage;
private int bRoomCat;
private int bPriceList;
private int bBase;
private String checkInDate;
private String checkOutDate;
private int bHotelFaclilite;
private int bHotelService;
private int bRoomFacilite;
private int bRoomService;
public int getbHotelFaclilite() {
return bHotelFaclilite;
}
public void setbHotelFaclilite(int bHotelFaclilite) {
this.bHotelFaclilite = bHotelFaclilite;
}
public int getbHotelService() {
return bHotelService;
}
public void setbHotelService(int bHotelService) {
this.bHotelService = bHotelService;
}
public int getbRoomFacilite() {
return bRoomFacilite;
}
public void setbRoomFacilite(int bRoomFacilite) {
this.bRoomFacilite = bRoomFacilite;
}
public int getbRoomService() {
return bRoomService;
}
public void setbRoomService(int bRoomService) {
this.bRoomService = bRoomService;
}
public int getbBase() {
return bBase;
}
public void setbBase(int bBase) {
this.bBase = bBase;
}
public String getCheckInDate() {
return checkInDate;
}
public void setCheckInDate(String checkInDate) {
this.checkInDate = checkInDate;
}
public String getCheckOutDate() {
return checkOutDate;
}
public void setCheckOutDate(String checkOutDate) {
this.checkOutDate = checkOutDate;
}
public int getHotelID() {
return hotelID;
}
public void setHotelID(int hotelID) {
this.hotelID = hotelID;
}
public int getbGallery() {
return bGallery;
}
public void setbGallery(int bGallery) {
this.bGallery = bGallery;
}
public int getbSelectImage() {
return bSelectImage;
}
public void setbSelectImage(int bSelectImage) {
this.bSelectImage = bSelectImage;
}
public int getbRoomCat() {
return bRoomCat;
}
public void setbRoomCat(int bRoomCat) {
this.bRoomCat = bRoomCat;
}
public int getbPriceList() {
return bPriceList;
}
public void setbPriceList(int bPriceList) {
this.bPriceList = bPriceList;
}
}
|
3e1c3641a948ea21a58175868fb8e8d47afa843d | 1,356 | java | Java | app/src/main/java/com/antonio/samir/wonderfulredtooth/repository/ConversationRepositoryPreferences.java | samirma/TheWonderfulRedtoothMachine | a7d70e301489b27d87b43b940980437bb9b1c313 | [
"Apache-2.0"
] | 1 | 2016-01-28T15:27:14.000Z | 2016-01-28T15:27:14.000Z | app/src/main/java/com/antonio/samir/wonderfulredtooth/repository/ConversationRepositoryPreferences.java | samirma/TheWonderfulRedtoothMachine | a7d70e301489b27d87b43b940980437bb9b1c313 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/antonio/samir/wonderfulredtooth/repository/ConversationRepositoryPreferences.java | samirma/TheWonderfulRedtoothMachine | a7d70e301489b27d87b43b940980437bb9b1c313 | [
"Apache-2.0"
] | null | null | null | 27.673469 | 97 | 0.744838 | 11,961 | package com.antonio.samir.wonderfulredtooth.repository;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.antonio.samir.wonderfulredtooth.model.Conversation;
import com.google.gson.Gson;
public class ConversationRepositoryPreferences extends ConversationRepository {
private static final Gson GSON = new Gson();
private static final String CONVERSATION = "CONVERSATION";
private Context context;
public ConversationRepositoryPreferences(final Context context) {
this.context = context;
}
@Override
public void saveConversation(final Conversation conversation) {
SharedPreferences sharedPref = ((Activity) context).getPreferences(Context.MODE_PRIVATE);
final String json = GSON.toJson(conversation);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(CONVERSATION, json);
editor.commit();
}
@Override
public Conversation getConversationById(Integer id) {
SharedPreferences sharedPref = ((Activity) context).getPreferences(Context.MODE_PRIVATE);
final String sharedPrefString = sharedPref.getString(CONVERSATION, null);
final Conversation conversation = GSON.fromJson(sharedPrefString, Conversation.class);
return conversation;
}
}
|
3e1c36e77505dda314ed9b6362e8e5fa1df3e3dd | 3,431 | java | Java | com/a/b/a/a/b/class_171.java | kabbi/local-runner-2015 | b74b6bd084986ae9dabdbc394ab5d6766d0594c8 | [
"Apache-2.0"
] | null | null | null | com/a/b/a/a/b/class_171.java | kabbi/local-runner-2015 | b74b6bd084986ae9dabdbc394ab5d6766d0594c8 | [
"Apache-2.0"
] | null | null | null | com/a/b/a/a/b/class_171.java | kabbi/local-runner-2015 | b74b6bd084986ae9dabdbc394ab5d6766d0594c8 | [
"Apache-2.0"
] | null | null | null | 27.669355 | 131 | 0.613815 | 11,962 | package com.a.b.a.a.b;
import com.a.a.a.a.class_121;
import com.a.b.a.a.e.a.class_11;
import com.a.b.a.a.e.a.class_179;
import com.codeforces.commons.io.IoUtil;
import com.codeforces.commons.reflection.Name;
import com.codeforces.commons.text.StringUtil;
import java.util.concurrent.atomic.AtomicLong;
// $FF: renamed from: com.a.b.a.a.b.n
public class class_171 {
// $FF: renamed from: a java.util.concurrent.atomic.AtomicLong
private static final AtomicLong field_691 = new AtomicLong();
// $FF: renamed from: b long
@Name("id")
private final long field_692;
// $FF: renamed from: c java.lang.String
@Name("name")
private final String field_693;
// $FF: renamed from: d long
private final long field_694 = class_121.method_792();
// $FF: renamed from: e com.a.b.a.a.e.a.f
private final class_11 field_695;
// $FF: renamed from: f boolean
private boolean field_696;
// $FF: renamed from: g java.lang.String
private String field_697;
// $FF: renamed from: h long
private long field_698;
// $FF: renamed from: i long
private long field_699;
// $FF: renamed from: j int
private int field_700;
public class_171(String var1, class_11 var2) {
this.field_692 = field_691.incrementAndGet();
this.field_693 = var1;
this.field_695 = var2;
}
// $FF: renamed from: a () long
public final long method_917() {
return this.field_692;
}
// $FF: renamed from: b () java.lang.String
public String method_918() {
return this.field_693;
}
// $FF: renamed from: c () long
public long method_919() {
return this.field_694;
}
// $FF: renamed from: d () com.a.b.a.a.e.a.f
public class_11 method_920() {
return this.field_695;
}
// $FF: renamed from: e () boolean
public boolean method_921() {
return this.field_695 instanceof class_179;
}
// $FF: renamed from: f () boolean
public boolean method_922() {
return this.field_696;
}
// $FF: renamed from: g () java.lang.String
public String method_923() {
return this.field_697;
}
// $FF: renamed from: a (java.lang.String) void
public void method_924(String var1) {
if(!this.method_921()) {
this.field_696 = true;
this.field_697 = var1;
IoUtil.closeQuietly((AutoCloseable)this.field_695);
}
}
// $FF: renamed from: h () long
public long method_925() {
return this.field_698;
}
// $FF: renamed from: a (long) void
public void method_926(long var1) {
this.field_698 = var1;
}
// $FF: renamed from: b (long) void
public void method_927(long var1) {
this.field_699 = var1;
this.field_698 -= var1;
}
// $FF: renamed from: i () int
public int method_928() {
return this.field_700;
}
// $FF: renamed from: a (int) void
public void method_929(int var1) {
this.field_700 += var1;
}
public final boolean equals(Object var1) {
return this == var1 || var1 != null && this.getClass() == var1.getClass() && this.field_692 == ((class_171)var1).field_692;
}
public final int hashCode() {
return Long.valueOf(this.field_692).hashCode();
}
public String toString() {
return StringUtil.toString(this, false, "id", "name");
}
}
|
3e1c371e2c2342b7ca27d8bd6b0cab1d5bf68fcb | 803 | java | Java | src/main/java/org/prebid/server/spring/config/bidder/model/UsersyncConfigurationProperties.java | Bugxyb/prebid-server-java | a409b1abd45acad371658967dc8c8dea67458ea4 | [
"Apache-2.0"
] | 20 | 2018-03-12T06:29:06.000Z | 2022-02-01T09:05:53.000Z | src/main/java/org/prebid/server/spring/config/bidder/model/UsersyncConfigurationProperties.java | Bugxyb/prebid-server-java | a409b1abd45acad371658967dc8c8dea67458ea4 | [
"Apache-2.0"
] | 121 | 2020-11-19T13:43:09.000Z | 2022-03-31T09:50:55.000Z | src/main/java/org/prebid/server/spring/config/bidder/model/UsersyncConfigurationProperties.java | Marfeel/prebid-server-java | f825152ee382d4074a636ddb6ede57e91e276586 | [
"Apache-2.0"
] | 50 | 2018-03-09T15:05:18.000Z | 2022-03-05T11:11:36.000Z | 17.456522 | 59 | 0.724782 | 11,963 | package org.prebid.server.spring.config.bidder.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Validated
@Data
@NoArgsConstructor
public class UsersyncConfigurationProperties {
String url;
String redirectUrl;
@NotBlank
String cookieFamilyName;
@NotBlank
String type;
@NotNull
Boolean supportCors;
SecondaryConfigurationProperties secondary;
@Validated
@Data
@NoArgsConstructor
public static class SecondaryConfigurationProperties {
String url;
String redirectUrl;
@NotBlank
String type;
@NotNull
Boolean supportCors;
}
}
|
3e1c3736d9a8d2526a388692a77b36ab652e8970 | 1,413 | java | Java | dataintegration-run/dataintegration-run-management-plugins/steps/s3-connector/src/main/java/com/github/vfss3/FileServerConfig.java | Rhinob1/data-integration | 88964799357c8833f1251264e0e2e38524890599 | [
"Apache-2.0"
] | null | null | null | dataintegration-run/dataintegration-run-management-plugins/steps/s3-connector/src/main/java/com/github/vfss3/FileServerConfig.java | Rhinob1/data-integration | 88964799357c8833f1251264e0e2e38524890599 | [
"Apache-2.0"
] | null | null | null | dataintegration-run/dataintegration-run-management-plugins/steps/s3-connector/src/main/java/com/github/vfss3/FileServerConfig.java | Rhinob1/data-integration | 88964799357c8833f1251264e0e2e38524890599 | [
"Apache-2.0"
] | null | null | null | 45.580645 | 164 | 0.723992 | 11,964 | package com.github.vfss3;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.auth.StaticUserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
public class FileServerConfig {
public static FileSystemOptions getFileSystemOptions(String fileServerType, String username, String password) throws FileSystemException {
FileSystemOptions opts = new FileSystemOptions();
switch (fileServerType) {
case "ftp":
StaticUserAuthenticator auth = new StaticUserAuthenticator("username", username, password);
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
break;
case "s3":
S3FileSystemConfigBuilder.getInstance().setUseHttps(opts, false);
S3FileSystemConfigBuilder.getInstance().setCredentialsProvider(opts, new AWSStaticCredentialsProvider(new BasicAWSCredentials(username, password)));
break;
default:
break;
}
return opts;
}
}
|
3e1c37af5eb20318fd51716b8c4354806d4777d6 | 268 | java | Java | gulimall-order/src/main/java/com/atguigu/gulimall/order/constant/OrderConstant.java | sjswi/gulimall | 598bea08511df27570613d051ff1fe9005d866f4 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/atguigu/gulimall/order/constant/OrderConstant.java | sjswi/gulimall | 598bea08511df27570613d051ff1fe9005d866f4 | [
"Apache-2.0"
] | 1 | 2022-03-06T12:01:42.000Z | 2022-03-06T12:01:45.000Z | gulimall-order/src/main/java/com/atguigu/gulimall/order/constant/OrderConstant.java | sjswi/gulimall | 598bea08511df27570613d051ff1fe9005d866f4 | [
"Apache-2.0"
] | null | null | null | 21.153846 | 70 | 0.716364 | 11,965 | package com.atguigu.gulimall.order.constant;
/**
* @program: gulimall
* @description:
* @author: yuxiaobing
* @dycjh@example.com
* @date: 2022-03-25 22:42
**/
public class OrderConstant {
public static final String USER_ORDER_TOKEN_PREFIX="order:token:";
}
|
3e1c382a283f1315e7b1c8f27217d09c73fa02ea | 800 | java | Java | test/limelight/styles/attributes/RightBorderColorAttributeTest.java | slagyr/limelight | 2e8db684771587422d55a9329e895481e9b56a26 | [
"MIT"
] | 10 | 2015-05-21T05:07:37.000Z | 2020-11-29T20:09:34.000Z | test/limelight/styles/attributes/RightBorderColorAttributeTest.java | slagyr/limelight | 2e8db684771587422d55a9329e895481e9b56a26 | [
"MIT"
] | null | null | null | test/limelight/styles/attributes/RightBorderColorAttributeTest.java | slagyr/limelight | 2e8db684771587422d55a9329e895481e9b56a26 | [
"MIT"
] | 4 | 2016-05-14T00:10:17.000Z | 2021-02-08T06:41:09.000Z | 27.586207 | 91 | 0.76375 | 11,966 | //- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved.
//- Limelight and all included source files are distributed under terms of the MIT License.
package limelight.styles.attributes;
import limelight.styles.compiling.DimensionAttributeCompiler;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class RightBorderColorAttributeTest extends Assert
{
private RightBorderColorAttribute attribute;
@Before
public void setUp() throws Exception
{
attribute = new RightBorderColorAttribute();
}
@Test
public void shouldCreation() throws Exception
{
assertEquals("Right Border Color", attribute.getName());
assertEquals("color", attribute.getCompiler().type);
assertEquals("#000000ff", attribute.getDefaultValue().toString());
}
}
|
3e1c387eb7a4ad37080aae51ab98ddea156c0715 | 3,292 | java | Java | azylee/azylee-core/src/main/java/com/yuzhyn/azylee/core/datas/collections/MapTool.java | yuzhengyang/Fork4j | bfa29046d733789cd168172abac8276a961e5f55 | [
"Apache-2.0"
] | null | null | null | azylee/azylee-core/src/main/java/com/yuzhyn/azylee/core/datas/collections/MapTool.java | yuzhengyang/Fork4j | bfa29046d733789cd168172abac8276a961e5f55 | [
"Apache-2.0"
] | null | null | null | azylee/azylee-core/src/main/java/com/yuzhyn/azylee/core/datas/collections/MapTool.java | yuzhengyang/Fork4j | bfa29046d733789cd168172abac8276a961e5f55 | [
"Apache-2.0"
] | null | null | null | 28.877193 | 108 | 0.558323 | 11,967 | package com.yuzhyn.azylee.core.datas.collections;
import com.yuzhyn.azylee.core.datas.datetimes.LocalDateTimeTool;
import com.yuzhyn.azylee.core.datas.numbers.IntTool;
import com.yuzhyn.azylee.core.datas.numbers.LongTool;
import com.yuzhyn.azylee.core.logs.Alog;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class MapTool {
/**
* 判断 Map 存在至少一个元素
* @param map
* @return
*/
public static boolean ok(Map map) {
if (map != null && map.size() > 0) {
return true;
}
return false;
}
/**
* 判断 Map 中存在指定 Keys,且指定的 Keys 值不为 Null
* @param map
* @param keys
* @return
*/
public static boolean ok(Map map, String... keys) {
if (MapTool.ok(map)) {
for (String key : keys) {
if (map.getOrDefault(key, null) == null) {
return false;
}
}
return true;
}
return false;
}
public static <K, T> T get(Map<K, T> map, K key, T defaultValue) {
if (map.containsKey(key)) {
return Optional.ofNullable(map.getOrDefault(key, defaultValue)).orElse(defaultValue);
}
return defaultValue;
}
public static <K, T> String getString(Map<K, T> map, K key, T defaultValue) {
if (map.containsKey(key)) {
return Optional.ofNullable(map.getOrDefault(key, defaultValue)).orElse(defaultValue).toString();
}
return defaultValue.toString();
}
public static <K, T> int getInt(Map<K, T> map, K key, T defaultValue) {
String s = MapTool.getString(map, key, defaultValue);
return IntTool.parse(s, IntTool.parse(defaultValue.toString(), 0));
}
public static <K, T> long getLong(Map<K, T> map, K key, T defaultValue) {
String s = MapTool.getString(map, key, defaultValue);
return LongTool.parse(s, LongTool.parse(defaultValue.toString(), 0));
}
public static <K, T> boolean getBoolean(Map<K, T> map, K key, T defaultValue) {
String s = MapTool.getString(map, key, defaultValue);
return Boolean.valueOf(s);
}
public static <K, T> LocalDateTime getLocalDateTime(Map<K, T> map, K key, T defaultValue) {
String s = MapTool.getString(map, key, null);
LocalDateTime time = LocalDateTimeTool.parse(s);
if (time != null) return time;
return null;
}
/**
* 抽取Map列表中的key值数据列表
*
* @param mapList
* @param key
* @param <K>
* @param <T>
* @return
*/
public static <K, T> List<T> extract(List<Map<K, T>> mapList, K key) {
List<T> result = new ArrayList<>();
if (ListTool.ok(mapList)) {
for (Map<K, T> map : mapList) {
if (ok(map)) {
result.add(get(map, key, null));
}
}
}
return result;
}
public static void print(Map map) {
Alog.w("maptool:print");
if (ok(map)) {
for (Object key : map.keySet()) {
Alog.i(key + " = " + map.get(key));
}
} else {
Alog.e("maptool:map is null");
}
}
}
|
3e1c388af2a297e519e6f7b7578d1de1fc8f37a9 | 2,290 | java | Java | spm-monitor-utils/src/main/java/com/sematext/spm/client/util/PercentileUtils.java | sematext/sematext-agent-java | 93876ffa0e9560c78caf66a2d17dfc18d4ecfd2b | [
"Apache-2.0"
] | 20 | 2018-10-23T21:18:57.000Z | 2022-02-23T22:30:42.000Z | spm-monitor-utils/src/main/java/com/sematext/spm/client/util/PercentileUtils.java | sematext/sematext-agent-java | 93876ffa0e9560c78caf66a2d17dfc18d4ecfd2b | [
"Apache-2.0"
] | 40 | 2018-10-06T22:05:22.000Z | 2022-01-25T13:10:25.000Z | spm-monitor-utils/src/main/java/com/sematext/spm/client/util/PercentileUtils.java | sematext/sematext-agent-java | 93876ffa0e9560c78caf66a2d17dfc18d4ecfd2b | [
"Apache-2.0"
] | 6 | 2019-06-26T07:27:22.000Z | 2022-01-26T17:33:32.000Z | 33.188406 | 112 | 0.675546 | 11,968 | /*
* Licensed to Sematext Group, Inc
*
* See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Sematext Group, Inc 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.sematext.spm.client.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PercentileUtils {
private static final int MAX_PCTLS_PER_DEFINITION = 5;
private static final Map<String, List<Long>> DEFINITIONS_TO_PCTLS_LISTS = new HashMap<String, List<Long>>(10);
private static String formPctlName(Long pctl, String metricName) {
return metricName + ".pctl." + pctl;
}
public static Map<Long, String> getPctlToNameMap(String definition, String baseMetricName) {
definition = definition.trim();
List<Long> pctls = DEFINITIONS_TO_PCTLS_LISTS.get(definition);
if (pctls == null) {
pctls = new ArrayList<Long>(MAX_PCTLS_PER_DEFINITION);
for (String s : definition.split(",")) {
s = s.trim();
if (s.equals("")) {
continue;
}
if (pctls.size() == MAX_PCTLS_PER_DEFINITION) {
throw new IllegalArgumentException(
"Pctls definition '" + definition + "' contains more than " + MAX_PCTLS_PER_DEFINITION +
" pctls");
}
Long pctl = Long.valueOf(s);
if (pctl <= 0 || pctl >= 100) {
throw new IllegalArgumentException("Unsupported pctl definition: " + pctl);
}
pctls.add(pctl);
}
}
Map<Long, String> pctlsToNames = new HashMap<Long, String>(pctls.size());
for (Long pctl : pctls) {
pctlsToNames.put(pctl, formPctlName(pctl, baseMetricName));
}
return pctlsToNames;
}
}
|
3e1c38a1a7c8307a43fe44495de3a8706c3fe873 | 2,753 | java | Java | core/src/main/java/net/dummydigit/qbranch/protocols/CompactBinaryFieldInfo.java | fuzhouch/qbranch | e126f99a6c8db6c1f998d1ddb0dc6c85b2ecb896 | [
"MIT"
] | 2 | 2017-08-21T05:51:23.000Z | 2019-05-21T09:29:12.000Z | core/src/main/java/net/dummydigit/qbranch/protocols/CompactBinaryFieldInfo.java | fuzhouch/qbranch | e126f99a6c8db6c1f998d1ddb0dc6c85b2ecb896 | [
"MIT"
] | null | null | null | core/src/main/java/net/dummydigit/qbranch/protocols/CompactBinaryFieldInfo.java | fuzhouch/qbranch | e126f99a6c8db6c1f998d1ddb0dc6c85b2ecb896 | [
"MIT"
] | 1 | 2017-10-16T05:49:53.000Z | 2017-10-16T05:49:53.000Z | 40.485294 | 108 | 0.667635 | 11,969 | // Licensed under the MIT license. See LICENSE file in the project root
// for full license information.
package net.dummydigit.qbranch.protocols;
import java.io.IOException;
import java.io.InputStream;
import net.dummydigit.qbranch.BondDataType;
import net.dummydigit.qbranch.UnsignedInt;
import net.dummydigit.qbranch.exceptions.EndOfStreamException;
import net.dummydigit.qbranch.utils.VariableLength;
/**
* A helper class to extract field type Id from binary stream.
*/
public class CompactBinaryFieldInfo extends FieldInfo {
private static final int TWO_BYTE_FIELD_INFO_FLAG = 0x6; // b(110)
private static final int FOUR_BYTE_FIELD_INFO_FLAG = 0x7; // b(111)
public CompactBinaryFieldInfo(InputStream input) throws IOException, EndOfStreamException {
byte firstByte = (byte)input.read();
int _typeId = firstByte & 0x1F; // Get low 5 bits
int flag = (firstByte >> 5) & 0x7; // Get high 3 bits
byte[] moreFieldBytes = null;
int actualBytesRead;
switch (flag) {
case TWO_BYTE_FIELD_INFO_FLAG:
moreFieldBytes = new byte[1];
break;
case FOUR_BYTE_FIELD_INFO_FLAG:
moreFieldBytes = new byte[3];
break;
default:
fieldId = flag;
break;
}
if (moreFieldBytes != null) {
actualBytesRead = input.read(moreFieldBytes, 0, moreFieldBytes.length);
if (actualBytesRead != moreFieldBytes.length) {
throw new EndOfStreamException(moreFieldBytes.length, actualBytesRead);
}
fieldId = 0;
for (int eachFieldBytes : moreFieldBytes) {
fieldId = (fieldId << 8) + eachFieldBytes;
}
}
typeId = BondDataType.values()[_typeId];
}
public static ContainerHeaderInfo decodeContainerHeaderV1(InputStream stream) throws IOException {
byte oneByte = (byte)stream.read();
BondDataType elementType = BondDataType.values()[oneByte & 0x1F];
UnsignedInt containerLength = VariableLength.decodeVarUInt32(stream);
return new ContainerHeaderInfo(elementType, containerLength.getValue(), 1);
}
public static KvpContainerHeaderInfo decodeKvpContainerHeaderV1(InputStream stream) throws IOException {
byte firstByte = (byte)stream.read();
byte secondByte = (byte)stream.read();
BondDataType keyType = BondDataType.values()[firstByte & 0x1F];
BondDataType valueType = BondDataType.values()[secondByte & 0x1F];
UnsignedInt kvpCount = VariableLength.decodeVarUInt32(stream);
return new KvpContainerHeaderInfo(keyType, valueType, kvpCount.getValue(), 1);
}
}
|
3e1c3926558e03a42077e787dcb922520bbb882f | 11,608 | java | Java | src/main/java/com/alcatrazescapee/mcjunitlib/TestMain.java | cech12/mcjunitlib | 57459789d383e8185d5a067e3716d92e90b21985 | [
"MIT"
] | 15 | 2020-10-06T16:42:42.000Z | 2022-01-29T23:01:04.000Z | src/main/java/com/alcatrazescapee/mcjunitlib/TestMain.java | cech12/mcjunitlib | 57459789d383e8185d5a067e3716d92e90b21985 | [
"MIT"
] | 9 | 2021-06-06T22:59:28.000Z | 2022-02-16T01:07:09.000Z | src/main/java/com/alcatrazescapee/mcjunitlib/TestMain.java | cech12/mcjunitlib | 57459789d383e8185d5a067e3716d92e90b21985 | [
"MIT"
] | 4 | 2020-11-26T01:58:14.000Z | 2022-02-13T01:54:57.000Z | 57.465347 | 362 | 0.730617 | 11,970 | package com.alcatrazescapee.mcjunitlib;
import java.io.File;
import java.net.Proxy;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.block.Blocks;
import net.minecraft.command.Commands;
import net.minecraft.crash.CrashReport;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.NBTDynamicOps;
import net.minecraft.resources.*;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ServerPropertiesProvider;
import net.minecraft.server.dedicated.PropertyManager;
import net.minecraft.server.dedicated.ServerProperties;
import net.minecraft.server.management.PlayerProfileCache;
import net.minecraft.util.DefaultUncaughtExceptionHandler;
import net.minecraft.util.Util;
import net.minecraft.util.datafix.DataFixesManager;
import net.minecraft.util.datafix.codec.DatapackCodec;
import net.minecraft.util.registry.*;
import net.minecraft.world.*;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biomes;
import net.minecraft.world.chunk.listener.LoggingChunkStatusListener;
import net.minecraft.world.gen.DimensionSettings;
import net.minecraft.world.gen.FlatChunkGenerator;
import net.minecraft.world.gen.FlatGenerationSettings;
import net.minecraft.world.gen.FlatLayerInfo;
import net.minecraft.world.gen.settings.DimensionGeneratorSettings;
import net.minecraft.world.gen.settings.DimensionStructuresSettings;
import net.minecraft.world.storage.FolderName;
import net.minecraft.world.storage.IServerConfiguration;
import net.minecraft.world.storage.SaveFormat;
import net.minecraft.world.storage.ServerWorldInfo;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.server.ServerModLoader;
import com.alcatrazescapee.mcjunitlib.framework.IntegrationTestManager;
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.serialization.Lifecycle;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
public class TestMain
{
private static final Level UNIT_TEST = Level.forName("UNITTEST", 50);
private static final Logger LOGGER = LogManager.getLogger();
private static final String TEST_WORLD = "test-world";
public static void main(String[] args)
{
LOGGER.log(UNIT_TEST, "TestMain launching");
OptionParser spec = new OptionParser();
// Consume unused options, so they don't error if used inadvertently
spec.accepts("nogui");
spec.accepts("initSettings", "Initializes 'server.properties' and 'eula.txt', then quits");
spec.accepts("demo");
spec.accepts("bonusChest");
spec.accepts("forceUpgrade");
spec.accepts("eraseCache");
spec.accepts("safeMode", "Loads level with vanilla datapack only");
spec.accepts("help").forHelp();
spec.accepts("singleplayer").withRequiredArg();
OptionSpec<String> universeOption = spec.accepts("universe").withRequiredArg().defaultsTo(".");
OptionSpec<String> worldOption = spec.accepts("world").withRequiredArg();
spec.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(-1);
spec.accepts("serverId").withRequiredArg();
spec.nonOptions();
spec.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed
spec.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side.
// Additional options, for testing purposes
OptionSpec<Void> crashOnFailedTestsSpec = spec.accepts("crashOnFailedTests");
try
{
OptionSet options = spec.parse(args);
CrashReport.preload();
Bootstrap.bootStrap();
Bootstrap.validate();
Util.startTimerHackThread();
ServerModLoader.load();
// After mods have loaded, immediately setup for integration tests.
IntegrationTestManager.setup();
DynamicRegistries.Impl builtinRegistries = DynamicRegistries.builtin();
// Delete the old test world, we create a new one each run
LOGGER.log(UNIT_TEST, "Removing previous test world...");
FileUtils.deleteDirectory(new File(TEST_WORLD));
// Edit the server.properties file before force saving it. This requires some minor reflection into the original properties object
final Path path = Paths.get("server.properties");
final ServerPropertiesProvider serverPropertiesProvider = new ServerPropertiesProvider(builtinRegistries, path);
final ServerProperties serverProperties = serverPropertiesProvider.getProperties();
final Properties properties = ObfuscationReflectionHelper.getPrivateValue(PropertyManager.class, serverProperties, "field_73672_b"); // properties
Objects.requireNonNull(properties);
properties.setProperty("difficulty", "normal");
properties.setProperty("enable-command-block", "true");
properties.setProperty("gamemode", "creative");
properties.setProperty("generate-structures", "false");
properties.setProperty("level-name", TEST_WORLD);
properties.setProperty("max-tick-time", "0");
properties.setProperty("online-mode", "false");
serverPropertiesProvider.forceSave();
File universeFile = new File(options.valueOf(universeOption));
YggdrasilAuthenticationService authService = new YggdrasilAuthenticationService(Proxy.NO_PROXY, UUID.randomUUID().toString());
MinecraftSessionService sessionService = authService.createMinecraftSessionService();
GameProfileRepository profileRepository = authService.createProfileRepository();
PlayerProfileCache profileCache = new PlayerProfileCache(profileRepository, new File(universeFile, MinecraftServer.USERID_CACHE_FILE.getName()));
// The world is not read from either server.properties, or the passed in options
if (new File(universeFile, TEST_WORLD).getAbsolutePath().equals(new File(TEST_WORLD).getAbsolutePath()))
{
LOGGER.log(UNIT_TEST, "Error: Invalid world directory specified, must not be null, empty or the same directory as your universe! " + TEST_WORLD);
return;
}
SaveFormat saveFormat = SaveFormat.createDefault(universeFile.toPath());
SaveFormat.LevelSave levelSave = saveFormat.createAccess(TEST_WORLD);
MinecraftServer.convertFromRegionFormatIfNeeded(levelSave);
DatapackCodec levelDataPacks = levelSave.getDataPacks();
ResourcePackList resourcePacks = new ResourcePackList(new ServerPackFinder(), new FolderPackFinder(levelSave.getLevelPath(FolderName.DATAPACK_DIR).toFile(), IPackNameDecorator.WORLD));
DatapackCodec dataPacks = MinecraftServer.configurePackRepository(resourcePacks, levelDataPacks == null ? DatapackCodec.DEFAULT : levelDataPacks, false);
CompletableFuture<DataPackRegistries> dataPackFuture = DataPackRegistries.loadResources(resourcePacks.openAllSelected(), Commands.EnvironmentType.DEDICATED, serverPropertiesProvider.getProperties().functionPermissionLevel, Util.backgroundExecutor(), Runnable::run);
DataPackRegistries dataPackRegistries;
try
{
dataPackRegistries = dataPackFuture.get();
}
catch (Exception e)
{
LOGGER.log(UNIT_TEST, "FATAL: Failed to load datapacks, can't proceed with server load. You can either fix your datapacks or reset to vanilla with --safeMode", e);
resourcePacks.close();
return;
}
dataPackRegistries.updateGlobals();
WorldSettingsImport<INBT> worldSettingsImport = WorldSettingsImport.create(NBTDynamicOps.INSTANCE, dataPackRegistries.getResourceManager(), builtinRegistries);
// Custom world settings, ignoring most of the options in server.properties
final WorldSettings worldSettings = new WorldSettings(TEST_WORLD, GameType.CREATIVE, false, Difficulty.NORMAL, true, new GameRules(), dataPacks);
// Custom dimension generator settings
// Modified from DimensionGeneratorSettings#create
final long testSeed = new Random().nextLong();
final Registry<DimensionType> dimensionTypeRegistry = builtinRegistries.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY);
final Registry<Biome> biomeRegistry = builtinRegistries.registryOrThrow(Registry.BIOME_REGISTRY);
final Registry<DimensionSettings> dimensionSettingsRegistry = builtinRegistries.registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY);
final SimpleRegistry<Dimension> dimensionRegistry = DimensionType.defaultDimensions(dimensionTypeRegistry, biomeRegistry, dimensionSettingsRegistry, testSeed);
// Flat chunk generator. Modified from FlatPresetsScreen#<cinit>
LOGGER.log(UNIT_TEST, "Setting random seed: " + testSeed);
final List<FlatLayerInfo> layers = new ArrayList<>(Arrays.asList(new FlatLayerInfo(1, Blocks.BEDROCK), new FlatLayerInfo(2, Blocks.DIRT), new FlatLayerInfo(1, Blocks.GRASS_BLOCK)));
final FlatChunkGenerator chunkGenerator = new FlatChunkGenerator(new FlatGenerationSettings(biomeRegistry, new DimensionStructuresSettings(Optional.empty(), new HashMap<>()), layers, false, false, Optional.of(() -> biomeRegistry.getOrThrow(Biomes.PLAINS))));
final DimensionGeneratorSettings testDimensionGeneratorSettings = new DimensionGeneratorSettings(testSeed, false, false, DimensionGeneratorSettings.withOverworld(dimensionTypeRegistry, dimensionRegistry, chunkGenerator));
final IServerConfiguration serverConfiguration = new ServerWorldInfo(worldSettings, testDimensionGeneratorSettings, Lifecycle.stable());
levelSave.saveDataTag(builtinRegistries, serverConfiguration);
final boolean crashOnFailedTests = options.has(crashOnFailedTestsSpec);
final DedicatedTestServer server = MinecraftServer.spin(threadIn -> new DedicatedTestServer(threadIn, builtinRegistries, levelSave, resourcePacks, dataPackRegistries, serverConfiguration, serverPropertiesProvider, DataFixesManager.getDataFixer(), sessionService, profileRepository, profileCache, LoggingChunkStatusListener::new, crashOnFailedTests));
Thread thread = new Thread("Server Shutdown Thread")
{
public void run()
{
server.halt(!server.crashed());
LogManager.shutdown(); // we're manually managing the logging shutdown on the server. Make sure we do it here at the end.
}
};
thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER));
Runtime.getRuntime().addShutdownHook(thread);
}
catch (Exception e)
{
LOGGER.log(UNIT_TEST, "FATAL: Failed to start the minecraft server", e);
}
}
}
|
3e1c39ba5e12967e76e047bb5244b7354c134616 | 2,532 | java | Java | Java_Homework/src/main/java/algorithm/gui/main/MainForm.java | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | Java_Homework/src/main/java/algorithm/gui/main/MainForm.java | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | Java_Homework/src/main/java/algorithm/gui/main/MainForm.java | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | 32.050633 | 98 | 0.559637 | 11,971 | package algorithm.gui.main;
import algorithm.gui.GUIFather;
import algorithm.gui.lcs.LisGUI;
import algorithm.gui.sort_gui.SortGUI;
import algorithm.gui.sudent_data_gui.add.AddStudentDataGUI;
import algorithm.gui.sudent_data_gui.remove.RemoveStudentDataGUI;
import algorithm.gui.sudent_data_gui.show.ShowStudentDataGUI;
import algorithm.gui.tological.ToplogicalGUI;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class MainForm extends GUIFather {
private JTextField main_input_choose;
private JPanel jPanel;
private JButton main_choose_button;
public MainForm(String windowName) {
super(windowName);
setContentPane(jPanel);
setVisible(true);
main_choose_button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectFunction(main_input_choose.getText());
}
});
main_input_choose.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
selectFunction(main_input_choose.getText());
}
}
});
}
private void selectFunction(String selectString) {
switch (selectString) {
case "1":
new ShowStudentDataGUI("查詢學生單科成績頁面", "請先選擇檔案後 輸入學生學號及科目");
break;
case "2":
new ShowStudentDataGUI("查詢學生所有成績頁面", "請先選擇檔案後 輸入學生學號");
break;
case "3":
new AddStudentDataGUI("新增學生成績頁面", "請先選擇檔案後 輸入學生學號及科目成績");
break;
case "4":
new RemoveStudentDataGUI("刪除學生成績頁面", "請先選擇檔案後 輸入學生學號");
break;
case "5":
new SortGUI("排序頁面");
break;
case "6":
new LisGUI("最長遞增成績子序列頁面");
break;
case "7":
new ToplogicalGUI("排課頁面");
break;
case "8":
this.dispose();
System.exit(0);
break;
default:
JOptionPane.showMessageDialog(null, "未知輸入", "未知輸入錯誤", JOptionPane.ERROR_MESSAGE);
}
}
}
|
3e1c39dac5a13521e69a53a0baaeff38252c7792 | 2,726 | java | Java | app/src/main/java/snijsure/com/sunrisedemo/ApptInfoAdapter.java | snijsure/sunrisedemo | 6827d4f5fd88097322f7ab3a7abb32d448aa8a82 | [
"MIT"
] | 1 | 2016-03-19T13:31:36.000Z | 2016-03-19T13:31:36.000Z | app/src/main/java/snijsure/com/sunrisedemo/ApptInfoAdapter.java | snijsure/sunrisedemo | 6827d4f5fd88097322f7ab3a7abb32d448aa8a82 | [
"MIT"
] | null | null | null | app/src/main/java/snijsure/com/sunrisedemo/ApptInfoAdapter.java | snijsure/sunrisedemo | 6827d4f5fd88097322f7ab3a7abb32d448aa8a82 | [
"MIT"
] | null | null | null | 31.333333 | 88 | 0.658107 | 11,972 | package snijsure.com.sunrisedemo;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/*
* This classs is adapter interface to represent
* all the appointments one may have in the calendar.
* It uses inner class ApptHolder that contains the view
* information to display it on the screen.
*/
public class ApptInfoAdapter extends RecyclerView.Adapter<ApptInfoAdapter.ApptHolder> {
enum ApptType {
TITLE, // Indicates this is a title for the day
APPOINTMENT, // Indicates this is a valid appt
EMPTYDAY // Indicates this day has no appointment.
}
// Right now appointments are only added to this list
private ArrayList<Appointment> mAppointments;
public ApptInfoAdapter(ArrayList<Appointment> list) {
mAppointments = list;
}
@Override
public ApptHolder onCreateViewHolder(ViewGroup parent, int pos) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.appt_item, parent, false);
return new ApptHolder(view);
}
@Override
public void onBindViewHolder(final ApptHolder holder, int pos) {
Appointment rowItem = mAppointments.get(pos);
holder.bindAppt(rowItem);
}
@Override
public int getItemCount() {
return mAppointments.size();
}
// This is the class that holds single appointment entry
class ApptHolder extends RecyclerView.ViewHolder {
View mHolderView;
TextView title;
TextView description;
TextView startStop;
TextView location;
int appt_entry_type;
public ApptHolder(View itemView) {
super(itemView);
mHolderView = itemView;
title = (TextView) itemView.findViewById(R.id.title);
description = (TextView) itemView.findViewById(R.id.description);
startStop = (TextView) itemView.findViewById(R.id.startstop);
location = (TextView) itemView.findViewById(R.id.location);
}
public void bindAppt(Appointment apptItem) {
title.setText(apptItem.getTitle());
description.setText(apptItem.getDescription());
// See documentation at
// https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
startStop.setText(apptItem.getStartDate("M/d h:mm a") +
"\n" + apptItem.getEndDate("M/d h:mm a") +
"\n" + Long.toString(apptItem.durationInMinutes()) + " min" );
location.setText(apptItem.getLocation());
}
}
}
|
3e1c3afce363f7f8ae88b74a30c01b06e29f8049 | 1,389 | java | Java | src/main/java/droidicus/aquaregia/proxy/CombinedClientProxy.java | droidicus/AquaRegia | 9e2595c32bce2df9e7e19b39f04383a4c0f40d2f | [
"MIT"
] | 2 | 2016-09-07T13:05:19.000Z | 2016-09-12T07:23:03.000Z | src/main/java/droidicus/aquaregia/proxy/CombinedClientProxy.java | droidicus/AquaRegia | 9e2595c32bce2df9e7e19b39f04383a4c0f40d2f | [
"MIT"
] | null | null | null | src/main/java/droidicus/aquaregia/proxy/CombinedClientProxy.java | droidicus/AquaRegia | 9e2595c32bce2df9e7e19b39f04383a4c0f40d2f | [
"MIT"
] | null | null | null | 27.78 | 96 | 0.758099 | 11,973 | package droidicus.aquaregia.proxy;
import droidicus.aquaregia.client.event.ClientEventHandler;
import droidicus.aquaregia.client.model.ModColourManager;
import droidicus.aquaregia.client.model.ModModelManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
@SideOnly(Side.CLIENT)
public class CombinedClientProxy implements IProxy {
private final Minecraft minecraft = Minecraft.getMinecraft();
@Override
public void preInit() {
ModModelManager.INSTANCE.registerAllModels();
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
// RenderingRegistry.registerEntityRenderingHandler(EntityModArrow.class, RenderModArrow::new);
}
@Override
public void init() {
ModColourManager.registerColourHandlers();
}
@Override
public void postInit() {
}
@Override
public void doClientRightClick() {
// Press the Use Item keybinding
KeyBinding.onTick(minecraft.gameSettings.keyBindUseItem.getKeyCode());
}
@Nullable
@Override
public EntityPlayer getClientPlayer() {
return minecraft.thePlayer;
}
}
|
3e1c3d35be2921fbf214c8fa18abed857ecba610 | 857 | java | Java | app/src/main/java/wps/de/android_schulung_app/TestMainActivity.java | AdrianMetzner/Android-Schulung | 1be1a4a845479b39d411a66182ad418e5d59e0a4 | [
"MIT"
] | null | null | null | app/src/main/java/wps/de/android_schulung_app/TestMainActivity.java | AdrianMetzner/Android-Schulung | 1be1a4a845479b39d411a66182ad418e5d59e0a4 | [
"MIT"
] | null | null | null | app/src/main/java/wps/de/android_schulung_app/TestMainActivity.java | AdrianMetzner/Android-Schulung | 1be1a4a845479b39d411a66182ad418e5d59e0a4 | [
"MIT"
] | null | null | null | 31.740741 | 200 | 0.759627 | 11,974 | package wps.de.android_schulung_app;
import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import wps.de.android_schulung_app.databinding.ActivityTestMainBinding;
/**
* Created by Adrian on 11.03.2018.
*/
public class TestMainActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestDataMethod devInfo = new TestDataMethod(String.format("%s %s|%s", Build.BRAND, Build.DEVICE, Build.MODEL), String.format("OS: %s | SDK: %d", Build.VERSION.RELEASE, Build.VERSION.SDK_INT));
ActivityTestMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_test_main);
binding.setDevInfo(devInfo);
}
}
|
3e1c3e624e104e5f5be89466f9374bff24298ad6 | 748 | java | Java | Include/scripts/groovy/com/kms/katalon/core/appium/driver/AppiumOutputStreamHandler.java | carlin-q-scott/katalon-studio-testing-framework | 5ef79c27f31542bfcb1d81e718b379c0f79f805f | [
"FSFAP"
] | 34 | 2019-01-10T04:04:58.000Z | 2022-03-27T23:14:37.000Z | Include/scripts/groovy/com/kms/katalon/core/appium/driver/AppiumOutputStreamHandler.java | carlin-q-scott/katalon-studio-testing-framework | 5ef79c27f31542bfcb1d81e718b379c0f79f805f | [
"FSFAP"
] | 9 | 2019-02-27T22:46:05.000Z | 2022-02-01T00:04:10.000Z | Include/scripts/groovy/com/kms/katalon/core/appium/driver/AppiumOutputStreamHandler.java | carlin-q-scott/katalon-studio-testing-framework | 5ef79c27f31542bfcb1d81e718b379c0f79f805f | [
"FSFAP"
] | 46 | 2019-01-11T01:33:02.000Z | 2022-03-27T23:14:40.000Z | 31.166667 | 101 | 0.717914 | 11,975 | package com.kms.katalon.core.appium.driver;
import java.io.File;
import java.io.PrintStream;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListenerAdapter;
public class AppiumOutputStreamHandler extends Tailer {
private AppiumOutputStreamHandler(String appiumLogFilePath, PrintStream outStream) {
super(new File(appiumLogFilePath), new TailerListenerAdapter() {
@Override
public void handle(String line) {
outStream.println(line);
}
});
}
public static AppiumOutputStreamHandler create(String appiumLogFilePath, PrintStream outStream) {
return new AppiumOutputStreamHandler(appiumLogFilePath, outStream);
}
}
|
3e1c3e9a8587c7150512b553f7d6fb027ef8a0d1 | 15,756 | java | Java | shetland/core/src/main/java/org/n52/shetland/aqd/AqdConstants.java | 52North/arctic-sea | 2adb4a423db9efd2350920af264f761c29b2604f | [
"Apache-2.0"
] | 19 | 2017-01-13T13:30:32.000Z | 2021-11-27T16:21:42.000Z | shetland/core/src/main/java/org/n52/shetland/aqd/AqdConstants.java | 52North/arctic-sea | 2adb4a423db9efd2350920af264f761c29b2604f | [
"Apache-2.0"
] | 81 | 2017-12-19T15:47:04.000Z | 2022-03-30T04:00:52.000Z | shetland/core/src/main/java/org/n52/shetland/aqd/AqdConstants.java | 52North/arctic-sea | 2adb4a423db9efd2350920af264f761c29b2604f | [
"Apache-2.0"
] | 32 | 2017-12-21T14:32:29.000Z | 2022-03-02T15:04:52.000Z | 31.512 | 117 | 0.681455 | 11,976 | /*
* Copyright (C) 2015-2021 52°North Spatial Information Research 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.n52.shetland.aqd;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import org.n52.janmayen.http.MediaType;
import org.n52.shetland.iso.GcoConstants;
import org.n52.shetland.iso.gmd.GmdConstants;
import org.n52.shetland.w3c.SchemaLocation;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
public interface AqdConstants {
String TEXT = "text";
String AQD = "AQD";
String VERSION = "1.0.0";
String DEFINITION_VERIFICATION = "http://dd.eionet.europa.eu/vocabularies/aq/observationverification";
String DEFINITION_VALIDITY = "http://dd.eionet.europa.eu/vocabularies/aq/observationvalidity";
String DEFINITION_DATA_CAPTURE = "http://dd.eionet.europa.eu/vocabulary/aq/primaryObservation/dc";
String DEFINITION_UOM_STATISTICS_PERCENTAGE =
"http://dd.eionet.europa.eu/vocabularyconcept/uom/statistics/percentage";
String NAME_FIXED_OBSERVATIONS = "FixedObservations";
String NS_AQD = "http://dd.eionet.europa.eu/schemaset/id2011850eu-1.0";
String NS_AQD_PREFIX = "aqd";
String NS_AQD_SCHEMA = "http://dd.eionet.europa.eu/schemas/id2011850eu-1.0/AirQualityReporting.xsd";
SchemaLocation NS_AQD_SCHEMA_LOCATION = new SchemaLocation(NS_AQD, NS_AQD_SCHEMA);
MediaType AQD_CONTENT_TYPE = new MediaType(TEXT, "xml", "subtype", "id2011850eu/1.0");
String NS_AD = "urn:x-inspire:specification:gmlas:Addresses:3.0";
String NS_AD_PREFIX = "ad";
String NS_AM = "http://inspire.ec.europa.eu/schemas/am/3.0";
String NS_AM_PREFIX = "am";
String NS_AU = "urn:x-inspire:specification:gmlas:AdministrativeUnits:3.0";
String NS_AU_PREFIX = "au";
String NS_BASE = "http://inspire.ec.europa.eu/schemas/base/3.3";
String NS_BASE_PREFIX = "base";
String NS_BASE2 = "http://inspire.ec.europa.eu/schemas/base2/1.0";
String NS_BASE2_PREFIX = "base2";
String NS_EF = "http://inspire.ec.europa.eu/schemas/ef/3.0";
String NS_EF_PREFIX = "ef";
String NS_GN = "urn:x-inspire:specification:gmlas:GeographicalNames:3.0";
String NS_GN_PREFIX = "gn";
String NS_OMPR = "http://inspire.ec.europa.eu/schemas/ompr/2.0";
String NS_OMPR_PREFIX = "ompr";
Map<String, String> NAMESPACE_PREFIX_MAP = ImmutableMap.<String, String> builder().put(NS_AQD, NS_AQD_PREFIX)
.put(NS_AD, NS_AD_PREFIX).put(NS_AM, NS_AM_PREFIX).put(NS_AU, NS_AU_PREFIX).put(NS_BASE, NS_BASE_PREFIX)
.put(NS_BASE2, NS_BASE2_PREFIX).put(NS_EF, NS_EF_PREFIX).put(NS_GN, NS_GN_PREFIX)
.put(NS_OMPR, NS_OMPR_PREFIX).put(GcoConstants.NS_GCO, GcoConstants.NS_GCO_PREFIX)
.put(GmdConstants.NS_GMD, GmdConstants.NS_GMD_PREFIX).build();
String AN_CODE_SPACE = "codeSpace";
String AN_NIL_REASON = "nilReason";
String EN_ADDRESS = "address";
String EN_ADDRESS_AREA = "addressArea";
String EN_ADDRESS_FEATURE = "addressFeature";
String EN_ADDRESS_REPRESENTATION = "AddressRepresentation";
String EN_ADMIN_UNIT = "adminUnit";
String EN_CHANGE = "change";
String EN_CHANGE_DESCRIPTION = "changeDescription";
String EN_CONTACT = "contact";
String EN_C_ONTACT = "Contact";
String EN_CONTACT_INSTRUCTIONS = "contactInstructions";
String EN_CONTENT = "content";
String EN_DELETE = "delete";
String EN_ELECTRONIC_MAIL_ADDRESS = "electronicMailAddress";
String EN_GEOGRAPHICAL_NAME = "GeographicalName";
String EN_GRAMMATICAL_GENDER = "grammaticalGender";
String EN_GRAMMATICAL_NUMBER = "grammaticalNumber";
String EN_HOURS_OF_SERVICE = "hoursOfService";
String EN_IDENTIFIER = "Identifier";
String EN_INDIVIDUAL_NAME = "individualName";
String EN_INSPIRE_ID = "inspireId";
String EN_LANGUAGE = "language";
String EN_LOCAL_ID = "localId";
String EN_LOCATOR_DESIGNATOR = "locatorDesignator";
String EN_LOCATOR_NAME = "locatorName";
String EN_NAME_STATUS = "nameStatus";
String EN_NAMESPACE = "namespace";
String EN_NATIVENESS = "nativeness";
String EN_ORGANISATION_NAME = "organisationName";
String EN_POSITION_NAME = "positionName";
String EN_POST_CODE = "postCode";
String EN_POST_NAME = "postName";
String EN_PRONUNCIATION = "pronunciation";
String EN_PRONUNCIATION_IPA = "pronunciationIPA";
String EN_PRONUNCIATION_OF_NAME = "PronunciationOfName";
String EN_PRONUNCIATION_SOUND_LINK = "pronunciationSoundLink";
String EN_RELATED_PARTY = "RelatedParty";
String EN_REPORTING_AUTHORITY = "reportingAuthority";
String EN_REPORTING_HEADER = "AQD_ReportingHeader";
String EN_REPORTING_PERIOD = "reportingPeriod";
String EN_ROLE = "role";
String EN_SCRIPT = "script";
String EN_SOURCE_OF_NAME = "sourceOfName";
String EN_SPELLING = "spelling";
String EN_SPELLING_OF_NAME = "SpellingOfName";
String EN_TELEPHONE_FACSIMILE = "telephoneFacsimile";
String EN_TELEPHONE_VOICE = "telephoneVoice";
String EN_TEXT = TEXT;
String EN_THOROUGHFARE = "thoroughfare";
String EN_TRANSLITERATION_SCHEME = "transliterationScheme";
String EN_VERSION_ID = "versionId";
String EN_WEBSITE = "website";
QName QN_NIL_REASON = new QName(AN_NIL_REASON);
QName QN_AD_ADDRESS_AREA = new QName(NS_AD, EN_ADDRESS_AREA, NS_AD_PREFIX);
QName QN_AD_ADDRESS_FEATURE = new QName(NS_AD, EN_ADDRESS_FEATURE, NS_AD_PREFIX);
QName QN_AD_ADDRESS_REPRESENTATION = new QName(NS_AD, EN_ADDRESS_REPRESENTATION, NS_AD_PREFIX);
QName QN_AD_ADMIN_UNIT = new QName(NS_AD, EN_ADMIN_UNIT, NS_AD_PREFIX);
QName QN_AD_LOCATOR_DESIGNATOR = new QName(NS_AD, EN_LOCATOR_DESIGNATOR, NS_AD_PREFIX);
QName QN_AD_LOCATOR_NAME = new QName(NS_AD, EN_LOCATOR_NAME, NS_AD_PREFIX);
QName QN_AD_POST_CODE = new QName(NS_AD, EN_POST_CODE, NS_AD_PREFIX);
QName QN_AD_POST_NAME = new QName(NS_AD, EN_POST_NAME, NS_AD_PREFIX);
QName QN_AD_THOROUGHFARE = new QName(NS_AD, EN_THOROUGHFARE, NS_AD_PREFIX);
QName QN_AQD_CHANGE = new QName(NS_AQD, EN_CHANGE, NS_AQD_PREFIX);
QName QN_AQD_CHANGE_DESCRIPTION = new QName(NS_AQD, EN_CHANGE_DESCRIPTION, NS_AQD_PREFIX);
QName QN_AQD_CONTENT = new QName(NS_AQD, EN_CONTENT, NS_AQD_PREFIX);
QName QN_AQD_DELETE = new QName(NS_AQD, EN_DELETE, NS_AQD_PREFIX);
QName QN_AQD_INSPIRE_ID = new QName(NS_AQD, EN_INSPIRE_ID, NS_AQD_PREFIX);
QName QN_AQD_REPORTING_AUTHORITY = new QName(NS_AQD, EN_REPORTING_AUTHORITY, NS_AQD_PREFIX);
QName QN_AQD_REPORTING_HEADER = new QName(NS_AQD, EN_REPORTING_HEADER, NS_AQD_PREFIX);
QName QN_AQD_REPORTING_PERIOD = new QName(NS_AQD, EN_REPORTING_PERIOD, NS_AQD_PREFIX);
QName QN_BASE_IDENTIFIER = new QName(NS_BASE, EN_IDENTIFIER, NS_BASE_PREFIX);
QName QN_BASE_LOCAL_ID = new QName(NS_BASE, EN_LOCAL_ID, NS_BASE_PREFIX);
QName QN_BASE_NAMESPACE = new QName(NS_BASE, EN_NAMESPACE, NS_BASE_PREFIX);
QName QN_BASE_VERSION_ID = new QName(NS_BASE, EN_VERSION_ID, NS_BASE_PREFIX);
QName QN_BASE2_ADDRESS = new QName(NS_BASE2, EN_ADDRESS, NS_BASE2_PREFIX);
QName QN_BASE2_CONTACT = new QName(NS_BASE2, EN_CONTACT, NS_BASE2_PREFIX);
QName QN_BASE2_C_ONTACT = new QName(NS_BASE2, EN_C_ONTACT, NS_BASE2_PREFIX);
QName QN_BASE2_CONTACT_INSTRUCTIONS = new QName(NS_BASE2, EN_CONTACT_INSTRUCTIONS, NS_BASE2_PREFIX);
QName QN_BASE2_ELECTRONIC_MAIL_ADDRESS = new QName(NS_BASE2, EN_ELECTRONIC_MAIL_ADDRESS, NS_BASE2_PREFIX);
QName QN_BASE2_HOURS_OF_SERVICE = new QName(NS_BASE2, EN_HOURS_OF_SERVICE, NS_BASE2_PREFIX);
QName QN_BASE2_INDIVIDUAL_NAME = new QName(NS_BASE2, EN_INDIVIDUAL_NAME, NS_BASE2_PREFIX);
QName QN_BASE2_ORGANISATION_NAME = new QName(NS_BASE2, EN_ORGANISATION_NAME, NS_BASE2_PREFIX);
QName QN_BASE2_POSITION_NAME = new QName(NS_BASE2, EN_POSITION_NAME, NS_BASE2_PREFIX);
QName QN_BASE2_RELATED_PARTY = new QName(NS_BASE2, EN_RELATED_PARTY, NS_BASE2_PREFIX);
QName QN_BASE2_ROLE = new QName(NS_BASE2, EN_ROLE, NS_BASE2_PREFIX);
QName QN_BASE2_TELEPHONE_FACSIMILE = new QName(NS_BASE2, EN_TELEPHONE_FACSIMILE, NS_BASE2_PREFIX);
QName QN_BASE2_TELEPHONE_VOICE = new QName(NS_BASE2, EN_TELEPHONE_VOICE, NS_BASE2_PREFIX);
QName QN_BASE2_WEBSITE = new QName(NS_BASE2, EN_WEBSITE, NS_BASE2_PREFIX);
QName QN_GN_GEOGRAPHICAL_NAME = new QName(NS_GN, EN_GEOGRAPHICAL_NAME, NS_GN_PREFIX);
QName QN_GN_GRAMMATICAL_GENDER = new QName(NS_GN, EN_GRAMMATICAL_GENDER, NS_GN_PREFIX);
QName QN_GN_GRAMMATICAL_NUMBER = new QName(NS_GN, EN_GRAMMATICAL_NUMBER, NS_GN_PREFIX);
QName QN_GN_LANGUAGE = new QName(NS_GN, EN_LANGUAGE, NS_GN_PREFIX);
QName QN_GN_NAME_STATUS = new QName(NS_GN, EN_NAME_STATUS, NS_GN_PREFIX);
QName QN_GN_NATIVENESS = new QName(NS_GN, EN_NATIVENESS, NS_GN_PREFIX);
QName QN_GN_PRONUNCIATION = new QName(NS_GN, EN_PRONUNCIATION, NS_GN_PREFIX);
QName QN_GN_PRONUNCIATION_IPA = new QName(NS_GN, EN_PRONUNCIATION_IPA, NS_GN_PREFIX);
QName QN_GN_PRONUNCIATION_OF_NAME = new QName(NS_GN, EN_PRONUNCIATION_OF_NAME, NS_GN_PREFIX);
QName QN_GN_PRONUNCIATION_SOUND_LINK = new QName(NS_GN, EN_PRONUNCIATION_SOUND_LINK, NS_GN_PREFIX);
QName QN_GN_SCRIPT = new QName(NS_GN, EN_SCRIPT, NS_GN_PREFIX);
QName QN_GN_SOURCE_OF_NAME = new QName(NS_GN, EN_SOURCE_OF_NAME, NS_GN_PREFIX);
QName QN_GN_SPELLING = new QName(NS_GN, EN_SPELLING, NS_GN_PREFIX);
QName QN_GN_SPELLING_OF_NAME = new QName(NS_GN, EN_SPELLING_OF_NAME, NS_GN_PREFIX);
QName QN_GN_TEXT = new QName(NS_GN, EN_TEXT, NS_GN_PREFIX);
QName QN_GN_TRANSLITERATION_SCHEME = new QName(NS_GN, EN_TRANSLITERATION_SCHEME, NS_GN_PREFIX);
String HOUR = "hour";
String DAY = "day";
String WEEK = "week";
String FORTNIGHT = "fortnight";
String MONTH = "month";
String QUARTER = "quarter";
String VAR = "var";
String EXTENSION_FLOW = "flow";
String MODEL = "model";
/**
* the names of the operations supported by all versions of the SOS
* specification
*/
enum Operations {
GetCapabilities, GetObservation, DescribeSensor
}
enum PrimaryObservation {
Hourly(HOUR), Daily(DAY), Weekly(WEEK), Fortnightly(FORTNIGHT), Monthly(MONTH), Quarterly(QUARTER), Variable(
VAR);
private static final String BASE_URI = "http://dd.eionet.europa.eu/vocabulary/aq/primaryObservation/";
private static final Set<String> MULTI_DAYS = Sets.newHashSet(WEEK, FORTNIGHT, MONTH, QUARTER);
private final String id;
private final String conceptURI;
PrimaryObservation(String id) {
this.id = id;
this.conceptURI = BASE_URI + id;
}
public String getId() {
return id;
}
public String getConceptURI() {
return conceptURI;
}
public static PrimaryObservation from(String v) {
for (PrimaryObservation c : PrimaryObservation.values()) {
if (c.getConceptURI().equals(v) || c.getId().equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public static PrimaryObservation fromConceptURI(String v) {
for (PrimaryObservation c : PrimaryObservation.values()) {
if (c.getConceptURI().equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public static PrimaryObservation fromId(String v) {
for (PrimaryObservation c : PrimaryObservation.values()) {
if (c.getId().equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public boolean isMultyDayPrimaryObservation() {
return MULTI_DAYS.contains(this.id);
}
}
enum ProcessParameter {
AssessmentType("AssessmentType"),
CalibrationSamplingPointsOther("CAL-SPother"),
CalibrationSamplingPoints("CAL-SPs"),
EnvironmentalObjective("EO"),
Model(MODEL),
ObjectiveEstimation("objective-estimation"),
PrimaryObservationTime("primaryObsTime"),
SamplingPoint("SamplingPoint"),
MonitoringStation("Station"),
Network("Network"),
VerificationSamplingPoints("VER-SP"),
VerificationSamplingPointsOther("VER-SPother"),
Unknown("Unknown");
private static final String BASE_URI = "http://dd.eionet.europa.eu/vocabulary/aq/processparameter/";
private final String id;
private final String conceptURI;
ProcessParameter(String id) {
this.id = id;
this.conceptURI = BASE_URI + id;
}
public String getId() {
return id;
}
public String getConceptURI() {
return conceptURI;
}
public static ProcessParameter from(String v) {
for (ProcessParameter p : ProcessParameter.values()) {
if (p.getConceptURI().equals(v) || p.getId().equals(v)) {
return p;
}
}
throw new IllegalArgumentException(v);
}
public static ProcessParameter fromOrUnknown(String v) {
for (ProcessParameter p : ProcessParameter.values()) {
if (p.getConceptURI().equals(v) || p.getId().equals(v)) {
return p;
}
}
return Unknown;
}
}
enum AssessmentType {
Fixed("fixed"),
Interactive("interactive"),
Model(MODEL),
Objective("objective");
private static final String BASE_URI = "http://dd.eionet.europa.eu/vocabulary/aq/assessmenttype/";
private final String id;
private final String conceptURI;
AssessmentType(String id) {
this.id = id;
this.conceptURI = BASE_URI + id;
}
public String getId() {
return id;
}
public String getConceptURI() {
return conceptURI;
}
public static AssessmentType from(String v) {
for (AssessmentType c : AssessmentType.values()) {
if (c.getConceptURI().equals(v) || c.getId().equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public static AssessmentType fromConceptURI(String v) {
for (AssessmentType c : AssessmentType.values()) {
if (c.getConceptURI().equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public static AssessmentType fromId(String v) {
for (AssessmentType c : AssessmentType.values()) {
if (c.getId().equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
}
|
3e1c3ec3079a3ca9b710e16108aadd9a8dfcdc78 | 1,997 | java | Java | src/com/reason/build/annotations/ErrorsManagerImpl.java | nirvdrum/reasonml-idea-plugin | 6491a9294ee19c4e1d6c39e3f950b9fe0d9f3f91 | [
"MIT"
] | null | null | null | src/com/reason/build/annotations/ErrorsManagerImpl.java | nirvdrum/reasonml-idea-plugin | 6491a9294ee19c4e1d6c39e3f950b9fe0d9f3f91 | [
"MIT"
] | null | null | null | src/com/reason/build/annotations/ErrorsManagerImpl.java | nirvdrum/reasonml-idea-plugin | 6491a9294ee19c4e1d6c39e3f950b9fe0d9f3f91 | [
"MIT"
] | null | null | null | 33.847458 | 103 | 0.652979 | 11,977 | package com.reason.build.annotations;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.containers.ConcurrentMultiMap;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
public class ErrorsManagerImpl implements ErrorsManager {
private final ConcurrentMultiMap<String, OutputInfo> m_errorsByFile = new ConcurrentMultiMap<>();
private final ConcurrentMultiMap<String, OutputInfo> m_warningsByFile = new ConcurrentMultiMap<>();
@Override
public void addAllInfo(@NotNull Iterable<OutputInfo> bsbInfo) {
VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
for (OutputInfo info : bsbInfo) {
if (info != null && info.path != null && !info.path.isEmpty()) {
VirtualFile fileByUrl = virtualFileManager.findFileByUrl("file://" + info.path);
if (fileByUrl != null) {
if (info.isError) {
m_errorsByFile.putValue(fileByUrl.getPath(), info);
} else {
m_warningsByFile.putValue(fileByUrl.getPath(), info);
}
}
}
}
}
@NotNull
@Override
public Collection<OutputInfo> getInfo(@NotNull String filePath) {
ArrayList<OutputInfo> result = new ArrayList<>(m_errorsByFile.get(filePath));
result.addAll(m_warningsByFile.get(filePath));
return result;
}
@NotNull
@Override
public ConcurrentMultiMap<String, OutputInfo> getAllErrors() {
return m_errorsByFile;
}
@Override
public boolean hasErrors(@NotNull VirtualFile file) {
String filePath = file.getCanonicalPath();
return filePath != null && m_errorsByFile.containsKey(filePath);
}
@Override
public void clearErrors() {
m_errorsByFile.clear();
m_warningsByFile.clear();
}
}
|
3e1c3f6b0aaae3acbf1ce71c4e9a977fb4629d97 | 1,830 | java | Java | Main.java | code-blooded/connected-graph-generation | 9cbb5c90e65d0fdff0d73723292d90a1137234b8 | [
"MIT"
] | null | null | null | Main.java | code-blooded/connected-graph-generation | 9cbb5c90e65d0fdff0d73723292d90a1137234b8 | [
"MIT"
] | null | null | null | Main.java | code-blooded/connected-graph-generation | 9cbb5c90e65d0fdff0d73723292d90a1137234b8 | [
"MIT"
] | null | null | null | 27.313433 | 68 | 0.52459 | 11,978 | /* AUTHOR https://github.com/code-blooded */
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class random_graph {
public int nodes;
private List connected;
private List unconnected;
private PrintWriter writer;
random_graph(int n){
nodes = n;
connected = new ArrayList();
unconnected = new ArrayList();
connected.add(1);
for (int i = 2; i <= nodes; i++) {
unconnected.add(i);
}
try {
writer = new PrintWriter("the-file-name.txt", "UTF-8");
}catch (Exception e) {
System.out.println("File Error");
}
}
void generate(double percentage){
int extra_edges,edges;
extra_edges = (int)(nodes*nodes*(percentage/100.0));
System.out.println(extra_edges);
edges = 0;
Random R = new Random(4587);
while(!unconnected.isEmpty()){
int temp1 = R.nextInt(connected.size());
int temp2 = R.nextInt(unconnected.size());
int u = (int)connected.get(temp1);
int v = (int)unconnected.get(temp2);
addEdge(u,v);
unconnected.remove(temp2);
connected.add(v);
edges++;
}
while(extra_edges>0){
int temp1 = R.nextInt(nodes);
int temp2 = R.nextInt(nodes);
addEdge(temp1,temp2);
extra_edges--;
}
writer.close();
}
void addEdge(int u,int v){
//System.out.println(u+" "+v);
writer.println(u+" "+v);
}
}
public class Main {
public static void main(String[] args) {
random_graph g = new random_graph(1000);
g.generate(0.1);
}
}
|
3e1c40a42dd8cddb62f0a8cd7e738bd4250e3ce4 | 2,715 | java | Java | src/main/java/com/eway/payment/rapid/sdk/message/convert/request/RefundToDirectRefundReqConverter.java | noojee/eway-rapid-java | 94c787c8b69ba0ec58da5123f03ca03e6f684c11 | [
"MIT"
] | 4 | 2015-08-20T23:13:48.000Z | 2019-05-24T02:52:35.000Z | src/main/java/com/eway/payment/rapid/sdk/message/convert/request/RefundToDirectRefundReqConverter.java | Shlomi295/eway-rapid-java | 226ac11aa9962183159a2d0e0f2cbcc5cd868157 | [
"MIT"
] | 15 | 2015-12-17T00:17:47.000Z | 2022-01-27T00:05:02.000Z | src/main/java/com/eway/payment/rapid/sdk/message/convert/request/RefundToDirectRefundReqConverter.java | Shlomi295/eway-rapid-java | 226ac11aa9962183159a2d0e0f2cbcc5cd868157 | [
"MIT"
] | 11 | 2015-10-29T04:53:07.000Z | 2021-11-10T02:08:03.000Z | 50.277778 | 118 | 0.694659 | 11,979 | package com.eway.payment.rapid.sdk.message.convert.request;
import com.eway.payment.rapid.sdk.beans.external.LineItem;
import com.eway.payment.rapid.sdk.beans.external.Refund;
import com.eway.payment.rapid.sdk.beans.external.ShippingDetails;
import com.eway.payment.rapid.sdk.beans.external.CardDetails;
import com.eway.payment.rapid.sdk.beans.internal.Option;
import com.eway.payment.rapid.sdk.beans.internal.ShippingAddress;
import com.eway.payment.rapid.sdk.beans.internal.Customer;
import com.eway.payment.rapid.sdk.entities.DirectRefundRequest;
import com.eway.payment.rapid.sdk.exception.RapidSdkException;
import com.eway.payment.rapid.sdk.message.convert.BeanConverter;
import com.eway.payment.rapid.sdk.message.convert.CustomerToInternalCustomerConverter;
import com.eway.payment.rapid.sdk.message.convert.ShippingDetailsToAddressConverter;
import java.util.ArrayList;
import java.util.List;
public class RefundToDirectRefundReqConverter implements BeanConverter<Refund, DirectRefundRequest> {
public DirectRefundRequest doConvert(Refund refund) throws RapidSdkException {
DirectRefundRequest request = new DirectRefundRequest();
if (refund != null) {
request.setRefund(refund.getRefundDetails());
BeanConverter<ShippingDetails, ShippingAddress> shippingConvert = new ShippingDetailsToAddressConverter();
request.setShippingAddress(shippingConvert.doConvert(refund.getShippingDetails()));
CustomerToInternalCustomerConverter customerConvert = new CustomerToInternalCustomerConverter();
Customer customer = customerConvert.doConvert(refund.getCustomer());
if (customer.getCardDetails() == null) {
customer.setCardDetails(new CardDetails());
}
request.setCustomer(customer);
request.setPartnerID(refund.getPartnerID());
request.setDeviceID(refund.getDeviceID());
List<LineItem> lineItems = refund.getLineItems();
if (lineItems != null) {
LineItem[] items = lineItems.toArray(new LineItem[lineItems.size()]);
request.setItems(items);
}
List<Option> listOptions = refund.getOptions();
if (listOptions != null && !listOptions.isEmpty()) {
List<Option> listConvert = new ArrayList<Option>();
for (Option value : listOptions) {
Option op = new Option();
op.setValue(value.getValue());
listConvert.add(op);
}
request.setOptions(listConvert.toArray(new Option[listConvert.size()]));
}
}
return request;
}
}
|
3e1c40d6dbeed89df0b16d0f4ef0c9d11f9779a6 | 1,047 | java | Java | liuyi-im-backend/src/main/java/com/creolophus/im/service/UserClientService.java | magicnana999/liuyi-im | f9e6e1d4719f37efe78ce0c3812228b22f2d016d | [
"MIT"
] | 8 | 2020-10-21T02:20:55.000Z | 2021-12-21T16:15:00.000Z | liuyi-im-backend/src/main/java/com/creolophus/im/service/UserClientService.java | magicnana999/liuyi-im | f9e6e1d4719f37efe78ce0c3812228b22f2d016d | [
"MIT"
] | null | null | null | liuyi-im-backend/src/main/java/com/creolophus/im/service/UserClientService.java | magicnana999/liuyi-im | f9e6e1d4719f37efe78ce0c3812228b22f2d016d | [
"MIT"
] | 3 | 2020-11-29T17:16:21.000Z | 2021-07-22T05:53:35.000Z | 29.914286 | 90 | 0.774594 | 11,980 | package com.creolophus.im.service;
import com.creolophus.im.common.base.BaseService;
import com.creolophus.im.domain.GatewayAddr;
import com.creolophus.im.storage.GatewayStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author magicnana
* @date 2019/6/20 下午6:27
*/
@Service
public class UserClientService extends BaseService {
private static final Logger logger = LoggerFactory.getLogger(UserClientService.class);
@Resource
private GatewayStorage gatewayStorage;
public GatewayAddr findUserClient(Long userId) {
return gatewayStorage.getUserClient(userId);
}
public void registerUserClient(String gatewayIp, Integer gatewayPort, Long userId) {
gatewayStorage.registerUserClient(gatewayIp, gatewayPort, userId);
}
public void unregisterUserClient(String gatewayIp, Integer gatewayPort, Long userId) {
gatewayStorage.unregisterUserClient(gatewayIp, gatewayPort, userId);
}
} |
3e1c4126ea365ca3f87ee2cdc07cd7faf512335a | 257 | java | Java | src/main/java/TTT/ITestService.java | michael-wang-0624/wms | 1ae933bd7bc368fe583d311dceea0c07cadd7d42 | [
"Apache-2.0"
] | null | null | null | src/main/java/TTT/ITestService.java | michael-wang-0624/wms | 1ae933bd7bc368fe583d311dceea0c07cadd7d42 | [
"Apache-2.0"
] | null | null | null | src/main/java/TTT/ITestService.java | michael-wang-0624/wms | 1ae933bd7bc368fe583d311dceea0c07cadd7d42 | [
"Apache-2.0"
] | null | null | null | 15.117647 | 56 | 0.700389 | 11,981 | package TTT;
import com.stylefeng.guns.common.persistence.model.Test;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author stylefeng
* @since 2017-08-03
*/
public interface ITestService extends IService<Test> {
}
|
3e1c41577b2fd92aaa210009decb3548ed8efe9a | 3,717 | java | Java | src/main/java/org/apache/hadoop/hbase/index/test/ScanPreprocessTest.java | winter-ict/LCIndex | 601f5fffb9798f9e481a990ef083d8b930605c40 | [
"Apache-2.0"
] | 12 | 2017-05-16T02:02:53.000Z | 2018-01-17T12:02:28.000Z | src/main/java/org/apache/hadoop/hbase/index/test/ScanPreprocessTest.java | fengchen8086/LCIndex | 601f5fffb9798f9e481a990ef083d8b930605c40 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/hadoop/hbase/index/test/ScanPreprocessTest.java | fengchen8086/LCIndex | 601f5fffb9798f9e481a990ef083d8b930605c40 | [
"Apache-2.0"
] | 1 | 2017-05-18T15:19:03.000Z | 2017-05-18T15:19:03.000Z | 35.066038 | 98 | 0.647027 | 11,982 | package org.apache.hadoop.hbase.index.test;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.FilterList.Operator;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.index.client.IndexConstants;
import org.apache.hadoop.hbase.util.Bytes;
public class ScanPreprocessTest {
public static void main(String[] args) throws IOException {
HTable table = new HTable(HBaseConfiguration.create(), "orders");
Scan scan = new Scan();
FilterList f1 = new FilterList(Operator.MUST_PASS_ALL);
f1.addFilter(new SingleColumnValueFilter(Bytes.toBytes("f"), Bytes.toBytes("c3"),
CompareOp.LESS, Bytes.toBytes(3000.0)));
f1.addFilter(new SingleColumnValueFilter(Bytes.toBytes("f"), Bytes.toBytes("c5"),
CompareOp.EQUAL, Bytes.toBytes("1-URGENT")));
scan.setFilter(f1);
scan.setAttribute(IndexConstants.SCAN_WITH_INDEX, Bytes.toBytes(true));
scan.setAttribute(IndexConstants.MAX_SCAN_SCALE, Bytes.toBytes(0.5f));
scan.setCacheBlocks(false);
scan.setCaching(100000);
// scan.setStopRow(Bytes.toBytes("13"));
ResultScanner scanner=table.getScanner(scan);
Result result = null;
long startTime = System.currentTimeMillis();
int count = 0;
boolean print=false;
while ((result = scanner.next()) != null) {
count++;
if (print) {
println(result);
}
if (count % 100000 == 0) {
System.out.println("Time elapsed: " + (System.currentTimeMillis() - startTime)
+ " ms, result count: " + count);
}
}
long stopTime = System.currentTimeMillis();
System.out.println("Time elapsed: " + (stopTime - startTime) + " ms, result count: " + count);
table.close();
}
static void println(Result result) {
StringBuilder sb = new StringBuilder();
sb.append("row=" + Bytes.toString(result.getRow()));
List<KeyValue> kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c1"));
if (kv.size() != 0) {
sb.append(", f:c1=" + Bytes.toInt(kv.get(0).getValue()));
}
kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c2"));
if (kv.size() != 0) {
sb.append(", f:c2=" + Bytes.toString(kv.get(0).getValue()));
}
kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c3"));
if (kv.size() != 0) {
sb.append(", f:c3=" + Bytes.toDouble(kv.get(0).getValue()));
}
kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c4"));
if (kv.size() != 0) {
sb.append(", f:c4=" + Bytes.toString(kv.get(0).getValue()));
}
kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c5"));
if (kv.size() != 0) {
sb.append(", f:c5=" + Bytes.toString(kv.get(0).getValue()));
}
kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c6"));
if (kv.size() != 0) {
sb.append(", f:c6=" + Bytes.toString(kv.get(0).getValue()));
}
kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c7"));
if (kv.size() != 0) {
sb.append(", f:c7=" + Bytes.toInt(kv.get(0).getValue()));
}
kv = result.getColumn(Bytes.toBytes("f"), Bytes.toBytes("c8"));
if (kv.size() != 0) {
sb.append(", f:c8=" + Bytes.toString(kv.get(0).getValue()));
}
System.out.println(sb.toString());
}
}
|
3e1c421a5cd0d368b8508b5b83016770daf10356 | 686 | java | Java | EntidadesOCR/build/generated-sources/ap-source-output/entidades/Parametro_.java | jsebastianbarretoj99/ProyectoFinalBases | 305140b682cec9ff70b88c0ea4f8be8328d3d6a8 | [
"CC0-1.0"
] | null | null | null | EntidadesOCR/build/generated-sources/ap-source-output/entidades/Parametro_.java | jsebastianbarretoj99/ProyectoFinalBases | 305140b682cec9ff70b88c0ea4f8be8328d3d6a8 | [
"CC0-1.0"
] | null | null | null | EntidadesOCR/build/generated-sources/ap-source-output/entidades/Parametro_.java | jsebastianbarretoj99/ProyectoFinalBases | 305140b682cec9ff70b88c0ea4f8be8328d3d6a8 | [
"CC0-1.0"
] | null | null | null | 38.111111 | 81 | 0.8207 | 11,983 | package entidades;
import entidades.Renta;
import javax.annotation.Generated;
import javax.persistence.metamodel.CollectionAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2021-06-04T09:43:56")
@StaticMetamodel(Parametro.class)
public class Parametro_ {
public static volatile CollectionAttribute<Parametro, Renta> rentaCollection;
public static volatile SingularAttribute<Parametro, Integer> valor;
public static volatile SingularAttribute<Parametro, Integer> tasacarros;
public static volatile SingularAttribute<Parametro, Integer> id;
} |
3e1c42d39ec515ae67904a5256aa5eb10b477a3d | 3,733 | java | Java | components/apimgt/org.wso2.carbon.apimgt.eventing.hub/src/main/java/org/wso2/carbon/apimgt/eventing/hub/EventHubEventPublisherFactory.java | madushadhanushka/carbon-apimgt-1 | 873cc85a48df2ae92cd0541fb8f7ad6536b613d7 | [
"Apache-2.0"
] | null | null | null | components/apimgt/org.wso2.carbon.apimgt.eventing.hub/src/main/java/org/wso2/carbon/apimgt/eventing/hub/EventHubEventPublisherFactory.java | madushadhanushka/carbon-apimgt-1 | 873cc85a48df2ae92cd0541fb8f7ad6536b613d7 | [
"Apache-2.0"
] | 1 | 2021-06-03T10:43:35.000Z | 2021-06-03T11:34:04.000Z | components/apimgt/org.wso2.carbon.apimgt.eventing.hub/src/main/java/org/wso2/carbon/apimgt/eventing/hub/EventHubEventPublisherFactory.java | madushadhanushka/carbon-apimgt-1 | 873cc85a48df2ae92cd0541fb8f7ad6536b613d7 | [
"Apache-2.0"
] | 1 | 2018-02-08T09:56:04.000Z | 2018-02-08T09:56:04.000Z | 51.136986 | 109 | 0.770694 | 11,984 | /*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.eventing.hub;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.eventing.EventPublisher;
import org.wso2.carbon.apimgt.eventing.EventPublisherFactory;
import org.wso2.carbon.apimgt.eventing.EventPublisherType;
import org.wso2.carbon.apimgt.eventing.hub.internal.ServiceReferenceHolder;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import java.util.HashMap;
import java.util.Map;
/**
* Factory for getting event hub event publisher instances.
*/
public class EventHubEventPublisherFactory implements EventPublisherFactory {
private static final Log log = LogFactory.getLog(EventHubEventPublisherFactory.class);
@Override
public void configure(Map<String, String> configuration) {
OutputEventAdapterConfiguration adapterConfiguration = new OutputEventAdapterConfiguration();
adapterConfiguration.setName(EventHubEventPublisherConstants.EVENT_HUB_NOTIFICATION_EVENT_PUBLISHER);
adapterConfiguration.setType(EventHubEventPublisherConstants.BLOCKING_EVENT_TYPE);
adapterConfiguration.setMessageFormat(EventHubEventPublisherConstants.BLOCKING_EVENT_FORMAT);
Map<String, String> adapterParameters = new HashMap<>();
adapterParameters.put(EventHubEventPublisherConstants.RECEIVER_URL,
configuration.get(EventHubEventPublisherConstants.RECEIVER_URL));
adapterParameters.put(EventHubEventPublisherConstants.AUTHENTICATOR_URL,
configuration.get(EventHubEventPublisherConstants.AUTHENTICATOR_URL));
adapterParameters.put(EventHubEventPublisherConstants.USERNAME,
configuration.get(EventHubEventPublisherConstants.USERNAME));
adapterParameters.put(EventHubEventPublisherConstants.PASSWORD,
configuration.get(EventHubEventPublisherConstants.PASSWORD));
adapterParameters.put(EventHubEventPublisherConstants.PROTOCOL,
configuration.get(EventHubEventPublisherConstants.PROTOCOL));
adapterParameters.put(EventHubEventPublisherConstants.PUBLISHING_MODE,
configuration.get(EventHubEventPublisherConstants.PUBLISHING_MODE));
adapterParameters.put(EventHubEventPublisherConstants.PUBLISHING_TIME_OUT,
configuration.get(EventHubEventPublisherConstants.PUBLISHING_TIME_OUT));
adapterConfiguration.setStaticProperties(adapterParameters);
try {
ServiceReferenceHolder.getInstance().getOutputEventAdapterService().create(adapterConfiguration);
} catch (OutputEventAdapterException e) {
log.warn("Exception occurred while creating WSO2 Event Adapter. Event notification may not work "
+ "properly", e);
}
}
@Override
public EventPublisher getEventPublisher(EventPublisherType eventPublisherType) {
return new EventHubEventPublisher();
}
}
|
3e1c42f26e842b849ae1443cf4ca25de213150dd | 1,075 | java | Java | orchextrasdk-control/src/main/java/com/gigigo/orchextra/control/presenters/scanner/entities/ScannerResultPresenter.java | nuborisar/oxcustomMc | aafc375cb8e24c0ed7cdf36effc4fb443f0113a9 | [
"Apache-2.0"
] | null | null | null | orchextrasdk-control/src/main/java/com/gigigo/orchextra/control/presenters/scanner/entities/ScannerResultPresenter.java | nuborisar/oxcustomMc | aafc375cb8e24c0ed7cdf36effc4fb443f0113a9 | [
"Apache-2.0"
] | null | null | null | orchextrasdk-control/src/main/java/com/gigigo/orchextra/control/presenters/scanner/entities/ScannerResultPresenter.java | nuborisar/oxcustomMc | aafc375cb8e24c0ed7cdf36effc4fb443f0113a9 | [
"Apache-2.0"
] | null | null | null | 26.219512 | 75 | 0.698605 | 11,985 | /*
* Created by Orchextra
*
* Copyright (C) 2016 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.control.presenters.scanner.entities;
public class ScannerResultPresenter {
private String content;
private String type;
public void setContent(String content) {
this.content = content;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public String getType() {
return type;
}
}
|
3e1c4306ea57e992e774e8b83ac943252d84b356 | 944 | java | Java | src/main/java/org/apache/ibatis/scripting/xmltags/SqlNode.java | jiangyinsuo/mybatis-code | 369c1aa7a9de4bdf388eb36d2f064198a0f39539 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/ibatis/scripting/xmltags/SqlNode.java | jiangyinsuo/mybatis-code | 369c1aa7a9de4bdf388eb36d2f064198a0f39539 | [
"ECL-2.0",
"Apache-2.0"
] | 137 | 2020-07-17T07:35:23.000Z | 2022-03-09T08:02:22.000Z | src/main/java/org/apache/ibatis/scripting/xmltags/SqlNode.java | jiangyinsuo/mybatis-code | 369c1aa7a9de4bdf388eb36d2f064198a0f39539 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 29.5 | 75 | 0.713983 | 11,986 | /**
* Copyright ${license.git.copyrightYears} 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.apache.ibatis.scripting.xmltags;
/**
* @author Clinton Begin
* SQL Node 接口,每个 XML Node 会解析成对应的 SQL Node 对象
*/
public interface SqlNode {
/**
* 应用当前 SQL Node 节点
*
* @param context 上下文
* @return 当前 SQL Node 节点是否应用成功。
*/
boolean apply(DynamicContext context);
}
|
3e1c431770e46ee4cea595cb843982024530d140 | 1,762 | java | Java | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-backend/src/main/java/org/kie/workbench/common/stunner/bpmn/backend/converters/tostunner/properties/GatewayPropertyReader.java | tkobayas/kie-wb-common | 2c69347f0f634268fb7cca77ccf9e1311f1486e9 | [
"Apache-2.0"
] | 34 | 2017-05-21T11:28:40.000Z | 2021-07-03T13:15:03.000Z | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-backend/src/main/java/org/kie/workbench/common/stunner/bpmn/backend/converters/tostunner/properties/GatewayPropertyReader.java | tkobayas/kie-wb-common | 2c69347f0f634268fb7cca77ccf9e1311f1486e9 | [
"Apache-2.0"
] | 2,576 | 2017-03-14T00:57:07.000Z | 2022-03-29T07:52:38.000Z | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-backend/src/main/java/org/kie/workbench/common/stunner/bpmn/backend/converters/tostunner/properties/GatewayPropertyReader.java | tkobayas/kie-wb-common | 2c69347f0f634268fb7cca77ccf9e1311f1486e9 | [
"Apache-2.0"
] | 158 | 2017-03-15T08:55:40.000Z | 2021-11-19T14:07:17.000Z | 38.304348 | 114 | 0.742338 | 11,987 | /*
* Copyright 2018 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.workbench.common.stunner.bpmn.backend.converters.tostunner.properties;
import org.eclipse.bpmn2.Gateway;
import org.eclipse.bpmn2.di.BPMNDiagram;
import org.eclipse.bpmn2.di.BPMNShape;
import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.CustomAttribute;
import org.kie.workbench.common.stunner.core.graph.content.Bounds;
public class GatewayPropertyReader extends FlowElementPropertyReader {
// These values are present in the SVG declaration for the gateway shape.
static final double WIDTH = 56d;
static final double HEIGHT = 56d;
public GatewayPropertyReader(Gateway element, BPMNDiagram diagram, BPMNShape shape, double resolutionFactor) {
super(element, diagram, shape, resolutionFactor);
}
@Override
protected Bounds computeBounds(org.eclipse.dd.dc.Bounds bounds) {
final double x = bounds.getX() * resolutionFactor;
final double y = bounds.getY() * resolutionFactor;
return Bounds.create(x, y, x + WIDTH, y + HEIGHT);
}
public String getDefaultRoute() {
return CustomAttribute.dg.of(element).get();
}
}
|
3e1c437a2265298f7d856f1c2e5c8395b0c86c53 | 2,313 | java | Java | MLModelService/src/main/java/io/pivotal/rtsmadlib/client/MADlibRESTServiceApplication.java | pivotal/Realtime-scoring-for-MADlib | 4ed6500bdd3422c3d090d8c6c679d940c2b7c4f4 | [
"Apache-2.0"
] | 9 | 2019-08-13T11:02:44.000Z | 2021-03-29T17:10:33.000Z | MLModelService/src/main/java/io/pivotal/rtsmadlib/client/MADlibRESTServiceApplication.java | pivotal/Realtime-scoring-for-MADlib | 4ed6500bdd3422c3d090d8c6c679d940c2b7c4f4 | [
"Apache-2.0"
] | 1 | 2019-08-12T16:11:28.000Z | 2019-08-12T16:11:43.000Z | MLModelService/src/main/java/io/pivotal/rtsmadlib/client/MADlibRESTServiceApplication.java | pivotal/Realtime-scoring-for-MADlib | 4ed6500bdd3422c3d090d8c6c679d940c2b7c4f4 | [
"Apache-2.0"
] | 7 | 2019-10-22T04:07:40.000Z | 2021-05-18T18:28:36.000Z | 36.714286 | 95 | 0.731518 | 11,988 | /**********************************************************************************************
Copyright 2019 Pivotal Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*********************************************************************************************/
package io.pivotal.rtsmadlib.client;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Profile;
import io.pivotal.rtsmadlib.client.db.repo.ContainerDbRepository;
import io.pivotal.rtsmadlib.client.db.repo.ExportImplortRepository;
import io.pivotal.rtsmadlib.client.meta.AppProperties;
/**
* @author Sridhar Paladugu
*
*/
@SpringBootApplication(scanBasePackages = "io.pivotal")
@Profile("!test")
public class MADlibRESTServiceApplication implements CommandLineRunner {
static final Log log = LogFactory.getLog(MADlibRESTServiceApplication.class.getName());
public static void main(String[] args) {
SpringApplication.run(MADlibRESTServiceApplication.class, args);
}
@Autowired
ExportImplortRepository exportImplortRepository;
@Autowired
ContainerDbRepository containerDbRespository;
@Autowired
AppProperties props;
@Override
public void run(String... args) throws Exception {
log.debug("Boot strapping the local postgres madlib model tables greenplum .......");
exportImplortRepository.performExportImportModel();
containerDbRespository.fetchActorTableMetada();
log.debug("Finished importing madlib model artifacts to container!");
log.debug("Container is ready for requests!");
}
}
|
3e1c4436d1538e9edb21b7c65956283c62841c12 | 594 | java | Java | src/test/java/org/apache/ibatis/submitted/flush_statement_npe/Person.java | yangfancoming/mybatis | 7cd9c6093a608a0e0da32155e75d1fddd090c8d5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/test/java/org/apache/ibatis/submitted/flush_statement_npe/Person.java | yangfancoming/mybatis | 7cd9c6093a608a0e0da32155e75d1fddd090c8d5 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2021-12-10T01:18:31.000Z | 2021-12-14T21:27:31.000Z | src/test/java/org/apache/ibatis/submitted/flush_statement_npe/Person.java | yangfancoming/mybatis | 7cd9c6093a608a0e0da32155e75d1fddd090c8d5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 22 | 56 | 0.62963 | 11,989 |
package org.apache.ibatis.submitted.flush_statement_npe;
public class Person {
private Integer id;
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
3e1c443c824ab699176829b54704b35e60b82837 | 3,226 | java | Java | src/main/java/net/openrs/cache/tools/NpcModelDumper.java | Rune-Status/OSRS-sprite-editor | 3139857810cc1e5960af08475ee93312f6cdfbaa | [
"MIT"
] | 1 | 2018-08-24T23:43:35.000Z | 2018-08-24T23:43:35.000Z | src/main/java/net/openrs/cache/tools/NpcModelDumper.java | Rune-Status/OSRS-sprite-editor | 3139857810cc1e5960af08475ee93312f6cdfbaa | [
"MIT"
] | null | null | null | src/main/java/net/openrs/cache/tools/NpcModelDumper.java | Rune-Status/OSRS-sprite-editor | 3139857810cc1e5960af08475ee93312f6cdfbaa | [
"MIT"
] | 1 | 2018-08-24T23:43:38.000Z | 2018-08-24T23:43:38.000Z | 26.016129 | 110 | 0.677929 | 11,990 | /**
* Copyright (c) Kyle Fricilone
*
* 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.openrs.cache.tools;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import net.openrs.cache.Cache;
import net.openrs.cache.Constants;
import net.openrs.cache.Container;
import net.openrs.cache.FileStore;
import net.openrs.cache.ReferenceTable;
import net.openrs.cache.type.npcs.NpcType;
import net.openrs.cache.type.npcs.NpcTypeList;
/**
* Dumps only models for npcs
*
* @author Freyr
*
* @since 04/01/2017
*/
public class NpcModelDumper {
public static void main(String[] args) throws IOException {
File directory = new File(Constants.MODEL_PATH + "/npcs");
if (!directory.exists()) {
directory.mkdirs();
}
try (Cache cache = new Cache(FileStore.open(Constants.CACHE_PATH))) {
NpcTypeList list = new NpcTypeList();
list.initialize(cache);
Set<Integer> set = new HashSet<>();
for (int i = 0; i < list.size(); i++) {
NpcType npc = list.list(i);
if (npc == null) {
continue;
}
int[] models = npc.getModels();
if (models != null) {
Arrays.stream(models).forEach(set::add);
}
int[] headModels = npc.getModels_2();
if (headModels != null) {
Arrays.stream(headModels).forEach(set::add);
}
}
ReferenceTable table = cache.getReferenceTable(7);
Iterator<Integer> itr = set.iterator();
int count = 0;
int size = set.size();
while (itr.hasNext()) {
int i = itr.next();
if (table.getEntry(i) == null) {
continue;
}
Container container = cache.read(7, i);
byte[] bytes = new byte[container.getData().limit()];
container.getData().get(bytes);
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(directory, i + ".dat")))) {
dos.write(bytes);
}
count++;
double progress = (double) (count) / size * 100;
System.out.printf("%.2f%s\n", progress, "%");
itr.remove();
}
}
}
}
|
3e1c45049c161d1f197a762fdb67a6244e6c62ab | 3,288 | java | Java | IDEAworkspace/src/com/zxy/test/nio/NIOServer.java | xiaomaozu/zxy-javase-base | 8d25bd385a4011b8fee74c2a6e81071143ccfca4 | [
"Apache-2.0"
] | 1 | 2018-07-25T09:50:38.000Z | 2018-07-25T09:50:38.000Z | IDEAworkspace/src/com/zxy/test/nio/NIOServer.java | xiaomaozu/zxy-javase-base | 8d25bd385a4011b8fee74c2a6e81071143ccfca4 | [
"Apache-2.0"
] | null | null | null | IDEAworkspace/src/com/zxy/test/nio/NIOServer.java | xiaomaozu/zxy-javase-base | 8d25bd385a4011b8fee74c2a6e81071143ccfca4 | [
"Apache-2.0"
] | null | null | null | 31.92233 | 75 | 0.629562 | 11,991 | package com.zxy.test.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NIOServer {
private int flag=1;
// private int port=8088;
private int blockSize=4096;
//分配空间大小,发送数据的缓存区
private ByteBuffer sendbuffer=ByteBuffer.allocate(blockSize);
//接送数据的缓存区
private ByteBuffer receivebuffer=ByteBuffer.allocate(blockSize);
//选择器
private Selector selector;
public NIOServer(int port) throws IOException {
//打开服务端的channel
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
//是否堵塞
serverSocketChannel.configureBlocking(false);
//获得一个socket对象
ServerSocket serverSocket= serverSocketChannel.socket();
//绑定IP、端口
serverSocket.bind(new InetSocketAddress(port));
//打开选择器
selector=Selector.open();
//注册
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
System.out.println("Server start"+port);
}
//监听,不断的监听
public void listen() throws IOException{
while(true){
selector.select();
//返回的是一个集合
Set<SelectionKey> selectionkeys=selector.selectedKeys();
//遍历它
Iterator<SelectionKey> iterator=selectionkeys.iterator();
while(iterator.hasNext()){
SelectionKey selectionKey=iterator.next();
iterator.remove();
//业务逻缉
}
}
}
private void handleKey(SelectionKey selectionKey) throws IOException{
ServerSocketChannel server=null;
SocketChannel client=null;
String receiveText;
String sendText;
int count=0;
if(selectionKey.isAcceptable()){
server=(ServerSocketChannel) selectionKey.channel();
client =server.accept();
client.configureBlocking(false);
client.register(selector,selectionKey.OP_READ);
}else if(selectionKey.isReadable()){
client=(SocketChannel) selectionKey.channel();
count=client.read(receivebuffer);
if(count>0){
receiveText=new String(receivebuffer.array(),0,count);
System.out.println("服务端接收到客户端的信息:"+receiveText);
//注册写的事件
client.register(selector,selectionKey.OP_WRITE);
}
}else if(selectionKey.isWritable()){
sendbuffer.clear();
client=(SocketChannel)selectionKey.channel();
//发送的数据
sendText="msg send to to client"+flag++;
//写到我们的缓冲区里面去
sendbuffer.put(sendText.getBytes());
//Buffer有两种模式,写模式和读模式。在写模式下调用flip()之后,Buffer从写模式变成读模式。
sendbuffer.flip();
client.write(sendbuffer);
System.out.println("服务端发送数据给客户端:"+sendText);
}
}
public static void main(String[] args) throws IOException{
int port=7080;
NIOServer server=new NIOServer(port);
server.listen();
}
}
|
3e1c452720cd0d0f9ea9799bd3a8ccb5caeb6272 | 174 | java | Java | app/src/main/java/info/nightscout/android/medtronic/exception/UsbException.java | janrpn/600SeriesAndroidUploader | 96be90d3b6ac7bf70b6c98aa34d1e8ddd86a2eca | [
"MIT"
] | 172 | 2017-04-23T19:58:52.000Z | 2022-03-01T22:05:18.000Z | app/src/main/java/info/nightscout/android/medtronic/exception/UsbException.java | janrpn/600SeriesAndroidUploader | 96be90d3b6ac7bf70b6c98aa34d1e8ddd86a2eca | [
"MIT"
] | 169 | 2017-04-15T11:24:21.000Z | 2022-03-06T19:31:44.000Z | app/src/main/java/info/nightscout/android/medtronic/exception/UsbException.java | janrpn/600SeriesAndroidUploader | 96be90d3b6ac7bf70b6c98aa34d1e8ddd86a2eca | [
"MIT"
] | 322 | 2017-04-15T19:26:09.000Z | 2022-03-07T07:18:13.000Z | 21.75 | 52 | 0.735632 | 11,992 | package info.nightscout.android.medtronic.exception;
public class UsbException extends Throwable {
public UsbException(String message) {
super(message);
}
}
|
3e1c4529638119f4f00a72c16e74edf5e8f72dbb | 9,935 | java | Java | spring/boot-actuator-autoconfigure/src/main/java/com/linecorp/armeria/spring/actuate/ArmeriaSpringActuatorAutoConfiguration.java | jacobis/armeria | bcc346cfb9ee9a6e1547b7a3d5027fa6ef9e5d9b | [
"Apache-2.0"
] | 1 | 2020-02-18T02:50:16.000Z | 2020-02-18T02:50:16.000Z | spring/boot-actuator-autoconfigure/src/main/java/com/linecorp/armeria/spring/actuate/ArmeriaSpringActuatorAutoConfiguration.java | jacobis/armeria | bcc346cfb9ee9a6e1547b7a3d5027fa6ef9e5d9b | [
"Apache-2.0"
] | null | null | null | spring/boot-actuator-autoconfigure/src/main/java/com/linecorp/armeria/spring/actuate/ArmeriaSpringActuatorAutoConfiguration.java | jacobis/armeria | bcc346cfb9ee9a6e1547b7a3d5027fa6ef9e5d9b | [
"Apache-2.0"
] | null | null | null | 46.425234 | 104 | 0.660695 | 11,993 | /*
* Copyright 2019 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.spring.actuate;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.endpoint.EndpointFilter;
import org.springframework.boot.actuate.endpoint.http.ActuatorMediaType;
import org.springframework.boot.actuate.endpoint.invoke.OperationInvokerAdvisor;
import org.springframework.boot.actuate.endpoint.invoke.ParameterValueMapper;
import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver;
import org.springframework.boot.actuate.endpoint.web.EndpointMapping;
import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes;
import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint;
import org.springframework.boot.actuate.endpoint.web.Link;
import org.springframework.boot.actuate.endpoint.web.PathMapper;
import org.springframework.boot.actuate.endpoint.web.WebEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.WebOperationRequestPredicate;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpointDiscoverer;
import org.springframework.boot.actuate.health.HealthStatusHttpMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.server.HttpService;
import com.linecorp.armeria.server.Route;
import com.linecorp.armeria.server.cors.CorsService;
import com.linecorp.armeria.server.cors.CorsServiceBuilder;
import com.linecorp.armeria.spring.ArmeriaServerConfigurator;
/**
* A {@link Configuration} to enable actuator endpoints on an Armeria server. Corresponds to
* {@link org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointAutoConfiguration}.
*/
@Configuration
@AutoConfigureAfter(EndpointAutoConfiguration.class)
@EnableConfigurationProperties({ WebEndpointProperties.class, CorsEndpointProperties.class })
public class ArmeriaSpringActuatorAutoConfiguration {
@VisibleForTesting
static final MediaType ACTUATOR_MEDIA_TYPE = MediaType.parse(ActuatorMediaType.V3_JSON);
private static final List<String> MEDIA_TYPES =
ImmutableList.of(ActuatorMediaType.V3_JSON, "application/json");
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Bean
@ConditionalOnMissingBean
EndpointMediaTypes endpointMediaTypes() {
return new EndpointMediaTypes(MEDIA_TYPES, MEDIA_TYPES);
}
@Bean
@ConditionalOnMissingBean(WebEndpointsSupplier.class)
WebEndpointDiscoverer webEndpointDiscoverer(
ApplicationContext applicationContext,
ParameterValueMapper parameterValueMapper,
EndpointMediaTypes endpointMediaTypes,
ObjectProvider<PathMapper> endpointPathMappers,
ObjectProvider<OperationInvokerAdvisor> invokerAdvisors,
ObjectProvider<EndpointFilter<ExposableWebEndpoint>> filters) {
return new WebEndpointDiscoverer(applicationContext,
parameterValueMapper,
endpointMediaTypes,
endpointPathMappers.orderedStream().collect(toImmutableList()),
invokerAdvisors.orderedStream().collect(toImmutableList()),
filters.orderedStream().collect(toImmutableList()));
}
@Bean
@ConditionalOnMissingBean // In case HealthEndpointAutoConfiguration is excluded
HealthStatusHttpMapper healthStatusHttpMapper() {
return new HealthStatusHttpMapper();
}
@Bean
ArmeriaServerConfigurator actuatorServerConfigurator(
WebEndpointsSupplier endpointsSupplier,
EndpointMediaTypes mediaTypes,
WebEndpointProperties properties,
HealthStatusHttpMapper healthMapper,
CorsEndpointProperties corsProperties) {
final EndpointMapping endpointMapping = new EndpointMapping(properties.getBasePath());
final Collection<ExposableWebEndpoint> endpoints = endpointsSupplier.getEndpoints();
return sb -> {
final CorsServiceBuilder cors;
if (!corsProperties.getAllowedOrigins().isEmpty()) {
cors = CorsService.builder(corsProperties.getAllowedOrigins());
if (!corsProperties.getAllowedMethods().contains("*")) {
if (corsProperties.getAllowedMethods().isEmpty()) {
cors.allowRequestMethods(HttpMethod.GET);
} else {
cors.allowRequestMethods(
corsProperties.getAllowedMethods().stream().map(HttpMethod::valueOf)
::iterator);
}
}
if (!corsProperties.getAllowedHeaders().isEmpty() &&
!corsProperties.getAllowedHeaders().contains("*")) {
cors.allowRequestHeaders(corsProperties.getAllowedHeaders());
}
if (!corsProperties.getExposedHeaders().isEmpty()) {
cors.exposeHeaders(corsProperties.getExposedHeaders());
}
if (Boolean.TRUE.equals(corsProperties.getAllowCredentials())) {
cors.allowCredentials();
}
cors.maxAge(corsProperties.getMaxAge());
} else {
cors = null;
}
endpoints.stream()
.flatMap(endpoint -> endpoint.getOperations().stream())
.forEach(operation -> {
final WebOperationRequestPredicate predicate = operation.getRequestPredicate();
final String path = endpointMapping.createSubPath(predicate.getPath());
final Route route = route(predicate.getHttpMethod().name(),
path,
predicate.getConsumes(),
predicate.getProduces());
sb.service(route, new WebOperationService(operation, healthMapper));
if (cors != null) {
cors.route(path);
}
});
if (StringUtils.hasText(endpointMapping.getPath())) {
final Route route = route(
HttpMethod.GET.name(),
endpointMapping.getPath(),
ImmutableList.of(),
mediaTypes.getProduced()
);
final HttpService linksService = (ctx, req) -> {
final Map<String, Link> links =
new EndpointLinksResolver(endpoints).resolveLinks(req.path());
return HttpResponse.of(
HttpStatus.OK,
ACTUATOR_MEDIA_TYPE,
OBJECT_MAPPER.writeValueAsBytes(ImmutableMap.of("_links", links))
);
};
sb.service(route, linksService);
if (cors != null) {
cors.route(endpointMapping.getPath());
}
}
if (cors != null) {
sb.routeDecorator().pathPrefix("/").build(cors.newDecorator());
}
};
}
private static Route route(
String method, String path, Collection<String> consumes, Collection<String> produces) {
return Route.builder()
.path(path)
.methods(ImmutableSet.of(HttpMethod.valueOf(method)))
.consumes(convertMediaTypes(consumes))
.produces(convertMediaTypes(produces))
.build();
}
private static Set<MediaType> convertMediaTypes(Iterable<String> mediaTypes) {
return Streams.stream(mediaTypes).map(MediaType::parse).collect(toImmutableSet());
}
}
|
3e1c45a704069a6fe82537c2654e98b67103bfc5 | 4,855 | java | Java | _src/Chapter01/worldgdp/src/test/java/com/nilangpatel/test/config/controller/api/CountryLanguageAPIControllerTest.java | paullewallencom/spring-978-1-7883-9041-5 | d73f33b9881261aaab51a178ca1ab8d0084f19ba | [
"Apache-2.0"
] | 41 | 2019-02-23T15:25:23.000Z | 2022-03-01T23:01:57.000Z | Chapter01/worldgdp/src/test/java/com/nilangpatel/test/config/controller/api/CountryLanguageAPIControllerTest.java | hocyadav/Spring-5.0-Projects | 3ae4f71c060eb56241cfa1a1803d0e5f30457b38 | [
"MIT"
] | 13 | 2019-03-05T05:29:40.000Z | 2022-03-17T22:27:49.000Z | Chapter01/worldgdp/src/test/java/com/nilangpatel/test/config/controller/api/CountryLanguageAPIControllerTest.java | hocyadav/Spring-5.0-Projects | 3ae4f71c060eb56241cfa1a1803d0e5f30457b38 | [
"MIT"
] | 63 | 2019-02-27T06:20:48.000Z | 2022-03-29T04:22:24.000Z | 35.962963 | 89 | 0.775901 | 11,994 | package com.nilangpatel.test.config.controller.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
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.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nilangpatel.worldgdp.AppConfiguration;
import com.nilangpatel.worldgdp.dao.CountryLanguageDAO;
import com.nilangpatel.worldgdp.model.CountryLanguage;
//@Slf4j
@RunWith(SpringRunner.class)
@SpringJUnitWebConfig(classes = {AppConfiguration.class})
public class CountryLanguageAPIControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Autowired CountryLanguageDAO cLanguageDao;
@Autowired
NamedParameterJdbcTemplate namedParamJdbcTemplate;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
cLanguageDao.setNamedParamJdbcTemplate(namedParamJdbcTemplate);
}
@Test
public void testGetLanguages() throws Exception {
String countryCode = "IND";
this.mockMvc.perform(get("/api/languages/{countryCode}", countryCode)
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$.length()", is(10)))
.andExpect(jsonPath("$[0].language", is("Hindi")));
}
@Test
public void testAddLanguage() throws Exception{
String countryCode = "IND";
CountryLanguage cl = new CountryLanguage();
cl.setCountryCode(countryCode);
cl.setIsOfficial("1");
cl.setLanguage("TEST");
cl.setPercentage(100d);
ObjectMapper objectMapper = new ObjectMapper();
MvcResult result = this.mockMvc.perform(
post("/api/languages/{countryCode}",countryCode)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(cl))
).andExpect(status().isOk())
.andReturn();
List<CountryLanguage> langs = cLanguageDao.getLanguages(countryCode, 1);
CountryLanguage first = langs.get(0);
assertThat(first.getLanguage()).isEqualTo("TEST");
cLanguageDao.deleteLanguage(countryCode, first.getLanguage());
}
@Test
public void testAddLanguage_DuplicateLang() throws Exception{
String countryCode = "IND";
CountryLanguage cl = new CountryLanguage();
cl.setCountryCode(countryCode);
cl.setIsOfficial("1");
cl.setLanguage("TEST");
cl.setPercentage(100d);
cLanguageDao.addLanguage(countryCode, cl);
ObjectMapper objectMapper = new ObjectMapper();
MvcResult result = this.mockMvc.perform(
post("/api/languages/{countryCode}",countryCode)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(cl))
).andExpect(status().isBadRequest())
.andReturn();
cLanguageDao.deleteLanguage(countryCode, cl.getLanguage());
}
@Test
public void testDeleteCity() throws Exception {
String countryCode = "IND";
CountryLanguage cl = new CountryLanguage();
cl.setCountryCode(countryCode);
cl.setIsOfficial("1");
cl.setLanguage("TEST");
cl.setPercentage(100d);
cLanguageDao.addLanguage(countryCode, cl);
this.mockMvc.perform(
delete("/api/languages/{countryCode}/language/{language}",
countryCode, cl.getLanguage())
).andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
List<CountryLanguage> langs = cLanguageDao.getLanguages(countryCode, 1);
CountryLanguage first = langs.get(0);
assertThat(first.getLanguage()).isEqualTo("Hindi");
}
}
|
3e1c47149fa20746fae4b815000f2c9bdd0a7498 | 1,847 | java | Java | src/main/java/com/mmall/concurrencystudy/review/atomic/AtomicExample6Review.java | cxmshine/concurrency-study | d162c14ff51148d0d3e94f0e3cb6d1273a398c31 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mmall/concurrencystudy/review/atomic/AtomicExample6Review.java | cxmshine/concurrency-study | d162c14ff51148d0d3e94f0e3cb6d1273a398c31 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mmall/concurrencystudy/review/atomic/AtomicExample6Review.java | cxmshine/concurrency-study | d162c14ff51148d0d3e94f0e3cb6d1273a398c31 | [
"Apache-2.0"
] | 1 | 2020-11-04T08:57:08.000Z | 2020-11-04T08:57:08.000Z | 29.31746 | 74 | 0.605847 | 11,995 | package com.mmall.concurrencystudy.review.atomic;
import com.mmall.concurrencystudy.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@Slf4j
@ThreadSafe
public class AtomicExample6Review {
private static AtomicBoolean isHappended = new AtomicBoolean(false);
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
public static void main(String[] args) throws Exception{
// 定义线程池
ExecutorService executorService = Executors.newCachedThreadPool();
// 定义计数器闭锁
CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
// 定义信号量
Semaphore semaphore = new Semaphore(threadTotal);
for(int i=0;i<clientTotal;i++) {
executorService.execute(()-> {
try {
// 获取信号量,只有拿到信号量才可以执行后续操作
semaphore.acquire();
// 并发操作
test();
// 执行完add()方法后,释放信号量
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 每调用1次add()方法,计数器的值减1
countDownLatch.countDown();
});
}
// 只有当计数器的值为0时,才会执行后面的代码
countDownLatch.await();
// 关闭线程池
executorService.shutdown();
log.info("isHappended:{}",isHappended.get());
}
private static void test() {
if(isHappended.compareAndSet(false,true)) {
log.info("execute");
}
}
}
|
3e1c47ce6c4294994f0b3610aa2e9cff2e483815 | 195 | java | Java | src/main/java/edu/wzm/action/strategy/template/ConcreteStrategyC.java | GatsbyNewton/design-pattern | 4437c4f87c7b372fd7d91d43c72092c3775d3021 | [
"MIT"
] | null | null | null | src/main/java/edu/wzm/action/strategy/template/ConcreteStrategyC.java | GatsbyNewton/design-pattern | 4437c4f87c7b372fd7d91d43c72092c3775d3021 | [
"MIT"
] | null | null | null | src/main/java/edu/wzm/action/strategy/template/ConcreteStrategyC.java | GatsbyNewton/design-pattern | 4437c4f87c7b372fd7d91d43c72092c3775d3021 | [
"MIT"
] | null | null | null | 21.666667 | 52 | 0.702564 | 11,996 | package edu.wzm.action.strategy.template;
public class ConcreteStrategyC implements Strategy {
@Override
public void algorithmStrategy() {
System.out.println("算法 C 实现");
}
}
|
3e1c47d09e03c229be40f40beebd0cfdb0c7b4bf | 9,599 | java | Java | processor/src/main/java/com/example/processor/MyProcessor.java | nangonghuang/AnnotationProcess | 3de0ddd40e96243c0bfd73ef15f76d58960ad3e8 | [
"MIT"
] | null | null | null | processor/src/main/java/com/example/processor/MyProcessor.java | nangonghuang/AnnotationProcess | 3de0ddd40e96243c0bfd73ef15f76d58960ad3e8 | [
"MIT"
] | null | null | null | processor/src/main/java/com/example/processor/MyProcessor.java | nangonghuang/AnnotationProcess | 3de0ddd40e96243c0bfd73ef15f76d58960ad3e8 | [
"MIT"
] | null | null | null | 39.665289 | 150 | 0.66882 | 11,997 | package com.example.processor;
import com.example.annotation.AnnotationFIELD;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.util.Elements;
import javax.swing.text.View;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
/**
* Created by alan on 2017/12/2.
*/
@AutoService(Processor.class)
public class MyProcessor extends AbstractProcessor {
static final String NAME_SUFFIX = "_ViewBinding";
String packageName;
private String className;
private String classFullName;
/**
* AbstractProcessor的函数,需要重写
*
* @param set
* @param roundEnvironment
* @return
*/
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
printMessageInGradleConsole(" *** start : ***");
// Map<Element, ViewBinding> map = new LinkedHashMap<>();
// List<ViewBinding> list = new ArrayList<>();
//
// for (Element element : roundEnvironment.getElementsAnnotatedWith(AnnotationFIELD.class)) {
// TypeElement typeElement = (TypeElement) element.getEnclosingElement();
// Elements elementUtils = processingEnv.getElementUtils();
// PackageElement packageElement = elementUtils.getPackageOf(typeElement);
//
// className = typeElement.getSimpleName() + NAME_SUFFIX;
// classFullName = typeElement.getQualifiedName().toString();
// packageName = packageElement.getQualifiedName().toString();
//
// TypeMirror typeMirror = element.asType();
// String type = typeMirror.toString();
// //注解的值
// int value = element.getAnnotation(AnnotationFIELD.class).value();
//
// ViewBinding viewBinding = new ViewBinding(type, element.getSimpleName().toString(), value);
// list.add(viewBinding);
//
// printMessageInGradleConsole("viewBinding : " + viewBinding);
// }
//
// try {
// printMessageInGradleConsole("classFullName : " + classFullName);
// MethodSpec.Builder constructorbuilder = MethodSpec.constructorBuilder()
// .addModifiers(Modifier.PUBLIC)
// .addParameter(this.getClass(), "activity");
// constructorbuilder.addStatement("$T decor = $L", View.class.getName(), "activity.getWindow().getDecorView()");
// for (ViewBinding viewBinding : list) {
// constructorbuilder.addStatement("$S $S = $S.findViewById($S)", viewBinding.fieldType, viewBinding.variableName, "decor", "1212314");
// }
// constructorbuilder.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!");
//
// TypeSpec helloWorld = TypeSpec.classBuilder(className)
// .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
// .addMethod(constructorbuilder.build())
// .build();
//
// JavaFile javaFile = JavaFile.builder(packageName, helloWorld)
// .build();
//
// TypeName.get()
// javaFile.writeTo(new File("d:", className));
// } catch (Exception e) {
// e.printStackTrace();
// }
parseRoundEnvironment(roundEnvironment);
printMessageInGradleConsole(" === end : ===");
return true;
}
private void parseRoundEnvironment(RoundEnvironment roundEnv) {
Map<TypeElement, BindClass> map = new LinkedHashMap<>();
for (Element element : roundEnv.getElementsAnnotatedWith(AnnotationFIELD.class)) {
TypeElement classElement = (TypeElement) element.getEnclosingElement(); //表示注解所在的类
int annotationValue = element.getAnnotation(AnnotationFIELD.class).value();
BindClass bindClass = map.get(classElement);
if (bindClass == null) {
bindClass = getBindClass(classElement);
map.put(classElement, bindClass);
}
ViewBinding viewBinding = getBindItemInfo(element, annotationValue);
bindClass.addAnnotationField(viewBinding);
}
for (Map.Entry<TypeElement, BindClass> entry : map.entrySet()) {
try {
entry.getValue().preJavaFile().writeTo(processingEnv.getFiler());//一个一个类去生成
} catch (IOException e) {
e.printStackTrace();
}
}
}
private ViewBinding getBindItemInfo(Element element, int annotationValue) {
String name = element.getSimpleName().toString();
TypeName type = TypeName.get(element.asType());
return new ViewBinding(type, name, annotationValue);
}
private BindClass getBindClass(TypeElement classElement) {
TypeName targetType = TypeName.get(classElement.asType());//表示注解所在的类
if (targetType instanceof ParameterizedTypeName) { //如果注解有泛型参数
targetType = ((ParameterizedTypeName) targetType).rawType;
}
//比如com.example.alan.annotationprocess.MainActivity,就拿到
//com.example.alan.annotationprocess了
String packageName = classElement.getQualifiedName().toString();
packageName = packageName.substring(0, packageName.lastIndexOf("."));
String className = classElement.getSimpleName().toString();
ClassName bindingClassName = ClassName.get(packageName, className + "_ViewBinding");
boolean isFinal = classElement.getModifiers().contains(Modifier.FINAL);
return new BindClass(targetType, bindingClassName, isFinal);
}
private void logMsg(Element element) {
//ElementType.FIELD注解可以直接强转VariableElement
VariableElement variableElement = (VariableElement) element;
//ElementType.TYPE注解可以直接强转TypeElement,否则需要getEnclosingElement
TypeElement classElement = (TypeElement) element.getEnclosingElement();
//这里是util包下的Element
Elements elementUtils = processingEnv.getElementUtils();
PackageElement packageElement = elementUtils.getPackageOf(classElement);
//注解用在哪个类
String className = classElement.getQualifiedName().toString();
//注解用在哪个包
String packageName = packageElement.getQualifiedName().toString();
//注解修饰的变量的名字
Name simpleName = element.getSimpleName();
//注解用在哪个类成员名(全路径名,包含参数信息)
TypeMirror typeMirror = variableElement.asType();
String type = typeMirror.toString();
//注解的值
int value = element.getAnnotation(AnnotationFIELD.class).value();
// //取得方法参数列表
// List<? extends VariableElement> methodParameters = executableElement.getParameters();
// //参数类型列表
// List<String> types = new ArrayList<>();
// for (VariableElement var : methodParameters) {
// TypeMirror methodParameterType = var.asType();
// if (methodParameterType instanceof TypeVariable) {
// TypeVariable typeVariable = (TypeVariable) methodParameterType;
// methodParameterType = typeVariable.getUpperBound();
//
// }
// //参数名
// String parameterName = var.getSimpleName().toString();
// //参数类型
// String parameteKind = methodParameterType.toString();
// types.add(methodParameterType.toString());
// }
printMessageInGradleConsole("simpleName : " + simpleName);
printMessageInGradleConsole("className : " + className);
printMessageInGradleConsole("packageName : " + packageName);
printMessageInGradleConsole("type : " + type);
printMessageInGradleConsole("value : " + value);
}
/**
* AbstractProcessor的函数,需要重写,就不用加注解了
*
* @return
*/
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotations = new LinkedHashSet<>();
annotations.add(AnnotationFIELD.class.getCanonicalName());
return annotations;
}
/**
* AbstractProcessor的函数,需要重写,就不用加注解了
*
* @return
*/
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
void printMessageInGradleConsole(String str) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING, str);
}
void printMessageInGradleConsole(CharSequence charSequence) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING, charSequence);
}
}
|
3e1c482af5b43bb52185c8248623a3d46df4acc2 | 1,840 | java | Java | src/main/java/com/hubspot/imap/protocol/response/tagged/TaggedResponse.java | hs-jenkins-bot/NioImapClient | 8f148566137ed382f7c000065caa756168413e68 | [
"Apache-2.0"
] | 35 | 2017-03-28T19:57:40.000Z | 2021-10-09T03:14:26.000Z | src/main/java/com/hubspot/imap/protocol/response/tagged/TaggedResponse.java | hs-jenkins-bot/NioImapClient | 8f148566137ed382f7c000065caa756168413e68 | [
"Apache-2.0"
] | 20 | 2017-03-28T21:43:35.000Z | 2021-09-03T13:23:01.000Z | src/main/java/com/hubspot/imap/protocol/response/tagged/TaggedResponse.java | hs-jenkins-bot/NioImapClient | 8f148566137ed382f7c000065caa756168413e68 | [
"Apache-2.0"
] | 14 | 2017-03-28T20:12:34.000Z | 2021-08-12T07:02:53.000Z | 22.168675 | 55 | 0.644565 | 11,998 | package com.hubspot.imap.protocol.response.tagged;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.MoreObjects;
import com.hubspot.imap.protocol.response.ImapResponse;
import com.hubspot.imap.protocol.response.ResponseCode;
public interface TaggedResponse extends ImapResponse {
String getTag();
List<Object> getUntagged();
ResponseCode getCode();
class Builder implements TaggedResponse {
private String tag;
private String message;
private List<Object> untagged = new ArrayList<>();
private ResponseCode code;
public TaggedResponse build() {
return this;
}
protected void copy(TaggedResponse response) {
setCode(response.getCode());
setMessage(response.getMessage());
setTag(response.getTag());
}
public String getTag() {
return this.tag;
}
public Builder setTag(String tag) {
this.tag = tag;
return this;
}
public String getMessage() {
return this.message;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public List<Object> getUntagged() {
return this.untagged;
}
public Builder addUntagged(String untagged) {
this.untagged.add(untagged);
return this;
}
public Builder setUntagged(List<Object> untagged) {
this.untagged = untagged;
return this;
}
public ResponseCode getCode() {
return this.code;
}
public Builder setCode(ResponseCode code) {
this.code = code;
return this;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("tag", tag)
.add("message", message)
.add("untagged", untagged)
.add("code", code)
.toString();
}
}
}
|
3e1c490e078661c103df422f900341d9e774c6c9 | 2,357 | java | Java | src/main/java/com/github/pocketkid2/survivalgames/SurvivalGamesPlugin.java | Joesudoedapizza/survivalgames | 13c3a1e54fe13db42e35659bfc9074b3aa212599 | [
"MIT"
] | null | null | null | src/main/java/com/github/pocketkid2/survivalgames/SurvivalGamesPlugin.java | Joesudoedapizza/survivalgames | 13c3a1e54fe13db42e35659bfc9074b3aa212599 | [
"MIT"
] | null | null | null | src/main/java/com/github/pocketkid2/survivalgames/SurvivalGamesPlugin.java | Joesudoedapizza/survivalgames | 13c3a1e54fe13db42e35659bfc9074b3aa212599 | [
"MIT"
] | null | null | null | 26.784091 | 80 | 0.764531 | 11,999 | package com.github.pocketkid2.survivalgames;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import com.github.pocketkid2.survivalgames.commands.BaseCommand;
import com.github.pocketkid2.survivalgames.config.SettingsManager;
import com.github.pocketkid2.survivalgames.listeners.BlockListener;
import com.github.pocketkid2.survivalgames.listeners.ChestListener;
import com.github.pocketkid2.survivalgames.listeners.DamageListener;
import com.github.pocketkid2.survivalgames.listeners.MoveListener;
import com.github.pocketkid2.survivalgames.listeners.PlayerListener;
public class SurvivalGamesPlugin extends JavaPlugin {
private SettingsManager sm;
private GameManager gm;
@Override
public void onEnable() {
// Register serializable object
ConfigurationSerialization.registerClass(Arena.class, "arena");
// Initialize config manager
sm = new SettingsManager(this);
// Register base command
getCommand("survivalgames").setExecutor(new BaseCommand(this));
// Prepare loading task
new LoadTask(this).runTaskLater(this, 20);
getLogger().info("Done!");
}
@Override
public void onDisable() {
// Stop all games and save to file
gm.shutdown(sm);
getLogger().info("Done!");
}
private class LoadTask extends BukkitRunnable {
private SurvivalGamesPlugin plugin;
public LoadTask(SurvivalGamesPlugin plugin) {
this.plugin = plugin;
}
@Override
public void run() {
plugin.loadMaps();
plugin.registerListeners();
}
}
private void loadMaps() {
// Initialize game manager
gm = new GameManager(this, sm);
// Notify how many arenas were loaded from file
getLogger().info("Loaded " + gm.allGames().size() + " maps");
}
private void registerListeners() {
getServer().getPluginManager().registerEvents(new MoveListener(this), this);
getServer().getPluginManager().registerEvents(new BlockListener(this), this);
getServer().getPluginManager().registerEvents(new DamageListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
getServer().getPluginManager().registerEvents(new ChestListener(this), this);
}
// Getter
public SettingsManager getSM() {
return sm;
}
// Getter
public GameManager getGM() {
return gm;
}
}
|
3e1c4a5b33b30dc72e9be31c9901c35f80d5abc0 | 1,625 | java | Java | src/main/java/cn/liulin/algorithm/leetcode/array/simple/PerimeterOfTheIsland463.java | LLBlood/authentic_algorithm | 210b34af25a6a9423edcae3634240fcecb680ddd | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/liulin/algorithm/leetcode/array/simple/PerimeterOfTheIsland463.java | LLBlood/authentic_algorithm | 210b34af25a6a9423edcae3634240fcecb680ddd | [
"Apache-2.0"
] | 1 | 2022-01-11T09:27:45.000Z | 2022-01-11T09:53:38.000Z | src/main/java/cn/liulin/algorithm/leetcode/array/simple/PerimeterOfTheIsland463.java | LLBlood/authentic_algorithm | 210b34af25a6a9423edcae3634240fcecb680ddd | [
"Apache-2.0"
] | null | null | null | 31.25 | 84 | 0.451077 | 12,000 | package cn.liulin.algorithm.leetcode.array.simple;
/**
* cn.liulin.algorithm.leetcode.array.simple$
* 463. 岛屿的周长
* 给定一个 row x col 的二维网格地图 grid ,其中:grid[i][j] = 1 表示陆地, grid[i][j] = 0 表示水域。
* 网格中的格子 水平和垂直 方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。
* 岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。
* @author ll
* @date 2021-10-11 16:47:17
**/
public class PerimeterOfTheIsland463 {
/**
* 自定义法:相邻比减2
* 两个小岛如果相连,则该小岛的周长会减去2,所以只需要判断一个小岛左上是否存在小岛即可
* @author ll
* @date 2021-10-11 17:29:39
* @param grid
* @return int
**/
public int islandPerimeter(int[][] grid) {
int perimeter = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
perimeter += 4;
//检查这个小岛左边和上边是否存在小岛,并减去2即可
if (i > 0) {
//检查上边
if (grid[i - 1][j] == 1) {
perimeter -= 2;
}
}
if (j > 0) {
//检查左边
if (grid[i][j - 1] == 1) {
perimeter -= 2;
}
}
}
}
}
return perimeter;
}
public static void main(String[] args) {
int[][] grid = {{0,1,0,0},{1,1,1,0},{0,1,0,0},{1,1,0,0}};
int i = new PerimeterOfTheIsland463().islandPerimeter(grid);
System.out.println(i);
}
}
|
3e1c4ab2f704a5f512320ff956519b6fd6fd70f3 | 1,671 | java | Java | nifi-commons/nifi-record/src/main/java/org/apache/nifi/serialization/RecordWriter.java | NullOranje/nifi | dee7b02c197395d7d3a5ada9467bb1439b618153 | [
"Apache-2.0"
] | 3,212 | 2015-07-18T01:39:17.000Z | 2022-03-31T04:10:07.000Z | nifi-commons/nifi-record/src/main/java/org/apache/nifi/serialization/RecordWriter.java | NullOranje/nifi | dee7b02c197395d7d3a5ada9467bb1439b618153 | [
"Apache-2.0"
] | 4,786 | 2015-07-24T18:57:19.000Z | 2022-03-31T22:21:57.000Z | nifi-commons/nifi-record/src/main/java/org/apache/nifi/serialization/RecordWriter.java | NullOranje/nifi | dee7b02c197395d7d3a5ada9467bb1439b618153 | [
"Apache-2.0"
] | 2,715 | 2015-07-20T11:26:22.000Z | 2022-03-31T13:42:28.000Z | 34.8125 | 99 | 0.719928 | 12,001 | /*
* 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.nifi.serialization;
import java.io.Closeable;
import java.io.IOException;
import org.apache.nifi.serialization.record.Record;
public interface RecordWriter extends Closeable {
/**
* Writes the given record to the underlying stream
*
* @param record the record to write
* @return the results of writing the data
* @throws IOException if unable to write to the underlying stream
*/
WriteResult write(Record record) throws IOException;
/**
* @return the MIME Type that the Record Writer produces. This will be added to FlowFiles using
* the mime.type attribute.
*/
String getMimeType();
/**
* Flushes any buffered data to the underlying stream
*
* @throws IOException if unable to write to the underlying stream
*/
void flush() throws IOException;
}
|
3e1c4bd479527028380814fac89c0140229081d0 | 459 | java | Java | _src/Module 2/Chapter_02/webstore/src/main/java/com/packt/webstore/controller/HomeController.java | paullewallencom/spring-978-1-7871-2755-5 | 541209a03d35f7d804dff5242e6053c62df8983e | [
"Apache-2.0"
] | 42 | 2016-10-13T02:26:38.000Z | 2021-07-19T02:04:48.000Z | _src/Module 2/Chapter_02/webstore/src/main/java/com/packt/webstore/controller/HomeController.java | paullewallencom/spring-978-1-7871-2755-5 | 541209a03d35f7d804dff5242e6053c62df8983e | [
"Apache-2.0"
] | 25 | 2020-05-15T22:14:02.000Z | 2021-12-09T22:03:07.000Z | _src/Module 2/Chapter_02/webstore/src/main/java/com/packt/webstore/controller/HomeController.java | paullewallencom/spring-978-1-7871-2755-5 | 541209a03d35f7d804dff5242e6053c62df8983e | [
"Apache-2.0"
] | 50 | 2016-08-04T06:34:13.000Z | 2021-05-06T21:31:21.000Z | 25.5 | 72 | 0.75817 | 12,002 | package com.packt.webstore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String welcome(Model model) {
model.addAttribute("greeting", "Welcome to Web Store!");
model.addAttribute("tagline", "The one and only amazing web store");
return "welcome";
}
}
|
3e1c4bfef41a778bdf36d6bbbf65b83e8cfc493b | 569 | java | Java | week07-parallel/src/yom2/ParallelArgMinOld.java | erelsgl-at-ariel/oop-5778 | 81ad76014283bce5ee43fed4fc64aab8d0df2f48 | [
"MIT"
] | 9 | 2019-10-29T07:49:56.000Z | 2020-11-03T11:24:29.000Z | week07-parallel/src/yom2/ParallelArgMinOld.java | erelsgl/ariel-oop-5778 | 81ad76014283bce5ee43fed4fc64aab8d0df2f48 | [
"MIT"
] | 2 | 2017-11-16T09:48:43.000Z | 2017-12-14T09:49:27.000Z | week07-parallel/src/yom2/ParallelArgMinOld.java | erelsgl/ariel-oop-course | 81ad76014283bce5ee43fed4fc64aab8d0df2f48 | [
"MIT"
] | 31 | 2017-11-09T06:16:48.000Z | 2018-06-27T08:53:41.000Z | 19.62069 | 65 | 0.678383 | 12,003 | package yom2;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
/**
* An example of finding the arg-min of a function using streams.
*
* @author erelsgl
*/
public class ParallelArgMinOld {
static double f(int i) {
return Math.sin(i/100.0);
}
public static void main(String[] args) {
Comparator<Integer> sineComparator = (i,j) ->
Double.compare(f(i), f(j));
int bestIndex = IntStream.range(1,1000)
.mapToObj(i->i)
.min(sineComparator)
.get();
System.out.println(bestIndex+ " " + f(bestIndex));
}
}
|
3e1c4d114510f40b5a6a9395a399d80f6c42fc94 | 506 | java | Java | acgs-core/src/test/java/io/github/acgs/core/util/DateUtilTest.java | acgs-org/acgs-cms-spring-boot-starter | 91448713c473b862bf6765f6fd8d3cd795a9ed1d | [
"Apache-2.0"
] | 1 | 2021-04-30T13:56:55.000Z | 2021-04-30T13:56:55.000Z | acgs-core/src/test/java/io/github/acgs/core/util/DateUtilTest.java | acgs-org/acgs-cms-spring-boot-starter | 91448713c473b862bf6765f6fd8d3cd795a9ed1d | [
"Apache-2.0"
] | null | null | null | acgs-core/src/test/java/io/github/acgs/core/util/DateUtilTest.java | acgs-org/acgs-cms-spring-boot-starter | 91448713c473b862bf6765f6fd8d3cd795a9ed1d | [
"Apache-2.0"
] | null | null | null | 23 | 58 | 0.650198 | 12,004 | package io.github.acgs.core.util;
import junit.framework.TestCase;
import java.util.Date;
/**
* @author John@acgs-org
* create time is 2021/4/26
*/
public class DateUtilTest extends TestCase {
public void testGetDurationDate() {
Date duration = DateUtil.getDurationDate(10);
long now = new Date().getTime();
assertTrue(duration.getTime() > now);
assertTrue(duration.getTime() - now > 5 * 1000);
assertTrue(duration.getTime() - now <= 10 * 1000);
}
}
|
3e1c4d870824ed55567a02b09b615dfde982b675 | 702 | java | Java | src/main/java/com/microsoft/graph/requests/extensions/IWorkbookFunctionsSumIfsRequest.java | winsonrich/msgraph-sdk-java | e513cd2d6481ed65d40562af7a892d6e0fd27ba0 | [
"MIT"
] | 1 | 2018-10-30T03:59:21.000Z | 2018-10-30T03:59:21.000Z | src/main/java/com/microsoft/graph/requests/extensions/IWorkbookFunctionsSumIfsRequest.java | winsonrich/msgraph-sdk-java | e513cd2d6481ed65d40562af7a892d6e0fd27ba0 | [
"MIT"
] | null | null | null | src/main/java/com/microsoft/graph/requests/extensions/IWorkbookFunctionsSumIfsRequest.java | winsonrich/msgraph-sdk-java | e513cd2d6481ed65d40562af7a892d6e0fd27ba0 | [
"MIT"
] | null | null | null | 41.294118 | 152 | 0.623932 | 12,005 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.requests.generated.IBaseWorkbookFunctionsSumIfsRequest;
// This file is available for extending, afterwards please submit a pull request.
/**
* The interface for the Workbook Functions Sum Ifs Request.
*/
public interface IWorkbookFunctionsSumIfsRequest extends IBaseWorkbookFunctionsSumIfsRequest {
}
|
3e1c4db20cd98d397f560bfd3f34cc40dc4d8bc9 | 1,722 | java | Java | dhis-2/dhis-api/src/main/java/org/hisp/dhis/message/MessageConversationStatus.java | dddaley/dhis2-core | 56c03f9c9eb0c03085ae13a1690866aeddd653e7 | [
"BSD-3-Clause"
] | 236 | 2016-08-30T21:40:48.000Z | 2022-03-26T02:25:04.000Z | dhis-2/dhis-api/src/main/java/org/hisp/dhis/message/MessageConversationStatus.java | dddaley/dhis2-core | 56c03f9c9eb0c03085ae13a1690866aeddd653e7 | [
"BSD-3-Clause"
] | 4,606 | 2016-08-31T07:54:58.000Z | 2022-03-31T20:13:34.000Z | dhis-2/dhis-api/src/main/java/org/hisp/dhis/message/MessageConversationStatus.java | radnov/dhis2-core | 93ed20e954b72d2b2a9c392040d23f70f045cc9a | [
"BSD-3-Clause"
] | 322 | 2016-08-30T15:19:59.000Z | 2022-03-24T15:22:02.000Z | 42 | 82 | 0.766551 | 12,006 | /*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.message;
/**
* @author Stian Sandvold
*/
public enum MessageConversationStatus
{
NONE,
OPEN,
PENDING,
INVALID,
SOLVED
}
|
3e1c4f4575d7a6b5b554856433b1b82843657316 | 6,931 | java | Java | app/src/main/java/xx/erhuo/com/SoldHistoryActivity.java | 2333Ge/ErHuo | d142f8c2bffa9bddbea7eb99f659d702b9258193 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/xx/erhuo/com/SoldHistoryActivity.java | 2333Ge/ErHuo | d142f8c2bffa9bddbea7eb99f659d702b9258193 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/xx/erhuo/com/SoldHistoryActivity.java | 2333Ge/ErHuo | d142f8c2bffa9bddbea7eb99f659d702b9258193 | [
"Apache-2.0"
] | null | null | null | 34.482587 | 111 | 0.628336 | 12,007 | package xx.erhuo.com;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.erhuo.utils.HttpUtils;
import com.erhuo.utils.LogUtils;
import com.erhuo.utils.NotLeakHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import xx.erhuo.bean.Constant;
import xx.erhuo.bean.SoldHistoryBean;
import xx.erhuo.bean.User;
import xx.erhuo.com.adapter.SoldHistoryAdapter;
public class SoldHistoryActivity extends AppCompatActivity {
public static void actionStart(Context context,String title,String uid){
Intent intent = new Intent(context,SoldHistoryActivity.class);
intent.putExtra("title",title);
intent.putExtra("uid",uid);
context.startActivity(intent);
}
private TextView tv_title;
private RecyclerView rv_sold;
private Toolbar t_title;
private String title;
private String uid;
private User user;
private List<SoldHistoryBean> historyBeanList;
private SoldHistoryAdapter historyAdapter;
private final int SEARCH_FAIL = 0;
private final int SEARCH_SUCCESS = 1;
private final int TRANS_SUCCESS = 2;
private final int TRANS_FAIL = 3;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sold);
initView();
initData();
}
private void initView() {
tv_title = findViewById(R.id.tv_sold_toolbar);
rv_sold = findViewById(R.id.rv_sold);
t_title = findViewById(R.id.toolbar_sold);
setSupportActionBar(t_title);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
t_title.setNavigationIcon(R.drawable.back32);
}
private void initData() {
Intent temp = getIntent();
uid = temp.getStringExtra("uid");
title = temp.getStringExtra("title");
tv_title.setText(title);
historyBeanList = new ArrayList<>();
historyAdapter = new SoldHistoryAdapter(historyBeanList);
historyAdapter.setOnItemClickListener(rvItemClickListener);
rv_sold.setAdapter(historyAdapter);
HttpUtils.sendOkHttpRequest(Constant.checkSoldHistoryUrl, "uid", uid, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message m = handler.obtainMessage();
m.what = SEARCH_FAIL;
LogUtils.e("查找失败","" + e.toString());
handler.sendMessage(m);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
LogUtils.i("卖纪录====",result);
Message m = handler.obtainMessage();
int status = setListSoldHistoryFromJson(historyBeanList,result);
if(status == TRANS_SUCCESS){
m.what = SEARCH_SUCCESS;
}else{
m.what = TRANS_FAIL;
}
handler.sendMessage(m);
}
});
}
@SuppressLint("HandlerLeak")
private NotLeakHandler handler = new NotLeakHandler<SoldHistoryActivity>(this){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case SEARCH_SUCCESS:
historyAdapter.notifyDataSetChanged();
break;
case SEARCH_FAIL:
toast("查询失败,请检查网络后重试");
break;
case TRANS_FAIL:
toast("服务器返回数据解读失败");
break;
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 将json串转换为实体list
* @param list
* @param jsonStr
* @return
*/
private int setListSoldHistoryFromJson(List<SoldHistoryBean> list, String jsonStr){
try {
JSONArray jsonArray = new JSONArray(jsonStr);
JSONObject jsonObject;
SoldHistoryBean soldHistoryBean;
for(int i = 0; i< jsonArray.length() ; i++){
jsonObject = jsonArray.getJSONObject(i);
soldHistoryBean = new SoldHistoryBean();
//[{"product_name":"果6s16g全网通,自己用的手机屏幕没有划痕,后面有痕迹自己看图",
// "pid":"143","image":"http://39.105.0.212/shop/products/cb36ff75e30c46f29ef6be7e001b6114.jpg"
// ,"price":"800.0","liuyan":"null","uid_buyer":"77","name_buyer":"冰雪灵之心",
// "payDate":"2018-6-26 3:59:55"}
soldHistoryBean.setTitle(jsonObject.getString("product_name"));
soldHistoryBean.setBuyerName(jsonObject.getString("name_buyer"));
soldHistoryBean.setImgUrl(jsonObject.getString("image"));
soldHistoryBean.setPid(jsonObject.getString("pid"));
soldHistoryBean.setBuyerId(jsonObject.getString("uid_buyer"));
soldHistoryBean.setLeaveMessage(jsonObject.getString("liuyan"));
soldHistoryBean.setDate(jsonObject.getString("payDate"));
soldHistoryBean.setPrice(jsonObject.getString("price"));
list.add(soldHistoryBean);
}
return TRANS_SUCCESS;
} catch (JSONException e) {
e.printStackTrace();
LogUtils.e("setListSoldHistoryFromJson","转换失败,请检查json格式");
return TRANS_FAIL;
}
}
SoldHistoryAdapter.OnItemClickListener rvItemClickListener = new SoldHistoryAdapter.OnItemClickListener() {
@Override
public void otherClick(int position) {
ACommodityActivity.actionStart(SoldHistoryActivity.this,historyBeanList.get(position).getPid());
}
};
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeMessages(SEARCH_FAIL);
handler.removeMessages(TRANS_FAIL);
handler.removeMessages(SEARCH_SUCCESS);
}
private void toast(String str){
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
}
}
|
3e1c4f7b81147e6b67619ddd018793ecf72ec624 | 5,093 | java | Java | infobip-mobile-messaging-android-chat-sdk/src/main/java/org/infobip/mobile/messaging/chat/mobileapi/InAppChatSynchronizer.java | isabella232/mobile-messaging-sdk-android | c72a05ef07daef88caecaf256478731a09165b43 | [
"Apache-2.0"
] | 40 | 2016-09-30T12:51:01.000Z | 2022-03-03T14:16:42.000Z | infobip-mobile-messaging-android-chat-sdk/src/main/java/org/infobip/mobile/messaging/chat/mobileapi/InAppChatSynchronizer.java | infobip/mobile-messaging-sdk-android | e86bc42c0bc7aa435e9334ebf145fa05647de48d | [
"Apache-2.0"
] | 29 | 2017-10-28T08:24:40.000Z | 2022-02-17T16:14:17.000Z | infobip-mobile-messaging-android-chat-sdk/src/main/java/org/infobip/mobile/messaging/chat/mobileapi/InAppChatSynchronizer.java | isabella232/mobile-messaging-sdk-android | c72a05ef07daef88caecaf256478731a09165b43 | [
"Apache-2.0"
] | 16 | 2016-04-28T13:13:07.000Z | 2022-03-28T09:19:39.000Z | 50.425743 | 170 | 0.701551 | 12,008 | package org.infobip.mobile.messaging.chat.mobileapi;
import android.content.Context;
import org.infobip.mobile.messaging.MobileMessaging;
import org.infobip.mobile.messaging.MobileMessagingCore;
import org.infobip.mobile.messaging.api.chat.MobileApiChat;
import org.infobip.mobile.messaging.api.chat.WidgetInfo;
import org.infobip.mobile.messaging.chat.core.InAppChatBroadcaster;
import org.infobip.mobile.messaging.chat.properties.MobileMessagingChatProperty;
import org.infobip.mobile.messaging.logging.MobileMessagingLogger;
import org.infobip.mobile.messaging.mobileapi.InternalSdkError;
import org.infobip.mobile.messaging.mobileapi.MobileMessagingError;
import org.infobip.mobile.messaging.mobileapi.Result;
import org.infobip.mobile.messaging.mobileapi.common.MRetryPolicy;
import org.infobip.mobile.messaging.mobileapi.common.MRetryableTask;
import org.infobip.mobile.messaging.mobileapi.common.RetryPolicyProvider;
import org.infobip.mobile.messaging.mobileapi.common.exceptions.BackendInvalidParameterException;
import org.infobip.mobile.messaging.platform.AndroidBroadcaster;
import org.infobip.mobile.messaging.util.PreferenceHelper;
public class InAppChatSynchronizer {
private final Context context;
private final MobileMessagingCore mobileMessagingCore;
private final AndroidBroadcaster coreBroadcaster;
private final InAppChatBroadcaster inAppChatBroadcaster;
private final MobileApiChat mobileApiChat;
private final MRetryPolicy retryPolicy;
public InAppChatSynchronizer(Context context,
MobileMessagingCore mobileMessagingCore,
AndroidBroadcaster coreBroadcaster,
InAppChatBroadcaster inAppChatBroadcaster,
MobileApiChat mobileApiChat) {
this.context = context;
this.mobileMessagingCore = mobileMessagingCore;
this.coreBroadcaster = coreBroadcaster;
this.inAppChatBroadcaster = inAppChatBroadcaster;
this.mobileApiChat = mobileApiChat;
this.retryPolicy = new RetryPolicyProvider(context).DEFAULT();
}
public void getWidgetConfiguration(final MobileMessaging.ResultListener<WidgetInfo> listener) {
if (!mobileMessagingCore.isRegistrationAvailable()) {
if (listener != null) {
listener.onResult(new Result<WidgetInfo, MobileMessagingError>(InternalSdkError.NO_VALID_REGISTRATION.getError()));
}
return;
}
if (mobileMessagingCore.isDepersonalizeInProgress()) {
MobileMessagingLogger.w("Depersonalization is in progress, will report custom event later");
if (listener != null) {
listener.onResult(new Result<WidgetInfo, MobileMessagingError>(InternalSdkError.DEPERSONALIZATION_IN_PROGRESS.getError()));
}
return;
}
new MRetryableTask<Void, WidgetInfo>() {
@Override
public WidgetInfo run(Void[] voids) {
MobileMessagingLogger.v("GET WIDGET CONFIGURATION >>>");
return mobileApiChat.getWidgetConfiguration();
}
@Override
public void after(WidgetInfo widgetInfo) {
MobileMessagingLogger.v("GET WIDGET CONFIGURATION DONE <<<");
PreferenceHelper.saveString(context, MobileMessagingChatProperty.IN_APP_CHAT_WIDGET_ID.getKey(), widgetInfo.getId());
PreferenceHelper.saveString(context, MobileMessagingChatProperty.IN_APP_CHAT_WIDGET_TITLE.getKey(), widgetInfo.getTitle());
PreferenceHelper.saveString(context, MobileMessagingChatProperty.IN_APP_CHAT_WIDGET_PRIMARY_COLOR.getKey(), widgetInfo.getPrimaryColor());
PreferenceHelper.saveString(context, MobileMessagingChatProperty.IN_APP_CHAT_WIDGET_BACKGROUND_COLOR.getKey(), widgetInfo.getBackgroundColor());
PreferenceHelper.saveLong(context, MobileMessagingChatProperty.IN_APP_CHAT_WIDGET_MAX_UPLOAD_CONTENT_SIZE.getKey(), widgetInfo.getMaxUploadContentSize());
if (listener != null) {
listener.onResult(new Result<>(widgetInfo));
}
inAppChatBroadcaster.chatConfigurationSynced();
}
@Override
public void error(Throwable error) {
MobileMessagingLogger.v("GET WIDGET CONFIGURATION ERROR <<<", error);
MobileMessagingError mobileMessagingError = MobileMessagingError.createFrom(error);
if (error instanceof BackendInvalidParameterException) {
mobileMessagingCore.handleNoRegistrationError(mobileMessagingError);
}
coreBroadcaster.error(MobileMessagingError.createFrom(error));
if (listener != null) {
listener.onResult(new Result<WidgetInfo, MobileMessagingError>(MobileMessagingError.createFrom(error)));
}
}
}
.retryWith(retryPolicy)
.execute();
}
} |
3e1c4f9aa9424631aecc3b4887442f05e2482f08 | 325 | java | Java | hcu/hcu-external-lib/src/main/java/eduni/simdiag/GraphListener.java | tuwiendsg/RAHYMS | 7404db72546a819817585848e6dc2a8ecefd095c | [
"Apache-2.0"
] | 1 | 2019-11-14T02:51:44.000Z | 2019-11-14T02:51:44.000Z | source/eduni/simdiag/GraphListener.java | ServioTRC/airport-security-check-point-simulation | 26da3dab34645b6acc32f7a85b564c21d4dd6fda | [
"MIT"
] | null | null | null | source/eduni/simdiag/GraphListener.java | ServioTRC/airport-security-check-point-simulation | 26da3dab34645b6acc32f7a85b564c21d4dd6fda | [
"MIT"
] | 1 | 2021-05-28T09:59:57.000Z | 2021-05-28T09:59:57.000Z | 21.666667 | 54 | 0.744615 | 12,009 | package eduni.simdiag;
import java.util.EventListener;
/**
* Graph event listener interface. <p>
* Implemented by graph drawing routine.
* @see eduni.simdiag.GraphDiagram
*/
public interface GraphListener extends EventListener {
/** Responds to a single graph event */
void handleGraph(GraphEventObject teo);
}
|
3e1c5002b1b7fcdbd7145f16100680db04d4e496 | 1,151 | java | Java | addressbook-web-test/src/test/java/ru/sar/neo/addressbook/tests/GroupDeletionTests.java | vsaryanidi/software_testing | 0beb040486383c71ee627ccd9708d937edd731ab | [
"Apache-2.0"
] | null | null | null | addressbook-web-test/src/test/java/ru/sar/neo/addressbook/tests/GroupDeletionTests.java | vsaryanidi/software_testing | 0beb040486383c71ee627ccd9708d937edd731ab | [
"Apache-2.0"
] | null | null | null | addressbook-web-test/src/test/java/ru/sar/neo/addressbook/tests/GroupDeletionTests.java | vsaryanidi/software_testing | 0beb040486383c71ee627ccd9708d937edd731ab | [
"Apache-2.0"
] | null | null | null | 25.577778 | 65 | 0.720243 | 12,010 | package ru.sar.neo.addressbook.tests;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.sar.neo.addressbook.model.GroupData;
import ru.sar.neo.addressbook.model.Groups;
import java.util.List;
import java.util.Set;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.testng.Assert.*;
public class GroupDeletionTests extends TestBase {
@BeforeMethod
public void ensurePreconditions(){
if (app.db().groups().size() == 0){
app.goTo().groupPage();
app.group().create(new GroupData().withName("TestGroup1"));
}
}
@Test
public void testGroupDeletion() throws Exception {
Groups before = app.db().groups();
GroupData deletedGroup = before.iterator().next();
app.goTo().groupPage();
app.group().delete(deletedGroup);
assertThat(app.group().count(), equalTo(before.size() - 1));
Groups after = app.db().groups();
assertThat(after, equalTo(before.without(deletedGroup)));
verifyGroupListInUI();
}
}
|
3e1c51457737fab1cb48e2b37355ebcb33239bbc | 1,771 | java | Java | src/main/java/com/github/yws179/business/common/utils/IPUtils.java | yws179/bussine-common-library | 20e8332675c0d9793d626586be29a14f43d27cc7 | [
"MIT"
] | null | null | null | src/main/java/com/github/yws179/business/common/utils/IPUtils.java | yws179/bussine-common-library | 20e8332675c0d9793d626586be29a14f43d27cc7 | [
"MIT"
] | null | null | null | src/main/java/com/github/yws179/business/common/utils/IPUtils.java | yws179/bussine-common-library | 20e8332675c0d9793d626586be29a14f43d27cc7 | [
"MIT"
] | 1 | 2020-08-14T03:57:01.000Z | 2020-08-14T03:57:01.000Z | 34.72549 | 104 | 0.523433 | 12,011 | package com.github.yws179.business.common.utils;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author yws
* @date 2020/07/25
*/
@Slf4j
public class IPUtils {
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if ("127.0.0.1".equals(ipAddress)) {
// 根据网卡取本机配置的IP
try {
ipAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error("获取本机IP失败", e);
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***".length()
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
log.error("获取请求方的IP失败", e);
}
return ipAddress;
}
}
|
3e1c514cd9e59b5759ca9e07543f03ccbf553c40 | 9,192 | java | Java | src/org/adl/samplerte/server/UserService.java | adlnet/SCORM-2004-4ed-SampleRTE | d22df2c4bc80836aefd99762edd99627bacd1cb7 | [
"Apache-2.0"
] | 15 | 2015-03-17T02:38:20.000Z | 2021-10-06T13:23:20.000Z | src/org/adl/samplerte/server/UserService.java | adlnet/SCORM-2004-4ed-SampleRTE | d22df2c4bc80836aefd99762edd99627bacd1cb7 | [
"Apache-2.0"
] | 3 | 2015-05-19T15:00:00.000Z | 2015-06-24T17:49:42.000Z | src/org/adl/samplerte/server/UserService.java | adlnet/SCORM-2004-4ed-SampleRTE | d22df2c4bc80836aefd99762edd99627bacd1cb7 | [
"Apache-2.0"
] | 14 | 2015-03-11T14:12:35.000Z | 2021-06-01T13:38:07.000Z | 31.806228 | 93 | 0.614991 | 12,012 |
/*******************************************************************************
ADL SCORM 2004 4th Edition Sample Run-Time Environment
The ADL SCORM 2004 4th Ed. Sample Run-Time Environment is licensed under
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States.
The Advanced Distributed Learning Initiative allows you to:
* Share - to copy, distribute and transmit the work.
* Remix - to adapt the work.
Under the following conditions:
* Attribution. You must attribute the work in the manner specified by the author or
licensor (but not in any way that suggests that they endorse you or your use
of the work).
* Noncommercial. You may not use this work for commercial purposes.
* Share Alike. If you alter, transform, or build upon this work, you may distribute
the resulting work only under the same or similar license to this one.
For any reuse or distribution, you must make clear to others the license terms of this work.
Any of the above conditions can be waived if you get permission from the ADL Initiative.
Nothing in this license impairs or restricts the author's moral rights.
*******************************************************************************/
package org.adl.samplerte.server;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import org.adl.samplerte.util.LMSDatabaseHandler;
/**
* <strong>Filename:</strong> UserService.java<br><br>
*
* <strong>Description:</strong><br>
* The UserService class handles user manipulation requests of the Sample RTE.
*
* <strong>Design Issues:</strong><br>
* This implementation is intended to be used by the SCORM 2004 4th Edition Sample RTE<br>
* <br>
*
* <strong>References:</strong><br>
* <ul>
* <li>IMS SS Specification
* <li>SCORM 2004 4th Edition
* </ul>
*
* @author ADL Technical Team
*/
public class UserService
{
/**
* This constructor creates a UserService object.
*/
UserService()
{
// Default constructor
}
/**
* Returns a list of users registered in the Sample RTE
* @param iOnlyActive - return a list of inactive or active users
* @return List of users registered in the system
*/
public Vector getUsers(boolean iOnlyActive)
{
Connection conn;
PreparedStatement stmtSelectUser;
Vector mUserVector = new Vector();
String sqlSelectUser = "SELECT * FROM UserInfo";
if (iOnlyActive == true)
{
sqlSelectUser = sqlSelectUser + " WHERE Active = yes";
}
try
{
conn = LMSDatabaseHandler.getConnection();
stmtSelectUser = conn.prepareStatement(sqlSelectUser);
ResultSet userRS = null;
// returns a list of user information
userRS = stmtSelectUser.executeQuery();
// Loops through the result set of all users and adds them to the return
// Vector.
while (userRS.next())
{
UserProfile mUserProfile = new UserProfile();
mUserProfile.mUserID = userRS.getString("UserID");
mUserProfile.mLastName = userRS.getString("LastName");
mUserProfile.mFirstName = userRS.getString("FirstName");
mUserVector.add(mUserProfile);
}
userRS.close();
stmtSelectUser.close();
conn.close();
}
catch (Exception e)
{
System.out.println("This failed in UserService::getUsers()");
e.printStackTrace();
}
return mUserVector;
}
/**
* Returns a UserProfile for the desired user
* @param iUserID - the ID of the desired user
* @return UserProfile object for the desired user
*/
public UserProfile getUser(String iUserID)
{
Connection conn;
PreparedStatement stmtSelectUser;
String sqlSelectUser = "SELECT * FROM UserInfo WHERE UserId = ?";
UserProfile mUserProfile = new UserProfile();
try
{
conn = LMSDatabaseHandler.getConnection();
stmtSelectUser = conn.prepareStatement(sqlSelectUser);
ResultSet userRS = null;
synchronized(stmtSelectUser)
{
stmtSelectUser.setString(1, iUserID);
userRS = stmtSelectUser.executeQuery();
}
while (userRS.next())
{
mUserProfile.mUserID = userRS.getString("UserID");
mUserProfile.mLastName = userRS.getString("LastName");
mUserProfile.mFirstName = userRS.getString("FirstName");
mUserProfile.mPassword = userRS.getString("Password");
mUserProfile.mAudioLevel = userRS.getString("AudioLevel");
mUserProfile.mAudioCaptioning = userRS.getString("AudioCaptioning");
mUserProfile.mDeliverySpeed = userRS.getString("DeliverySpeed");
mUserProfile.mLanguage = userRS.getString("Language");
mUserProfile.mAdmin = userRS.getBoolean("Admin");
}
userRS.close();
stmtSelectUser.close();
conn.close();
}
catch (Exception e)
{
System.out.println("Error in UserService::getUser()");
e.printStackTrace();
}
return mUserProfile;
}
/**
* This method is used to update the user information.
* @param iUser - the UserProfile object of a specific user
* @return String - indicates whether the update was successful
*/
public String updateUser(UserProfile iUser)
{
String result = "true";
Connection conn = LMSDatabaseHandler.getConnection();
PreparedStatement stmtSetUserInfo;
String sqlSetUserInfo = "UPDATE UserInfo SET Password = ?,"
+ "AudioLevel = ?, AudioCaptioning = ?,"
+ "DeliverySpeed = ?, Language = ?, Admin = ? "
+ "WHERE UserID = ?";
try
{
stmtSetUserInfo = conn.prepareStatement(sqlSetUserInfo);
synchronized(stmtSetUserInfo)
{
stmtSetUserInfo.setString(1, iUser.mPassword);
stmtSetUserInfo.setString(2, iUser.mAudioLevel);
stmtSetUserInfo.setString(3, iUser.mAudioCaptioning);
stmtSetUserInfo.setString(4, iUser.mDeliverySpeed);
stmtSetUserInfo.setString(5, iUser.mLanguage);
stmtSetUserInfo.setBoolean(6, iUser.mAdmin);
stmtSetUserInfo.setString(7, iUser.mUserID);
stmtSetUserInfo.executeUpdate();
}
conn.close();
}
catch (Exception e)
{
System.out.println("error in db update in UserService::updateUser()");
result = "false";
e.printStackTrace();
}
return result;
}
/**
* Adds a user to the Sample Run Time Environment
* @param iUser - UserProfile object of the desired user to be added to the system
* @return String describing the success of the operation (true or false)
*/
public String addUser(UserProfile iUser)
{
String result = "true";
Connection conn;
PreparedStatement stmtInsertUserInfo;
String sqlInsertUserInfo =
"INSERT INTO UserInfo VALUES (?, ?, ?, ?, ?,'1','1','0','1','')";
try
{
conn = LMSDatabaseHandler.getConnection();
stmtInsertUserInfo = conn.prepareStatement(sqlInsertUserInfo);
synchronized(stmtInsertUserInfo)
{
stmtInsertUserInfo.setString(1, iUser.mUserID);
stmtInsertUserInfo.setString(2, iUser.mLastName);
stmtInsertUserInfo.setString(3, iUser.mFirstName);
stmtInsertUserInfo.setBoolean(4, iUser.mAdmin);
stmtInsertUserInfo.setString(5, iUser.mPassword);
stmtInsertUserInfo.executeUpdate();
}
stmtInsertUserInfo.close();
conn.close();
}
catch (Exception e)
{
System.out.println("error updating db in UserService::addUser()");
result = "false";
e.printStackTrace();
}
return result;
}
/**
* Deletes the undesired user
* @param iUser - ID of the user to be deleted from the Sample RTE
* @return String representing the success of the operation (true or false)
*/
public String deleteUser(String iUser)
{
String result = "true";
try
{
Connection conn;
PreparedStatement stmtUpdateUser;
conn = LMSDatabaseHandler.getConnection();
// The SQL string is created and converted to a prepared statement.
String sqlUpdateUser = "UPDATE UserInfo set Active = no where UserID = ?";
stmtUpdateUser = conn.prepareStatement(sqlUpdateUser);
synchronized(stmtUpdateUser)
{
stmtUpdateUser.setString(1, iUser);
stmtUpdateUser.executeUpdate();
}
stmtUpdateUser.close();
conn.close();
}
catch (Exception e)
{
result = "false";
System.out.println("error updating db in UserService::deleteUser()");
e.printStackTrace();
}
return result;
}
} |
3e1c51bd045c290dbd64f3a515b573be6fd4b34a | 7,330 | java | Java | src/test/java/picard/sam/AbstractAlignmentMergerTest.java | naumanjaved/picard | 547bc7766ca4f73de5208be9f413065d552321ec | [
"MIT"
] | null | null | null | src/test/java/picard/sam/AbstractAlignmentMergerTest.java | naumanjaved/picard | 547bc7766ca4f73de5208be9f413065d552321ec | [
"MIT"
] | null | null | null | src/test/java/picard/sam/AbstractAlignmentMergerTest.java | naumanjaved/picard | 547bc7766ca4f73de5208be9f413065d552321ec | [
"MIT"
] | null | null | null | 44.969325 | 132 | 0.708049 | 12,013 | package picard.sam;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SAMRecordSetBuilder;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import org.testng.Assert;
import org.testng.annotations.Test;
import picard.cmdline.CommandLineProgramTest;
import picard.cmdline.argumentcollections.RequiredReferenceArgumentCollection;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* Tests related to code in AbstractAlignmentMerger
*/
public class AbstractAlignmentMergerTest extends CommandLineProgramTest {
@Test public void tesOverlappedReadClippingWithNonOverlappedReads() {
final SAMRecordSetBuilder set = new SAMRecordSetBuilder();
set.setReadLength(110);
final List<SAMRecord> recs = set.addPair("q1", 0, 100, 200, false, false, "110M", "110M", false, true, 30);
final SAMRecord r1 = recs.get(0);
final SAMRecord r2 = recs.get(1);
AbstractAlignmentMerger.clipForOverlappingReads(r1, r2);
Assert.assertEquals(r1.getAlignmentStart(), 100);
Assert.assertEquals(r1.getCigarString(), "110M");
Assert.assertEquals(r2.getAlignmentStart(), 200);
Assert.assertEquals(r2.getCigarString(), "110M");
}
@Test public void testBasicOverlappedReadClipping() {
final SAMRecordSetBuilder set = new SAMRecordSetBuilder();
set.setReadLength(110);
final List<SAMRecord> recs = set.addPair("q1", 0, 100, 90, false, false, "110M", "110M", false, true, 30);
final SAMRecord r1 = recs.get(0);
final SAMRecord r2 = recs.get(1);
AbstractAlignmentMerger.clipForOverlappingReads(r1, r2);
Assert.assertEquals(r1.getAlignmentStart(), 100);
Assert.assertEquals(r1.getCigarString(), "100M10S");
Assert.assertEquals(r2.getAlignmentStart(), 100);
Assert.assertEquals(r2.getCigarString(), "10S100M");
}
@Test public void testOverlappedReadClippingWithExistingSoftClipping() {
final SAMRecordSetBuilder set = new SAMRecordSetBuilder();
set.setReadLength(120);
final List<SAMRecord> recs = set.addPair("q1", 0, 100, 95, false, false, "110M10S", "15S105M", false, true, 30);
final SAMRecord r1 = recs.get(0);
final SAMRecord r2 = recs.get(1);
AbstractAlignmentMerger.clipForOverlappingReads(r1, r2);
Assert.assertEquals(r1.getAlignmentStart(), 100);
Assert.assertEquals(r1.getCigarString(), "100M20S");
Assert.assertEquals(r2.getAlignmentStart(), 100);
Assert.assertEquals(r2.getCigarString(), "20S100M");
}
@Test public void testOverlappedReadClippingWithExistingSoftClippingAndHardClipping() {
final SAMRecordSetBuilder set = new SAMRecordSetBuilder();
set.setReadLength(120);
final List<SAMRecord> recs = set.addPair("q1", 0, 100, 95, false, false, "110M10S5H", "5H15S105M", false, true, 30);
final SAMRecord r1 = recs.get(0);
final SAMRecord r2 = recs.get(1);
AbstractAlignmentMerger.clipForOverlappingReads(r1, r2);
Assert.assertEquals(r1.getAlignmentStart(), 100);
Assert.assertEquals(r1.getCigarString(), "100M20S5H");
Assert.assertEquals(r2.getAlignmentStart(), 100);
Assert.assertEquals(r2.getCigarString(), "5H20S100M");
}
@Test
public void testUnmapBacterialContamination() throws IOException {
final SAMRecordSetBuilder builder = new SAMRecordSetBuilder(true, SAMFileHeader.SortOrder.queryname);
final SAMFileHeader header = builder.getHeader();
final SAMFileHeader.SortOrder sortOrder = header.getSortOrder();
final SAMFileHeader newHeader = SAMRecordSetBuilder.makeDefaultHeader(sortOrder, 100000,true);
builder.setHeader(newHeader);
final File reference = File.createTempFile("reference",".fasta");
reference.deleteOnExit();
builder.writeRandomReference(reference.toPath());
builder.addPair("overlappingpair", 0,500,500, false,false,"20S20M60S","20S20M60M",true,false,45);
builder.addPair("overlappingpairFirstAligned", 0,500,500, false,true,"20S20M60S",null,true,false,45);
builder.addPair("overlappingpairSecondAligned", 0,500,500, true,false,null,"20S20M60S",true,false,45);
builder.addPair("overlappingpairFirstAlignedB", 0,500,500, false,true,"20S20M60S",null,false,true,45);
builder.addPair("overlappingpairSecondAlignedB", 0,500,500, true,false,null,"20S20M60S",false,true,45);
// builder.addFrag("frag",1,500,false,false,"20S20M60S",null, 45);
// builder.addFrag("frag2",1,500,true,false,"20S20M60S",null, 45);
// builder.addFrag("frag3",1,500,false,false,"20S20M60S",null, 45);
// builder.addFrag("frag4",1,500,true,false,"20S20M60S",null, 45);
final File file = newTempSamFile("aligned");
try (SAMFileWriter writer = new SAMFileWriterFactory().makeWriter(builder.getHeader(), true, file, null)) {
builder.getRecords().forEach(writer::addAlignment);
}
final RevertSam revertSam = new RevertSam();
revertSam.INPUT = file;
final File fileUnaligned = newTempSamFile("unaligned");
revertSam.OUTPUT = fileUnaligned;
revertSam.SANITIZE = false;
revertSam.REMOVE_ALIGNMENT_INFORMATION=true;
revertSam.REMOVE_DUPLICATE_INFORMATION=true;
revertSam.SORT_ORDER = SAMFileHeader.SortOrder.queryname;
Assert.assertEquals(revertSam.doWork(),0);
MergeBamAlignment mergeBamAlignment = new MergeBamAlignment();
mergeBamAlignment.ALIGNED_BAM = Collections.singletonList(file);
mergeBamAlignment.UNMAPPED_BAM = fileUnaligned;
mergeBamAlignment.UNMAP_CONTAMINANT_READS = true;
//yuck!
final RequiredReferenceArgumentCollection requiredReferenceArgumentCollection = new RequiredReferenceArgumentCollection();
requiredReferenceArgumentCollection.REFERENCE_SEQUENCE = reference;
mergeBamAlignment.referenceSequence = requiredReferenceArgumentCollection;
final File fileMerged = newTempSamFile("merged");
mergeBamAlignment.OUTPUT = fileMerged;
// merge file with itself.
Assert.assertEquals(mergeBamAlignment.doWork(),0);
// check that all reads have been unmapped due to bacterial contamination as needed.
try (SamReader mergedReader = SamReaderFactory.makeDefault().open(fileMerged)) {
for (SAMRecord mergedRecord : mergedReader) {
Assert.assertTrue(mergedRecord.getReadUnmappedFlag(), mergedRecord.toString());
Assert.assertTrue(!mergedRecord.getReadPairedFlag() || mergedRecord.getMateUnmappedFlag(), mergedRecord.toString());
}
}
}
@Override
public String getCommandLineProgramName() {
return this.getClass().getSimpleName();
}
private static File newTempSamFile(final String filename) throws IOException {
final File file = File.createTempFile(filename,".sam");
file.deleteOnExit();
return file;
}
}
|
3e1c522653a463cf1fa72e113d20c9c7203e4494 | 3,127 | java | Java | java/youngfriend/main_pnl/deleagte/OutParamTableDeletate.java | polllyxiong/datasource_swing | f29a54781afdb9f85418b4c51a3508b918dc2727 | [
"Apache-2.0"
] | null | null | null | java/youngfriend/main_pnl/deleagte/OutParamTableDeletate.java | polllyxiong/datasource_swing | f29a54781afdb9f85418b4c51a3508b918dc2727 | [
"Apache-2.0"
] | null | null | null | java/youngfriend/main_pnl/deleagte/OutParamTableDeletate.java | polllyxiong/datasource_swing | f29a54781afdb9f85418b4c51a3508b918dc2727 | [
"Apache-2.0"
] | null | null | null | 36.360465 | 118 | 0.631276 | 12,014 | package youngfriend.main_pnl.deleagte;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import youngfriend.exception.ParamValidateExcption;
import youngfriend.main_pnl.utils.MainPnlUtil;
import youngfriend.utils.PubUtil;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
/**
* Created by xiong on 9/2/16.
*/
public class OutParamTableDeletate {
//出口参数表格index
public static final int INDEX_OUTPARAMS_FIELD = 0;
public static final int INDEX_OUTPARAMS_FIELD_DESC = 1;
private final DefaultTableModel model;
private JTable table;
public OutParamTableDeletate(final JTable table, JButton addBtn, JButton delBtn) {
this.table=table;
model = (DefaultTableModel) table.getModel();
addBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
PubUtil.stopTabelCellEditor(table);
int selectedRow = table.getSelectedRow();
selectedRow++;
model.insertRow(selectedRow, new String[2]);
PubUtil.tableSelect(table, selectedRow);
}
});
PubUtil.tableDelRow(delBtn, table);
}
public void clear() {
MainPnlUtil.clearTable(table);
}
public void load(JsonObject inparamObj) {
JsonArray outparam = PubUtil.getJsonObj(inparamObj, "outparam", JsonArray.class);
if (outparam != null) {
JsonArray outParams = PubUtil.getJsonObj(outparam.get(0).getAsJsonObject(), "outParams", JsonArray.class);
if(outParams!=null){
Iterator<JsonElement> iterator = outParams.iterator();
while (iterator.hasNext()) {
JsonObject fieldObj = iterator.next().getAsJsonObject();
model.addRow(new String[]{PubUtil.getProp(fieldObj, "name"), PubUtil.getProp(fieldObj, "label")});
}
}
}
}
public JsonArray getOutParamsLevel2() {
PubUtil.stopTabelCellEditor(table);
int rowCount_out = table.getRowCount();
JsonArray fieldoutParams = null;
if (rowCount_out > 0) {
fieldoutParams = new JsonArray();
for (int i = 0; i < rowCount_out; i++) {
String fieldname = (String) table.getValueAt(i, INDEX_OUTPARAMS_FIELD);
String fielddesc = (String) table.getValueAt(i, INDEX_OUTPARAMS_FIELD_DESC);
if (PubUtil.existNull(fieldname, fielddesc)) {
PubUtil.tableSelect(table, i);
throw new ParamValidateExcption("出口参数设错误");
}
JsonObject fieldObj = new JsonObject();
fieldObj.addProperty("name", fieldname);
fieldObj.addProperty("label", fielddesc);
fieldoutParams.add(fieldObj);
}
}
return fieldoutParams;
}
}
|
3e1c525d278287e32dc12cf695304f6e28079ebd | 2,508 | java | Java | src/test/java/org/letitbeat/oauth/twitter/domain/UserTest.java | letitbeat/twitter-streaming-oauth | c27082beafd72c7cb5cff41d7c53dbbcf04089e6 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/letitbeat/oauth/twitter/domain/UserTest.java | letitbeat/twitter-streaming-oauth | c27082beafd72c7cb5cff41d7c53dbbcf04089e6 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/letitbeat/oauth/twitter/domain/UserTest.java | letitbeat/twitter-streaming-oauth | c27082beafd72c7cb5cff41d7c53dbbcf04089e6 | [
"Apache-2.0"
] | null | null | null | 26.680851 | 94 | 0.731659 | 12,015 | package org.letitbeat.oauth.twitter.domain;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.letitbeat.oauth.twitter.domain.comparators.DateComparator;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @author Jose Reyes
* @version 1.0 05/2017.
*/
public class UserTest {
private static final String DATE_FORMAT_PATTERN = "E MMM d HH:mm:ss Z y";
@Test
public void testNewInstance(){
long now = System.currentTimeMillis();
User user = new User()
.setId(12345)
.setName("new user")
.setScreenName("screen")
.setCreatedAt(new Date(now));
assertEquals(12345L, user.getId());
assertEquals("new user", user.getName());
assertEquals("screen", user.getScreenName());
}
@Test
public void testJsonToObject() throws IOException, ParseException {
InputStream jsonStream = getClass().getClassLoader()
.getResourceAsStream("user.json");
ObjectMapper mapper = new ObjectMapper();
User mappedUser = mapper.readValue(jsonStream, User.class);
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN);
assertEquals(7891011L, mappedUser.getId());
assertEquals("This should be the name", mappedUser.getName());
assertEquals("screenName", mappedUser.getScreenName());
assertEquals(dateFormat.parse("Fri May 26 09:00:00 -0800 2017"), mappedUser.getCreatedAt());
}
@Test
public void testEquals(){
User user1 = new User().setId(12345L);
User user2 = new User().setId(12345L);
assertEquals(user1, user2);
}
@Test
public void testDateComparator() throws ParseException {
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN);
User user1 = new User().setId(12345L).setCreatedAt(
dateFormat.parse("Fri May 26 09:00:00 -0800 2017"));
User user2 = new User().setId(678910L).setCreatedAt(
dateFormat.parse("Fri May 26 08:00:00 -0800 2017"));
User user3 = new User().setId(111213L).setCreatedAt(
dateFormat.parse("Fri May 26 07:00:00 -0800 2017"));
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
Collections.sort(users, new DateComparator());
assertEquals(user3, users.get(0));
assertEquals(user2, users.get(1));
assertEquals(user1, users.get(2));
}
}
|
3e1c52b7e1bfdff04fbec2091806e64f526e0313 | 1,731 | java | Java | app/app/src/main/java/com/yan/sh/sh_android/engine/managers/GameManager.java | sas5580/ScavengerHunt-App | 2e97df614b299a03c987bd1fc3edced48590cd9f | [
"MIT"
] | null | null | null | app/app/src/main/java/com/yan/sh/sh_android/engine/managers/GameManager.java | sas5580/ScavengerHunt-App | 2e97df614b299a03c987bd1fc3edced48590cd9f | [
"MIT"
] | null | null | null | app/app/src/main/java/com/yan/sh/sh_android/engine/managers/GameManager.java | sas5580/ScavengerHunt-App | 2e97df614b299a03c987bd1fc3edced48590cd9f | [
"MIT"
] | null | null | null | 23.08 | 77 | 0.615829 | 12,016 | package com.yan.sh.sh_android.engine.managers;
import com.yan.sh.sh_android.engine.Engine;
import com.yan.sh.sh_android.ui.LoginActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import timber.log.Timber;
/**
* Created by yan on 6/11/17.
*/
public class GameManager extends Manager {
private boolean initalized = false;
private String startTime;
private String gameCode;
private Integer rank;
private Integer numPlayers;
public GameManager(){
this.startup();
}
public void storeGameData(JSONObject data, String newGameCode){
if(data == null || newGameCode == null){
return;
}
gameCode = newGameCode;
try{
JSONArray objectives = data.getJSONArray("data");
Engine.objective().loadObjectives(objectives);
Engine.data().saveGameData(gameCode);
initalized = true;
}catch(JSONException ex){
Timber.e(ex, "Json error");
}
}
public boolean initialized(){
return initalized;
}
public String getGameCode(){
return gameCode;
}
public Boolean setRank(Integer rank, Integer players){
if(rank != null && players !=null && rank <= players){
this.rank = rank;
this.numPlayers = players;
return true;
}
return false;
}
public String createRankText(){
if(rank == null || numPlayers == null){
return "";
}
return Integer.toString(rank) + " / " + Integer.toString(numPlayers);
}
}
|
3e1c5339a2716bed0506a39546389aad843e9933 | 117 | java | Java | Principal.java | gunter895/JavaPracticeHacktoberfest | cac2be7e5f03aad41b5b3fd98f7cf79b63120539 | [
"Apache-2.0"
] | null | null | null | Principal.java | gunter895/JavaPracticeHacktoberfest | cac2be7e5f03aad41b5b3fd98f7cf79b63120539 | [
"Apache-2.0"
] | null | null | null | Principal.java | gunter895/JavaPracticeHacktoberfest | cac2be7e5f03aad41b5b3fd98f7cf79b63120539 | [
"Apache-2.0"
] | null | null | null | 23.4 | 47 | 0.606838 | 12,017 | public principal {
public static void main (String [] args ) {
System.out.println("Adios mundo");
}
} |
3e1c543c32e026c19eba463fbd02ce4c5aac0011 | 1,400 | java | Java | src/test/java/com/github/chanhohang/akka/AkkaBaseImpl.java | chanhohang/akka-cluster-messenger | e8fb0ccadf9fbe1c7e9e5dd0f3b7e95aabd7e002 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/github/chanhohang/akka/AkkaBaseImpl.java | chanhohang/akka-cluster-messenger | e8fb0ccadf9fbe1c7e9e5dd0f3b7e95aabd7e002 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/github/chanhohang/akka/AkkaBaseImpl.java | chanhohang/akka-cluster-messenger | e8fb0ccadf9fbe1c7e9e5dd0f3b7e95aabd7e002 | [
"Apache-2.0"
] | null | null | null | 25.925926 | 84 | 0.753571 | 12,018 | package com.github.chanhohang.akka;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import com.github.chanhohang.akka.AkkaClusterMessengerConstants.PersistentId;
import com.github.chanhohang.akka.spring.SpringAkkaBase;
import org.springframework.stereotype.Component;
@Component
public class AkkaBaseImpl extends SpringAkkaBase {
private final ActorSystem actorSystem;
private ActorRef clusterListener;
private ActorRef clusterMessagingReceiver;
private ActorRef clusterMessagingSender;
public AkkaBaseImpl() {
actorSystem = ActorSystem.create("system");
}
@Override
public ActorSystem getActorSystem() {
return actorSystem;
}
@Override
public ActorRef getActor(String actorId) {
// @formatter:off
switch (actorId) {
case PersistentId.Cluster.Listener:
return clusterListener;
case PersistentId.Cluster.Receiver:
return clusterMessagingReceiver;
case PersistentId.Cluster.Sender:
return clusterMessagingSender;
default:
return getActor(actorSystem, actorId);
}
// @formatter:on
}
@Override
public void initialize() {
clusterListener = getActor(actorSystem, PersistentId.Cluster.Listener);
clusterMessagingReceiver = getActor(actorSystem, PersistentId.Cluster.Receiver);
clusterMessagingSender = getActor(actorSystem, PersistentId.Cluster.Sender);
}
}
|
3e1c547e0c401ae9972e687b3b9e3323caf7cd8b | 2,363 | java | Java | sql/dao/src/main/java/genericdao/finder/impl/ExtendedFinderNamingStrategy.java | xuzhikethinker/t4f-data | d5bddb7d05189ee2291592e2689b5a6a44259dbf | [
"Apache-2.0"
] | 1 | 2015-03-16T04:00:39.000Z | 2015-03-16T04:00:39.000Z | sql/dao/src/main/java/genericdao/finder/impl/ExtendedFinderNamingStrategy.java | xuzhikethinker/t4f-data | d5bddb7d05189ee2291592e2689b5a6a44259dbf | [
"Apache-2.0"
] | null | null | null | sql/dao/src/main/java/genericdao/finder/impl/ExtendedFinderNamingStrategy.java | xuzhikethinker/t4f-data | d5bddb7d05189ee2291592e2689b5a6a44259dbf | [
"Apache-2.0"
] | null | null | null | 47.26 | 119 | 0.58358 | 12,019 | /****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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 genericdao.finder.impl;
import java.lang.reflect.Method;
import genericdao.finder.FinderNamingStrategy;
/**
* Looks up Hibernate named queries based on the simple name of the invoced class and the method name of the invocation
*/
public class ExtendedFinderNamingStrategy implements FinderNamingStrategy
{
// Always look for queries that start with findBy (even if method is iterateBy.. or scrollBy...)
public String queryNameFromMethod(Class findTargetType, Method finderMethod)
{
String methodName = finderMethod.getName();
String methodPart = methodName;
if(methodName.startsWith("findBy")) {
// No-op
}
else if(methodName.startsWith("listBy")) {
methodPart = "findBy" + methodName.substring("listBy".length());
}
else if(methodName.startsWith("iterateBy")) {
methodPart = "findBy" + methodName.substring("iterateBy".length());
}
else if(methodName.startsWith("scrollBy")) {
methodPart = "findBy" + methodName.substring("scrollBy".length());
}
return findTargetType.getSimpleName() + "." + methodPart;
}
}
|
3e1c54b230b891aa9f0319132269881bb7164c43 | 791 | java | Java | src/main/java/com/thegongoliers/commands/GameSpecificMessageCommand.java | Gongoliers/Library-of-Gongolierium | 7d73073123ae9e9b1c79881befb0f22920dcb710 | [
"MIT"
] | 9 | 2017-07-09T22:21:30.000Z | 2022-01-22T19:24:03.000Z | src/main/java/com/thegongoliers/commands/GameSpecificMessageCommand.java | Gongoliers/Library-of-Gongolierium | 7d73073123ae9e9b1c79881befb0f22920dcb710 | [
"MIT"
] | 48 | 2017-07-11T01:25:49.000Z | 2022-03-26T19:03:26.000Z | src/main/java/com/thegongoliers/commands/GameSpecificMessageCommand.java | Gongoliers/Library-of-Gongolierium | 7d73073123ae9e9b1c79881befb0f22920dcb710 | [
"MIT"
] | null | null | null | 35.954545 | 108 | 0.764855 | 12,020 | package com.thegongoliers.commands;
import com.thegongoliers.input.gameMessages.GameSpecificMessage2018;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.ConditionalCommand;
public class GameSpecificMessageCommand extends ConditionalCommand {
public interface GameSpecificMessageHandler {
boolean shouldRunTrueCommand(GameSpecificMessage2018 message);
}
public GameSpecificMessageCommand(Command onTrue, Command onFalse, GameSpecificMessageHandler handler) {
super(onTrue, onFalse, () -> {
return handler != null && handler.shouldRunTrueCommand(
new GameSpecificMessage2018(DriverStation.getInstance().getGameSpecificMessage()));
});
}
}
|
3e1c54d0a096d9eb84fe388f2cce294a2b48c375 | 1,765 | java | Java | openmrs-client/src/main/java/org/openmrs/mobile/activities/patientdashboard/details/PatientPhotoActivity.java | wesc09/AndroidApp | ccaeb6fc2405d2191a26e87bee360aaafbaf3553 | [
"OLDAP-2.5",
"OLDAP-2.4",
"OLDAP-2.6"
] | 1 | 2017-06-29T06:54:45.000Z | 2017-06-29T06:54:45.000Z | openmrs-client/src/main/java/org/openmrs/mobile/activities/patientdashboard/details/PatientPhotoActivity.java | wesc09/openmrs-contrib-android-client-master | ebd62dbb202a49cbca27a839b1cada887b825041 | [
"OLDAP-2.5",
"OLDAP-2.4",
"OLDAP-2.7",
"OLDAP-2.6"
] | null | null | null | openmrs-client/src/main/java/org/openmrs/mobile/activities/patientdashboard/details/PatientPhotoActivity.java | wesc09/openmrs-contrib-android-client-master | ebd62dbb202a49cbca27a839b1cada887b825041 | [
"OLDAP-2.5",
"OLDAP-2.4",
"OLDAP-2.7",
"OLDAP-2.6"
] | null | null | null | 34.607843 | 81 | 0.735411 | 12,021 | /*
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.mobile.activities.patientdashboard.details;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import org.openmrs.mobile.R;
import java.io.ByteArrayInputStream;
public class PatientPhotoActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_photo);
byte[] photo = getIntent().getByteArrayExtra("photo");
ByteArrayInputStream inputStream = new ByteArrayInputStream(photo);
Bitmap patientPhoto = BitmapFactory.decodeStream(inputStream);
ImageView patientImageView = (ImageView) findViewById(R.id.patientPhoto);
patientImageView.setImageBitmap(patientPhoto);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
String patientName = getIntent().getStringExtra("name");
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(patientName);
}
}
}
|
3e1c58373485181ccd56e7afe74599d7dcd8c26c | 2,449 | java | Java | bkhech-boot-configures/bkhech-boot-configure-common/src/main/java/com/bkhech/boot/configure/common/builder/chart/radar/RadarBuilder.java | guowenmeng/bkhech-boot | 4503fcc440a10fb06a25ccb419b99e79ff015f08 | [
"Apache-2.0"
] | null | null | null | bkhech-boot-configures/bkhech-boot-configure-common/src/main/java/com/bkhech/boot/configure/common/builder/chart/radar/RadarBuilder.java | guowenmeng/bkhech-boot | 4503fcc440a10fb06a25ccb419b99e79ff015f08 | [
"Apache-2.0"
] | null | null | null | bkhech-boot-configures/bkhech-boot-configure-common/src/main/java/com/bkhech/boot/configure/common/builder/chart/radar/RadarBuilder.java | guowenmeng/bkhech-boot | 4503fcc440a10fb06a25ccb419b99e79ff015f08 | [
"Apache-2.0"
] | null | null | null | 28.149425 | 128 | 0.683544 | 12,022 | package com.bkhech.boot.configure.common.builder.chart.radar;
import com.bkhech.boot.commons.util.ApplicationContextUtil;
import com.bkhech.boot.configure.common.builder.chart.ChartContext;
import com.bkhech.boot.configure.common.builder.chart.NameAndData;
import com.bkhech.boot.configure.common.builder.chart.radar.response.RadarChartResponse;
import com.bkhech.boot.configure.common.builder.chart.radar.response.WithRadarPropertyCharts;
import com.bkhech.boot.configure.common.builder.BaseBuilder;
import com.bkhech.boot.configure.common.builder.chart.NameAndValue;
import java.util.List;
/**
* Description: RadarBuilder
* @author guowm 2018/9/19
*/
public class RadarBuilder implements BaseBuilder {
private RadarChartResponse response;
private WithRadarPropertyCharts chartDto = new WithRadarPropertyCharts();
private static ChartContext context;
static {
try {
context = ApplicationContextUtil.getBean(RadarContext.class);
} catch (Exception e) {
throw new RuntimeException("init ChartContext failed,please enable EnableBkhMvc annotation.", e.fillInStackTrace());
}
}
protected RadarBuilder(RadarChartResponse response) {
this.response = response;
}
private RadarBuilder(String index) {
RadarBuilder builder = (RadarBuilder) context.createChart(index);
builder.getResponse().setChart(chartDto);
this.response = builder.getResponse();
}
private RadarChartResponse getResponse() {
return response;
}
/**
* set y轴数据
* @param yAxis
* @param <T>
* @return this builder
*/
public <T extends Number> RadarBuilder yAxis(List<NameAndData<T>> yAxis) {
this.chartDto.setyAxis(yAxis);
return this;
}
/**
* set 雷达图外围的最大值 即参照值
* @param radar
* @param <T>
* @return this builder
*/
public <T extends Number> RadarBuilder radar(List<NameAndValue<T>> radar) {
this.chartDto.setRadar(radar);
return this;
}
/**
* set 提示数据
* @param label
* @return this builder
*/
public RadarBuilder label(List<NameAndData<String>> label) {
this.chartDto.setLabel(label);
return this;
}
public RadarChartResponse build() {
return this.getResponse();
}
public static RadarBuilder newBuilder(String index) {
return new RadarBuilder(index);
}
}
|
3e1c5886b1ea818835ed404614f9c335a5ba4135 | 4,084 | java | Java | MensaApp/src/main/java/de/lukasniemeier/mensa/parser/TodaysMenuParser.java | lukasniemeier/mensaapp | 29ac769ffe6b1ba116bbcae54f3579c745b6b001 | [
"MIT"
] | 1 | 2015-11-06T03:16:44.000Z | 2015-11-06T03:16:44.000Z | MensaApp/src/main/java/de/lukasniemeier/mensa/parser/TodaysMenuParser.java | lukasniemeier/mensaapp | 29ac769ffe6b1ba116bbcae54f3579c745b6b001 | [
"MIT"
] | null | null | null | MensaApp/src/main/java/de/lukasniemeier/mensa/parser/TodaysMenuParser.java | lukasniemeier/mensaapp | 29ac769ffe6b1ba116bbcae54f3579c745b6b001 | [
"MIT"
] | null | null | null | 34.033333 | 114 | 0.644221 | 12,023 | package de.lukasniemeier.mensa.parser;
import android.content.Context;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.lukasniemeier.mensa.model.Mensa;
import de.lukasniemeier.mensa.model.Menu;
import de.lukasniemeier.mensa.model.WeeklyMenu;
import de.lukasniemeier.mensa.utils.SerializableTime;
import de.lukasniemeier.mensa.utils.Utils;
/**
* Created on 17.09.13.
*/
public class TodaysMenuParser extends WeeklyMenuParser {
private static final String priceGroup = "Studierende";
private final Map<String, Collection<String>> alternativeNameMap;
public TodaysMenuParser(Context context, Document page, Mensa mensa) {
super(context, page, mensa);
alternativeNameMap = new HashMap<String, Collection<String>>();
alternativeNameMap.put("Veganes Angebot", Arrays.asList("Veganes Essen"));
}
@Override
protected SerializableTime parseDate(Element menuTable) {
return Utils.today();
}
@Override
protected Menu parseMenu(WeeklyMenu weeklyMenu, Element menuTable) throws WeeklyMenuParseException {
Menu menu = new Menu(weeklyMenu);
Elements rows = menuTable.select("tr");
for (Element nameElement : rows.select("td.head")) {
int index = nameElement.parent().children().indexOf(nameElement);
Element nextParent = nameElement.parent().nextElementSibling();
if (nextParent == null) {
throw new WeeklyMenuParseException("Expected parent for description");
}
Element nextNextParent = nextParent.nextElementSibling();
if (nextParent == null) {
throw new WeeklyMenuParseException("Expected description and meal type elements");
}
Element descriptionElement = getChild(index, nextParent);
Element mealTypesElement = getChild(index, nextNextParent);
String name = nameElement.text();
String price = getPrice(menuTable.ownerDocument(), name);
addMeal(menu, nameElement.text(), descriptionElement.text(), parseMealTypes(mealTypesElement), price);
}
return menu;
}
private String getPrice(Document document, String name) {
String price = null;
for (String alternativeName : getAlternativeNames(name)) {
price = findPriceInDocument(document, alternativeName);
if (price != null) {
break;
}
}
if (price == null) {
price = getDefaultPrice(name);
}
return price;
}
private Collection<String> getAlternativeNames(String name) {
Collection<String> names = alternativeNameMap.get(name);
if (names == null) {
names = new ArrayList<String>(1);
} else {
names = new ArrayList<String>(names);
}
// always add original name
names.add(name);
return names;
}
private String findPriceInDocument(Document document, String name) {
String paragraphRegex = String.format("%s.*" + priceGroup + ":", name);
Elements priceElements = document.select("p:matches(" + paragraphRegex + ")");
if (priceElements.size() == 1) {
Pattern priceRegex = Pattern.compile(name + ".*?" + priceGroup + ": (\\d+,\\d+)", Pattern.DOTALL);
Matcher match = priceRegex.matcher(priceElements.get(0).text());
if (match.find()) {
return match.group(1);
}
}
return null;
}
private Element getChild(int index, Element parent) throws WeeklyMenuParseException {
if (parent.children().size() <= index) {
throw new WeeklyMenuParseException("Expected element for description or meal types");
}
return parent.child(index);
}
}
|
3e1c59cf08c2ac8f2116f9e10e2d4099bb567a78 | 1,344 | java | Java | xiaom-work/src/main/java/kim/xiaom/work/converter/UserConverter.java | goworks/goworks | 65a62e1ee70d124e090d1708007e1ab860671154 | [
"Apache-2.0"
] | null | null | null | xiaom-work/src/main/java/kim/xiaom/work/converter/UserConverter.java | goworks/goworks | 65a62e1ee70d124e090d1708007e1ab860671154 | [
"Apache-2.0"
] | 12 | 2020-07-21T01:07:57.000Z | 2022-03-08T22:50:03.000Z | xiaom-work/src/main/java/kim/xiaom/work/converter/UserConverter.java | goworks/goworks | 65a62e1ee70d124e090d1708007e1ab860671154 | [
"Apache-2.0"
] | null | null | null | 27.428571 | 54 | 0.648065 | 12,024 | package kim.xiaom.work.converter;
import kim.xiaom.work.entity.dataObjects.UserDO;
import kim.xiaom.work.entity.viewObjects.UserVO;
import kim.xiaom.work.utils.XiaomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.UUID;
/**
* Created by ge on 12/05/2018.
*/
@Component
public class UserConverter {
public UserDO convert(UserVO userVO) {
if (Objects.isNull(userVO)) {
return null;
}
UserDO userDO = new UserDO();
userDO.setUserId(userVO.getId());
userDO.setUsername(userVO.getUsername());
userDO.setEmail(userVO.getEmail());
userDO.setPassword(userVO.getPassword());
userDO.setPhone(userVO.getPhone());
if (StringUtils.isEmpty(userDO.getUserId())) {
userDO.setUserId(XiaomUtils.uuid());
}
return userDO;
}
public UserVO convert(UserDO userDO) {
if (Objects.isNull(userDO)) {
return null;
}
UserVO userVO = new UserVO();
userVO.setId(userDO.getUserId());
userVO.setUsername(userDO.getUsername());
userVO.setEmail(userDO.getEmail());
userVO.setPassword(userDO.getPassword());
userVO.setPhone(userDO.getPhone());
return userVO;
}
}
|
3e1c59d35421028bc146a3fac2b0d1191702bde9 | 415 | java | Java | app/src/main/java/com/acuteksolutions/uhotel/mvp/model/movies/Period.java | Huynhvantoan/uHotel | 240c9d28132ed8246144aabb45e54877ea87277f | [
"MIT"
] | null | null | null | app/src/main/java/com/acuteksolutions/uhotel/mvp/model/movies/Period.java | Huynhvantoan/uHotel | 240c9d28132ed8246144aabb45e54877ea87277f | [
"MIT"
] | null | null | null | app/src/main/java/com/acuteksolutions/uhotel/mvp/model/movies/Period.java | Huynhvantoan/uHotel | 240c9d28132ed8246144aabb45e54877ea87277f | [
"MIT"
] | null | null | null | 16.6 | 52 | 0.607229 | 12,025 | package com.acuteksolutions.uhotel.mvp.model.movies;
import io.realm.RealmObject;
public class Period extends RealmObject{
private long start;
private long end;
public Period() {
}
public Period(long start, long end) {
this.start = start;
this.end = end;
}
public long getStart() {
return start;
}
public long getEnd() {
return end;
}
}
|
3e1c5ae098570c578bc4e1ade42826779b78a7e6 | 8,176 | java | Java | app/src/main/java/ru/solandme/washwait/network/map/model/places/Result.java | solandmedotru/WashWait | c55361382e71f6225a8b882827e80790aedf22e7 | [
"Apache-2.0"
] | 2 | 2017-04-01T12:24:55.000Z | 2021-01-20T19:08:15.000Z | app/src/main/java/ru/solandme/washwait/network/map/model/places/Result.java | solandmedotru/WashWait | c55361382e71f6225a8b882827e80790aedf22e7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/ru/solandme/washwait/network/map/model/places/Result.java | solandmedotru/WashWait | c55361382e71f6225a8b882827e80790aedf22e7 | [
"Apache-2.0"
] | 1 | 2022-02-25T07:09:06.000Z | 2022-02-25T07:09:06.000Z | 18.008811 | 80 | 0.530822 | 12,026 |
package ru.solandme.washwait.network.map.model.places;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Result {
@SerializedName("address_components")
@Expose
private List<AddressComponent> addressComponents = null;
@SerializedName("adr_address")
@Expose
private String adrAddress;
@SerializedName("formatted_address")
@Expose
private String formattedAddress;
@SerializedName("formatted_phone_number")
@Expose
private String formattedPhoneNumber;
@SerializedName("geometry")
@Expose
private Geometry geometry;
@SerializedName("icon")
@Expose
private String icon;
@SerializedName("id")
@Expose
private String id;
@SerializedName("international_phone_number")
@Expose
private String internationalPhoneNumber;
@SerializedName("name")
@Expose
private String name;
@SerializedName("opening_hours")
@Expose
private OpeningHours openingHours;
@SerializedName("photos")
@Expose
private List<Photo> photos = null;
@SerializedName("place_id")
@Expose
private String placeId;
@SerializedName("rating")
@Expose
private double rating;
@SerializedName("reference")
@Expose
private String reference;
@SerializedName("reviews")
@Expose
private List<Review> reviews = null;
@SerializedName("scope")
@Expose
private String scope;
@SerializedName("types")
@Expose
private List<String> types = null;
@SerializedName("url")
@Expose
private String url;
@SerializedName("utc_offset")
@Expose
private int utcOffset;
@SerializedName("vicinity")
@Expose
private String vicinity;
@SerializedName("website")
@Expose
private String website;
/**
*
* @return
* The addressComponents
*/
public List<AddressComponent> getAddressComponents() {
return addressComponents;
}
/**
*
* @param addressComponents
* The address_components
*/
public void setAddressComponents(List<AddressComponent> addressComponents) {
this.addressComponents = addressComponents;
}
/**
*
* @return
* The adrAddress
*/
public String getAdrAddress() {
return adrAddress;
}
/**
*
* @param adrAddress
* The adr_address
*/
public void setAdrAddress(String adrAddress) {
this.adrAddress = adrAddress;
}
/**
*
* @return
* The formattedAddress
*/
public String getFormattedAddress() {
return formattedAddress;
}
/**
*
* @param formattedAddress
* The formatted_address
*/
public void setFormattedAddress(String formattedAddress) {
this.formattedAddress = formattedAddress;
}
/**
*
* @return
* The formattedPhoneNumber
*/
public String getFormattedPhoneNumber() {
return formattedPhoneNumber;
}
/**
*
* @param formattedPhoneNumber
* The formatted_phone_number
*/
public void setFormattedPhoneNumber(String formattedPhoneNumber) {
this.formattedPhoneNumber = formattedPhoneNumber;
}
/**
*
* @return
* The geometry
*/
public Geometry getGeometry() {
return geometry;
}
/**
*
* @param geometry
* The geometry
*/
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
/**
*
* @return
* The icon
*/
public String getIcon() {
return icon;
}
/**
*
* @param icon
* The icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
*
* @return
* The id
*/
public String getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* @return
* The internationalPhoneNumber
*/
public String getInternationalPhoneNumber() {
return internationalPhoneNumber;
}
/**
*
* @param internationalPhoneNumber
* The international_phone_number
*/
public void setInternationalPhoneNumber(String internationalPhoneNumber) {
this.internationalPhoneNumber = internationalPhoneNumber;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The openingHours
*/
public OpeningHours getOpeningHours() {
return openingHours;
}
/**
*
* @param openingHours
* The opening_hours
*/
public void setOpeningHours(OpeningHours openingHours) {
this.openingHours = openingHours;
}
/**
*
* @return
* The photos
*/
public List<Photo> getPhotos() {
return photos;
}
/**
*
* @param photos
* The photos
*/
public void setPhotos(List<Photo> photos) {
this.photos = photos;
}
/**
*
* @return
* The placeId
*/
public String getPlaceId() {
return placeId;
}
/**
*
* @param placeId
* The place_id
*/
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
/**
*
* @return
* The rating
*/
public double getRating() {
return rating;
}
/**
*
* @param rating
* The rating
*/
public void setRating(double rating) {
this.rating = rating;
}
/**
*
* @return
* The reference
*/
public String getReference() {
return reference;
}
/**
*
* @param reference
* The reference
*/
public void setReference(String reference) {
this.reference = reference;
}
/**
*
* @return
* The reviews
*/
public List<Review> getReviews() {
return reviews;
}
/**
*
* @param reviews
* The reviews
*/
public void setReviews(List<Review> reviews) {
this.reviews = reviews;
}
/**
*
* @return
* The scope
*/
public String getScope() {
return scope;
}
/**
*
* @param scope
* The scope
*/
public void setScope(String scope) {
this.scope = scope;
}
/**
*
* @return
* The types
*/
public List<String> getTypes() {
return types;
}
/**
*
* @param types
* The types
*/
public void setTypes(List<String> types) {
this.types = types;
}
/**
*
* @return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* @return
* The utcOffset
*/
public int getUtcOffset() {
return utcOffset;
}
/**
*
* @param utcOffset
* The utc_offset
*/
public void setUtcOffset(int utcOffset) {
this.utcOffset = utcOffset;
}
/**
*
* @return
* The vicinity
*/
public String getVicinity() {
return vicinity;
}
/**
*
* @param vicinity
* The vicinity
*/
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
/**
*
* @return
* The website
*/
public String getWebsite() {
return website;
}
/**
*
* @param website
* The website
*/
public void setWebsite(String website) {
this.website = website;
}
}
|
3e1c5c9d1ba166dcc38383e464a26c281cd0fa36 | 39,826 | java | Java | org.linkedin.util-core/src/test/java/org/linkedin/util/io/resource/TestResource.java | LinkedInAttic/linkedin-utils | ca097410b537fb09847c42037593c0f474c0571f | [
"Apache-2.0"
] | 55 | 2015-03-06T22:03:06.000Z | 2020-12-02T18:19:10.000Z | org.linkedin.util-core/src/test/java/org/linkedin/util/io/resource/TestResource.java | linkedin/linkedin-utils | ca097410b537fb09847c42037593c0f474c0571f | [
"Apache-2.0"
] | 2 | 2015-04-14T13:57:29.000Z | 2015-04-14T16:28:56.000Z | org.linkedin.util-core/src/test/java/org/linkedin/util/io/resource/TestResource.java | linkedin/linkedin-utils | ca097410b537fb09847c42037593c0f474c0571f | [
"Apache-2.0"
] | 30 | 2015-05-05T19:31:59.000Z | 2020-05-26T14:09:31.000Z | 30.591398 | 134 | 0.641075 | 12,027 | /*
* Copyright 2010-2010 LinkedIn, Inc
* Portions Copyright (c) 2011 Yan Pujante
*
* 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.linkedin.util.io.resource;
import junit.framework.TestCase;
import org.linkedin.util.clock.SystemClock;
import org.linkedin.util.concurrent.ExternalCommand;
import org.linkedin.util.io.IOUtils;
import org.linkedin.util.io.PathUtils;
import org.linkedin.util.io.ram.RAMDirectory;
import org.linkedin.util.io.resource.internal.InternalResource;
import org.linkedin.util.io.resource.internal.InternalResourceProvider;
import org.linkedin.util.io.resource.internal.ResourceProviderChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author efpyi@example.com
*
*/
public class TestResource extends TestCase
{
public static final String MODULE = TestResource.class.getName();
public static final Logger log = LoggerFactory.getLogger(MODULE);
private final static int ROOT = 0;
private final static int A = 1;
private final static int B = 2;
private final static int C = 3;
private final static int EMPTY = 4;
private final static int D = 5;
private final static String WEB_XML_CONTENT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"\n" +
"<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>\n" +
"\n" +
"<web-app>\n" +
" <servlet>\n" +
" <servlet-name>TestServletContextResource</servlet-name>\n" +
" <servlet-class>" +
TestResource.class.getName() +
"</servlet-class>\n" +
" <load-on-startup>1</load-on-startup>\n" +
" </servlet>\n" +
"\n" +
" <servlet-mapping>\n" +
" <servlet-name>TestServletContextResource</servlet-name>\n" +
" <url-pattern>/tscr</url-pattern>\n" +
" </servlet-mapping>\n" +
"</web-app>";
private final List<File> _deleteOnExit = new ArrayList<File>();
/**
* Constructor
*/
public TestResource(String name)
{
super(name);
}
@Override
protected void tearDown() throws Exception
{
try
{
Collections.reverse(_deleteOnExit);
for(File file : _deleteOnExit)
{
try
{
IOUtils.deleteFile(file);
}
catch(IOException e)
{
log.warn("Exception [ignored] while deleting file " + file, e);
}
}
}
finally
{
super.tearDown();
}
}
protected String getWebXmlContent()
{
return WEB_XML_CONTENT;
}
public static abstract class Checker
{
protected void checkIsModifiedSince(Resource resource)
{
long lastModified = resource.lastModified();
if(lastModified == 0L)
{
assertFalse(resource.isModifiedSince(lastModified));
assertFalse(resource.isModifiedSince(1000L));
}
else
{
// 1ms in the past it was
assertTrue(resource.isModifiedSince(lastModified - 1));
// last modified or future
assertFalse(resource.isModifiedSince(lastModified));
assertFalse(resource.isModifiedSince(lastModified + 1));
// 0 (modified)
assertTrue(resource.isModifiedSince(0));
}
}
protected void checkLastModified(ResourceInfo info, File file) throws IOException
{
assertEquals(file.lastModified(), info.getLastModified());
}
protected void checkInfo(Resource resource, File file) throws IOException
{
ResourceInfo info = resource.getInfo();
checkLastModified(info, file);
checkContentLength(info, file);
checkIsModifiedSince(resource);
}
protected void checkContentLength(ResourceInfo info, File file) throws IOException
{
assertEquals(file.isDirectory() ? 0 : file.length(), info.getContentLength());
}
/**
* By default the content of a directory is not readable (not as an input stream..)
*/
protected void checkDirectoryContent(Resource resource) throws IOException
{
try
{
readContent(resource);
fail("cannot read content of a directory");
}
catch(IOException e)
{
// expected
}
}
protected void checkIsDirectory(Resource resource)
{
assertTrue(resource.isDirectory());
}
protected abstract void checkURI(Resource resource, File file) throws URISyntaxException;
protected void checkListResource(Resource resource, File file) throws IOException
{
Resource[] resources = resource.list();
assertEquals(file.list().length, resources.length);
}
/**
* Apply the filter to the list and check that the result matches the expected elements.
*
* @param resource
* @param filter
* @param expected
* @throws IOException
*/
protected void checkListResources(Resource resource, final String filter, Resource... expected)
throws IOException
{
Resource[] filteredResources = resource.list(new ResourceFilter()
{
@Override
public boolean accept(Resource resource)
{
return resource.getFilename().endsWith(filter);
}
});
assertEqualsOrderDontCare(filter, filteredResources, expected);
}
}
public static class FileChecker extends TestResource.Checker
{
@Override
public void checkURI(Resource resource, File file)
{
assertEquals(file.toURI(), resource.toURI());
}
}
public static class RAMChecker extends TestResource.Checker
{
private final URI _fileBaseURI;
public RAMChecker(URI fileBaseURI)
{
_fileBaseURI = fileBaseURI;
}
@Override
protected void checkURI(Resource resource, File file) throws URISyntaxException
{
String fileURI = file.toURI().toString().substring(_fileBaseURI.toString().length());
assertEquals(new URI("ram:///" + fileURI), resource.toURI());
}
}
public static class JarChecker extends TestResource.Checker
{
private final URI _fileBaseURI;
private final URI _jarBaseURI;
public JarChecker(URI jarBaseURI, URI fileBaseURI)
{
_fileBaseURI = fileBaseURI;
_jarBaseURI = jarBaseURI;
}
/**
* It seems that jar and filesystem differ on this field... I wrote a separate program to test
* my intuition and indeed some (but not all!) last modified are off by a second. My guess is
* that jar and file round up to the nearest second but they don't seem to do it exactly the
* same way....
*/
@Override
public void checkLastModified(ResourceInfo info, File file) throws IOException
{
assertTrue(Math.abs(file.lastModified() - info.getLastModified()) <= 1000);
}
/**
* We recreate the uri resource from the base uri
*/
@Override
public void checkURI(Resource resource, File file) throws URISyntaxException
{
String fileURI = file.toURI().toString().substring(_fileBaseURI.toString().length());
assertEquals(new URI("jar:" + PathUtils.removeTrailingSlash(_jarBaseURI.toString()) +
"!/" + fileURI),
resource.toURI());
}
/*
Test code that proves what I say about last modified...
public static void main(String[] args) throws IOException, InterruptedException
{
File root = new File("/tmp/ypujante/TestJarURL4");
readFiles(root, new JarFile(new File("/tmp/ypujante/toto.jar")));
//createFiles(root);
}
private static void readFiles(File root, JarFile jarFile)
{
for(int i = 0; i < 100; i++)
{
File file = new File(root, "f" + i);
JarEntry jarEntry = jarFile.getJarEntry("TestJarURL4/f" + i);
if(file.lastModified() != jarEntry.getTime())
System.out.println(file.toString() + " | " + jarEntry.toString() + " =>" +
file.lastModified() + " (" + new Date(file.lastModified()) + ") " +
"/" +
jarEntry.getTime() + " (" + new Date(jarEntry.getTime()) + ") ");
}
}
private static void createFiles(File root)
throws IOException, InterruptedException
{
root.mkdirs();
for(int i = 0; i < 100; i++)
{
File file = new File(root, "f" + i);
FileWriter fw = new FileWriter(file);
try
{
BufferedWriter writer = new BufferedWriter(fw);
writer.write("content " + i);
writer.flush();
}
finally
{
fw.close();
}
System.out.println(file.toString() + " =>" + file.lastModified());
Thread.sleep(100);
}
}
*/
}
/**
* Test with a non existent file
*
* @throws IOException
*/
public void testNonExistentFile() throws IOException, URISyntaxException
{
// we create a directory and then we delete it to make sure it does not exist...
File root = createTempDirectory(TestResource.class.getName(), "testNonExistentFile");
IOUtils.deleteFile(root);
checkNonExistentResource(FileResource.createFromRoot(root), root, new TestResource.FileChecker());
}
/**
* Convenient call which checks that a resource does not exists...
*
* @param resource the resource to check
*/
public static void checkNonExistentResource(Resource resource,
File nonExistenFile,
TestResource.Checker checker)
throws IOException, URISyntaxException
{
assertFalse(resource.exists());
assertNull(resource.list());
try
{
resource.getInfo();
fail("non exsitent");
}
catch(IOException e)
{
// expected
}
try
{
resource.getInputStream();
fail("it is a directory...");
}
catch(IOException e)
{
// expected
}
checker.checkURI(resource, nonExistenFile);
assertFalse(resource.createRelative("bar").exists());
}
/**
* We test with an empty directory.
*/
public void testEmptyDirectory() throws IOException, URISyntaxException
{
File root = createTempDirectory(TestResource.class.getName(), "testEmptyDirectory");
try
{
checkEmptyDirectory(root, FileResource.createFromRoot(root), new TestResource.FileChecker());
}
finally
{
IOUtils.deleteFile(root);
}
}
/**
* Checks that the resource points to an empty directory
*
* @param emptyDirectory
* @param resource
* @throws IOException
*/
private static void checkEmptyDirectory(File emptyDirectory, Resource resource, TestResource.Checker checker)
throws IOException, URISyntaxException
{
assertTrue(resource.exists());
checker.checkIsDirectory(resource);
// empty directory => 0 entries returned
checker.checkListResource(resource, emptyDirectory);
// info should be the same as what file returns (since in this case it is a thin wrapper)
checker.checkInfo(resource, emptyDirectory);
checker.checkDirectoryContent(resource);
checker.checkURI(resource, emptyDirectory);
// the directory is empty so it will point to a non existent resource
checkNonExistentResource(resource.createRelative("foo"),
new File(emptyDirectory, "foo"),
checker);
}
/**
* test for file resource
*/
public void testTreeDirectoryFileResource() throws IOException, URISyntaxException
{
File root = createTempDirectory(TestResource.class.getName(), "testTreeDirectoryFileResource");
try
{
File[][] directoryStructure = createDirectoryStructure(root, getWebXmlContent());
// root
Resource rootResource = FileResource.createFromRoot(root);
checkTreeResource(rootResource, directoryStructure, new TestResource.FileChecker());
}
finally
{
IOUtils.deleteFile(root);
}
}
/**
* Test for RAM resource
*/
public void testTreeDirectoryRAMResource() throws IOException, URISyntaxException
{
File root = createTempDirectory(TestResource.class.getName(), "testTreeDirectoryRAMResource");
try
{
File[][] directoryStructure = createDirectoryStructure(root, getWebXmlContent());
// root
Resource rootResource = RAMResource.create(createRAMDirectory(root));
checkTreeResource(rootResource, directoryStructure, new TestResource.RAMChecker(root.toURI()));
}
finally
{
IOUtils.deleteFile(root);
}
}
/**
* Duplicates the directory structure on the filesystem in a RAMDirectory
*/
private RAMDirectory createRAMDirectory(File root) throws IOException
{
RAMDirectory ramRoot = new RAMDirectory(SystemClock.instance(), "");
populateRAMDirectory(ramRoot, root);
return ramRoot;
}
/**
* Recursively populates the ram directory
*/
private void populateRAMDirectory(RAMDirectory ramDirectory, File directory) throws IOException
{
String[] names = directory.list();
for(String name : names)
{
File file = new File(directory, name);
if(file.isDirectory())
{
RAMDirectory subdir = ramDirectory.mkdir(name);
subdir.touch(file.lastModified());
populateRAMDirectory(subdir, file);
}
else
{
ramDirectory.add(name, readContent(file)).touch(file.lastModified());
}
}
}
/**
* Test for resource chain: we create 2 directory structures with some similarities and
* dissimilarities. root1 is the same as the one created in {@link #createDirectoryStructure2(File)}
*
* <pre>
* root2/
* a.html
* d.txt
* d1/
* a.html
* d.txt
* d1_1/
* a.html
* d.txt
* empty/
* d3/
* a.html
* d.txt
* <p/>
* </pre>
*
* @throws IOException
* @throws URISyntaxException
*/
public void testTreeDirectoryResourceChain() throws IOException, URISyntaxException
{
File root1 = createTempDirectory(TestResource.class.getName(), "testTreeDirectoryResourceChain1");
try
{
// root1
File[][] directoryStructure1 = createDirectoryStructure(root1, getWebXmlContent());
// chain should work the same if there is only one element in it!
checkTreeResource(ResourceChain.create(FileResource.createFromRoot(root1)),
directoryStructure1,
new TestResource.FileChecker());
// chain should work the same if there is only one element in it!
// I need to do this otherwise the previous create method bypass the chain entirely...
InternalResourceProvider provider =
(InternalResourceProvider) ((InternalResource) FileResource.createFromRoot(root1)).getResourceProvider();
checkTreeResource(new ResourceProviderChain(provider).getRootResource(),
directoryStructure1,
new TestResource.FileChecker());
File root2 = createTempDirectory(TestResource.class.getName(), "testTreeDirectoryResourceChain2");
try
{
// root2
File[][] directoryStructure2 = createDirectoryStructure2(root2);
// here we create a chain where both resources are at the root...
Resource root = ResourceChain.create(FileResource.createFromRoot(root1),
FileResource.createFromRoot(root2));
checkChain(root, directoryStructure1, directoryStructure2, new TestResource.FileChecker());
}
finally
{
IOUtils.deleteFile(root2);
}
}
finally
{
IOUtils.deleteFile(root1);
}
}
/**
* Verifies that the chain is working properly.
*/
private void checkChain(Resource root,
File[][] ds1,
File[][] ds2,
Checker checker) throws IOException, URISyntaxException
{
checkResource(root, "a.html", ds1[0][A], checker); // in root1 (precedence)
checkResource(root, "b.txt", ds1[0][B], checker); // in root1 (only there)
checkResource(root, "d.txt", ds2[0][D], checker); // in root2 (only there)
checkNonExistentResource(root.createRelative("e.txt"), new File(ds2[0][ROOT], "e.txt"), checker);
// now we go in d1:
Resource d1 = root.createRelative("d1");
checkResource(d1, "a.html", ds1[1][A], checker); // in root1/d1 (precedence)
checkResource(d1, "b.txt", ds1[1][B], checker); // in root1/d1 (only there)
checkResource(d1, "d.txt", ds2[1][D], checker); // in root2/d1 (only there)
// now we go in d1_1:
Resource d1_1 = d1.createRelative("d1_1");
checkResource(d1_1, "a.html", ds1[2][A], checker); // in root1/d1/d1_1 (precedence)
checkResource(d1_1, "b.txt", ds1[2][B], checker); // in root1/d1/d1_1 (only there)
checkResource(d1_1, "d.txt", ds2[2][D], checker); // in root2/d1/d1_1 (only there)
// now we go in d2:
Resource d2 = root.createRelative("d2");
checkResource(d2, "a.html", ds1[3][A], checker); // in root1/d2 (only there)
checkResource(d2, "b.txt", ds1[3][B], checker); // in root1/d2 (only there)
checkNonExistentResource(d2.createRelative("d.txt"), new File(ds2[0][ROOT], "d2/d.txt"), checker);
// now we go in d3:
Resource d3 = root.createRelative("d3");
checkResource(d3, "a.html", ds2[3][A], checker); // in root2/d3 (only there)
checkResource(d3, "d.txt", ds2[3][D], checker); // in root2/d3 (only there)
checkNonExistentResource(d3.createRelative("b.txt"), new File(ds2[0][ROOT], "d3/b.txt"), checker);
checker.checkListResources(d1_1, ".txt",
d1_1.createRelative("b.txt"),
d1_1.createRelative("c.txt"),
d1_1.createRelative("d.txt"));
checker.checkListResources(d3, ".txt",
d3.createRelative("d.txt"));
}
/**
* Create the following directory structure
* <pre>
* root/
* a.html
* b.txt
* c.txt
* empty/
* d1/
* a.html
* b.txt
* c.txt
* empty/
* d1_1/
* a.html
* b.txt
* c.txt
* empty/
* d2/
* a.html
* b.txt
* c.txt
* empty/
* WEB-INF/
* web.xml
* <p/>
* </pre>
*
* @throws IOException
*/
protected File[][] createDirectoryStructure(File root, String webXmlContent) throws IOException
{
File[] rootFiles = createSubTree(root);
File[] d1Files = createSubTree(createDir(new File(rootFiles[ROOT], "d1")));
File[] d2Files = createSubTree(createDir(new File(rootFiles[ROOT], "d2")));
File[] d1_1Files = createSubTree(createDir(new File(d1Files[ROOT], "d1_1")));
File[] webInfFiles = createWebInfFiles(createDir(new File(rootFiles[ROOT], "WEB-INF")),
webXmlContent);
return new File[][]{rootFiles, d1Files, d1_1Files, d2Files, webInfFiles};
}
/**
* Create the following directory structure
* <pre>
* root2/
* a.html
* d.txt
* d1/
* a.html
* d.txt
* d1_1/
* a.html
* d.txt
* empty/
* d3/
* a.html
* d.txt
* <p/>
* </pre>
*
* @throws IOException
*/
private File[][] createDirectoryStructure2(File root) throws IOException
{
File[] rootFiles = createSubTree(root, "a.html", null, null, null, "d.txt", "d1/", "d3/");
File[] d1Files = createSubTree(rootFiles[6], "a.html", null, null, null, "d.txt", "d1_1/");
File[] d3Files = createSubTree(rootFiles[7], "a.html", null, null, "empty/", "d.txt");
File[] d1_1Files = createSubTree(d1Files[6], "a.html", null, null, null, "d.txt");
return new File[][]{rootFiles, d1Files, d1_1Files, d3Files};
}
/**
* test for jar resource
*/
public void testTreeDirectoryJarResource()
throws IOException, InterruptedException, URISyntaxException
{
File root = createTempDirectory(TestResource.class.getName(), "testTreeDirectoryJarResource");
try
{
File nestedRoot = createDir(new File(root, "root"));
File[][] directoryStructure = createDirectoryStructure(nestedRoot, getWebXmlContent());
// first test where root is /
File jarFile = createJarFile(TestResource.class.getName(), nestedRoot);
try
{
// the following calls should be equivalent
checkTreeResource(JarResource.create(FileResource.createFromRoot(jarFile)),
directoryStructure,
new TestResource.JarChecker(jarFile.toURI(), nestedRoot.toURI()));
checkTreeResource(JarResource.create(URI.create("jar:" + jarFile.toURI() + "!/")),
directoryStructure,
new TestResource.JarChecker(jarFile.toURI(), nestedRoot.toURI()));
}
finally
{
jarFile.delete();
}
// second test where root is /root
jarFile = createJarFile(TestResource.class.getName(), root);
try
{
// the following calls should be equivalent
checkTreeResource(JarResource.create(FileResource.createFromRoot(jarFile), "/root"),
directoryStructure,
new TestResource.JarChecker(jarFile.toURI(), root.toURI()));
}
finally
{
jarFile.delete();
}
}
finally
{
IOUtils.deleteFile(root);
}
}
/**
* Checks the tree resource.
*/
public static void checkTreeResource(Resource rootResource,
File[][] files,
TestResource.Checker checker)
throws IOException, URISyntaxException
{
assertTrue(rootResource.exists());
checkSubTree(rootResource, files[0], rootResource, files[0], checker);
checker.checkListResource(rootResource, files[0][ROOT]);
// d1
Resource d1Resource = rootResource.createRelative("d1/");
checkSubTree(rootResource, files[0], d1Resource, files[1], checker);
checker.checkListResource(d1Resource, files[1][ROOT]);
// we make sure that a combination of / is not affecting the result (note that since
// d1 is at the root /d1 and d1 are equivalent)
d1Resource = rootResource.createRelative("d1/");
checkSubTree(rootResource, files[0], d1Resource, files[1], checker);
checker.checkListResource(d1Resource, files[1][ROOT]);
d1Resource = rootResource.createRelative("/d1");
checkSubTree(rootResource, files[0], d1Resource, files[1], checker);
checker.checkListResource(d1Resource, files[1][ROOT]);
d1Resource = rootResource.createRelative("/d1/");
checkSubTree(rootResource, files[0], d1Resource, files[1], checker);
checker.checkListResource(d1Resource, files[1][ROOT]);
// d1_1
Resource d1_1Resource = d1Resource.createRelative("d1_1");
checkSubTree(rootResource, files[0], d1_1Resource, files[2], checker);
checker.checkListResource(d1_1Resource, files[2][ROOT]);
// /d1_1 does not exists...
checkNonExistentResource(d1Resource.getRootResource().createRelative("/d1_1"),
new File(files[0][ROOT], "d1_1"), checker);
// test of chroot
checkChroot(d1Resource, files[2][A], checker);
// d2
Resource d2Resource = rootResource.createRelative("d2");
checkSubTree(rootResource, files[0], d2Resource, files[3], checker);
checker.checkListResource(d2Resource, files[3][ROOT]);
// WEB-INF
Resource webInfResource = rootResource.createRelative("/WEB-INF");
checker.checkListResource(webInfResource, files[4][ROOT]);
checkResource(webInfResource, "web.xml", files[4][1], checker);
}
/**
* Checks chroot
*/
private static void checkChroot(Resource d1Resource, File expectedFile, TestResource.Checker checker)
throws IOException, URISyntaxException
{
Resource d1_1Resource = d1Resource.chroot("d1_1/");
assertEquals(d1_1Resource, d1_1Resource.getRootResource());
assertEquals(d1_1Resource, d1_1Resource.getParentResource());
checkResource(d1_1Resource, "a.html", expectedFile, checker);
d1_1Resource = d1Resource.chroot("d1_1");
assertEquals(d1_1Resource, d1_1Resource.getRootResource());
assertEquals(d1_1Resource, d1_1Resource.getParentResource());
checkResource(d1_1Resource, "a.html", expectedFile, checker);
d1_1Resource = d1Resource.getRootResource().chroot("/d1/d1_1/");
assertEquals(d1_1Resource, d1_1Resource.getRootResource());
assertEquals(d1_1Resource, d1_1Resource.getParentResource());
checkResource(d1_1Resource, "a.html", expectedFile, checker);
d1_1Resource = d1_1Resource.chroot(".");
assertEquals(d1_1Resource, d1_1Resource.getRootResource());
assertEquals(d1_1Resource, d1_1Resource.getParentResource());
checkResource(d1_1Resource, "a.html", expectedFile, checker);
d1_1Resource = d1Resource.createRelative("d1_1/empty/").chroot("../");
assertEquals(d1_1Resource, d1_1Resource.getRootResource());
assertEquals(d1_1Resource, d1_1Resource.getParentResource());
checkResource(d1_1Resource, "a.html", expectedFile, checker);
Resource ar = d1Resource.createRelative("d1_1/a.html").chroot("");
checkResource(ar, expectedFile, checker);
assertEquals("/a.html", ar.getPath());
ar = d1Resource.chroot("d1_1/a.html");
checkResource(ar, expectedFile, checker);
assertEquals("/a.html", ar.getPath());
}
/**
* Checks the tree resource.
*/
public static void checkTreeResourceForURL(Resource rootResource,
File[][] files,
TestResource.Checker checker)
throws IOException, URISyntaxException
{
checkSubTree(rootResource, files[0], rootResource, files[0], checker);
checker.checkListResource(rootResource, files[0][ROOT]);
// d1
Resource d1Resource = rootResource.createRelative("d1/");
checkSubTree(rootResource, files[0], d1Resource, files[1], checker);
checker.checkListResource(d1Resource, files[1][ROOT]);
// d1_1
Resource d1_1Resource = d1Resource.createRelative("d1_1/");
checkSubTree(rootResource, files[0], d1_1Resource, files[2], checker);
checker.checkListResource(d1_1Resource, files[2][ROOT]);
// d2
Resource d2Resource = rootResource.createRelative("d2/");
checkSubTree(rootResource, files[0], d2Resource, files[3], checker);
checker.checkListResource(d2Resource, files[3][ROOT]);
}
/**
* Check the subtree: verifies createRelative(filter), and each individual resource
*/
private static void checkSubTree(Resource rooResource,
File[] rootFiles,
Resource resource,
File[] files,
TestResource.Checker checker)
throws IOException, URISyntaxException
{
assertTrue(rooResource.exists());
checker.checkListResources(resource, ".foo");
checker.checkListResources(resource, ".html", resource.createRelative("a.html"));
checker.checkListResources(resource,
".txt",
resource.createRelative("b.txt"),
resource.createRelative("c.txt"));
checker.checkListResources(resource, "empty", resource.createRelative("empty/"));
checker.checkListResources(resource, "empty", resource.createRelative("empty"));
checker.checkListResources(resource, "empty", resource.createRelative("/empty/"));
checker.checkListResources(resource, "empty", resource.createRelative("/empty"));
checker.checkListResources(rooResource, "empty", resource.getRootResource().createRelative("/empty/"));
checker.checkListResources(rooResource, "empty", resource.getRootResource().createRelative("/empty"));
checkResource(resource, "a.html", files[A], checker);
checkResource(resource, "b.txt", files[B], checker);
checkResource(resource, "c.txt", files[C], checker);
checkResource(resource, "empty/", files[EMPTY], checker);
checkResource(resource.getRootResource(), "/a.html", rootFiles[A], checker);
checkResource(resource.getRootResource(), "/b.txt", rootFiles[B], checker);
checkResource(resource.getRootResource(), "/c.txt", rootFiles[C], checker);
checkResource(resource.getRootResource(), "/empty/", rootFiles[EMPTY], checker);
// checking that . ./ and "" are working correctly
assertEquals(resource.createRelative("empty").toURI(),
resource.createRelative("empty").createRelative(".").toURI());
assertEquals(resource.createRelative("empty/").toURI(),
resource.createRelative("empty/").createRelative(".").toURI());
assertEquals(resource.createRelative("empty/").toURI(),
resource.createRelative("empty/").createRelative("./").toURI());
assertEquals(resource.createRelative("empty").toURI(),
resource.createRelative("empty").createRelative("").toURI());
assertTrue(resource.createRelative("/").getPath().endsWith("/"));
assertTrue(resource.createRelative("a.html").createRelative("/").getPath().endsWith("/"));
checkEmptyDirectory(files[EMPTY], resource.createRelative("empty/"), checker);
checkParentResource(resource);
checkRootResource(resource, rooResource);
}
/**
* We check the parent resource functionnality
*
* @param resourceDir
* @throws IOException
*/
private static void checkParentResource(Resource resourceDir) throws IOException
{
checkResource(resourceDir.createRelative("a.html").getParentResource(), resourceDir);
checkResource(resourceDir.createRelative("a.html").createRelative(".."), resourceDir);
checkResource(resourceDir.createRelative("a.html").createRelative("../b.txt"),
resourceDir.createRelative("b.txt"));
}
/**
* Compares 2 resources..
*
* @param resource
* @param expectedResource
*/
private static void checkResource(Resource resource, Resource expectedResource)
{
assertEquals(expectedResource.isDirectory(), resource.isDirectory());
assertEquals(expectedResource.getFilename(), resource.getFilename());
checkPath(expectedResource.getPath(), resource.getPath());
assertEquals(PathUtils.removeTrailingSlash(expectedResource.toURI().toString()),
PathUtils.removeTrailingSlash(resource.toURI().toString()));
}
/**
* The problem with paths is that there may be a trailing slash or not depending on the
* implementation...
*
* @param path
* @param expectedPath
*/
private static void checkPath(String path, String expectedPath)
{
if(expectedPath.equals("/"))
assertEquals("/", path);
else
assertEquals(PathUtils.removeTrailingSlash(expectedPath),
PathUtils.removeTrailingSlash(path));
}
/**
* We check the root resource functionnality
*
* @throws IOException
*/
private static void checkRootResource(Resource resource, Resource expectedRootResource) throws IOException
{
checkResource(resource.getRootResource(), expectedRootResource);
checkResource(resource.getRootResource().createRelative("/"), expectedRootResource);
checkResource(resource.getRootResource().createRelative("/.././"), expectedRootResource);
}
/**
* Check an individual resource and compares it to the original file. Even read the content
*/
private static void checkResource(Resource root, String relativePath, File file, TestResource.Checker checker)
throws IOException, URISyntaxException
{
checkResource(root.createRelative(relativePath), file, checker);
}
/**
* Check an individual resource and compares it to the original file. Even read the content
*/
private static void checkResource(Resource resource, File file, TestResource.Checker checker)
throws IOException, URISyntaxException
{
checker.checkInfo(resource, file);
if(file.isDirectory())
{
checker.checkDirectoryContent(resource);
}
else
{
assertEquals(readContent(file), readContent(resource));
}
checker.checkURI(resource, file);
assertEquals(file.getName(), resource.getFilename());
}
/**
* Compare the 2 arrays without caring about the order of the elements in the array
*
* @param msg
* @param computed
* @param expected
* @throws IOException
*/
private static void assertEqualsOrderDontCare(String msg, Resource[] computed, Resource... expected)
throws IOException
{
if(expected == null)
{
assertNull("computed should be null", computed);
return;
}
assertNotNull("computed should not be null", computed);
assertEquals(expected.length, computed.length);
if(expected.length == 0)
return;
if(expected.length > 1)
{
Set<String> expectedURIs = new HashSet<String>(expected.length);
for(Resource resource : expected)
{
String uri = resource.toString();
uri = PathUtils.removeTrailingSlash(uri);
expectedURIs.add(uri);
}
Set<String> computedURIs = new HashSet<String>(computed.length);
for(Resource resource : computed)
{
String uri = resource.toString();
uri = PathUtils.removeTrailingSlash(uri);
computedURIs.add(uri);
}
assertEquals(msg, expectedURIs, computedURIs);
}
else
{
checkResource(computed[0], expected[0]);
}
}
/**
* Creates a subtree in the given directory.
*
* @param root
* @return the file objects created (using the constants)
* @throws IOException
*/
private File[] createSubTree(File root) throws IOException
{
return createSubTree(root, "a.html", "b.txt", "c.txt", "empty/");
}
/**
* Creates a subtree in the given directory.
*
* @param root
* @return the file objects created (using the constants)
* @throws IOException
*/
private File[] createSubTree(File root, String... paths) throws IOException
{
File[] res = new File[paths.length + 1];
res[ROOT] = root;
for(int i = 0; i < paths.length; i++)
{
File file = null;
String path = paths[i];
if(path != null)
{
if(path.endsWith("/"))
file = createDir(new File(root, path));
else
file = createFile(new File(root, path));
}
res[i+1] = file;
}
return res;
}
/**
* Creates the web-inf files. Currently web.xml.
*/
private File[] createWebInfFiles(File dir, String webXmlContent) throws IOException
{
File[] res = new File[2];
res[0] = dir;
if(webXmlContent != null)
res[1] = createFile(new File(dir, "web.xml"), webXmlContent);
return res;
}
/**
* Creates a temporary directory.
*
* @param namespace
* @param name root name of the temporary directory
* @return the temp dir
* @throws IOException if there is a problem
*/
public File createTempDirectory(String namespace, String name) throws IOException
{
File tempDirectory = IOUtils.createTempDirectory(namespace, name);
_deleteOnExit.add(tempDirectory.getParentFile());
return tempDirectory;
}
/**
* Creates a file and populate with the content.
*
* @param file
* @return the file provided for convenience...
*/
public static File createFile(File file) throws IOException
{
return createFile(file, "{" + file.getCanonicalPath() + "}");
}
/**
* Creates a file and populate with the content.
*
* @param file
* @param content
* @return the file provided for convenience...
*/
public static File createFile(File file, String content) throws IOException
{
file.deleteOnExit();
FileWriter fw = new FileWriter(file);
try
{
BufferedWriter writer = new BufferedWriter(fw);
writer.write(content);
writer.flush();
return file.getCanonicalFile();
}
finally
{
fw.close();
}
}
/**
* Encapsulates the creation of a directory
*
* @param dir
* @return the directory provided for convenience
* @throws IOException
*/
public static File createDir(File dir) throws IOException
{
IOUtils.createNewDirectory(dir);
dir.deleteOnExit();
return dir.getCanonicalFile();
}
/**
* Reads the full content of the resource
*
* @param resource
* @return the full content
* @throws IOException
*/
public static String readContent(Resource resource) throws IOException
{
InputStream is = resource.getInputStream();
try
{
return readContent(is);
}
finally
{
is.close();
}
}
/**
* Reads the full content of the file
*
* @param file
* @return the full content
* @throws IOException
*/
public static String readContent(File file) throws IOException
{
InputStream is = new FileInputStream(file);
try
{
return readContent(is);
}
finally
{
is.close();
}
}
/**
* Reads the content of the input stream and return it as a string.
*
* @param is
* @return the content as a string
* @throws IOException
*/
public static String readContent(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(is, baos);
return new String(baos.toByteArray());
}
/**
* Creates a jar file with all the files contained in root. (Uses jar command)
*
* @param namespace
* @param root
* @return the jar file
* @throws IOException
* @throws InterruptedException
*/
public File createJarFile(String namespace, File root)
throws IOException, InterruptedException
{
File jarDirectory = createTempDirectory(namespace, root.getName() + "_jar");
File jarFile = new File(jarDirectory, root.getName() + ".jar");
return copyToJar(jarFile, root, false);
}
/**
* Creates a jar file with all the files contained in root. (Uses jar command)
*
* @param jarFile to put the files in
* @param root
* @return the jar file
* @throws IOException
* @throws InterruptedException
*/
public static File copyToJar(File jarFile, File root, boolean update)
throws IOException, InterruptedException
{
ExternalCommand cmd =
ExternalCommand.create("jar", "-" + (update ? "u" : "c") + "vfM",
jarFile.getCanonicalPath(),
".");
cmd.setWorkingDirectory(root);
cmd.start();
cmd.waitFor();
assertEquals(0, cmd.exitValue());
jarFile.deleteOnExit();
return jarFile.getCanonicalFile();
}
}
|
3e1c5cae2013e2e08fb39ed6a70677c427290c02 | 8,361 | java | Java | webfx-kit/webfx-kit-javafxgraphics-emul/src/main/java/javafx/scene/image/PixelReader.java | naga-project/naga-core | b9263c7df5b106b7095b92ee661ea51d2fac9d37 | [
"Apache-2.0"
] | 127 | 2019-01-01T23:41:32.000Z | 2022-03-22T12:19:27.000Z | webfx-kit/webfx-kit-javafxgraphics-emul/src/main/java/javafx/scene/image/PixelReader.java | naga-project/naga-core | b9263c7df5b106b7095b92ee661ea51d2fac9d37 | [
"Apache-2.0"
] | 3 | 2019-11-14T10:20:26.000Z | 2020-11-27T21:54:33.000Z | webfx-kit/webfx-kit-javafxgraphics-emul/src/main/java/javafx/scene/image/PixelReader.java | naga-project/naga-core | b9263c7df5b106b7095b92ee661ea51d2fac9d37 | [
"Apache-2.0"
] | 10 | 2020-08-08T20:24:10.000Z | 2022-01-29T23:35:51.000Z | 46.97191 | 79 | 0.679584 | 12,028 | /*
* Copyright (c) 2012, 2017, 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 javafx.scene.image;
import javafx.scene.paint.Color;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
/**
* This interface defines methods for retrieving the pixel data from an
* {@link Image} or other surface containing pixels.
* @since JavaFX 2.2
*/
public interface PixelReader {
/**
* This method returns the {@code PixelFormat} in which the surface
* stores its pixels, or a roughly equivalent pixel format into which
* it can easily convert its pixels for purposes of reading them.
*
* @return the {@code PixelFormat} that best describes the underlying
* pixels
*/
public PixelFormat getPixelFormat();
/**
* Reads a 32-bit integer representation of the color of a pixel
* from the specified coordinates in the surface.
* The 32-bit integer will contain the 4 color components in separate
* 8-bit fields in ARGB order from the most significant byte to the least
* significant byte.
*
* @param x the X coordinate of the pixel color to read
* @param y the Y coordinate of the pixel color to read
* @return a 32-bit representation of the color in the format
* described by the {@link PixelFormat.Type#INT_ARGB INT_ARGB}
* PixelFormat type.
*/
public int getArgb(int x, int y);
/**
* Reads the color of a pixel from the specified coordinates in the
* surface and returns the value as a {@link Color} object.
*
* @param x the X coordinate of the pixel color to read
* @param y the Y coordinate of the pixel color to read
* @return the Color object representing the color of the indicated
* pixel
*/
public Color getColor(int x, int y);
/**
* Reads pixel data from a rectangular region of the surface into the
* specified buffer.
* The format to be used for pixels in the buffer is defined by the
* {@link PixelFormat} object and pixel format conversions will be
* performed as needed to store the data in the indicated format.
* The buffer is assumed to be positioned to the location where the
* first pixel data from the image pixel at location {@code (x, y)}
* will be stored.
* Pixel data for a row will be stored in adjacent locations within
* the buffer packed as tightly as possible for increasing X
* coordinates.
* Pixel data for adjacent rows will be stored offset from each other
* by the number of buffer data elements defined by
* {@code scanlineStride}.
*
* @param <T> the type of the buffer
* @param x the X coordinate of the rectangular region to read
* @param y the Y coordinate of the rectangular region to read
* @param w the width of the rectangular region to read
* @param h the height of the rectangular region to read
* @param pixelformat the {@code PixelFormat} object defining the format
* to store the pixels into buffer
* @param buffer a buffer of a type appropriate for the indicated
* {@code PixelFormat} object
* @param scanlineStride the distance between the pixel data for the
* start of one row of data in the buffer to the start of the
* next row of data.
*/
public <T extends Buffer>
void getPixels(int x, int y, int w, int h,
WritablePixelFormat<T> pixelformat,
T buffer, int scanlineStride);
/**
* Reads pixel data from a rectangular region of the surface into the
* specified byte array.
* The format to be used for pixels in the buffer is defined by the
* {@link PixelFormat} object and pixel format conversions will be
* performed as needed to store the data in the indicated format.
* The {@code pixelformat} must be a compatible
* {@code PixelFormat<ByteBuffer>} type.
* The data for the first pixel at location {@code (x, y)} will be
* read into the array index specified by the {@code offset} parameter.
* Pixel data for a row will be stored in adjacent locations within
* the array packed as tightly as possible for increasing X
* coordinates.
* Pixel data for adjacent rows will be stored offset from each other
* by the number of byte array elements defined by
* {@code scanlineStride}.
*
* @param x the X coordinate of the rectangular region to read
* @param y the Y coordinate of the rectangular region to read
* @param w the width of the rectangular region to read
* @param h the height of the rectangular region to read
* @param pixelformat the {@code PixelFormat<ByteBuffer>} object
* defining the byte format to store the pixels into buffer
* @param buffer a byte array to store the returned pixel data
* @param offset the offset into {@code buffer} to store the first
* pixel data
* @param scanlineStride the distance between the pixel data for the
* start of one row of data in the buffer to the start of the
* next row of data
*/
public void getPixels(int x, int y, int w, int h,
WritablePixelFormat<ByteBuffer> pixelformat,
byte buffer[], int offset, int scanlineStride);
/**
* Reads pixel data from a rectangular region of the surface into the
* specified int array.
* The format to be used for pixels in the buffer is defined by the
* {@link PixelFormat} object and pixel format conversions will be
* performed as needed to store the data in the indicated format.
* The {@code pixelformat} must be a compatible
* {@code PixelFormat<IntBuffer>} type.
* The data for the first pixel at location {@code (x, y)} will be
* read into the array index specified by the {@code offset} parameter.
* Pixel data for a row will be stored in adjacent locations within
* the array packed as tightly as possible for increasing X
* coordinates.
* Pixel data for adjacent rows will be stored offset from each other
* by the number of int array elements defined by
* {@code scanlineStride}.
*
* @param x the X coordinate of the rectangular region to read
* @param y the Y coordinate of the rectangular region to read
* @param w the width of the rectangular region to read
* @param h the height of the rectangular region to read
* @param pixelformat the {@code PixelFormat<IntBuffer>} object
* defining the int format to store the pixels into buffer
* @param buffer a int array to store the returned pixel data
* @param offset the offset into {@code buffer} to store the first
* pixel data
* @param scanlineStride the distance between the pixel data for the
* start of one row of data in the buffer to the start of the
* next row of data
*/
public void getPixels(int x, int y, int w, int h,
WritablePixelFormat<IntBuffer> pixelformat,
int buffer[], int offset, int scanlineStride);
}
|
3e1c5ce65641f14631109f33894317fc4290846b | 982 | java | Java | src/com/cg/demo/col/EmpDemoCol.java | sonudabhade/com-cg-java-demo | ee7d600f177ded5a19856fd559ebc1d3ca7409dd | [
"MIT"
] | null | null | null | src/com/cg/demo/col/EmpDemoCol.java | sonudabhade/com-cg-java-demo | ee7d600f177ded5a19856fd559ebc1d3ca7409dd | [
"MIT"
] | null | null | null | src/com/cg/demo/col/EmpDemoCol.java | sonudabhade/com-cg-java-demo | ee7d600f177ded5a19856fd559ebc1d3ca7409dd | [
"MIT"
] | null | null | null | 22.318182 | 59 | 0.676171 | 12,029 | package com.cg.demo.col;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class EmpDemoCol {
public static void main(String[] args) {
EmployeeCol emp = new EmployeeCol();
Delete delete = new Delete();
List<EmployeeCol> empList = new ArrayList<EmployeeCol>();
empList.add(emp);
empList.add(new EmployeeCol());
empList.add(new EmployeeCol(103, "Aaa", 10.5));
// empList.add("Aaa"); // CE
// empList.add(delete); // CE
// System.out.println(empList);
System.out.println("Iterate using for loop");
for (int i = 0; i < empList.size(); i++) {
System.out.println(empList.get(i).toString());
}
System.out.println("Iterate using for each loop");
for (EmployeeCol e : empList) {
System.out.println(e.toString());
}
System.out.println("Iterate using Iterator");
Iterator<EmployeeCol> iterator = empList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toString());
}
}
} |
3e1c5d1caf0c7a97e5c6360acad346b82fb8a9e0 | 5,594 | java | Java | geode-core/src/main/java/org/apache/geode/internal/cache/backup/TemporaryBackupFiles.java | Kris-10-0/geode | 7ccdc8297b1ded06175f41543884d945d5995c60 | [
"Apache-2.0"
] | 1,475 | 2016-12-06T06:10:53.000Z | 2022-03-30T09:55:23.000Z | geode-core/src/main/java/org/apache/geode/internal/cache/backup/TemporaryBackupFiles.java | Kris-10-0/geode | 7ccdc8297b1ded06175f41543884d945d5995c60 | [
"Apache-2.0"
] | 2,809 | 2016-12-06T19:24:26.000Z | 2022-03-31T22:02:20.000Z | geode-core/src/main/java/org/apache/geode/internal/cache/backup/TemporaryBackupFiles.java | Kris-10-0/geode | 7ccdc8297b1ded06175f41543884d945d5995c60 | [
"Apache-2.0"
] | 531 | 2016-12-06T05:48:47.000Z | 2022-03-31T23:06:37.000Z | 39.957143 | 100 | 0.746693 | 12,030 | /*
* 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.geode.internal.cache.backup;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Logger;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.internal.cache.DirectoryHolder;
import org.apache.geode.internal.cache.Oplog;
import org.apache.geode.logging.internal.log4j.api.LogService;
/**
* Creates and keeps track of the temporary locations used during a backup. Most temporary files are
* stored in a shared temporary directory, except for those for DiskStores. For each
* {@link DiskStore}, a temporary directory is created per disk directory within that disk directory
* (for enabling creation of hard-links for backing up the files of an {@link Oplog}).
*/
class TemporaryBackupFiles {
private static final Logger logger = LogService.getLogger();
private final String diskStoreDirectoryName;
private final Path directory;
private final Map<DiskStore, Map<DirectoryHolder, Path>> diskStoreDirDirsByDiskStore =
new HashMap<>();
/**
* Creates a new instance with the default structure, where temporary directories are created
* using the current timestamp in their name for the purpose of uniquification
*
* @return a new TemporaryBackupFiles
* @throws IOException If unable to create a temporary directory
*/
static TemporaryBackupFiles create() throws IOException {
long currentTime = System.currentTimeMillis();
String diskStoreDirectoryName = BackupService.TEMPORARY_DIRECTORY_FOR_BACKUPS + currentTime;
Path temporaryDirectory = Files.createTempDirectory("backup_" + currentTime);
return new TemporaryBackupFiles(temporaryDirectory, diskStoreDirectoryName);
}
/**
* Constructs a new TemporaryBackupFiles that will use the specified locations for temporary files
*
* @param directory the location to create and store temporary files during backup
* @param diskStoreDirectoryName name of directory to create within each disk store directory for
* its temporary files during backup
*/
TemporaryBackupFiles(Path directory, String diskStoreDirectoryName) {
if (directory == null) {
throw new IllegalArgumentException("Must provide a temporary directory location");
}
if (diskStoreDirectoryName == null || diskStoreDirectoryName.isEmpty()) {
throw new IllegalArgumentException("Must provide a name for temporary DiskStore directories");
}
this.directory = directory;
this.diskStoreDirectoryName = diskStoreDirectoryName;
}
/**
* Provides the temporary directory location used for all temporary backup files except those for
* Oplogs
*
* @return The path of the shared temporary directory
*/
Path getDirectory() {
return directory;
}
/**
* Provides, and creates if necessary, the temporary directory used during the backup for Oplog
* files for the given DiskStore and DirectoryHolder
*
* @param diskStore The corresponding {@link DiskStore} to get a temporary directory for
* @param dirHolder The disk directory of the {@link DiskStore} to get a temporary directory for
* @return Path to the temporary directory
* @throws IOException If the temporary directory did not exist and could not be created
*/
Path getDiskStoreDirectory(DiskStore diskStore, DirectoryHolder dirHolder) throws IOException {
Map<DirectoryHolder, Path> tempDirByDirectoryHolder =
diskStoreDirDirsByDiskStore.computeIfAbsent(diskStore, k -> new HashMap<>());
Path directory = tempDirByDirectoryHolder.get(dirHolder);
if (directory != null) {
return directory;
}
File diskStoreDir = dirHolder.getDir();
directory = diskStoreDir.toPath().resolve(diskStoreDirectoryName);
Files.createDirectories(directory);
tempDirByDirectoryHolder.put(dirHolder, directory);
return directory;
}
/**
* Attempts to delete all temporary directories and their contents. An attempt will be made to
* delete each directory, regardless of the failure to delete any particular one.
*/
void cleanupFiles() {
if (directory != null) {
deleteDirectory(directory);
}
for (Map<DirectoryHolder, Path> diskStoreDirToTempDirMap : diskStoreDirDirsByDiskStore
.values()) {
for (Path tempDir : diskStoreDirToTempDirMap.values()) {
deleteDirectory(tempDir);
}
}
}
private void deleteDirectory(Path directory) {
try {
FileUtils.deleteDirectory(directory.toFile());
} catch (IOException | IllegalArgumentException e) {
logger.warn("Unable to delete temporary directory created during backup, " + this.directory,
e);
}
}
}
|
3e1c5d4e8f2052b229ebab6ac7e1271b58372b54 | 61 | java | Java | src/main/java/haus/pup/tts/Gender.java | wlfyit/TTSHub | 6643dd41be0a8b40ad06dddb21c252cb79b1feb3 | [
"MIT"
] | null | null | null | src/main/java/haus/pup/tts/Gender.java | wlfyit/TTSHub | 6643dd41be0a8b40ad06dddb21c252cb79b1feb3 | [
"MIT"
] | null | null | null | src/main/java/haus/pup/tts/Gender.java | wlfyit/TTSHub | 6643dd41be0a8b40ad06dddb21c252cb79b1feb3 | [
"MIT"
] | null | null | null | 10.166667 | 21 | 0.704918 | 12,031 | package haus.pup.tts;
public enum Gender {
MALE, FEMALE
}
|
3e1c5d9984fa73abd392b66d3648b8fad0f489d5 | 156 | java | Java | src/solution/MaxValueInQueue.java | IT-Billy/Point2offer | b7aa57cadb099c19ad45472479a3785787294c6e | [
"Apache-2.0"
] | 11 | 2019-03-07T12:37:43.000Z | 2021-12-16T05:14:59.000Z | src/solution/MaxValueInQueue.java | IT-Billy/Point2offer | b7aa57cadb099c19ad45472479a3785787294c6e | [
"Apache-2.0"
] | null | null | null | src/solution/MaxValueInQueue.java | IT-Billy/Point2offer | b7aa57cadb099c19ad45472479a3785787294c6e | [
"Apache-2.0"
] | 4 | 2019-08-04T12:45:50.000Z | 2021-06-13T12:12:49.000Z | 13 | 42 | 0.730769 | 12,032 | package solution;
/**
* 面试题59(二):队列的最大值
* 题目:请定义一个队列并实现函数max得到队列里的最大值,
* 要求函数max、pollLast和pollFirst的时间复杂度都是O(1)。
*/
public class MaxValueInQueue {
}
|
3e1c5da7d716d8080a1e332fab8cc2889b665271 | 10,538 | java | Java | kernel/src/test/java/com/itextpdf/kernel/pdf/ImageFormatsTest.java | liuzhenxin/itext7 | 1b90f52b17700805ef8942c7276b35abaca8b31b | [
"RSA-MD"
] | 1,269 | 2016-05-03T13:57:05.000Z | 2022-03-31T02:35:48.000Z | kernel/src/test/java/com/itextpdf/kernel/pdf/ImageFormatsTest.java | liuzhenxin/itext7 | 1b90f52b17700805ef8942c7276b35abaca8b31b | [
"RSA-MD"
] | 61 | 2016-06-03T21:59:20.000Z | 2022-02-25T07:05:35.000Z | kernel/src/test/java/com/itextpdf/kernel/pdf/ImageFormatsTest.java | liuzhenxin/itext7 | 1b90f52b17700805ef8942c7276b35abaca8b31b | [
"RSA-MD"
] | 396 | 2016-05-21T03:36:50.000Z | 2022-03-30T08:55:57.000Z | 46.632743 | 116 | 0.670462 | 12,033 | /*
This file is part of the iText (R) project.
Copyright (c) 1998-2021 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: efpyi@example.com
*/
package com.itextpdf.kernel.pdf;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.utils.CompareTool;
import com.itextpdf.test.ExtendedITextTest;
import com.itextpdf.test.annotations.type.IntegrationTest;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.IOException;
@Category(IntegrationTest.class)
public class ImageFormatsTest extends ExtendedITextTest {
public static final String destinationFolder = "./target/test/com/itextpdf/kernel/pdf/ImageFormatsTest/";
public static final String sourceFolder = "./src/test/resources/com/itextpdf/kernel/pdf/ImageFormatsTest/";
@BeforeClass
public static void beforeClass() {
createOrClearDestinationFolder(destinationFolder);
}
@Test
public void imagesWithDifferentDepth() throws IOException, InterruptedException {
String outFileName = destinationFolder + "transparencyTest01.pdf";
String cmpFileName = sourceFolder + "cmp_transparencyTest01.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties()
.setCompressionLevel(CompressionConstants.NO_COMPRESSION)));
PdfPage page = pdfDocument.addNewPage(PageSize.A3);
PdfCanvas canvas = new PdfCanvas(page);
canvas.setFillColor(ColorConstants.LIGHT_GRAY).fill();
canvas.rectangle(80, 0, 700, 1200).fill();
canvas
.saveState()
.beginText()
.moveText(116, 1150)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 14)
.setFillColor(ColorConstants.MAGENTA)
.showText("8 bit depth PNG")
.endText()
.restoreState();
ImageData img = ImageDataFactory.create(sourceFolder + "manualTransparency_8bit.png");
canvas.addImageFittedIntoRectangle(img, new Rectangle(100, 780, 200, 292.59f), false);
canvas
.saveState()
.beginText()
.moveText(316, 1150)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 14)
.setFillColor(ColorConstants.MAGENTA)
.showText("24 bit depth PNG")
.endText()
.restoreState();
img = ImageDataFactory.create(sourceFolder + "manualTransparency_24bit.png");
canvas.addImageFittedIntoRectangle(img, new Rectangle(300, 780, 200, 292.59f), false);
canvas
.saveState()
.beginText()
.moveText(516, 1150)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 14)
.setFillColor(ColorConstants.MAGENTA)
.showText("32 bit depth PNG")
.endText()
.restoreState();
img = ImageDataFactory.create(sourceFolder + "manualTransparency_32bit.png");
canvas.addImageFittedIntoRectangle(img, new Rectangle(500, 780, 200, 292.59f), false);
canvas
.saveState()
.beginText()
.moveText(116, 650)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 16)
.setFillColor(ColorConstants.MAGENTA)
.showText("GIF image ")
.endText()
.restoreState();
img = ImageDataFactory.create(sourceFolder + "manualTransparency_gif.gif");
canvas.addImageFittedIntoRectangle(img, new Rectangle(100, 300, 200, 292.59f), false);
canvas
.saveState()
.beginText()
.moveText(316, 650)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 16)
.setFillColor(ColorConstants.MAGENTA)
.showText("TIF image ")
.endText()
.restoreState();
img = ImageDataFactory.create(sourceFolder + "manualTransparency_tif.tif");
canvas.addImageFittedIntoRectangle(img, new Rectangle(300, 300, 200, 292.59f), false);
canvas.release();
pdfDocument.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff_"));
}
@Test
public void png_imageTransparency_8bitDepthImage() throws IOException, InterruptedException {
String outFileName = destinationFolder + "png_imageTransparancy_8bitDepthImage.pdf";
String cmpFileName = sourceFolder + "cmp_png_imageTransparancy_8bitDepthImage.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties()
.setCompressionLevel(CompressionConstants.NO_COMPRESSION)));
PdfPage page = pdfDocument.addNewPage(PageSize.A4);
PdfCanvas canvas = new PdfCanvas(page);
canvas.setFillColor(ColorConstants.LIGHT_GRAY).fill();
canvas.rectangle(80, 0, PageSize.A4.getWidth()-80, PageSize.A4.getHeight()).fill();
canvas
.saveState()
.beginText()
.moveText(116, 800)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 14)
.setFillColor(ColorConstants.MAGENTA)
.showText("8 bit depth PNG")
.moveText(0,-20)
.showText("This image should not have a black rectangle as background")
.endText()
.restoreState();
ImageData img = ImageDataFactory.create(sourceFolder + "manualTransparency_8bit.png");
canvas.addImageFittedIntoRectangle(img, new Rectangle(100, 450, 200, 292.59f), false);
canvas.release();
pdfDocument.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff_"));
}
@Test
public void png_imageTransparency_24bitDepthImage() throws IOException, InterruptedException {
String outFileName = destinationFolder + "png_imageTransparancy_24bitDepthImage.pdf";
String cmpFileName = sourceFolder + "cmp_png_imageTransparancy_24bitDepthImage.pdf";
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName, new WriterProperties()
.setCompressionLevel(CompressionConstants.NO_COMPRESSION)));
PdfPage page = pdfDocument.addNewPage(PageSize.A4);
PdfCanvas canvas = new PdfCanvas(page);
canvas.setFillColor(ColorConstants.LIGHT_GRAY).fill();
canvas.rectangle(80, 0, PageSize.A4.getWidth()-80, PageSize.A4.getHeight()).fill();
canvas
.saveState()
.beginText()
.moveText(116, 800)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 14)
.setFillColor(ColorConstants.MAGENTA)
.showText("24 bit depth PNG")
.moveText(0,-20)
.showText("This image should not have a white rectangle as background")
.endText()
.restoreState();
ImageData img = ImageDataFactory.create(sourceFolder + "manualTransparency_24bit.png");
canvas.addImageFittedIntoRectangle(img, new Rectangle(100, 450, 200, 292.59f), false);
canvas
.saveState()
.beginText()
.moveText(116, 400)
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 14)
.setFillColor(ColorConstants.MAGENTA)
.showText("32 bit depth PNG")
.endText()
.restoreState();
img = ImageDataFactory.create(sourceFolder + "manualTransparency_32bit.png");
canvas.addImageFittedIntoRectangle(img, new Rectangle(116, 100, 200, 292.59f), false);
canvas.release();
pdfDocument.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff_"));
}
}
|
3e1c5e074e92a2f3eb985f4833171722c4084eca | 224 | java | Java | src/main/java/io/odpf/firehose/sink/objectstorage/writer/local/policy/WriterPolicy.java | gauravsinghania/firehose | 300db433fa370645da09f13860c34bfa677b919b | [
"Apache-2.0"
] | null | null | null | src/main/java/io/odpf/firehose/sink/objectstorage/writer/local/policy/WriterPolicy.java | gauravsinghania/firehose | 300db433fa370645da09f13860c34bfa677b919b | [
"Apache-2.0"
] | null | null | null | src/main/java/io/odpf/firehose/sink/objectstorage/writer/local/policy/WriterPolicy.java | gauravsinghania/firehose | 300db433fa370645da09f13860c34bfa677b919b | [
"Apache-2.0"
] | null | null | null | 28 | 72 | 0.825893 | 12,034 | package io.odpf.firehose.sink.objectstorage.writer.local.policy;
import io.odpf.firehose.sink.objectstorage.writer.local.LocalFileWriter;
public interface WriterPolicy {
boolean shouldRotate(LocalFileWriter writer);
}
|
3e1c6029eaf70bfc9012227a0a1c6f4d7a46f643 | 7,287 | java | Java | app/src/main/java/cbgm/de/listapi/basic/CBViewHolder.java | cbgm/ListAPI | ab22b7b923105b0e124b26a9882875cc7ab482e6 | [
"MIT"
] | null | null | null | app/src/main/java/cbgm/de/listapi/basic/CBViewHolder.java | cbgm/ListAPI | ab22b7b923105b0e124b26a9882875cc7ab482e6 | [
"MIT"
] | null | null | null | app/src/main/java/cbgm/de/listapi/basic/CBViewHolder.java | cbgm/ListAPI | ab22b7b923105b0e124b26a9882875cc7ab482e6 | [
"MIT"
] | null | null | null | 36.435 | 167 | 0.639907 | 12,035 | package cbgm.de.listapi.basic;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
import cbgm.de.listapi.R;
import cbgm.de.listapi.data.CBLayoutID;
import cbgm.de.listapi.data.CBListMode;
import cbgm.de.listapi.data.CBModeHelper;
import cbgm.de.listapi.listener.ICBActionNotifier;
@SuppressWarnings("unused")
public abstract class CBViewHolder<I> extends RecyclerView.ViewHolder {
/* The background item which shows up on swipe */
protected LinearLayout backItem;
/* The list item menu container which is within the background item */
protected LinearLayout buttonContainer;
/* The foreground item */
protected GridLayout frontItem;
/* The basic delete button */
protected LinearLayout delete;
/* The basic edit button */
protected LinearLayout edit;
//tells if the edit button should be added
private boolean addEdit;
//tells if the delete button should be added
private boolean addDelete;
//list of custom buttons
protected List<CBBaseButton> customButtons;
public CBViewHolder(final View itemView, final Context context, final ViewGroup parent, final int itemResource, final boolean addEdit, final boolean addDelete) {
super(itemView);
initView(itemView, context, parent, itemResource, addEdit, addDelete);
}
@SuppressLint("ClickableViewAccessibility")
public void addFunctionalityOnView(final I listObject, final int position, final ICBActionNotifier<I> actionNotifier, final Context context) {
CBModeHelper modeHelper = CBModeHelper.getInstance();
CBListMode mode = modeHelper.getListMode();
switch (mode) {
case SWIPE:
this.frontItem.setBackgroundColor(Color.WHITE);
if (addEdit) {
this.edit.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (CBModeHelper.getInstance().isItemTouchCurrentItem(position)) {
actionNotifier.editAction(listObject);
return true;
}
return false;
}
});
}
if (addDelete) {
this.delete.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (CBModeHelper.getInstance().isItemTouchCurrentItem(position)) {
actionNotifier.deleteAction(listObject);
return true;
}
return false;
}
});
}
break;
case SELECT:
break;
case SORT:
//highlight item with different color if dragged
if (CBModeHelper.getInstance().getSelectedPosition() == position) {
this.frontItem.setBackgroundColor(modeHelper.getSelectColor());
} else {
this.frontItem.setBackgroundColor(Color.WHITE);
}
break;
case NULL:
break;
default:
break;
}
setUpPersonalView(listObject, position, actionNotifier, context);
}
/**
* Method for initializing the base view
* @param itemView the base view
* @param context the context
* @param parent the view group
* @param itemResource the layout resource of the front item
* @param addEdit the add button option
* @param addDelete the delete button option
*/
private void initView(final View itemView, final Context context, final ViewGroup parent, final int itemResource, final boolean addEdit, final boolean addDelete) {
this.addEdit = addEdit;
this.addDelete = addDelete;
this.customButtons = new ArrayList<>();
initCustomButtons();
this.frontItem = (GridLayout) itemView.findViewById(CBLayoutID.ITEM_FOREGROUND_ID);
this.buttonContainer = (LinearLayout) itemView.findViewById(CBLayoutID.BUTTON_CONTAINER_ID);
if (addEdit) {
this.buttonContainer.addView(new CBBaseButton().getButton(CBLayoutID.EDIT_BUTTON_ID, context, R.color.cb_edit_background_color, R.mipmap.edit_icon));
this.edit = (LinearLayout) itemView.findViewById(CBLayoutID.EDIT_BUTTON_ID);
}
if (addDelete) {
this.buttonContainer.addView(new CBBaseButton().getButton(CBLayoutID.DELETE_BUTTON_ID, context, R.color.cb_delete_background_color, R.mipmap.trash_icon));
this.delete = (LinearLayout) itemView.findViewById(CBLayoutID.DELETE_BUTTON_ID);
}
for (CBBaseButton customButton : this.customButtons) {
this.buttonContainer.addView(customButton.getCustomButton(context));
}
this.backItem = (LinearLayout) itemView.findViewById(CBLayoutID.ITEM_BACKGROUND_ID);
LayoutInflater inflater = LayoutInflater.from(context);
View personalView = inflater.inflate(itemResource, parent, false);
this.frontItem.addView(personalView);
initPersonalView(itemView, context);
itemView.setTag(this);
}
protected abstract void initCustomButtons();
/**
* Method for setting up the view functionality (values, listeners).
* @param listObject the current list element
* @param actionNotifier the listener for clicks
* @param context the context
*/
protected abstract void setUpPersonalView(final I listObject, final int position, final ICBActionNotifier<I> actionNotifier, final Context context);
/**
* Method for initializing the view.
* @param itemView the convert view
*/
protected abstract void initPersonalView(final View itemView, final Context context);
public LinearLayout getBackItem() {
return backItem;
}
public void setBackItem(final LinearLayout backItem) {
this.backItem = backItem;
}
public LinearLayout getButtonContainer() {
return buttonContainer;
}
public void setButtonContainer(final LinearLayout buttonContainer) {
this.buttonContainer = buttonContainer;
}
public GridLayout getFrontItem() {
return frontItem;
}
public void setFrontItem(final GridLayout frontItem) {
this.frontItem = frontItem;
}
public LinearLayout getDelete() {
return delete;
}
public void setDelete(final LinearLayout delete) {
this.delete = delete;
}
public LinearLayout getEdit() {
return edit;
}
public void setEdit(final LinearLayout edit) {
this.edit = edit;
}
}
|
3e1c608e4f698736dfbabf919003eee8692eca51 | 10,477 | java | Java | google-ads-examples/src/main/java/com/google/ads/googleads/examples/advancedoperations/AddGmailAd.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | 3 | 2020-12-20T18:56:52.000Z | 2021-07-29T12:12:02.000Z | google-ads-examples/src/main/java/com/google/ads/googleads/examples/advancedoperations/AddGmailAd.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | null | null | null | google-ads-examples/src/main/java/com/google/ads/googleads/examples/advancedoperations/AddGmailAd.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | null | null | null | 42.076305 | 98 | 0.708504 | 12,036 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.advancedoperations;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v5.common.GmailAdInfo;
import com.google.ads.googleads.v5.common.GmailTeaser;
import com.google.ads.googleads.v5.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v5.enums.MediaTypeEnum.MediaType;
import com.google.ads.googleads.v5.enums.MimeTypeEnum.MimeType;
import com.google.ads.googleads.v5.errors.GoogleAdsError;
import com.google.ads.googleads.v5.errors.GoogleAdsException;
import com.google.ads.googleads.v5.resources.Ad;
import com.google.ads.googleads.v5.resources.AdGroupAd;
import com.google.ads.googleads.v5.resources.MediaFile;
import com.google.ads.googleads.v5.resources.MediaImage;
import com.google.ads.googleads.v5.services.AdGroupAdOperation;
import com.google.ads.googleads.v5.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v5.services.MediaFileOperation;
import com.google.ads.googleads.v5.services.MediaFileServiceClient;
import com.google.ads.googleads.v5.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v5.services.MutateMediaFileResult;
import com.google.ads.googleads.v5.services.MutateMediaFilesResponse;
import com.google.ads.googleads.v5.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.protobuf.ByteString;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Adds a Gmail ad to a given ad group. The ad group's campaign needs to have an
* AdvertisingChannelType of DISPLAY and AdvertisingChannelSubType of DISPLAY_GMAIL_AD.
*/
public class AddGmailAd {
private static class AddGmailAdParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID)
private Long customerId;
@Parameter(names = ArgumentNames.AD_GROUP_ID)
private Long adGroupId;
}
public static void main(String[] args) throws IOException {
AddGmailAdParams params = new AddGmailAdParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddGmailAd().runExample(googleAdsClient, params.customerId, params.adGroupId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ad group ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
* @throws IOException if there is an error opening the image files.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId)
throws IOException {
Map<String, String> mediaFiles = addMediaFiles(googleAdsClient, customerId);
addGmailAd(googleAdsClient, customerId, adGroupId, mediaFiles);
}
/**
* Adds the image files.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
* @throws IOException if there is an error opening the image files.
* @return a hash map of the image file resource names.
*/
private Map<String, String> addMediaFiles(GoogleAdsClient googleAdsClient, long customerId)
throws IOException {
// Creates a bytes array from the logo image data.
byte[] logoImageData = ByteStreams.toByteArray(new URL("https://goo.gl/mtt54n").openStream());
// Creates the logo image.
MediaFile mediaFileLogo =
MediaFile.newBuilder()
.setType(MediaType.IMAGE)
.setImage(MediaImage.newBuilder().setData(ByteString.copyFrom(logoImageData)).build())
.setMimeType(MimeType.IMAGE_PNG)
.build();
// Creates the operation for the logo image.
MediaFileOperation mediaFileLogoOperation =
MediaFileOperation.newBuilder().setCreate(mediaFileLogo).build();
// Creates a bytes array from the marketing image data.
byte[] marketingImageData =
ByteStreams.toByteArray(new URL("https://goo.gl/3b9Wfh").openStream());
// Creates the marketing image.
MediaFile mediaFileMarketing =
MediaFile.newBuilder()
.setType(MediaType.IMAGE)
.setImage(
MediaImage.newBuilder().setData(ByteString.copyFrom(marketingImageData)).build())
.setMimeType(MimeType.IMAGE_JPEG)
.build();
// Creates the operation for the marketing image.
MediaFileOperation mediaFileMarketingOperation =
MediaFileOperation.newBuilder().setCreate(mediaFileMarketing).build();
// Creates the media file service client.
try (MediaFileServiceClient mediaFileServiceClient =
googleAdsClient.getLatestVersion().createMediaFileServiceClient()) {
// Adds the media files.
MutateMediaFilesResponse response =
mediaFileServiceClient.mutateMediaFiles(
Long.toString(customerId),
ImmutableList.of(mediaFileLogoOperation, mediaFileMarketingOperation));
// Displays the results.
for (MutateMediaFileResult result : response.getResultsList()) {
System.out.printf(
"Created media file with resource name '%s'.%n", result.getResourceName());
}
// Creates a map of the media files to return.
Map<String, String> mediaFiles = new HashMap<>();
mediaFiles.put("logoResourceName", response.getResults(0).getResourceName());
mediaFiles.put("marketingImageResourceName", response.getResults(1).getResourceName());
return mediaFiles;
}
}
/**
* Adds the gmail ad.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ad group ID.
* @param mediaFiles a map with keys of unique string identifiers and values of media file
* resource names.
* @throws GoogleAdsException if an API request failed with one or more service errors.
* @throws IOException if there is an error opening the image files.
*/
private void addGmailAd(
GoogleAdsClient googleAdsClient,
long customerId,
long adGroupId,
Map<String, String> mediaFiles) {
// Creates the Gmail ad info.
GmailAdInfo gmailAdInfo =
GmailAdInfo.newBuilder()
// Sets the teaser information.
.setTeaser(
GmailTeaser.newBuilder()
.setHeadline("Dream")
.setDescription("Create your own adventure")
.setBusinessName("Interplanetary Ships")
.setLogoImage(mediaFiles.get("logoResourceName"))
.build())
// Sets the marketing image and other information.
.setMarketingImage(mediaFiles.get("marketingImageResourceName"))
.setMarketingImageHeadline("Travel")
.setMarketingImageDescription("Take to the skies!")
.build();
// Creates the ad.
Ad ad =
Ad.newBuilder()
.setName("Gmail Ad #" + System.currentTimeMillis())
.addFinalUrls("http://www.example.com")
.setGmailAd(gmailAdInfo)
.build();
// Gets the ad group resource name.
String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);
// Creates the ad group ad.
AdGroupAd adGroupAd =
AdGroupAd.newBuilder()
.setAd(ad)
.setStatus(AdGroupAdStatus.PAUSED)
.setAdGroup(adGroupResourceName)
.build();
// Creates the operation.
AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();
// Creates the ad group ad service client.
try (AdGroupAdServiceClient adGroupAdServiceClient =
googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
MutateAdGroupAdsResponse response =
adGroupAdServiceClient.mutateAdGroupAds(
Long.toString(customerId), ImmutableList.of(operation));
// Displays the results.
System.out.printf(
"Created ad group ad with resource name '%s'.%n",
response.getResults(0).getResourceName());
}
}
}
|
3e1c60b5ba1c52b0a284e3b192bd10e274c66216 | 1,237 | java | Java | WeBankBlockchain-Data-Export-sdk/WeBankBlockchain-Data-Export-db/src/main/java/com/webank/blockchain/data/export/db/repository/RollbackInterface.java | laifagen4897/Data-Export | 186199575d9f52da12870c92278c6edb8e6d2622 | [
"Apache-2.0"
] | 29 | 2020-12-09T00:48:55.000Z | 2022-03-04T02:36:18.000Z | WeBankBlockchain-Data-Export-sdk/WeBankBlockchain-Data-Export-db/src/main/java/com/webank/blockchain/data/export/db/repository/RollbackInterface.java | laifagen4897/Data-Export | 186199575d9f52da12870c92278c6edb8e6d2622 | [
"Apache-2.0"
] | 8 | 2020-12-31T13:55:21.000Z | 2022-03-30T08:04:37.000Z | WeBankBlockchain-Data-Export-sdk/WeBankBlockchain-Data-Export-db/src/main/java/com/webank/blockchain/data/export/db/repository/RollbackInterface.java | laifagen4897/Data-Export | 186199575d9f52da12870c92278c6edb8e6d2622 | [
"Apache-2.0"
] | 11 | 2020-12-08T03:11:50.000Z | 2022-01-14T05:34:11.000Z | 31.717949 | 118 | 0.723525 | 12,037 | /**
* Copyright 2020 Webank.
*
* <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 com.webank.blockchain.data.export.db.repository;
/**
* RollbackOneInterface
*
* @Description: RollbackOneInterface
* @author maojiayu
* @data Dec 13, 2018 10:53:39 AM
*
*/
public interface RollbackInterface {
/*
* @see com.webank.blockchain.data.export.sys.db.repository.RollbackInterface#rollback(long)
*/
void rollback(long blockHeight);
/**
* rollback from startBlockHeight to endBlockHeight, including startBlockHeight, but not including endBlockHeight.
*
* @param startBlockHeight
* @param endBlockHeight
*/
void rollback(long startBlockHeight, long endBlockHeight);
}
|
3e1c60e3a0b5872f180116435bfa81b2008d0a56 | 1,389 | java | Java | app/src/main/java/com/davidbuzatu/schedly/model/Appointment.java | DavidBuzatu-Marian/Schedly | 158d29e198f3a7c1d028e3f733bb34f505ad0dcf | [
"Unlicense"
] | null | null | null | app/src/main/java/com/davidbuzatu/schedly/model/Appointment.java | DavidBuzatu-Marian/Schedly | 158d29e198f3a7c1d028e3f733bb34f505ad0dcf | [
"Unlicense"
] | null | null | null | app/src/main/java/com/davidbuzatu/schedly/model/Appointment.java | DavidBuzatu-Marian/Schedly | 158d29e198f3a7c1d028e3f733bb34f505ad0dcf | [
"Unlicense"
] | null | null | null | 21.045455 | 93 | 0.643629 | 12,038 | package com.davidbuzatu.schedly.model;
import com.google.gson.Gson;
import java.util.Properties;
public class Appointment{
private String mHour;
private String mName;
private String mPhoneNumber;
private String mDate;
private String mAppointmentType;
private Long mDateInMillis;
public Appointment(String hour, Gson gson, String json, String date, Long dateInMillis) {
mHour = hour;
Properties data = gson.fromJson(json, Properties.class);
mName = data.getProperty("Name");
mPhoneNumber = data.getProperty("PhoneNumber");
mAppointmentType = data.getProperty("AppointmentType");
mDate = date;
mDateInMillis = dateInMillis;
}
public String getmHour() {
return mHour;
}
public void setmHour(String mHour) {
this.mHour = mHour;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmPhoneNumber() {
return mPhoneNumber;
}
public void setmPhoneNumber(String mPhoneNumber) {
this.mPhoneNumber = mPhoneNumber;
}
public String getmDate() {
return mDate;
}
public Long getmDateInMillis() {
return mDateInMillis;
}
public String getmAppointmentType() {
return mAppointmentType;
}
}
|
3e1c60fc2d2f09f4e03013fbf59b396dee3cca11 | 546 | java | Java | mybatis_base_one2one_anno/src/test/src/One2OneTest.java | cxpcxpcxp/csdn_case_mybatis | c0977f0fd74d490a1aca1a005bb86cb907590cea | [
"Apache-2.0"
] | null | null | null | mybatis_base_one2one_anno/src/test/src/One2OneTest.java | cxpcxpcxp/csdn_case_mybatis | c0977f0fd74d490a1aca1a005bb86cb907590cea | [
"Apache-2.0"
] | 1 | 2022-03-31T21:51:18.000Z | 2022-03-31T21:51:18.000Z | mybatis_base_one2one_xml/src/test/src/One2OneTest.java | cxpcxpcxp/csdn_case_mybatis | c0977f0fd74d490a1aca1a005bb86cb907590cea | [
"Apache-2.0"
] | null | null | null | 27.3 | 65 | 0.695971 | 12,039 | import com.one2one.dao.IUserDAO;
import com.one2one.domain.Users;
import com.one2one.utils.MySqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class One2OneTest {
@Test
public void test(){
SqlSession sqlSession = MySqlSessionUtil.getSqlSession();
IUserDAO mapper = sqlSession.getMapper(IUserDAO.class);
List<Users> byOne2One = mapper.findByOne2One();
for (Users users : byOne2One) {
System.out.println(users);
}
}
}
|
3e1c614ab3911dc1d39e37b260e42c94d29d1ce2 | 2,278 | java | Java | gmall-pms/src/main/java/com/atguigu/gmall/pms/controller/BrandController.java | tongw555/gmall-191125 | aa1b5689334af4373b76f40aefbe26602ae19215 | [
"Apache-2.0"
] | null | null | null | gmall-pms/src/main/java/com/atguigu/gmall/pms/controller/BrandController.java | tongw555/gmall-191125 | aa1b5689334af4373b76f40aefbe26602ae19215 | [
"Apache-2.0"
] | 3 | 2021-03-19T20:22:53.000Z | 2021-09-20T20:58:47.000Z | gmall-pms/src/main/java/com/atguigu/gmall/pms/controller/BrandController.java | tongw555/gmall-191125 | aa1b5689334af4373b76f40aefbe26602ae19215 | [
"Apache-2.0"
] | null | null | null | 24.021053 | 79 | 0.708151 | 12,040 | package com.atguigu.gmall.pms.controller;
import java.util.List;
import com.atguigu.gamll.pms.entity.BrandEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.gmall.pms.service.BrandService;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.bean.PageParamVo;
/**
* 品牌
*
* @author tongwei
* @email ychag@example.com
* @date 2020-05-17 16:41:32
*/
@Api(tags = "品牌 管理")
@RestController
@RequestMapping("pms/brand")
public class BrandController {
@Autowired
private BrandService brandService;
/**
* 列表
*/
@GetMapping
@ApiOperation("分页查询")
public ResponseVo<PageResultVo> queryBrandByPage(PageParamVo paramVo){
PageResultVo pageResultVo = brandService.queryPage(paramVo);
return ResponseVo.ok(pageResultVo);
}
/**
* 信息
*/
@GetMapping("{id}")
@ApiOperation("详情查询")
public ResponseVo<BrandEntity> queryBrandById(@PathVariable("id") Long id){
BrandEntity brand = brandService.getById(id);
return ResponseVo.ok(brand);
}
/**
* 保存
*/
@PostMapping
@ApiOperation("保存")
public ResponseVo<Object> save(@RequestBody BrandEntity brand){
brandService.save(brand);
return ResponseVo.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@ApiOperation("修改")
public ResponseVo update(@RequestBody BrandEntity brand){
brandService.updateById(brand);
return ResponseVo.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@ApiOperation("删除")
public ResponseVo delete(@RequestBody List<Long> ids){
brandService.removeByIds(ids);
return ResponseVo.ok();
}
}
|
3e1c62d149391df3c8e398f02500a24da1ee3401 | 2,927 | java | Java | app/src/main/java/cn/edu/scu/notifyme/LocaleUtils.java | LiRunZhe/NotifyMe | 9332f92b6ce0c995ffa5829be9fa78980b6e2b8f | [
"MIT"
] | null | null | null | app/src/main/java/cn/edu/scu/notifyme/LocaleUtils.java | LiRunZhe/NotifyMe | 9332f92b6ce0c995ffa5829be9fa78980b6e2b8f | [
"MIT"
] | null | null | null | app/src/main/java/cn/edu/scu/notifyme/LocaleUtils.java | LiRunZhe/NotifyMe | 9332f92b6ce0c995ffa5829be9fa78980b6e2b8f | [
"MIT"
] | 3 | 2019-03-03T09:35:35.000Z | 2019-03-05T01:08:53.000Z | 32.522222 | 103 | 0.676802 | 12,041 | package cn.edu.scu.notifyme;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import com.blankj.utilcode.util.SPUtils;
import java.util.Locale;
public class LocaleUtils {
public static final String EN = "en";
public static final String ZH_CN = "zh-CN";
public static Context getBaseContext() {
return baseContext;
}
public static void setBaseContext(Context baseContext) {
LocaleUtils.baseContext = baseContext;
}
private static Context baseContext;
public static String getLocale() {
return SPUtils.getInstance().getString("locale", ZH_CN);
}
public static Context setLocale(Context context, String locale) {
Locale newLocale;
if (locale.equals("system")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
newLocale = Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
newLocale = Resources.getSystem().getConfiguration().locale;
}
} else {
newLocale = new Locale(locale);
}
Locale.setDefault(newLocale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, newLocale);
} else {
return updateResourcesLegacy(context, newLocale);
}
}
public static Context onAttach(Context context) {
return setLocale(context, getLocale());
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, Locale locale) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale);
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
public static String getString(int id) {
Configuration configuration = new Configuration(baseContext.getResources().getConfiguration());
configuration.setLocale(new Locale(getLocale()));
return baseContext.createConfigurationContext(configuration).getResources().getString(id);
}
public static void store(String s) {
SPUtils.getInstance().put("locale", s);
}
}
|
3e1c62d661596555152ee2d887e080e5c0f87a5d | 4,740 | java | Java | archetype/engine-v2/src/main/java/io/helidon/build/archetype/engine/v2/prompter/EnumPrompt.java | batsatt/helidon-build-tools | 769076cf3ca9e7b23767a8c2f8dd25e802fa9a74 | [
"Apache-2.0"
] | null | null | null | archetype/engine-v2/src/main/java/io/helidon/build/archetype/engine/v2/prompter/EnumPrompt.java | batsatt/helidon-build-tools | 769076cf3ca9e7b23767a8c2f8dd25e802fa9a74 | [
"Apache-2.0"
] | null | null | null | archetype/engine-v2/src/main/java/io/helidon/build/archetype/engine/v2/prompter/EnumPrompt.java | batsatt/helidon-build-tools | 769076cf3ca9e7b23767a8c2f8dd25e802fa9a74 | [
"Apache-2.0"
] | 1 | 2019-12-17T13:51:34.000Z | 2019-12-17T13:51:34.000Z | 31.184211 | 120 | 0.560759 | 12,042 | /*
* Copyright (c) 2021 Oracle 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 io.helidon.build.archetype.engine.v2.prompter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import io.helidon.build.archetype.engine.v2.interpreter.ContextEnumAST;
import io.helidon.build.archetype.engine.v2.interpreter.ContextNodeAST;
import io.helidon.build.archetype.engine.v2.interpreter.InputEnumAST;
import io.helidon.build.archetype.engine.v2.interpreter.OptionAST;
import io.helidon.build.archetype.engine.v2.interpreter.UserInputAST;
/**
* Prompt of the one value from the enum.
*/
public class EnumPrompt extends Prompt<String> {
private final List<Option> options = new ArrayList<>();
private EnumPrompt(
String stepLabel,
String stepHelp,
String help,
String label,
String name,
String def,
String prompt,
List<Option> options,
boolean optional,
boolean canBeGenerated
) {
super(stepLabel, stepHelp, help, label, name, def, prompt, optional, canBeGenerated);
if (options != null) {
this.options.addAll(options);
}
}
/**
* Get the options.
*
* @return options
*/
public List<Option> options() {
return options;
}
/**
* Create a new builder.
*
* @return a new builder
*/
public static EnumPrompt.Builder builder() {
return new EnumPrompt.Builder();
}
@Override
public String accept(Prompter prompter) {
return prompter.prompt(this);
}
@Override
public ContextNodeAST acceptAndConvert(Prompter prompter, String path) {
String value = prompter.prompt(this);
ContextEnumAST result = new ContextEnumAST(path);
result.value(value);
return result;
}
public static class Builder extends Prompt.Builder<EnumPrompt, EnumPrompt.Builder> {
private List<Option> options = new ArrayList<>();
/**
* Set the options.
*
* @param options list of options
* @return Builder
*/
public EnumPrompt.Builder options(List<Option> options) {
if (options != null) {
this.options = options;
}
return this;
}
@Override
public EnumPrompt.Builder instance() {
return this;
}
@Override
public EnumPrompt.Builder userInputAST(UserInputAST userInputAST) {
if (userInputAST.children().isEmpty()) {
throw new IllegalArgumentException("UserInputAST must contain a child note");
}
if (userInputAST.children().get(0) instanceof InputEnumAST) {
InputEnumAST inputEnumAST = (InputEnumAST) userInputAST.children().get(0);
initFields(userInputAST);
options.addAll(
inputEnumAST.children().stream()
.filter(ch -> ch instanceof OptionAST)
.map(ch -> (OptionAST) ch)
.map(o -> new Option(o.label(), o.value(), o.help()))
.collect(Collectors.toList())
);
return this;
}
throw new IllegalArgumentException(
String.format(
"Incorrect type of the child node in the UserInputAST instance. Must be - %s. Actual - %s.",
EnumPrompt.class.getName(),
userInputAST.children().get(0).getClass().getName()
)
);
}
@Override
public EnumPrompt build() {
return new EnumPrompt(
stepLabel(),
stepHelp(),
help(),
label(),
name(),
defaultValue(),
prompt(),
options,
optional(),
canBeGenerated()
);
}
}
}
|
3e1c6460b8b56db1a5f207eec9317e456df14f54 | 19,011 | java | Java | multiple-languages/java/ros-cdk-cen/src/main/java/com/aliyun/ros/cdk/cen/CenVbrHealthCheck.java | aliyun/Resource-Orchestration-Service-Cloud-Development-K | 2b81e135002ed81cb72f7d07be7ff497ea39e2e1 | [
"Apache-2.0"
] | 15 | 2020-11-10T02:00:28.000Z | 2022-02-07T19:28:10.000Z | multiple-languages/java/ros-cdk-cen/src/main/java/com/aliyun/ros/cdk/cen/CenVbrHealthCheck.java | aliyun/Resource-Orchestration-Service-Cloud-Development-K | 2b81e135002ed81cb72f7d07be7ff497ea39e2e1 | [
"Apache-2.0"
] | 23 | 2021-02-02T04:37:02.000Z | 2022-03-31T06:41:06.000Z | multiple-languages/java/ros-cdk-cen/src/main/java/com/aliyun/ros/cdk/cen/CenVbrHealthCheck.java | aliyun/Resource-Orchestration-Service-Cloud-Development-K | 2b81e135002ed81cb72f7d07be7ff497ea39e2e1 | [
"Apache-2.0"
] | 4 | 2021-01-13T05:48:43.000Z | 2022-03-15T11:26:48.000Z | 53.855524 | 519 | 0.679028 | 12,043 | package com.aliyun.ros.cdk.cen;
/**
* A ROS resource type: `ALIYUN::CEN::CenVbrHealthCheck`.
*/
@javax.annotation.Generated(value = "jsii-pacmak/1.49.0 (build e322d87)", date = "2021-12-21T15:12:56.965Z")
@software.amazon.jsii.Jsii(module = com.aliyun.ros.cdk.cen.$Module.class, fqn = "@alicloud/ros-cdk-cen.CenVbrHealthCheck")
public class CenVbrHealthCheck extends com.aliyun.ros.cdk.core.Resource {
protected CenVbrHealthCheck(final software.amazon.jsii.JsiiObjectRef objRef) {
super(objRef);
}
protected CenVbrHealthCheck(final software.amazon.jsii.JsiiObject.InitializationMode initializationMode) {
super(initializationMode);
}
/**
* Create a new `ALIYUN::CEN::CenVbrHealthCheck`.
* <p>
* Param scope - scope in which this resource is defined
* Param id - scoped id of the resource
* Param props - resource properties
* <p>
* @param scope This parameter is required.
* @param id This parameter is required.
* @param props This parameter is required.
* @param enableResourcePropertyConstraint
*/
public CenVbrHealthCheck(final @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.Construct scope, final @org.jetbrains.annotations.NotNull java.lang.String id, final @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.cen.CenVbrHealthCheckProps props, final @org.jetbrains.annotations.Nullable java.lang.Boolean enableResourcePropertyConstraint) {
super(software.amazon.jsii.JsiiObject.InitializationMode.JSII);
software.amazon.jsii.JsiiEngine.getInstance().createNewObject(this, new Object[] { java.util.Objects.requireNonNull(scope, "scope is required"), java.util.Objects.requireNonNull(id, "id is required"), java.util.Objects.requireNonNull(props, "props is required"), enableResourcePropertyConstraint });
}
/**
* Create a new `ALIYUN::CEN::CenVbrHealthCheck`.
* <p>
* Param scope - scope in which this resource is defined
* Param id - scoped id of the resource
* Param props - resource properties
* <p>
* @param scope This parameter is required.
* @param id This parameter is required.
* @param props This parameter is required.
*/
public CenVbrHealthCheck(final @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.Construct scope, final @org.jetbrains.annotations.NotNull java.lang.String id, final @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.cen.CenVbrHealthCheckProps props) {
super(software.amazon.jsii.JsiiObject.InitializationMode.JSII);
software.amazon.jsii.JsiiEngine.getInstance().createNewObject(this, new Object[] { java.util.Objects.requireNonNull(scope, "scope is required"), java.util.Objects.requireNonNull(id, "id is required"), java.util.Objects.requireNonNull(props, "props is required") });
}
/**
* Attribute CenId: The ID of the CEN instance.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrCenId() {
return software.amazon.jsii.Kernel.get(this, "attrCenId", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* Attribute HealthCheckInterval: Specifies the time interval at which probe packets are sent during the health check.
* <p>
* Default value: 2. Valid values: 2 to 3. Unit: second.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrHealthCheckInterval() {
return software.amazon.jsii.Kernel.get(this, "attrHealthCheckInterval", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* Attribute HealthCheckSourceIp: You can use either of the following methods to specify the source IP address of the health check.
* <p>
* Automatic IP Address: The system automatically assigns an IP address within the CIDR block 100.96.0.0/16 (recommended). Custom IP Address: You can specify a source IP address that is available within the CIDR block 10.0.0.0/8, 192.168.0.0/16, or 172.16.0.0/12. The specified source IP address must not overlap with the IP addresses of the Alibaba Cloud-facing and client-facing interfaces on the VBR instance, or the IP addresses of the instances with which the VBR instance needs to communicate in the CEN.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrHealthCheckSourceIp() {
return software.amazon.jsii.Kernel.get(this, "attrHealthCheckSourceIp", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* Attribute HealthCheckTargetIp: Specifies the destination IP address of the health check.
* <p>
* The destination IP address is the IP address of the client-facing interface on the VBR instance.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrHealthCheckTargetIp() {
return software.amazon.jsii.Kernel.get(this, "attrHealthCheckTargetIp", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* Attribute HealthyThreshold: Specifies the number of probe packets to be sent during the health check.
* <p>
* Default value: 8. Valid values: 3 to 8. Unit: packet.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrHealthyThreshold() {
return software.amazon.jsii.Kernel.get(this, "attrHealthyThreshold", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* Attribute VbrInstanceId: The ID of the VBR instance.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrVbrInstanceId() {
return software.amazon.jsii.Kernel.get(this, "attrVbrInstanceId", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* Attribute VbrInstanceOwnerId: The User ID (UID) of the account to which the VBR instance belongs.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrVbrInstanceOwnerId() {
return software.amazon.jsii.Kernel.get(this, "attrVbrInstanceOwnerId", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* Attribute VbrInstanceRegionId: The ID of the region where the VBR instance is deployed.
* <p>
* You can call the DescribeRegionsoperation to query region IDs.
*/
public @org.jetbrains.annotations.NotNull com.aliyun.ros.cdk.core.IResolvable getAttrVbrInstanceRegionId() {
return software.amazon.jsii.Kernel.get(this, "attrVbrInstanceRegionId", software.amazon.jsii.NativeType.forClass(com.aliyun.ros.cdk.core.IResolvable.class));
}
/**
* A fluent builder for {@link com.aliyun.ros.cdk.cen.CenVbrHealthCheck}.
*/
public static final class Builder implements software.amazon.jsii.Builder<com.aliyun.ros.cdk.cen.CenVbrHealthCheck> {
/**
* @return a new instance of {@link Builder}.
* @param scope This parameter is required.
* @param id This parameter is required.
* @param enableResourcePropertyConstraint
*/
public static Builder create(final com.aliyun.ros.cdk.core.Construct scope, final java.lang.String id, final java.lang.Boolean enableResourcePropertyConstraint) {
return new Builder(scope, id, enableResourcePropertyConstraint);
}
/**
* @return a new instance of {@link Builder}.
* @param scope This parameter is required.
* @param id This parameter is required.
*/
public static Builder create(final com.aliyun.ros.cdk.core.Construct scope, final java.lang.String id) {
return new Builder(scope, id, null);
}
private final com.aliyun.ros.cdk.core.Construct scope;
private final java.lang.String id;
private final java.lang.Boolean enableResourcePropertyConstraint;
private final com.aliyun.ros.cdk.cen.CenVbrHealthCheckProps.Builder props;
private Builder(final com.aliyun.ros.cdk.core.Construct scope, final java.lang.String id, final java.lang.Boolean enableResourcePropertyConstraint) {
this.scope = scope;
this.id = id;
this.enableResourcePropertyConstraint = enableResourcePropertyConstraint;
this.props = new com.aliyun.ros.cdk.cen.CenVbrHealthCheckProps.Builder();
}
/**
* Property cenId: The ID of the CEN instance.
* <p>
* @return {@code this}
* @param cenId Property cenId: The ID of the CEN instance. This parameter is required.
*/
public Builder cenId(final java.lang.String cenId) {
this.props.cenId(cenId);
return this;
}
/**
* Property cenId: The ID of the CEN instance.
* <p>
* @return {@code this}
* @param cenId Property cenId: The ID of the CEN instance. This parameter is required.
*/
public Builder cenId(final com.aliyun.ros.cdk.core.IResolvable cenId) {
this.props.cenId(cenId);
return this;
}
/**
* Property healthCheckTargetIp: Specifies the destination IP address of the health check.
* <p>
* The destination IP address is the IP address of the client-facing interface on the VBR instance.
* <p>
* @return {@code this}
* @param healthCheckTargetIp Property healthCheckTargetIp: Specifies the destination IP address of the health check. This parameter is required.
*/
public Builder healthCheckTargetIp(final java.lang.String healthCheckTargetIp) {
this.props.healthCheckTargetIp(healthCheckTargetIp);
return this;
}
/**
* Property healthCheckTargetIp: Specifies the destination IP address of the health check.
* <p>
* The destination IP address is the IP address of the client-facing interface on the VBR instance.
* <p>
* @return {@code this}
* @param healthCheckTargetIp Property healthCheckTargetIp: Specifies the destination IP address of the health check. This parameter is required.
*/
public Builder healthCheckTargetIp(final com.aliyun.ros.cdk.core.IResolvable healthCheckTargetIp) {
this.props.healthCheckTargetIp(healthCheckTargetIp);
return this;
}
/**
* Property vbrInstanceId: The ID of the VBR instance.
* <p>
* @return {@code this}
* @param vbrInstanceId Property vbrInstanceId: The ID of the VBR instance. This parameter is required.
*/
public Builder vbrInstanceId(final java.lang.String vbrInstanceId) {
this.props.vbrInstanceId(vbrInstanceId);
return this;
}
/**
* Property vbrInstanceId: The ID of the VBR instance.
* <p>
* @return {@code this}
* @param vbrInstanceId Property vbrInstanceId: The ID of the VBR instance. This parameter is required.
*/
public Builder vbrInstanceId(final com.aliyun.ros.cdk.core.IResolvable vbrInstanceId) {
this.props.vbrInstanceId(vbrInstanceId);
return this;
}
/**
* Property vbrInstanceRegionId: The ID of the region where the VBR instance is deployed.
* <p>
* You can call the DescribeRegionsoperation to query region IDs.
* <p>
* @return {@code this}
* @param vbrInstanceRegionId Property vbrInstanceRegionId: The ID of the region where the VBR instance is deployed. This parameter is required.
*/
public Builder vbrInstanceRegionId(final java.lang.String vbrInstanceRegionId) {
this.props.vbrInstanceRegionId(vbrInstanceRegionId);
return this;
}
/**
* Property vbrInstanceRegionId: The ID of the region where the VBR instance is deployed.
* <p>
* You can call the DescribeRegionsoperation to query region IDs.
* <p>
* @return {@code this}
* @param vbrInstanceRegionId Property vbrInstanceRegionId: The ID of the region where the VBR instance is deployed. This parameter is required.
*/
public Builder vbrInstanceRegionId(final com.aliyun.ros.cdk.core.IResolvable vbrInstanceRegionId) {
this.props.vbrInstanceRegionId(vbrInstanceRegionId);
return this;
}
/**
* Property healthCheckInterval: Specifies the time interval at which probe packets are sent during the health check.
* <p>
* Default value: 2. Valid values: 2 to 3. Unit: second.
* <p>
* @return {@code this}
* @param healthCheckInterval Property healthCheckInterval: Specifies the time interval at which probe packets are sent during the health check. This parameter is required.
*/
public Builder healthCheckInterval(final java.lang.Number healthCheckInterval) {
this.props.healthCheckInterval(healthCheckInterval);
return this;
}
/**
* Property healthCheckInterval: Specifies the time interval at which probe packets are sent during the health check.
* <p>
* Default value: 2. Valid values: 2 to 3. Unit: second.
* <p>
* @return {@code this}
* @param healthCheckInterval Property healthCheckInterval: Specifies the time interval at which probe packets are sent during the health check. This parameter is required.
*/
public Builder healthCheckInterval(final com.aliyun.ros.cdk.core.IResolvable healthCheckInterval) {
this.props.healthCheckInterval(healthCheckInterval);
return this;
}
/**
* Property healthCheckSourceIp: You can use either of the following methods to specify the source IP address of the health check.
* <p>
* Automatic IP Address: The system automatically assigns an IP address within the CIDR block 100.96.0.0/16 (recommended). Custom IP Address: You can specify a source IP address that is available within the CIDR block 10.0.0.0/8, 192.168.0.0/16, or 172.16.0.0/12. The specified source IP address must not overlap with the IP addresses of the Alibaba Cloud-facing and client-facing interfaces on the VBR instance, or the IP addresses of the instances with which the VBR instance needs to communicate in the CEN.
* <p>
* @return {@code this}
* @param healthCheckSourceIp Property healthCheckSourceIp: You can use either of the following methods to specify the source IP address of the health check. This parameter is required.
*/
public Builder healthCheckSourceIp(final java.lang.String healthCheckSourceIp) {
this.props.healthCheckSourceIp(healthCheckSourceIp);
return this;
}
/**
* Property healthCheckSourceIp: You can use either of the following methods to specify the source IP address of the health check.
* <p>
* Automatic IP Address: The system automatically assigns an IP address within the CIDR block 100.96.0.0/16 (recommended). Custom IP Address: You can specify a source IP address that is available within the CIDR block 10.0.0.0/8, 192.168.0.0/16, or 172.16.0.0/12. The specified source IP address must not overlap with the IP addresses of the Alibaba Cloud-facing and client-facing interfaces on the VBR instance, or the IP addresses of the instances with which the VBR instance needs to communicate in the CEN.
* <p>
* @return {@code this}
* @param healthCheckSourceIp Property healthCheckSourceIp: You can use either of the following methods to specify the source IP address of the health check. This parameter is required.
*/
public Builder healthCheckSourceIp(final com.aliyun.ros.cdk.core.IResolvable healthCheckSourceIp) {
this.props.healthCheckSourceIp(healthCheckSourceIp);
return this;
}
/**
* Property healthyThreshold: Specifies the number of probe packets to be sent during the health check.
* <p>
* Default value: 8. Valid values: 3 to 8. Unit: packet.
* <p>
* @return {@code this}
* @param healthyThreshold Property healthyThreshold: Specifies the number of probe packets to be sent during the health check. This parameter is required.
*/
public Builder healthyThreshold(final java.lang.Number healthyThreshold) {
this.props.healthyThreshold(healthyThreshold);
return this;
}
/**
* Property healthyThreshold: Specifies the number of probe packets to be sent during the health check.
* <p>
* Default value: 8. Valid values: 3 to 8. Unit: packet.
* <p>
* @return {@code this}
* @param healthyThreshold Property healthyThreshold: Specifies the number of probe packets to be sent during the health check. This parameter is required.
*/
public Builder healthyThreshold(final com.aliyun.ros.cdk.core.IResolvable healthyThreshold) {
this.props.healthyThreshold(healthyThreshold);
return this;
}
/**
* Property vbrInstanceOwnerId: The User ID (UID) of the account to which the VBR instance belongs.
* <p>
* @return {@code this}
* @param vbrInstanceOwnerId Property vbrInstanceOwnerId: The User ID (UID) of the account to which the VBR instance belongs. This parameter is required.
*/
public Builder vbrInstanceOwnerId(final java.lang.Number vbrInstanceOwnerId) {
this.props.vbrInstanceOwnerId(vbrInstanceOwnerId);
return this;
}
/**
* Property vbrInstanceOwnerId: The User ID (UID) of the account to which the VBR instance belongs.
* <p>
* @return {@code this}
* @param vbrInstanceOwnerId Property vbrInstanceOwnerId: The User ID (UID) of the account to which the VBR instance belongs. This parameter is required.
*/
public Builder vbrInstanceOwnerId(final com.aliyun.ros.cdk.core.IResolvable vbrInstanceOwnerId) {
this.props.vbrInstanceOwnerId(vbrInstanceOwnerId);
return this;
}
/**
* @returns a newly built instance of {@link com.aliyun.ros.cdk.cen.CenVbrHealthCheck}.
*/
@Override
public com.aliyun.ros.cdk.cen.CenVbrHealthCheck build() {
return new com.aliyun.ros.cdk.cen.CenVbrHealthCheck(
this.scope,
this.id,
this.props.build(),
this.enableResourcePropertyConstraint
);
}
}
}
|
3e1c678e822366bdced3e81f53737c838d220b14 | 719 | java | Java | src/main/java/org/thread/executor/NamedThreadPool.java | haiyang1985/thread | 54efdbc6d2fac4d8aa89daecbb0ae13720dc2dd9 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/thread/executor/NamedThreadPool.java | haiyang1985/thread | 54efdbc6d2fac4d8aa89daecbb0ae13720dc2dd9 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/thread/executor/NamedThreadPool.java | haiyang1985/thread | 54efdbc6d2fac4d8aa89daecbb0ae13720dc2dd9 | [
"Apache-2.0"
] | null | null | null | 26.62963 | 88 | 0.723227 | 12,044 | package org.thread.executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author hy_gu on 2019/1/18
**/
public class NamedThreadPool implements ThreadFactory {
private static final AtomicInteger mThreadNum = new AtomicInteger(1);
private final ThreadGroup mGroup;
public NamedThreadPool() {
SecurityManager s = System.getSecurityManager();
mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
}
@Override
public Thread newThread(Runnable r) {
String name = "ghy-" + mThreadNum.getAndIncrement();
Thread thread = new Thread(mGroup, r, name, 0);
thread.setDaemon(true);
return thread;
}
}
|
3e1c67aeea87acfb513ec7432122e57ef22db1cf | 2,007 | java | Java | api/src/main/java/org/ocpsoft/rewrite/util/Instances.java | mdfst13/rewrite | d79194c3eef303e7cd413a7e7803ce073f8df142 | [
"Apache-2.0"
] | null | null | null | api/src/main/java/org/ocpsoft/rewrite/util/Instances.java | mdfst13/rewrite | d79194c3eef303e7cd413a7e7803ce073f8df142 | [
"Apache-2.0"
] | null | null | null | api/src/main/java/org/ocpsoft/rewrite/util/Instances.java | mdfst13/rewrite | d79194c3eef303e7cd413a7e7803ce073f8df142 | [
"Apache-2.0"
] | 1 | 2020-07-14T04:49:56.000Z | 2020-07-14T04:49:56.000Z | 31.546875 | 91 | 0.7053 | 12,045 | /*
* Copyright 2013 <a href="mailto:efpyi@example.com">Lincoln Baxter, III</a>
*
* 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.ocpsoft.rewrite.util;
import java.util.Collections;
import java.util.List;
import org.ocpsoft.common.pattern.WeightedComparator;
import org.ocpsoft.common.services.ServiceLoader;
import org.ocpsoft.common.util.Iterators;
import org.ocpsoft.logging.Logger;
import org.ocpsoft.rewrite.spi.InstanceProvider;
/**
* Utility class for looking up instances of Java types. See also {@link InstanceProvider}.
*
* @author <a href="mailto:efpyi@example.com">Lincoln Baxter, III</a>
*/
public final class Instances
{
private static Logger log = Logger.getLogger(Instances.class);
private static List<InstanceProvider> instanceProviders;
private Instances()
{}
/**
* Lookup an instance of the given {@link Class} type.
*/
@SuppressWarnings("unchecked")
public static <T> T lookup(Class<T> type)
{
if (instanceProviders == null) {
instanceProviders = Iterators.asList(ServiceLoader.load(InstanceProvider.class));
Collections.sort(instanceProviders, new WeightedComparator());
ServiceLogger.logLoadedServices(log, InstanceProvider.class, instanceProviders);
}
T result = null;
for (InstanceProvider p : instanceProviders) {
result = (T) p.getInstance(type);
if (result != null)
{
break;
}
}
return result;
}
}
|
3e1c68445d08d4091f7ca33a457ff88566857721 | 3,256 | java | Java | httpclient5/src/main/java/org/apache/hc/client5/http/async/HttpAsyncClient.java | h0nIg/httpcomponents-client | 6559b60342233e75ccf76c7bfe490ea23be0f767 | [
"Apache-2.0"
] | 756 | 2017-05-20T16:47:14.000Z | 2022-03-31T07:01:22.000Z | httpclient5/src/main/java/org/apache/hc/client5/http/async/HttpAsyncClient.java | h0nIg/httpcomponents-client | 6559b60342233e75ccf76c7bfe490ea23be0f767 | [
"Apache-2.0"
] | 170 | 2017-05-17T15:09:45.000Z | 2022-03-30T13:55:41.000Z | httpclient5/src/main/java/org/apache/hc/client5/http/async/HttpAsyncClient.java | h0nIg/httpcomponents-client | 6559b60342233e75ccf76c7bfe490ea23be0f767 | [
"Apache-2.0"
] | 628 | 2017-05-17T13:13:22.000Z | 2022-03-30T03:37:04.000Z | 43.413333 | 92 | 0.70731 | 12,047 | /*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.http.async;
import java.util.concurrent.Future;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
import org.apache.hc.core5.http.nio.AsyncRequestProducer;
import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
import org.apache.hc.core5.http.nio.HandlerFactory;
import org.apache.hc.core5.http.protocol.HttpContext;
/**
* This interface represents only the most basic contract for HTTP request
* execution. It imposes no restrictions or particular details on the request
* execution process and leaves the specifics of state management,
* authentication and redirect handling up to individual implementations.
*
* @since 4.0
*/
public interface HttpAsyncClient {
/**
* Initiates asynchronous HTTP request execution using the given context.
* <p>
* The request producer passed to this method will be used to generate
* a request message and stream out its content without buffering it
* in memory. The response consumer passed to this method will be used
* to process a response message without buffering its content in memory.
* <p>
* Please note it may be unsafe to interact with the context instance
* while the request is still being executed.
*
* @param <T> the result type of request execution.
* @param requestProducer request producer callback.
* @param responseConsumer response consumer callback.
* @param pushHandlerFactory the push handler factory. Optional and may be {@code null}.
* @param context HTTP context. Optional and may be {@code null}.
* @param callback future callback. Optional and may be {@code null}.
* @return future representing pending completion of the operation.
*/
<T> Future<T> execute(
AsyncRequestProducer requestProducer,
AsyncResponseConsumer<T> responseConsumer,
HandlerFactory<AsyncPushConsumer> pushHandlerFactory,
HttpContext context,
FutureCallback<T> callback);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.