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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e169a08fb750f30dc7a789db00c6ffffb9923ee | 500 | java | Java | gmall-ums/src/main/java/com/atguigu/gmall/ums/service/UserAddressService.java | ding1120/guli-mall | 656dfb938c24629e6b425a24ca579b2ff2ad67e1 | [
"Apache-2.0"
] | null | null | null | gmall-ums/src/main/java/com/atguigu/gmall/ums/service/UserAddressService.java | ding1120/guli-mall | 656dfb938c24629e6b425a24ca579b2ff2ad67e1 | [
"Apache-2.0"
] | null | null | null | gmall-ums/src/main/java/com/atguigu/gmall/ums/service/UserAddressService.java | ding1120/guli-mall | 656dfb938c24629e6b425a24ca579b2ff2ad67e1 | [
"Apache-2.0"
] | null | null | null | 22.681818 | 73 | 0.779559 | 9,638 | package com.atguigu.gmall.ums.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.ums.entity.UserAddressEntity;
import java.util.Map;
/**
* 收货地址表
*
* @author ding
* @email envkt@example.com
* @date 2020-12-15 17:50:15
*/
public interface UserAddressService extends IService<UserAddressEntity> {
PageResultVo queryPage(PageParamVo paramVo);
}
|
3e169b5142fdc1d2f26d90866a5b8a9515dfc893 | 6,534 | java | Java | testsAT/src/test/java/com/stratio/cassandra/lucene/testsAT/story/ComplexKeyIndexHandlingIT.java | shaurya10000/cassandra-lucene-index | a94a4d9af6c25d40e1108729974c35c27c54441c | [
"Apache-2.0"
] | 652 | 2015-06-08T22:52:01.000Z | 2022-02-20T14:20:55.000Z | testsAT/src/test/java/com/stratio/cassandra/lucene/testsAT/story/ComplexKeyIndexHandlingIT.java | shaurya10000/cassandra-lucene-index | a94a4d9af6c25d40e1108729974c35c27c54441c | [
"Apache-2.0"
] | 314 | 2015-06-09T13:01:14.000Z | 2019-12-11T15:45:17.000Z | testsAT/src/test/java/com/stratio/cassandra/lucene/testsAT/story/ComplexKeyIndexHandlingIT.java | shaurya10000/cassandra-lucene-index | a94a4d9af6c25d40e1108729974c35c27c54441c | [
"Apache-2.0"
] | 177 | 2015-06-12T13:30:41.000Z | 2022-03-18T00:24:22.000Z | 32.346535 | 75 | 0.40955 | 9,639 | /*
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.cassandra.lucene.testsAT.story;
import com.stratio.cassandra.lucene.testsAT.BaseIT;
import com.stratio.cassandra.lucene.testsAT.util.CassandraUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static com.stratio.cassandra.lucene.builder.Builder.wildcard;
import static com.stratio.cassandra.lucene.testsAT.story.DataHelper.*;
@RunWith(JUnit4.class)
public class ComplexKeyIndexHandlingIT extends BaseIT {
private CassandraUtils utils;
@Before
public void before() {
utils = CassandraUtils.builder("complex_key_index_handling")
.withPartitionKey("integer_1", "ascii_1")
.withClusteringKey("double_1")
.withColumn("ascii_1", "ascii")
.withColumn("bigint_1", "bigint")
.withColumn("blob_1", "blob")
.withColumn("boolean_1", "boolean")
.withColumn("decimal_1", "decimal")
.withColumn("date_1", "timestamp")
.withColumn("double_1", "double")
.withColumn("float_1", "float")
.withColumn("integer_1", "int")
.withColumn("inet_1", "inet")
.withColumn("text_1", "text")
.withColumn("varchar_1", "varchar")
.withColumn("uuid_1", "uuid")
.withColumn("timeuuid_1", "timeuuid")
.withColumn("list_1", "list<text>")
.withColumn("set_1", "set<text>")
.withColumn("map_1", "map<text,text>")
.build()
.createKeyspace()
.createTable();
}
@After
public void after() {
CassandraUtils.dropKeyspaceIfNotNull(utils);
}
@Test
public void testCreateIndexAfterInsertions() {
utils.insert(data1,
data2,
data3,
data4,
data5,
data6,
data7,
data8,
data9,
data10,
data11,
data12,
data13,
data14,
data15,
data16,
data17,
data18,
data19,
data20)
.createIndex()
.refresh()
.filter(wildcard("ascii_1", "*"))
.check(20);
}
@Test
public void testCreateIndexDuringInsertions1() {
utils.insert(data1,
data2,
data3,
data4,
data5,
data6,
data7,
data8,
data9,
data10,
data11,
data12,
data13,
data14,
data15)
.createIndex()
.refresh()
.insert(data16, data17, data18, data19, data20)
.refresh()
.filter(wildcard("ascii_1", "*"))
.check(20);
}
@Test
public void testCreateIndexDuringInsertions2() {
utils.insert(data1,
data2,
data3,
data4,
data6,
data7,
data8,
data9,
data11,
data12,
data13,
data14,
data16,
data17,
data18,
data19)
.createIndex()
.refresh()
.insert(data5, data10, data15, data20)
.refresh()
.filter(wildcard("ascii_1", "*"))
.check(20);
}
@Test
public void testCreateIndexDuringInsertions3() {
utils.insert(data2,
data3,
data4,
data5,
data6,
data8,
data9,
data10,
data11,
data12,
data14,
data15,
data16,
data17,
data18,
data20)
.createIndex()
.refresh()
.insert(data1, data7, data13, data19)
.refresh()
.filter(wildcard("ascii_1", "*"))
.check(20);
}
@Test
public void testRecreateIndexAfterInsertions() {
utils.createIndex()
.refresh()
.insert(data1,
data2,
data3,
data4,
data5,
data6,
data7,
data8,
data9,
data10,
data11,
data12,
data13,
data14,
data15,
data16,
data17,
data18,
data19,
data20)
.refresh()
.dropIndex()
.createIndex()
.refresh()
.filter(wildcard("ascii_1", "*"))
.check(20);
}
} |
3e169b7172800b430e4b978a12ea3abc69042f96 | 1,159 | java | Java | igloo/igloo-components/igloo-component-commons/src/test/java/org/iglooproject/test/commons/util/validator/TestPermissivePhoneNumberValidator.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 17 | 2017-10-19T07:03:44.000Z | 2022-01-17T20:44:22.000Z | igloo/igloo-components/igloo-component-commons/src/test/java/org/iglooproject/test/commons/util/validator/TestPermissivePhoneNumberValidator.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 38 | 2018-01-22T15:57:35.000Z | 2022-01-14T16:28:45.000Z | igloo/igloo-components/igloo-component-commons/src/test/java/org/iglooproject/test/commons/util/validator/TestPermissivePhoneNumberValidator.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 6 | 2017-10-19T07:03:50.000Z | 2020-08-06T16:12:35.000Z | 26.340909 | 90 | 0.722174 | 9,640 | package org.iglooproject.test.commons.util.validator;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.iglooproject.commons.util.validator.PermissivePhoneNumberValidator;
@RunWith(Parameterized.class)
public class TestPermissivePhoneNumberValidator {
@Parameters(name = "{index} - \"{0}\" expecting {1}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "+1 (555) 555-5555", true },
{ "+33 3 33 33 33 33", true },
{ "++3 3 33 33 33 33", false },
{ "33 3 33 33 33 33+", false },
{ "some text", false },
});
}
@Parameter(0)
public String phoneNumber;
@Parameter(1)
public boolean expectedValid;
@Test
public void testValidation() {
PermissivePhoneNumberValidator validator = PermissivePhoneNumberValidator.getInstance();
if (expectedValid) {
Assert.assertTrue(validator.isValid(phoneNumber));
} else {
Assert.assertFalse(validator.isValid(phoneNumber));
}
}
}
|
3e169ba2eec84c0393e146655abd79cbc6298550 | 254 | java | Java | app/src/main/java/com/ruiqin/androidjingtong/base/BasePresenter.java | jianesrq0724/AndroidJingTong | 36bc3feb1ed261f2dc1bfaf8f7030525cacabed5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/ruiqin/androidjingtong/base/BasePresenter.java | jianesrq0724/AndroidJingTong | 36bc3feb1ed261f2dc1bfaf8f7030525cacabed5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/ruiqin/androidjingtong/base/BasePresenter.java | jianesrq0724/AndroidJingTong | 36bc3feb1ed261f2dc1bfaf8f7030525cacabed5 | [
"Apache-2.0"
] | null | null | null | 14.941176 | 40 | 0.586614 | 9,641 | package com.ruiqin.androidjingtong.base;
/**
* Created by jiane on 2016/9/28.
*/
public class BasePresenter<T, M> {
public T mView;
public M mModel;
public void setVM(T v, M m) {
this.mView = v;
this.mModel = m;
}
}
|
3e169bf4e1620b6ac0404f89e18a2ed745e0df2a | 887 | java | Java | src/main/java/com/ezlearning/platform/controller/aws/AwsS3Controller.java | AbdellahElahmar/Elearning-website | b8d75b78f734a0e23f5724a19cc1a55e1051d312 | [
"MIT"
] | 8 | 2019-12-03T12:57:59.000Z | 2022-02-11T23:02:34.000Z | src/main/java/com/ezlearning/platform/controller/aws/AwsS3Controller.java | AbdellahElahmar/Elearning-website | b8d75b78f734a0e23f5724a19cc1a55e1051d312 | [
"MIT"
] | null | null | null | src/main/java/com/ezlearning/platform/controller/aws/AwsS3Controller.java | AbdellahElahmar/Elearning-website | b8d75b78f734a0e23f5724a19cc1a55e1051d312 | [
"MIT"
] | 15 | 2020-01-20T07:19:58.000Z | 2021-12-14T13:11:59.000Z | 28.612903 | 67 | 0.780158 | 9,642 | package com.ezlearning.platform.controller.aws;
import com.ezlearning.platform.services.aws.AmazonS3ClientService;
import com.ezlearning.platform.services.aws.AmazonSqsClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/s3")
@PreAuthorize("hasRole('ROLE_USER')")
@Slf4j
public class AwsS3Controller {
AmazonS3ClientService s3Service;
public AwsS3Controller(AmazonS3ClientService service) {
this.s3Service = service;
}
@GetMapping("/createbucket")
int createBucket() {
log.info("Get request to /aws/createbucket");
return s3Service.createBucket();
}
}
|
3e169c8a1c4c9a9486ea9ebfe7b7475ef336364d | 1,584 | java | Java | core/src/main/java/org/opoo/press/impl/ListHolderImpl.java | JLLeitschuh/opoopress | 4ed0265d294c8b748be48cf097949aa905ff1df2 | [
"Apache-2.0"
] | 76 | 2015-01-05T09:07:33.000Z | 2021-06-07T06:09:49.000Z | core/src/main/java/org/opoo/press/impl/ListHolderImpl.java | JLLeitschuh/opoopress | 4ed0265d294c8b748be48cf097949aa905ff1df2 | [
"Apache-2.0"
] | 4 | 2015-01-20T03:28:40.000Z | 2015-04-22T14:17:46.000Z | core/src/main/java/org/opoo/press/impl/ListHolderImpl.java | JLLeitschuh/opoopress | 4ed0265d294c8b748be48cf097949aa905ff1df2 | [
"Apache-2.0"
] | 30 | 2015-01-13T09:43:09.000Z | 2020-02-11T15:05:35.000Z | 26.4 | 75 | 0.659091 | 9,643 | /*
* Copyright 2013-2015 Alex Lin.
*
* 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.opoo.press.impl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.opoo.press.ListHolder;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Alex Lin
*/
public class ListHolderImpl<T> implements ListHolder<T>, Serializable {
private Map<String, List<T>> map = Maps.newHashMap();
@Override
public List<T> get(String metaName) {
List<T> list = map.get(metaName);
if (list == null) {
list = Lists.newArrayList();
map.put(metaName, list);
}
return list;
}
@Override
public ListHolderImpl<T> add(String metaName, T e) {
get(metaName).add(e);
return this;
}
@Override
public String[] getKeys() {
Set<String> set = map.keySet();
return set.toArray(new String[set.size()]);
}
@Override
public void clear() {
map.clear();
}
}
|
3e169ccebc7b77912f482b7753632b9506fc3b26 | 1,810 | java | Java | Resources/Code/Eclipse-SW360antenna/antenna/core/runtime/src/test/java/org/eclipse/sw360/antenna/util/ZipExtractorTest.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | 2 | 2020-02-07T17:32:14.000Z | 2022-02-08T09:14:01.000Z | Resources/Code/Eclipse-SW360antenna/antenna/core/runtime/src/test/java/org/eclipse/sw360/antenna/util/ZipExtractorTest.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | Resources/Code/Eclipse-SW360antenna/antenna/core/runtime/src/test/java/org/eclipse/sw360/antenna/util/ZipExtractorTest.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | 30.677966 | 121 | 0.698343 | 9,644 | /*
* Copyright (c) Bosch Software Innovations GmbH 2019.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.sw360.antenna.util;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.assertj.core.api.Assertions.assertThat;
public class ZipExtractorTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void testZipExtractor() throws IOException {
File zipFileFolder = temporaryFolder.newFolder();
StringBuilder sb = new StringBuilder();
sb.append("Test String");
File zipFile = zipFileFolder.toPath().resolve("zipFile.zip").toFile();
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream out = new ZipOutputStream(fos)) {
ZipEntry e = new ZipEntry("testText.txt");
out.putNextEntry(e);
byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();
}
File unzipFolder = temporaryFolder.newFolder();
ZipExtractor.extractAll(zipFile, unzipFolder);
assertThat(unzipFolder.list()).contains("testText.txt");
assertThat(Files.readAllLines(Paths.get(unzipFolder.toString(), "testText.txt"))).containsExactly("Test String");
}
}
|
3e169d4273d707ab7f776099f034887bb6621201 | 1,235 | java | Java | src/main/java/me/matthewmerrill/ek/Player.java | MatthewMerrill/ek-matthewmerrill-me | 6c4205e1e64ff62e03b07ac6c0672f74efc17ecd | [
"MIT"
] | 1 | 2019-03-30T02:31:39.000Z | 2019-03-30T02:31:39.000Z | src/main/java/me/matthewmerrill/ek/Player.java | MatthewMerrill/ek-matthewmerrill-me | 6c4205e1e64ff62e03b07ac6c0672f74efc17ecd | [
"MIT"
] | null | null | null | src/main/java/me/matthewmerrill/ek/Player.java | MatthewMerrill/ek-matthewmerrill-me | 6c4205e1e64ff62e03b07ac6c0672f74efc17ecd | [
"MIT"
] | null | null | null | 20.245902 | 83 | 0.696356 | 9,645 | package me.matthewmerrill.ek;
import java.util.HashMap;
import me.matthewmerrill.ek.card.Card;
import me.matthewmerrill.ek.card.Deck;
public class Player extends HashMap<String, Object> implements Comparable<Player> {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String NAME = "name";
public static final String SESSION_ID = "sessionId";
public static final String DECK = "playerDeck";
public static final String KILLED = "killed";
public Player(String name, String sessionId) {
put(NAME, name);
put(SESSION_ID, sessionId);
put(DECK, new Deck());
put(KILLED, false);
}
public Deck getDeck() {
return (Deck) get(DECK);
}
public void giveCard(Card card) {
Deck deck = (Deck) get(DECK);
deck.add(0, card);
put(DECK, deck);
}
@Override
public boolean equals(Object obj) {
return compareTo((Player)obj) == 0;
}
@Override
public int compareTo(Player player) {
return get(SESSION_ID).toString().compareTo(player.get(SESSION_ID).toString());
}
@Override
public int hashCode() {
return get(SESSION_ID).hashCode();
}
public String getSsid() {
return (String) get(SESSION_ID);
}
public String getName() {
return (String) get(NAME);
}
}
|
3e169d5360094863f498f21ac2b89fd750aa13e6 | 937 | java | Java | maven_tema3/src/main/java/com/codigonline/hb/entities/Deporte.java | CodigOnline/acces-a-datos | d9407e8d8158372c60400347b8ef624fc91e6741 | [
"MIT"
] | 2 | 2021-10-02T18:45:22.000Z | 2021-10-03T16:10:20.000Z | maven_tema3/src/main/java/com/codigonline/hb/entities/Deporte.java | CodigOnline/acces-a-datos | d9407e8d8158372c60400347b8ef624fc91e6741 | [
"MIT"
] | null | null | null | maven_tema3/src/main/java/com/codigonline/hb/entities/Deporte.java | CodigOnline/acces-a-datos | d9407e8d8158372c60400347b8ef624fc91e6741 | [
"MIT"
] | null | null | null | 18.74 | 54 | 0.604055 | 9,646 | package com.codigonline.hb.entities;
import java.util.Set;
public class Deporte {
private int id;
private String nombre;
private boolean aireLibre;
private Set<Persona> personas;
public Deporte() {
}
public Deporte(String nombre, boolean aireLibre) {
this.nombre = nombre;
this.aireLibre = aireLibre;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public boolean isAireLibre() {
return aireLibre;
}
public void setAireLibre(boolean aireLibre) {
this.aireLibre = aireLibre;
}
public Set<Persona> getPersonas() {
return personas;
}
public void setPersonas(Set<Persona> personas) {
this.personas = personas;
}
}
|
3e169d5575bf39b2b8d6acc19df275e8f7570300 | 1,460 | java | Java | erp_web/src/main/java/cn/itcast/erp/action/ReportAction.java | xs1031893936/erp | 6e7209e3c5d9f8654632b717f98c521d4b0fe1e5 | [
"Apache-2.0"
] | 1 | 2020-02-05T14:25:41.000Z | 2020-02-05T14:25:41.000Z | erp_web/src/main/java/cn/itcast/erp/action/ReportAction.java | xs1031893936/erp | 6e7209e3c5d9f8654632b717f98c521d4b0fe1e5 | [
"Apache-2.0"
] | 2 | 2021-04-22T16:45:34.000Z | 2022-02-09T22:57:04.000Z | erp_web/src/main/java/cn/itcast/erp/action/ReportAction.java | xs1031893936/erp | 6e7209e3c5d9f8654632b717f98c521d4b0fe1e5 | [
"Apache-2.0"
] | null | null | null | 18.25 | 69 | 0.608219 | 9,647 | package cn.itcast.erp.action;
import cn.itcast.erp.biz.IReportBiz;
import cn.itcast.erp.util.ViewUtils;
import com.alibaba.fastjson.JSON;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 报表 Action
* Author xushuai
* Description
*/
public class ReportAction {
private IReportBiz reportBiz;
/** 开始日期 */
private Date startDate;
/** 截止日期 */
private Date endDate;
/** 年份 */
private int year;
/**
* 生成销售额统计(按商品类型)
*/
public void ordersReport() {
List list = reportBiz.ordersReport(startDate, endDate);
ViewUtils.write(JSON.toJSONString(list));
}
/**
* 生成销售额统计(按年份)
*/
public void trendReport() {
List<Map<String, Object>> list = reportBiz.trendReport(year);
ViewUtils.write(JSON.toJSONString(list));
}
/** 以下为 get、set 方法 */
public void setReportBiz(IReportBiz reportBiz) {
this.reportBiz = reportBiz;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public IReportBiz getReportBiz() {
return reportBiz;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
|
3e169dab6f0a9d2628a26ea5b41e42106b7f5c19 | 5,315 | java | Java | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/IndexRedirectWriter.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/IndexRedirectWriter.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/IndexRedirectWriter.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | 45.818966 | 132 | 0.721731 | 9,648 | /*
* Copyright (c) 2016, 2021, 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 jdk.javadoc.internal.doclets.formats.html;
import java.util.Collections;
import jdk.javadoc.internal.doclets.formats.html.markup.Head;
import jdk.javadoc.internal.doclets.formats.html.markup.ContentBuilder;
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlAttr;
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlDocument;
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle;
import jdk.javadoc.internal.doclets.formats.html.markup.TagName;
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTree;
import jdk.javadoc.internal.doclets.formats.html.markup.Script;
import jdk.javadoc.internal.doclets.formats.html.markup.Text;
import jdk.javadoc.internal.doclets.toolkit.Content;
import jdk.javadoc.internal.doclets.toolkit.util.DocFile;
import jdk.javadoc.internal.doclets.toolkit.util.DocFileIOException;
import jdk.javadoc.internal.doclets.toolkit.util.DocPath;
import jdk.javadoc.internal.doclets.toolkit.util.DocPaths;
/**
* Writes a file that tries to redirect to an alternate page.
* The redirect uses JavaScript, if enabled, falling back on
* {@code <meta http-equiv=refresh content="0,<uri>">}.
* If neither are supported/enabled in a browser, the page displays the
* standard "JavaScript not enabled" message, and a link to the alternate page.
*/
public class IndexRedirectWriter extends HtmlDocletWriter {
public static void generate(HtmlConfiguration configuration)
throws DocFileIOException {
generate(configuration, DocPaths.INDEX, configuration.topFile);
}
public static void generate(HtmlConfiguration configuration, DocPath fileName, DocPath target)
throws DocFileIOException {
IndexRedirectWriter indexRedirect = new IndexRedirectWriter(configuration, fileName, target);
indexRedirect.generateIndexFile();
}
private DocPath target;
private IndexRedirectWriter(HtmlConfiguration configuration, DocPath filename, DocPath target) {
super(configuration, filename);
this.target = target;
}
/**
* Generate an index file that redirects to an alternate file.
* @throws DocFileIOException if there is a problem generating the file
*/
private void generateIndexFile() throws DocFileIOException {
Head head = new Head(path, configuration.getDocletVersion(), configuration.startTime)
.setTimestamp(!options.noTimestamp())
.setDescription("index redirect")
.setGenerator(getGenerator(getClass()))
.setStylesheets(configuration.getMainStylesheet(), Collections.emptyList()) // avoid reference to default stylesheet
.addDefaultScript(false);
String title = (options.windowTitle().length() > 0)
? options.windowTitle()
: resources.getText("doclet.Generated_Docs_Untitled");
head.setTitle(title)
.setCharset(options.charset())
.setCanonicalLink(target);
String targetPath = target.getPath();
Script script = new Script("window.location.replace(")
.appendStringLiteral(targetPath, '\'')
.append(")");
HtmlTree metaRefresh = new HtmlTree(TagName.META)
.put(HtmlAttr.HTTP_EQUIV, "Refresh")
.put(HtmlAttr.CONTENT, "0;" + targetPath);
head.addContent(script.asContent(), HtmlTree.NOSCRIPT(metaRefresh));
ContentBuilder bodyContent = new ContentBuilder();
bodyContent.add(HtmlTree.NOSCRIPT(
HtmlTree.P(contents.getContent("doclet.No_Script_Message"))));
bodyContent.add(HtmlTree.P(HtmlTree.A(targetPath, Text.of(targetPath))));
Content body = new HtmlTree(TagName.BODY).setStyle(HtmlStyle.indexRedirectPage);
HtmlTree main = HtmlTree.MAIN(bodyContent);
body.add(main);
HtmlDocument htmlDocument = new HtmlDocument(
HtmlTree.HTML(configuration.getLocale().getLanguage(), head, body));
htmlDocument.write(DocFile.createFileForOutput(configuration, path));
}
}
|
3e169e4c6b5076b895f3883cbfb21c5f158d2d3e | 4,265 | java | Java | clients/google-api-services-bigqueryreservation/v1/1.31.0/com/google/api/services/bigqueryreservation/v1/model/Assignment.java | Canufindme/google-api-java-client-services | 8d0198de8bfee76631693a63477bb61013d55715 | [
"Apache-2.0"
] | 372 | 2018-09-05T21:06:51.000Z | 2022-03-31T09:22:03.000Z | clients/google-api-services-bigqueryreservation/v1/1.31.0/com/google/api/services/bigqueryreservation/v1/model/Assignment.java | tonymade8/google-api-java-client-services | 5bb8286e0d6f139c7011499ecf37fa80d4649663 | [
"Apache-2.0"
] | 1,351 | 2018-10-12T23:07:12.000Z | 2022-03-05T09:25:29.000Z | clients/google-api-services-bigqueryreservation/v1/1.31.0/com/google/api/services/bigqueryreservation/v1/model/Assignment.java | tonymade8/google-api-java-client-services | 5bb8286e0d6f139c7011499ecf37fa80d4649663 | [
"Apache-2.0"
] | 307 | 2018-09-04T20:15:31.000Z | 2022-03-31T09:42:39.000Z | 29.013605 | 182 | 0.684408 | 9,649 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.bigqueryreservation.v1.model;
/**
* An assignment allows a project to submit jobs of a certain type using slots from the specified
* reservation.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the BigQuery Reservation API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Assignment extends com.google.api.client.json.GenericJson {
/**
* The resource which will use the reservation. E.g. `projects/myproject`, `folders/123`, or
* `organizations/456`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String assignee;
/**
* Which type of jobs will use the reservation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String jobType;
/**
* Output only. Name of the resource. E.g.:
* `projects/myproject/locations/US/reservations/team1-prod/assignments/123`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Output only. State of the assignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String state;
/**
* The resource which will use the reservation. E.g. `projects/myproject`, `folders/123`, or
* `organizations/456`.
* @return value or {@code null} for none
*/
public java.lang.String getAssignee() {
return assignee;
}
/**
* The resource which will use the reservation. E.g. `projects/myproject`, `folders/123`, or
* `organizations/456`.
* @param assignee assignee or {@code null} for none
*/
public Assignment setAssignee(java.lang.String assignee) {
this.assignee = assignee;
return this;
}
/**
* Which type of jobs will use the reservation.
* @return value or {@code null} for none
*/
public java.lang.String getJobType() {
return jobType;
}
/**
* Which type of jobs will use the reservation.
* @param jobType jobType or {@code null} for none
*/
public Assignment setJobType(java.lang.String jobType) {
this.jobType = jobType;
return this;
}
/**
* Output only. Name of the resource. E.g.:
* `projects/myproject/locations/US/reservations/team1-prod/assignments/123`.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Output only. Name of the resource. E.g.:
* `projects/myproject/locations/US/reservations/team1-prod/assignments/123`.
* @param name name or {@code null} for none
*/
public Assignment setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Output only. State of the assignment.
* @return value or {@code null} for none
*/
public java.lang.String getState() {
return state;
}
/**
* Output only. State of the assignment.
* @param state state or {@code null} for none
*/
public Assignment setState(java.lang.String state) {
this.state = state;
return this;
}
@Override
public Assignment set(String fieldName, Object value) {
return (Assignment) super.set(fieldName, value);
}
@Override
public Assignment clone() {
return (Assignment) super.clone();
}
}
|
3e169e8fed4c938c0ee9e5a89532dc3ee8a8b05f | 445 | java | Java | jphp-runtime/src/php/runtime/ext/core/classes/lib/legacy/OldNumUtils.java | Diffblue-benchmarks/Jphp-group-jphp | e0d00163a74d78adb72629d8309d1df3ffed7662 | [
"Apache-2.0"
] | 903 | 2015-01-02T18:49:24.000Z | 2018-05-02T14:44:25.000Z | jphp-runtime/src/php/runtime/ext/core/classes/lib/legacy/OldNumUtils.java | Diffblue-benchmarks/Jphp-group-jphp | e0d00163a74d78adb72629d8309d1df3ffed7662 | [
"Apache-2.0"
] | 137 | 2018-05-11T20:47:24.000Z | 2022-02-24T23:21:21.000Z | jphp-runtime/src/php/runtime/ext/core/classes/lib/legacy/OldNumUtils.java | Diffblue-benchmarks/Jphp-group-jphp | e0d00163a74d78adb72629d8309d1df3ffed7662 | [
"Apache-2.0"
] | 129 | 2015-01-06T06:34:03.000Z | 2018-04-22T10:00:35.000Z | 29.666667 | 60 | 0.773034 | 9,650 | package php.runtime.ext.core.classes.lib.legacy;
import php.runtime.annotation.Reflection.Name;
import php.runtime.env.Environment;
import php.runtime.ext.core.classes.lib.ItemsUtils;
import php.runtime.ext.core.classes.lib.NumUtils;
import php.runtime.reflection.ClassEntity;
@Name("php\\lib\\Number")
public class OldNumUtils extends NumUtils {
public OldNumUtils(Environment env, ClassEntity clazz) {
super(env, clazz);
}
}
|
3e169eb2fba961e32536d983eb58336d6bf3935d | 4,149 | java | Java | beeline/src/java/org/apache/hive/beeline/hs2connection/HS2ConnectionFileParser.java | manbuyun/hive | cdb1052e24ca493c6486fef3dd8956dde61be834 | [
"Apache-2.0"
] | 4,140 | 2015-01-07T11:57:35.000Z | 2022-03-31T06:26:22.000Z | beeline/src/java/org/apache/hive/beeline/hs2connection/HS2ConnectionFileParser.java | manbuyun/hive | cdb1052e24ca493c6486fef3dd8956dde61be834 | [
"Apache-2.0"
] | 1,779 | 2015-05-27T04:32:42.000Z | 2022-03-31T18:53:19.000Z | beeline/src/java/org/apache/hive/beeline/hs2connection/HS2ConnectionFileParser.java | manbuyun/hive | cdb1052e24ca493c6486fef3dd8956dde61be834 | [
"Apache-2.0"
] | 3,958 | 2015-01-01T15:14:49.000Z | 2022-03-30T21:08:32.000Z | 47.147727 | 122 | 0.739214 | 9,651 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hive.beeline.hs2connection;
import java.util.Properties;
/**
* HS2ConnectionFileParser provides a interface to be used by Beeline to parse a configuration (file
* or otherwise) to return a Java Properties object which contain key value pairs to be used to construct
* connection URL automatically for the Beeline connection
*/
public interface HS2ConnectionFileParser {
/**
* prefix string used for the keys
*/
public static final String BEELINE_CONNECTION_PROPERTY_PREFIX = "beeline.hs2.connection.";
/**
* Property key used to provide the URL prefix for the connection URL
*/
public static final String URL_PREFIX_PROPERTY_KEY = "url_prefix";
/**
* Property key used to provide the default database in the connection URL
*/
public static final String DEFAULT_DB_PROPERTY_KEY = "defaultDB";
/**
* Property key used to provide the hosts in the connection URL
*/
public static final String HOST_PROPERTY_KEY = "hosts";
/**
* Property key used to provide the hive configuration key value pairs in the connection URL
*/
public static final String HIVE_CONF_PROPERTY_KEY = "hiveconf";
/**
* Property key used to provide the hive variables in the connection URL
*/
public static final String HIVE_VAR_PROPERTY_KEY = "hivevar";
/**
* Returns a Java properties object which contain the key value pairs which can be used in the
* Beeline connection URL<p>
* The properties returned must include url_prefix and hosts<p>
* Following are some examples of the URLs and returned properties object<p>
* <ul>
* <li> jdbc:hive2://hs2-instance1.example.com:10000/default;user=hive;password=mypassword should
* return [ "url_prefix"="jdbc:hive2://", "hosts"="hs2-instance1.example.com:10000",
* "defaultDB"=default, "user"="hive", "password"="mypassword" ]
* <li>jdbc:hive2://zk-instance1:10001,zk-instance2:10002,zk-instance3:10003/default;
* serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2 should return [
* "url_prefix"="jdbc:hive2://",
* "hosts"="zk-instance1:10001,zk-instance2:10002,zk-instance3:10003", "defaultDB"="default",
* "serviceDiscoveryMode"="zooKeeper", "zooKeeperNamespace"="hiveserver2" ]
*
* <li>If hive_conf_list and hive_var_list is present in the url it should return a comma separated
* key=value pairs for each of them<p>
* For example :<p>
* jdbc:hive2://hs2-instance1.example.com:10000/default;user=hive?hive.cli.print.currentdb=true;
* hive.cli.print.header=true#hivevar:mytbl=customers;hivevar:mycol=id it should return [
* "url_prefix"="jdbc:hive2://", "hosts"="hs2-instance1.example.com:10000", "defaultDB"="default",
* "user"="hive", "hiveconf"="hive.cli.print.currentdb=true, hive.cli.print.header=true",
* "hivevar"="hivevar:mytb1=customers, hivevar:mycol=id" ]
* </ul>
*
* @return Properties object which contain connection URL properties for Beeline connection. Returns an empty properties
* object if the connection configuration is not found
* @throws BeelineHS2ConnectionFileParseException if there is invalid key with appropriate message
*/
Properties getConnectionProperties() throws BeelineConfFileParseException;
/**
*
* @return returns true if the configuration exists else returns false
*/
boolean configExists();
} |
3e169fa9edc1337f796bd9a3f8cda001f1c7a9ef | 32,660 | java | Java | src/test/java/uk/gov/hmcts/ethos/replacement/docmosis/reports/hearingstojudgments/HearingsToJudgmentsReportTest.java | banderous/et-ccd-callbacks | 8af6e73a6b4f7eb2d79be0c47752a88edfcc67b7 | [
"MIT"
] | null | null | null | src/test/java/uk/gov/hmcts/ethos/replacement/docmosis/reports/hearingstojudgments/HearingsToJudgmentsReportTest.java | banderous/et-ccd-callbacks | 8af6e73a6b4f7eb2d79be0c47752a88edfcc67b7 | [
"MIT"
] | null | null | null | src/test/java/uk/gov/hmcts/ethos/replacement/docmosis/reports/hearingstojudgments/HearingsToJudgmentsReportTest.java | banderous/et-ccd-callbacks | 8af6e73a6b4f7eb2d79be0c47752a88edfcc67b7 | [
"MIT"
] | null | null | null | 60.258303 | 172 | 0.703613 | 9,652 | package uk.gov.hmcts.ethos.replacement.docmosis.reports.hearingstojudgments;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import uk.gov.hmcts.ecm.common.model.ccd.items.JudgementTypeItem;
import uk.gov.hmcts.ecm.common.model.helper.TribunalOffice;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.ACCEPTED_STATE;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.CLOSED_STATE;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.ENGLANDWALES_CASE_TYPE_ID;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.ENGLANDWALES_LISTING_CASE_TYPE_ID;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_STATUS_HEARD;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_STATUS_LISTED;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_STATUS_POSTPONED;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_STATUS_SETTLED;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_STATUS_WITHDRAWN;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_JUDICIAL_COSTS_HEARING;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_JUDICIAL_HEARING;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_JUDICIAL_MEDIATION;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_JUDICIAL_MEDIATION_TCC;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_JUDICIAL_RECONSIDERATION;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_JUDICIAL_REMEDY;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_PERLIMINARY_HEARING;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_PERLIMINARY_HEARING_CM;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.NO;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.OLD_DATE_TIME_PATTERN;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.OLD_DATE_TIME_PATTERN2;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.SCOTLAND_CASE_TYPE_ID;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.SCOTLAND_LISTING_CASE_TYPE_ID;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.SUBMITTED_STATE;
import static uk.gov.hmcts.ecm.common.model.helper.Constants.YES;
class HearingsToJudgmentsReportTest {
HearingsToJudgmentsDataSource hearingsToJudgmentsReportDataSource;
HearingsToJudgmentsReport hearingsToJudgmentsReport;
HearingsToJudgmentsCaseDataBuilder caseDataBuilder;
List<HearingsToJudgmentsSubmitEvent> submitEvents = new ArrayList<>();
static final LocalDateTime BASE_DATE = LocalDateTime.of(2021, 7, 1, 0, 0,0);
static final String HEARING_LISTING_DATE = BASE_DATE.format(OLD_DATE_TIME_PATTERN);
static final String DATE_WITHIN_4WKS = BASE_DATE.plusWeeks(1).format(OLD_DATE_TIME_PATTERN2);
static final String DATE_NOT_WITHIN_4WKS = BASE_DATE.plusWeeks(5).format(OLD_DATE_TIME_PATTERN2);
static final String JUDGMENT_HEARING_DATE = BASE_DATE.format(OLD_DATE_TIME_PATTERN2);
static final String DATE_FROM = BASE_DATE.minusDays(1).format(OLD_DATE_TIME_PATTERN);
static final String DATE_TO = BASE_DATE.plusDays(29).format(OLD_DATE_TIME_PATTERN);
static final String INVALID_JUDGMENT_HEARING_DATE = BASE_DATE.plusDays(1).format(OLD_DATE_TIME_PATTERN2);
static final String INVALID_HEARING_LISTING_DATE = BASE_DATE.minusDays(2).format(OLD_DATE_TIME_PATTERN);
static final String DYNAMIC_JUDGMENT_HEARING_LABEL = "1 : Hearing";
static final String HEARING_NUMBER = "1";
public HearingsToJudgmentsReportTest() {
caseDataBuilder = new HearingsToJudgmentsCaseDataBuilder();
}
@BeforeEach
public void setup() {
submitEvents.clear();
hearingsToJudgmentsReportDataSource = mock(HearingsToJudgmentsDataSource.class);
when(hearingsToJudgmentsReportDataSource.getData(ENGLANDWALES_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName(), DATE_FROM, DATE_TO)).thenReturn(submitEvents);
hearingsToJudgmentsReport = new HearingsToJudgmentsReport(hearingsToJudgmentsReportDataSource, DATE_FROM, DATE_TO);
}
@Test
void shouldNotShowSubmittedCase() {
// Given a case is submitted
// When I request report data
// Then the case should not be in the report data
submitEvents.add(caseDataBuilder.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName()).buildAsSubmitEvent(SUBMITTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertTrue(reportData.getReportDetails().isEmpty());
}
@Test
void shouldNotShowCaseIfNoHearingsExist() {
// Given a case is not submitted
// And has no hearings
// When I request report data
// Then the case should not be in the report data
submitEvents.add(caseDataBuilder.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName()).buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertTrue(reportData.getReportDetails().isEmpty());
}
@Test
void shouldNotShowCaseIfNoHearingHasNotBeenHeard() {
// Given a case is accepted
// And has no hearing that has been heard
// When I request report data
// Then the case should not be in the report data
submitEvents.add(caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_LISTED, HEARING_TYPE_JUDICIAL_HEARING, YES)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertTrue(reportData.getReportDetails().isEmpty());
}
@Test
void shouldNotShowCaseIfHeardButNoJudgmentsMade() {
// Given a case is accepted
// And has been heard
// And has no judgments
// When I request report data
// Then the case should not be in the report data
submitEvents.add(caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertTrue(reportData.getReportDetails().isEmpty());
}
@Test
void shouldNotShowCaseIfHeardButJudgmentsHasNoValue() {
// Given a case is accepted
// And has been heard
// And has judgement but without a value
// When I request report data
// Then the case should not be in the report data
var judgmentTypeItem = new JudgementTypeItem();
judgmentTypeItem.setValue(null);
var submitEvent = caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment("2021-07-16", DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE);
submitEvent.getCaseData().getJudgementCollection().add(judgmentTypeItem);
submitEvents.add(submitEvent);
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertTrue(reportData.getReportDetails().isEmpty());
}
@Test
void shouldNotShowCaseIfHeardButJudgmentsHasNoHearingDate() {
// Given a case is accepted
// And has been heard
// And has judgment but without a hearing date
// When I request report data
// Then the case should not be in the report data
var submitEvent = caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment("2021-07-16", DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.withJudgment(null, null, null, null)
.buildAsSubmitEvent(ACCEPTED_STATE);
submitEvents.add(submitEvent);
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertTrue(reportData.getReportDetails().isEmpty());
}
@ParameterizedTest
@CsvSource({
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + YES,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + YES,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + YES,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + YES,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + NO,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + YES,
HEARING_STATUS_HEARD + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + NO,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + YES,
HEARING_STATUS_LISTED + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + NO,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + YES,
HEARING_STATUS_SETTLED + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + NO,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + YES,
HEARING_STATUS_WITHDRAWN + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_COSTS_HEARING + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_HEARING + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_MEDIATION + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_MEDIATION_TCC + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_PERLIMINARY_HEARING + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_RECONSIDERATION + "," + NO,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + YES,
HEARING_STATUS_POSTPONED + "," + HEARING_TYPE_JUDICIAL_REMEDY + "," + NO,
})
void shouldNotShowInvalidHearings(String hearingStatus, String HearingType, String disposed) {
// Given a case is accepted
// And has been heard
// And has a judgment made
// When I request report data
// Then the case is not in the report data
submitEvents.add(caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, hearingStatus, HearingType, disposed)
.withJudgment(JUDGMENT_HEARING_DATE, DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(0, reportData.getReportDetails().size());
}
@Test
void shouldNotShowHearingsWithInvalidHearingListDate() {
// Given a case is accepted
// And has a hearing with listed date outside the date range
// When I request report data
// Then the case is not in the report data
submitEvents.add(caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(INVALID_HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment(INVALID_JUDGMENT_HEARING_DATE, DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(0, reportData.getReportDetails().size());
}
@Test
void shouldNotShowHearingsWithInvalidJudgments() {
// Given a case is accepted
// And has been heard
// And has invalid judgment
// When I request report data
// Then the case is not in the report data
submitEvents.add(caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment(INVALID_JUDGMENT_HEARING_DATE, DATE_WITHIN_4WKS, DATE_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(0, reportData.getReportDetails().size());
}
@Test
void shouldShowNotShowJudgmentWithInvalidHearingNumber() {
// Given a case is accepted
// And has been heard
// And has a judgment made with the incorrect hearing number
// When I request report data
// Then the case is not in the report data
submitEvents.add(caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, "2", HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment(JUDGMENT_HEARING_DATE, DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(0, reportData.getReportDetails().size());
}
@Test
void shouldShowValidCase() {
// Given a case is accepted
// And has been heard
// And has a judgment made
// When I request report data
// Then the case is in the report data
submitEvents.add(caseDataBuilder
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment(JUDGMENT_HEARING_DATE, DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(1, reportData.getReportDetails().size());
}
@Test
void shouldShowCorrectScotlandOfficeValidCase() {
// Given a case with a scottish office is accepted
// And has been heard
// And has a judgment made
// When I request report data
// Then the case is in the report data
var managingOffice = TribunalOffice.GLASGOW.getOfficeName();
when(hearingsToJudgmentsReportDataSource.getData(SCOTLAND_CASE_TYPE_ID, managingOffice, DATE_FROM, DATE_TO)).thenReturn(submitEvents);
submitEvents.add(caseDataBuilder
.withManagingOffice(managingOffice)
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment(JUDGMENT_HEARING_DATE, DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(SCOTLAND_LISTING_CASE_TYPE_ID, managingOffice);
assertNotNull(reportData);
assertEquals(TribunalOffice.SCOTLAND.getOfficeName(), reportData.getReportSummary().getOffice());
assertEquals(1, reportData.getReportDetails().size());
var reportDetail = reportData.getReportDetails().get(0);
assertEquals(TribunalOffice.GLASGOW.getOfficeName(), reportDetail.getReportOffice());
}
@Test
void shouldShowTotalHearingsInSummary() {
// Given I have 2 valid cases with hearings with judgements within 4 weeks
// And 1 valid case with hearings with judgement not within 4 weeks
// When I request report data
// Then the report summary shows 3 total hearings
// And 2 total hearings with judgements within 4 weeks
// And 1 total hearings with judgement not within 4 weeks
submitEvents.add(createValidSubmitEventNotWithin4Wks());
submitEvents.add(createValidSubmitEventWithin4Wks());
submitEvents.add(createValidSubmitEventWithin4Wks());
submitEvents.add(createValidSubmitEventWithin4Wks());
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals("4", reportData.getReportSummary().getTotalCases());
assertEquals(1, reportData.getReportDetails().size());
assertEquals("3", reportData.getReportSummary().getTotal4Wk());
assertEquals("75.00", reportData.getReportSummary().getTotal4WkPercent());
assertEquals("1", reportData.getReportSummary().getTotalX4Wk());
assertEquals("25.00", reportData.getReportSummary().getTotalX4WkPercent());
}
@Test
void shouldSortCasesByTotalDays() {
// Given I have 2 cases with a judgment outside of 4 weeks
// When I request report data
// The details section should be ordered by total days ascending
submitEvents.add(createValidSubmitEventNotWithin4Wks());
submitEvents.add(createValidSubmitEventNotWithin4Wks());
// Will set the first cases total days to a number larger than the second cases
submitEvents.get(0).getCaseData().getJudgementCollection().get(0).getValue().setDateJudgmentSent("2021-12-31");
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID,
TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(2, reportData.getReportDetails().size());
assertTrue(Integer.parseInt(reportData.getReportDetails().get(0).getTotalDays())
< Integer.parseInt(reportData.getReportDetails().get(1).getTotalDays()));
}
@ParameterizedTest
@CsvSource({
"2021-07-16T10:00:00.000,2021-07-16,2021-08-26,2021-08-26,42,2500121/2021,1,One Test,"
+ HEARING_TYPE_JUDICIAL_HEARING + "," + YES + "," + ACCEPTED_STATE,
"2021-07-17T10:00:00.000,2021-07-17,2021-08-26,2021-08-26,41,2500122/2021,2,Two Test,"
+ HEARING_TYPE_PERLIMINARY_HEARING + "," + NO + "," + ACCEPTED_STATE,
"2021-07-18T10:00:00.000,2021-07-18,2021-08-26,2021-08-26,40,2500123/2021,3,Three Test,"
+ HEARING_TYPE_PERLIMINARY_HEARING_CM + ",," + CLOSED_STATE,
"2021-07-19T10:00:00.000,2021-07-19,2021-08-26,2021-08-26,39,2500124/2021,4,Four Test,"
+ HEARING_TYPE_PERLIMINARY_HEARING_CM_TCC + "," + YES + "," + CLOSED_STATE})
void shouldContainCorrectDetailValuesForHearingsWithValidJudgment(String hearingListedDate, String judgmentHearingDate,
String dateJudgmentMade, String dateJudgmentSent,
String expectedTotalDays, String caseReference,
String hearingNumber, String hearingJudge,
String hearingType, String hearingReserved,
String caseState) {
// Given I have a case in a valid state
// And the case has a valid hearing and judgment
// When I request report data
// Then I have correct report detail values for the case
submitEvents.add(caseDataBuilder
.withEthosCaseReference(caseReference)
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(hearingListedDate, HEARING_STATUS_HEARD, hearingType, YES,
hearingNumber, hearingJudge, hearingReserved)
.withJudgment(judgmentHearingDate, dateJudgmentMade, dateJudgmentSent, hearingNumber)
.buildAsSubmitEvent(caseState));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(1, reportData.getReportDetails().size());
var reportDetail = reportData.getReportDetails().get(0);
assertEquals(hearingJudge, reportDetail.getHearingJudge());
assertEquals(TribunalOffice.NEWCASTLE.getOfficeName(), reportDetail.getReportOffice());
assertEquals(caseReference, reportDetail.getCaseReference());
assertEquals(hearingReserved, reportDetail.getReservedHearing());
assertEquals(expectedTotalDays, reportDetail.getTotalDays());
assertEquals(judgmentHearingDate, reportDetail.getHearingDate());
assertEquals(dateJudgmentSent, reportDetail.getJudgementDateSent());
}
@Test
void shouldContainCorrectDetailValuesForMultipleHearingsWithJudgments() {
// Given I have a valid case
// And the case has the following hearings:
// | Listed Date | Hearing Number | Date Judgment Made | Date Judgment Sent |
// | 2021-07-06 | 1 | 2021-08-03 | 2021-08-04
// | 2021-07-05 | 2 | 2021-08-03 | 2021-08-04
// When I request report data
// Then I have correct hearing values for hearing #2
var expectedTotalDays = "31";
var caseReference = "2500123/2021";
var judge = "3756_Hugh Garfield"; // Amended to mimic Judge's ITCO reference
var judgmentHearingDate = "2021-07-05";
var dateJudgmentSent = "2021-08-04";
submitEvents.add(caseDataBuilder
.withEthosCaseReference(caseReference)
.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing("2021-07-06T10:00:00.000", HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING,
YES, HEARING_NUMBER, "A.N. Other", YES)
.withJudgment("2021-07-06", "2021-08-03", "2021-08-04", DYNAMIC_JUDGMENT_HEARING_LABEL)
.withHearing("2021-07-05T10:00:00.000", HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING,
YES, "2", judge, NO)
.withJudgment(judgmentHearingDate, "2021-08-03", dateJudgmentSent, "2")
.buildAsSubmitEvent(ACCEPTED_STATE));
var reportData = hearingsToJudgmentsReport.runReport(ENGLANDWALES_LISTING_CASE_TYPE_ID, TribunalOffice.NEWCASTLE.getOfficeName());
assertCommonValues(reportData);
assertEquals(1, reportData.getReportDetails().size());
var reportDetail = reportData.getReportDetails().get(0);
assertEquals(judge, reportDetail.getHearingJudge());
assertEquals(TribunalOffice.NEWCASTLE.getOfficeName(), reportDetail.getReportOffice());
assertEquals(caseReference, reportDetail.getCaseReference());
assertEquals(NO, reportDetail.getReservedHearing());
assertEquals(expectedTotalDays, reportDetail.getTotalDays());
assertEquals(judgmentHearingDate, reportDetail.getHearingDate());
assertEquals(dateJudgmentSent, reportDetail.getJudgementDateSent());
}
private HearingsToJudgmentsSubmitEvent createValidSubmitEventWithin4Wks() {
caseDataBuilder = new HearingsToJudgmentsCaseDataBuilder();
return caseDataBuilder.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment(JUDGMENT_HEARING_DATE, DATE_WITHIN_4WKS, DATE_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE);
}
private HearingsToJudgmentsSubmitEvent createValidSubmitEventNotWithin4Wks() {
caseDataBuilder = new HearingsToJudgmentsCaseDataBuilder();
return caseDataBuilder.withManagingOffice(TribunalOffice.NEWCASTLE.getOfficeName())
.withHearing(HEARING_LISTING_DATE, HEARING_NUMBER, HEARING_STATUS_HEARD, HEARING_TYPE_JUDICIAL_HEARING, YES)
.withJudgment(JUDGMENT_HEARING_DATE, DATE_NOT_WITHIN_4WKS, DATE_NOT_WITHIN_4WKS, DYNAMIC_JUDGMENT_HEARING_LABEL)
.buildAsSubmitEvent(ACCEPTED_STATE);
}
private void assertCommonValues(HearingsToJudgmentsReportData reportData) {
assertNotNull(reportData);
assertEquals(TribunalOffice.NEWCASTLE.getOfficeName(), reportData.getReportSummary().getOffice());
}
}
|
3e16a05398b4c6ab69afbd57de9d512e6bc1e74a | 835 | java | Java | src/main/java/cc/niushuai/rjz/common/util/excel/ExcelAttr.java | niushuai233/rjz-springboot | 378ccbffc2b26f4aec7074de48a31259c239d044 | [
"Apache-2.0"
] | null | null | null | src/main/java/cc/niushuai/rjz/common/util/excel/ExcelAttr.java | niushuai233/rjz-springboot | 378ccbffc2b26f4aec7074de48a31259c239d044 | [
"Apache-2.0"
] | null | null | null | src/main/java/cc/niushuai/rjz/common/util/excel/ExcelAttr.java | niushuai233/rjz-springboot | 378ccbffc2b26f4aec7074de48a31259c239d044 | [
"Apache-2.0"
] | null | null | null | 16.7 | 71 | 0.588024 | 9,653 | package cc.niushuai.rjz.common.util.excel;
import java.io.Serializable;
/**
* @author ns
* @date 2019/12/12
*/
public class ExcelAttr implements Serializable {
private static final long serialVersionUID = -6209130033397718707L;
/**
* 标题名称
*/
private String title;
/**
* 属性字段名
*/
private String attrName;
/**
* 排序号
*/
private Integer order;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAttrName() {
return attrName;
}
public void setAttrName(String attrName) {
this.attrName = attrName;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
}
|
3e16a0b4de1ad925fa245ad5219a7530991b3cd2 | 6,801 | java | Java | src/main/java/org/rappsilber/fdr/entities/AbstractFDRElement.java | Rappsilber-Laboratory/xiFDR | c5ba6908eaf111dec2141ab40705e3173b8f4487 | [
"Apache-2.0"
] | 2 | 2020-07-02T17:27:24.000Z | 2021-02-16T00:30:29.000Z | src/main/java/org/rappsilber/fdr/entities/AbstractFDRElement.java | Rappsilber-Laboratory/xiFDR | c5ba6908eaf111dec2141ab40705e3173b8f4487 | [
"Apache-2.0"
] | 15 | 2016-09-13T16:33:56.000Z | 2021-07-23T15:57:59.000Z | src/main/java/org/rappsilber/fdr/entities/AbstractFDRElement.java | Rappsilber-Laboratory/xiFDR | c5ba6908eaf111dec2141ab40705e3173b8f4487 | [
"Apache-2.0"
] | 1 | 2017-03-14T11:34:26.000Z | 2017-03-14T11:34:26.000Z | 27.204 | 88 | 0.622408 | 9,654 | /*
* Copyright 2015 Lutz Fischer <lfischer at staffmail.ed.ac.uk>.
*
* 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.rappsilber.fdr.entities;
import java.util.Collection;
import java.util.HashSet;
import org.rappsilber.fdr.entities.PeptidePair;
import org.rappsilber.fdr.entities.Site;
import org.rappsilber.fdr.entities.ProteinGroup;
import org.rappsilber.utils.SelfAdd;
/**
*
* @author lfischer
*/
public abstract class AbstractFDRElement<T extends SelfAdd<T>> implements FDRSelfAdd<T>{
protected double m_higherFDR;
protected double m_lowerFDR;
/**
* The next Target-Decoy match with a lower FDR
*/
private AbstractFDRElement<T> m_lowerFDRTD;
/**
* The next Target-Decoy match with a higher FDR
*/
private AbstractFDRElement<T> m_HigherFDRTD;
protected double m_linkedSupport = 1;
protected HashSet<String> m_negativeGroups;
protected HashSet<String> m_positiveGroups;
private HashSet<String> m_additionalGroups = new HashSet<>();
private double m_pep;
public abstract Site getLinkSite1();
public abstract Site getLinkSite2();
/**
* @return the higherFDR
*/
public double getHigherFDR() {
return m_higherFDR;
}
/**
* @param higherFDR the higherFDR to set
*/
public void setHigherFDR(double higherFDR) {
this.m_higherFDR = higherFDR;
}
/**
* @return the m_linkedSupport
*/
public double getLinkedSupport() {
return m_linkedSupport;
}
/**
* @param linkedSupport the linkedSupport to set
*/
public void setLinkedSupport(double linkedSupport) {
this.m_linkedSupport = linkedSupport;
}
/**
* @return the lowerFDR
*/
public double getLowerFDR() {
return m_lowerFDR;
}
/**
* @param lowerFDR the lowerFDR to set
*/
public void setLowerFDR(double lowerFDR) {
this.m_lowerFDR = lowerFDR;
}
public abstract ProteinGroup getProteinGroup1();
public abstract ProteinGroup getProteinGroup2();
public boolean hasPositiveGrouping() {
return this.m_positiveGroups!=null;
}
public void setPositiveGrouping(String av) {
if (av == null) {
this.m_positiveGroups = null;
}else {
this.m_positiveGroups = new HashSet<String>(1);
this.m_positiveGroups.add(av);
}
}
public HashSet<String> getPositiveGrouping() {
return m_positiveGroups;
}
public void addPositiveGrouping(String av) {
if (this.m_positiveGroups == null)
this.m_positiveGroups = new HashSet<String>(1);
this.m_positiveGroups.add(av);
}
/**
* indicates this passed some form of Negative value that makes this
* inherently less likely to be true
*/
public boolean hasNegativeGrouping() {
return m_negativeGroups != null;
}
/**
* are all supporting PSMs "special" cases?
* @param specialcase
*/
public void setNegativeGrouping(String cause) {
if (cause == null) {
this.m_negativeGroups = null;
} else {
this.m_negativeGroups = new HashSet<>(1);
this.m_negativeGroups.add(cause);
}
}
public HashSet<String> getNegativeGrouping() {
return this.m_negativeGroups;
}
public void addNegativeGrouping(String cause) {
if (this.m_negativeGroups == null) {
this.m_negativeGroups = new HashSet<>(1);
}
this.m_negativeGroups.add(cause);
}
public void addFDRGroups(AbstractFDRElement e) {
if (this.m_negativeGroups != null) {
if (e.m_negativeGroups == null) {
this.m_negativeGroups = null;
} else {
m_negativeGroups.retainAll(e.m_negativeGroups);
}
}
if (e.hasPositiveGrouping()) {
if (this.m_positiveGroups == null) {
this.m_positiveGroups = e.getPositiveGrouping();
} else if (!this.m_positiveGroups.containsAll(e.getPositiveGrouping())) {
this.m_positiveGroups.addAll(e.getPositiveGrouping());
}
}
}
public abstract Collection<PeptidePair> getPeptidePairs();
/**
* @return the m_additionalGroups
*/
public HashSet<String> getAdditionalFDRGroups() {
return m_additionalGroups;
}
/**
* The next Target-Decoy match with a lower FDR
* @return the m_lowerTD
*/
public AbstractFDRElement<T> getLowerFDRTD() {
return m_lowerFDRTD;
}
/**
* The next Target-Decoy match with a lower FDR
* @param m_lowerTD the m_lowerTD to set
*/
public void setLowerFDRTD(AbstractFDRElement<T> TD) {
this.m_lowerFDRTD = TD;
}
/**
* The next Target-Decoy match with a higher FDR
* @return the m_higherTD
*/
public AbstractFDRElement<T> getHigherFDRTD() {
return m_HigherFDRTD;
}
/**
* The next Target-Decoy match with a higher FDR
* @param m_higherTD the m_higherTD to set
*/
public void setHigherFDRTD(AbstractFDRElement<T> TD) {
this.m_HigherFDRTD = TD;
}
public double getEstimatedFDR() {
double lowerFDRScore = this.getLowerFDRTD().getScore();
double higherFDRScore = this.getHigherFDRTD().getScore();
double lowerFDR = this.getLowerFDRTD().getFDR();
double higherFDR = this.getHigherFDRTD().getFDR();
double stepScore = lowerFDRScore - higherFDRScore;
double myStepScore = lowerFDRScore - getScore();
if (stepScore == 0) {
return lowerFDR + (higherFDR-lowerFDR)/2;
} else {
double stepScoreRatio = myStepScore/stepScore;
double stepFDR = higherFDR - lowerFDR;
double myStepFDR = stepFDR*stepScoreRatio;
return lowerFDR + myStepFDR;
}
}
public double getOriginalScore() {
return getScore();
}
@Override
public void setPEP(double pep) {
this.m_pep = pep;
}
@Override
public Double getPEP() {
return this.m_pep;
}
}
|
3e16a12e9edfc2f139901ae871a02ad741b479e4 | 4,044 | java | Java | bundles/org.aposin.gem.ui/src/org/aposin/gem/ui/part/listener/workflow/SessionWorkflowLauncherListener.java | aposin/gem | 0c07464ec4bbe7a837b620a229274a1f49f94910 | [
"Apache-2.0"
] | 1 | 2021-11-23T19:44:38.000Z | 2021-11-23T19:44:38.000Z | bundles/org.aposin.gem.ui/src/org/aposin/gem/ui/part/listener/workflow/SessionWorkflowLauncherListener.java | aposin/gem | 0c07464ec4bbe7a837b620a229274a1f49f94910 | [
"Apache-2.0"
] | 27 | 2021-07-16T13:31:50.000Z | 2022-03-09T08:09:22.000Z | bundles/org.aposin.gem.ui/src/org/aposin/gem/ui/part/listener/workflow/SessionWorkflowLauncherListener.java | aposin/gem | 0c07464ec4bbe7a837b620a229274a1f49f94910 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:27:49.000Z | 2021-09-13T11:27:49.000Z | 31.59375 | 297 | 0.655786 | 9,655 | /**
* Copyright 2020 Association for the promotion of open-source insurance software and for the establishment of open interface standards in the insurance industry (Verein zur Foerderung quelloffener Versicherungssoftware und Etablierung offener Schnittstellenstandards in der Versicherungsbranche)
*
* 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.aposin.gem.ui.part.listener.workflow;
import java.util.function.Function;
import org.aposin.gem.core.api.launcher.ILauncher;
import org.aposin.gem.core.api.workflow.WorkflowException;
import org.aposin.gem.ui.lifecycle.Session;
import org.aposin.gem.ui.part.listener.LauncherSelectionListener;
import org.eclipse.swt.events.SelectionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract selection listener which gets a launcher depending on
* some conditions and workflow finished hook.
*/
public abstract class SessionWorkflowLauncherListener<T> extends LauncherSelectionListener {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final Session session;
private final Function<Session, T> sessionObjectProvider;
private final Function<T, ILauncher> workflowFunction;
private T currentSessionObject;
/**
* Default constructor.
*
* @param sesion
* @param workflowFunction
*/
protected SessionWorkflowLauncherListener(final Session session,
final Function<Session, T> sessionObjectProvider,
final Function<T, ILauncher> workflowFunction) {
super(null);
this.session = session;
this.sessionObjectProvider = sessionObjectProvider;
this.workflowFunction = workflowFunction;
}
/**
* Gets the session for the workflow launcher.
*
* @return session.
*/
protected final Session getSession() {
return session;
}
@Override
public final ILauncher getLauncher() {
if (launcher == null) {
try {
launcher = getWorkflowLauncher();
} catch (final WorkflowException e) {
logger.warn("Ignored exception getting workflow launcher", e);
}
}
return launcher;
}
/**
* Gets the current session object used to get the launcher.
*/
public final T getCurrentSessionObject() {
return currentSessionObject;
}
/**
* Gets the workflow launcher.
*
* @return launcher.
* @throws WorkflowException if there is any problem.
*/
private final ILauncher getWorkflowLauncher() throws WorkflowException {
if (currentSessionObject == null) {
currentSessionObject = sessionObjectProvider.apply(session);
}
return currentSessionObject == null ? null : workflowFunction.apply(currentSessionObject);
}
/**
* Hook when the workflow have finished.
*/
public abstract void onWorkflowFinished();
/**
* {@inheritDoc}
*/
@Override
public final void widgetSelected(final SelectionEvent event) {
try {
super.widgetSelected(event);
} finally {
onWorkflowFinished();
refresh();
}
}
/**
* {@inheritDoc}
*/
@Override
public final void refresh() {
currentSessionObject = null;
launcher = null;
super.refresh();
}
}
|
3e16a1963b48653975d984dc55256567193ea11a | 1,189 | java | Java | apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/i18n/CommonMessageKey.java | AppSecAI-TEST/qalingo-engine | 7380084369034012d9ad6cb1ab4973ce7960aa2d | [
"Apache-2.0"
] | 321 | 2015-01-04T08:13:13.000Z | 2021-12-29T02:27:29.000Z | apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/i18n/CommonMessageKey.java | AppSecAI-TEST/qalingo-engine | 7380084369034012d9ad6cb1ab4973ce7960aa2d | [
"Apache-2.0"
] | 24 | 2021-04-02T13:21:00.000Z | 2022-02-10T09:22:15.000Z | apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/i18n/CommonMessageKey.java | Rostov1991/qalingo-engine | cd48ffe14fe2a6a14e3fbb777b3e2ce6a7454621 | [
"Apache-2.0"
] | 220 | 2015-01-04T08:04:53.000Z | 2022-01-25T06:46:44.000Z | 41.034483 | 93 | 0.75042 | 9,656 | /**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - lyhxr@example.com
*
*/
package org.hoteia.qalingo.core.i18n;
public class CommonMessageKey {
// SEO
public static final String SEO_META_AUTHOR = "meta_author";
public static final String SEO_META_KEYWORDS = "meta_keywords";
public static final String SEO_META_DESCRIPTION = "meta_description";
public static final String SEO_PAGE_TITLE_PREFIX = "page_title.";
public static final String SEO_PAGE_TITLE_SITE_NAME = "page_title_site_name";
public static final String PAGE_META_OG_TITLE = "page_meta_og_default_title";
public static final String PAGE_META_OG_DESCRIPTION = "page_meta_og_default_description";
public static final String PAGE_META_OG_IMAGE = "page_meta_og_default_image";
public static final String MAIN_CONTENT_TITLE_PREFIX = "main_content_title_";
public static final String MAIN_CONTENT_TEXT = "content_text";
} |
3e16a33e836f56d506fe4784a8a821838aa10bfe | 729 | java | Java | managed/src/main/java/com/yugabyte/yw/forms/XClusterConfigCreateFormData.java | praveenmunagapati/yugabyte-db | 1b34db79446ecf2d6acc583a6156a6047198c2a0 | [
"Apache-2.0",
"CC0-1.0"
] | 3,702 | 2019-09-17T13:49:56.000Z | 2022-03-31T21:50:59.000Z | managed/src/main/java/com/yugabyte/yw/forms/XClusterConfigCreateFormData.java | praveenmunagapati/yugabyte-db | 1b34db79446ecf2d6acc583a6156a6047198c2a0 | [
"Apache-2.0",
"CC0-1.0"
] | 9,291 | 2019-09-16T21:47:07.000Z | 2022-03-31T23:52:28.000Z | managed/src/main/java/com/yugabyte/yw/forms/XClusterConfigCreateFormData.java | praveenmunagapati/yugabyte-db | 1b34db79446ecf2d6acc583a6156a6047198c2a0 | [
"Apache-2.0",
"CC0-1.0"
] | 673 | 2019-09-16T21:27:53.000Z | 2022-03-31T22:23:59.000Z | 28.038462 | 73 | 0.766804 | 9,657 | package com.yugabyte.yw.forms;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Set;
import java.util.UUID;
@ApiModel(description = "xcluster create form")
public class XClusterConfigCreateFormData {
@ApiModelProperty(value = "Name", required = true)
public String name;
@ApiModelProperty(value = "Source Universe UUID", required = true)
public UUID sourceUniverseUUID;
@ApiModelProperty(value = "Target Universe UUID", required = true)
public UUID targetUniverseUUID;
@ApiModelProperty(value = "Source Universe table IDs", required = true)
public Set<String> tables;
@ApiModelProperty(value = "Bootstrap IDs")
public Set<String> bootstrapIds;
}
|
3e16a405360ecf659599ddf29aef539072d461eb | 5,308 | java | Java | java-dev-journal/Java/data-structure-with-java/linkedList/singly/MySinglyLinkedList.java | kdheeraj1502/code-examples | e93ead8824a4f1ed51e6a2e25cbd7613b98fe7b1 | [
"MIT"
] | null | null | null | java-dev-journal/Java/data-structure-with-java/linkedList/singly/MySinglyLinkedList.java | kdheeraj1502/code-examples | e93ead8824a4f1ed51e6a2e25cbd7613b98fe7b1 | [
"MIT"
] | null | null | null | java-dev-journal/Java/data-structure-with-java/linkedList/singly/MySinglyLinkedList.java | kdheeraj1502/code-examples | e93ead8824a4f1ed51e6a2e25cbd7613b98fe7b1 | [
"MIT"
] | null | null | null | 28.847826 | 126 | 0.511492 | 9,658 | package linkedList.singly;
public class MySinglyLinkedList {
/**
* Head of the LinkedList
*/
public Node head;
/**
* This is a method static class defining a LinkedList Node.
* since it is static, main() method can access it
*/
public static class Node {
public int data;
public Node next;
Node(int data)
{
this.data = data;
next = null;
}
}
/**
* Insert a node to the given LinkedList
* This method will insert at head if the list is empty
* Or else, it will inset at last
* @param list - LinkedList
* @param data - node data
*/
public static void insert(MySinglyLinkedList list, int data)
{
Node node = new Node(data);
node.next = null;
// If the LinkedList is empty, then make the new node as head.
if (list.head == null) {
list.head = node;
}
else {// else traverse the list till the last node and insert at the last.
Node last = list.head;
while (last.next != null) {
last = last.next;
}
// Insert the new node at last node
last.next = node;
}
}
/**
* This method will insert the new node after any given node.
* @param previousNode
* @param dataToBeInserted
*/
public void insertAfter(Node previousNode, int dataToBeInserted)
{
if (previousNode == null)
{
System.out.println("The given previous node cannot be null");
return;
}
Node newNode = new Node(dataToBeInserted);
newNode.next = previousNode.next;
previousNode.next = newNode;
}
/**
* Delete a node by given data at the node.
* @param list - LinkedList
* @param data - node data
*/
public void deleteByKey(MySinglyLinkedList list, int data)
{
System.out.println("trying to delete node with data:" + data);
// Store head node
Node currentNode = list.head;
Node prev = null;
if(currentNode!=null){
if(currentNode.data==data){
list.head = currentNode.next; // Changed head
System.out.println("element " + data + " has been deleted");
}else{
while (currentNode != null && currentNode.data != data) {
prev = currentNode;
currentNode = currentNode.next;
}
if (currentNode != null) {
prev.next = currentNode.next;
System.out.println("element " + data + " has been deleted");
}else{
System.out.println("no node found with data:" + data);
}
}
}
}
/**
* Delete a node by given position.
* @param list - LinkedList
* @param pos - position of the node
*/
public void deleteAtPosition(MySinglyLinkedList list, int pos)
{
System.out.println("trying to delete node at position:"+ pos);
Node currentNode = list.head;
Node prev = null;
int counter = 0;
if(currentNode!=null){
if(pos==0){
list.head = currentNode.next;
System.out.println("element at position" + pos + " has been deleted");
}else{
// Count for the pos to be deleted, keep track of the previous node as it is needed to change currentNode.next
while (currentNode != null) {
if (counter == pos) {
prev.next = currentNode.next;
System.out.println("element at " + pos + " has been deleted");
break;
} else {
prev = currentNode;
currentNode = currentNode.next;
counter++;
}
}
}
}
if(pos>counter){
System.out.println("no node found at position:"+ pos + " ,as it greater than the size of the list");
}
}
/**
* Recursive Searching
* find a node with given data in the LinkedList
* @param head - head node
* @param data - node data
* @return - boolean value (true/false)
*/
public boolean search(Node head, int data)
{
if (head == null)
return false;
if (head.data == data)
return true;
return search(head.next, data);
}
/**
* Traverse and print the list
* @param list
*/
public void traverseAndPrintList(MySinglyLinkedList list)
{
Node currNode = list.head;
System.out.print("LinkedList: ");
while (currNode != null) {
System.out.print(currNode.data + " ");
currNode = currNode.next;
}
System.out.println();
}
/**
*
* @param list
* @return the size of the list
*/
public int size(MySinglyLinkedList list){
int count=0;
Node currNode = list.head;
while (currNode != null) {
count++;
currNode = currNode.next;
}
return count;
}
}
|
3e16a48b2d27b96a7407bf2f8b568f5726415a34 | 3,521 | java | Java | server/src/main/java/be/sgerard/i18n/model/i18n/dto/translation/text/TextTranslationResponseDto.java | sebge2/github-oauth | 7d72d2c9aa38906ed9267e2c7f243856ff19362c | [
"Apache-2.0"
] | null | null | null | server/src/main/java/be/sgerard/i18n/model/i18n/dto/translation/text/TextTranslationResponseDto.java | sebge2/github-oauth | 7d72d2c9aa38906ed9267e2c7f243856ff19362c | [
"Apache-2.0"
] | null | null | null | server/src/main/java/be/sgerard/i18n/model/i18n/dto/translation/text/TextTranslationResponseDto.java | sebge2/github-oauth | 7d72d2c9aa38906ed9267e2c7f243856ff19362c | [
"Apache-2.0"
] | null | null | null | 38.271739 | 147 | 0.650383 | 9,659 | package be.sgerard.i18n.model.i18n.dto.translation.text;
import be.sgerard.i18n.model.i18n.dto.translate.ExternalTranslationSourceDto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import static java.util.Collections.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
/**
* Translations of a text.
*/
@Schema(name = "TextTranslationResponse", description = "Translations of a text. This text may have been translated by different sources.")
@Getter
public class TextTranslationResponseDto {
/**
* Returns a new {@link Collector collector} for {@link TextTranslationResponseDto text translation response}.
*/
public static Collector<TextTranslationResponseDto, List<TextTranslationResponseDto>, TextTranslationResponseDto> toTextTranslationResponse() {
return new Collector<>() {
@Override
public Supplier<List<TextTranslationResponseDto>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<TextTranslationResponseDto>, TextTranslationResponseDto> accumulator() {
return List::add;
}
@Override
public BinaryOperator<List<TextTranslationResponseDto>> combiner() {
return (first, second) -> {
first.addAll(second);
return first;
};
}
@Override
public Function<List<TextTranslationResponseDto>, TextTranslationResponseDto> finisher() {
return (list) -> new TextTranslationResponseDto(
list.stream()
.map(TextTranslationResponseDto::getExternalSources)
.flatMap(Collection::stream)
.collect(toSet()),
list.stream()
.map(TextTranslationResponseDto::getTranslations)
.flatMap(Collection::stream)
.collect(toList())
);
}
@Override
public Set<Characteristics> characteristics() {
return emptySet();
}
};
}
@Schema(description = "Definition of external translation sources.")
private final Collection<ExternalTranslationSourceDto> externalSources;
@Schema(description = "Available translations.")
private final List<TextTranslationDto> translations;
@JsonCreator
public TextTranslationResponseDto(@JsonProperty("externalSources") Collection<ExternalTranslationSourceDto> externalSources,
@JsonProperty("translations") List<TextTranslationDto> translations) {
this.externalSources = externalSources;
this.translations = translations;
}
public TextTranslationResponseDto(ExternalTranslationSourceDto externalSource, TextTranslationDto translation) {
this(singleton(externalSource), singletonList(translation));
}
}
|
3e16a5297964270549170231a04c9a87dc6c3a01 | 6,578 | java | Java | luminescence_src/WayofTime/luminescence/client/renderer/model/ModelMuxFluidBlock.java | WayofTime/LuminiferousTransmission | eafa3533780307418bc5adc3e2843d69c7df87d4 | [
"CC-BY-4.0"
] | 1 | 2015-06-07T12:05:17.000Z | 2015-06-07T12:05:17.000Z | luminescence_src/WayofTime/luminescence/client/renderer/model/ModelMuxFluidBlock.java | WayofTime/LuminiferousTransmission | eafa3533780307418bc5adc3e2843d69c7df87d4 | [
"CC-BY-4.0"
] | null | null | null | luminescence_src/WayofTime/luminescence/client/renderer/model/ModelMuxFluidBlock.java | WayofTime/LuminiferousTransmission | eafa3533780307418bc5adc3e2843d69c7df87d4 | [
"CC-BY-4.0"
] | null | null | null | 34.439791 | 139 | 0.610672 | 9,660 | package WayofTime.luminescence.client.renderer.model;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraftforge.common.ForgeDirection;
public class ModelMuxFluidBlock extends ModelBase
{
//fields
ModelRenderer lens1;
ModelRenderer lens2;
ModelRenderer lens3;
ModelRenderer lens4;
ModelRenderer lens5;
ModelRenderer lens6;
ModelRenderer core;
ModelRenderer Shape2;
ModelRenderer Shape3;
ModelRenderer Shape4;
ModelRenderer Shape5;
ModelRenderer Shape6;
ModelRenderer Shape7;
ModelRenderer Shape8;
ModelRenderer Shape9;
ModelRenderer Shape10;
ModelRenderer Shape11;
ModelRenderer Shape12;
ModelRenderer Shape13;
public ModelMuxFluidBlock()
{
textureWidth = 64;
textureHeight = 64;
lens1 = new ModelRenderer(this, 0, 0);
lens1.addBox(-4F, -4F, -6F, 8, 8, 1);
lens1.setRotationPoint(0F, 16F, 0F);
lens1.setTextureSize(64, 64);
lens1.mirror = true;
setRotation(lens1, 0F, 0F, 0F);
lens2 = new ModelRenderer(this, 0, 0);
lens2.addBox(-4F, -4F, 5F, 8, 8, 1);
lens2.setRotationPoint(0F, 16F, 0F);
lens2.setTextureSize(64, 64);
lens2.mirror = true;
setRotation(lens2, 0F, 0F, 0F);
lens3 = new ModelRenderer(this, 0, 10);
lens3.addBox(-4F, -6F, -4F, 8, 1, 8);
lens3.setRotationPoint(0F, 16F, 0F);
lens3.setTextureSize(64, 64);
lens3.mirror = true;
setRotation(lens3, 0F, 0F, 0F);
lens4 = new ModelRenderer(this, 0, 10);
lens4.addBox(-4F, 5F, -4F, 8, 1, 8);
lens4.setRotationPoint(0F, 16F, 0F);
lens4.setTextureSize(64, 64);
lens4.mirror = true;
setRotation(lens4, 0F, 0F, 0F);
lens5 = new ModelRenderer(this, 0, 20);
lens5.addBox(5F, -4F, -4F, 1, 8, 8);
lens5.setRotationPoint(0F, 16F, 0F);
lens5.setTextureSize(64, 64);
lens5.mirror = true;
setRotation(lens5, 0F, 0F, 0F);
lens6 = new ModelRenderer(this, 0, 20);
lens6.addBox(-6F, -4F, -4F, 1, 8, 8);
lens6.setRotationPoint(0F, 16F, 0F);
lens6.setTextureSize(64, 64);
lens6.mirror = true;
setRotation(lens6, 0F, 0F, 0F);
core = new ModelRenderer(this, 0, 37);
core.addBox(-2F, -2F, -2F, 4, 4, 4);
core.setRotationPoint(0F, 16F, 0F);
core.setTextureSize(64, 64);
core.mirror = true;
setRotation(core, 0.7853982F, 0.7853982F, 0.7853982F);
Shape2 = new ModelRenderer(this, 20, 0);
Shape2.addBox(3F, -1F, -5F, 2, 2, 2);
Shape2.setRotationPoint(0F, 16F, 0F);
Shape2.setTextureSize(64, 64);
Shape2.mirror = true;
setRotation(Shape2, 0F, 0F, 0F);
Shape3 = new ModelRenderer(this, 20, 0);
Shape3.addBox(3F, -1F, 3F, 2, 2, 2);
Shape3.setRotationPoint(0F, 16F, 0F);
Shape3.setTextureSize(64, 64);
Shape3.mirror = true;
setRotation(Shape3, 0F, 0F, 0F);
Shape4 = new ModelRenderer(this, 20, 0);
Shape4.addBox(-5F, -1F, -5F, 2, 2, 2);
Shape4.setRotationPoint(0F, 16F, 0F);
Shape4.setTextureSize(64, 64);
Shape4.mirror = true;
setRotation(Shape4, 0F, 0F, 0F);
Shape5 = new ModelRenderer(this, 20, 0);
Shape5.addBox(-5F, -1F, 3F, 2, 2, 2);
Shape5.setRotationPoint(0F, 16F, 0F);
Shape5.setTextureSize(64, 64);
Shape5.mirror = true;
setRotation(Shape5, 0F, 0F, 0F);
Shape6 = new ModelRenderer(this, 20, 0);
Shape6.addBox(-1F, -5F, -5F, 2, 2, 2);
Shape6.setRotationPoint(0F, 16F, 0F);
Shape6.setTextureSize(64, 64);
Shape6.mirror = true;
setRotation(Shape6, 0F, 0F, 0F);
Shape7 = new ModelRenderer(this, 20, 0);
Shape7.addBox(-1F, -5F, 3F, 2, 2, 2);
Shape7.setRotationPoint(0F, 16F, 0F);
Shape7.setTextureSize(64, 64);
Shape7.mirror = true;
setRotation(Shape7, 0F, 0F, 0F);
Shape8 = new ModelRenderer(this, 20, 0);
Shape8.addBox(-5F, -5F, -1F, 2, 2, 2);
Shape8.setRotationPoint(0F, 16F, 0F);
Shape8.setTextureSize(64, 64);
Shape8.mirror = true;
setRotation(Shape8, 0F, 0F, 0F);
Shape9 = new ModelRenderer(this, 20, 0);
Shape9.addBox(3F, -5F, -1F, 2, 2, 2);
Shape9.setRotationPoint(0F, 16F, 0F);
Shape9.setTextureSize(64, 64);
Shape9.mirror = true;
setRotation(Shape9, 0F, 0F, 0F);
Shape10 = new ModelRenderer(this, 20, 0);
Shape10.addBox(-1F, 3F, 3F, 2, 2, 2);
Shape10.setRotationPoint(0F, 16F, 0F);
Shape10.setTextureSize(64, 64);
Shape10.mirror = true;
setRotation(Shape10, 0F, 0F, 0F);
Shape11 = new ModelRenderer(this, 20, 0);
Shape11.addBox(-1F, 3F, -5F, 2, 2, 2);
Shape11.setRotationPoint(0F, 16F, 0F);
Shape11.setTextureSize(64, 64);
Shape11.mirror = true;
setRotation(Shape11, 0F, 0F, 0F);
Shape12 = new ModelRenderer(this, 20, 0);
Shape12.addBox(3F, 3F, -1F, 2, 2, 2);
Shape12.setRotationPoint(0F, 16F, 0F);
Shape12.setTextureSize(64, 64);
Shape12.mirror = true;
setRotation(Shape12, 0F, 0F, 0F);
Shape13 = new ModelRenderer(this, 20, 0);
Shape13.addBox(-5F, 3F, -1F, 2, 2, 2);
Shape13.setRotationPoint(0F, 16F, 0F);
Shape13.setTextureSize(64, 64);
Shape13.mirror = true;
setRotation(Shape13, 0F, 0F, 0F);
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, ForgeDirection input, ForgeDirection output)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
lens1.render(f5);
lens2.render(f5);
lens3.render(f5);
lens4.render(f5);
lens5.render(f5);
lens6.render(f5);
core.render(f5);
Shape2.render(f5);
Shape3.render(f5);
Shape4.render(f5);
Shape5.render(f5);
Shape6.render(f5);
Shape7.render(f5);
Shape8.render(f5);
Shape9.render(f5);
Shape10.render(f5);
Shape11.render(f5);
Shape12.render(f5);
Shape13.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity)
{
super.setRotationAngles(f, f1, f2, f3, f4, f5, entity);
}
}
|
3e16a5a675b7aaf281028955268ce02c2630d6b1 | 2,023 | java | Java | starshield/src/main/java/com/jdcloud/sdk/service/starshield/model/ListAvailableCustomPagesResult.java | jdcloud-apigateway/jdcloud-sdk-java | 62e0924aa4b7f51fc8d73404bdc7aa38d820732e | [
"Apache-2.0"
] | 38 | 2018-04-19T09:53:59.000Z | 2021-11-08T12:52:15.000Z | starshield/src/main/java/com/jdcloud/sdk/service/starshield/model/ListAvailableCustomPagesResult.java | jdcloud-apigateway/jdcloud-sdk-java | 62e0924aa4b7f51fc8d73404bdc7aa38d820732e | [
"Apache-2.0"
] | 22 | 2018-04-24T12:17:20.000Z | 2022-03-31T10:39:18.000Z | starshield/src/main/java/com/jdcloud/sdk/service/starshield/model/ListAvailableCustomPagesResult.java | jdcloud-apigateway/jdcloud-sdk-java | 62e0924aa4b7f51fc8d73404bdc7aa38d820732e | [
"Apache-2.0"
] | 53 | 2018-04-19T10:48:05.000Z | 2022-03-16T09:15:16.000Z | 23.252874 | 99 | 0.658428 | 9,661 | /*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Custom Pages for a Zone
* Custom pages associated with a zone
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.starshield.model;
import java.util.List;
import java.util.ArrayList;
import com.jdcloud.sdk.service.starshield.model.CustomPage;
import com.jdcloud.sdk.service.JdcloudResult;
/**
* 域可以使用的可用自定义页面列表
*/
public class ListAvailableCustomPagesResult extends JdcloudResult implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* dataList
*/
private List<CustomPage> dataList;
/**
* get dataList
*
* @return
*/
public List<CustomPage> getDataList() {
return dataList;
}
/**
* set dataList
*
* @param dataList
*/
public void setDataList(List<CustomPage> dataList) {
this.dataList = dataList;
}
/**
* set dataList
*
* @param dataList
*/
public ListAvailableCustomPagesResult dataList(List<CustomPage> dataList) {
this.dataList = dataList;
return this;
}
/**
* add item to dataList
*
* @param dataList
*/
public void addDataList(CustomPage dataList) {
if (this.dataList == null) {
this.dataList = new ArrayList<>();
}
this.dataList.add(dataList);
}
} |
3e16a61904a7ab30dd9650bbc2e764f004ebf05c | 2,870 | java | Java | order-domain/src/main/java/com/demo/order/domain/service/OrderService.java | AnthonyRsw/order-microservice | b862b900a88cdd84b8cd6751874f464e9cb1fabd | [
"Apache-2.0"
] | null | null | null | order-domain/src/main/java/com/demo/order/domain/service/OrderService.java | AnthonyRsw/order-microservice | b862b900a88cdd84b8cd6751874f464e9cb1fabd | [
"Apache-2.0"
] | null | null | null | order-domain/src/main/java/com/demo/order/domain/service/OrderService.java | AnthonyRsw/order-microservice | b862b900a88cdd84b8cd6751874f464e9cb1fabd | [
"Apache-2.0"
] | null | null | null | 38.783784 | 117 | 0.68223 | 9,662 | package com.demo.order.domain.service;
import com.demo.order.domain.entity.Order;
import com.demo.order.domain.repository.OrderRepository;
import com.demo.order.domain.util.CommonUtils;
import com.demo.order.object.OrderQo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class OrderService {
@Autowired
private OrderRepository orderRepository;
public Order findOne(Long id){
return orderRepository.findOne(id);
}
public void save(Order order){
orderRepository.save(order);
}
public void delete(Long id){
orderRepository.delete(id);
}
public Page<Order> findAll(OrderQo orderQo){
Sort sort = new Sort(Sort.Direction.DESC, "created");
Pageable pageable = new PageRequest(orderQo.getPage(), orderQo.getSize(), sort);
return orderRepository.findAll(new Specification<Order>(){
@Override
public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicatesList = new ArrayList<Predicate>();
if(CommonUtils.isNotNull(orderQo.getUserid())) {
predicatesList.add(criteriaBuilder.equal(root.get("userid"), orderQo.getUserid()));
}
if(CommonUtils.isNotNull(orderQo.getMerchantid())) {
predicatesList.add(criteriaBuilder.equal(root.get("merchantid"), orderQo.getMerchantid()));
}
if(CommonUtils.isNotNull(orderQo.getOrderNo())) {
predicatesList.add(criteriaBuilder.equal(root.get("orderNo"), orderQo.getOrderNo()));
}
if(CommonUtils.isNotNull(orderQo.getStatus())) {
predicatesList.add(criteriaBuilder.equal(root.get("status"), orderQo.getStatus()));
}
if(CommonUtils.isNotNull(orderQo.getCreated())){
predicatesList.add(criteriaBuilder.greaterThan(root.get("created"), orderQo.getCreated()));
}
query.where(predicatesList.toArray(new Predicate[predicatesList.size()]));
return query.getRestriction();
}
}, pageable);
}
}
|
3e16a6b531f2c938bf9053f656ec224a973725d1 | 4,486 | java | Java | redis/redis-checker/src/test/java/com/ctrip/xpipe/redis/checker/healthcheck/actions/redismaster/RedisWrongSlaveMonitorTest.java | z131031231/x-pipe | b175922e3cd4fb77bad4f821c9cf7f7c4e67731e | [
"Apache-2.0"
] | 1 | 2022-03-16T01:40:40.000Z | 2022-03-16T01:40:40.000Z | redis/redis-checker/src/test/java/com/ctrip/xpipe/redis/checker/healthcheck/actions/redismaster/RedisWrongSlaveMonitorTest.java | jiao-duan/x-pipe | b31d9712a0db529f854716e777d70db9bd220938 | [
"Apache-2.0"
] | null | null | null | redis/redis-checker/src/test/java/com/ctrip/xpipe/redis/checker/healthcheck/actions/redismaster/RedisWrongSlaveMonitorTest.java | jiao-duan/x-pipe | b31d9712a0db529f854716e777d70db9bd220938 | [
"Apache-2.0"
] | null | null | null | 38.672414 | 122 | 0.728043 | 9,663 | package com.ctrip.xpipe.redis.checker.healthcheck.actions.redismaster;
import com.ctrip.xpipe.api.server.Server;
import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.redis.checker.AbstractCheckerTest;
import com.ctrip.xpipe.redis.checker.alert.ALERT_TYPE;
import com.ctrip.xpipe.redis.checker.alert.AlertManager;
import com.ctrip.xpipe.redis.checker.healthcheck.actions.ping.PingService;
import com.ctrip.xpipe.redis.core.entity.RedisMeta;
import com.ctrip.xpipe.redis.core.meta.MetaCache;
import com.ctrip.xpipe.redis.core.protocal.pojo.MasterRole;
import com.ctrip.xpipe.redis.core.protocal.pojo.Role;
import com.ctrip.xpipe.redis.core.protocal.pojo.SlaveRole;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collections;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.when;
/**
* @author lishanglin
* date 2021/11/19
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class RedisWrongSlaveMonitorTest extends AbstractCheckerTest {
@InjectMocks
private RedisWrongSlaveMonitor wrongSlaveMonitor;
@Mock
private MetaCache metaCache;
@Mock
private AlertManager alertManager;
@Mock
private PingService pingService;
private int masterPort = 6379;
private int slavePort = 7379;
@Mock
private MasterRole masterRole;
@Mock
private SlaveRole slaveRole;
@Before
public void setupRedisWrongSlaveMonitorTest() {
when(slaveRole.getServerRole()).thenReturn(Server.SERVER_ROLE.SLAVE);
when(masterRole.getServerRole()).thenReturn(Server.SERVER_ROLE.MASTER);
when(masterRole.getSlaveHostPorts()).thenReturn(Collections.singletonList(new HostPort("127.0.0.1", slavePort)));
when(metaCache.getRedisOfDcClusterShard(anyString(), anyString(), anyString()))
.thenReturn(Arrays.asList(new RedisMeta().setIp("127.0.0.1").setPort(masterPort),
new RedisMeta().setIp("127.0.0.1").setPort(slavePort).setMaster("127.0.0.1:"+masterPort)));
when(pingService.isRedisAlive(any())).thenReturn(true);
}
@Test
public void testWrongSlave_doAlert() throws Exception {
when(masterRole.getSlaveHostPorts()).thenReturn(Collections.emptyList());
wrongSlaveMonitor.onAction(mockRoleContext(masterRole));
Mockito.verify(alertManager)
.alert(anyString(), anyString(), anyString(),
eq(new HostPort("127.0.0.1", slavePort)),
eq(ALERT_TYPE.REPL_WRONG_SLAVE), anyString());
}
@Test
public void testSlaveDown_doNothing() throws Exception {
when(pingService.isRedisAlive(any())).thenReturn(false);
when(masterRole.getSlaveHostPorts()).thenReturn(Collections.emptyList());
wrongSlaveMonitor.onAction(mockRoleContext(masterRole));
Mockito.verify(alertManager, never()).alert(anyString(), anyString(), anyString(), any(), any(), anyString());
}
@Test
public void testSlaveRole_doNothing() throws Exception {
when(masterRole.getSlaveHostPorts()).thenReturn(Collections.emptyList());
wrongSlaveMonitor.onAction(mockRoleContext(slaveRole));
Mockito.verify(alertManager, never()).alert(anyString(), anyString(), anyString(), any(), any(), anyString());
}
@Test
public void testRoleFail_doNothing() throws Exception {
wrongSlaveMonitor.onAction(mockFailRoleContext());
Mockito.verify(alertManager, never()).alert(anyString(), anyString(), anyString(), any(), any(), anyString());
}
@Test
public void testSlaveAllRight_doNothing() throws Exception {
wrongSlaveMonitor.onAction(mockRoleContext(masterRole));
Mockito.verify(alertManager, never()).alert(anyString(), anyString(), anyString(), any(), any(), anyString());
}
private RedisMasterActionContext mockFailRoleContext() throws Exception {
return new RedisMasterActionContext(newRandomRedisHealthCheckInstance(masterPort), new Throwable("do role fail"));
}
private RedisMasterActionContext mockRoleContext(Role role) throws Exception {
return new RedisMasterActionContext(newRandomRedisHealthCheckInstance(masterPort), role);
}
}
|
3e16a6c8b1ca03f841644b1dcdcf3e84a8ba6e81 | 27,383 | java | Java | java/com/sscommu/pokeumcho/TradeMainFragment.java | PoKeumCho/SScommu | 67a0e1cb452e07b39d02a8db2ed08342c9da874d | [
"Apache-2.0"
] | null | null | null | java/com/sscommu/pokeumcho/TradeMainFragment.java | PoKeumCho/SScommu | 67a0e1cb452e07b39d02a8db2ed08342c9da874d | [
"Apache-2.0"
] | 4 | 2022-01-29T04:52:45.000Z | 2022-02-05T06:38:20.000Z | java/com/sscommu/pokeumcho/TradeMainFragment.java | PoKeumCho/SScommu | 67a0e1cb452e07b39d02a8db2ed08342c9da874d | [
"Apache-2.0"
] | null | null | null | 34.100872 | 134 | 0.59515 | 9,664 | package com.sscommu.pokeumcho;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class TradeMainFragment extends Fragment
implements SwipeRefreshLayout.OnRefreshListener,
View.OnClickListener, onKeyBackPressedListener,
EndlessNestedScrollListener {
private final int MAX_DISPLAY = 30; // 출력 개수
private String mUserId;
private ArrayList<Trade> mTradeList; // Http 통신으로 받아온 데이터
private ArrayList<Trade> mSearchResultTradeList; // 검색 요건에 해당하는 데이터
private ArrayList<Trade> mDisplayTradeList; // 사용자 UI에 띄울 데이터
private int mSelectedCampus;
private int mSelectedCategory;
private String mSearch;
private LinearLayout myArticleTrade; // 내 판매 글 clickable layout
private LinearLayout writeArticleTrade; // 중고거래 글쓰기 clickable layout
private Spinner campusSpinner;
private Spinner categorySpinner;
private String[] mCategory;
private boolean mIsSearchActivate;
private Button btnSearchActivate;
private EditText editTextSearch;
private RecyclerView recyclerView;
private TradeAdapter mTradeAdapter;
private TextView noNetworkTxt;
private FloatingActionButton fab;
private SwipeRefreshLayout refreshLayout;
private EndlessNestedScrollView endlessNestedScrollView;
private ArrayList<AsyncTask> mAsyncTaskList;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mEditor;
private int mSelectedTradeIndex;
ActivityResultLauncher<Intent> mPostCheckRemovedLauncher;
ActivityResultLauncher<Intent> mPostCheckAddLauncher;
ActivityResultLauncher<Intent> mPostCheckChangeLauncher;
private boolean mIsActiveFragmentMode;
private boolean mIsPostOnCreateView;
private boolean mIsPostLauncher;
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) { /* Do when hidden */
mIsActiveFragmentMode = false;
/** onCreateView() 보다 먼저 실행되는 경우에 대비한다. */
if (mIsPostOnCreateView) {
if (mIsSearchActivate) { searchDeactivate(); }
mSelectedCampus = 0;
mSelectedCategory = 0;
campusSpinner.setSelection(mSelectedCampus);
categorySpinner.setSelection(mSelectedCategory);
clearTask();
mSearchResultTradeList.clear();
mDisplayTradeList.clear();
}
} else { /* Do when show */
mIsActiveFragmentMode = true;
Reselect();
endlessNestedScrollView.smoothScrollTo(0,0);
}
}
@Override
public void onResume() {
super.onResume();
if (mIsActiveFragmentMode && !mIsPostLauncher) { resumeTask(); }
if (mIsPostLauncher) { mIsPostLauncher = false; }
}
@Override
public void onStop() {
super.onStop();
if (mIsActiveFragmentMode) { clearTask(); }
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
// Fragment 에서 Back key Event 처리
((MainActivity)getActivity()).setOnKeyBackPressedListener(this);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// default value
mSelectedCampus = 0;
mSelectedCategory = 0;
mSearch = "";
mIsSearchActivate = false;
mIsActiveFragmentMode = false;
mIsPostOnCreateView = false;
mIsPostLauncher = false;
setCategoryArray();
/**
* TradeMainFragment --> ViewTradeActivity 이동 후,
* 해당 데이터가 삭제된 경우 mDisplayTradeList 를 수정한다.
*/
mPrefs = getActivity().getSharedPreferences("SScommu", Context.MODE_PRIVATE);
mEditor = mPrefs.edit();
mPostCheckRemovedLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_CANCELED) {
if (mPrefs.getBoolean("TRADE_REMOVED", false)) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"게시물이 존재하지 않거나 삭제되었습니다.",
Snackbar.LENGTH_SHORT).show();
Trade removedTrade = mDisplayTradeList.get(mSelectedTradeIndex);
mTradeList.remove(removedTrade);
mSearchResultTradeList.remove(removedTrade);
mDisplayTradeList.remove(mSelectedTradeIndex);
mTradeAdapter.notifyDataSetChanged();
} else { resumeTask(); }
mEditor.putBoolean("TRADE_REMOVED", false).commit();
}
}
});
/** TradeMainFragment --> EditTradeActivity 이동 후, 데이터가 추가된 경우 */
mPostCheckAddLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_CANCELED) {
if (mPrefs.getBoolean("TRADE_ADD_SUCCESS", false)) {
tradeAddProcess();
Reselect();
} else { resumeTask(); }
mEditor.putBoolean("TRADE_ADD_SUCCESS", false).commit();
}
}
});
/** TradeMainFragment --> MyTradeArticleActivity 이동 후, 데이터가 변경된 경우 */
mPostCheckChangeLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_CANCELED) {
if (mPrefs.getBoolean("TRADE_CHANGED", false)) {
notifyChangeNotCommitted();
}
// 중간에 이미지 로드를 중단한 경우 처리
resumeTask();
mEditor.putBoolean("TRADE_CHANGED", false).commit();
}
}
});
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
// Data which sent from activity
mUserId = getArguments().getString("USER_ID");
View view = inflater.inflate(R.layout.content_main_trade,
container, false);
myArticleTrade = view.findViewById(R.id.myArticleTrade);
writeArticleTrade = view.findViewById(R.id.writeArticleTrade);
campusSpinner = view.findViewById(R.id.campusSpinner);
categorySpinner = view.findViewById(R.id.categorySpinner);
btnSearchActivate = view.findViewById(R.id.btnSearchActivate);
editTextSearch = view.findViewById(R.id.editTextSearch);
recyclerView = view.findViewById(R.id.recyclerView);
fab = view.findViewById(R.id.fab);
refreshLayout = view.findViewById(R.id.refreshLayout);
noNetworkTxt = view.findViewById(R.id.noNetworkTxt);
endlessNestedScrollView = view.findViewById(R.id.endlessNestedScrollView);
endlessNestedScrollView.setScrollViewListener(this);
myArticleTrade.setOnClickListener(this);
writeArticleTrade.setOnClickListener(this);
btnSearchActivate.setOnClickListener(this);
fab.setOnClickListener(this);
/**
* To make keyboard enter button say "Search" and handle its click
* [참고] https://stackoverflow.com/questions/3205339/android-how-to-make-keyboard-enter-button-say-search-and-handle-its-click
*/
editTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
// RecyclerView Pull-To-Refresh
refreshLayout.setOnRefreshListener(this);
setSpinner();
mTradeList = new ArrayList<Trade>();
mSearchResultTradeList = new ArrayList<Trade>();
mDisplayTradeList = new ArrayList<Trade>();
loadTradeList();
setSelectedTradeList();
setRecyclerView();
mIsPostOnCreateView = true;
return view;
}
/** EndlessNestedScrollView Scroll Bottom Detect */
@Override
public void onScrollChanged(
EndlessNestedScrollView scrollView, int x, int y, int oldX, int oldY) {
View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
int distanceToEnd = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));
// If diff is zero, then the bottom has been reached
if (distanceToEnd == 0) {
if (mSearchResultTradeList.size() > mDisplayTradeList.size()
&& mAsyncTaskList.size() > 0) {
Toast.makeText(getContext(),
R.string.loading_message,
Toast.LENGTH_SHORT).show();
} else {
int size = mDisplayTradeList.size();
int max = Math.min(mSearchResultTradeList.size(), (size + MAX_DISPLAY));
for (int i = size; i < max; i++)
mDisplayTradeList.add(mSearchResultTradeList.get(i));
mTradeAdapter.notifyDataSetChanged();
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.myArticleTrade:
clearTask();
startMyTradeArticleActivity();
break;
case R.id.writeArticleTrade:
clearTask();
startEditTradeActivity();
break;
case R.id.btnSearchActivate:
searchActivate();
setFocusOnEditText();
break;
case R.id.fab:
endlessNestedScrollView.smoothScrollTo(0,0); // Go to top
break;
}
}
private void setSpinner() {
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_dropdown_item, mCategory);
categorySpinner.setAdapter(adapter);
/* 캠퍼스 */
campusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mSelectedCampus != position) {
mSelectedCampus = position;
Reselect();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) { }
});
/* 카테고리 */
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// 글자 크기 14sp로 설정한다.
((TextView) parent.getChildAt(0)).setTextSize(14);
if (mSelectedCategory != position) {
mSelectedCategory = position;
Reselect();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) { }
});
}
private void setRecyclerView() {
mAsyncTaskList = new ArrayList<AsyncTask>();
mTradeAdapter = new TradeAdapter(
this, mDisplayTradeList, mAsyncTaskList);
RecyclerView.LayoutManager layoutManager
= new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
// Add a neat dividing line between items in the list
recyclerView.addItemDecoration(
new DividerItemDecoration(getContext(), LinearLayout.VERTICAL));
// set the adapter
recyclerView.setAdapter(mTradeAdapter);
}
private void Reselect() {
clearTask();
setSelectedTradeList();
mTradeAdapter.notifyDataSetChanged();
}
/** 내부에서 분류 작업을 처리 */
private void setSelectedTradeList() {
// 기존 값 초기화
mSearchResultTradeList.clear();
mDisplayTradeList.clear();
for (Trade trade: mTradeList) {
if (trade.isSelectedCampus(mSelectedCampus) &&
trade.isSelectedCategory(mSelectedCategory) &&
trade.isSearchMatch(mSearch)) {
mSearchResultTradeList.add(trade);
}
}
int max = Math.min(mSearchResultTradeList.size(), MAX_DISPLAY);
for (int i = 0; i < max; i++)
mDisplayTradeList.add(mSearchResultTradeList.get(i));
}
private void searchActivate() {
mIsSearchActivate = true;
btnSearchActivate.setVisibility(View.GONE);
editTextSearch.setVisibility(View.VISIBLE);
}
private void searchDeactivate() {
mIsSearchActivate = false;
btnSearchActivate.setVisibility(View.VISIBLE);
editTextSearch.setVisibility(View.GONE);
editTextSearch.setText("");
mSearch = "";
}
private void performSearch() {
String search = editTextSearch.getText().toString().trim();
editTextSearch.setText(search);
editTextSearch.setSelection(editTextSearch.getText().length());
if (search.equals("")) {
Snackbar.make(getView(), "검색어를 입력해주세요.",
Snackbar.LENGTH_SHORT).show();
} else {
mSearch = search;
Reselect();
hideKeyboard();
}
}
@Override
public void onRefresh() {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setMessage("새로고침 하시겠습니까?")
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mIsSearchActivate) {
editTextSearch.setText(mSearch);
editTextSearch.setSelection(editTextSearch.getText().length());
}
Refresh();
}
})
.setNegativeButton("취소", null)
.show();
refreshLayout.setRefreshing(false); // 로딩 바 제거
}
/** 새로고침 처리 */
private void Refresh() {
if (mCategory.length == 1) {
setCategoryArray();
setSpinner();
}
loadTradeList();
Reselect();
}
@Override
public void onBack() {
if (mIsSearchActivate) {
searchDeactivate();
Reselect();
endlessNestedScrollView.smoothScrollTo(0,0);
} else {
MainActivity activity = (MainActivity) getActivity();
activity.setOnKeyBackPressedListener(null);
activity.onBackPressed();
}
}
private void clearTask() {
for (AsyncTask task: mAsyncTaskList)
task.cancel(true);
mAsyncTaskList.clear();
}
private void resumeTask() { mTradeAdapter.notifyDataSetChanged(); }
/** 추가된 데이터를 mTradeList 에 추가한다. */
private void tradeAddProcess() {
int id = mPrefs.getInt("TRADE_ADD_ID", 0);
String category = mPrefs.getString("TRADE_ADD_CATEGORY", "");
int categoryid = mPrefs.getInt("TRADE_ADD_CATEGORY_ID", 0);
String title = mPrefs.getString("TRADE_ADD_TITLE", "");
int price = mPrefs.getInt("TRADE_ADD_PRICE", -1);
String info = mPrefs.getString("TRADE_ADD_INFO", "");
String firstImgPath = mPrefs.getString("TRADE_ADD_FIRST_IMG_PATH", "");
String campus = mPrefs.getString("TRADE_ADD_CAMPUS", "");
String date = mPrefs.getString("TRADE_ADD_DATE", "");
if (id != 0 &&
!category.equals("") &&
categoryid != 0 &&
!title.equals("") &&
price != -1 &&
!info.equals("") &&
!firstImgPath.equals("") &&
!campus.equals("") &&
!date.equals("")) {
Trade addTrade = new Trade();
addTrade.setId(id);
addTrade.setCategory(category);
addTrade.setCategoryId(categoryid);
addTrade.setTitle(title);
addTrade.setPrice(price);
addTrade.setInfo(info);
addTrade.setImgPath(new String[] { firstImgPath });
addTrade.setCampus(campus);
addTrade.setDate(date);
mTradeList.add(0, addTrade);
}
}
private void notifyChangeNotCommitted() {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setMessage("변경된 내용은 새로 고침 후에 반영됩니다.")
.setPositiveButton("확인", null)
.show();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* 중고거래 목록을 가져온다.
*/
private void loadTradeList() {
if (isNetworkAvailable()) {
noNetworkTxt.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
try {
TradeNetworkTask tradeNetworkTask = new TradeNetworkTask();
String jsonString = tradeNetworkTask.execute().get();
onPostTradeNetworkTask(jsonString);
} catch (Exception exc) { } // Handle exceptions
} else {
recyclerView.setVisibility(View.GONE);
noNetworkTxt.setVisibility(View.VISIBLE);
}
}
public class TradeNetworkTask
extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
String result;
Map<String, String> queryMap = new HashMap();
/** 모든 데이터를 가져와서 내부에서 분류 작업을 진행하도록 처리 */
queryMap.put("campus", String.valueOf(0));
queryMap.put("category", String.valueOf(0));
queryMap.put("search", "");
SimpleHttpJSON simpleHttpJSON = new SimpleHttpJSON("trade", queryMap);
try {
result = simpleHttpJSON.sendPost();
} catch (Exception exc) {
result = "";
}
return result;
}
}
private void onPostTradeNetworkTask(String jsonString) {
// 기존 값 초기화
mTradeList.clear();
try {
// Parsing String with JSONTokener to JSONObject
JSONTokener tokener = new JSONTokener(jsonString);
JSONObject response = new JSONObject(tokener);
if (response.getBoolean("result")) {
JSONArray jArray = response.getJSONArray("trade");
for (int i = 0; i < jArray.length(); i++) {
mTradeList.add(new Trade(jArray.getJSONObject(i)));
}
} else { } // Handle false result
} catch (JSONException exc) { } // Handle exceptions
}
/** 중고거래 카테고리 목록을 가져온다. */
private void setCategoryArray() {
if (isNetworkAvailable()) {
TradeCategory tradeCategoryHelper = new TradeCategory();
mCategory = tradeCategoryHelper.getCategoryArray();
} else {
Toast.makeText(getContext(),
R.string.network_not_available,
Toast.LENGTH_SHORT).show();
}
if (mCategory == null)
mCategory = new String[] { "[-- 카테고리 --]" };
}
/**
* 이미지가 모두 로드되기 전에 Activity 를 이동하면 Black Screen 이 발생하므로,
* 이미지가 모두 로드된 후에만 접근할 수 있도록 제한한다.
*/
public void showTrade(int tradeToShow) {
clearTask();
mSelectedTradeIndex = tradeToShow;
Intent viewTradeIntent = new Intent(getActivity(), ViewTradeActivity.class);
viewTradeIntent.putExtra("TRADE_ID", mDisplayTradeList.get(tradeToShow).getId());
mPostCheckRemovedLauncher.launch(viewTradeIntent);
mIsPostLauncher = true;
}
/** 신고 (expel) 구현 */
public void expelTrade(int tradeToExpel) {
final int tradeId = mDisplayTradeList.get(tradeToExpel).getId();
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setMessage(R.string.trade_expel_msg)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
expelTradeProcess(tradeId);
}
})
.setNegativeButton("취소", null)
.show();
}
private void expelTradeProcess(int tradeId) {
clearTask();
if (isNetworkAvailable()) {
try {
TradeExpelNetworkTask tradeExpelNetworkTask = new TradeExpelNetworkTask(tradeId);
String jsonString = tradeExpelNetworkTask.execute().get();
onPostTradeExpelNetworkTask(jsonString);
} catch (Exception exc) { } // Handle exceptions
} else {
// Handle network not available
Snackbar.make(getActivity().findViewById(android.R.id.content),
R.string.network_not_available,
Snackbar.LENGTH_SHORT).show();
}
resumeTask();
}
public class TradeExpelNetworkTask
extends AsyncTask<Void, Void, String> {
private int tradeId;
public TradeExpelNetworkTask(int tradeId) {
this.tradeId = tradeId;
}
@Override
protected String doInBackground(Void... voids) {
String result;
Map<String, String> queryMap = new HashMap();
queryMap.put("id", mUserId);
queryMap.put("tradeid", String.valueOf(tradeId));
SimpleHttpJSON simpleHttpJSON
= new SimpleHttpJSON("tradeExpel", queryMap);
try {
result = simpleHttpJSON.sendPost();
} catch (Exception exc) {
result = "";
}
return result;
}
}
private void onPostTradeExpelNetworkTask(String jsonString) {
try {
// Parsing String with JSONTokener to JSONObject
JSONTokener tokener = new JSONTokener(jsonString);
JSONObject response = new JSONObject(tokener);
if (response.getBoolean("result") &&
!response.getBoolean("proceed")) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
R.string.trade_expel_proceed_before_msg,
Snackbar.LENGTH_SHORT).show();
}
} catch (JSONException exc) {
// Handle exceptions
}
}
private void startEditTradeActivity() {
Intent editTradeIntent = new Intent(getActivity(), EditTradeActivity.class);
mPostCheckAddLauncher.launch(editTradeIntent);
mIsPostLauncher = true;
}
private void startMyTradeArticleActivity() {
Intent myTradeArticleIntent = new Intent(getActivity(), MyTradeArticleActivity.class);
mPostCheckChangeLauncher.launch(myTradeArticleIntent);
mIsPostLauncher = true;
}
/** Hide keyboard */
private void hideKeyboard() {
if (getActivity().getCurrentFocus() != null) {
InputMethodManager imm
= (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(), 0);
}
}
/** Set focus on EditText and show keyboard */
private void setFocusOnEditText() {
editTextSearch.setFocusable(true);
editTextSearch.setFocusableInTouchMode(true);
editTextSearch.requestFocus();
InputMethodManager imm = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editTextSearch, InputMethodManager.SHOW_IMPLICIT);
}
} |
3e16a887273270d76bee31f407c28426db96f438 | 17,998 | java | Java | components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandler.java | samgregoost/carbon-apimgt | 389b79f40159aaea7d055c4756a3011f8073adc8 | [
"Apache-2.0"
] | null | null | null | components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandler.java | samgregoost/carbon-apimgt | 389b79f40159aaea7d055c4756a3011f8073adc8 | [
"Apache-2.0"
] | null | null | null | components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandler.java | samgregoost/carbon-apimgt | 389b79f40159aaea7d055c4756a3011f8073adc8 | [
"Apache-2.0"
] | null | null | null | 49.581267 | 175 | 0.693077 | 9,665 | /*
* Copyright WSO2 Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.apimgt.gateway.handlers.security;
import edu.umd.cs.findbugs.annotations.*;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.synapse.*;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.apache.synapse.rest.RESTConstants;
import org.apache.synapse.transport.passthru.PassThroughConstants;
import org.apache.synapse.transport.passthru.util.RelayUtils;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.handlers.Utils;
import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.metrics.manager.MetricManager;
import org.wso2.carbon.metrics.manager.Timer;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Authentication handler for REST APIs exposed in the API gateway. This handler will
* drop the requests if an authentication failure occurs. But before a message is dropped
* it looks for a special custom error handler sequence APISecurityConstants.API_AUTH_FAILURE_HANDLER
* through which the message will be mediated when available. This is a custom extension point
* provided to the users to handle authentication failures in a deployment specific manner.
* Once the custom error handler has been invoked, this implementation will further try to
* respond to the client with a 401 Unauthorized response. If this is not required, the users
* must drop the message in their custom error handler itself.
* <p/>
* If no authentication errors are encountered, this will add some AuthenticationContext
* information to the request and let it through to the next handler in the chain.
*/
public class APIAuthenticationHandler extends AbstractHandler implements ManagedLifecycle {
private static final Log log = LogFactory.getLog(APIAuthenticationHandler.class);
private volatile Authenticator authenticator;
private SynapseEnvironment synapseEnvironment;
public void init(SynapseEnvironment synapseEnvironment) {
this.synapseEnvironment = synapseEnvironment;
if (log.isDebugEnabled()) {
log.debug("Initializing API authentication handler instance");
}
if (ServiceReferenceHolder.getInstance().getApiManagerConfigurationService() != null){
initializeAuthenticator();
}
}
public void destroy() {
if(authenticator != null) {
authenticator.destroy();
} else {
log.warn("Unable to destroy uninitialized authentication handler instance");
}
}
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "LEST_LOST_EXCEPTION_STACK_TRACE", justification = "The exception needs to thrown for fault sequence invocation")
private void initializeAuthenticator() {
String authenticatorType = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration().
getFirstProperty(APISecurityConstants.API_SECURITY_AUTHENTICATOR);
if (authenticatorType == null) {
/*
if the APIManagerConfigurationService is not set at the time the APIAuthenticationHandler intializes
the authenticator is null. Then we need to initialize the authenticator in the first request
*/
authenticatorType = OAuthAuthenticator.class.getName();
}
try {
authenticator = (Authenticator) APIUtil.getClassForName(authenticatorType).newInstance();
} catch (Exception e) {
// Just throw it here - Synapse will handle it
throw new SynapseException("Error while initializing authenticator of " +
"type: " + authenticatorType);
}
authenticator.init(synapseEnvironment);
}
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "EXS_EXCEPTION_SOFTENING_RETURN_FALSE",
justification = "Error is sent through payload")
public boolean handleRequest(MessageContext messageContext) {
Timer timer = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(
APIConstants.METRICS_PREFIX, this.getClass().getSimpleName()));
Timer.Context context = timer.start();
long startTime = System.nanoTime();
long endTime;
long difference;
try {
if (Utils.isStatsEnabled()) {
long currentTime = System.currentTimeMillis();
messageContext.setProperty("api.ut.requestTime", Long.toString(currentTime));
}
if (authenticator == null) {
initializeAuthenticator();
}
if (authenticator.authenticate(messageContext)) {
if (log.isDebugEnabled()) {
// We do the calculations only if the debug logs are enabled. Otherwise this would be an overhead
// to all the gateway calls that is happening.
endTime = System.nanoTime();
difference = (endTime - startTime) / 1000000;
String messageDetails = logMessageDetails(messageContext);
log.debug("Authenticated API, authentication response relieved: " + messageDetails +
", elapsedTimeInMilliseconds=" + difference / 1000000);
}
setAPIParametersToMessageContext(messageContext);
return true;
}
} catch (APISecurityException e) {
if (log.isDebugEnabled()) {
// We do the calculations only if the debug logs are enabled. Otherwise this would be an overhead
// to all the gateway calls that is happening.
endTime = System.nanoTime();
difference = (endTime - startTime) / 1000000;
String messageDetails = logMessageDetails(messageContext);
log.debug("Call to API gateway : " + messageDetails + ", elapsedTimeInMilliseconds=" +
difference / 1000000);
}
// We do not need to log authentication failures as errors since these are not product errors.
log.warn("API authentication failure due to " +
APISecurityConstants.getAuthenticationFailureMessage(e.getErrorCode()));
if (log.isDebugEnabled()) {
log.debug("API authentication failed with error " + e.getErrorCode(), e);
}
handleAuthFailure(messageContext, e);
} finally {
context.stop();
}
return false;
}
public boolean handleResponse(MessageContext messageContext) {
if (Utils.isStatsEnabled()) {
long currentTime = System.currentTimeMillis();
messageContext.setProperty("api.ut.backendRequestEndTime", Long.toString(currentTime));
}
return true;
}
private void handleAuthFailure(MessageContext messageContext, APISecurityException e) {
messageContext.setProperty(SynapseConstants.ERROR_CODE, e.getErrorCode());
messageContext.setProperty(SynapseConstants.ERROR_MESSAGE,
APISecurityConstants.getAuthenticationFailureMessage(e.getErrorCode()));
messageContext.setProperty(SynapseConstants.ERROR_EXCEPTION, e);
Mediator sequence = messageContext.getSequence(APISecurityConstants.API_AUTH_FAILURE_HANDLER);
// Invoke the custom error handler specified by the user
if (sequence != null && !sequence.mediate(messageContext)) {
// If needed user should be able to prevent the rest of the fault handling
// logic from getting executed
return;
}
// By default we send a 401 response back
org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
getAxis2MessageContext();
// This property need to be set to avoid sending the content in pass-through pipe (request message)
// as the response.
axis2MC.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
try {
RelayUtils.consumeAndDiscardMessage(axis2MC);
} catch (AxisFault axisFault) {
//In case of an error it is logged and the process is continued because we're setting a fault message in the payload.
log.error("Error occurred while consuming and discarding the message", axisFault);
}
axis2MC.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/soap+xml");
int status;
if (e.getErrorCode() == APISecurityConstants.API_AUTH_GENERAL_ERROR) {
status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
} else if (e.getErrorCode() == APISecurityConstants.API_AUTH_INCORRECT_API_RESOURCE ||
e.getErrorCode() == APISecurityConstants.API_AUTH_FORBIDDEN ||
e.getErrorCode() == APISecurityConstants.INVALID_SCOPE) {
status = HttpStatus.SC_FORBIDDEN;
} else {
status = HttpStatus.SC_UNAUTHORIZED;
Map<String, String> headers =
(Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
if (headers != null) {
headers.put(HttpHeaders.WWW_AUTHENTICATE, authenticator.getChallengeString());
axis2MC.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers);
}
}
if (messageContext.isDoingPOX() || messageContext.isDoingGET()) {
Utils.setFaultPayload(messageContext, getFaultPayload(e));
} else {
Utils.setSOAPFault(messageContext, "Client", "Authentication Failure", e.getMessage());
}
Utils.sendFault(messageContext, status);
}
private OMElement getFaultPayload(APISecurityException e) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace ns = fac.createOMNamespace(APISecurityConstants.API_SECURITY_NS,
APISecurityConstants.API_SECURITY_NS_PREFIX);
OMElement payload = fac.createOMElement("fault", ns);
OMElement errorCode = fac.createOMElement("code", ns);
errorCode.setText(String.valueOf(e.getErrorCode()));
OMElement errorMessage = fac.createOMElement("message", ns);
errorMessage.setText(APISecurityConstants.getAuthenticationFailureMessage(e.getErrorCode()));
OMElement errorDetail = fac.createOMElement("description", ns);
errorDetail.setText(APISecurityConstants.getFailureMessageDetailDescription(e.getErrorCode(), e.getMessage()));
payload.addChild(errorCode);
payload.addChild(errorMessage);
payload.addChild(errorDetail);
return payload;
}
private String logMessageDetails(MessageContext messageContext) {
//TODO: Hardcoded const should be moved to a common place which is visible to org.wso2.carbon.apimgt.gateway.handlers
String applicationName = (String) messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME);
String endUserName = (String) messageContext.getProperty(APIMgtGatewayConstants.END_USER_NAME);
Date incomingReqTime = null;
org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
String logMessage = "API call failed reason=API_authentication_failure"; //"app-name=" + applicationName + " " + "user-name=" + endUserName;
String logID = axisMC.getOptions().getMessageId();
if (applicationName != null) {
logMessage = " belonging to appName=" + applicationName;
}
if (endUserName != null) {
logMessage = logMessage + " userName=" + endUserName;
}
if (logID != null) {
logMessage = logMessage + " transactionId=" + logID;
}
String userAgent = (String) ((TreeMap) axisMC.getProperty(org.apache.axis2.context.MessageContext
.TRANSPORT_HEADERS)).get(APIConstants.USER_AGENT);
if (userAgent != null) {
logMessage = logMessage + " with userAgent=" + userAgent;
}
String accessToken = (String) ((TreeMap) axisMC.getProperty(org.apache.axis2.context.MessageContext
.TRANSPORT_HEADERS)).get(APIMgtGatewayConstants.AUTHORIZATION);
if (accessToken != null) {
logMessage = logMessage + " with accessToken=" + accessToken;
}
String requestURI = (String) messageContext.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
if (requestURI != null) {
logMessage = logMessage + " for requestURI=" + requestURI;
}
long reqIncomingTimestamp = Long.parseLong((String) ((Axis2MessageContext) messageContext).
getAxis2MessageContext().getProperty(APIMgtGatewayConstants.REQUEST_RECEIVED_TIME));
incomingReqTime = new Date(reqIncomingTimestamp);
logMessage = logMessage + " at time=" + incomingReqTime;
String remoteIP = (String) axisMC.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
if (remoteIP != null) {
logMessage = logMessage + " from clientIP=" + remoteIP;
}
return logMessage;
}
private void setAPIParametersToMessageContext(MessageContext messageContext) {
AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(messageContext);
org.apache.axis2.context.MessageContext axis2MsgContext =
((Axis2MessageContext) messageContext).getAxis2MessageContext();
String consumerKey = "";
String username = "";
String applicationName = "";
String applicationId = "";
if (authContext != null) {
consumerKey = authContext.getConsumerKey();
username = authContext.getUsername();
applicationName = authContext.getApplicationName();
applicationId = authContext.getApplicationId();
}
String context = (String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT);
String apiVersion = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API);
String apiPublisher = (String) messageContext.getProperty(APIMgtGatewayConstants.API_PUBLISHER);
int index = apiVersion.indexOf("--");
if (index != -1) {
apiVersion = apiVersion.substring(index + 2);
}
String api = apiVersion.split(":")[0];
String version = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
String fullRequestPath = (String) messageContext.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(fullRequestPath);
if (apiPublisher == null) {
apiPublisher = APIUtil.getAPIProviderFromRESTAPI(apiVersion,tenantDomain);
}
String resource = extractResource(messageContext);
String method = (String) (axis2MsgContext.getProperty(
Constants.Configuration.HTTP_METHOD));
String hostName = APIUtil.getHostAddress();
messageContext.setProperty(APIMgtGatewayConstants.CONSUMER_KEY, consumerKey);
messageContext.setProperty(APIMgtGatewayConstants.USER_ID, username);
messageContext.setProperty(APIMgtGatewayConstants.CONTEXT, context);
messageContext.setProperty(APIMgtGatewayConstants.API_VERSION, apiVersion);
messageContext.setProperty(APIMgtGatewayConstants.API, api);
messageContext.setProperty(APIMgtGatewayConstants.VERSION, version);
messageContext.setProperty(APIMgtGatewayConstants.RESOURCE, resource);
messageContext.setProperty(APIMgtGatewayConstants.HTTP_METHOD, method);
messageContext.setProperty(APIMgtGatewayConstants.HOST_NAME, hostName);
messageContext.setProperty(APIMgtGatewayConstants.API_PUBLISHER, apiPublisher);
messageContext.setProperty(APIMgtGatewayConstants.APPLICATION_NAME, applicationName);
messageContext.setProperty(APIMgtGatewayConstants.APPLICATION_ID, applicationId);
}
private String extractResource(MessageContext mc) {
String resource = "/";
Pattern pattern = Pattern.compile(APIMgtGatewayConstants.RESOURCE_PATTERN);
Matcher matcher = pattern.matcher((String) mc.getProperty(RESTConstants.REST_FULL_REQUEST_PATH));
if (matcher.find()) {
resource = matcher.group(1);
}
return resource;
}
}
|
3e16a90af3ec87bcef0f4633e46a8735cf75fadc | 2,510 | java | Java | ickprotocol/core/src/main/java/com/ickstream/protocol/service/core/DeviceResponse.java | ickStream/ickstream-java-common | a7ab024043625c050538f94a1acce478598827ae | [
"BSD-3-Clause"
] | null | null | null | ickprotocol/core/src/main/java/com/ickstream/protocol/service/core/DeviceResponse.java | ickStream/ickstream-java-common | a7ab024043625c050538f94a1acce478598827ae | [
"BSD-3-Clause"
] | null | null | null | ickprotocol/core/src/main/java/com/ickstream/protocol/service/core/DeviceResponse.java | ickStream/ickstream-java-common | a7ab024043625c050538f94a1acce478598827ae | [
"BSD-3-Clause"
] | null | null | null | 32.179487 | 85 | 0.705578 | 9,666 | /*
* Copyright (c) 2013-2014, ickStream GmbH
* 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 ickStream nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ickstream.protocol.service.core;
public class DeviceResponse {
private String id;
private String name;
private String model;
private String address;
private String publicAddress;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPublicAddress() {
return publicAddress;
}
public void setPublicAddress(String publicAddress) {
this.publicAddress = publicAddress;
}
}
|
3e16aa2cbcdde3a3bf339d8572b5b4af95daa5d4 | 2,123 | java | Java | client/rest-high-level/src/test/java/org/elasticsearch/client/asyncsearch/SubmitAsyncSearchRequestTests.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | client/rest-high-level/src/test/java/org/elasticsearch/client/asyncsearch/SubmitAsyncSearchRequestTests.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | client/rest-high-level/src/test/java/org/elasticsearch/client/asyncsearch/SubmitAsyncSearchRequestTests.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | 45.170213 | 125 | 0.705134 | 9,667 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.client.asyncsearch;
import org.elasticsearch.client.ValidationException;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.test.ESTestCase;
import java.util.Optional;
public class SubmitAsyncSearchRequestTests extends ESTestCase {
public void testValidation() {
{
SearchSourceBuilder source = new SearchSourceBuilder();
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(source, "test");
Optional<ValidationException> validation = request.validate();
assertFalse(validation.isPresent());
}
{
SearchSourceBuilder source = new SearchSourceBuilder().suggest(new SuggestBuilder());
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(source, "test");
Optional<ValidationException> validation = request.validate();
assertTrue(validation.isPresent());
assertEquals(1, validation.get().validationErrors().size());
assertEquals("suggest-only queries are not supported", validation.get().validationErrors().get(0));
}
{
SubmitAsyncSearchRequest request = new SubmitAsyncSearchRequest(new SearchSourceBuilder(), "test");
request.setKeepAlive(new TimeValue(1));
Optional<ValidationException> validation = request.validate();
assertTrue(validation.isPresent());
assertEquals(1, validation.get().validationErrors().size());
assertEquals("[keep_alive] must be greater than 1 minute, got: 1ms", validation.get().validationErrors().get(0));
}
}
}
|
3e16ab49b82e6642af166ea13e756d7152d06541 | 10,072 | java | Java | java/examples/datatypes/H5Ex_T_OpaqueAttribute.java | seanm/hdf5 | 2e0d789ba3d857adff8afc4b04d0db5455c2c7fb | [
"BSD-3-Clause-LBNL"
] | 215 | 2020-04-27T17:08:20.000Z | 2022-03-09T14:36:37.000Z | java/examples/datatypes/H5Ex_T_OpaqueAttribute.java | seanm/hdf5 | 2e0d789ba3d857adff8afc4b04d0db5455c2c7fb | [
"BSD-3-Clause-LBNL"
] | 562 | 2020-06-21T15:38:20.000Z | 2022-03-31T15:33:59.000Z | java/examples/datatypes/H5Ex_T_OpaqueAttribute.java | seanm/hdf5 | 2e0d789ba3d857adff8afc4b04d0db5455c2c7fb | [
"BSD-3-Clause-LBNL"
] | 180 | 2020-04-30T17:05:42.000Z | 2022-03-31T16:04:26.000Z | 33.022951 | 108 | 0.510226 | 9,668 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://www.hdfgroup.org/licenses. *
* If you do not have access to either file, you may request a copy from *
* anpch@example.com. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/************************************************************
This example shows how to read and write opaque datatypes
to an attribute. The program first writes opaque data to
an attribute with a dataspace of DIM0, then closes the
file. Next, it reopens the file, reads back the data, and
outputs it to the screen.
************************************************************/
package examples.datatypes;
import hdf.hdf5lib.H5;
import hdf.hdf5lib.HDF5Constants;
public class H5Ex_T_OpaqueAttribute {
private static String FILENAME = "H5Ex_T_OpaqueAttribute.h5";
private static String DATASETNAME = "DS1";
private static String ATTRIBUTENAME = "A1";
private static final int DIM0 = 4;
private static final int LEN = 7;
private static final int RANK = 1;
private static void CreateDataset() {
long file_id = HDF5Constants.H5I_INVALID_HID;
long dataspace_id = HDF5Constants.H5I_INVALID_HID;
long datatype_id = HDF5Constants.H5I_INVALID_HID;
long dataset_id = HDF5Constants.H5I_INVALID_HID;
long attribute_id = HDF5Constants.H5I_INVALID_HID;
long[] dims = { DIM0 };
byte[] dset_data = new byte[DIM0 * LEN];
byte[] str_data = { 'O', 'P', 'A', 'Q', 'U', 'E' };
// Initialize data.
for (int indx = 0; indx < DIM0; indx++) {
for (int jndx = 0; jndx < LEN - 1; jndx++)
dset_data[jndx + indx * LEN] = str_data[jndx];
dset_data[LEN - 1 + indx * LEN] = (byte) (indx + '0');
}
// Create a new file using default properties.
try {
file_id = H5.H5Fcreate(FILENAME, HDF5Constants.H5F_ACC_TRUNC, HDF5Constants.H5P_DEFAULT,
HDF5Constants.H5P_DEFAULT);
}
catch (Exception e) {
e.printStackTrace();
}
// Create dataset with a scalar dataspace.
try {
dataspace_id = H5.H5Screate(HDF5Constants.H5S_SCALAR);
if (dataspace_id >= 0) {
dataset_id = H5.H5Dcreate(file_id, DATASETNAME, HDF5Constants.H5T_STD_I32LE, dataspace_id,
HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT);
H5.H5Sclose(dataspace_id);
dataspace_id = HDF5Constants.H5I_INVALID_HID;
}
}
catch (Exception e) {
e.printStackTrace();
}
// Create opaque datatype and set the tag to something appropriate.
// For this example we will write and view the data as a character
// array.
try {
datatype_id = H5.H5Tcreate(HDF5Constants.H5T_OPAQUE, (long)LEN);
if (datatype_id >= 0)
H5.H5Tset_tag(datatype_id, "Character array");
}
catch (Exception e) {
e.printStackTrace();
}
// Create dataspace. Setting maximum size to NULL sets the maximum
// size to be the current size.
try {
dataspace_id = H5.H5Screate_simple(RANK, dims, null);
}
catch (Exception e) {
e.printStackTrace();
}
// Create the attribute and write the array data to it.
try {
if ((dataset_id >= 0) && (datatype_id >= 0) && (dataspace_id >= 0))
attribute_id = H5.H5Acreate(dataset_id, ATTRIBUTENAME, datatype_id, dataspace_id,
HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT);
}
catch (Exception e) {
e.printStackTrace();
}
// Write the dataset.
try {
if ((attribute_id >= 0) && (datatype_id >= 0))
H5.H5Awrite(attribute_id, datatype_id, dset_data);
}
catch (Exception e) {
e.printStackTrace();
}
// End access to the dataset and release resources used by it.
try {
if (attribute_id >= 0)
H5.H5Aclose(attribute_id);
}
catch (Exception e) {
e.printStackTrace();
}
try {
if (dataset_id >= 0)
H5.H5Dclose(dataset_id);
}
catch (Exception e) {
e.printStackTrace();
}
// Terminate access to the data space.
try {
if (dataspace_id >= 0)
H5.H5Sclose(dataspace_id);
}
catch (Exception e) {
e.printStackTrace();
}
try {
if (datatype_id >= 0)
H5.H5Tclose(datatype_id);
}
catch (Exception e) {
e.printStackTrace();
}
// Close the file.
try {
if (file_id >= 0)
H5.H5Fclose(file_id);
}
catch (Exception e) {
e.printStackTrace();
}
}
private static void ReadDataset() {
long file_id = HDF5Constants.H5I_INVALID_HID;
long datatype_id = HDF5Constants.H5I_INVALID_HID;
long dataspace_id = HDF5Constants.H5I_INVALID_HID;
long dataset_id = HDF5Constants.H5I_INVALID_HID;
long attribute_id = HDF5Constants.H5I_INVALID_HID;
long type_len = -1;
long[] dims = { DIM0 };
byte[] dset_data;
String tag_name = null;
// Open an existing file.
try {
file_id = H5.H5Fopen(FILENAME, HDF5Constants.H5F_ACC_RDONLY, HDF5Constants.H5P_DEFAULT);
}
catch (Exception e) {
e.printStackTrace();
}
// Open an existing dataset.
try {
if (file_id >= 0)
dataset_id = H5.H5Dopen(file_id, DATASETNAME, HDF5Constants.H5P_DEFAULT);
}
catch (Exception e) {
e.printStackTrace();
}
try {
if (dataset_id >= 0)
attribute_id = H5.H5Aopen_by_name(dataset_id, ".", ATTRIBUTENAME, HDF5Constants.H5P_DEFAULT,
HDF5Constants.H5P_DEFAULT);
}
catch (Exception e) {
e.printStackTrace();
}
// Get datatype and properties for the datatype.
try {
if (attribute_id >= 0)
datatype_id = H5.H5Aget_type(attribute_id);
if (datatype_id >= 0) {
type_len = H5.H5Tget_size(datatype_id);
tag_name = H5.H5Tget_tag(datatype_id);
}
}
catch (Exception e) {
e.printStackTrace();
}
// Get dataspace and allocate memory for read buffer.
try {
if (attribute_id >= 0)
dataspace_id = H5.H5Aget_space(attribute_id);
}
catch (Exception e) {
e.printStackTrace();
}
try {
if (dataspace_id >= 0)
H5.H5Sget_simple_extent_dims(dataspace_id, dims, null);
}
catch (Exception e) {
e.printStackTrace();
}
// Allocate buffer.
dset_data = new byte[(int) (dims[0] * type_len)];
// Read data.
try {
if ((attribute_id >= 0) && (datatype_id >= 0))
H5.H5Aread(attribute_id, datatype_id, dset_data);
}
catch (Exception e) {
e.printStackTrace();
}
// Output the data to the screen.
System.out.println("Datatype tag for " + ATTRIBUTENAME + " is: \"" + tag_name + "\"");
for (int indx = 0; indx < dims[0]; indx++) {
System.out.print(ATTRIBUTENAME + "[" + indx + "]: ");
for (int jndx = 0; jndx < type_len; jndx++) {
char temp = (char) dset_data[jndx + indx * (int)type_len];
System.out.print(temp);
}
System.out.println("");
}
System.out.println();
// End access to the dataset and release resources used by it.
try {
if (attribute_id >= 0)
H5.H5Aclose(attribute_id);
}
catch (Exception e) {
e.printStackTrace();
}
try {
if (dataset_id >= 0)
H5.H5Dclose(dataset_id);
}
catch (Exception e) {
e.printStackTrace();
}
// Terminate access to the data space.
try {
if (dataspace_id >= 0)
H5.H5Sclose(dataspace_id);
}
catch (Exception e) {
e.printStackTrace();
}
try {
if (datatype_id >= 0)
H5.H5Tclose(datatype_id);
}
catch (Exception e) {
e.printStackTrace();
}
// Close the file.
try {
if (file_id >= 0)
H5.H5Fclose(file_id);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
H5Ex_T_OpaqueAttribute.CreateDataset();
// Now we begin the read section of this example. Here we assume
// the dataset and array have the same name and rank, but can have
// any size. Therefore we must allocate a new array to read in
// data using malloc().
H5Ex_T_OpaqueAttribute.ReadDataset();
}
}
|
3e16abcac6ebb328cb1dfe2bd298d5174ab7e986 | 1,129 | java | Java | src/com/adyen/reportMerger/entities/MergeTypes.java | daanvinken/adyen-report-merger | c8fe096aa7fcdcc012813b7e9edf36d4d5ee675a | [
"MIT"
] | 6 | 2015-10-27T13:49:35.000Z | 2021-07-07T00:50:20.000Z | src/com/adyen/reportMerger/entities/MergeTypes.java | daanvinken/adyen-report-merger | c8fe096aa7fcdcc012813b7e9edf36d4d5ee675a | [
"MIT"
] | 4 | 2019-08-02T19:54:06.000Z | 2022-03-22T13:01:23.000Z | src/com/adyen/reportMerger/entities/MergeTypes.java | daanvinken/adyen-report-merger | c8fe096aa7fcdcc012813b7e9edf36d4d5ee675a | [
"MIT"
] | 13 | 2017-03-20T13:12:43.000Z | 2022-02-24T08:07:27.000Z | 24.543478 | 74 | 0.627989 | 9,669 | package com.adyen.reportMerger.entities;
/**
* Created by andrew on 9/22/16.
*/
public enum MergeTypes {
BATCHRANGE ("Batch range", "batch"),
DATERANGE ("Date range", "date");
String mergeTypeDescription;
String mergeType;
MergeTypes(String mergeTypeDescription, String mergeType) {
this.mergeTypeDescription = mergeTypeDescription;
this.mergeType = mergeType;
}
public String getMergeTypeDescription() {
return mergeTypeDescription;
}
public void setMergeTypeDescription(String mergeTypeDescription) {
this.mergeTypeDescription = mergeTypeDescription;
}
public String getMergeType() {
return mergeType;
}
public void setMergeType(String mergeType) {
this.mergeType = mergeType;
}
public static MergeTypes getMergeTypeFromDescription(String text) {
if (text != null) {
for (MergeTypes mt : MergeTypes.values()) {
if (text.equalsIgnoreCase(mt.getMergeTypeDescription())) {
return mt;
}
}
}
return null;
}
}
|
3e16abe3cf3cadab4e67446ae9c270b3165e5a5b | 944 | java | Java | cevr/src/com/cevr/component/core/XmlReaderException.java | mzxc/cevr | 4a9383ac175f47799e25dd4ee3320bec936ae56e | [
"Apache-2.0"
] | null | null | null | cevr/src/com/cevr/component/core/XmlReaderException.java | mzxc/cevr | 4a9383ac175f47799e25dd4ee3320bec936ae56e | [
"Apache-2.0"
] | null | null | null | cevr/src/com/cevr/component/core/XmlReaderException.java | mzxc/cevr | 4a9383ac175f47799e25dd4ee3320bec936ae56e | [
"Apache-2.0"
] | 3 | 2016-08-26T06:11:07.000Z | 2017-06-15T14:03:07.000Z | 17.811321 | 77 | 0.506356 | 9,670 | /*
* 文 件 名: CkXmlException.java
* 版 权: gomyck
* 描 述: <描述>
* 修 改 人: 郝洋
* 修改时间: 2016-8-19
* 跟踪单号: <跟踪单号>
* 修改单号: <修改单号>
* 修改内容: <修改内容>
*/
package com.cevr.component.core;
/**
* <一句话功能简述> <功能详细描述>
*
* @author 郝洋
* @version [版本号, 2016-8-19]
* @see #XmlReaderException
* @since 1.0
*/
@SuppressWarnings("serial")
public class XmlReaderException extends RuntimeException {
/**
* <默认构造函数>
*/
public XmlReaderException() {
super();
}
/**
* <默认构造函数>
*/
public XmlReaderException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* <默认构造函数>
*/
public XmlReaderException(final String message) {
super(message);
}
/**
* <默认构造函数>
*/
public XmlReaderException(final Throwable cause) {
super(cause);
}
}
|
3e16acba48e9a34ac679786f32318a957a708fdd | 3,248 | java | Java | contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HivePartitionHolder.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 1,510 | 2015-01-04T01:35:19.000Z | 2022-03-28T23:36:02.000Z | contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HivePartitionHolder.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 1,979 | 2015-01-28T03:18:38.000Z | 2022-03-31T13:49:32.000Z | contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HivePartitionHolder.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 940 | 2015-01-01T01:39:39.000Z | 2022-03-25T08:46:59.000Z | 33.484536 | 114 | 0.728756 | 9,671 | /*
* 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.drill.exec.store.hive;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.hadoop.fs.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper class that stores partition values per key.
* Key to index mapper contains key and index corresponding to partition values position in partition values list.
* Since several keys may have that same partition values, such structure is optimized to save memory usage.
* Partition values are stored in list of consecutive values.
*/
public class HivePartitionHolder {
private final Map<Path, Integer> keyToIndexMapper;
private final List<List<String>> partitionValues;
@JsonCreator
public HivePartitionHolder(@JsonProperty("keyToIndexMapper") Map<Path, Integer> keyToIndexMapper,
@JsonProperty("partitionValues") List<List<String>> partitionValues) {
this.keyToIndexMapper = keyToIndexMapper;
this.partitionValues = partitionValues;
}
public HivePartitionHolder() {
this.keyToIndexMapper = new HashMap<>();
this.partitionValues = new ArrayList<>();
}
@JsonProperty
public Map<Path, Integer> getKeyToIndexMapper() {
return keyToIndexMapper;
}
@JsonProperty
public List<List<String>> getPartitionValues() {
return partitionValues;
}
/**
* Checks if partition values already exist in holder.
* If not, adds them to holder and adds key and index corresponding to partition values to mapper.
* If partition values exist, adds key and existing partition values index to mapper.
*
* @param key mapper key
* @param values partition values
*/
public void add(Path key, List<String> values) {
int index = partitionValues.indexOf(values);
if (index == -1) {
index = partitionValues.size();
partitionValues.add(values);
}
keyToIndexMapper.put(key, index);
}
/**
* Returns list of partition values stored in holder for the given key.
* If there are no corresponding partition values, return empty list.
*
* @param key mapper key
* @return list of partition values
*/
public List<String> get(Path key) {
Integer index = keyToIndexMapper.get(key);
if (index == null) {
return Collections.emptyList();
}
return partitionValues.get(index);
}
}
|
3e16add6d512960dc5061e2c2b46a9764a90e5a3 | 2,315 | java | Java | fabric-armor-api-v1/src/main/java/net/fabricmc/fabric/impl/armor/FabricArmorItem.java | BluCobalt/fabric | d2e8cdd6130558e5adcc18ce6f74a4967ba697f8 | [
"Apache-2.0"
] | 2 | 2020-12-01T02:28:00.000Z | 2020-12-03T06:20:36.000Z | fabric-armor-api-v1/src/main/java/net/fabricmc/fabric/impl/armor/FabricArmorItem.java | BluCobalt/fabric | d2e8cdd6130558e5adcc18ce6f74a4967ba697f8 | [
"Apache-2.0"
] | null | null | null | fabric-armor-api-v1/src/main/java/net/fabricmc/fabric/impl/armor/FabricArmorItem.java | BluCobalt/fabric | d2e8cdd6130558e5adcc18ce6f74a4967ba697f8 | [
"Apache-2.0"
] | null | null | null | 25.722222 | 104 | 0.757235 | 9,672 | /*
* Copyright (c) 2020 Legacy Fabric
* Copyright (c) 2016 - 2020 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.fabricmc.fabric.impl.armor;
import java.util.Random;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.ItemStack;
import net.fabricmc.fabric.api.armor.v1.ArmorMaterial;
import net.fabricmc.fabric.mixin.armor.MixinArmorItem;
public class FabricArmorItem extends ArmorItem {
private final ArmorMaterial material;
private final int slotId;
public FabricArmorItem(ArmorMaterial material, EquipmentSlot slot) {
super(/*Can be anything but null*/Material.DIAMOND, new Random().nextInt(16777216), slot.getSlotId());
this.material = material;
this.slotId = slot.getSlotId();
((MixinArmorItem) this).setProtection(material.getProtectionValue(slot.getSlotId()));
this.setMaxDamage(ArmorMaterial.BASE_DURABILITY[this.slotId] * material.getDurabilityMultiplier());
}
public ArmorMaterial getArmorMaterial() {
return this.material;
}
public EquipmentSlot getEquipmentSlot() {
return EquipmentSlot.getById(this.slotId);
}
@Override
public int getEnchantability() {
return this.material.getEnchantability();
}
@Override
public int getMaxCount() {
return 1;
}
public boolean canRepair(ItemStack stack, ItemStack ingredient) {
return this.material.getRepairIngredient().test(ingredient);
}
@Deprecated
@Override
public int getDisplayColor(ItemStack itemStack, int i) {
return i;
}
@Deprecated
@Override
public int getColor(ItemStack itemStack) {
return 16777215;
}
@Deprecated
@Override
public void removeColor(ItemStack stack) {
}
@Deprecated
@Override
public void setColor(ItemStack itemStack, int i) {
}
@Deprecated
@Override
public boolean hasColor(ItemStack stack) {
return false;
}
}
|
3e16ae72acda020ba72b305456987711c5aafeec | 5,379 | java | Java | limelight_run_importer/src/main/java/org/yeastrc/limelight/limelight_run_importer/database_update_with_transaction_services/GetNextTrackingToProcessDBTransaction.java | guoci/limelight-core | 6ce269903ebc5948dd844047d5a2b5580fdc5432 | [
"Apache-2.0"
] | 3 | 2019-02-21T21:23:04.000Z | 2021-07-12T18:30:03.000Z | limelight_run_importer/src/main/java/org/yeastrc/limelight/limelight_run_importer/database_update_with_transaction_services/GetNextTrackingToProcessDBTransaction.java | guoci/limelight-core | 6ce269903ebc5948dd844047d5a2b5580fdc5432 | [
"Apache-2.0"
] | 5 | 2020-11-13T01:30:36.000Z | 2021-11-24T22:18:53.000Z | limelight_run_importer/src/main/java/org/yeastrc/limelight/limelight_run_importer/database_update_with_transaction_services/GetNextTrackingToProcessDBTransaction.java | guoci/limelight-core | 6ce269903ebc5948dd844047d5a2b5580fdc5432 | [
"Apache-2.0"
] | 3 | 2021-01-31T18:42:54.000Z | 2021-07-11T20:33:07.000Z | 35.86 | 211 | 0.772263 | 9,673 | /*
* Original author: Daniel Jaschob <djaschob .at. uw.edu>
*
* Copyright 2018 University of Washington - Seattle, WA
*
* 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.yeastrc.limelight.limelight_run_importer.database_update_with_transaction_services;
import java.sql.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yeastrc.limelight.limelight_importer_runimporter_shared.db.ImportRunImporterDBConnectionFactory;
import org.yeastrc.limelight.limelight_importer_runimporter_shared.file_import_limelight_xml_scans.dao.FileImportTrackingRun_Importer_RunImporter_DAO;
import org.yeastrc.limelight.limelight_importer_runimporter_shared.file_import_limelight_xml_scans.dao.FileImportTracking_Importer_RunImporter_DAO;
import org.yeastrc.limelight.limelight_importer_runimporter_shared.file_import_limelight_xml_scans.objects.TrackingDTOTrackingRunDTOPair;
import org.yeastrc.limelight.limelight_run_importer.dao.FileImportTracking_For_ImporterRunner_DAO;
import org.yeastrc.limelight.limelight_shared.file_import_limelight_xml_scans.dto.FileImportTrackingDTO;
import org.yeastrc.limelight.limelight_shared.file_import_limelight_xml_scans.dto.FileImportTrackingRunDTO;
import org.yeastrc.limelight.limelight_shared.file_import_limelight_xml_scans.enum_classes.FileImportStatus;
/**
* Service for getting next Tracking to process, updating Tracking and updating and inserting Tracking Run records as a single DB transaction
*
*/
public class GetNextTrackingToProcessDBTransaction {
private static final Logger log = LoggerFactory.getLogger( GetNextTrackingToProcessDBTransaction.class );
private GetNextTrackingToProcessDBTransaction() { }
public static GetNextTrackingToProcessDBTransaction getInstance() {
return new GetNextTrackingToProcessDBTransaction();
}
/**
* @param maxPriority - max priority value to consider
* @return - null when no next record to process is found
* @throws Exception
*/
public TrackingDTOTrackingRunDTOPair getNextTrackingToProcess( int maxPriority ) throws Exception {
TrackingDTOTrackingRunDTOPair trackingDTOTrackingRunDTOPair = null;
FileImportTrackingDTO fileImportTrackingDTO = null;
FileImportTrackingRunDTO fileImportTrackingRunDTO = null;
Connection dbConnection = null;
try {
dbConnection = ImportRunImporterDBConnectionFactory.getInstance().getConnection();
dbConnection.setAutoCommit(false);
fileImportTrackingDTO =
FileImportTracking_For_ImporterRunner_DAO.getInstance().getNextQueued( maxPriority, dbConnection );
if ( fileImportTrackingDTO != null ) {
fileImportTrackingDTO.setStatus( FileImportStatus.STARTED );
FileImportTracking_Importer_RunImporter_DAO.getInstance()
.updateStatusStarted( fileImportTrackingDTO.getId(), dbConnection );
// Clear "current_run" on previous runs for tracking id
FileImportTrackingRun_Importer_RunImporter_DAO.getInstance()
.updateClearCurrentRunForTrackingId( fileImportTrackingDTO.getId(), dbConnection );
// Create a "run" db record
fileImportTrackingRunDTO = new FileImportTrackingRunDTO();
fileImportTrackingRunDTO.setFileImportTrackingId( fileImportTrackingDTO.getId() );
fileImportTrackingRunDTO.setRunStatus( FileImportStatus.STARTED );
FileImportTrackingRun_Importer_RunImporter_DAO.getInstance().save( fileImportTrackingRunDTO, dbConnection );
trackingDTOTrackingRunDTOPair = new TrackingDTOTrackingRunDTOPair();
trackingDTOTrackingRunDTOPair.setFileImportTrackingDTO( fileImportTrackingDTO );
trackingDTOTrackingRunDTOPair.setFileImportTrackingRunDTO( fileImportTrackingRunDTO );
}
dbConnection.commit();
} catch ( Exception e ) {
String msg = "Failed getNextTrackingToProcess(...)";
log.error( msg , e);
if ( dbConnection != null ) {
try {
dbConnection.rollback();
} catch (Exception ex) {
String msgRollback = "Rollback Exception: getNextTrackingToProcess(...) Exception: See Syserr or Sysout for original exception: Rollback Exception, tables are in an inconsistent state. '" + ex.toString();
System.out.println( msgRollback );
System.err.println( msgRollback );
log.error( msgRollback, ex );
throw new Exception( msgRollback, ex );
}
}
throw e;
} finally {
if( dbConnection != null ) {
try {
dbConnection.setAutoCommit(true); /// reset for next user of connection
} catch (Exception ex) {
String msg = "Failed dbConnection.setAutoCommit(true) in getNextTrackingToProcess(...)";
System.out.println( msg );
System.err.println( msg );
throw new Exception(msg);
}
try { dbConnection.close(); }
catch(Throwable t ) { ; }
dbConnection = null;
}
}
return trackingDTOTrackingRunDTOPair;
}
}
|
3e16af1ab815612a26dc1d77a00c39f13f68e082 | 151 | java | Java | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_8729.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | 1 | 2016-01-18T17:57:21.000Z | 2016-01-18T17:57:21.000Z | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_8729.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | null | null | null | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_8729.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | null | null | null | 18.875 | 52 | 0.827815 | 9,674 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_8729 {
}
|
3e16af3eb31b64f261d6e6c205b6d3e747cec6ad | 3,137 | java | Java | src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingDeleter.java | sjackso/twilio-java | fe3cbd8f6cd27d913bb61176fc959c5e7016c3d4 | [
"MIT"
] | null | null | null | src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingDeleter.java | sjackso/twilio-java | fe3cbd8f6cd27d913bb61176fc959c5e7016c3d4 | [
"MIT"
] | 11 | 2018-11-19T19:46:33.000Z | 2019-01-25T23:06:10.000Z | src/main/java/com/twilio/rest/api/v2010/account/conference/RecordingDeleter.java | TomMD/twilio-java | 00c11510fc1a1862ecc658874a044526c6222444 | [
"MIT"
] | null | null | null | 35.247191 | 143 | 0.636914 | 9,675 | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.api.v2010.account.conference;
import com.twilio.base.Deleter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
public class RecordingDeleter extends Deleter<Recording> {
private String pathAccountSid;
private final String pathConferenceSid;
private final String pathSid;
/**
* Construct a new RecordingDeleter.
*
* @param pathConferenceSid Fetch by unique conference Sid for the recording
* @param pathSid Delete by unique recording Sid
*/
public RecordingDeleter(final String pathConferenceSid,
final String pathSid) {
this.pathConferenceSid = pathConferenceSid;
this.pathSid = pathSid;
}
/**
* Construct a new RecordingDeleter.
*
* @param pathAccountSid The account_sid
* @param pathConferenceSid Fetch by unique conference Sid for the recording
* @param pathSid Delete by unique recording Sid
*/
public RecordingDeleter(final String pathAccountSid,
final String pathConferenceSid,
final String pathSid) {
this.pathAccountSid = pathAccountSid;
this.pathConferenceSid = pathConferenceSid;
this.pathSid = pathSid;
}
/**
* Make the request to the Twilio API to perform the delete.
*
* @param client TwilioRestClient with which to make the request
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public boolean delete(final TwilioRestClient client) {
this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid;
Request request = new Request(
HttpMethod.DELETE,
Domains.API.toString(),
"/2010-04-01/Accounts/" + this.pathAccountSid + "/Conferences/" + this.pathConferenceSid + "/Recordings/" + this.pathSid + ".json",
client.getRegion()
);
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("Recording delete failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(
restException.getMessage(),
restException.getCode(),
restException.getMoreInfo(),
restException.getStatus(),
null
);
}
return response.getStatusCode() == 204;
}
} |
3e16afcc7a34125a6ee8330b51ceaabb0cc1e0f1 | 16,404 | java | Java | javatests/com/google/gerrit/plugins/checks/acceptance/api/UpdateCheckIT.java | GerritCodeReview/plugins_checks | 2e3f9f291310b4f3822b4900c72a4e781d37c2bf | [
"Apache-2.0"
] | null | null | null | javatests/com/google/gerrit/plugins/checks/acceptance/api/UpdateCheckIT.java | GerritCodeReview/plugins_checks | 2e3f9f291310b4f3822b4900c72a4e781d37c2bf | [
"Apache-2.0"
] | null | null | null | javatests/com/google/gerrit/plugins/checks/acceptance/api/UpdateCheckIT.java | GerritCodeReview/plugins_checks | 2e3f9f291310b4f3822b4900c72a4e781d37c2bf | [
"Apache-2.0"
] | 1 | 2021-06-14T03:37:25.000Z | 2021-06-14T03:37:25.000Z | 36.697987 | 100 | 0.726652 | 9,676 | // Copyright (C) 2019 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.plugins.checks.acceptance.api;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.testing.GerritJUnit.assertThrows;
import com.google.gerrit.acceptance.UseClockStep;
import com.google.gerrit.acceptance.config.GerritConfig;
import com.google.gerrit.acceptance.testsuite.project.ProjectOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.entities.Project;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.plugins.checks.CheckKey;
import com.google.gerrit.plugins.checks.CheckerUuid;
import com.google.gerrit.plugins.checks.acceptance.AbstractCheckersTest;
import com.google.gerrit.plugins.checks.acceptance.testsuite.CheckTestData;
import com.google.gerrit.plugins.checks.acceptance.testsuite.CheckerTestData;
import com.google.gerrit.plugins.checks.api.CheckInfo;
import com.google.gerrit.plugins.checks.api.CheckInput;
import com.google.gerrit.plugins.checks.api.CheckState;
import com.google.gerrit.server.util.time.TimeUtil;
import com.google.gerrit.testing.TestTimeUtil;
import com.google.inject.Inject;
import java.sql.Timestamp;
import org.junit.Before;
import org.junit.Test;
@UseClockStep(startAtEpoch = true)
public class UpdateCheckIT extends AbstractCheckersTest {
@Inject private RequestScopeOperations requestScopeOperations;
@Inject private ProjectOperations projectOperations;
private PatchSet.Id patchSetId;
private CheckKey checkKey;
@Before
public void setUp() throws Exception {
patchSetId = createChange().getPatchSetId();
CheckerUuid checkerUuid = checkerOperations.newChecker().repository(project).create();
checkKey = CheckKey.create(project, patchSetId, checkerUuid);
checkOperations.newCheck(checkKey).upsert();
}
@Test
public void updateCheckState() throws Exception {
CheckInput input = new CheckInput();
input.state = CheckState.FAILED;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.FAILED);
}
@Test
public void cannotUpdateCheckerUuid() throws Exception {
CheckInput input = new CheckInput();
input.checkerUuid = "foo:bar";
BadRequestException thrown =
assertThrows(
BadRequestException.class,
() -> checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input));
assertThat(thrown)
.hasMessageThat()
.contains("checker UUID in input must either be null or the same as on the resource");
}
@Test
public void specifyingCheckerUuidInInputThatMatchesTheCheckerUuidInTheUrlIsOkay()
throws Exception {
CheckInput input = new CheckInput();
input.checkerUuid = checkKey.checkerUuid().get();
checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
}
@Test
public void updateMessage() throws Exception {
CheckInput input = new CheckInput();
input.message = "some message";
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.message).isEqualTo(input.message);
}
@Test
public void updateMessage_rejected_tooLong() {
CheckInput input = new CheckInput();
input.message = new String(new char[10_001]).replace('\0', 'x');
BadRequestException thrown =
assertThrows(
BadRequestException.class,
() -> checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input));
assertThat(thrown).hasMessageThat().contains("exceeds size limit (10001 > 10000)");
}
@Test
@GerritConfig(name = "plugin.checks.messageSizeLimit", value = "5")
public void updateMessage_rejected_configureLimit() {
CheckInput input = new CheckInput();
input.message = "foobar";
BadRequestException thrown =
assertThrows(
BadRequestException.class,
() -> checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input));
assertThat(thrown).hasMessageThat().contains("exceeds size limit (6 > 5)");
}
@Test
public void unsetMessage() throws Exception {
checkOperations.check(checkKey).forUpdate().message("some message").upsert();
CheckInput input = new CheckInput();
input.message = "";
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.message).isNull();
}
@Test
public void updateUrl() throws Exception {
CheckInput input = new CheckInput();
input.url = "http://example.com/my-check";
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.url).isEqualTo(input.url);
}
@Test
public void unsetUrl() throws Exception {
checkOperations.check(checkKey).forUpdate().url("http://example.com/my-check").upsert();
CheckInput input = new CheckInput();
input.url = "";
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.url).isNull();
}
@Test
public void cannotSetInvalidUrl() throws Exception {
CheckInput input = new CheckInput();
input.url = CheckTestData.INVALID_URL;
BadRequestException thrown =
assertThrows(
BadRequestException.class,
() -> checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input));
assertThat(thrown).hasMessageThat().contains("only http/https URLs supported: " + input.url);
}
@Test
public void updateStarted() throws Exception {
CheckInput input = new CheckInput();
input.started = TimeUtil.nowTs();
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.started).isEqualTo(input.started);
}
@Test
public void unsetStarted() throws Exception {
checkOperations.check(checkKey).forUpdate().started(TimeUtil.nowTs()).upsert();
CheckInput input = new CheckInput();
input.started = TimeUtil.never();
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.started).isNull();
}
@Test
public void updateFinished() throws Exception {
CheckInput input = new CheckInput();
input.finished = TimeUtil.nowTs();
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.finished).isEqualTo(input.finished);
}
@Test
public void unsetFinished() throws Exception {
checkOperations.check(checkKey).forUpdate().finished(TimeUtil.nowTs()).upsert();
CheckInput input = new CheckInput();
input.finished = TimeUtil.never();
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.finished).isNull();
}
@Test
public void updateWithEmptyInput() throws Exception {
assertThat(
checksApiFactory
.revision(patchSetId)
.id(checkKey.checkerUuid())
.update(new CheckInput()))
.isNotNull();
}
@Test
public void updateResultsInNewUpdatedTimestamp() throws Exception {
CheckInput input = new CheckInput();
input.state = CheckState.FAILED;
Timestamp expectedUpdateTimestamp = TestTimeUtil.getCurrentTimestamp();
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.updated).isEqualTo(expectedUpdateTimestamp);
}
@Test
public void noOpUpdateDoesntResultInNewUpdatedTimestamp() throws Exception {
CheckInput input = new CheckInput();
input.state = CheckState.FAILED;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
Timestamp expectedUpdateTimestamp = info.updated;
info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.updated).isEqualTo(expectedUpdateTimestamp);
}
@Test
public void canUpdateCheckForDisabledChecker() throws Exception {
checkerOperations.checker(checkKey.checkerUuid()).forUpdate().disable().update();
CheckInput input = new CheckInput();
input.state = CheckState.SUCCESSFUL;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.SUCCESSFUL);
}
@Test
public void canUpdateCheckForCheckerThatDoesNotApplyToTheProjectAndCheckExists()
throws Exception {
Project.NameKey otherProject = projectOperations.newProject().create();
checkerOperations.checker(checkKey.checkerUuid()).forUpdate().repository(otherProject).update();
CheckInput input = new CheckInput();
input.state = CheckState.SUCCESSFUL;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.SUCCESSFUL);
}
@Test
public void
throwExceptionForUpdateCheckForCheckerThatDoesNotApplyToTheProjectAndCheckDoesNotExist()
throws Exception {
Project.NameKey otherProject = projectOperations.newProject().create();
CheckerUuid checkerUuid = checkerOperations.newChecker().repository(otherProject).create();
CheckKey checkKey = CheckKey.create(otherProject, patchSetId, checkerUuid);
assertThrows(
ResourceNotFoundException.class,
() ->
checksApiFactory
.revision(patchSetId)
.id(checkKey.checkerUuid())
.update(new CheckInput()));
}
@Test
public void canUpdateCheckForCheckerWithUnsupportedOperatorInQuery() throws Exception {
checkerOperations
.checker(checkKey.checkerUuid())
.forUpdate()
.query(CheckerTestData.QUERY_WITH_UNSUPPORTED_OPERATOR)
.update();
CheckInput input = new CheckInput();
input.state = CheckState.SUCCESSFUL;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.SUCCESSFUL);
}
@Test
public void canUpdateCheckForCheckerWithInvalidQuery() throws Exception {
checkerOperations
.checker(checkKey.checkerUuid())
.forUpdate()
.query(CheckerTestData.INVALID_QUERY)
.update();
CheckInput input = new CheckInput();
input.state = CheckState.SUCCESSFUL;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.SUCCESSFUL);
}
@Test
public void canUpdateCheckForCheckerThatDoesNotApplyToTheChange() throws Exception {
checkerOperations
.checker(checkKey.checkerUuid())
.forUpdate()
.query("message:not-matching")
.update();
CheckInput input = new CheckInput();
input.state = CheckState.SUCCESSFUL;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.SUCCESSFUL);
}
@Test
public void canUpdateCheckForNonExistingChecker() throws Exception {
checkerOperations.checker(checkKey.checkerUuid()).forInvalidation().deleteRef().invalidate();
CheckInput input = new CheckInput();
input.state = CheckState.SUCCESSFUL;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.SUCCESSFUL);
}
@Test
public void canUpdateCheckForInvalidChecker() throws Exception {
checkerOperations
.checker(checkKey.checkerUuid())
.forInvalidation()
.nonParseableConfig()
.invalidate();
CheckInput input = new CheckInput();
input.state = CheckState.SUCCESSFUL;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.SUCCESSFUL);
}
@Test
public void cannotUpdateCheckWithoutAdministrateCheckers() throws Exception {
requestScopeOperations.setApiUser(user.id());
AuthException thrown =
assertThrows(
AuthException.class,
() ->
checksApiFactory
.revision(patchSetId)
.id(checkKey.checkerUuid())
.update(new CheckInput()));
assertThat(thrown).hasMessageThat().contains("not permitted");
}
@Test
public void cannotUpdateCheckAnonymously() throws Exception {
requestScopeOperations.setApiUserAnonymous();
AuthException thrown =
assertThrows(
AuthException.class,
() ->
checksApiFactory
.revision(patchSetId)
.id(checkKey.checkerUuid())
.update(new CheckInput()));
assertThat(thrown).hasMessageThat().contains("Authentication required");
}
@Test
public void otherPropertiesCanBeSetWithoutEverSettingTheState() throws Exception {
// Create a new checker so that we know for sure that no other update ever happened for it.
CheckerUuid checkerUuid = checkerOperations.newChecker().repository(project).create();
CheckInput input = new CheckInput();
input.url = "https://www.example.com";
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkerUuid).update(input);
assertThat(info.url).isEqualTo("https://www.example.com");
assertThat(info.state).isEqualTo(CheckState.NOT_STARTED);
}
@Test
public void stateCanBeSetToNotStarted() throws Exception {
checkOperations.check(checkKey).forUpdate().state(CheckState.FAILED).upsert();
CheckInput input = new CheckInput();
input.state = CheckState.NOT_STARTED;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.state).isEqualTo(CheckState.NOT_STARTED);
}
@Test
public void otherPropertiesAreKeptWhenStateIsSetToNotStarted() throws Exception {
checkOperations
.check(checkKey)
.forUpdate()
.state(CheckState.FAILED)
.message("some message")
.url("https://www.example.com")
.upsert();
CheckInput input = new CheckInput();
input.state = CheckState.NOT_STARTED;
CheckInfo info = checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
assertThat(info.message).isEqualTo("some message");
assertThat(info.url).isEqualTo("https://www.example.com");
}
@Test
public void updateOfCheckChangesETagOfChange() throws Exception {
String oldETag = parseChangeResource(patchSetId.changeId().toString()).getETag();
CheckInput input = new CheckInput();
input.state = CheckState.FAILED;
checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
String newETag = parseChangeResource(patchSetId.changeId().toString()).getETag();
assertThat(newETag).isNotEqualTo(oldETag);
}
@Test
public void noOpUpdateOfCheckDoesNotChangeETagOfChange() throws Exception {
CheckInput input = new CheckInput();
input.state = CheckState.FAILED;
checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
String oldETag = parseChangeResource(patchSetId.changeId().toString()).getETag();
checksApiFactory.revision(patchSetId).id(checkKey.checkerUuid()).update(input);
String newETag = parseChangeResource(patchSetId.changeId().toString()).getETag();
assertThat(newETag).isEqualTo(oldETag);
}
}
|
3e16afdfb4930f7af0e9658c5f8adde91e581c56 | 3,615 | java | Java | build/src/main/java/com/mypurecloud/sdk/v2/api/request/PutGreetingsDefaultsRequest.java | Dschinds/platform-client-sdk-java | 8fbf2b9bb4ef89347e0e71d1c874737201d7e58b | [
"MIT"
] | 3 | 2018-05-22T14:33:38.000Z | 2020-05-06T15:33:36.000Z | build/src/main/java/com/mypurecloud/sdk/v2/api/request/PutGreetingsDefaultsRequest.java | Dschinds/platform-client-sdk-java | 8fbf2b9bb4ef89347e0e71d1c874737201d7e58b | [
"MIT"
] | 4 | 2018-05-18T13:52:45.000Z | 2019-11-06T18:04:56.000Z | build/src/main/java/com/mypurecloud/sdk/v2/api/request/PutGreetingsDefaultsRequest.java | Dschinds/platform-client-sdk-java | 8fbf2b9bb4ef89347e0e71d1c874737201d7e58b | [
"MIT"
] | 10 | 2018-05-18T00:08:16.000Z | 2022-02-17T08:45:42.000Z | 28.464567 | 144 | 0.706224 | 9,677 | package com.mypurecloud.sdk.v2.api.request;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.mypurecloud.sdk.v2.ApiException;
import com.mypurecloud.sdk.v2.ApiClient;
import com.mypurecloud.sdk.v2.ApiRequest;
import com.mypurecloud.sdk.v2.ApiRequestBuilder;
import com.mypurecloud.sdk.v2.ApiResponse;
import com.mypurecloud.sdk.v2.Configuration;
import com.mypurecloud.sdk.v2.model.*;
import com.mypurecloud.sdk.v2.Pair;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import com.mypurecloud.sdk.v2.model.ErrorBody;
import com.mypurecloud.sdk.v2.model.Greeting;
import com.mypurecloud.sdk.v2.model.GreetingMediaInfo;
import com.mypurecloud.sdk.v2.model.DomainEntityListing;
import com.mypurecloud.sdk.v2.model.DefaultGreetingList;
import com.mypurecloud.sdk.v2.model.GreetingListing;
public class PutGreetingsDefaultsRequest {
private DefaultGreetingList body;
public DefaultGreetingList getBody() {
return this.body;
}
public void setBody(DefaultGreetingList body) {
this.body = body;
}
public PutGreetingsDefaultsRequest withBody(DefaultGreetingList body) {
this.setBody(body);
return this;
}
private final Map<String, String> customHeaders = new HashMap<>();
public Map<String, String> getCustomHeaders() {
return this.customHeaders;
}
public void setCustomHeaders(Map<String, String> customHeaders) {
this.customHeaders.clear();
this.customHeaders.putAll(customHeaders);
}
public void addCustomHeader(String name, String value) {
this.customHeaders.put(name, value);
}
public PutGreetingsDefaultsRequest withCustomHeader(String name, String value) {
this.addCustomHeader(name, value);
return this;
}
public ApiRequest<DefaultGreetingList> withHttpInfo() {
// verify the required parameter 'body' is set
if (this.body == null) {
throw new IllegalStateException("Missing the required parameter 'body' when building request for PutGreetingsDefaultsRequest.");
}
return ApiRequestBuilder.create("PUT", "/api/v2/greetings/defaults")
.withBody(body)
.withCustomHeaders(customHeaders)
.withContentTypes("application/json")
.withAccepts("application/json")
.withAuthNames("PureCloud OAuth")
.build();
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(DefaultGreetingList body) {
return new Builder()
.withRequiredParams(body);
}
public static class Builder {
private final PutGreetingsDefaultsRequest request;
private Builder() {
request = new PutGreetingsDefaultsRequest();
}
public Builder withBody(DefaultGreetingList body) {
request.setBody(body);
return this;
}
public Builder withRequiredParams(DefaultGreetingList body) {
request.setBody(body);
return this;
}
public PutGreetingsDefaultsRequest build() {
// verify the required parameter 'body' is set
if (request.body == null) {
throw new IllegalStateException("Missing the required parameter 'body' when building request for PutGreetingsDefaultsRequest.");
}
return request;
}
}
}
|
3e16afe6ce67cab007879ec1fb7bd0b4e6877d7a | 2,701 | java | Java | src/org/tech/frontier/db/models/ArticleDetailModel.java | yrickwong/the-tech-frontier-app | cfb5b9e663e40f1ff518a27eedc9634a5838facc | [
"MIT"
] | 77 | 2016-04-23T04:03:04.000Z | 2021-11-12T11:59:53.000Z | src/org/tech/frontier/db/models/ArticleDetailModel.java | oumogang/the-tech-frontier-app | cfb5b9e663e40f1ff518a27eedc9634a5838facc | [
"MIT"
] | 12 | 2015-05-19T14:32:23.000Z | 2015-12-18T05:55:44.000Z | src/org/tech/frontier/db/models/ArticleDetailModel.java | oumogang/the-tech-frontier-app | cfb5b9e663e40f1ff518a27eedc9634a5838facc | [
"MIT"
] | 45 | 2015-05-13T12:54:43.000Z | 2016-03-31T02:47:48.000Z | 37.513889 | 102 | 0.697149 | 9,678 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 Umeng, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.tech.frontier.db.models;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import org.tech.frontier.db.ArticleDetailDBAPI;
import org.tech.frontier.db.cmd.Command;
import org.tech.frontier.entities.ArticleDetail;
import org.tech.frontier.listeners.DataListener;
/**
* 操作文章内容相关的数据库实现
*
* @author mrsimple
*/
class ArticleDetailModel extends ArticleDetailDBAPI {
@Override
protected ContentValues toContentValues(ArticleDetail detail) {
ContentValues contentValues = new ContentValues();
contentValues.put("post_id", detail.postId);
contentValues.put("content", detail.content);
return contentValues;
}
@Override
public void fetchArticleContent(final String postId, final DataListener<ArticleDetail> listener) {
sDbExecutor.execute(new Command<ArticleDetail>(listener) {
@Override
protected ArticleDetail doInBackground(SQLiteDatabase database) {
Cursor cursor = database.query(mTableName, new String[] {
"content"
}, "post_id=?", new String[] {
postId
}, null, null, null);
String result = queryArticleCotent(cursor);
cursor.close();
return new ArticleDetail(postId, result);
}
});
}
private String queryArticleCotent(Cursor cursor) {
return cursor.moveToNext() ? cursor.getString(0) : "";
}
}
|
3e16b0cf1ddbfc2762f6bcb31be6317a28f3d783 | 1,702 | java | Java | src/drcl/inet/sensorsim/OneHopTDMA/OH_TDMA_Packet.java | M-Artemisia/Msc-Thesis | 17b9fd899e4ae78260f84af556ef747c5e1c3417 | [
"BSD-3-Clause"
] | null | null | null | src/drcl/inet/sensorsim/OneHopTDMA/OH_TDMA_Packet.java | M-Artemisia/Msc-Thesis | 17b9fd899e4ae78260f84af556ef747c5e1c3417 | [
"BSD-3-Clause"
] | null | null | null | src/drcl/inet/sensorsim/OneHopTDMA/OH_TDMA_Packet.java | M-Artemisia/Msc-Thesis | 17b9fd899e4ae78260f84af556ef747c5e1c3417 | [
"BSD-3-Clause"
] | null | null | null | 24.314286 | 108 | 0.608696 | 9,679 | package drcl.inet.sensorsim.OneHopTDMA;
import drcl.net.Packet;
/**
* @author Nicholas Merizzi
* @version 1.0, 06/03/2005
*
* This class represent the body of a packet that is used when sensors want to send their
* periodic updates back to the base station. It is essentially a data packet which contains
* 5 pieces of information: Who sent it, the senders location (i.e. its coordinates), a
* timestamp to keep track of latency, the size, and the latest data sensed (i.e the phenomenon the sensors
* are sensing).
*
*/
public class OH_TDMA_Packet extends Packet {
long sender_id; //sender ID
private double[] sender_pos; //what position the sender is at
double timeStamp; //what time the packet was sent at
public OH_TDMA_Packet(long sid, double[] s_pos, double timeStamp_, int size_, Object phenomenon_)
{
sender_id = sid;
this.sender_pos = new double[3];
this.sender_pos = s_pos;
this.timeStamp = timeStamp_;
size = size_;
body = phenomenon_;
}
public long getSID()
{
return(sender_id);
}
public double getSenderX()
{
return (sender_pos[0]);
}
public double getSenderY()
{
return (sender_pos[1]);
}
public double getSenderZ()
{
return (sender_pos[2]);
}
public double getSendTime()
{
return (timeStamp);
}
public String getName()
{
return "One Hop TDMA Packet";
}
public Object clone()
{
return new OH_TDMA_Packet(this.sender_id,this.sender_pos, this.timeStamp, size, body);
}
}
|
3e16b1a2f61e5247f5c919c5e60c4bb68c741953 | 8,410 | java | Java | Data/Juliet-Java/Juliet-Java-v103/000/138/420/CWE400_Resource_Exhaustion__getQueryString_Servlet_for_loop_12.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/138/420/CWE400_Resource_Exhaustion__getQueryString_Servlet_for_loop_12.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/138/420/CWE400_Resource_Exhaustion__getQueryString_Servlet_for_loop_12.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | 35.787234 | 134 | 0.500357 | 9,680 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE400_Resource_Exhaustion__getQueryString_Servlet_for_loop_12.java
Label Definition File: CWE400_Resource_Exhaustion.label.xml
Template File: sources-sinks-12.tmpl.java
*/
/*
* @description
* CWE: 400 Resource Exhaustion
* BadSource: getQueryString_Servlet Parse id param out of the URL query string (without using getParameter())
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: for_loop
* GoodSink: Validate count before using it as the loop variant in a for loop
* BadSink : Use count as the loop variant in a for loop
* Flow Variant: 12 Control flow: if(IO.staticReturnsTrueOrFalse())
*
* */
import javax.servlet.http.*;
import java.util.StringTokenizer;
import java.util.logging.Level;
public class CWE400_Resource_Exhaustion__getQueryString_Servlet_for_loop_12 extends AbstractTestCaseServlet
{
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int count;
if(IO.staticReturnsTrueOrFalse())
{
count = Integer.MIN_VALUE; /* initialize count in case id is not in query string */
/* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
{
StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken(); /* a token will be like "id=33" */
if(token.startsWith("id=")) /* check if we have the "id" parameter" */
{
try
{
count = Integer.parseInt(token.substring(3)); /* set count to the int 33 */
}
catch(NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception reading id from query string", exceptNumberFormat);
}
break; /* exit while loop */
}
}
}
}
else
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
count = 2;
}
if(IO.staticReturnsTrueOrFalse())
{
int i = 0;
/* POTENTIAL FLAW: For loop using count as the loop variant and no validation */
for (i = 0; i < count; i++)
{
IO.writeLine("Hello");
}
}
else
{
int i = 0;
/* FIX: Validate count before using it as the for loop variant */
if (count > 0 && count <= 20)
{
for (i = 0; i < count; i++)
{
IO.writeLine("Hello");
}
}
}
}
/* goodG2B() - use goodsource and badsink by changing the first "if" so that
* both branches use the GoodSource */
private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int count;
if(IO.staticReturnsTrueOrFalse())
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
count = 2;
}
else
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
count = 2;
}
if(IO.staticReturnsTrueOrFalse())
{
int i = 0;
/* POTENTIAL FLAW: For loop using count as the loop variant and no validation */
for (i = 0; i < count; i++)
{
IO.writeLine("Hello");
}
}
else
{
int i = 0;
/* POTENTIAL FLAW: For loop using count as the loop variant and no validation */
for (i = 0; i < count; i++)
{
IO.writeLine("Hello");
}
}
}
/* goodB2G() - use badsource and goodsink by changing the second "if" so that
* both branches use the GoodSink */
private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
int count;
if(IO.staticReturnsTrueOrFalse())
{
count = Integer.MIN_VALUE; /* initialize count in case id is not in query string */
/* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
{
StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken(); /* a token will be like "id=33" */
if(token.startsWith("id=")) /* check if we have the "id" parameter" */
{
try
{
count = Integer.parseInt(token.substring(3)); /* set count to the int 33 */
}
catch(NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception reading id from query string", exceptNumberFormat);
}
break; /* exit while loop */
}
}
}
}
else
{
count = Integer.MIN_VALUE; /* initialize count in case id is not in query string */
/* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */
{
StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken(); /* a token will be like "id=33" */
if(token.startsWith("id=")) /* check if we have the "id" parameter" */
{
try
{
count = Integer.parseInt(token.substring(3)); /* set count to the int 33 */
}
catch(NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception reading id from query string", exceptNumberFormat);
}
break; /* exit while loop */
}
}
}
}
if(IO.staticReturnsTrueOrFalse())
{
int i = 0;
/* FIX: Validate count before using it as the for loop variant */
if (count > 0 && count <= 20)
{
for (i = 0; i < count; i++)
{
IO.writeLine("Hello");
}
}
}
else
{
int i = 0;
/* FIX: Validate count before using it as the for loop variant */
if (count > 0 && count <= 20)
{
for (i = 0; i < count; i++)
{
IO.writeLine("Hello");
}
}
}
}
public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
goodG2B(request, response);
goodB2G(request, response);
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
3e16b3a2ea9a39577ebc6bb7071ab806356a4c0d | 1,569 | java | Java | src/main/java/cn/ucaner/leecode/cspiration/_60_PermutationSequence.java | Jasonandy/LeeCode | 3aef88493edf39d629807f41ef3b7974d4e14d2d | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/ucaner/leecode/cspiration/_60_PermutationSequence.java | Jasonandy/LeeCode | 3aef88493edf39d629807f41ef3b7974d4e14d2d | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/ucaner/leecode/cspiration/_60_PermutationSequence.java | Jasonandy/LeeCode | 3aef88493edf39d629807f41ef3b7974d4e14d2d | [
"Apache-2.0"
] | null | null | null | 21.493151 | 70 | 0.456342 | 9,681 | package cn.ucaner.leecode.cspiration;
import java.util.ArrayList;
import java.util.List;
public class _60_PermutationSequence {
/**
* 60. Permutation Sequence
* The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
1, 2, 3, 4:
1 + {2, 3, 4}
2 + {1, 3, 4}
3 + {1, 2, 4}
4 + {1, 2, 3}
18 : 3421
res :
fact : 1 1 2 6
k = 17
i = 4 index = 17 / 6 = 2 k = 17 % 6 = 5
i = 3 index = 5 / 2 = 2 k = 5 % 2 = 1
i = 2 index = 1 / 1 = 1 k = 1 % 1 = 0
4 3 2 1
3 4 2 1
time : O(n^2)
space : O(n)
* @param n
* @param k
* @return
*/
public static String getPermutation(int n, int k) {
List<Integer> res = new ArrayList<>();
for (int i = 1; i <= n; i++) {
res.add(i);
}
int[] fact = new int[n];
fact[0] = 1;
for (int i = 1; i < n; i++) {
fact[i] = i * fact[i - 1];
}
k = k - 1;
StringBuilder sb = new StringBuilder();
for (int i = n; i > 0; i--) {
int index = k / fact[i - 1];
k = k % fact[i - 1];
sb.append(res.get(index));
res.remove(index);
}
return sb.toString();
}
}
|
3e16b41c313776e2ee03b2b538cb3df4e28e6225 | 912 | java | Java | jshuntingyard/src/main/java/org/oss/jshuntingyard/evaluator/NullArgument.java | OpenSoftwareSolutions/jhuntingyard | 2de47c057adacc6876696aa3fc112519d5eed1fb | [
"Apache-2.0"
] | 2 | 2016-07-28T19:27:36.000Z | 2017-06-19T22:28:30.000Z | jshuntingyard/src/main/java/org/oss/jshuntingyard/evaluator/NullArgument.java | OpenSoftwareSolutions/jhuntingyard | 2de47c057adacc6876696aa3fc112519d5eed1fb | [
"Apache-2.0"
] | 6 | 2015-08-28T16:14:47.000Z | 2016-11-07T20:58:11.000Z | jshuntingyard/src/main/java/org/oss/jshuntingyard/evaluator/NullArgument.java | OpenSoftwareSolutions/jhuntingyard | 2de47c057adacc6876696aa3fc112519d5eed1fb | [
"Apache-2.0"
] | null | null | null | 30.4 | 75 | 0.762061 | 9,682 | /**
* Copyright [2015] [Open Software Solutions 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.oss.jshuntingyard.evaluator;
public class NullArgument extends AbstractFunctionElementArgument<Object>{
@Override
public FunctionElementArgument.ArgumentType getType() {
return FunctionElementArgument.ArgumentType.NULL;
}
@Override
public Object getValue() {
return null;
}
}
|
3e16b482e9b662e3a1a8af3a2f6c26f6d5bc3453 | 791 | java | Java | Chapter_2/src/com/wuroc/chapterfour/LabeledWhile.java | WuRoc/ThinkingInJava | 42c8bb10afa93bfe69cfd4b62005555a6153ebdb | [
"MIT"
] | 1 | 2020-07-16T16:01:35.000Z | 2020-07-16T16:01:35.000Z | Chapter_2/src/com/wuroc/chapterfour/LabeledWhile.java | WuRoc/Thinking-In-Java---StudyNotes | 038fa7e98ce6313a2cbdcb6d9e7b4fce8aed708f | [
"MIT"
] | null | null | null | Chapter_2/src/com/wuroc/chapterfour/LabeledWhile.java | WuRoc/Thinking-In-Java---StudyNotes | 038fa7e98ce6313a2cbdcb6d9e7b4fce8aed708f | [
"MIT"
] | null | null | null | 11.80597 | 44 | 0.475348 | 9,683 | //: LabeledWhile.java
package com.wuroc.chapterfour;
/**
* @author WuRoc
* @GitHub www.github.com/WuRoc
* @version 1.0
* @2020年7月6日
*
*
*/
public class LabeledWhile {
public static void main(String[] args) {
int i = 0;
outer:
while(true) {
System.out.println("Outer while loop");
while(true) {
i++;
System.out.println("i = " + i);
if(i == 1) {
System.out.println("continue");
continue;
}
if(i == 3) {
System.out.println("continue outer");
continue outer;
}
if(i == 5) {
System.out.println("break");
break;
}
if(i == 7) {
System.out.println("break outer");
break outer;
}
}
}
}
}
|
3e16b54370effb9e6ff356136accd023fbeb35d4 | 568 | java | Java | chapter05/chapter05.00/src/main/java/io/baselogic/springsecurity/Application.java | rozdolsky33/spring_security_course | 2dbcf25498e0791fa423c63cccca2555cbe3d031 | [
"BSD-2-Clause"
] | 1 | 2020-10-12T15:31:12.000Z | 2020-10-12T15:31:12.000Z | chapter05/chapter05.00/src/main/java/io/baselogic/springsecurity/Application.java | rozdolsky33/spring_security_course | 2dbcf25498e0791fa423c63cccca2555cbe3d031 | [
"BSD-2-Clause"
] | null | null | null | chapter05/chapter05.00/src/main/java/io/baselogic/springsecurity/Application.java | rozdolsky33/spring_security_course | 2dbcf25498e0791fa423c63cccca2555cbe3d031 | [
"BSD-2-Clause"
] | null | null | null | 27.047619 | 68 | 0.797535 | 9,684 | package io.baselogic.springsecurity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.crypto.password.PasswordEncoder;
@SpringBootApplication
@Slf4j
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
private PasswordEncoder passwordEncoder;
} // The End...
|
3e16b5d7fc29a2e7390d0f788e781749cfa7ee9d | 25,331 | java | Java | si-onem2m-src/IITP_IoT_2_7/src/main/java/net/herit/iot/onem2m/core/convertor/ConvertorFactory.java | uguraba/SI | 9e0f89a7413c351b2f739b1ee8ae2687c04d5ec1 | [
"BSD-2-Clause"
] | 47 | 2015-12-31T07:10:44.000Z | 2021-12-15T13:31:00.000Z | si-onem2m-src/IITP_IoT_2_7/src/main/java/net/herit/iot/onem2m/core/convertor/ConvertorFactory.java | uguraba/SI | 9e0f89a7413c351b2f739b1ee8ae2687c04d5ec1 | [
"BSD-2-Clause"
] | 6 | 2016-01-27T03:30:46.000Z | 2020-11-24T11:48:26.000Z | si-onem2m-src/IITP_IoT_2_7/src/main/java/net/herit/iot/onem2m/core/convertor/ConvertorFactory.java | uguraba/SI | 9e0f89a7413c351b2f739b1ee8ae2687c04d5ec1 | [
"BSD-2-Clause"
] | 31 | 2016-01-11T12:35:34.000Z | 2020-02-20T13:12:21.000Z | 55.30786 | 128 | 0.748687 | 9,685 | package net.herit.iot.onem2m.core.convertor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import net.herit.iot.message.onem2m.OneM2mResponse.RESPONSE_STATUS;
import net.herit.iot.onem2m.core.util.OneM2MException;
import net.herit.iot.onem2m.resource.*;
public class ConvertorFactory {
private static HashMap<Class<?>, DaoJSONConvertor<?>> daoJsonMap = new HashMap<Class<?>, DaoJSONConvertor<?>>();
private static HashMap<Class<?>, JSONConvertor<?>> jsonMap = new HashMap<Class<?>, JSONConvertor<?>>();
private static HashMap<Class<?>, XMLConvertor<?>> xmlMap = new HashMap<Class<?>, XMLConvertor<?>>();
private static int maxCiCount = 10;
private static AtomicInteger curCiIndex;
private static ArrayList<XMLConvertor<ContentInstance>> xmlCiCvtArr = new ArrayList<XMLConvertor<ContentInstance>>();
public static void initialize(int maxCnt) throws OneM2MException {
curCiIndex.set(0);
maxCiCount = maxCnt;
for (int i = 0; i< maxCiCount; i++) {
xmlCiCvtArr.add((XMLConvertor<ContentInstance>)createXMLConvertor(ContentInstance.class, ContentInstance.SCHEMA_LOCATION));
}
}
public static DaoJSONConvertor<?> getDaoJSONConvertor(Class<?> t, String schema) throws OneM2MException {
DaoJSONConvertor<?> cvt = daoJsonMap.get(t);
if (cvt == null) {
cvt = createDaoJSONConvertor(t, schema);
daoJsonMap.put(t, cvt);
}
return cvt;
}
public static JSONConvertor<?> getJSONConvertor(Class<?> t, String schema) throws OneM2MException {
JSONConvertor<?> cvt = jsonMap.get(t);
if (cvt == null) {
cvt = createJSONConvertor(t, schema);
jsonMap.put(t, cvt);
}
return cvt;
}
public static XMLConvertor<?> getXMLConvertor(Class<?> t, String schema) throws OneM2MException {
XMLConvertor<?> cvt = xmlMap.get(t);
if (cvt == null) {
cvt = createXMLConvertor(t, schema);
xmlMap.put(t, cvt);
}
return cvt;
}
public static XMLConvertor<?> getXMLConvertorCI() throws OneM2MException {
XMLConvertor<ContentInstance> cvt = xmlCiCvtArr.get(curCiIndex.addAndGet(1) % maxCiCount);
return cvt;
}
static DaoJSONConvertor<?> createDaoJSONConvertor(Class<?> t, String schema) throws OneM2MException {
DaoJSONConvertor<?> ContInstXC;
if (t.equals(UriContent.class)) {
ContInstXC = new DaoJSONConvertor<UriContent>(UriContent.class);
} else if (t.equals(UriListContent.class)) {
ContInstXC = new DaoJSONConvertor<UriListContent>(UriListContent.class);
} else if (t.equals(Notification.class)) {
//ContInstXC = new JSONConvertor<Notification>(Notification.class);
ContInstXC = new DaoJSONConvertor<Notification>(Notification.class,
new Class[] {Notification.class,UriListContent.class,AccessControlPolicy.class,AE.class,
Container.class,ContentInstance.class,CSEBase.class,Delivery.class,
EventConfig.class,ExecInstance.class,Group.class,LocationPolicy.class,
MgmtCmd.class,Node.class,PollingChannel.class,RemoteCSE.class,Request.class,
Schedule.class,ServiceSubscribedAppRule.class,ServiceSubscribedNode.class,
StatsCollect.class,StatsConfig.class,Subscription.class,AccessControlPolicyAnnc.class,
AEAnnc.class,ContainerAnnc.class,ContentInstanceAnnc.class,GroupAnnc.class,
LocationPolicyAnnc.class,NodeAnnc.class,RemoteCSEAnnc.class,ScheduleAnnc.class, String.class});
} else if (t.equals(AggregatedResponse.class)) {
ContInstXC = new DaoJSONConvertor<AggregatedResponse>(AggregatedResponse.class);
} else if (t.equals(AggregatedRequest.class)) {
ContInstXC = new DaoJSONConvertor<AggregatedRequest>(AggregatedRequest.class);
} else if (t.equals(RequestPrimitive.class)) {
ContInstXC = new DaoJSONConvertor<RequestPrimitive>(RequestPrimitive.class);
} else if (t.equals(ResponsePrimitive.class)) {
ContInstXC = new DaoJSONConvertor<ResponsePrimitive>(ResponsePrimitive.class);
} else if (t.equals(AE.class)) {
ContInstXC = new DaoJSONConvertor<AE>(AE.class);
} else if (t.equals(AEAnnc.class)) {
ContInstXC = new DaoJSONConvertor<AEAnnc>(AEAnnc.class);
} else if (t.equals(Container.class)) {
ContInstXC = new DaoJSONConvertor<Container>(Container.class);
} else if (t.equals(ContainerAnnc.class)) {
ContInstXC = new DaoJSONConvertor<ContainerAnnc>(ContainerAnnc.class);
} else if (t.equals(ContentInstance.class)) {
ContInstXC = new DaoJSONConvertor<ContentInstance>(ContentInstance.class);
} else if (t.equals(ContentInstanceAnnc.class)) {
ContInstXC = new DaoJSONConvertor<ContentInstanceAnnc>(ContentInstanceAnnc.class);
} else if (t.equals(AccessControlPolicy.class)) {
ContInstXC = new DaoJSONConvertor<AccessControlPolicy>(AccessControlPolicy.class);
} else if (t.equals(AccessControlPolicyAnnc.class)) {
ContInstXC = new DaoJSONConvertor<AccessControlPolicyAnnc>(AccessControlPolicyAnnc.class);
} else if (t.equals(CSEBase.class)) {
ContInstXC = new DaoJSONConvertor<CSEBase>(CSEBase.class);
} else if (t.equals(Subscription.class)) {
ContInstXC = new DaoJSONConvertor<Subscription>(Subscription.class);
} else if (t.equals(Group.class)) {
ContInstXC = new DaoJSONConvertor<Group>(Group.class);
} else if (t.equals(GroupAnnc.class)) {
ContInstXC = new DaoJSONConvertor<GroupAnnc>(GroupAnnc.class);
} else if (t.equals(PollingChannel.class)) {
ContInstXC = new DaoJSONConvertor<PollingChannel>(PollingChannel.class);
} else if (t.equals(Request.class)) {
ContInstXC = new DaoJSONConvertor<Request>(Request.class);
} else if (t.equals(RemoteCSE.class)) {
ContInstXC = new DaoJSONConvertor<RemoteCSE>(RemoteCSE.class);
} else if (t.equals(RemoteCSEAnnc.class)) {
ContInstXC = new DaoJSONConvertor<RemoteCSEAnnc>(RemoteCSEAnnc.class);
} else if (t.equals(Node.class)) {
ContInstXC = new DaoJSONConvertor<Node>(Node.class);
} else if (t.equals(NodeAnnc.class)) {
ContInstXC = new DaoJSONConvertor<NodeAnnc>(NodeAnnc.class);
} else if (t.equals(Schedule.class)) {
ContInstXC = new DaoJSONConvertor<Schedule>(Schedule.class);
} else if (t.equals(ScheduleAnnc.class)) {
ContInstXC = new DaoJSONConvertor<ScheduleAnnc>(ScheduleAnnc.class);
} else if (t.equals(RestCommand.class)) {
ContInstXC = new DaoJSONConvertor<RestCommand>(RestCommand.class);
} else if (t.equals(RestAuth.class)) {
ContInstXC = new DaoJSONConvertor<RestAuth>(RestAuth.class);
} else if (t.equals(RestCommandResult.class)) {
ContInstXC = new DaoJSONConvertor<RestCommandResult>(RestCommandResult.class);
} else if (t.equals(RestCommandCI.class)) {
ContInstXC = new DaoJSONConvertor<RestCommandCI>(RestCommandCI.class);
} else if (t.equals(RestSemanticCI.class)) {
ContInstXC = new DaoJSONConvertor<RestSemanticCI>(RestSemanticCI.class);
} else if (t.equals(RestSubscription.class)) {
ContInstXC = new DaoJSONConvertor<RestSubscription>(RestSubscription.class);
} else if (t.equals(MgmtResource.class)) {
ContInstXC = new DaoJSONConvertor<MgmtResource>(MgmtResource.class);
} else if (t.equals(Firmware.class)) {
ContInstXC = new DaoJSONConvertor<Firmware>(Firmware.class);
} else if (t.equals(Software.class)) {
ContInstXC = new DaoJSONConvertor<Software>(Software.class);
} else if (t.equals(Memory.class)) {
ContInstXC = new DaoJSONConvertor<Memory>(Memory.class);
} else if (t.equals(AreaNwkInfo.class)) {
ContInstXC = new DaoJSONConvertor<AreaNwkInfo>(AreaNwkInfo.class);
} else if (t.equals(AreaNwkDeviceInfo.class)) {
ContInstXC = new DaoJSONConvertor<AreaNwkDeviceInfo>(AreaNwkDeviceInfo.class);
} else if (t.equals(Battery.class)) {
ContInstXC = new DaoJSONConvertor<Battery>(Battery.class);
} else if (t.equals(DeviceInfo.class)) {
ContInstXC = new DaoJSONConvertor<DeviceInfo>(DeviceInfo.class);
} else if (t.equals(DeviceCapability.class)) {
ContInstXC = new DaoJSONConvertor<DeviceCapability>(DeviceCapability.class);
} else if (t.equals(Reboot.class)) {
ContInstXC = new DaoJSONConvertor<Reboot>(Reboot.class);
} else if (t.equals(EventLog.class)) {
ContInstXC = new DaoJSONConvertor<EventLog>(EventLog.class);
} else if (t.equals(MgmtCmd.class)) {
ContInstXC = new DaoJSONConvertor<MgmtCmd>(MgmtCmd.class);
} else if (t.equals(ExecInstance.class)) {
ContInstXC = new DaoJSONConvertor<ExecInstance>(ExecInstance.class);
} else if (t.equals(SemanticDescriptor.class)) {
ContInstXC = new DaoJSONConvertor<SemanticDescriptor>(SemanticDescriptor.class);
} else if (t.equals(FlexContainerResource.class)) {
ContInstXC = new DaoJSONConvertor<FlexContainerResource>(FlexContainerResource.class);
} else if (t.equals(AllJoynApp.class)) {
ContInstXC = new DaoJSONConvertor<AllJoynApp>(AllJoynApp.class);
} else if (t.equals(AllJoynProperty.class)) {
ContInstXC = new DaoJSONConvertor<AllJoynProperty>(AllJoynProperty.class);
} else if (t.equals(AllJoynSvcObject.class)) {
ContInstXC = new DaoJSONConvertor<AllJoynSvcObject>(AllJoynSvcObject.class);
} else if (t.equals(AllJoynInterface.class)) {
ContInstXC = new DaoJSONConvertor<AllJoynInterface>(AllJoynInterface.class);
} else if (t.equals(AllJoynMethod.class)) {
ContInstXC = new DaoJSONConvertor<AllJoynMethod>(AllJoynMethod.class);
} else if (t.equals(AllJoynMethodCall.class)) {
ContInstXC = new DaoJSONConvertor<AllJoynMethodCall>(AllJoynMethodCall.class);
} else if (t.equals(SvcObjWrapper.class)) {
ContInstXC = new DaoJSONConvertor<SvcObjWrapper>(SvcObjWrapper.class);
} else if (t.equals(SvcFwWrapper.class)) {
ContInstXC = new DaoJSONConvertor<SvcFwWrapper>(SvcFwWrapper.class);
} else if (t.equals(GenericInterworkingService.class)) {
ContInstXC = new DaoJSONConvertor<GenericInterworkingService>(GenericInterworkingService.class);
} else if (t.equals(GenericInterworkingOperationInstance.class)) {
ContInstXC = new DaoJSONConvertor<GenericInterworkingOperationInstance>(GenericInterworkingOperationInstance.class);
} else {
throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR, "Fail to create JSON Convertor for "+ t.getCanonicalName());
}
return ContInstXC;
}
static JSONConvertor<?> createJSONConvertor(Class<?> t, String schema) throws OneM2MException {
JSONConvertor<?> ContInstXC;
if (t.equals(UriContent.class)) {
ContInstXC = new JSONConvertor<UriContent>(UriContent.class);
} else if (t.equals(UriListContent.class)) {
ContInstXC = new JSONConvertor<UriListContent>(UriListContent.class);
} else if (t.equals(Notification.class)) {
//ContInstXC = new JSONConvertor<Notification>(Notification.class);
ContInstXC = new JSONConvertor<Notification>(Notification.class,
new Class[] {Notification.class,UriListContent.class,AccessControlPolicy.class,AE.class,
Container.class,ContentInstance.class,CSEBase.class,Delivery.class,
EventConfig.class,ExecInstance.class,Group.class,LocationPolicy.class,
MgmtCmd.class,Node.class,PollingChannel.class,RemoteCSE.class,Request.class,
Schedule.class,ServiceSubscribedAppRule.class,ServiceSubscribedNode.class,
StatsCollect.class,StatsConfig.class,Subscription.class,AccessControlPolicyAnnc.class,
AEAnnc.class,ContainerAnnc.class,ContentInstanceAnnc.class,GroupAnnc.class,
LocationPolicyAnnc.class,NodeAnnc.class,RemoteCSEAnnc.class,ScheduleAnnc.class, String.class});
} else if (t.equals(AggregatedResponse.class)) {
ContInstXC = new JSONConvertor<AggregatedResponse>(AggregatedResponse.class);
} else if (t.equals(AggregatedRequest.class)) {
ContInstXC = new JSONConvertor<AggregatedRequest>(AggregatedRequest.class);
} else if (t.equals(RequestPrimitive.class)) {
ContInstXC = new JSONConvertor<RequestPrimitive>(RequestPrimitive.class);
} else if (t.equals(ResponsePrimitive.class)) {
ContInstXC = new JSONConvertor<ResponsePrimitive>(ResponsePrimitive.class);
} else if (t.equals(AE.class)) {
ContInstXC = new JSONConvertor<AE>(AE.class);
} else if (t.equals(AEAnnc.class)) {
ContInstXC = new JSONConvertor<AEAnnc>(AEAnnc.class);
} else if (t.equals(Container.class)) {
ContInstXC = new JSONConvertor<Container>(Container.class);
} else if (t.equals(ContainerAnnc.class)) {
ContInstXC = new JSONConvertor<ContainerAnnc>(ContainerAnnc.class);
} else if (t.equals(ContentInstance.class)) {
ContInstXC = new JSONConvertor<ContentInstance>(ContentInstance.class);
} else if (t.equals(ContentInstanceAnnc.class)) {
ContInstXC = new JSONConvertor<ContentInstanceAnnc>(ContentInstanceAnnc.class);
} else if (t.equals(AccessControlPolicy.class)) {
ContInstXC = new JSONConvertor<AccessControlPolicy>(AccessControlPolicy.class);
} else if (t.equals(AccessControlPolicyAnnc.class)) {
ContInstXC = new JSONConvertor<AccessControlPolicyAnnc>(AccessControlPolicyAnnc.class);
} else if (t.equals(CSEBase.class)) {
ContInstXC = new JSONConvertor<CSEBase>(CSEBase.class);
} else if (t.equals(Subscription.class)) {
ContInstXC = new JSONConvertor<Subscription>(Subscription.class);
} else if (t.equals(Group.class)) {
ContInstXC = new JSONConvertor<Group>(Group.class);
} else if (t.equals(GroupAnnc.class)) {
ContInstXC = new JSONConvertor<GroupAnnc>(GroupAnnc.class);
} else if (t.equals(PollingChannel.class)) {
ContInstXC = new JSONConvertor<PollingChannel>(PollingChannel.class);
} else if (t.equals(Request.class)) {
ContInstXC = new JSONConvertor<Request>(Request.class);
} else if (t.equals(RemoteCSE.class)) {
ContInstXC = new JSONConvertor<RemoteCSE>(RemoteCSE.class);
} else if (t.equals(RemoteCSEAnnc.class)) {
ContInstXC = new JSONConvertor<RemoteCSEAnnc>(RemoteCSEAnnc.class);
} else if (t.equals(Node.class)) {
ContInstXC = new JSONConvertor<Node>(Node.class);
} else if (t.equals(NodeAnnc.class)) {
ContInstXC = new JSONConvertor<NodeAnnc>(NodeAnnc.class);
} else if (t.equals(Schedule.class)) {
ContInstXC = new JSONConvertor<Schedule>(Schedule.class);
} else if (t.equals(ScheduleAnnc.class)) {
ContInstXC = new JSONConvertor<ScheduleAnnc>(ScheduleAnnc.class);
} else if (t.equals(RestCommand.class)) {
ContInstXC = new JSONConvertor<RestCommand>(RestCommand.class);
} else if (t.equals(RestAuth.class)) { // added by brianmoon at 2016-09-05
ContInstXC = new JSONConvertor<RestAuth>(RestAuth.class);
} else if (t.equals(RestCommandResult.class)) {
ContInstXC = new JSONConvertor<RestCommandResult>(RestCommandResult.class);
} else if (t.equals(RestCommandCI.class)) {
ContInstXC = new JSONConvertor<RestCommandCI>(RestCommandCI.class);
} else if (t.equals(RestSemanticCI.class)) {
ContInstXC = new JSONConvertor<RestSemanticCI>(RestSemanticCI.class);
} else if (t.equals(RestSubscription.class)) {
ContInstXC = new JSONConvertor<RestSubscription>(RestSubscription.class);
} else if (t.equals(MgmtResource.class)) {
ContInstXC = new JSONConvertor<MgmtResource>(MgmtResource.class);
} else if (t.equals(Firmware.class)) {
ContInstXC = new JSONConvertor<Firmware>(Firmware.class);
} else if (t.equals(Software.class)) {
ContInstXC = new JSONConvertor<Software>(Software.class);
} else if (t.equals(Memory.class)) {
ContInstXC = new JSONConvertor<Memory>(Memory.class);
} else if (t.equals(AreaNwkInfo.class)) {
ContInstXC = new JSONConvertor<AreaNwkInfo>(AreaNwkInfo.class);
} else if (t.equals(AreaNwkDeviceInfo.class)) {
ContInstXC = new JSONConvertor<AreaNwkDeviceInfo>(AreaNwkDeviceInfo.class);
} else if (t.equals(Battery.class)) {
ContInstXC = new JSONConvertor<Battery>(Battery.class);
} else if (t.equals(DeviceInfo.class)) {
ContInstXC = new JSONConvertor<DeviceInfo>(DeviceInfo.class);
} else if (t.equals(DeviceCapability.class)) {
ContInstXC = new JSONConvertor<DeviceCapability>(DeviceCapability.class);
} else if (t.equals(Reboot.class)) {
ContInstXC = new JSONConvertor<Reboot>(Reboot.class);
} else if (t.equals(EventLog.class)) {
ContInstXC = new JSONConvertor<EventLog>(EventLog.class);
} else if (t.equals(MgmtCmd.class)) {
ContInstXC = new JSONConvertor<MgmtCmd>(MgmtCmd.class);
} else if (t.equals(ExecInstance.class)) {
ContInstXC = new JSONConvertor<ExecInstance>(ExecInstance.class);
} else if (t.equals(SemanticDescriptor.class)) {
ContInstXC = new JSONConvertor<SemanticDescriptor>(SemanticDescriptor.class);
} else if (t.equals(FlexContainerResource.class)) {
ContInstXC = new JSONConvertor<FlexContainerResource>(FlexContainerResource.class);
} else if (t.equals(AllJoynApp.class)) {
ContInstXC = new JSONConvertor<AllJoynApp>(AllJoynApp.class);
} else if (t.equals(AllJoynProperty.class)) {
ContInstXC = new JSONConvertor<AllJoynProperty>(AllJoynProperty.class);
} else if (t.equals(AllJoynSvcObject.class)) {
ContInstXC = new JSONConvertor<AllJoynSvcObject>(AllJoynSvcObject.class);
} else if (t.equals(AllJoynInterface.class)) {
ContInstXC = new JSONConvertor<AllJoynInterface>(AllJoynInterface.class);
} else if (t.equals(AllJoynMethod.class)) {
ContInstXC = new JSONConvertor<AllJoynMethod>(AllJoynMethod.class);
} else if (t.equals(AllJoynMethodCall.class)) {
ContInstXC = new JSONConvertor<AllJoynMethodCall>(AllJoynMethodCall.class);
} else if (t.equals(SvcObjWrapper.class)) {
ContInstXC = new JSONConvertor<SvcObjWrapper>(SvcObjWrapper.class);
} else if (t.equals(SvcFwWrapper.class)) {
ContInstXC = new JSONConvertor<SvcFwWrapper>(SvcFwWrapper.class);
} else if (t.equals(GenericInterworkingService.class)) {
ContInstXC = new JSONConvertor<GenericInterworkingService>(GenericInterworkingService.class);
} else if (t.equals(GenericInterworkingOperationInstance.class)) {
ContInstXC = new JSONConvertor<GenericInterworkingOperationInstance>(GenericInterworkingOperationInstance.class);
} else {
throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR, "Fail to create JSON Convertor for "+ t.getCanonicalName());
}
return ContInstXC;
}
static XMLConvertor<?> createXMLConvertor(Class<?> t, String schema) throws OneM2MException {
XMLConvertor<?> ContInstXC;
if (t.equals(UriContent.class)) {
ContInstXC = new XMLConvertor<UriContent>(UriContent.class, schema);
} else if (t.equals(UriListContent.class)) {
ContInstXC = new XMLConvertor<UriListContent>(UriListContent.class, schema);
} else if (t.equals(Notification.class)) {
//ContInstXC = new XMLConvertor<Notification>(Notification.class, schema);
ContInstXC = new XMLConvertor<Notification>(Notification.class, schema,
new Class[] {Notification.class,UriListContent.class,AccessControlPolicy.class,AE.class,
Container.class,ContentInstance.class,CSEBase.class,Delivery.class,
EventConfig.class,ExecInstance.class,Group.class,LocationPolicy.class,
MgmtCmd.class,Node.class,PollingChannel.class,RemoteCSE.class,Request.class,
Schedule.class,ServiceSubscribedAppRule.class,ServiceSubscribedNode.class,
StatsCollect.class,StatsConfig.class,Subscription.class,AccessControlPolicyAnnc.class,
AEAnnc.class,ContainerAnnc.class,ContentInstanceAnnc.class,GroupAnnc.class,
LocationPolicyAnnc.class,NodeAnnc.class,RemoteCSEAnnc.class,ScheduleAnnc.class, String.class});
} else if (t.equals(AggregatedResponse.class)) {
ContInstXC = new XMLConvertor<AggregatedResponse>(AggregatedResponse.class, schema);
} else if (t.equals(AggregatedRequest.class)) {
ContInstXC = new XMLConvertor<AggregatedRequest>(AggregatedRequest.class, schema);
} else if (t.equals(ResponsePrimitive.class)) {
ContInstXC = new XMLConvertor<ResponsePrimitive>(ResponsePrimitive.class, schema);
} else if (t.equals(AE.class)) {
ContInstXC = new XMLConvertor<AE>(AE.class, schema);
} else if (t.equals(AEAnnc.class)) {
ContInstXC = new XMLConvertor<AEAnnc>(AEAnnc.class, schema);
} else if (t.equals(Container.class)) {
ContInstXC = new XMLConvertor<Container>(Container.class, schema);
} else if (t.equals(ContainerAnnc.class)) {
ContInstXC = new XMLConvertor<ContainerAnnc>(ContainerAnnc.class, schema);
} else if (t.equals(ContentInstance.class)) {
ContInstXC = new XMLConvertor<ContentInstance>(ContentInstance.class, schema);
} else if (t.equals(ContentInstanceAnnc.class)) {
ContInstXC = new XMLConvertor<ContentInstanceAnnc>(ContentInstanceAnnc.class, schema);
} else if (t.equals(AccessControlPolicy.class)) {
ContInstXC = new XMLConvertor<AccessControlPolicy>(AccessControlPolicy.class, schema);
} else if (t.equals(AccessControlPolicyAnnc.class)) {
ContInstXC = new XMLConvertor<AccessControlPolicyAnnc>(AccessControlPolicyAnnc.class, schema);
} else if (t.equals(CSEBase.class)) {
ContInstXC = new XMLConvertor<CSEBase>(CSEBase.class, schema);
} else if (t.equals(Subscription.class)) {
ContInstXC = new XMLConvertor<Subscription>(Subscription.class, schema);
} else if (t.equals(Group.class)) {
ContInstXC = new XMLConvertor<Group>(Group.class, schema);
} else if (t.equals(GroupAnnc.class)) {
ContInstXC = new XMLConvertor<GroupAnnc>(GroupAnnc.class, schema);
} else if (t.equals(PollingChannel.class)) {
ContInstXC = new XMLConvertor<PollingChannel>(PollingChannel.class, schema);
} else if (t.equals(Request.class)) {
ContInstXC = new XMLConvertor<Request>(Request.class, schema);
} else if (t.equals(RemoteCSE.class)) {
ContInstXC = new XMLConvertor<RemoteCSE>(RemoteCSE.class, schema);
} else if (t.equals(RemoteCSEAnnc.class)) {
ContInstXC = new XMLConvertor<RemoteCSEAnnc>(RemoteCSEAnnc.class, schema);
} else if (t.equals(Node.class)) {
ContInstXC = new XMLConvertor<Node>(Node.class, schema);
} else if (t.equals(NodeAnnc.class)) {
ContInstXC = new XMLConvertor<NodeAnnc>(NodeAnnc.class, schema);
} else if (t.equals(Schedule.class)) {
ContInstXC = new XMLConvertor<Schedule>(Schedule.class, schema);
} else if (t.equals(ScheduleAnnc.class)) {
ContInstXC = new XMLConvertor<ScheduleAnnc>(ScheduleAnnc.class, schema);
} else if (t.equals(RequestPrimitive.class)) {
ContInstXC = new XMLConvertor<RequestPrimitive>(RequestPrimitive.class, schema);
} else if (t.equals(ResponsePrimitive.class)) {
ContInstXC = new XMLConvertor<ResponsePrimitive>(ResponsePrimitive.class, schema);
} else if (t.equals(MgmtResource.class)) {
ContInstXC = new XMLConvertor<MgmtResource>(MgmtResource.class, schema);
} else if (t.equals(Firmware.class)) {
ContInstXC = new XMLConvertor<Firmware>(Firmware.class, schema);
} else if (t.equals(Software.class)) {
ContInstXC = new XMLConvertor<Software>(Software.class, schema);
} else if (t.equals(Memory.class)) {
ContInstXC = new XMLConvertor<Memory>(Memory.class, schema);
} else if (t.equals(AreaNwkInfo.class)) {
ContInstXC = new XMLConvertor<AreaNwkInfo>(AreaNwkInfo.class, schema);
} else if (t.equals(AreaNwkDeviceInfo.class)) {
ContInstXC = new XMLConvertor<AreaNwkDeviceInfo>(AreaNwkDeviceInfo.class, schema);
} else if (t.equals(Battery.class)) {
ContInstXC = new XMLConvertor<Battery>(Battery.class, schema);
} else if (t.equals(DeviceInfo.class)) {
ContInstXC = new XMLConvertor<DeviceInfo>(DeviceInfo.class, schema);
} else if (t.equals(DeviceCapability.class)) {
ContInstXC = new XMLConvertor<DeviceCapability>(DeviceCapability.class, schema);
} else if (t.equals(Reboot.class)) {
ContInstXC = new XMLConvertor<Reboot>(Reboot.class, schema);
} else if (t.equals(EventLog.class)) {
ContInstXC = new XMLConvertor<EventLog>(EventLog.class, schema);
} else if (t.equals(MgmtCmd.class)) {
ContInstXC = new XMLConvertor<MgmtCmd>(MgmtCmd.class, schema);
} else if (t.equals(ExecInstance.class)) {
ContInstXC = new XMLConvertor<ExecInstance>(ExecInstance.class, schema);
} else if (t.equals(SemanticDescriptor.class)) {
ContInstXC = new XMLConvertor<SemanticDescriptor>(SemanticDescriptor.class, schema);
} else if (t.equals(FlexContainerResource.class)) {
ContInstXC = new XMLConvertor<FlexContainerResource>(FlexContainerResource.class, schema);
} else if (t.equals(AllJoynApp.class)) {
ContInstXC = new XMLConvertor<AllJoynApp>(AllJoynApp.class, schema);
} else if (t.equals(AllJoynProperty.class)) {
ContInstXC = new XMLConvertor<AllJoynProperty>(AllJoynProperty.class, schema);
} else if (t.equals(AllJoynSvcObject.class)) {
ContInstXC = new XMLConvertor<AllJoynSvcObject>(AllJoynSvcObject.class, schema);
} else if (t.equals(AllJoynInterface.class)) {
ContInstXC = new XMLConvertor<AllJoynInterface>(AllJoynInterface.class, schema);
} else if (t.equals(AllJoynMethod.class)) {
ContInstXC = new XMLConvertor<AllJoynMethod>(AllJoynMethod.class, schema);
} else if (t.equals(AllJoynMethodCall.class)) {
ContInstXC = new XMLConvertor<AllJoynMethodCall>(AllJoynMethodCall.class, schema);
} else if (t.equals(SvcObjWrapper.class)) {
ContInstXC = new XMLConvertor<SvcObjWrapper>(SvcObjWrapper.class, schema);
} else if (t.equals(SvcFwWrapper.class)) {
ContInstXC = new XMLConvertor<SvcFwWrapper>(SvcFwWrapper.class, schema);
} else {
throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR, "Fail to create XML Convertor for "+ t.getCanonicalName());
}
return ContInstXC;
}
}
|
3e16b68ae701b6340a6edde91aae868c9df2d12a | 344 | java | Java | src/model/category/CategoryType.java | CarlVanderwegen/selftest-ooo-herex | 3f013b9a18648472f76745ddaf882beab6a115d0 | [
"Unlicense"
] | null | null | null | src/model/category/CategoryType.java | CarlVanderwegen/selftest-ooo-herex | 3f013b9a18648472f76745ddaf882beab6a115d0 | [
"Unlicense"
] | null | null | null | src/model/category/CategoryType.java | CarlVanderwegen/selftest-ooo-herex | 3f013b9a18648472f76745ddaf882beab6a115d0 | [
"Unlicense"
] | null | null | null | 20.235294 | 44 | 0.747093 | 9,686 | package model.category;
import model.vraag.VraagType;
import model.vraag.VragenLijst;
import java.util.ArrayList;
public interface CategoryType {
String getNaam();
String getDescription();
VragenLijst getVragen();
void setNaam(String naam);
void setDescription(String description);
void addVraag(VraagType vraag);
}
|
3e16b6b1c66cea7a5778ef7810f3971cfc21b734 | 637 | java | Java | JiHoonLim/java/21th/src/DiscorruptBank.java | KHWeb19/Homework | 4ebbcb1f3e680df2b760f8505ab932773d804417 | [
"MIT"
] | 37 | 2021-12-20T11:24:09.000Z | 2022-03-23T11:49:50.000Z | JiHoonLim/java/21th/src/DiscorruptBank.java | KHWeb19/Homework | 4ebbcb1f3e680df2b760f8505ab932773d804417 | [
"MIT"
] | 39 | 2021-12-22T17:35:55.000Z | 2022-03-15T13:17:01.000Z | JiHoonLim/java/21th/src/DiscorruptBank.java | KHWeb19/Homework | 4ebbcb1f3e680df2b760f8505ab932773d804417 | [
"MIT"
] | 33 | 2021-12-20T11:24:33.000Z | 2022-01-25T02:00:49.000Z | 21.233333 | 51 | 0.577708 | 9,687 | import java.math.BigInteger;
public class DiscorruptBank {
public static BigInteger money;
public DiscorruptBank() {
money = new BigInteger("100000000000");
}
public void depositMoney(BigInteger deposit){
money = money.add(deposit);
try{
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void withdrawMoney(BigInteger withdraw){
money = money.subtract(withdraw);
try{
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
3e16b738816b9e48c8e0df9e5ee3696fc687c49c | 2,932 | java | Java | engine/src/main/java/com/stratio/decision/functions/dal/IndexStreamFunction.java | compae/Decision | e80cc8a85e627a8a854da64b0a37620473a55d8e | [
"Apache-2.0"
] | 197 | 2015-10-06T05:10:41.000Z | 2022-03-23T12:26:13.000Z | engine/src/main/java/com/stratio/decision/functions/dal/IndexStreamFunction.java | maduhu/Decision | 675eb4f005031bfcaa6cf43200f37aa5ba288139 | [
"Apache-2.0"
] | 35 | 2015-12-31T10:02:28.000Z | 2020-02-11T18:30:06.000Z | engine/src/main/java/com/stratio/decision/functions/dal/IndexStreamFunction.java | maduhu/Decision | 675eb4f005031bfcaa6cf43200f37aa5ba288139 | [
"Apache-2.0"
] | 83 | 2015-10-26T14:32:42.000Z | 2022-01-09T12:46:34.000Z | 38.578947 | 111 | 0.772169 | 9,688 | /**
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.decision.functions.dal;
import com.stratio.decision.commons.constants.ReplyCode;
import com.stratio.decision.commons.constants.STREAM_OPERATIONS;
import com.stratio.decision.commons.constants.StreamAction;
import com.stratio.decision.commons.messages.StratioStreamingMessage;
import com.stratio.decision.functions.ActionBaseFunction;
import com.stratio.decision.functions.validator.ActionEnabledValidation;
import com.stratio.decision.functions.validator.RequestValidation;
import com.stratio.decision.functions.validator.StreamNameNotEmptyValidation;
import com.stratio.decision.functions.validator.StreamNotExistsValidation;
import com.stratio.decision.service.StreamOperationService;
import java.util.Set;
public class IndexStreamFunction extends ActionBaseFunction {
private static final long serialVersionUID = -689381870050478255L;
public IndexStreamFunction(StreamOperationService streamOperationService, String zookeeperHost) {
super(streamOperationService, zookeeperHost);
}
@Override
protected String getStartOperationCommand() {
return STREAM_OPERATIONS.ACTION.INDEX;
}
@Override
protected String getStopOperationCommand() {
return STREAM_OPERATIONS.ACTION.STOP_INDEX;
}
@Override
protected boolean startAction(StratioStreamingMessage message) {
getStreamOperationService().enableAction(message.getStreamName(), StreamAction.SAVE_TO_ELASTICSEARCH);
return true;
}
@Override
protected boolean stopAction(StratioStreamingMessage message) {
getStreamOperationService().disableAction(message.getStreamName(), StreamAction.SAVE_TO_ELASTICSEARCH);
return true;
}
@Override
protected void addStopRequestsValidations(Set<RequestValidation> validators) {
validators.add(new StreamNameNotEmptyValidation());
validators.add(new StreamNotExistsValidation());
}
@Override
protected void addStartRequestsValidations(Set<RequestValidation> validators) {
validators.add(new StreamNameNotEmptyValidation());
validators.add(new ActionEnabledValidation(StreamAction.SAVE_TO_ELASTICSEARCH,
ReplyCode.KO_ACTION_ALREADY_ENABLED.getCode()));
validators.add(new StreamNotExistsValidation());
}
}
|
3e16b82307068ae0c209b078809796078776bba7 | 6,424 | java | Java | src/main/java/liquibase/ext/metastore/hive/database/HiveDatabase.java | maketubo/liquibase-hive | 639a2f921e0c0c5305bcfd0fb96173fa4b2af291 | [
"Apache-2.0"
] | 1 | 2020-09-19T10:53:25.000Z | 2020-09-19T10:53:25.000Z | src/main/java/liquibase/ext/metastore/hive/database/HiveDatabase.java | maketubo/liquibase-hive | 639a2f921e0c0c5305bcfd0fb96173fa4b2af291 | [
"Apache-2.0"
] | null | null | null | src/main/java/liquibase/ext/metastore/hive/database/HiveDatabase.java | maketubo/liquibase-hive | 639a2f921e0c0c5305bcfd0fb96173fa4b2af291 | [
"Apache-2.0"
] | 1 | 2021-11-15T10:01:06.000Z | 2021-11-15T10:01:06.000Z | 31.64532 | 133 | 0.627491 | 9,689 | package liquibase.ext.metastore.hive.database;
import liquibase.database.AbstractJdbcDatabase;
import liquibase.database.DatabaseConnection;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.ext.metastore.database.HiveDatabaseConnectionWrapper;
import liquibase.logging.LogService;
import liquibase.logging.Logger;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.Arrays;
import java.util.List;
public class HiveDatabase extends AbstractJdbcDatabase {
public static final List<String> RESERVED = Arrays.asList("ALL", "ALTER", "AND", "ARRAY", "AS", "AUTHORIZATION", "BETWEEN",
"BIGINT", "BINARY", "BOOLEAN", "BOTH", "BY", "CASE", "CAST", "CHAR",
"COLUMN", "CONF", "CREATE", "CROSS", "CUBE", "CURRENT", "CURRENT_DATE",
"CURRENT_TIMESTAMP", "CURSOR", "DATABASE", "DATE", "DECIMAL", "DELETE",
"DESCRIBE", "DISTINCT", "DOUBLE", "DROP", "ELSE", "END", "EXCHANGE", "EXISTS",
"EXTENDED", "EXTERNAL", "FALSE", "FETCH", "FLOAT", "FOLLOWING", "FOR", "FROM",
"FULL", "FUNCTION", "GRANT", "GROUP", "GROUPING", "HAVING", "IF", "IMPORT", "IN",
"INNER", "INSERT", "INT", "INTERSECT", "INTERVAL", "INTO", "IS", "JOIN", "LATERAL",
"LEFT", "LESS", "LIKE", "LOCAL", "MACRO", "MAP", "MORE", "NONE", "NOT", "NULL", "OF",
"ON", "OR", "ORDER", "OUT", "OUTER", "OVER", "PARTIALSCAN", "PARTITION", "PERCENT",
"PRECEDING", "PRESERVE", "PROCEDURE", "RANGE", "READS", "REDUCE", "REVOKE", "RIGHT",
"ROLLUP", "ROW", "ROWS", "SELECT", "SET", "SMALLINT", "TABLE", "TABLESAMPLE", "THEN",
"TIMESTAMP", "TO", "TRANSFORM", "TRIGGER", "TRUE", "TRUNCATE", "UNBOUNDED", "UNION",
"UNIQUEJOIN", "UPDATE", "USER", "USING", "UTC_TMESTAMP", "VALUES", "VARCHAR", "WHEN",
"WHERE", "WINDOW", "WITH", "COMMIT", "ONLY", "REGEXP", "RLIKE", "ROLLBACK", "START",
"CACHE", "CONSTRAINT", "FOREIGN", "PRIMARY", "REFERENCES", "DAYOFWEEK", "EXTRACT",
"FLOOR", "INTEGER", "PRECISION", "VIEWS");
private static final Logger LOG = LogService.getLog(HiveDatabase.class);
private final String databaseProductName;
private final String prefix;
private final String databaseDriver;
public HiveDatabase() {
this.databaseProductName = "Apache Hive";
this.prefix = "jdbc:hive2";
this.databaseDriver = "org.apache.hive.jdbc.HiveDriver";
}
@Override
public Integer getDefaultPort() {
return 10000;
}
public void setReservedWords() {
addReservedWords(RESERVED);
}
@Override
public String getCurrentDateTimeFunction() {
return "CURRENT_TIMESTAMP()";
}
@Override
protected String getConnectionSchemaName() {
String[] tokens = super.getConnection().getURL().split("/");
String dbName = tokens[tokens.length - 1].split(";")[0];
String schema = getSchemaDatabaseSpecific("SHOW SCHEMAS LIKE '" + dbName + "'");
return schema == null ? "default" : schema;
}
@Override
protected String getQuotingStartCharacter() {
return "`";
}
@Override
protected String getQuotingEndCharacter() {
return "`";
}
@Override
public boolean isCorrectDatabaseImplementation(DatabaseConnection databaseConnection) throws DatabaseException {
return databaseProductName.equalsIgnoreCase(databaseConnection.getDatabaseProductName());
}
@Override
public String getDefaultDriver(String url) {
if (url.startsWith(prefix)) {
return databaseDriver;
}
return null;
}
@Override
protected String getDefaultDatabaseProductName() {
return databaseProductName;
}
@Override
public String getShortName() {
return databaseProductName.toLowerCase();
}
@Override
public int getPriority() {
return PRIORITY_DATABASE;
}
@Override
public boolean requiresPassword() {
return false;
}
@Override
public boolean requiresUsername() {
return true;
}
@Override
public boolean isAutoCommit() throws DatabaseException {
return true;
}
@Override
public boolean supportsInitiallyDeferrableColumns() {
return false;
}
@Override
public boolean supportsTablespaces() {
return false;
}
@Override
public boolean supportsSequences() {
return false;
}
@Override
public boolean supportsSchemas() {
return true;
}
@Override
public boolean supportsAutoIncrement() {
return false;
}
@Override
public boolean supportsRestrictForeignKeys() {
return false;
}
@Override
public boolean supportsDropTableCascadeConstraints() {
return false;
}
@Override
public boolean supportsDDLInTransaction() {
return false;
}
@Override
public boolean supportsPrimaryKeyNames() {
return false;
}
@Override
public void setConnection(DatabaseConnection conn) {
setReservedWords();
super.setConnection(new HiveDatabaseConnectionWrapper((JdbcConnection) conn));
}
public Connection connect() throws SQLException, IllegalAccessException, InstantiationException {
Driver driver;
try {
driver = (Driver) Class.forName(getDefaultDriver(super.getConnection().getURL())).getDeclaredConstructor().newInstance();
} catch (InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
return driver.connect(super.getConnection().getURL(), System.getProperties());
}
private String getSchemaDatabaseSpecific(String query) {
try (Connection con = connect();
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(query)) {
resultSet.next();
String schema = resultSet.getString(1);
LOG.info("Schema name is '" + schema + "'");
return schema;
} catch (Exception e) {
LOG.info("Can't get default schema:", e);
}
return null;
}
@Override
public boolean isCaseSensitive() {
return false;
}
}
|
3e16b88d82c965b15f2294ef11471ad5eb5e450f | 3,146 | java | Java | backend/de.metas.elasticsearch.server/src/main/java/de/metas/elasticsearch/denormalizers/impl/DateDenormalizer.java | boost-entropy-repos-org/metasfresh | 2ae46926e3a2bf060f9274e4215f14a36e1d0b3c | [
"RSA-MD"
] | 1 | 2021-02-17T12:00:41.000Z | 2021-02-17T12:00:41.000Z | backend/de.metas.elasticsearch.server/src/main/java/de/metas/elasticsearch/denormalizers/impl/DateDenormalizer.java | boost-entropy-repos-org/metasfresh | 2ae46926e3a2bf060f9274e4215f14a36e1d0b3c | [
"RSA-MD"
] | null | null | null | backend/de.metas.elasticsearch.server/src/main/java/de/metas/elasticsearch/denormalizers/impl/DateDenormalizer.java | boost-entropy-repos-org/metasfresh | 2ae46926e3a2bf060f9274e4215f14a36e1d0b3c | [
"RSA-MD"
] | null | null | null | 28.089286 | 105 | 0.750159 | 9,690 | package de.metas.elasticsearch.denormalizers.impl;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import de.metas.common.util.time.SystemTime;
import org.adempiere.exceptions.AdempiereException;
import org.compiere.util.DisplayType;
import org.elasticsearch.common.xcontent.XContentBuilder;
import de.metas.elasticsearch.denormalizers.IESDenormalizer;
import de.metas.elasticsearch.types.ESIndexType;
import lombok.NonNull;
import lombok.ToString;
/*
* #%L
* de.metas.business
* %%
* Copyright (C) 2016 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@ToString
final class DateDenormalizer implements IESDenormalizer
{
public static DateDenormalizer of(final int dateDisplayType, final ESIndexType indexType)
{
return new DateDenormalizer(dateDisplayType, indexType);
}
private static final DateTimeFormatter FORMATTER_StrictDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final ESIndexType indexType;
private final int dateDisplayType;
private DateDenormalizer(final int dateDisplayType, @NonNull final ESIndexType indexType)
{
this.dateDisplayType = dateDisplayType;
this.indexType = indexType;
}
@Override
public void appendMapping(final Object builderObj, final String fieldName) throws IOException
{
final XContentBuilder builder = ESDenormalizerHelper.extractXContentBuilder(builderObj);
//@formatter:off
builder.startObject(fieldName)
.field("type", "date")
.field("index", indexType.getEsTypeAsString())
.field("format", "strict_date_optional_time||epoch_millis")
.endObject();
//@formatter:on
}
@Override
public Object denormalize(final Object value)
{
if (value == null)
{
return null;
}
if (dateDisplayType == DisplayType.Date)
{
return FORMATTER_StrictDate.format(toTemporal(value));
}
else if (dateDisplayType == DisplayType.DateTime)
{
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(toTemporal(value));
}
return value;
}
private Temporal toTemporal(final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof java.util.Date)
{
final java.util.Date date = (java.util.Date)value;
return ZonedDateTime.ofInstant(date.toInstant(), SystemTime.zoneId());
}
else if (value instanceof Temporal)
{
return (Temporal)value;
}
else
{
throw new AdempiereException("Unsupported date value '" + value + "' (" + value.getClass() + "))");
}
}
}
|
3e16b8fab8b873f635597a8e7a38ac933cad6a3a | 9,061 | java | Java | src/main/java/mytown/entities/Plot.java | GameModsBR/MyTown2 | 75cbfff7e59ffe9a65c1aa53c5e95ffd7d1b1314 | [
"Unlicense"
] | null | null | null | src/main/java/mytown/entities/Plot.java | GameModsBR/MyTown2 | 75cbfff7e59ffe9a65c1aa53c5e95ffd7d1b1314 | [
"Unlicense"
] | 2 | 2016-06-07T13:43:20.000Z | 2016-06-07T15:08:19.000Z | src/main/java/mytown/entities/Plot.java | GameModsBR/MyTown2 | 75cbfff7e59ffe9a65c1aa53c5e95ffd7d1b1314 | [
"Unlicense"
] | null | null | null | 28.139752 | 170 | 0.504249 | 9,691 | package mytown.entities;
import myessentials.entities.Volume;
import myessentials.entities.sign.SignType;
import mypermissions.proxies.PermissionProxy;
import mytown.entities.flag.Flag;
import mytown.entities.flag.FlagType;
import mytown.handlers.VisualsHandler;
import mytown.new_datasource.MyTownUniverse;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Plot {
private int dbID;
private final int dim, x1, y1, z1, x2, y2, z2;
private Town town;
private String key, name;
public final Flag.Container flagsContainer = new Flag.Container();
public final Resident.Container membersContainer = new Resident.Container();
public final Resident.Container ownersContainer = new Resident.Container();
public Plot(String name, Town town, int dim, int x1, int y1, int z1, int x2, int y2, int z2) {
if (x1 > x2) {
int aux = x2;
x2 = x1;
x1 = aux;
}
if (z1 > z2) {
int aux = z2;
z2 = z1;
z1 = aux;
}
if (y1 > y2) {
int aux = y2;
y2 = y1;
y1 = aux;
}
// Second parameter is always highest
this.name = name;
this.town = town;
this.x1 = x1;
this.y1 = y1;
this.z1 = z1;
this.x2 = x2;
this.y2 = y2;
this.z2 = z2;
this.dim = dim;
updateKey();
}
public boolean isCoordWithin(int dim, int x, int y, int z) {
return dim == this.dim && x1 <= x && x <= x2 && y1 <= y && y <= y2 && z1 <= z && z <= z2;
}
public boolean hasPermission(Resident res, FlagType<Boolean> flagType) {
if(flagType.configurable ? flagsContainer.getValue(flagType) : flagType.defaultValue) {
return true;
}
if(res == null) {
return false;
}
if(membersContainer.contains(res) || ownersContainer.contains(res)) {
return true;
}
if (res.getFakePlayer()) {
return false;
}
boolean permissionBypass = PermissionProxy.getPermissionManager().hasPermission(res.getUUID(), flagType.getBypassPermission());
if(!permissionBypass) {
res.protectionDenial(flagType, ownersContainer.toString());
return false;
}
return true;
}
@Override
public String toString() {
return String.format("Plot: {Name: %s, Dim: %s, Start: [%s, %s, %s], End: [%s, %s, %s]}", name, dim, x1, y1, z1, x2, y2, z2);
}
public Volume toVolume() {
return new Volume(x1, y1, z1, x2, y2, z2);
}
public int getDim() {
return dim;
}
public int getStartX() {
return x1;
}
public int getStartY() {
return y1;
}
public int getStartZ() {
return z1;
}
public int getEndX() {
return x2;
}
public int getEndY() {
return y2;
}
public int getEndZ() {
return z2;
}
public int getStartChunkX() {
return x1 >> 4;
}
public int getStartChunkZ() {
return z1 >> 4;
}
public int getEndChunkX() {
return x2 >> 4;
}
public int getEndChunkZ() {
return z2 >> 4;
}
public Town getTown() {
return town;
}
public String getKey() {
return key;
}
/**
* Updates the key of the plot if any changes have been made to it.
*/
private void updateKey() {
key = String.format("%s;%s;%s;%s;%s;%s;%s", dim, x1, y1, z1, x2, y2, z2);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setDbID(int id) {
this.dbID = id;
}
public int getDbID() {
return this.dbID;
}
public void deleteSignBlocks(SignType signType, World world) {
if(world.provider.dimensionId != dim)
return;
int x1 = getStartX();
int y1 = getStartY();
int z1 = getStartZ();
int x2 = getEndX();
int y2 = getEndY();
int z2 = getEndZ();
int cx1 = x1 >> 4;
int cz1 = z1 >> 4;
int cx2 = x2 >> 4;
int cz2 = z2 >> 4;
for(int cx = cx1; cx <= cx2; cx++)
for(int cz = cz1; cz <= cz2; cz++) {
Chunk chunk = world.getChunkFromChunkCoords(cx, cz);
if(!chunk.isChunkLoaded)
chunk = world.getChunkProvider().loadChunk(cx, cz);
List<int[]> sellSigns = new ArrayList<int[]>(2);
for(Object obj: chunk.chunkTileEntityMap.values()) {
if(obj instanceof TileEntitySign) {
TileEntitySign sign = (TileEntitySign) obj;
if( sign.xCoord >= x1 && sign.xCoord <= x2
&& sign.yCoord >= y1 && sign.yCoord <= y2
&& sign.zCoord >= z1 && sign.zCoord <= z2
&& signType.isTileValid(sign) )
sellSigns.add(new int[]{sign.xCoord, sign.yCoord, sign.zCoord});
}
}
for(int[] sellSign: sellSigns) {
world.removeTileEntity(sellSign[0], sellSign[1], sellSign[2]);
world.setBlock(sellSign[0], sellSign[1], sellSign[2], Blocks.air);
}
}
}
public static class Container extends ArrayList<Plot> {
private int maxPlots;
public Container() {
this.maxPlots = -1;
}
public Container(int maxPlots) {
this.maxPlots = maxPlots;
}
public void remove(Plot plot) {
for (int x = plot.getStartChunkX(); x <= plot.getEndChunkX(); x++) {
for (int z = plot.getStartChunkZ(); z <= plot.getEndChunkZ(); z++) {
TownBlock b = MyTownUniverse.instance.blocks.get(plot.getDim(), x, z);
if (b != null) {
for(Iterator<Plot> it = b.plotsContainer.iterator(); it.hasNext(); ) {
Plot plotInBlock = it.next();
if(plot == plotInBlock) {
it.remove();
}
}
}
}
}
super.remove(plot);
}
public Plot get(String name) {
for(Plot plot : this) {
if(plot.getName().equals(name))
return plot;
}
return null;
}
public Plot get(int dim, int x, int y, int z) {
for(Plot plot : this) {
if(plot.isCoordWithin(dim, x, y, z)) {
return plot;
}
}
return null;
}
public Plot get(Resident res) {
return get(res.getPlayer().dimension, (int) Math.floor(res.getPlayer().posX), (int) Math.floor(res.getPlayer().posY), (int) Math.floor(res.getPlayer().posZ));
}
@Override
public Plot get(int plotID) {
for(Plot plot : this) {
if(plot.getDbID() == plotID) {
return plot;
}
}
return null;
}
public List<Plot> getPlotsOwned(Resident res) {
List<Plot> list = new ArrayList<Plot>();
for (Plot plot : this) {
if (plot.ownersContainer.contains(res))
list.add(plot);
}
return list;
}
public int getAmountPlotsOwned(Resident res) {
int plotsOwned = 0;
for (Plot plot : this) {
if (plot.ownersContainer.contains(res))
plotsOwned++;
}
return plotsOwned;
}
public int getMaxPlots() {
return this.maxPlots;
}
public void setMaxPlots(int maxPlots) {
this.maxPlots = maxPlots;
}
public boolean canResidentMakePlot(Resident res) {
return maxPlots == -1 || getAmountPlotsOwned(res) < maxPlots;
}
public void show(Resident res) {
if(res.getPlayer() instanceof EntityPlayerMP) {
for (Plot plot : this) {
VisualsHandler.instance.markPlotBorders(plot, (EntityPlayerMP) res.getPlayer());
}
}
}
public void hide(Resident res) {
if(res.getPlayer() instanceof EntityPlayerMP) {
for (Plot plot : this) {
VisualsHandler.instance.unmarkBlocks((EntityPlayerMP) res.getPlayer(), plot);
}
}
}
}
}
|
3e16b95684faefa21e1b2e80d8fca8d962ea6bdc | 1,678 | java | Java | src/gs/codepad/LRUCache.java | sobhanChitrada/JavaCodingPractice | 05d8f2b71993b483676dd8258a962fadb3110df5 | [
"MIT"
] | null | null | null | src/gs/codepad/LRUCache.java | sobhanChitrada/JavaCodingPractice | 05d8f2b71993b483676dd8258a962fadb3110df5 | [
"MIT"
] | null | null | null | src/gs/codepad/LRUCache.java | sobhanChitrada/JavaCodingPractice | 05d8f2b71993b483676dd8258a962fadb3110df5 | [
"MIT"
] | null | null | null | 27.064516 | 79 | 0.501192 | 9,692 | package gs.codepad;
import java.util.HashMap;
import java.util.LinkedHashMap;
class LRUCache {
LinkedHashMap<Integer,Integer> map;
int c=0,cap=0;
public LRUCache(int capacity) {
map =new LinkedHashMap<>();
cap=capacity;
}
public int get(int key) {
int val=map.getOrDefault(key,-1);
if(val!=-1) {
map.remove(key);
map.put(key,val);
}
return val;
}
public void put(int key, int value) {
if(map.containsKey(key) && c<=cap) {
map.remove(key);
map.put(key,value);
} else if(c<cap) {
c++;
map.put(key,value);
} else {
int temp=0;
for(Integer k:map.keySet()) {
temp=k;
break;
}
map.remove(temp);
map.put(key,value);
}
}
public static void main(String[] args) {
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/ |
3e16b99c0e61aab7557c8c88342602b5076e78b5 | 213 | java | Java | src/main/java/uk/co/thefishlive/auth/assessments/exception/AssessmentCreateException.java | JamesFitzpatrick-Coursework/Web-Library | 0d72dc49ab5453d2020dd56785bfc36cef3983d0 | [
"MIT"
] | null | null | null | src/main/java/uk/co/thefishlive/auth/assessments/exception/AssessmentCreateException.java | JamesFitzpatrick-Coursework/Web-Library | 0d72dc49ab5453d2020dd56785bfc36cef3983d0 | [
"MIT"
] | null | null | null | src/main/java/uk/co/thefishlive/auth/assessments/exception/AssessmentCreateException.java | JamesFitzpatrick-Coursework/Web-Library | 0d72dc49ab5453d2020dd56785bfc36cef3983d0 | [
"MIT"
] | null | null | null | 21.3 | 68 | 0.769953 | 9,693 | package uk.co.thefishlive.auth.assessments.exception;
public class AssessmentCreateException extends AssessmentException {
public AssessmentCreateException(String message) {
super(message);
}
}
|
3e16ba3115b4aa8fc953e6350380e369a0d4eedc | 9,618 | java | Java | core/target/generated-sources/localizer/hudson/node_monitors/Messages.java | KyleDeflerUK/mp3 | f57d4c0797455a308050189e825d70901a092ebe | [
"MIT"
] | null | null | null | core/target/generated-sources/localizer/hudson/node_monitors/Messages.java | KyleDeflerUK/mp3 | f57d4c0797455a308050189e825d70901a092ebe | [
"MIT"
] | 3 | 2021-02-03T19:35:13.000Z | 2021-08-02T17:21:24.000Z | core/target/generated-sources/localizer/hudson/node_monitors/Messages.java | KyleDeflerUK/mp3 | f57d4c0797455a308050189e825d70901a092ebe | [
"MIT"
] | 1 | 2020-04-10T21:44:36.000Z | 2020-04-10T21:44:36.000Z | 31.742574 | 111 | 0.624038 | 9,694 | // CHECKSTYLE:OFF
package hudson.node_monitors;
import org.jvnet.localizer.Localizable;
import org.jvnet.localizer.ResourceBundleHolder;
/**
* Generated localization support class.
*
*/
@SuppressWarnings({
"",
"PMD",
"all"
})
public class Messages {
/**
* The resource bundle reference
*
*/
private final static ResourceBundleHolder holder = ResourceBundleHolder.get(Messages.class);
/**
* Key {@code DiskSpaceMonitor.MarkedOnline}: {@code Putting {0} back
* online as there is enough disk space again}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Putting {0} back online as there is enough disk space again}
*/
public static String DiskSpaceMonitor_MarkedOnline(Object arg0) {
return holder.format("DiskSpaceMonitor.MarkedOnline", arg0);
}
/**
* Key {@code DiskSpaceMonitor.MarkedOnline}: {@code Putting {0} back
* online as there is enough disk space again}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Putting {0} back online as there is enough disk space again}
*/
public static Localizable _DiskSpaceMonitor_MarkedOnline(Object arg0) {
return new Localizable(holder, "DiskSpaceMonitor.MarkedOnline", arg0);
}
/**
* Key {@code ResponseTimeMonitor.TimeOut}: {@code Time out for last {0}
* try}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Time out for last {0} try}
*/
public static String ResponseTimeMonitor_TimeOut(Object arg0) {
return holder.format("ResponseTimeMonitor.TimeOut", arg0);
}
/**
* Key {@code ResponseTimeMonitor.TimeOut}: {@code Time out for last {0}
* try}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Time out for last {0} try}
*/
public static Localizable _ResponseTimeMonitor_TimeOut(Object arg0) {
return new Localizable(holder, "ResponseTimeMonitor.TimeOut", arg0);
}
/**
* Key {@code DiskSpaceMonitor.DisplayName}: {@code Free Disk Space}.
*
* @return
* {@code Free Disk Space}
*/
public static String DiskSpaceMonitor_DisplayName() {
return holder.format("DiskSpaceMonitor.DisplayName");
}
/**
* Key {@code DiskSpaceMonitor.DisplayName}: {@code Free Disk Space}.
*
* @return
* {@code Free Disk Space}
*/
public static Localizable _DiskSpaceMonitor_DisplayName() {
return new Localizable(holder, "DiskSpaceMonitor.DisplayName");
}
/**
* Key {@code SwapSpaceMonitor.DisplayName}: {@code Free Swap Space}.
*
* @return
* {@code Free Swap Space}
*/
public static String SwapSpaceMonitor_DisplayName() {
return holder.format("SwapSpaceMonitor.DisplayName");
}
/**
* Key {@code SwapSpaceMonitor.DisplayName}: {@code Free Swap Space}.
*
* @return
* {@code Free Swap Space}
*/
public static Localizable _SwapSpaceMonitor_DisplayName() {
return new Localizable(holder, "SwapSpaceMonitor.DisplayName");
}
/**
* Key {@code TemporarySpaceMonitor.DisplayName}: {@code Free Temp
* Space}.
*
* @return
* {@code Free Temp Space}
*/
public static String TemporarySpaceMonitor_DisplayName() {
return holder.format("TemporarySpaceMonitor.DisplayName");
}
/**
* Key {@code TemporarySpaceMonitor.DisplayName}: {@code Free Temp
* Space}.
*
* @return
* {@code Free Temp Space}
*/
public static Localizable _TemporarySpaceMonitor_DisplayName() {
return new Localizable(holder, "TemporarySpaceMonitor.DisplayName");
}
/**
* Key {@code ArchitectureMonitor.DisplayName}: {@code Architecture}.
*
* @return
* {@code Architecture}
*/
public static String ArchitectureMonitor_DisplayName() {
return holder.format("ArchitectureMonitor.DisplayName");
}
/**
* Key {@code ArchitectureMonitor.DisplayName}: {@code Architecture}.
*
* @return
* {@code Architecture}
*/
public static Localizable _ArchitectureMonitor_DisplayName() {
return new Localizable(holder, "ArchitectureMonitor.DisplayName");
}
/**
* Key {@code ResponseTimeMonitor.DisplayName}: {@code Response Time}.
*
* @return
* {@code Response Time}
*/
public static String ResponseTimeMonitor_DisplayName() {
return holder.format("ResponseTimeMonitor.DisplayName");
}
/**
* Key {@code ResponseTimeMonitor.DisplayName}: {@code Response Time}.
*
* @return
* {@code Response Time}
*/
public static Localizable _ResponseTimeMonitor_DisplayName() {
return new Localizable(holder, "ResponseTimeMonitor.DisplayName");
}
/**
* Key {@code ResponseTimeMonitor.MarkedOffline}: {@code Making {0}
* offline because it’s not responding}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Making {0} offline because it’s not responding}
*/
public static String ResponseTimeMonitor_MarkedOffline(Object arg0) {
return holder.format("ResponseTimeMonitor.MarkedOffline", arg0);
}
/**
* Key {@code ResponseTimeMonitor.MarkedOffline}: {@code Making {0}
* offline because it’s not responding}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Making {0} offline because it’s not responding}
*/
public static Localizable _ResponseTimeMonitor_MarkedOffline(Object arg0) {
return new Localizable(holder, "ResponseTimeMonitor.MarkedOffline", arg0);
}
/**
* Key {@code DiskSpaceMonitor.MarkedOffline}: {@code Making {0} offline
* temporarily due to the lack of disk space}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Making {0} offline temporarily due to the lack of disk space}
*/
public static String DiskSpaceMonitor_MarkedOffline(Object arg0) {
return holder.format("DiskSpaceMonitor.MarkedOffline", arg0);
}
/**
* Key {@code DiskSpaceMonitor.MarkedOffline}: {@code Making {0} offline
* temporarily due to the lack of disk space}.
*
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Making {0} offline temporarily due to the lack of disk space}
*/
public static Localizable _DiskSpaceMonitor_MarkedOffline(Object arg0) {
return new Localizable(holder, "DiskSpaceMonitor.MarkedOffline", arg0);
}
/**
* Key {@code AbstractNodeMonitorDescriptor.NoDataYet}: {@code Not yet}.
*
* @return
* {@code Not yet}
*/
public static String AbstractNodeMonitorDescriptor_NoDataYet() {
return holder.format("AbstractNodeMonitorDescriptor.NoDataYet");
}
/**
* Key {@code AbstractNodeMonitorDescriptor.NoDataYet}: {@code Not yet}.
*
* @return
* {@code Not yet}
*/
public static Localizable _AbstractNodeMonitorDescriptor_NoDataYet() {
return new Localizable(holder, "AbstractNodeMonitorDescriptor.NoDataYet");
}
/**
* Key {@code DiskSpaceMonitorDescriptor.DiskSpace.FreeSpaceTooLow}:
* {@code Disk space is too low. Only {0}GB left on {1}.}.
*
* @param arg1
* 2nd format parameter, {@code {1}}, as {@link String#valueOf(Object)}.
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Disk space is too low. Only {0}GB left on {1}.}
*/
public static String DiskSpaceMonitorDescriptor_DiskSpace_FreeSpaceTooLow(Object arg0, Object arg1) {
return holder.format("DiskSpaceMonitorDescriptor.DiskSpace.FreeSpaceTooLow", arg0, arg1);
}
/**
* Key {@code DiskSpaceMonitorDescriptor.DiskSpace.FreeSpaceTooLow}:
* {@code Disk space is too low. Only {0}GB left on {1}.}.
*
* @param arg1
* 2nd format parameter, {@code {1}}, as {@link String#valueOf(Object)}.
* @param arg0
* 1st format parameter, {@code {0}}, as {@link String#valueOf(Object)}.
* @return
* {@code Disk space is too low. Only {0}GB left on {1}.}
*/
public static Localizable _DiskSpaceMonitorDescriptor_DiskSpace_FreeSpaceTooLow(Object arg0, Object arg1) {
return new Localizable(holder, "DiskSpaceMonitorDescriptor.DiskSpace.FreeSpaceTooLow", arg0, arg1);
}
/**
* Key {@code ClockMonitor.DisplayName}: {@code Clock Difference}.
*
* @return
* {@code Clock Difference}
*/
public static String ClockMonitor_DisplayName() {
return holder.format("ClockMonitor.DisplayName");
}
/**
* Key {@code ClockMonitor.DisplayName}: {@code Clock Difference}.
*
* @return
* {@code Clock Difference}
*/
public static Localizable _ClockMonitor_DisplayName() {
return new Localizable(holder, "ClockMonitor.DisplayName");
}
}
|
3e16bbec1ade8c7a1b0af10d01ad0a306f662c4c | 1,089 | java | Java | src/main/java/com/ckf/springboot_mysql_redis/entity/Users.java | puucck/springboot_mysql_redis | 06863a6ce5f6b37154bd78dce7714bf384f1e5d5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ckf/springboot_mysql_redis/entity/Users.java | puucck/springboot_mysql_redis | 06863a6ce5f6b37154bd78dce7714bf384f1e5d5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ckf/springboot_mysql_redis/entity/Users.java | puucck/springboot_mysql_redis | 06863a6ce5f6b37154bd78dce7714bf384f1e5d5 | [
"Apache-2.0"
] | null | null | null | 19.105263 | 53 | 0.766758 | 9,695 | package com.ckf.springboot_mysql_redis.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Component;
/**
*
* @author www
* @date 2021/08/27
* @version 1.0
* @effect
*/
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("users")
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
private Integer userId;
private String userName;
private String password;
private String email;
private String registerTime;
private String updateTime;
private Integer age;
private String telephoneNumber;
private String nickname;
private Integer state;
private String auth;
}
|
3e16bced99660543f59901ad05cf93a59638e734 | 1,340 | java | Java | vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/OperationHandler.java | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/OperationHandler.java | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | 1 | 2021-01-21T01:37:37.000Z | 2021-01-21T01:37:37.000Z | vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/OperationHandler.java | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | 33.5 | 147 | 0.744776 | 9,696 | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.restapi;
import com.yahoo.vespaxmlparser.VespaXMLFeedReader;
import java.util.Optional;
/**
* Abstract the backend stuff for the REST API, such as retrieving or updating documents.
*
* @author dybis
*/
public interface OperationHandler {
class VisitResult{
public final Optional<String> token;
public final String documentsAsJsonList;
public VisitResult(Optional<String> token, String documentsAsJsonList) {
this.token = token;
this.documentsAsJsonList = documentsAsJsonList;
}
}
VisitResult visit(RestUri restUri, String documentSelection, Optional<String> cluster, Optional<String> continuation) throws RestApiException;
void put(RestUri restUri, VespaXMLFeedReader.Operation data, Optional<String> route) throws RestApiException;
void update(RestUri restUri, VespaXMLFeedReader.Operation data, Optional<String> route) throws RestApiException;
void delete(RestUri restUri, String condition, Optional<String> route) throws RestApiException;
Optional<String> get(RestUri restUri) throws RestApiException;
/** Called just before this is disposed of */
default void shutdown() {}
}
|
3e16bda8a2525314c217584a16fc9d7e8f2b573f | 454 | java | Java | MetadataStorage/src/main/java/eu/supersede/mdm/storage/bdi/extraction/NewNamespaces2.java | Kashif-Rabbani/ODIN | 122209fa82dcd6951429f1daba11e5036790eb98 | [
"Apache-2.0"
] | 7 | 2017-12-05T11:03:49.000Z | 2021-03-05T20:03:37.000Z | MetadataStorage/src/main/java/eu/supersede/mdm/storage/bdi/extraction/NewNamespaces2.java | Kashif-Rabbani/ODIN | 122209fa82dcd6951429f1daba11e5036790eb98 | [
"Apache-2.0"
] | null | null | null | MetadataStorage/src/main/java/eu/supersede/mdm/storage/bdi/extraction/NewNamespaces2.java | Kashif-Rabbani/ODIN | 122209fa82dcd6951429f1daba11e5036790eb98 | [
"Apache-2.0"
] | 4 | 2019-04-01T07:46:16.000Z | 2022-02-10T01:31:10.000Z | 22.7 | 52 | 0.700441 | 9,697 | package eu.supersede.mdm.storage.bdi.extraction;
public enum NewNamespaces2 {
source("http://www.BDIOntology.com/source#"),
schema("http://www.BDIOntology.com/schema"),
rdf("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
xsdd("http://www.w3.org/2001/XMLSchema#"),
rdfs("http://www.w3.org/2000/01/rdf-schema#");
private String element;
NewNamespaces2(String element) {
this.element = element;
}
public String val() {
return element;
}
}
|
3e16bdc6ede1f761d27aab923c8330f2d864f23b | 683 | java | Java | clbs/src/main/java/com/zw/protocol/msg/t809/body/module/PlatformMsgAckInfo.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | 1 | 2021-09-29T02:13:49.000Z | 2021-09-29T02:13:49.000Z | clbs/src/main/java/com/zw/protocol/msg/t809/body/module/PlatformMsgAckInfo.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | null | null | null | clbs/src/main/java/com/zw/protocol/msg/t809/body/module/PlatformMsgAckInfo.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | null | null | null | 17.075 | 57 | 0.704246 | 9,698 | package com.zw.protocol.msg.t809.body.module;
import lombok.Data;
import java.io.Serializable;
/**
* 平台查岗、下发平台间报文数据接收实体
*
* @author hujun
* @date 2018/6/6 14:50
*/
@Data
public class PlatformMsgAckInfo implements Serializable {
private Integer infoId;
private Integer msgDataType; // 子业务类型
private String answer;
private Integer objectType;
private String objectId;
private String serverIp;// 上级平台ip
private Integer msgGNSSCenterId;// 接入码
private String groupId; // 企业uuid
private String gangId; // 上级平台消息处理表id
private Integer msgSn; // 报文序列号
private Integer msgID; // 业务数据类型
private String platFormId; // 转发平台IP
}
|
3e16bde02e7586dc51eeeb2cd6899c251f2a6d75 | 1,061 | java | Java | java/j2ee.jpa.verification/src/org/netbeans/modules/j2ee/jpa/verification/api/VerificationWarningOverrider.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | java/j2ee.jpa.verification/src/org/netbeans/modules/j2ee/jpa/verification/api/VerificationWarningOverrider.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | java/j2ee.jpa.verification/src/org/netbeans/modules/j2ee/jpa/verification/api/VerificationWarningOverrider.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 34.225806 | 63 | 0.753063 | 9,699 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.jpa.verification.api;
/**
* Allows other modules to turn off a specific warning
*
* @author Dongmei Cao
*/
public interface VerificationWarningOverrider {
public boolean suppressWarning(String warningId);
}
|
3e16bf572ec52ecab650760ce620affd93542593 | 5,250 | java | Java | externals/java/src/com/tecartlab/sparck/misc/HttpServer.java | tecartlab/SPARCK | 6866a1b295190cdd77d5a7da5384a5505cb07116 | [
"MIT"
] | 25 | 2020-02-21T21:24:04.000Z | 2021-11-15T11:20:01.000Z | externals/java/src/com/tecartlab/sparck/misc/HttpServer.java | tecartlab/SPARCK | 6866a1b295190cdd77d5a7da5384a5505cb07116 | [
"MIT"
] | 2 | 2020-02-21T21:26:15.000Z | 2021-01-04T17:37:07.000Z | externals/java/src/com/tecartlab/sparck/misc/HttpServer.java | tecartlab/SPARCK | 6866a1b295190cdd77d5a7da5384a5505cb07116 | [
"MIT"
] | 3 | 2020-11-10T13:04:44.000Z | 2021-10-07T17:50:03.000Z | 32.608696 | 245 | 0.724762 | 9,700 | package com.tecartlab.sparck.misc;
/* MIT License
*
* Copyright (c) 2012-2020 tecartlab.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author maybites
*
*/
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
public class HttpServer {
public HttpServer(){
}
// sends data to server for startup log
public static void sendStartupLog(
String _machineID,
String _license,
String _serial,
int _pref_startupCounter,
int _pref_shutdownCounter,
int _pref_totalRunningTime) throws Exception {
String url = "http://sparck.tecartlab.com/logs/startup/logger.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String serialNumber = (_serial == null)? "UNREGISTERED-COPY----------": _serial;
//String urlParameters = "channel0Title=title&channel0Gain=license&channel0Offset=serial";
String urlParameters = "machineID="+_machineID+
"&license="+_license+
"&serial="+serialNumber+
"&build="+Versioner.BUILD_NUMBER+
"&version="+Versioner.VERSION+
"&release="+Versioner.RELEASE+
"&startupCounter="+_pref_startupCounter+
"&crashCounter="+(_pref_startupCounter - _pref_shutdownCounter)+
"&totalRunningTime="+_pref_totalRunningTime;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
con.getResponseCode();
}
// sends data to server for email confirmation
public static void sendEmailVerification(
String _Name,
String _Email,
String _Code,
String _LicenseType,
String _machineID) throws IOException {
String url = "http://sparck.tecartlab.com/logs/verify/email.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//String urlParameters = "channel0Title=title&channel0Gain=license&channel0Offset=serial";
String urlParameters = "machineID="+_machineID+
"&version="+Versioner.VERSION+
"&name="+_Name+
"&email="+_Email+
"&licensetype="+_LicenseType+
"&code="+_Code;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
con.getResponseCode();
}
public static void sendOrderConfirmation(
String _mail,
String _name,
String _license,
String _price,
String _serial,
String _coupon) throws IOException {
String url = "http://sparck.tecartlab.com/logs/order/confirmation.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String coupontext = (_coupon.length() > 0)?"Promo Code: " +_coupon:"";
Calendar cal = new GregorianCalendar();
String date = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()) + " " + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault() ) + " " + cal.get(Calendar.YEAR);
//String urlParameters = "channel0Title=title&channel0Gain=license&channel0Offset=serial";
String urlParameters =
"&name="+_name+
"&email="+_mail+
"&license="+_license+
"&serial="+_serial+
"&coupon="+coupontext+
"&price="+_price+
"&date="+date;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
con.getResponseCode();
}
}
|
3e16bf700520108818ad0293974db97c30eae64b | 1,411 | java | Java | src/main/java/org/age/akka/core/actors/master/services/topology/RingTopologyProcessorActor.java | franc90/age-akka-starter | d6710159a4a7b08093f65d1556c5debf476c4373 | [
"MIT"
] | 1 | 2015-05-22T21:00:45.000Z | 2015-05-22T21:00:45.000Z | src/main/java/org/age/akka/core/actors/master/services/topology/RingTopologyProcessorActor.java | franc90/age-akka-starter | d6710159a4a7b08093f65d1556c5debf476c4373 | [
"MIT"
] | null | null | null | src/main/java/org/age/akka/core/actors/master/services/topology/RingTopologyProcessorActor.java | franc90/age-akka-starter | d6710159a4a7b08093f65d1556c5debf476c4373 | [
"MIT"
] | null | null | null | 32.068182 | 110 | 0.7236 | 9,701 | package org.age.akka.core.actors.master.services.topology;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.age.akka.core.actors.worker.NodeId;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.UnmodifiableDirectedGraph;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.google.common.collect.Iterables.getLast;
public class RingTopologyProcessorActor extends AbstractTopologyProcessorActor {
private final LoggingAdapter log = Logging.getLogger(context().system(), this);
public RingTopologyProcessorActor() {
super();
}
@Override
protected UnmodifiableDirectedGraph<NodeId, DefaultEdge> createNewTopologyWithNodes(Set<NodeId> nodeIds) {
log.debug("process new topology with nodes {}", nodeIds.size());
DefaultDirectedGraph<NodeId, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);
nodeIds.forEach(graph::addVertex);
List<NodeId> sortedIds = nodeIds.stream()
.sorted()
.collect(Collectors.toList());
sortedIds.stream().reduce(getLast(sortedIds), (nodeIdentity1, nodeIdentity2) -> {
graph.addEdge(nodeIdentity1, nodeIdentity2);
return nodeIdentity2;
});
return new UnmodifiableDirectedGraph<>(graph);
}
}
|
3e16bfcdbbed9eaef4aa778faf13b863d2b26da3 | 434 | java | Java | src/main/java/me/shedaniel/rei/gui/config/RecipeScreenType.java | AlexIIL/RoughlyEnoughItems | e965379aef6270e79e0ddadcd1b4b222fecea2e3 | [
"MIT"
] | null | null | null | src/main/java/me/shedaniel/rei/gui/config/RecipeScreenType.java | AlexIIL/RoughlyEnoughItems | e965379aef6270e79e0ddadcd1b4b222fecea2e3 | [
"MIT"
] | null | null | null | src/main/java/me/shedaniel/rei/gui/config/RecipeScreenType.java | AlexIIL/RoughlyEnoughItems | e965379aef6270e79e0ddadcd1b4b222fecea2e3 | [
"MIT"
] | null | null | null | 19.727273 | 111 | 0.709677 | 9,702 | /*
* Roughly Enough Items by Danielshe.
* Licensed under the MIT License.
*/
package me.shedaniel.rei.gui.config;
import net.minecraft.client.resource.language.I18n;
import java.util.Locale;
public enum RecipeScreenType {
UNSET,
ORIGINAL,
VILLAGER;
@Override
public String toString() {
return I18n.translate("config.roughlyenoughitems.recipeScreenType." + name().toLowerCase(Locale.ROOT));
}
}
|
3e16c1bcf1d9d5d135c2b6c3cfacebebaa455593 | 452 | java | Java | src/java/com/threerings/msoy/money/gwt/BroadcastHistory.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 21 | 2015-04-30T10:28:47.000Z | 2021-06-23T23:00:45.000Z | src/java/com/threerings/msoy/money/gwt/BroadcastHistory.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 36 | 2015-07-29T20:50:57.000Z | 2021-09-18T22:37:25.000Z | src/java/com/threerings/msoy/money/gwt/BroadcastHistory.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 35 | 2015-04-30T10:29:41.000Z | 2022-02-15T21:17:01.000Z | 18.08 | 53 | 0.668142 | 9,703 | //
// $Id$
package com.threerings.msoy.money.gwt;
import java.util.Date;
import com.google.gwt.user.client.rpc.IsSerializable;
public class BroadcastHistory
implements IsSerializable
{
/** Time the message was posted. */
public Date timeSent;
/** Member who posted it. */
public int memberId;
/** Number of bars paid for it. */
public int barsPaid;
/** The content of the message. */
public String message;
}
|
3e16c2d164912f878e1786d0c6c6b3e1643df569 | 425 | java | Java | ops4j-base-net/src/main/java/org/ops4j/net/DefaultPortTester.java | JoshuaEngland/org.ops4j.base | 6972e8d3d7ad70fcae595bf7eff4c7c78a0f625d | [
"Apache-2.0"
] | null | null | null | ops4j-base-net/src/main/java/org/ops4j/net/DefaultPortTester.java | JoshuaEngland/org.ops4j.base | 6972e8d3d7ad70fcae595bf7eff4c7c78a0f625d | [
"Apache-2.0"
] | null | null | null | ops4j-base-net/src/main/java/org/ops4j/net/DefaultPortTester.java | JoshuaEngland/org.ops4j.base | 6972e8d3d7ad70fcae595bf7eff4c7c78a0f625d | [
"Apache-2.0"
] | null | null | null | 18.478261 | 83 | 0.684706 | 9,704 | package org.ops4j.net;
import java.net.ServerSocket;
public final class DefaultPortTester implements PortTester {
@Override
public boolean isFree(int port) {
try
{
ServerSocket sock = new ServerSocket( port );
sock.close();
// is free:
return true;
// We rely on an exception thrown to determine availability or not availability.
} catch( Exception e )
{
// not free.
return false;
}
}
}
|
3e16c2e6447f0745eaa5e79a5be4e7900a1afed3 | 1,648 | java | Java | sdk/src/main/java/com/vk/api/sdk/objects/utils/Stats.java | wtlgo/vk-java-sdk | 2f6caeb9a7dd6526ac0550c7f2dd53a0e1b75fe2 | [
"MIT"
] | 332 | 2016-08-24T11:22:26.000Z | 2022-03-30T16:33:31.000Z | sdk/src/main/java/com/vk/api/sdk/objects/utils/Stats.java | wtlgo/vk-java-sdk | 2f6caeb9a7dd6526ac0550c7f2dd53a0e1b75fe2 | [
"MIT"
] | 199 | 2016-09-07T13:23:14.000Z | 2022-03-24T06:30:19.000Z | sdk/src/main/java/com/vk/api/sdk/objects/utils/Stats.java | wtlgo/vk-java-sdk | 2f6caeb9a7dd6526ac0550c7f2dd53a0e1b75fe2 | [
"MIT"
] | 249 | 2016-08-23T17:12:17.000Z | 2022-03-26T13:35:42.000Z | 23.211268 | 67 | 0.606189 | 9,705 | // Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.objects.utils;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.vk.api.sdk.objects.Validable;
import java.util.Objects;
/**
* Stats object
*/
public class Stats implements Validable {
/**
* Start time
*/
@SerializedName("timestamp")
private Integer timestamp;
/**
* Total views number
*/
@SerializedName("views")
private Integer views;
public Integer getTimestamp() {
return timestamp;
}
public Stats setTimestamp(Integer timestamp) {
this.timestamp = timestamp;
return this;
}
public Integer getViews() {
return views;
}
public Stats setViews(Integer views) {
this.views = views;
return this;
}
@Override
public int hashCode() {
return Objects.hash(views, timestamp);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Stats stats = (Stats) o;
return Objects.equals(views, stats.views) &&
Objects.equals(timestamp, stats.timestamp);
}
@Override
public String toString() {
final Gson gson = new Gson();
return gson.toJson(this);
}
public String toPrettyString() {
final StringBuilder sb = new StringBuilder("Stats{");
sb.append("views=").append(views);
sb.append(", timestamp=").append(timestamp);
sb.append('}');
return sb.toString();
}
}
|
3e16c305082457f95a752f4491b02559b1daa4ba | 347 | java | Java | dataStructures/stack.java | sumitgrg24325/Java-1 | ad354991beb302c308b10a212cb84f84ca61c286 | [
"MIT"
] | 29 | 2020-09-24T03:16:04.000Z | 2022-03-29T03:05:49.000Z | dataStructures/stack.java | sumitgrg24325/Java-1 | ad354991beb302c308b10a212cb84f84ca61c286 | [
"MIT"
] | 2 | 2022-01-02T14:45:47.000Z | 2022-02-26T13:49:52.000Z | dataStructures/stack.java | sumitgrg24325/Java-1 | ad354991beb302c308b10a212cb84f84ca61c286 | [
"MIT"
] | 19 | 2020-09-24T02:58:20.000Z | 2022-03-31T09:27:52.000Z | 10.205882 | 43 | 0.504323 | 9,706 | class Sample{
public int[] itsStack = new int[];
public boolean isEmpty(){
}
public boolean isFull(){
}
public boolean push(){
}
public boolean pop(){
}
public int top(){
}
public void display(){
}
}
class Stack{
public static void main(String[] args){
}
} |
3e16c3333c9d033496423b513672c51cbfe67507 | 2,530 | java | Java | lib/net/egork/geometry/GeometryUtils.java | gaoyike/codeforces | 87e4ae8c65e8dce3292c0a7edaa0011c57e6535c | [
"Unlicense"
] | 1 | 2020-05-05T17:42:39.000Z | 2020-05-05T17:42:39.000Z | lib/net/egork/geometry/GeometryUtils.java | gaoyike/codeforces | 87e4ae8c65e8dce3292c0a7edaa0011c57e6535c | [
"Unlicense"
] | null | null | null | lib/net/egork/geometry/GeometryUtils.java | gaoyike/codeforces | 87e4ae8c65e8dce3292c0a7edaa0011c57e6535c | [
"Unlicense"
] | null | null | null | 28.166667 | 84 | 0.484813 | 9,707 | package net.egork.geometry;
/**
* @author Egor Kulikov (hzdkv@example.com)
*/
public class GeometryUtils {
public static double epsilon = 1e-8;
public static double fastHypot(double... x) {
if (x.length == 0) {
return 0;
} else if (x.length == 1) {
return Math.abs(x[0]);
} else {
double sumSquares = 0;
for (double value : x) {
sumSquares += value * value;
}
return Math.sqrt(sumSquares);
}
}
public static double fastHypot(double x, double y) {
return Math.sqrt(x * x + y * y);
}
public static double fastHypot(double[] x, double[] y) {
if (x.length == 0) {
return 0;
} else if (x.length == 1) {
return Math.abs(x[0] - y[0]);
} else {
double sumSquares = 0;
for (int i = 0; i < x.length; i++) {
double diff = x[i] - y[i];
sumSquares += diff * diff;
}
return Math.sqrt(sumSquares);
}
}
public static double fastHypot(int[] x, int[] y) {
if (x.length == 0) {
return 0;
} else if (x.length == 1) {
return Math.abs(x[0] - y[0]);
} else {
double sumSquares = 0;
for (int i = 0; i < x.length; i++) {
double diff = x[i] - y[i];
sumSquares += diff * diff;
}
return Math.sqrt(sumSquares);
}
}
public static double missileTrajectoryLength(double v, double angle, double g) {
return (v * v * Math.sin(2 * angle)) / g;
}
public static double sphereVolume(double radius) {
return 4 * Math.PI * radius * radius * radius / 3;
}
public static double triangleArea(double first, double second, double third) {
double p = (first + second + third) / 2;
return Math.sqrt(p * (p - first) * (p - second) * (p - third));
}
public static double canonicalAngle(double angle) {
while (angle > Math.PI) {
angle -= 2 * Math.PI;
}
while (angle < -Math.PI) {
angle += 2 * Math.PI;
}
return angle;
}
public static double positiveAngle(double angle) {
while (angle > 2 * Math.PI - GeometryUtils.epsilon) {
angle -= 2 * Math.PI;
}
while (angle < -GeometryUtils.epsilon) {
angle += 2 * Math.PI;
}
return angle;
}
}
|
3e16c47407113f5aa940659041deae5b29053707 | 5,448 | java | Java | server/src/main/java/net/christophe/genin/monitor/domain/server/adapter/nitrite/NitriteVersion.java | cgenin/monitor | 20ced83eafc2999b045b6224a8b818c51922232a | [
"MIT"
] | 5 | 2017-12-13T11:03:27.000Z | 2020-06-29T18:35:07.000Z | server/src/main/java/net/christophe/genin/monitor/domain/server/adapter/nitrite/NitriteVersion.java | cgenin/monitor | 20ced83eafc2999b045b6224a8b818c51922232a | [
"MIT"
] | null | null | null | server/src/main/java/net/christophe/genin/monitor/domain/server/adapter/nitrite/NitriteVersion.java | cgenin/monitor | 20ced83eafc2999b045b6224a8b818c51922232a | [
"MIT"
] | 2 | 2017-11-30T11:52:47.000Z | 2017-12-07T16:49:36.000Z | 31.491329 | 114 | 0.620228 | 9,708 | package net.christophe.genin.monitor.domain.server.adapter.nitrite;
import net.christophe.genin.monitor.domain.server.db.Schemas;
import net.christophe.genin.monitor.domain.server.db.nitrite.NitriteDbs;
import net.christophe.genin.monitor.domain.server.model.Version;
import net.christophe.genin.monitor.domain.server.model.port.VersionPort;
import org.dizitart.no2.Document;
import org.dizitart.no2.NitriteCollection;
import rx.Observable;
import rx.Single;
import java.util.List;
import java.util.Optional;
import static org.dizitart.no2.filters.Filters.and;
import static org.dizitart.no2.filters.Filters.eq;
public class NitriteVersion extends Version {
private final Document document;
private final NitriteVersionPort handler;
private NitriteVersion(NitriteVersionPort handler, String name, String idProject, Document document) {
super(name, idProject);
this.handler = handler;
this.document = document;
}
@Override
public String id() {
return Optional.ofNullable(document.get(Schemas.Version.id.name()))
.map(Object::toString)
.orElseGet(NitriteDbs::newId);
}
public long latestUpdate() {
return Optional.ofNullable(document.get(Schemas.Version.latestUpdate.name(), Long.class))
.orElse(0L);
}
public Version setLatestUpdate(long latestUpdate) {
document.put(Schemas.Version.latestUpdate.name(), latestUpdate);
return this;
}
@Override
public Version setIsSnapshot(boolean snapshot) {
document.put(Schemas.Version.isSnapshot.name(), snapshot);
return this;
}
@Override
public Version setJavadeps(List<String> javadeps) {
document.put(Schemas.Version.javaDeps.name(), javadeps);
return this;
}
@Override
public Version setTables(List<String> tables) {
document.put(Schemas.Version.tables.name(), tables);
return this;
}
@Override
public Version setChangeLog(String changeLog) {
document.put(Schemas.Version.changelog.name(), changeLog);
return this;
}
@Override
public Version setApis(List<String> apis) {
document.put(Schemas.Version.apis.name(), apis);
return this;
}
@Override
public Single<Boolean> save() {
return handler.save(this);
}
@Override
public boolean isSnapshot() {
return document.get(Schemas.Version.isSnapshot.name(), Boolean.class);
}
@Override
public String changelog() {
return document.get(Schemas.Version.changelog.name(), String.class);
}
@SuppressWarnings("unchecked")
@Override
public List<String> tables() {
return (List<String>) document.get(Schemas.Version.tables.name());
}
@SuppressWarnings("unchecked")
@Override
public List<String> apis() {
return (List<String>) document.get(Schemas.Version.apis.name());
}
@SuppressWarnings("unchecked")
@Override
public List<String> javaDeps() {
return (List<String>) document.get(Schemas.Version.javaDeps.name());
}
public static class NitriteVersionPort implements VersionPort {
private final NitriteDbs nitriteDbs;
public NitriteVersionPort(NitriteDbs nitriteDbs) {
this.nitriteDbs = nitriteDbs;
}
private NitriteCollection getCollection() {
return nitriteDbs.getCollection(Schemas.Version.collection());
}
public Single<Version> findByNameAndProjectOrDefault(String version, String idProject) {
return Single.fromCallable(
() -> getCollection().find(and(
eq(Schemas.Version.name.name(), version),
eq(Schemas.Version.idproject.name(), idProject)
)).toList())
.map(list -> {
if (list.isEmpty()) {
return Document.createDocument(Schemas.Version.latestUpdate.name(), 0L)
.put(Schemas.Version.name.name(), version)
.put(Schemas.Version.idproject.name(), idProject);
}
return list.get(0);
})
.map(this::toModel);
}
private Version toModel(Document document) {
String version = document.get(Schemas.Version.name.name()).toString();
String idproject = document.get(Schemas.Version.idproject.name()).toString();
return new NitriteVersion(this, version, idproject, document);
}
private Single<Boolean> save(NitriteVersion version) {
return Single.fromCallable(() -> {
getCollection().update(version.document, true);
return true;
});
}
public Single<Integer> removeAll() {
return NitriteDbs.removeAll(getCollection());
}
public Observable<Version> findByProject(String idProject) {
return Observable.from(getCollection().find(eq(Schemas.Version.idproject.name(), idProject)).toList())
.map(this::toModel);
}
@Override
public Observable<Version> findAll() {
return Observable.from(getCollection().find().toList())
.map(this::toModel);
}
}
}
|
3e16c495bc72de920c533feadab123526a550018 | 4,456 | java | Java | l2j_datapack/dist/game/data/scripts/quests/Q00362_BardsMandolin/Q00362_BardsMandolin.java | RollingSoftware/L2J_HighFive_Hardcore | a3c794c82c32b5afca49416119b4aafa8fb9b6d4 | [
"MIT"
] | null | null | null | l2j_datapack/dist/game/data/scripts/quests/Q00362_BardsMandolin/Q00362_BardsMandolin.java | RollingSoftware/L2J_HighFive_Hardcore | a3c794c82c32b5afca49416119b4aafa8fb9b6d4 | [
"MIT"
] | 38 | 2018-02-06T17:11:29.000Z | 2018-06-05T20:47:59.000Z | l2j_datapack/dist/game/data/scripts/quests/Q00362_BardsMandolin/Q00362_BardsMandolin.java | Vladislav-Zolotaryov/L2J_HighFive_Hardcore | a3c794c82c32b5afca49416119b4aafa8fb9b6d4 | [
"MIT"
] | null | null | null | 22.969072 | 84 | 0.6057 | 9,709 | /*
* Copyright (C) 2004-2016 L2J DataPack
*
* This file is part of L2J DataPack.
*
* L2J DataPack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* L2J DataPack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package quests.Q00362_BardsMandolin;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.quest.Quest;
import com.l2jserver.gameserver.model.quest.QuestState;
import com.l2jserver.gameserver.model.quest.State;
/**
* Bard's Mandolin (362)
* @author Adry_85
*/
public final class Q00362_BardsMandolin extends Quest
{
// NPCs
private static final int WOODROW = 30837;
private static final int NANARIN = 30956;
private static final int SWAN = 30957;
private static final int GALION = 30958;
// Items
private static final int SWANS_FLUTE = 4316;
private static final int SWANS_LETTER = 4317;
private static final int THEME_OF_JOURNEY = 4410;
// Misc
private static final int MIN_LEVEL = 15;
public Q00362_BardsMandolin()
{
super(362, Q00362_BardsMandolin.class.getSimpleName(), "Bard's Mandolin");
addStartNpc(SWAN);
addTalkId(SWAN, GALION, WOODROW, NANARIN);
registerQuestItems(SWANS_FLUTE, SWANS_LETTER);
}
@Override
public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
{
final QuestState st = getQuestState(player, false);
if (st == null)
{
return null;
}
String htmltext = null;
switch (event)
{
case "30957-02.htm":
{
st.startQuest();
st.setMemoState(1);
htmltext = event;
break;
}
case "30957-07.html":
case "30957-08.html":
{
if (st.isMemoState(5))
{
st.giveAdena(10000, true);
st.rewardItems(THEME_OF_JOURNEY, 1);
st.exitQuest(true, true);
htmltext = event;
}
break;
}
}
return htmltext;
}
@Override
public String onTalk(L2Npc npc, L2PcInstance player)
{
final QuestState st = getQuestState(player, true);
String htmltext = getNoQuestMsg(player);
switch (st.getState())
{
case State.CREATED:
{
if (npc.getId() == SWAN)
{
htmltext = (player.getLevel() >= MIN_LEVEL) ? "30957-01.htm" : "30957-03.html";
}
break;
}
case State.STARTED:
{
switch (npc.getId())
{
case SWAN:
{
switch (st.getMemoState())
{
case 1:
case 2:
{
htmltext = "30957-04.html";
break;
}
case 3:
{
st.setCond(4, true);
st.setMemoState(4);
st.giveItems(SWANS_LETTER, 1);
htmltext = "30957-05.html";
break;
}
case 4:
{
htmltext = "30957-05.html";
break;
}
case 5:
{
htmltext = "30957-06.html";
break;
}
}
break;
}
case GALION:
{
if (st.isMemoState(2))
{
st.setMemoState(3);
st.setCond(3, true);
st.giveItems(SWANS_FLUTE, 1);
htmltext = "30958-01.html";
}
else if (st.getMemoState() >= 3)
{
htmltext = "30958-02.html";
}
break;
}
case WOODROW:
{
if (st.isMemoState(1))
{
st.setMemoState(2);
st.setCond(2, true);
htmltext = "30837-01.html";
}
else if (st.isMemoState(2))
{
htmltext = "30837-02.html";
}
else if (st.getMemoState() >= 3)
{
htmltext = "30837-03.html";
}
break;
}
case NANARIN:
{
if (st.isMemoState(4) && st.hasQuestItems(SWANS_FLUTE, SWANS_LETTER))
{
st.setMemoState(5);
st.setCond(5, true);
st.takeItems(SWANS_FLUTE, -1);
st.takeItems(SWANS_LETTER, -1);
htmltext = "30956-01.html";
}
else if (st.getMemoState() >= 5)
{
htmltext = "30956-02.html";
}
break;
}
}
break;
}
}
return htmltext;
}
}
|
3e16c4c4c28009d9485ed5fc0337fb105ed60456 | 4,199 | java | Java | s2_idiomas-api/src/main/java/co/edu/uniandes/csw/idiomas/dtos/EncuentroDTO.java | Uniandes-isis2603/s2_Idiomas_2_201910 | e891da0f874aef44cfaa86ff75b0ed7a68c9417c | [
"MIT"
] | null | null | null | s2_idiomas-api/src/main/java/co/edu/uniandes/csw/idiomas/dtos/EncuentroDTO.java | Uniandes-isis2603/s2_Idiomas_2_201910 | e891da0f874aef44cfaa86ff75b0ed7a68c9417c | [
"MIT"
] | null | null | null | s2_idiomas-api/src/main/java/co/edu/uniandes/csw/idiomas/dtos/EncuentroDTO.java | Uniandes-isis2603/s2_Idiomas_2_201910 | e891da0f874aef44cfaa86ff75b0ed7a68c9417c | [
"MIT"
] | null | null | null | 29.992857 | 82 | 0.539176 | 9,710 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.csw.idiomas.dtos;
import co.edu.uniandes.csw.idiomas.entities.EncuentroEntity;
import java.io.Serializable;
/**
* EncuentroDTO Objeto de transferencia de datos del encuentro. Los DTO
* contienen las representaciones de los JSON que se transfieren entre el
* cliente y el servidor.
* @author g.cubillosb
*/
public class EncuentroDTO extends ActividadDTO implements Serializable{
// -------------------------------------------------------------------------
// Atributos
// -------------------------------------------------------------------------
/**
* Atributo que representa un lugar
*/
private String lugar;
/**
* Atributo que representa el número máximo de asistentes
*/
private Integer numeroMaxAsistentes;
/**
* Atributo que representa si el encuentro fue aprobado
*/
private Boolean aprobado;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
/**
* Constructor vacío
*/
public EncuentroDTO ()
{
super();
}
/**
* Convertir Entity a DTO (Crea un nuevo DTO con los valores que recibe en
* la entidad que viene de argumento.
*
* @param pEncuentroEntity: Es la entidad que se va a convertir a DTO
*/
public EncuentroDTO(EncuentroEntity pEncuentroEntity)
{
if (pEncuentroEntity != null)
{
this.id = pEncuentroEntity.getId();
this.descripcion = pEncuentroEntity.getDescripcion();
this.fecha = pEncuentroEntity.getFecha();
this.motivacion = pEncuentroEntity.getMotivacion();
this.nombre = pEncuentroEntity.getNombre();
this.pTipo = pEncuentroEntity.getSubTypeId();
this.aprobado = pEncuentroEntity.getAprobado();
this.lugar = pEncuentroEntity.getLugar();
this.numeroMaxAsistentes = pEncuentroEntity.getNumeroMaxAsistentes();
}
}
// -------------------------------------------------------------------------
// Métodos
// -------------------------------------------------------------------------
/**
* @return the lugar
*/
public String getLugar() {
return lugar;
}
/**
* @param lugar the lugar to set
*/
public void setLugar(String lugar) {
this.lugar = lugar;
}
/**
* @return the numeroMaxAsistentes
*/
public Integer getNumeroMaxAsistentes() {
return numeroMaxAsistentes;
}
/**
* @param numeroMaxAsistentes the numeroMaxAsistentes to set
*/
public void setNumeroMaxAsistentes(Integer numeroMaxAsistentes) {
this.numeroMaxAsistentes = numeroMaxAsistentes;
}
/**
* @return the aprobado
*/
public Boolean getAprobado() {
return aprobado;
}
/**
* @param aprobado the aprobado to set
*/
public void setAprobado(Boolean aprobado) {
this.aprobado = aprobado;
}
/**
* Convertir DTO a Entity
*
* @return Un Entity con los valores del DTO
*/
@Override
public EncuentroEntity toEntity()
{
EncuentroEntity encuentroEntity = new EncuentroEntity();
encuentroEntity.setId(this.getId());
encuentroEntity.setNombre(this.getNombre());
encuentroEntity.setDescripcion(this.getDescripcion());
encuentroEntity.setMotivacion(this.getMotivacion());
encuentroEntity.setFecha(this.getFecha());
encuentroEntity.setAprobado(this.getAprobado());
encuentroEntity.setLugar(this.getLugar());
encuentroEntity.setNumeroMaxAsistentes(this.getNumeroMaxAsistentes());
return encuentroEntity;
}
}
|
3e16c50af7a4087522d6ddc34f727e82c8d916e3 | 17,788 | java | Java | qpid-jms-client/src/test/java/org/apache/qpid/jms/util/URISupportTest.java | ppalaga/qpid-jms | 706514e7a1a75a45ceb1cff60583bcb76f769882 | [
"Apache-2.0"
] | 70 | 2015-04-12T15:00:13.000Z | 2022-01-31T13:06:57.000Z | qpid-jms-client/src/test/java/org/apache/qpid/jms/util/URISupportTest.java | ppalaga/qpid-jms | 706514e7a1a75a45ceb1cff60583bcb76f769882 | [
"Apache-2.0"
] | 35 | 2015-02-27T17:24:00.000Z | 2022-03-15T20:15:57.000Z | qpid-jms-client/src/test/java/org/apache/qpid/jms/util/URISupportTest.java | ppalaga/qpid-jms | 706514e7a1a75a45ceb1cff60583bcb76f769882 | [
"Apache-2.0"
] | 242 | 2015-02-27T17:18:13.000Z | 2022-03-29T00:36:07.000Z | 42.657074 | 166 | 0.651675 | 9,711 | /*
* 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.qpid.jms.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.qpid.jms.util.URISupport.CompositeData;
import org.junit.Test;
public class URISupportTest {
//---- parseComposite ----------------------------------------------------//
@Test
public void testEmptyCompositePath() throws Exception {
CompositeData data = URISupport.parseComposite(new URI("broker:()/localhost?persistent=false"));
assertEquals(0, data.getComponents().size());
}
@Test
public void testCompositePath() throws Exception {
CompositeData data = URISupport.parseComposite(new URI("test:(path)/path"));
assertEquals("path", data.getPath());
data = URISupport.parseComposite(new URI("test:path"));
assertNull(data.getPath());
}
@Test
public void testSimpleComposite() throws Exception {
CompositeData data = URISupport.parseComposite(new URI("test:part1"));
assertEquals(1, data.getComponents().size());
}
@Test
public void testParseComposite() throws Exception {
URI uri = new URI("test:(part1://host,part2://(sub1://part,sube2:part))");
CompositeData data = URISupport.parseComposite(uri);
assertEquals(2, data.getComponents().size());
assertFalse(URISupport.isCompositeURI(data.getComponents().get(0)));
assertTrue(URISupport.isCompositeURI(data.getComponents().get(1)));
assertTrue(data.getParameters().isEmpty());
}
@Test
public void testParseCompositeWithInnerURIsWithQueryValues() throws Exception {
URI uri = new URI("failover://(amqp://127.0.0.1:5678,amqp://127.0.0.2:5677,amqp://127.0.0.3:5676?amqp.traceFrames=false)?failover.useReconnectBackOff=false");
CompositeData data = URISupport.parseComposite(uri);
assertEquals(3, data.getComponents().size());
Map<String, String> parameters = data.getParameters();
assertEquals(1, parameters.size());
assertTrue(parameters.containsKey("failover.useReconnectBackOff"));
assertTrue(parameters.get("failover.useReconnectBackOff").equals("false"));
List<URI> uris = data.getComponents();
assertEquals(uris.get(0).toString(), "amqp://127.0.0.1:5678");
assertEquals(uris.get(1).toString(), "amqp://127.0.0.2:5677");
assertEquals(uris.get(2).toString(), "amqp://127.0.0.3:5676?amqp.traceFrames=false");
}
@Test
public void testParseCompositeWithMismatchedParends() throws Exception {
URI uri = new URI("test:(part1://host,part2://(sub1://part,sube2:part)");
try {
URISupport.parseComposite(uri);
fail("Should not parse when parends don't match.");
} catch (URISyntaxException ex) {
}
}
@Test
public void testEmptyCompositeWithParenthesisInParam() throws Exception {
URI uri = new URI("failover://()?updateURIsURL=file:/C:/Dir(1)/a.csv");
CompositeData data = URISupport.parseComposite(uri);
assertEquals(0, data.getComponents().size());
assertEquals(1, data.getParameters().size());
assertTrue(data.getParameters().containsKey("updateURIsURL"));
assertEquals("file:/C:/Dir(1)/a.csv", data.getParameters().get("updateURIsURL"));
}
@Test
public void testCompositeWithParenthesisInParam() throws Exception {
URI uri = new URI("failover://(test)?updateURIsURL=file:/C:/Dir(1)/a.csv");
CompositeData data = URISupport.parseComposite(uri);
assertEquals(1, data.getComponents().size());
assertEquals(1, data.getParameters().size());
assertTrue(data.getParameters().containsKey("updateURIsURL"));
assertEquals("file:/C:/Dir(1)/a.csv", data.getParameters().get("updateURIsURL"));
}
@Test
public void testCompositeWithComponentParam() throws Exception {
CompositeData data = URISupport.parseComposite(new URI("test:(part1://host?part1=true)?outside=true"));
assertEquals(1, data.getComponents().size());
assertEquals(1, data.getParameters().size());
Map<String, String> part1Params = URISupport.parseParameters(data.getComponents().get(0));
assertEquals(1, part1Params.size());
assertTrue(part1Params.containsKey("part1"));
}
@Test
public void testParsingCompositeURI() throws URISyntaxException {
CompositeData data = URISupport.parseComposite(new URI("broker://(tcp://localhost:61616)?name=foo"));
assertEquals("one component", 1, data.getComponents().size());
assertEquals("Size: " + data.getParameters(), 1, data.getParameters().size());
}
//---- parseQuery --------------------------------------------------------//
@Test
public void testParsingURI() throws Exception {
URI source = new URI("tcp://localhost:61626/foo/bar?cheese=Edam&x=123");
Map<String, String> map = PropertyUtil.parseQuery(source);
assertEquals("Size: " + map, 2, map.size());
assertMapKey(map, "cheese", "Edam");
assertMapKey(map, "x", "123");
URI result = URISupport.removeQuery(source);
assertEquals("result", new URI("tcp://localhost:61626/foo/bar"), result);
}
@Test
public void testParsingURIWithEmptyValuesInOptions() throws Exception {
URI source = new URI("tcp://localhost:61626/foo/bar?cheese=&x=");
Map<String, String> map = PropertyUtil.parseQuery(source);
assertEquals("Size: " + map, 2, map.size());
assertMapKey(map, "cheese", "");
assertMapKey(map, "x", "");
URI result = URISupport.removeQuery(source);
assertEquals("result", new URI("tcp://localhost:61626/foo/bar"), result);
}
protected void assertMapKey(Map<String, String> map, String key, Object expected) {
assertEquals("Map key: " + key, map.get(key), expected);
}
//---- checkParenthesis --------------------------------------------------------//
@Test
public void testCheckParenthesis() throws Exception {
String str = "fred:(((ddd))";
assertFalse(URISupport.checkParenthesis(str));
str += ")";
assertTrue(URISupport.checkParenthesis(str));
}
@Test
public void testCheckParenthesisWithNullOrEmpty() throws Exception {
assertTrue(URISupport.checkParenthesis(null));
assertTrue(URISupport.checkParenthesis(""));
}
//---- replaceQuery ------------------------------------------------------//
@Test
public void testParsingParams() throws Exception {
URI uri = new URI("static:(http://localhost:61617?proxyHost=jo&proxyPort=90)?proxyHost=localhost&proxyPort=80");
Map<String,String>parameters = URISupport.parseParameters(uri);
verifyParams(parameters);
uri = new URI("static://http://localhost:61617?proxyHost=localhost&proxyPort=80");
parameters = URISupport.parseParameters(uri);
verifyParams(parameters);
uri = new URI("http://0.0.0.0:61616");
parameters = URISupport.parseParameters(uri);
assertTrue(parameters.isEmpty());
uri = new URI("failover:(http://0.0.0.0:61616)");
parameters = URISupport.parseParameters(uri);
assertTrue(parameters.isEmpty());
}
@Test
public void testCreateWithQuery() throws Exception {
URI source = new URI("vm://localhost");
URI dest = PropertyUtil.replaceQuery(source, "network=true&one=two");
assertEquals("correct param count", 2, URISupport.parseParameters(dest).size());
assertEquals("same uri, host", source.getHost(), dest.getHost());
assertEquals("same uri, scheme", source.getScheme(), dest.getScheme());
assertFalse("same uri, ssp", dest.getQuery().equals(source.getQuery()));
}
@Test
public void testApplyParameters() throws Exception {
URI uri = new URI("http://0.0.0.0:61616");
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("t.proxyHost", "localhost");
parameters.put("t.proxyPort", "80");
uri = URISupport.applyParameters(uri, parameters);
Map<String,String> appliedParameters = URISupport.parseParameters(uri);
assertEquals("all params applied with no prefix", 2, appliedParameters.size());
// strip off params again
uri = PropertyUtil.eraseQuery(uri);
uri = URISupport.applyParameters(uri, parameters, "joe");
appliedParameters = URISupport.parseParameters(uri);
assertTrue("no params applied as none match joe", appliedParameters.isEmpty());
uri = URISupport.applyParameters(uri, parameters, "t.");
verifyParams(URISupport.parseParameters(uri));
}
//---- parseParameters ---------------------------------------------------//
@Test
public void testCompositeCreateURIWithQuery() throws Exception {
String queryString = "query=value";
URI originalURI = new URI("outerscheme:(innerscheme:innerssp)");
URI querylessURI = originalURI;
assertEquals(querylessURI, PropertyUtil.eraseQuery(originalURI));
assertEquals(querylessURI, PropertyUtil.replaceQuery(originalURI, ""));
assertEquals(new URI(querylessURI + "?" + queryString), PropertyUtil.replaceQuery(originalURI, queryString));
originalURI = new URI("outerscheme:(innerscheme:innerssp)?outerquery=0");
assertEquals(querylessURI, PropertyUtil.eraseQuery(originalURI));
assertEquals(querylessURI, PropertyUtil.replaceQuery(originalURI, ""));
assertEquals(new URI(querylessURI + "?" + queryString), PropertyUtil.replaceQuery(originalURI, queryString));
originalURI = new URI("outerscheme:(innerscheme:innerssp?innerquery=0)");
querylessURI = originalURI;
assertEquals(querylessURI, PropertyUtil.eraseQuery(originalURI));
assertEquals(querylessURI, PropertyUtil.replaceQuery(originalURI, ""));
assertEquals(new URI(querylessURI + "?" + queryString), PropertyUtil.replaceQuery(originalURI, queryString));
originalURI = new URI("outerscheme:(innerscheme:innerssp?innerquery=0)?outerquery=0");
assertEquals(querylessURI, PropertyUtil.eraseQuery(originalURI));
assertEquals(querylessURI, PropertyUtil.replaceQuery(originalURI, ""));
assertEquals(new URI(querylessURI + "?" + queryString), PropertyUtil.replaceQuery(originalURI, queryString));
}
@Test
public void testApplyParametersPreservesOriginalParameters() throws Exception {
URI uri = new URI("http://0.0.0.0:61616?timeout=1000");
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("t.proxyHost", "localhost");
parameters.put("t.proxyPort", "80");
uri = URISupport.applyParameters(uri, parameters, "t.");
Map<String,String> appliedParameters = URISupport.parseParameters(uri);
assertEquals("all params applied with no prefix", 3, appliedParameters.size());
verifyParams(appliedParameters);
}
@Test
public void testApplyParametersOverwritesOriginalParameters() throws Exception {
URI uri = new URI("http://0.0.0.0:61616?proxyHost=host&proxyPort=21&timeout=1000");
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("proxyHost", "localhost");
parameters.put("proxyPort", "80");
uri = URISupport.applyParameters(uri, parameters);
Map<String,String> appliedParameters = URISupport.parseParameters(uri);
assertEquals("all params applied with no prefix", 3, appliedParameters.size());
verifyParams(appliedParameters);
}
private void verifyParams(Map<String,String> parameters) {
assertEquals("localhost", parameters.get("proxyHost"));
assertEquals("80", parameters.get("proxyPort"));
}
//---- isCompositeURI ----------------------------------------------------//
@Test
public void testIsCompositeURIWithQueryNoSlashes() throws URISyntaxException {
URI[] compositeURIs = new URI[] { new URI("test:(part1://host?part1=true)?outside=true"), new URI("broker:(tcp://localhost:61616)?name=foo") };
for (URI uri : compositeURIs) {
assertTrue(uri + " must be detected as composite URI", URISupport.isCompositeURI(uri));
}
}
@Test
public void testIsCompositeURIWithQueryAndSlashes() throws URISyntaxException {
URI[] compositeURIs = new URI[] { new URI("test://(part1://host?part1=true)?outside=true"), new URI("broker://(tcp://localhost:61616)?name=foo") };
for (URI uri : compositeURIs) {
assertTrue(uri + " must be detected as composite URI", URISupport.isCompositeURI(uri));
}
}
@Test
public void testIsCompositeURINoQueryNoSlashes() throws URISyntaxException {
URI[] compositeURIs = new URI[] { new URI("test:(part1://host,part2://(sub1://part,sube2:part))"), new URI("test:(path)/path") };
for (URI uri : compositeURIs) {
assertTrue(uri + " must be detected as composite URI", URISupport.isCompositeURI(uri));
}
}
@Test
public void testIsCompositeWhenURIHasUnmatchedParends() throws Exception {
URI uri = new URI("test:(part1://host,part2://(sub1://part,sube2:part)");
assertFalse(URISupport.isCompositeURI(uri));
}
@Test
public void testIsCompositeURINoQueryNoSlashesNoParentheses() throws URISyntaxException {
assertFalse("test:part1" + " must be detected as non-composite URI", URISupport.isCompositeURI(new URI("test:part1")));
}
@Test
public void testIsCompositeURINoQueryWithSlashes() throws URISyntaxException {
URI[] compositeURIs = new URI[] { new URI("failover://(tcp://bla:61616,tcp://bla:61617)"),
new URI("failover://(tcp://localhost:61616,ssl://anotherhost:61617)") };
for (URI uri : compositeURIs) {
assertTrue(uri + " must be detected as composite URI", URISupport.isCompositeURI(uri));
}
}
//---- indexOfParenthesisMatch -------------------------------------------//
@Test
public void testIndexOfParenthesisMatch() throws URISyntaxException {
String source1 = "a(b)c";
assertEquals(3, URISupport.indexOfParenthesisMatch(source1, 1));
String source2 = "(b)";
assertEquals(2, URISupport.indexOfParenthesisMatch(source2, 0));
String source3 = "()";
assertEquals(1, URISupport.indexOfParenthesisMatch(source3, 0));
}
@Test
public void testIndexOfParenthesisMatchWhenNoMatchPresent() throws URISyntaxException {
try {
String source = "a(bc";
URISupport.indexOfParenthesisMatch(source, 1);
fail("Should have thrown URISyntaxException");
} catch (URISyntaxException use) {}
try {
String source = "(";
URISupport.indexOfParenthesisMatch(source, 0);
fail("Should have thrown URISyntaxException");
} catch (URISyntaxException use) {}
try {
String source = "a(";
URISupport.indexOfParenthesisMatch(source, 1);
fail("Should have thrown URISyntaxException");
} catch (URISyntaxException use) {}
}
@Test
public void testIndexOfParenthesisMatchExceptions() throws URISyntaxException {
try {
URISupport.indexOfParenthesisMatch(null, -1);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException iobe) {}
try {
URISupport.indexOfParenthesisMatch("tcp", 4);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException iobe) {}
try {
URISupport.indexOfParenthesisMatch("tcp", 2);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException iobe) {}
try {
URISupport.indexOfParenthesisMatch("(tcp", 0);
fail("Should have thrown URISyntaxException");
} catch (URISyntaxException iobe) {}
}
//---- applyParameters ---------------------------------------------------//
@Test
public void testApplyParametersWithNullOrEmptyParameters() throws URISyntaxException {
URI uri = new URI("tcp://localhost");
URI result = URISupport.applyParameters(uri, null, "value.");
assertSame(uri, result);
result = URISupport.applyParameters(uri, Collections.<String, String>emptyMap(), "value.");
assertSame(uri, result);
}
}
|
3e16c5a14f3b7860dcfc148f2c500d9e2f4942ec | 3,928 | java | Java | src/poblacion/AGenetico.java | r3sic/Programacion-Evolutiva-3 | 9c56f2892b95811b0d6df2f37ee0ab3934cfd1d2 | [
"Apache-2.0"
] | null | null | null | src/poblacion/AGenetico.java | r3sic/Programacion-Evolutiva-3 | 9c56f2892b95811b0d6df2f37ee0ab3934cfd1d2 | [
"Apache-2.0"
] | null | null | null | src/poblacion/AGenetico.java | r3sic/Programacion-Evolutiva-3 | 9c56f2892b95811b0d6df2f37ee0ab3934cfd1d2 | [
"Apache-2.0"
] | null | null | null | 21.944134 | 177 | 0.71945 | 9,712 | package poblacion;
public class AGenetico {
private Poblacion _poblacion;
private int _num_max_gen;
private int _gen_actual;
private double _prob_cruce;
private double _prob_mut;
private double _mejorApt;
private String _mejorFen;
private double _elitismo;
private int _tam;
private double _trunc;
private String _seleccion;
private String _mutacion;
private String _ini;
private int _hMax;
private boolean _creciente;
public AGenetico(int max_gen, double cruce, double mut, double elitismo, int tam, String seleccion, double trunc, String choice_mut, String ini, int hMax, boolean creciente) {
_num_max_gen = max_gen;
_gen_actual = 0;
_prob_cruce = cruce;
_prob_mut = mut;
_trunc = trunc;
_tam = tam;
_mutacion = choice_mut;
_seleccion = seleccion;
_elitismo = elitismo;
_ini = ini;
_hMax = hMax;
_creciente = creciente;
_poblacion = FactoriaPoblaciones.getPoblacion(tam,seleccion, choice_mut, elitismo, trunc, ini,hMax, creciente);
}
public AGenetico() {
_gen_actual = 0;
}
public void ejecutaAG(Solucion sol) {
_mejorApt = _poblacion.getMejorApt();
_mejorFen = _poblacion.getMejorFen();
sol.set_fenotipo(_mejorFen);
while(_gen_actual < _num_max_gen) {
System.out.println(_mejorFen+" :"+_mejorApt +" -> "+_poblacion.getMejorFen() + " :" + _poblacion.getMejorApt());
_poblacion.seleccion();
_poblacion.cruce(_prob_cruce);
_poblacion.mutacion(_prob_mut);
_poblacion.seleccionElitismo();
if(_mejorApt < _poblacion.getMejorApt()) {
_mejorApt = _poblacion.getMejorApt();
_mejorFen = _poblacion.getMejorFen();
sol.set_fenotipo(_mejorFen);
}
sol.add(_mejorApt, _poblacion.getMejorApt(), _poblacion.media());
_gen_actual++;
System.out.print(".");
if(_gen_actual %40 == 0)System.out.print("\n");
}
System.out.println(_mejorFen+" :"+_mejorApt +" -> "+_poblacion.getMejorFen() + " :" + _poblacion.getMejorApt());
}
public void Inicialia() {
this._poblacion =FactoriaPoblaciones.getPoblacion(_tam, _seleccion, _mutacion, _elitismo, _trunc, _ini, _hMax, _creciente);
}
public Poblacion get_poblacion() {
return _poblacion;
}
public void set_poblacion(Poblacion _poblacion) {
this._poblacion = _poblacion;
}
public int get_num_max_gen() {
return _num_max_gen;
}
public void set_num_max_gen(int _num_max_gen) {
this._num_max_gen = _num_max_gen;
}
public int get_gen_actual() {
return _gen_actual;
}
public void set_gen_actual(int _gen_actual) {
this._gen_actual = _gen_actual;
}
public double get_prob_cruce() {
return _prob_cruce;
}
public void set_prob_cruce(double _prob_cruce) {
this._prob_cruce = _prob_cruce;
}
public double get_prob_mut() {
return _prob_mut;
}
public void set_prob_mut(double _prob_mut) {
this._prob_mut = _prob_mut;
}
public double get_mejorApt() {
return _mejorApt;
}
public void set_mejorApt(double _mejorApt) {
this._mejorApt = _mejorApt;
}
public double get_elitismo() {
return _elitismo;
}
public void set_elitismo(double _elitismo) {
this._elitismo = _elitismo;
}
public int get_tam() {
return _tam;
}
public void set_tam(int _tam) {
this._tam = _tam;
}
public double get_trunc() {
return _trunc;
}
public void set_trunc(double _trunc) {
this._trunc = _trunc;
}
public String get_seleccion() {
return _seleccion;
}
public void set_seleccion(String _seleccion) {
this._seleccion = _seleccion;
}
public String get_mutacion() {
return _mutacion;
}
public void set_mutacion(String _mutacion) {
this._mutacion = _mutacion;
}
public String get_ini() {
return _ini;
}
public void set_ini(String _ini) {
this._ini = _ini;
}
public int get_hMax() {
return _hMax;
}
public void set_hMax(int _hMax) {
this._hMax = _hMax;
}
public boolean is_creciente() {
return _creciente;
}
public void set_creciente(boolean _creciente) {
this._creciente = _creciente;
}
}
|
3e16c5ccad2ad08ba5ead6be68d29c627f9fed52 | 1,939 | java | Java | ngcsmodel.editor/src-gen/com/home/ludo/ngcs/ngcsmodel/presentation/NgcsmodelEditorPlugin.java | lstumme/ngcsgenerator | 88215a0135efb524a8115c6d6b16d0a7917eb473 | [
"MIT"
] | null | null | null | ngcsmodel.editor/src-gen/com/home/ludo/ngcs/ngcsmodel/presentation/NgcsmodelEditorPlugin.java | lstumme/ngcsgenerator | 88215a0135efb524a8115c6d6b16d0a7917eb473 | [
"MIT"
] | null | null | null | ngcsmodel.editor/src-gen/com/home/ludo/ngcs/ngcsmodel/presentation/NgcsmodelEditorPlugin.java | lstumme/ngcsgenerator | 88215a0135efb524a8115c6d6b16d0a7917eb473 | [
"MIT"
] | null | null | null | 21.544444 | 83 | 0.597731 | 9,713 | /**
*/
package com.home.ludo.ngcs.ngcsmodel.presentation;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.common.ui.EclipseUIPlugin;
import org.eclipse.emf.common.util.ResourceLocator;
/**
* This is the central singleton for the Ngcsmodel editor plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public final class NgcsmodelEditorPlugin extends EMFPlugin {
/**
* Keep track of the singleton.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final NgcsmodelEditorPlugin INSTANCE = new NgcsmodelEditorPlugin();
/**
* Keep track of the singleton.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static Implementation plugin;
/**
* Create the instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NgcsmodelEditorPlugin() {
super(new ResourceLocator[] {});
}
/**
* Returns the singleton instance of the Eclipse plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the singleton instance.
* @generated
*/
@Override
public ResourceLocator getPluginResourceLocator() {
return plugin;
}
/**
* Returns the singleton instance of the Eclipse plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the singleton instance.
* @generated
*/
public static Implementation getPlugin() {
return plugin;
}
/**
* The actual implementation of the Eclipse <b>Plugin</b>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class Implementation extends EclipseUIPlugin {
/**
* Creates an instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Implementation() {
super();
// Remember the static instance.
//
plugin = this;
}
}
}
|
3e16c5d08f7d447d88904bcb42a30ec678705766 | 55,031 | java | Java | modules/andes-core/broker/src/test/java/org/wso2/andes/server/configuration/ServerConfigurationTest.java | Vathsan/andes | 292855fda3d4d047e8f2d2ca230fba166e7414b1 | [
"Apache-2.0"
] | 3 | 2017-08-01T04:41:47.000Z | 2018-04-20T10:12:21.000Z | modules/andes-core/broker/src/test/java/org/wso2/andes/server/configuration/ServerConfigurationTest.java | a5anka/andes | 7b4a8cd5d16777b920a0c6ca208aa07ea6426c49 | [
"Apache-2.0"
] | 183 | 2015-01-12T03:58:20.000Z | 2021-03-05T11:45:20.000Z | modules/andes-core/broker/src/test/java/org/wso2/andes/server/configuration/ServerConfigurationTest.java | a5anka/andes | 7b4a8cd5d16777b920a0c6ca208aa07ea6426c49 | [
"Apache-2.0"
] | 114 | 2015-01-22T05:06:07.000Z | 2022-03-30T03:18:29.000Z | 40.197955 | 141 | 0.647035 | 9,714 | /*
*
* 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.wso2.andes.configuration.qpid;
import static org.wso2.andes.transport.ConnectionSettings.WILDCARD_ADDRESS;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Locale;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.wso2.andes.configuration.qpid.ExchangeConfiguration;
import org.wso2.andes.configuration.qpid.ServerConfiguration;
import org.wso2.andes.configuration.qpid.VirtualHostConfiguration;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.server.exchange.Exchange;
import org.wso2.andes.server.registry.ApplicationRegistry;
import org.wso2.andes.server.registry.ConfigurationFileApplicationRegistry;
import org.wso2.andes.server.util.TestApplicationRegistry;
import org.wso2.andes.server.virtualhost.VirtualHost;
import org.wso2.andes.server.virtualhost.VirtualHostRegistry;
import org.wso2.andes.test.utils.QpidTestCase;
public class ServerConfigurationTest extends QpidTestCase
{
private XMLConfiguration _config = new XMLConfiguration();
private ServerConfiguration _serverConfig = null;
@Override
protected void setUp() throws Exception
{
super.setUp();
_serverConfig = new ServerConfiguration(_config);
ApplicationRegistry.initialise(new TestApplicationRegistry(_serverConfig));
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
ApplicationRegistry.remove();
}
public void testSetJMXManagementPort() throws ConfigurationException
{
_serverConfig.initialise();
_serverConfig.setJMXManagementPort(23);
assertEquals(23, _serverConfig.getJMXManagementPort());
}
public void testGetJMXManagementPort() throws ConfigurationException
{
_config.setProperty("management.jmxport", 42);
_serverConfig.initialise();
assertEquals(42, _serverConfig.getJMXManagementPort());
}
public void testGetPlatformMbeanserver() throws ConfigurationException
{
_serverConfig.initialise();
assertEquals(true, _serverConfig.getPlatformMbeanserver());
// Check value we set
_config.setProperty("management.platform-mbeanserver", false);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(false, _serverConfig.getPlatformMbeanserver());
}
public void testGetPluginDirectory() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(null, _serverConfig.getPluginDirectory());
// Check value we set
_config.setProperty("plugin-directory", "/path/to/plugins");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("/path/to/plugins", _serverConfig.getPluginDirectory());
}
public void testGetCacheDirectory() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(null, _serverConfig.getCacheDirectory());
// Check value we set
_config.setProperty("cache-directory", "/path/to/cache");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("/path/to/cache", _serverConfig.getCacheDirectory());
}
public void testGetFrameSize() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(65536, _serverConfig.getFrameSize());
// Check value we set
_config.setProperty("advanced.framesize", "23");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(23, _serverConfig.getFrameSize());
}
public void testGetStatusEnabled() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(ServerConfiguration.DEFAULT_STATUS_UPDATES.equalsIgnoreCase("on"),
_serverConfig.getStatusUpdatesEnabled());
// Check disabling we set
_config.setProperty(ServerConfiguration.STATUS_UPDATES, "off");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(false, _serverConfig.getStatusUpdatesEnabled());
// Check invalid values don't cause error but result in disabled
_config.setProperty(ServerConfiguration.STATUS_UPDATES, "Yes Please");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(false, _serverConfig.getStatusUpdatesEnabled());
}
public void testGetSynchedClocks() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(false, _serverConfig.getSynchedClocks());
// Check value we set
_config.setProperty("advanced.synced-clocks", true);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(true, _serverConfig.getSynchedClocks());
}
public void testGetLocale() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
// The Default is what ever the VMs default is
Locale defaultLocale = Locale.getDefault();
assertEquals(defaultLocale, _serverConfig.getLocale());
//Test Language only
Locale update = new Locale("es");
_config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(update, _serverConfig.getLocale());
//Test Language and Country
update = new Locale("es","ES");
_config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es_ES");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(update, _serverConfig.getLocale());
//Test Language and Country and Variant
update = new Locale("es","ES", "Traditional_WIN");
_config.setProperty(ServerConfiguration.ADVANCED_LOCALE, "es_ES_Traditional_WIN");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(update, _serverConfig.getLocale());
}
public void testGetMsgAuth() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(false, _serverConfig.getMsgAuth());
// Check value we set
_config.setProperty("security.msg-auth", true);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(true, _serverConfig.getMsgAuth());
}
public void testGetManagementKeyStorePath() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(null, _serverConfig.getManagementKeyStorePath());
// Check value we set
_config.setProperty("management.ssl.keyStorePath", "a");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("a", _serverConfig.getManagementKeyStorePath());
}
public void testGetManagementSSLEnabled() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(true, _serverConfig.getManagementSSLEnabled());
// Check value we set
_config.setProperty("management.ssl.enabled", false);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(false, _serverConfig.getManagementSSLEnabled());
}
public void testGetManagementKeyStorePassword() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(null, _serverConfig.getManagementKeyStorePassword());
// Check value we set
_config.setProperty("management.ssl.keyStorePassword", "a");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("a", _serverConfig.getManagementKeyStorePassword());
}
public void testGetQueueAutoRegister() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(true, _serverConfig.getQueueAutoRegister());
// Check value we set
_config.setProperty("queue.auto_register", false);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(false, _serverConfig.getQueueAutoRegister());
}
public void testGetManagementEnabled() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(true, _serverConfig.getManagementEnabled());
// Check value we set
_config.setProperty("management.enabled", false);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(false, _serverConfig.getManagementEnabled());
}
public void testSetManagementEnabled() throws ConfigurationException
{
// Check value we set
_serverConfig.initialise();
_serverConfig.setManagementEnabled(false);
assertEquals(false, _serverConfig.getManagementEnabled());
}
public void testGetHeartBeatDelay() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(5, _serverConfig.getHeartBeatDelay());
// Check value we set
_config.setProperty("heartbeat.delay", 23);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(23, _serverConfig.getHeartBeatDelay());
}
public void testGetHeartBeatTimeout() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(2.0, _serverConfig.getHeartBeatTimeout());
// Check value we set
_config.setProperty("heartbeat.timeoutFactor", 2.3);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(2.3, _serverConfig.getHeartBeatTimeout());
}
public void testGetMaximumMessageAge() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(0, _serverConfig.getMaximumMessageAge());
// Check value we set
_config.setProperty("maximumMessageAge", 10L);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(10, _serverConfig.getMaximumMessageAge());
}
public void testGetMaximumMessageCount() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(0, _serverConfig.getMaximumMessageCount());
// Check value we set
_config.setProperty("maximumMessageCount", 10L);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(10, _serverConfig.getMaximumMessageCount());
}
public void testGetMaximumQueueDepth() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(0, _serverConfig.getMaximumQueueDepth());
// Check value we set
_config.setProperty("maximumQueueDepth", 10L);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(10, _serverConfig.getMaximumQueueDepth());
}
public void testGetMaximumMessageSize() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(0, _serverConfig.getMaximumMessageSize());
// Check value we set
_config.setProperty("maximumMessageSize", 10L);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(10, _serverConfig.getMaximumMessageSize());
}
public void testGetMinimumAlertRepeatGap() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(0, _serverConfig.getMinimumAlertRepeatGap());
// Check value we set
_config.setProperty("minimumAlertRepeatGap", 10L);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(10, _serverConfig.getMinimumAlertRepeatGap());
}
public void testGetProcessors() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(4, _serverConfig.getConnectorProcessors());
// Check value we set
_config.setProperty("connector.processors", 10);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(10, _serverConfig.getConnectorProcessors());
}
public void testGetPorts() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertNotNull(_serverConfig.getPorts());
assertEquals(1, _serverConfig.getPorts().size());
assertEquals(5672, _serverConfig.getPorts().get(0));
// Check value we set
_config.setProperty("connector.port", "10");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertNotNull(_serverConfig.getPorts());
assertEquals(1, _serverConfig.getPorts().size());
assertEquals("10", _serverConfig.getPorts().get(0));
}
public void testGetBind() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(WILDCARD_ADDRESS, _serverConfig.getBind());
// Check value we set
_config.setProperty("connector.bind", "a");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("a", _serverConfig.getBind());
}
public void testGetReceiveBufferSize() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(ServerConfiguration.DEFAULT_BUFFER_SIZE, _serverConfig.getReceiveBufferSize());
// Check value we set
_config.setProperty("connector.socketReceiveBuffer", "23");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(23, _serverConfig.getReceiveBufferSize());
}
public void testGetWriteBufferSize() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(ServerConfiguration.DEFAULT_BUFFER_SIZE, _serverConfig.getWriteBufferSize());
// Check value we set
_config.setProperty("connector.socketWriteBuffer", "23");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(23, _serverConfig.getWriteBufferSize());
}
public void testGetTcpNoDelay() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(true, _serverConfig.getTcpNoDelay());
// Check value we set
_config.setProperty("connector.tcpNoDelay", false);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(false, _serverConfig.getTcpNoDelay());
}
public void testGetEnableExecutorPool() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(false, _serverConfig.getEnableExecutorPool());
// Check value we set
_config.setProperty("advanced.filterchain[@enableExecutorPool]", true);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(true, _serverConfig.getEnableExecutorPool());
}
public void testGetEnableSSL() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(false, _serverConfig.getEnableSSL());
// Check value we set
_config.setProperty("connector.ssl.enabled", true);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(true, _serverConfig.getEnableSSL());
}
public void testGetSSLOnly() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(false, _serverConfig.getSSLOnly());
// Check value we set
_config.setProperty("connector.ssl.sslOnly", true);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(true, _serverConfig.getSSLOnly());
}
public void testGetSSLPorts() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertNotNull(_serverConfig.getSSLPorts());
assertEquals(1, _serverConfig.getSSLPorts().size());
assertEquals(ServerConfiguration.DEFAULT_SSL_PORT, _serverConfig.getSSLPorts().get(0));
// Check value we set
_config.setProperty("connector.ssl.port", "10");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertNotNull(_serverConfig.getSSLPorts());
assertEquals(1, _serverConfig.getSSLPorts().size());
assertEquals("10", _serverConfig.getSSLPorts().get(0));
}
public void testGetKeystorePath() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals("none", _serverConfig.getKeystorePath());
// Check value we set
_config.setProperty("connector.ssl.keystorePath", "a");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("a", _serverConfig.getKeystorePath());
}
public void testGetKeystorePassword() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals("none", _serverConfig.getKeystorePassword());
// Check value we set
_config.setProperty("connector.ssl.keystorePassword", "a");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("a", _serverConfig.getKeystorePassword());
}
public void testGetCertType() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals("SunX509", _serverConfig.getKeyStoreCertType());
// Check value we set
_config.setProperty("connector.ssl.certType", "a");
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals("a", _serverConfig.getKeyStoreCertType());
}
public void testGetUseBiasedWrites() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(false, _serverConfig.getUseBiasedWrites());
// Check value we set
_config.setProperty("advanced.useWriteBiasedPool", true);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(true, _serverConfig.getUseBiasedWrites());
}
public void testGetHousekeepingExpiredMessageCheckPeriod() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
assertEquals(30000, _serverConfig.getHousekeepingCheckPeriod());
// Check value we set
_config.setProperty("housekeeping.expiredMessageCheckPeriod", 23L);
_serverConfig = new ServerConfiguration(_config);
_serverConfig.initialise();
assertEquals(23, _serverConfig.getHousekeepingCheckPeriod());
_serverConfig.setHousekeepingExpiredMessageCheckPeriod(42L);
assertEquals(42, _serverConfig.getHousekeepingCheckPeriod());
}
public void testSingleConfiguration() throws IOException, ConfigurationException
{
File fileA = File.createTempFile(getClass().getName(), null);
fileA.deleteOnExit();
FileWriter out = new FileWriter(fileA);
out.write("<broker><connector><port>2342</port><ssl><port>4235</port></ssl></connector></broker>");
out.close();
ServerConfiguration conf = new ServerConfiguration(fileA);
conf.initialise();
assertEquals("4235", conf.getSSLPorts().get(0));
}
public void testCombinedConfiguration() throws IOException, ConfigurationException
{
File mainFile = File.createTempFile(getClass().getName(), null);
File fileA = File.createTempFile(getClass().getName(), null);
File fileB = File.createTempFile(getClass().getName(), null);
mainFile.deleteOnExit();
fileA.deleteOnExit();
fileB.deleteOnExit();
FileWriter out = new FileWriter(mainFile);
out.write("<configuration><system/>");
out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>");
out.write("<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>");
out.write("</configuration>");
out.close();
out = new FileWriter(fileA);
out.write("<broker><connector><port>2342</port><ssl><port>4235</port></ssl></connector></broker>");
out.close();
out = new FileWriter(fileB);
out.write("<broker><connector><ssl><port>2345</port></ssl></connector></broker>");
out.close();
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
assertEquals("4235", config.getSSLPorts().get(0)); // From first file, not
// overriden by second
assertNotNull(config.getPorts());
assertEquals(1, config.getPorts().size());
assertEquals("2342", config.getPorts().get(0)); // From the first file, not
// present in the second
}
public void testVariableInterpolation() throws Exception
{
File mainFile = File.createTempFile(getClass().getName(), null);
mainFile.deleteOnExit();
FileWriter out = new FileWriter(mainFile);
out.write("<broker>\n");
out.write("\t<work>foo</work>\n");
out.write("\t<management><ssl><keyStorePath>${work}</keyStorePath></ssl></management>\n");
out.write("</broker>\n");
out.close();
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
assertEquals("Did not get correct interpolated value",
"foo", config.getManagementKeyStorePath());
}
private void writeConfigFile(File mainFile, boolean allow) throws IOException {
writeConfigFile(mainFile, allow, true, null, "test");
}
private void writeConfigFile(File mainFile, boolean allow, boolean includeVhosts, File vhostsFile, String name) throws IOException {
FileWriter out = new FileWriter(mainFile);
out.write("<broker>\n");
out.write("\t<management><enabled>false</enabled></management>\n");
out.write("\t<security>\n");
out.write("\t\t<pd-auth-manager>\n");
out.write("\t\t\t<principal-database>\n");
out.write("\t\t\t\t<class>org.wso2.andes.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
out.write("\t\t\t\t<attributes>\n");
out.write("\t\t\t\t\t<attribute>\n");
out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
out.write("\t\t\t\t\t</attribute>\n");
out.write("\t\t\t\t</attributes>\n");
out.write("\t\t\t</principal-database>\n");
out.write("\t\t</pd-auth-manager>\n");
out.write("\t\t<firewall>\n");
out.write("\t\t\t<rule access=\""+ ((allow) ? "allow" : "deny") +"\" network=\"127.0.0.1\"/>");
out.write("\t\t</firewall>\n");
out.write("\t</security>\n");
if (includeVhosts)
{
out.write("\t<virtualhosts>\n");
out.write("\t\t<default>test</default>\n");
out.write("\t\t<virtualhost>\n");
out.write(String.format("\t\t\t<name>%s</name>\n", name));
out.write(String.format("\t\t<%s> \n", name));
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<type>topic</type>\n");
out.write(String.format("\t\t\t\t\t<name>%s.topic</name>\n", name));
out.write("\t\t\t\t\t<durable>true</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write(String.format("\t\t</%s> \n", name));
out.write("\t\t</virtualhost>\n");
out.write("\t</virtualhosts>\n");
}
if (vhostsFile != null)
{
out.write("\t<virtualhosts>"+vhostsFile.getAbsolutePath()+"</virtualhosts>\n");
}
out.write("</broker>\n");
out.close();
}
private void writeTestFishConfigFile(File mainFile) throws IOException {
FileWriter out = new FileWriter(mainFile);
out.write("<broker>\n");
out.write("\t<management><enabled>false</enabled></management>\n");
out.write("\t<security>\n");
out.write("\t\t<pd-auth-manager>\n");
out.write("\t\t\t<principal-database>\n");
out.write("\t\t\t\t<class>org.wso2.andes.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
out.write("\t\t\t\t<attributes>\n");
out.write("\t\t\t\t\t<attribute>\n");
out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
out.write("\t\t\t\t\t</attribute>\n");
out.write("\t\t\t\t</attributes>\n");
out.write("\t\t\t</principal-database>\n");
out.write("\t\t</pd-auth-manager>\n");
out.write("\t\t<firewall>\n");
out.write("\t\t\t<rule access=\"allow\" network=\"127.0.0.1\"/>");
out.write("\t\t</firewall>\n");
out.write("\t</security>\n");
out.write("\t<virtualhosts>\n");
out.write("\t\t<virtualhost>\n");
out.write("\t\t\t<name>test</name>\n");
out.write("\t\t<test> \n");
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<type>topic</type>\n");
out.write("\t\t\t\t\t<name>test.topic</name>\n");
out.write("\t\t\t\t\t<durable>true</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write("\t\t</test> \n");
out.write("\t\t</virtualhost>\n");
out.write("\t\t<virtualhost>\n");
out.write("\t\t\t<name>fish</name>\n");
out.write("\t\t<fish> \n");
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<type>topic</type>\n");
out.write("\t\t\t\t\t<name>fish.topic</name>\n");
out.write("\t\t\t\t\t<durable>false</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write("\t\t</fish> \n");
out.write("\t\t</virtualhost>\n");
out.write("\t</virtualhosts>\n");
out.write("</broker>\n");
out.close();
}
private void writeVirtualHostsFile(File vhostsFile, String name) throws IOException {
FileWriter out = new FileWriter(vhostsFile);
out.write("<virtualhosts>\n");
out.write(String.format("\t\t<default>%s</default>\n", name));
out.write("\t<virtualhost>\n");
out.write(String.format("\t\t<name>%s</name>\n", name));
out.write(String.format("\t\t<%s>\n", name));
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<type>topic</type>\n");
out.write("\t\t\t\t\t<name>test.topic</name>\n");
out.write("\t\t\t\t\t<durable>true</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write(String.format("\t\t</%s>\n", name));
out.write("\t</virtualhost>\n");
out.write("</virtualhosts>\n");
out.close();
}
private void writeMultiVirtualHostsFile(File vhostsFile) throws IOException {
FileWriter out = new FileWriter(vhostsFile);
out.write("<virtualhosts>\n");
out.write("\t<virtualhost>\n");
out.write("\t\t<name>topic</name>\n");
out.write("\t\t<topic>\n");
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<type>topic</type>\n");
out.write("\t\t\t\t\t<name>test.topic</name>\n");
out.write("\t\t\t\t\t<durable>true</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write("\t\t</topic>\n");
out.write("\t</virtualhost>\n");
out.write("\t<virtualhost>\n");
out.write("\t\t<name>fanout</name>\n");
out.write("\t\t<fanout>\n");
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<type>fanout</type>\n");
out.write("\t\t\t\t\t<name>test.fanout</name>\n");
out.write("\t\t\t\t\t<durable>true</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write("\t\t</fanout>\n");
out.write("\t</virtualhost>\n");
out.write("</virtualhosts>\n");
out.close();
}
private void writeMultipleVhostsConfigFile(File mainFile, File[] vhostsFileArray) throws IOException {
FileWriter out = new FileWriter(mainFile);
out.write("<broker>\n");
out.write("\t<management><enabled>false</enabled></management>\n");
out.write("\t<security>\n");
out.write("\t\t<pd-auth-manager>\n");
out.write("\t\t\t<principal-database>\n");
out.write("\t\t\t\t<class>org.wso2.andes.server.security.auth.database.PlainPasswordFilePrincipalDatabase</class>\n");
out.write("\t\t\t\t<attributes>\n");
out.write("\t\t\t\t\t<attribute>\n");
out.write("\t\t\t\t\t\t<name>passwordFile</name>\n");
out.write("\t\t\t\t\t\t<value>/dev/null</value>\n");
out.write("\t\t\t\t\t</attribute>\n");
out.write("\t\t\t\t</attributes>\n");
out.write("\t\t\t</principal-database>\n");
out.write("\t\t</pd-auth-manager>\n");
out.write("\t\t<firewall>\n");
out.write("\t\t\t<rule access=\"allow\" network=\"127.0.0.1\"/>");
out.write("\t\t</firewall>\n");
out.write("\t</security>\n");
for (File vhostsFile : vhostsFileArray)
{
out.write("\t<virtualhosts>"+vhostsFile.getAbsolutePath()+"</virtualhosts>\n");
}
out.write("</broker>\n");
out.close();
}
private void writeCombinedConfigFile(File mainFile, File fileA, File fileB) throws Exception
{
FileWriter out = new FileWriter(mainFile);
out.write("<configuration><system/>");
out.write("<xml fileName=\"" + fileA.getAbsolutePath() + "\"/>");
out.write("<xml fileName=\"" + fileB.getAbsolutePath() + "\"/>");
out.write("</configuration>");
out.close();
}
/**
* Test that configuration loads correctly when virtual hosts are specified in the main
* configuration file only.
* <p>
* Test for QPID-2361
*/
public void testInternalVirtualhostConfigFile() throws Exception
{
// Write out config
File mainFile = File.createTempFile(getClass().getName(), "config");
mainFile.deleteOnExit();
writeConfigFile(mainFile, false, true, null, "test");
// Load config
ApplicationRegistry.remove();
ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
ApplicationRegistry.initialise(reg);
// Test config
VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
String defaultVirtualHost = reg.getConfiguration().getDefaultVirtualHost();
VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test");
Exchange exchange = virtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic"));
assertEquals("Incorrect default host", "test", defaultVirtualHost);
assertEquals("Incorrect virtualhost count", 1, virtualHostRegistry.getVirtualHosts().size());
assertEquals("Incorrect virtualhost name", "test", virtualHost.getName());
assertEquals("Incorrect exchange type", "topic", exchange.getType().getName().toString());
}
/**
* Test that configuration loads correctly when virtual hosts are specified in an external
* configuration file only.
* <p>
* Test for QPID-2361
*/
public void testExternalVirtualhostXMLFile() throws Exception
{
// Write out config
File mainFile = File.createTempFile(getClass().getName(), "config");
mainFile.deleteOnExit();
File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
vhostsFile.deleteOnExit();
writeConfigFile(mainFile, false, false, vhostsFile, null);
writeVirtualHostsFile(vhostsFile, "test");
// Load config
ApplicationRegistry.remove();
ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
ApplicationRegistry.initialise(reg);
// Test config
VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
String defaultVirtualHost = reg.getConfiguration().getDefaultVirtualHost();
VirtualHost virtualHost = virtualHostRegistry.getVirtualHost("test");
Exchange exchange = virtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic"));
assertEquals("Incorrect default host", "test", defaultVirtualHost);
assertEquals("Incorrect virtualhost count", 1, virtualHostRegistry.getVirtualHosts().size());
assertEquals("Incorrect virtualhost name", "test", virtualHost.getName());
assertEquals("Incorrect exchange type", "topic", exchange.getType().getName().toString());
}
/**
* Test that configuration loads correctly when virtual hosts are specified in an external
* configuration file only, with two vhosts that have different properties.
* <p>
* Test for QPID-2361
*/
public void testExternalMultiVirtualhostXMLFile() throws Exception
{
// Write out vhosts
File vhostsFile = File.createTempFile(getClass().getName(), "vhosts-multi");
vhostsFile.deleteOnExit();
writeMultiVirtualHostsFile(vhostsFile);
// Write out config
File mainFile = File.createTempFile(getClass().getName(), "config");
mainFile.deleteOnExit();
writeConfigFile(mainFile, false, false, vhostsFile, null);
// Load config
ApplicationRegistry.remove();
ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
ApplicationRegistry.initialise(reg);
// Test config
VirtualHostRegistry virtualHostRegistry = reg.getVirtualHostRegistry();
assertEquals("Incorrect virtualhost count", 2, virtualHostRegistry.getVirtualHosts().size());
// test topic host
VirtualHost topicVirtualHost = virtualHostRegistry.getVirtualHost("topic");
Exchange topicExchange = topicVirtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.topic"));
assertEquals("Incorrect topic virtualhost name", "topic", topicVirtualHost.getName());
assertEquals("Incorrect topic exchange type", "topic", topicExchange.getType().getName().toString());
// Test fanout host
VirtualHost fanoutVirtualHost = virtualHostRegistry.getVirtualHost("fanout");
Exchange fanoutExchange = fanoutVirtualHost.getExchangeRegistry().getExchange(new AMQShortString("test.fanout"));
assertEquals("Incorrect fanout virtualhost name", "fanout", fanoutVirtualHost.getName());
assertEquals("Incorrect fanout exchange type", "fanout", fanoutExchange.getType().getName().toString());
}
/**
* Test that configuration does not load when virtual hosts are specified in both the main
* configuration file and an external file. Should throw a {@link ConfigurationException}.
* <p>
* Test for QPID-2361
*/
public void testInternalAndExternalVirtualhostXMLFile() throws Exception
{
// Write out vhosts
File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
vhostsFile.deleteOnExit();
writeVirtualHostsFile(vhostsFile, "test");
// Write out config
File mainFile = File.createTempFile(getClass().getName(), "config");
mainFile.deleteOnExit();
writeConfigFile(mainFile, false, true, vhostsFile, "test");
// Load config
try
{
ApplicationRegistry.remove();
ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
ApplicationRegistry.initialise(reg);
fail("Different virtualhost XML configurations not allowed");
}
catch (ConfigurationException ce)
{
assertEquals("Incorrect error message", "Only one of external or embedded virtualhosts configuration allowed.", ce.getMessage());
}
}
/**
* Test that configuration does not load when virtual hosts are specified in multiple external
* files. Should throw a {@link ConfigurationException}.
* <p>
* Test for QPID-2361
*/
public void testMultipleInternalVirtualhostXMLFile() throws Exception
{
// Write out vhosts
File vhostsFileOne = File.createTempFile(getClass().getName(), "vhosts-one");
vhostsFileOne.deleteOnExit();
writeVirtualHostsFile(vhostsFileOne, "one");
File vhostsFileTwo = File.createTempFile(getClass().getName(), "vhosts-two");
vhostsFileTwo.deleteOnExit();
writeVirtualHostsFile(vhostsFileTwo, "two");
// Write out config
File mainFile = File.createTempFile(getClass().getName(), "config");
mainFile.deleteOnExit();
writeMultipleVhostsConfigFile(mainFile, new File[] { vhostsFileOne, vhostsFileTwo });
// Load config
try
{
ApplicationRegistry.remove();
ApplicationRegistry reg = new ConfigurationFileApplicationRegistry(mainFile);
ApplicationRegistry.initialise(reg);
fail("Multiple virtualhost XML configurations not allowed");
}
catch (ConfigurationException ce)
{
assertEquals("Incorrect error message",
"Only one external virtualhosts configuration file allowed, multiple filenames found.",
ce.getMessage());
}
}
/**
* Test that configuration loads correctly when virtual hosts are specified in an external
* configuration file in the first of two configurations and embedded in the second. This
* will throe a {@link ConfigurationException} since the configurations have different
* types.
* <p>
* Test for QPID-2361
*/
public void testCombinedDifferentVirtualhostConfig() throws Exception
{
// Write out vhosts config
File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
vhostsFile.deleteOnExit();
writeVirtualHostsFile(vhostsFile, "external");
// Write out combined config file
File mainFile = File.createTempFile(getClass().getName(), "main");
File fileA = File.createTempFile(getClass().getName(), "a");
File fileB = File.createTempFile(getClass().getName(), "b");
mainFile.deleteOnExit();
fileA.deleteOnExit();
fileB.deleteOnExit();
writeCombinedConfigFile(mainFile, fileA, fileB);
writeConfigFile(fileA, false, false, vhostsFile, null);
writeConfigFile(fileB, false);
// Load config
try
{
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
fail("Different virtualhost XML configurations not allowed");
}
catch (ConfigurationException ce)
{
assertEquals("Incorrect error message", "Only one of external or embedded virtualhosts configuration allowed.", ce.getMessage());
}
}
/**
* Test that configuration loads correctly when virtual hosts are specified two overriding configurations
* each with an embedded virtualhost section. The first configuration section should be used.
* <p>
* Test for QPID-2361
*/
public void testCombinedConfigEmbeddedVirtualhost() throws Exception
{
// Write out combined config file
File mainFile = File.createTempFile(getClass().getName(), "main");
File fileA = File.createTempFile(getClass().getName(), "a");
File fileB = File.createTempFile(getClass().getName(), "b");
mainFile.deleteOnExit();
fileA.deleteOnExit();
fileB.deleteOnExit();
writeCombinedConfigFile(mainFile, fileA, fileB);
writeConfigFile(fileA, false, true, null, "a");
writeConfigFile(fileB, false, true, null, "b");
// Load config
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
// Test config
VirtualHostConfiguration virtualHost = config.getVirtualHostConfig("a");
assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
assertEquals("Incorrect virtualhost name", "a", virtualHost.getName());
}
/**
* Test that configuration loads correctly when virtual hosts are specified two overriding configurations
* each with an external virtualhost XML file. The first configuration file should be used.
* <p>
* Test for QPID-2361
*/
public void testCombinedConfigExternalVirtualhost() throws Exception
{
// Write out vhosts config
File vhostsOne = File.createTempFile(getClass().getName(), "vhosts-one");
vhostsOne.deleteOnExit();
writeVirtualHostsFile(vhostsOne, "one");
File vhostsTwo = File.createTempFile(getClass().getName(), "vhosts-two");
vhostsTwo.deleteOnExit();
writeVirtualHostsFile(vhostsTwo, "two");
// Write out combined config file
File mainFile = File.createTempFile(getClass().getName(), "main");
File fileA = File.createTempFile(getClass().getName(), "a");
File fileB = File.createTempFile(getClass().getName(), "b");
mainFile.deleteOnExit();
fileA.deleteOnExit();
fileB.deleteOnExit();
writeCombinedConfigFile(mainFile, fileA, fileB);
writeConfigFile(fileA, false, false, vhostsOne, null);
writeConfigFile(fileB, false, false, vhostsTwo, null);
// Load config
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
// Test config
VirtualHostConfiguration virtualHost = config.getVirtualHostConfig("one");
assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
assertEquals("Incorrect virtualhost name", "one", virtualHost.getName());
}
/**
* Test that configuration loads correctly when an overriding virtualhost configuration resets
* a property of an embedded virtualhost section. The overriding configuration property value
* should be used.
* <p>
* Test for QPID-2361
*/
public void testCombinedConfigEmbeddedVirtualhostOverride() throws Exception
{
// Write out combined config file
File mainFile = File.createTempFile(getClass().getName(), "main");
File fileA = File.createTempFile(getClass().getName(), "override");
File fileB = File.createTempFile(getClass().getName(), "config");
mainFile.deleteOnExit();
fileA.deleteOnExit();
fileB.deleteOnExit();
writeCombinedConfigFile(mainFile, fileA, fileB);
writeTestFishConfigFile(fileB);
// Write out overriding virtualhosts section
FileWriter out = new FileWriter(fileA);
out.write("<broker>\n");
out.write("<virtualhosts>\n");
out.write("\t<virtualhost>\n");
out.write("\t\t<test>\n");
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<durable>false</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write("\t\t</test>\n");
out.write("\t\t<fish>\n");
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<durable>true</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write("\t\t</fish>\n");
out.write("\t</virtualhost>\n");
out.write("</virtualhosts>\n");
out.write("</broker>\n");
out.close();
// Load config
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
// Test config
VirtualHostConfiguration testHost = config.getVirtualHostConfig("test");
ExchangeConfiguration testExchange = testHost.getExchangeConfiguration("test.topic");
VirtualHostConfiguration fishHost = config.getVirtualHostConfig("fish");
ExchangeConfiguration fishExchange = fishHost.getExchangeConfiguration("fish.topic");
assertEquals("Incorrect virtualhost count", 2, config.getVirtualHosts().length);
assertEquals("Incorrect virtualhost name", "test", testHost.getName());
assertFalse("Incorrect exchange durable property", testExchange.getDurable());
assertEquals("Incorrect virtualhost name", "fish", fishHost.getName());
assertTrue("Incorrect exchange durable property", fishExchange.getDurable());
}
/**
* Test that configuration loads correctly when the virtualhost configuration is a set of overriding
* configuration files that resets a property of a virtualhost. The opmost overriding configuration
* property value should be used.
* <p>
* Test for QPID-2361
*/
public void testCombinedVirtualhostOverride() throws Exception
{
// Write out combined config file
File mainFile = File.createTempFile(getClass().getName(), "main");
File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
File fileA = File.createTempFile(getClass().getName(), "vhosts-override");
File fileB = File.createTempFile(getClass().getName(), "vhosts-base");
mainFile.deleteOnExit();
vhostsFile.deleteOnExit();
fileA.deleteOnExit();
fileB.deleteOnExit();
writeConfigFile(mainFile, true, false, vhostsFile, null);
writeCombinedConfigFile(vhostsFile, fileA, fileB);
// Write out overriding virtualhosts sections
FileWriter out = new FileWriter(fileA);
out.write("<virtualhosts>\n");
out.write("\t<virtualhost>\n");
out.write("\t\t<test>\n");
out.write("\t\t\t<exchanges>\n");
out.write("\t\t\t\t<exchange>\n");
out.write("\t\t\t\t\t<durable>false</durable>\n");
out.write("\t\t\t\t</exchange>\n");
out.write("\t\tt</exchanges>\n");
out.write("\t\t</test>\n");
out.write("\t</virtualhost>\n");
out.write("</virtualhosts>\n");
out.close();
writeVirtualHostsFile(fileB, "test");
// Load config
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
// Test config
VirtualHostConfiguration testHost = config.getVirtualHostConfig("test");
ExchangeConfiguration testExchange = testHost.getExchangeConfiguration("test.topic");
assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
assertEquals("Incorrect virtualhost name", "test", testHost.getName());
assertFalse("Incorrect exchange durable property", testExchange.getDurable());
}
/**
* Test that configuration loads correctly when the virtualhost configuration is a set of overriding
* configuration files that define multiple virtualhosts, one per file. Only the virtualhosts defined in
* the topmost file should be used.
* <p>
* Test for QPID-2361
*/
public void testCombinedMultipleVirtualhosts() throws Exception
{
// Write out combined config file
File mainFile = File.createTempFile(getClass().getName(), "main");
File vhostsFile = File.createTempFile(getClass().getName(), "vhosts");
File fileA = File.createTempFile(getClass().getName(), "vhosts-one");
File fileB = File.createTempFile(getClass().getName(), "vhosts-two");
mainFile.deleteOnExit();
vhostsFile.deleteOnExit();
fileA.deleteOnExit();
fileB.deleteOnExit();
writeConfigFile(mainFile, true, false, vhostsFile, null);
writeCombinedConfigFile(vhostsFile, fileA, fileB);
// Write both virtualhosts definitions
writeVirtualHostsFile(fileA, "test-one");
writeVirtualHostsFile(fileB, "test-two");
// Load config
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
// Test config
VirtualHostConfiguration oneHost = config.getVirtualHostConfig("test-one");
assertEquals("Incorrect virtualhost count", 1, config.getVirtualHosts().length);
assertEquals("Incorrect virtualhost name", "test-one", oneHost.getName());
}
/**
* Test that a non-existant virtualhost file throws a {@link ConfigurationException}.
* <p>
* Test for QPID-2624
*/
public void testNonExistantVirtualhosts() throws Exception
{
// Write out combined config file
File mainFile = File.createTempFile(getClass().getName(), "main");
File vhostsFile = new File("doesnotexist");
mainFile.deleteOnExit();
writeConfigFile(mainFile, true, false, vhostsFile, null);
// Load config
try
{
ServerConfiguration config = new ServerConfiguration(mainFile.getAbsoluteFile());
config.initialise();
}
catch (ConfigurationException ce)
{
assertEquals("Virtualhosts file does not exist", ce.getMessage());
}
catch (Exception e)
{
fail("Should throw a ConfigurationException");
}
}
/*
* Tests that the old element security.jmx.access (that used to be used
* to define JMX access rights) is rejected.
*/
public void testManagementAccessRejected() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
// Check value we set
_config.setProperty("security.jmx.access(0)", "jmxremote.access");
_serverConfig = new ServerConfiguration(_config);
try
{
_serverConfig.initialise();
fail("Exception not thrown");
}
catch (ConfigurationException ce)
{
assertEquals("Incorrect error message",
"Validation error : security/jmx/access is no longer a supported element within the configuration xml.",
ce.getMessage());
}
}
/*
* Tests that the old element security.jmx.principal-database (that used to define the
* principal database used for JMX authentication) is rejected.
*/
public void testManagementPrincipalDatabaseRejected() throws ConfigurationException
{
// Check default
_serverConfig.initialise();
// Check value we set
_config.setProperty("security.jmx.principal-database(0)", "mydb");
_serverConfig = new ServerConfiguration(_config);
try
{
_serverConfig.initialise();
fail("Exception not thrown");
}
catch (ConfigurationException ce)
{
assertEquals("Incorrect error message",
"Validation error : security/jmx/principal-database is no longer a supported element within the configuration xml.",
ce.getMessage());
}
}
/*
* Tests that the old element security.principal-databases. ... (that used to define
* principal databases) is rejected.
*/
public void testPrincipalDatabasesRejected() throws ConfigurationException
{
_serverConfig.initialise();
// Check value we set
_config.setProperty("security.principal-databases.principal-database.class", "myclass");
_serverConfig = new ServerConfiguration(_config);
try
{
_serverConfig.initialise();
fail("Exception not thrown");
}
catch (ConfigurationException ce)
{
assertEquals("Incorrect error message",
"Validation error : security/principal-databases is no longer supported within the configuration xml.",
ce.getMessage());
}
}
}
|
3e16c5e88a57e3609ddf5895bea90bda8e0eda0d | 1,642 | java | Java | src/main/java/mmm/comercial/centro/pojo/Usuario.java | airamg/centrocomercial | f9adf75ae6d7cb8e3866f4b6b83c95a110e1212d | [
"MIT"
] | null | null | null | src/main/java/mmm/comercial/centro/pojo/Usuario.java | airamg/centrocomercial | f9adf75ae6d7cb8e3866f4b6b83c95a110e1212d | [
"MIT"
] | null | null | null | src/main/java/mmm/comercial/centro/pojo/Usuario.java | airamg/centrocomercial | f9adf75ae6d7cb8e3866f4b6b83c95a110e1212d | [
"MIT"
] | null | null | null | 16.257426 | 73 | 0.688794 | 9,715 | package mmm.comercial.centro.pojo;
import java.sql.Date;
import java.util.Calendar;
public class Usuario {
private int id;
private String user;
private String pass;
private String nombre;
private String apellidos;
private String ruta_imagen;
private Date hora_conexion;
private int online; // 1: conectado - 0: desconectado
private String role; // CLI - EMP
public Usuario() {
setUser("");
setPass("");
setNombre("");
setApellidos("");
setHora_conexion(new Date(Calendar.getInstance().getTime().getTime()));
setOnline(1);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user=user;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass=pass;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getRuta_imagen() {
return ruta_imagen;
}
public void setRuta_imagen(String ruta_imagen) {
this.ruta_imagen = ruta_imagen;
}
public Date getHora_conexion() {
return hora_conexion;
}
public void setHora_conexion(Date hora_conexion) {
this.hora_conexion = hora_conexion;
}
public int getOnline() {
return online;
}
public void setOnline(int online) {
this.online = online;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
3e16c6441c6f91d4cf4b02f801a56e37aea191e6 | 89 | java | Java | src/main/java/swt6/spring/persistence/ActionCallback.java | bloody-orange/SWT3-Spring | 96ca0631bd6bee8563a57a4d6cd062fb0cbc34a0 | [
"MIT"
] | null | null | null | src/main/java/swt6/spring/persistence/ActionCallback.java | bloody-orange/SWT3-Spring | 96ca0631bd6bee8563a57a4d6cd062fb0cbc34a0 | [
"MIT"
] | null | null | null | src/main/java/swt6/spring/persistence/ActionCallback.java | bloody-orange/SWT3-Spring | 96ca0631bd6bee8563a57a4d6cd062fb0cbc34a0 | [
"MIT"
] | null | null | null | 14.833333 | 33 | 0.764045 | 9,716 | package swt6.spring.persistence;
public interface ActionCallback {
void execute();
}
|
3e16c66a1cda8778104b7b2e1e2cb2d87ed55d1b | 3,695 | java | Java | ibas.accounting/src/main/java/org/colorcoding/ibas/accounting/bo/costiemjournal/ICostItemJournal.java | color-coding/ibas.accounting | 0b9b058f72c62adca49518aaa5752cfd99223187 | [
"Apache-2.0"
] | null | null | null | ibas.accounting/src/main/java/org/colorcoding/ibas/accounting/bo/costiemjournal/ICostItemJournal.java | color-coding/ibas.accounting | 0b9b058f72c62adca49518aaa5752cfd99223187 | [
"Apache-2.0"
] | 1 | 2020-11-13T06:42:32.000Z | 2020-11-13T06:42:32.000Z | ibas.accounting/src/main/java/org/colorcoding/ibas/accounting/bo/costiemjournal/ICostItemJournal.java | color-coding/ibas.accounting | 0b9b058f72c62adca49518aaa5752cfd99223187 | [
"Apache-2.0"
] | 18 | 2019-01-15T07:39:44.000Z | 2022-02-10T01:50:02.000Z | 11.404321 | 62 | 0.551827 | 9,717 | package org.colorcoding.ibas.accounting.bo.costiemjournal;
import java.math.BigDecimal;
import org.colorcoding.ibas.accounting.data.emJournalCategory;
import org.colorcoding.ibas.bobas.bo.IBOSimple;
import org.colorcoding.ibas.bobas.data.DateTime;
/**
* 费用项目-日记账 接口
*
*/
public interface ICostItemJournal extends IBOSimple {
/**
* 获取-对象编号
*
* @return 值
*/
Integer getObjectKey();
/**
* 设置-对象编号
*
* @param value 值
*/
void setObjectKey(Integer value);
/**
* 获取-对象类型
*
* @return 值
*/
String getObjectCode();
/**
* 设置-对象类型
*
* @param value 值
*/
void setObjectCode(String value);
/**
* 获取-创建日期
*
* @return 值
*/
DateTime getCreateDate();
/**
* 设置-创建日期
*
* @param value 值
*/
void setCreateDate(DateTime value);
/**
* 获取-创建时间
*
* @return 值
*/
Short getCreateTime();
/**
* 设置-创建时间
*
* @param value 值
*/
void setCreateTime(Short value);
/**
* 获取-修改日期
*
* @return 值
*/
DateTime getUpdateDate();
/**
* 设置-修改日期
*
* @param value 值
*/
void setUpdateDate(DateTime value);
/**
* 获取-修改时间
*
* @return 值
*/
Short getUpdateTime();
/**
* 设置-修改时间
*
* @param value 值
*/
void setUpdateTime(Short value);
/**
* 获取-实例号(版本)
*
* @return 值
*/
Integer getLogInst();
/**
* 设置-实例号(版本)
*
* @param value 值
*/
void setLogInst(Integer value);
/**
* 获取-服务系列
*
* @return 值
*/
Integer getSeries();
/**
* 设置-服务系列
*
* @param value 值
*/
void setSeries(Integer value);
/**
* 获取-数据源
*
* @return 值
*/
String getDataSource();
/**
* 设置-数据源
*
* @param value 值
*/
void setDataSource(String value);
/**
* 获取-创建用户
*
* @return 值
*/
Integer getCreateUserSign();
/**
* 设置-创建用户
*
* @param value 值
*/
void setCreateUserSign(Integer value);
/**
* 获取-修改用户
*
* @return 值
*/
Integer getUpdateUserSign();
/**
* 设置-修改用户
*
* @param value 值
*/
void setUpdateUserSign(Integer value);
/**
* 获取-创建动作标识
*
* @return 值
*/
String getCreateActionId();
/**
* 设置-创建动作标识
*
* @param value 值
*/
void setCreateActionId(String value);
/**
* 获取-更新动作标识
*
* @return 值
*/
String getUpdateActionId();
/**
* 设置-更新动作标识
*
* @param value 值
*/
void setUpdateActionId(String value);
/**
* 获取-费用结构
*
* @return 值
*/
Integer getStructure();
/**
* 设置-费用结构
*
* @param value 值
*/
void setStructure(Integer value);
/**
* 获取-费用节点
*
* @return 值
*/
Integer getStructureNode();
/**
* 设置-费用节点
*
* @param value 值
*/
void setStructureNode(Integer value);
/**
* 获取-项目
*
* @return 值
*/
String getItem();
/**
* 设置-项目
*
* @param value 值
*/
void setItem(String value);
/**
* 获取-金额
*
* @return 值
*/
BigDecimal getAmount();
/**
* 设置-金额
*
* @param value 值
*/
void setAmount(BigDecimal value);
/**
* 获取-货币
*
* @return 值
*/
String getCurrency();
/**
* 设置-货币
*
* @param value 值
*/
void setCurrency(String value);
/**
* 获取-类别
*
* @return 值
*/
emJournalCategory getCategory();
/**
* 设置-类别
*
* @param value 值
*/
void setCategory(emJournalCategory value);
/**
* 获取-基于类型
*
* @return 值
*/
String getBaseDocumentType();
/**
* 设置-基于类型
*
* @param value 值
*/
void setBaseDocumentType(String value);
/**
* 获取-基于标识
*
* @return 值
*/
Integer getBaseDocumentEntry();
/**
* 设置-基于标识
*
* @param value 值
*/
void setBaseDocumentEntry(Integer value);
/**
* 获取-基于行号
*
* @return 值
*/
Integer getBaseDocumentLineId();
/**
* 设置-基于行号
*
* @param value 值
*/
void setBaseDocumentLineId(Integer value);
}
|
3e16c8acf8e0479fef412cc024e06723b50bb473 | 1,503 | java | Java | src/main/java/util/KeyPress.java | saav/HubTurbo | 411b24d93fc4b48730bdad06ac9538e24b59a87a | [
"Apache-2.0"
] | null | null | null | src/main/java/util/KeyPress.java | saav/HubTurbo | 411b24d93fc4b48730bdad06ac9538e24b59a87a | [
"Apache-2.0"
] | null | null | null | src/main/java/util/KeyPress.java | saav/HubTurbo | 411b24d93fc4b48730bdad06ac9538e24b59a87a | [
"Apache-2.0"
] | null | null | null | 33.4 | 110 | 0.658017 | 9,718 | package util;
import javafx.scene.input.KeyCode;
public class KeyPress {
private static int keyPressSpeed = 1000; // time difference between keypresses in ms
private static long lastKeyEventTime = 0;
private static KeyCode lastKeyPressedCode;
public static boolean isDoublePress(KeyCode matchingKeyCode, KeyCode currentKeyCode) {
long keyEventTime = System.currentTimeMillis();
if ((keyEventTime - lastKeyEventTime) < keyPressSpeed
&& currentKeyCode.equals(lastKeyPressedCode)
&& currentKeyCode.equals(matchingKeyCode)) {
lastKeyPressedCode = null;
lastKeyEventTime = 0;
return true;
} else {
lastKeyPressedCode = currentKeyCode;
lastKeyEventTime = keyEventTime;
}
return false;
}
public static boolean isValidKeyCombination(KeyCode firstKeyPressed, KeyCode keyPressed) {
long keyEventTime = System.currentTimeMillis();
if ((keyEventTime - lastKeyEventTime) < keyPressSpeed && firstKeyPressed.equals(lastKeyPressedCode)) {
lastKeyPressedCode = null;
lastKeyEventTime = 0;
return true;
} else {
lastKeyPressedCode = keyPressed;
lastKeyEventTime = keyEventTime;
}
return false;
}
public static void setLastKeyPressedCodeAndTime(KeyCode code) {
lastKeyPressedCode = code;
lastKeyEventTime = System.currentTimeMillis();
}
}
|
3e16c8b702492fff65fb84907a983121ea498e9c | 736 | java | Java | src/ArrayListExample/ArrayListRunner.java | psk264/Practive-Java | 8fd1831ade1eb6de67be6737724ce6bfde364370 | [
"MIT"
] | null | null | null | src/ArrayListExample/ArrayListRunner.java | psk264/Practive-Java | 8fd1831ade1eb6de67be6737724ce6bfde364370 | [
"MIT"
] | null | null | null | src/ArrayListExample/ArrayListRunner.java | psk264/Practive-Java | 8fd1831ade1eb6de67be6737724ce6bfde364370 | [
"MIT"
] | null | null | null | 35.047619 | 71 | 0.690217 | 9,719 | package ArrayListExample;
public class ArrayListRunner {
public static void main(String[] args){
ArrayListGroceryList shopriteList = new ArrayListGroceryList();
shopriteList.addGroceryItem("Eggs");
shopriteList.addGroceryItem("Milk");
shopriteList.addGroceryItem("Flour");
shopriteList.addGroceryItem("Sugar");
shopriteList.printGroceryList();
shopriteList.removeGroceryItem("Eggs");
shopriteList.printGroceryList();
shopriteList.modifyGroceryItem(1, "Almond flour");
shopriteList.printGroceryList();
shopriteList.addGroceryItem("Almond milk");
shopriteList.removeGroceryItem(0); //
shopriteList.printGroceryList();
}
}
|
3e16c8cd6453aa7dade51104c9bb096ccaa66ed3 | 976 | java | Java | src/com/oanda/v20/trade/TradeGetResponse.java | ngqinzhe/forexTrading | 06b90edcd1027fc671ab913044fa464744cd4eeb | [
"MIT"
] | 37 | 2017-05-14T23:16:47.000Z | 2021-10-19T03:22:13.000Z | src/com/oanda/v20/trade/TradeGetResponse.java | ngqinzhe/forexTrading | 06b90edcd1027fc671ab913044fa464744cd4eeb | [
"MIT"
] | 14 | 2017-05-11T22:36:05.000Z | 2021-11-25T08:37:24.000Z | src/com/oanda/v20/trade/TradeGetResponse.java | ngqinzhe/forexTrading | 06b90edcd1027fc671ab913044fa464744cd4eeb | [
"MIT"
] | 18 | 2017-12-28T09:07:42.000Z | 2022-02-15T19:36:21.000Z | 20.333333 | 81 | 0.630123 | 9,720 | package com.oanda.v20.trade;
import com.google.gson.annotations.SerializedName;
import com.oanda.v20.transaction.TransactionID;
/**
* TradeGetResponse
*/
public class TradeGetResponse {
/**
* TradeGetResponse Constructor
* <p>
* Construct a new TradeGetResponse
*/
private TradeGetResponse() {
}
@SerializedName("trade") private Trade trade;
/**
* Get the trade
* <p>
* The Account's list of open Trades
* <p>
* @return the trade
* @see Trade
*/
public Trade getTrade() {
return this.trade;
}
@SerializedName("lastTransactionID") private TransactionID lastTransactionID;
/**
* Get the lastTransactionID
* <p>
* The ID of the most recent Transaction created for the Account
* <p>
* @return the lastTransactionID
* @see TransactionID
*/
public TransactionID getLastTransactionID() {
return this.lastTransactionID;
}
}
|
3e16c9aa02601429f9c4a981387de9ce327282fa | 3,104 | java | Java | gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/MemberMessenger.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 38 | 2016-01-04T01:31:40.000Z | 2020-04-07T06:35:36.000Z | gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/MemberMessenger.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 261 | 2016-01-07T09:14:26.000Z | 2019-12-05T10:15:56.000Z | gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/MemberMessenger.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 22 | 2016-03-09T05:47:09.000Z | 2020-04-02T17:55:30.000Z | 32 | 86 | 0.753866 | 9,721 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.management.internal;
import java.util.Set;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.internal.DistributionMessage;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.internal.LogWriterImpl;
import com.gemstone.gemfire.internal.admin.remote.AlertLevelChangeMessage;
/**
* This class will act as a messenger from manager to members for various
* operations.
*
* To start with its is designed to Manager start stop details, change alert
* level.
*
*
* @author rishim
*
*/
public class MemberMessenger {
private MBeanJMXAdapter jmxAdapter;
private ManagementResourceRepo repo;
private InternalDistributedSystem system;
public MemberMessenger(MBeanJMXAdapter jmxAdapter,
ManagementResourceRepo repo, InternalDistributedSystem system) {
this.jmxAdapter = jmxAdapter;
this.repo = repo;
this.system = system;
}
public void sendManagerInfo(DistributedMember receiver) {
String levelName = jmxAdapter.getAlertLevel();
int alertCode = LogWriterImpl.levelNameToCode(levelName);
ManagerStartupMessage msg = ManagerStartupMessage.create(alertCode);
msg.setRecipient((InternalDistributedMember) receiver);
sendAsync(msg);
}
public void broadcastManagerInfo() {
Set<DistributedMember> otherMemberSet = system.getDistributionManager()
.getAllOtherMembers();
String levelName = jmxAdapter.getAlertLevel();
int alertCode = LogWriterImpl.levelNameToCode(levelName);
ManagerStartupMessage msg = ManagerStartupMessage.create(alertCode);
if (otherMemberSet != null && otherMemberSet.size() > 0) {
msg.setRecipients(otherMemberSet);
}
sendAsync(msg);
}
/**
* Sends a message and does not wait for a response
*/
void sendAsync(DistributionMessage msg) {
if (system != null) {
system.getDistributionManager().putOutgoing(msg);
}
}
/**
* Sets the alert level for this manager agent. Sends a
* {@link AlertLevelChangeMessage} to each member of the distributed system.
*/
public void setAlertLevel(String levelName) {
int alertCode = LogWriterImpl.levelNameToCode(levelName);
AlertLevelChangeMessage m = AlertLevelChangeMessage.create(alertCode);
sendAsync(m);
}
}
|
3e16c9e861038124bef1ddcc0cfafc2dc28cb884 | 18,430 | java | Java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapperFieldModel.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapperFieldModel.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapperFieldModel.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 36.351085 | 125 | 0.669669 | 9,722 | /*
* Copyright 2011-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.datamodeling;
import static com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGenerateStrategy.ALWAYS;
import static com.amazonaws.services.dynamodbv2.datamodeling.StandardTypeConverters.Vector.LIST;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.BEGINS_WITH;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.BETWEEN;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.CONTAINS;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.EQ;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.GE;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.GT;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.IN;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.NULL;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.LE;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.LT;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.NE;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.NOT_CONTAINS;
import static com.amazonaws.services.dynamodbv2.model.ComparisonOperator.NOT_NULL;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Field model.
*
* @param <T> The object type.
* @param <V> The field model type.
*/
public class DynamoDBMapperFieldModel<T,V> implements DynamoDBAutoGenerator<V>, DynamoDBTypeConverter<AttributeValue,V> {
public static enum DynamoDBAttributeType { B, N, S, BS, NS, SS, BOOL, NULL, L, M; };
private final DynamoDBMapperFieldModel.Properties<V> properties;
private final DynamoDBTypeConverter<AttributeValue,V> converter;
private final DynamoDBAttributeType attributeType;
private final DynamoDBMapperFieldModel.Reflect<T,V> reflect;
/**
* Creates a new field model instance.
* @param builder The builder.
*/
private DynamoDBMapperFieldModel(final DynamoDBMapperFieldModel.Builder<T,V> builder) {
this.properties = builder.properties;
this.converter = builder.converter;
this.attributeType = builder.attributeType;
this.reflect = builder.reflect;
}
/**
* @deprecated replaced by {@link DynamoDBMapperFieldModel#name}
*/
@Deprecated
public String getDynamoDBAttributeName() {
return properties.attributeName();
}
/**
* @deprecated replaced by {@link DynamoDBMapperFieldModel#attributeType}
*/
@Deprecated
public DynamoDBAttributeType getDynamoDBAttributeType() {
return attributeType;
}
/**
* Gets the attribute name.
* @return The attribute name.
*/
public final String name() {
return properties.attributeName();
}
/**
* Gets the value from the object instance.
* @param object The object instance.
* @return The value.
*/
public final V get(final T object) {
return reflect.get(object);
}
/**
* Sets the value on the object instance.
* @param object The object instance.
* @param value The value.
*/
public final void set(final T object, final V value) {
reflect.set(object, value);
}
/**
* {@inheritDoc}
*/
@Override
public final DynamoDBAutoGenerateStrategy getGenerateStrategy() {
if (properties.autoGenerator() != null) {
return properties.autoGenerator().getGenerateStrategy();
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public final V generate(final V currentValue) {
return properties.autoGenerator().generate(currentValue);
}
/**
* {@inheritDoc}
*/
@Override
public final AttributeValue convert(final V object) {
return converter.convert(object);
}
/**
* {@inheritDoc}
*/
@Override
public final V unconvert(final AttributeValue object) {
return converter.unconvert(object);
}
/**
* Get the current value from the object and convert it.
* @param object The object instance.
* @return The converted value.
*/
public final AttributeValue getAndConvert(final T object) {
return convert(get(object));
}
/**
* Unconverts the value and sets it on the object.
* @param object The object instance.
* @param value The attribute value.
*/
public final void unconvertAndSet(final T object, final AttributeValue value) {
set(object, unconvert(value));
}
/**
* Gets the DynamoDB attribute type.
* @return The DynamoDB attribute type.
*/
public final DynamoDBAttributeType attributeType() {
return attributeType;
}
/**
* Gets the key type.
* @return The key type if a key field, null otherwise.
*/
public final KeyType keyType() {
return properties.keyType();
}
/**
* Indicates if this attribute is a version attribute.
* @return True if it is, false otherwise.
*/
public final boolean versioned() {
return properties.versioned();
}
/**
* Gets the global secondary indexes.
* @param keyType The key type.
* @return The list of global secondary indexes.
*/
public final List<String> globalSecondaryIndexNames(final KeyType keyType) {
if (properties.globalSecondaryIndexNames().containsKey(keyType)) {
return properties.globalSecondaryIndexNames().get(keyType);
}
return Collections.emptyList();
}
/**
* Gets the local secondary indexes.
* @return The list of local secondary indexes.
*/
public final List<String> localSecondaryIndexNames() {
return properties.localSecondaryIndexNames();
}
/**
* Returns true if the field has any indexes.
* @return True if the propery matches.
*/
public final boolean indexed() {
return !properties.globalSecondaryIndexNames().isEmpty() || !properties.localSecondaryIndexNames().isEmpty();
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#BEGINS_WITH
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition beginsWith(final V value) {
return new Condition().withComparisonOperator(BEGINS_WITH).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified values.
* @param lo The start of the range (inclusive).
* @param hi The end of the range (inclusive).
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#BETWEEN
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition between(final V lo, final V hi) {
return new Condition().withComparisonOperator(BETWEEN).withAttributeValueList(convert(lo), convert(hi));
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#CONTAINS
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition contains(final V value) {
return new Condition().withComparisonOperator(CONTAINS).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#EQ
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition eq(final V value) {
return new Condition().withComparisonOperator(EQ).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#GE
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition ge(final V value) {
return new Condition().withComparisonOperator(GE).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#GT
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition gt(final V value) {
return new Condition().withComparisonOperator(GT).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified values.
* @param values The values.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#IN
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition in(final Collection<V> values) {
return new Condition().withComparisonOperator(IN).withAttributeValueList(LIST.convert(values, this));
}
/**
* Creates a condition which filters on the specified values.
* @param values The values.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#IN
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition in(final V ... values) {
return in(Arrays.asList(values));
}
/**
* Creates a condition which filters on the specified value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#NULL
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition isNull() {
return new Condition().withComparisonOperator(NULL);
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#LE
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition le(final V value) {
return new Condition().withComparisonOperator(LE).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#LT
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition lt(final V value) {
return new Condition().withComparisonOperator(LT).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#NE
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition ne(final V value) {
return new Condition().withComparisonOperator(NE).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified value.
* @param value The value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#NOT_CONTAINS
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition notContains(final V value) {
return new Condition().withComparisonOperator(NOT_CONTAINS).withAttributeValueList(convert(value));
}
/**
* Creates a condition which filters on the specified value.
* @return The condition.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#NOT_NULL
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition notNull() {
return new Condition().withComparisonOperator(NOT_NULL);
}
/**
* Creates a condition which filters on any non-null argument; if {@code lo}
* is null a {@code LE} condition is applied on {@code hi}, if {@code hi}
* is null a {@code GE} condition is applied on {@code lo}.
* @param lo The start of the range (inclusive).
* @param hi The end of the range (inclusive).
* @return The condition or null if both arguments are null.
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#BETWEEN
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#EQ
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#GE
* @see com.amazonaws.services.dynamodbv2.model.ComparisonOperator#LE
* @see com.amazonaws.services.dynamodbv2.model.Condition
*/
public final Condition betweenAny(final V lo, final V hi) {
return lo == null ? (hi == null ? null : le(hi)) : (hi == null ? ge(lo) : (lo.equals(hi) ? eq(lo) : between(lo,hi)));
}
/**
* {@link DynamoDBMapperFieldModel} builder.
*/
static class Builder<T,V> {
private final DynamoDBMapperFieldModel.Properties<V> properties;
private DynamoDBTypeConverter<AttributeValue,V> converter;
private DynamoDBMapperFieldModel.Reflect<T,V> reflect;
private DynamoDBAttributeType attributeType;
private Class<T> targetType;
public Builder(Class<T> targetType, DynamoDBMapperFieldModel.Properties<V> properties) {
this.properties = properties;
this.targetType = targetType;
}
public final Builder<T,V> with(DynamoDBTypeConverter<AttributeValue,V> converter) {
this.converter = converter;
return this;
}
public final Builder<T,V> with(DynamoDBAttributeType attributeType) {
this.attributeType = attributeType;
return this;
}
public final Builder<T,V> with(DynamoDBMapperFieldModel.Reflect<T,V> reflect) {
this.reflect = reflect;
return this;
}
public final DynamoDBMapperFieldModel<T,V> build() {
final DynamoDBMapperFieldModel<T,V> result = new DynamoDBMapperFieldModel<T,V>(this);
if ((result.keyType() != null || result.indexed()) && !result.attributeType().name().matches("[BNS]")) {
throw new DynamoDBMappingException(String.format(
"%s[%s]; only scalar (B, N, or S) type allowed for key",
targetType.getSimpleName(), result.name()
));
} else if (result.keyType() != null && result.getGenerateStrategy() == ALWAYS) {
throw new DynamoDBMappingException(String.format(
"%s[%s]; auto-generated key and ALWAYS not allowed",
targetType.getSimpleName(), result.name()
));
}
return result;
}
}
/**
* The field model properties.
*/
static interface Properties<V> {
public String attributeName();
public KeyType keyType();
public boolean versioned();
public Map<KeyType,List<String>> globalSecondaryIndexNames();
public List<String> localSecondaryIndexNames();
public DynamoDBAutoGenerator<V> autoGenerator();
static final class Immutable<V> implements Properties<V> {
private final String attributeName;
private final KeyType keyType;
private final boolean versioned;
private final Map<KeyType,List<String>> globalSecondaryIndexNames;
private final List<String> localSecondaryIndexNames;
private final DynamoDBAutoGenerator<V> autoGenerator;
public Immutable(final Properties<V> properties) {
this.attributeName = properties.attributeName();
this.keyType = properties.keyType();
this.versioned = properties.versioned();
this.globalSecondaryIndexNames = properties.globalSecondaryIndexNames();
this.localSecondaryIndexNames = properties.localSecondaryIndexNames();
this.autoGenerator = properties.autoGenerator();
}
@Override
public final String attributeName() {
return this.attributeName;
}
@Override
public final KeyType keyType() {
return this.keyType;
}
@Override
public final boolean versioned() {
return this.versioned;
}
@Override
public final Map<KeyType,List<String>> globalSecondaryIndexNames() {
return this.globalSecondaryIndexNames;
}
@Override
public final List<String> localSecondaryIndexNames() {
return this.localSecondaryIndexNames;
}
@Override
public final DynamoDBAutoGenerator<V> autoGenerator() {
return this.autoGenerator;
}
}
}
/**
* Get/set reflection operations.
* @param <T> The object type.
* @param <V> The value type.
*/
static interface Reflect<T,V> {
public V get(T object);
public void set(T object, V value);
}
}
|
3e16cb77e21c8390d209d16258f0a7b44d6d8674 | 2,178 | java | Java | src/main/java/com/ua/sasha/bogush/springbootmicrocervices/model/node/Inherited.java | BogushAleksandr/springboot-microcervices | 55bb711aabc70bd7e83da73bb5e802c31e8ca9b2 | [
"Apache-2.0"
] | 3 | 2020-11-15T18:01:44.000Z | 2021-01-26T07:18:45.000Z | src/main/java/com/ua/sasha/bogush/springbootmicrocervices/model/node/Inherited.java | BogushAleksandr/springboot-microcervices | 55bb711aabc70bd7e83da73bb5e802c31e8ca9b2 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ua/sasha/bogush/springbootmicrocervices/model/node/Inherited.java | BogushAleksandr/springboot-microcervices | 55bb711aabc70bd7e83da73bb5e802c31e8ca9b2 | [
"Apache-2.0"
] | null | null | null | 22.926316 | 85 | 0.662994 | 9,723 |
package com.ua.sasha.bogush.springbootmicrocervices.model.node;
import com.fasterxml.jackson.annotation.*;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author Oleksandr Bogush
* @version 1.0
* @since 30.12.2020
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"authorityId",
"name",
"accessStatus"
})
public class Inherited implements Serializable {
@JsonProperty("authorityId")
private String authorityId;
@JsonProperty("name")
private String name;
@JsonProperty("accessStatus")
private String accessStatus;
@JsonIgnore
@Valid
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = -5459316907558494796L;
/**
* No args constructor for use in serialization
*/
public Inherited() {
}
/**
* @param authorityId
* @param name
* @param accessStatus
*/
public Inherited(String authorityId, String name, String accessStatus) {
super();
this.authorityId = authorityId;
this.name = name;
this.accessStatus = accessStatus;
}
@JsonProperty("authorityId")
public String getAuthorityId() {
return authorityId;
}
@JsonProperty("authorityId")
public void setAuthorityId(String authorityId) {
this.authorityId = authorityId;
}
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("accessStatus")
public String getAccessStatus() {
return accessStatus;
}
@JsonProperty("accessStatus")
public void setAccessStatus(String accessStatus) {
this.accessStatus = accessStatus;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
3e16cb94d95ac94ffd36b561db103aca2bd11bfa | 1,473 | java | Java | doc/openjdk/hotspot/test/compiler/intrinsics/mathexact/AddExactLNonConstantTest.java | renshuaibing-aaron/jdk1.8-source-analysis | 3233a942039cdf8af53689c072be2d49edfc3990 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | doc/openjdk/hotspot/test/compiler/intrinsics/mathexact/AddExactLNonConstantTest.java | renshuaibing-aaron/jdk1.8-source-analysis | 3233a942039cdf8af53689c072be2d49edfc3990 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | doc/openjdk/hotspot/test/compiler/intrinsics/mathexact/AddExactLNonConstantTest.java | renshuaibing-aaron/jdk1.8-source-analysis | 3233a942039cdf8af53689c072be2d49edfc3990 | [
"Apache-2.0"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | 38.763158 | 131 | 0.748812 | 9,724 | /*
* Copyright (c) 2013, 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.
*
* 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.
*/
/*
* @test
* @bug 8026844
* @summary Test non constant addExact
* @compile AddExactLNonConstantTest.java Verify.java
* @run main AddExactLNonConstantTest -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseMathExactIntrinsics
*
*/
public class AddExactLNonConstantTest {
public static void main(String[] args) {
Verify.NonConstantLongTest.verify(new Verify.AddExactL());
}
}
|
3e16cbd73db5d7a685707338caa12cd32f7a7a4c | 13,452 | java | Java | azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkInterfaceIPConfigurationInner.java | Flanker32/azure-libraries-for-java | dea658743df837f3f6f92bd79f5619ca41a4af80 | [
"MIT"
] | 100 | 2017-11-10T02:19:58.000Z | 2022-03-27T10:24:07.000Z | azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkInterfaceIPConfigurationInner.java | Flanker32/azure-libraries-for-java | dea658743df837f3f6f92bd79f5619ca41a4af80 | [
"MIT"
] | 657 | 2017-10-24T16:39:52.000Z | 2022-03-31T03:12:57.000Z | azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkInterfaceIPConfigurationInner.java | Flanker32/azure-libraries-for-java | dea658743df837f3f6f92bd79f5619ca41a4af80 | [
"MIT"
] | 122 | 2017-10-23T23:14:15.000Z | 2021-12-22T08:27:13.000Z | 34.670103 | 173 | 0.717588 | 9,725 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.implementation;
import java.util.List;
import com.microsoft.azure.management.network.ApplicationGatewayBackendAddressPool;
import com.microsoft.azure.management.network.IPAllocationMethod;
import com.microsoft.azure.management.network.IPVersion;
import com.microsoft.azure.management.network.ProvisioningState;
import com.microsoft.azure.management.network.NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.SubResource;
/**
* IPConfiguration in a network interface.
*/
@JsonFlatten
public class NetworkInterfaceIPConfigurationInner extends SubResource {
/**
* The reference to Virtual Network Taps.
*/
@JsonProperty(value = "properties.virtualNetworkTaps")
private List<VirtualNetworkTapInner> virtualNetworkTaps;
/**
* The reference to ApplicationGatewayBackendAddressPool resource.
*/
@JsonProperty(value = "properties.applicationGatewayBackendAddressPools")
private List<ApplicationGatewayBackendAddressPool> applicationGatewayBackendAddressPools;
/**
* The reference to LoadBalancerBackendAddressPool resource.
*/
@JsonProperty(value = "properties.loadBalancerBackendAddressPools")
private List<BackendAddressPoolInner> loadBalancerBackendAddressPools;
/**
* A list of references of LoadBalancerInboundNatRules.
*/
@JsonProperty(value = "properties.loadBalancerInboundNatRules")
private List<InboundNatRuleInner> loadBalancerInboundNatRules;
/**
* Private IP address of the IP configuration.
*/
@JsonProperty(value = "properties.privateIPAddress")
private String privateIPAddress;
/**
* The private IP address allocation method. Possible values include:
* 'Static', 'Dynamic'.
*/
@JsonProperty(value = "properties.privateIPAllocationMethod")
private IPAllocationMethod privateIPAllocationMethod;
/**
* Whether the specific IP configuration is IPv4 or IPv6. Default is IPv4.
* Possible values include: 'IPv4', 'IPv6'.
*/
@JsonProperty(value = "properties.privateIPAddressVersion")
private IPVersion privateIPAddressVersion;
/**
* Subnet bound to the IP configuration.
*/
@JsonProperty(value = "properties.subnet")
private SubnetInner subnet;
/**
* Whether this is a primary customer address on the network interface.
*/
@JsonProperty(value = "properties.primary")
private Boolean primary;
/**
* Public IP address bound to the IP configuration.
*/
@JsonProperty(value = "properties.publicIPAddress")
private PublicIPAddressInner publicIPAddress;
/**
* Application security groups in which the IP configuration is included.
*/
@JsonProperty(value = "properties.applicationSecurityGroups")
private List<ApplicationSecurityGroupInner> applicationSecurityGroups;
/**
* The provisioning state of the network interface IP configuration.
* Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*/
@JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/**
* PrivateLinkConnection properties for the network interface.
*/
@JsonProperty(value = "properties.privateLinkConnectionProperties", access = JsonProperty.Access.WRITE_ONLY)
private NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties privateLinkConnectionProperties;
/**
* The name of the resource that is unique within a resource group. This
* name can be used to access the resource.
*/
@JsonProperty(value = "name")
private String name;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
@JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
private String etag;
/**
* Get the reference to Virtual Network Taps.
*
* @return the virtualNetworkTaps value
*/
public List<VirtualNetworkTapInner> virtualNetworkTaps() {
return this.virtualNetworkTaps;
}
/**
* Set the reference to Virtual Network Taps.
*
* @param virtualNetworkTaps the virtualNetworkTaps value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withVirtualNetworkTaps(List<VirtualNetworkTapInner> virtualNetworkTaps) {
this.virtualNetworkTaps = virtualNetworkTaps;
return this;
}
/**
* Get the reference to ApplicationGatewayBackendAddressPool resource.
*
* @return the applicationGatewayBackendAddressPools value
*/
public List<ApplicationGatewayBackendAddressPool> applicationGatewayBackendAddressPools() {
return this.applicationGatewayBackendAddressPools;
}
/**
* Set the reference to ApplicationGatewayBackendAddressPool resource.
*
* @param applicationGatewayBackendAddressPools the applicationGatewayBackendAddressPools value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withApplicationGatewayBackendAddressPools(List<ApplicationGatewayBackendAddressPool> applicationGatewayBackendAddressPools) {
this.applicationGatewayBackendAddressPools = applicationGatewayBackendAddressPools;
return this;
}
/**
* Get the reference to LoadBalancerBackendAddressPool resource.
*
* @return the loadBalancerBackendAddressPools value
*/
public List<BackendAddressPoolInner> loadBalancerBackendAddressPools() {
return this.loadBalancerBackendAddressPools;
}
/**
* Set the reference to LoadBalancerBackendAddressPool resource.
*
* @param loadBalancerBackendAddressPools the loadBalancerBackendAddressPools value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withLoadBalancerBackendAddressPools(List<BackendAddressPoolInner> loadBalancerBackendAddressPools) {
this.loadBalancerBackendAddressPools = loadBalancerBackendAddressPools;
return this;
}
/**
* Get a list of references of LoadBalancerInboundNatRules.
*
* @return the loadBalancerInboundNatRules value
*/
public List<InboundNatRuleInner> loadBalancerInboundNatRules() {
return this.loadBalancerInboundNatRules;
}
/**
* Set a list of references of LoadBalancerInboundNatRules.
*
* @param loadBalancerInboundNatRules the loadBalancerInboundNatRules value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withLoadBalancerInboundNatRules(List<InboundNatRuleInner> loadBalancerInboundNatRules) {
this.loadBalancerInboundNatRules = loadBalancerInboundNatRules;
return this;
}
/**
* Get private IP address of the IP configuration.
*
* @return the privateIPAddress value
*/
public String privateIPAddress() {
return this.privateIPAddress;
}
/**
* Set private IP address of the IP configuration.
*
* @param privateIPAddress the privateIPAddress value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withPrivateIPAddress(String privateIPAddress) {
this.privateIPAddress = privateIPAddress;
return this;
}
/**
* Get the private IP address allocation method. Possible values include: 'Static', 'Dynamic'.
*
* @return the privateIPAllocationMethod value
*/
public IPAllocationMethod privateIPAllocationMethod() {
return this.privateIPAllocationMethod;
}
/**
* Set the private IP address allocation method. Possible values include: 'Static', 'Dynamic'.
*
* @param privateIPAllocationMethod the privateIPAllocationMethod value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withPrivateIPAllocationMethod(IPAllocationMethod privateIPAllocationMethod) {
this.privateIPAllocationMethod = privateIPAllocationMethod;
return this;
}
/**
* Get whether the specific IP configuration is IPv4 or IPv6. Default is IPv4. Possible values include: 'IPv4', 'IPv6'.
*
* @return the privateIPAddressVersion value
*/
public IPVersion privateIPAddressVersion() {
return this.privateIPAddressVersion;
}
/**
* Set whether the specific IP configuration is IPv4 or IPv6. Default is IPv4. Possible values include: 'IPv4', 'IPv6'.
*
* @param privateIPAddressVersion the privateIPAddressVersion value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withPrivateIPAddressVersion(IPVersion privateIPAddressVersion) {
this.privateIPAddressVersion = privateIPAddressVersion;
return this;
}
/**
* Get subnet bound to the IP configuration.
*
* @return the subnet value
*/
public SubnetInner subnet() {
return this.subnet;
}
/**
* Set subnet bound to the IP configuration.
*
* @param subnet the subnet value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withSubnet(SubnetInner subnet) {
this.subnet = subnet;
return this;
}
/**
* Get whether this is a primary customer address on the network interface.
*
* @return the primary value
*/
public Boolean primary() {
return this.primary;
}
/**
* Set whether this is a primary customer address on the network interface.
*
* @param primary the primary value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withPrimary(Boolean primary) {
this.primary = primary;
return this;
}
/**
* Get public IP address bound to the IP configuration.
*
* @return the publicIPAddress value
*/
public PublicIPAddressInner publicIPAddress() {
return this.publicIPAddress;
}
/**
* Set public IP address bound to the IP configuration.
*
* @param publicIPAddress the publicIPAddress value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withPublicIPAddress(PublicIPAddressInner publicIPAddress) {
this.publicIPAddress = publicIPAddress;
return this;
}
/**
* Get application security groups in which the IP configuration is included.
*
* @return the applicationSecurityGroups value
*/
public List<ApplicationSecurityGroupInner> applicationSecurityGroups() {
return this.applicationSecurityGroups;
}
/**
* Set application security groups in which the IP configuration is included.
*
* @param applicationSecurityGroups the applicationSecurityGroups value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withApplicationSecurityGroups(List<ApplicationSecurityGroupInner> applicationSecurityGroups) {
this.applicationSecurityGroups = applicationSecurityGroups;
return this;
}
/**
* Get the provisioning state of the network interface IP configuration. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*
* @return the provisioningState value
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get privateLinkConnection properties for the network interface.
*
* @return the privateLinkConnectionProperties value
*/
public NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties privateLinkConnectionProperties() {
return this.privateLinkConnectionProperties;
}
/**
* Get the name of the resource that is unique within a resource group. This name can be used to access the resource.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name of the resource that is unique within a resource group. This name can be used to access the resource.
*
* @param name the name value to set
* @return the NetworkInterfaceIPConfigurationInner object itself.
*/
public NetworkInterfaceIPConfigurationInner withName(String name) {
this.name = name;
return this;
}
/**
* Get a unique read-only string that changes whenever the resource is updated.
*
* @return the etag value
*/
public String etag() {
return this.etag;
}
}
|
3e16cc2625eed816c37ce1deb492a24e1bd0d1be | 1,940 | java | Java | universal-application-tool-0.0.1/app/services/question/types/DateQuestionDefinition.java | shanemc-goog/civiform | d2dde08157f25cb8d54e77851abfd38526144617 | [
"Apache-2.0"
] | 41 | 2021-03-13T18:23:18.000Z | 2022-03-25T22:36:07.000Z | universal-application-tool-0.0.1/app/services/question/types/DateQuestionDefinition.java | shanemc-goog/civiform | d2dde08157f25cb8d54e77851abfd38526144617 | [
"Apache-2.0"
] | 1,136 | 2021-03-12T00:54:19.000Z | 2022-03-31T23:54:14.000Z | universal-application-tool-0.0.1/app/services/question/types/DateQuestionDefinition.java | shanemc-goog/civiform | d2dde08157f25cb8d54e77851abfd38526144617 | [
"Apache-2.0"
] | 40 | 2021-03-13T15:18:12.000Z | 2022-03-06T19:09:14.000Z | 27.714286 | 92 | 0.723711 | 9,726 | package services.question.types;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.auto.value.AutoValue;
import java.util.Optional;
import java.util.OptionalLong;
import services.LocalizedStrings;
/** Defines a date question. */
public class DateQuestionDefinition extends QuestionDefinition {
public DateQuestionDefinition(
String name,
Optional<Long> enumeratorId,
String description,
LocalizedStrings questionText,
LocalizedStrings questionHelpText) {
super(
name,
enumeratorId,
description,
questionText,
questionHelpText,
DateValidationPredicates.create());
}
public DateQuestionDefinition(
OptionalLong id,
String name,
Optional<Long> enumeratorId,
String description,
LocalizedStrings questionText,
LocalizedStrings questionHelpText) {
super(
id,
name,
enumeratorId,
description,
questionText,
questionHelpText,
DateValidationPredicates.create());
}
@AutoValue
public abstract static class DateValidationPredicates extends ValidationPredicates {
public static DateQuestionDefinition.DateValidationPredicates parse(String jsonString) {
try {
return mapper.readValue(
jsonString, AutoValue_DateQuestionDefinition_DateValidationPredicates.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static DateQuestionDefinition.DateValidationPredicates create() {
return new AutoValue_DateQuestionDefinition_DateValidationPredicates();
}
}
public DateQuestionDefinition.DateValidationPredicates getDateValidationPredicates() {
return (DateQuestionDefinition.DateValidationPredicates) getValidationPredicates();
}
@Override
public QuestionType getQuestionType() {
return QuestionType.DATE;
}
}
|
3e16cf1899dab17c263f82e53599d5db508e1bc4 | 6,110 | java | Java | AndroidStudio project/app/src/main/java/com/firebase_esp8266_android_alarm_app/MyFirebaseMessagingService.java | fckaminski/door-open-monitor-app | 031ceb9c41eb274887b471c1eae21b8c2c51e219 | [
"MIT"
] | null | null | null | AndroidStudio project/app/src/main/java/com/firebase_esp8266_android_alarm_app/MyFirebaseMessagingService.java | fckaminski/door-open-monitor-app | 031ceb9c41eb274887b471c1eae21b8c2c51e219 | [
"MIT"
] | null | null | null | AndroidStudio project/app/src/main/java/com/firebase_esp8266_android_alarm_app/MyFirebaseMessagingService.java | fckaminski/door-open-monitor-app | 031ceb9c41eb274887b471c1eae21b8c2c51e219 | [
"MIT"
] | null | null | null | 50.916667 | 147 | 0.693126 | 9,727 | package com.firebase_esp8266_android_alarm_app;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/*
This class receives Firebase FCM messages when app is foreground
credits: https://www.androidauthority.com/android-push-notifications-with-firebase-cloud-messaging-925075/
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage message) {
super.onMessageReceived(message);
//Establish an intent, which is the action taken when the notification is clicked on. This intent simply bring app to front.
Intent intent = new Intent(this, MainActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID, notification_description, notification_title;
//Receives FCM notification text
String messageBody = "No mensage";
String messageTitle = "No title";
if (message.getNotification() != null) {
messageTitle = message.getNotification().getTitle();
messageBody = message.getNotification().getBody();
}
Log.d("service", "Body is: " + messageBody );
//Searches this app persistent variable value, used to save notification option, and updates the spinner
final SharedPreferences sp_preferences = this.getSharedPreferences("user_preferences", Context.MODE_PRIVATE );
int spinner_position = sp_preferences.getInt("notification",0);
Uri alarmSound;
//defines notification sound
if(messageBody.equals("Porta aberta por mais de 5 minutos!")) {
NOTIFICATION_CHANNEL_ID = "channel_id_long";
notification_title = "5 min notification";
notification_description = "Aviso de 5 minutos porta aberta";
alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.chime);
}
else if(spinner_position == 2) {
NOTIFICATION_CHANNEL_ID = "channel_id_siren";
notification_title = "Siren notification";
notification_description = "Porta aberta com sirene";
alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.siren);
}
else {
NOTIFICATION_CHANNEL_ID = "channel_id_default";
notification_title = "Default notification";
notification_description = "Porta aberta com toque padrão";
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
//Before you can deliver the notification on Android 8.0 (Oreo) and higher, you must register your app's notification channel:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
notification_title, NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription(notification_description);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.CYAN);
//notificationChannel.enableVibration(true); ==> does not play sound when enabled
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
AudioAttributes att = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
notificationChannel.setSound(alarmSound,att); //plays siren sound if checkbox is checked
//We use the same channel to avoid multiple notifications. If there's already a channel, it won't be updated
if (notificationManager != null)
notificationManager.createNotificationChannel(notificationChannel);
}
//Defines notification settings
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID)
.setLights(Color.CYAN, 300, 1000) //notification device LED color
.setSmallIcon(R.drawable.door)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.security_alarm)) //notification icon
.setVibrate(new long[]{0, 1000, 500, 1000}) //device vibration pattern
.setContentTitle(messageTitle) //notification title text
.setContentText(messageBody) //notification secondary text
.setPriority(notificationManager.IMPORTANCE_HIGH) //sets maximum priority
.setContentIntent(pendingIntent); //action taken when notification gets clicked on
;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
mBuilder.setSound(alarmSound);
//triggers notification
notificationManager.notify(0, mBuilder.build());
}
} |
3e16d1b1384ce2b94fa48e9d43daabf1f287264d | 5,131 | java | Java | remotecallback/remotecallback/src/androidTest/java/androidx/remotecallback/BasicReceiverTest.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 3,799 | 2020-07-23T21:58:59.000Z | 2022-03-31T17:07:19.000Z | remotecallback/remotecallback/src/androidTest/java/androidx/remotecallback/BasicReceiverTest.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 152 | 2020-07-24T00:19:02.000Z | 2022-03-31T00:57:54.000Z | remotecallback/remotecallback/src/androidTest/java/androidx/remotecallback/BasicReceiverTest.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 582 | 2020-07-24T00:16:54.000Z | 2022-03-30T23:32:45.000Z | 32.27044 | 99 | 0.661469 | 9,728 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.remotecallback;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class BasicReceiverTest {
private static Uri sUri;
private static String sStr;
private static int sInt;
private static Integer sNullableInt;
private static CountDownLatch sLatch;
private final Context mContext = ApplicationProvider.getApplicationContext();
@Test
public void testRemoteCallback() {
Uri aUri = new Uri.Builder().authority("mine").build();
String something = "something";
int i = 42;
RemoteCallback callback = new BroadcastReceiver().createRemoteCallback(
mContext).myCallbackMethod(aUri, something, i, null);
assertNotNull(callback);
assertEquals("myCallbackMethod", callback.getMethodName());
assertEquals(BroadcastReceiver.class.getName(), callback.getReceiverClass());
assertEquals(RemoteCallback.TYPE_RECEIVER, callback.getType());
}
@Test
public void testCreateStatic() throws PendingIntent.CanceledException, InterruptedException {
Uri aUri = new Uri.Builder().authority("mine").build();
String something = "something";
int i = 42;
sLatch = new CountDownLatch(1);
resetState();
RemoteCallback.create(BroadcastReceiver.class, mContext).myCallbackMethod(
aUri, something, i, null).toPendingIntent().send();
sLatch.await(2, TimeUnit.SECONDS);
assertState(0, aUri, something, i);
}
@Test
public void testCreateCallback() throws PendingIntent.CanceledException, InterruptedException {
Uri aUri = new Uri.Builder().authority("mine").build();
String something = "something";
int i = 42;
sLatch = new CountDownLatch(1);
resetState();
new BroadcastReceiver().createRemoteCallback(mContext).myCallbackMethod(
aUri, something, i, null).toPendingIntent().send();
sLatch.await(2, TimeUnit.SECONDS);
assertState(0, aUri, something, i);
}
@Test
public void testOverrideNull() throws PendingIntent.CanceledException, InterruptedException {
Uri aUri = new Uri.Builder().authority("mine").build();
String something = "something";
int i = 42;
resetState();
Intent intent = new Intent()
.putExtra("p3", 3);
new BroadcastReceiver().createRemoteCallback(mContext).myCallbackMethod(
aUri, something, i, null).toPendingIntent().send(mContext, 0, intent);
sLatch.await(2, TimeUnit.SECONDS);
assertState(0, aUri, something, i);
}
private void resetState() {
sLatch = new CountDownLatch(1);
sUri = null;
sStr = null;
sInt = -1;
sNullableInt = 15;
}
private void assertState(int count, Uri aUri, String something, int i) {
assertEquals(count, sLatch.getCount());
assertEquals(aUri, sUri);
assertEquals(something, sStr);
assertEquals(i, sInt);
assertNull(sNullableInt);
}
public static class BroadcastReceiver extends
BroadcastReceiverWithCallbacks<BroadcastReceiver> {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("BasicReceiverTest", "onReceive " + intent);
super.onReceive(context, intent);
}
@RemoteCallable
public RemoteCallback myCallbackMethod(Uri myUri, String myStr, int myInt,
Integer myNullableInt) {
Log.d("BasicReceiverTest",
"myCallbackMethod " + myUri + " " + myStr + " " + myInt + " " + myNullableInt,
new Throwable());
sUri = myUri;
sStr = myStr;
sInt = myInt;
sNullableInt = myNullableInt;
if (sLatch != null) sLatch.countDown();
return RemoteCallback.LOCAL;
}
}
}
|
3e16d25166156b2b1503e9ef28da97b8c71c28d2 | 2,840 | java | Java | src/main/java/com/fundynamic/d2tm/game/rendering/gui/topbar/Topbar.java | begumerkal/PROJEM24 | 49e7a7b39297a6da713d5070f54ba72e4597eeab | [
"MIT"
] | 47 | 2015-09-25T16:13:12.000Z | 2022-01-21T04:47:28.000Z | src/main/java/com/fundynamic/d2tm/game/rendering/gui/topbar/Topbar.java | begumerkal/PROJEM24 | 49e7a7b39297a6da713d5070f54ba72e4597eeab | [
"MIT"
] | 132 | 2015-09-08T06:10:33.000Z | 2020-07-10T07:47:53.000Z | src/main/java/com/fundynamic/d2tm/game/rendering/gui/topbar/Topbar.java | begumerkal/PROJEM24 | 49e7a7b39297a6da713d5070f54ba72e4597eeab | [
"MIT"
] | 20 | 2015-10-26T21:16:29.000Z | 2022-01-21T04:47:29.000Z | 31.910112 | 161 | 0.663028 | 9,729 | package com.fundynamic.d2tm.game.rendering.gui.topbar;
import com.fundynamic.d2tm.game.entities.Player;
import com.fundynamic.d2tm.game.rendering.gui.GuiElement;
import com.fundynamic.d2tm.math.Vector2D;
import com.fundynamic.d2tm.utils.Colors;
import com.fundynamic.d2tm.utils.SlickUtils;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
/**
* Topbar
*/
public class Topbar extends GuiElement {
private final Player player;
private final Image lightningImage;
public Topbar(int x, int y, int width, int height, Player player, Image lightningImage) {
super(x, y, width, height);
this.player = player;
this.lightningImage = lightningImage;
}
@Override
public void render(Graphics graphics) {
Vector2D topLeft = getTopLeft();
if (hasFocus) {
graphics.setColor(Color.blue);
} else {
graphics.setColor(Color.gray);
}
graphics.fillRect(topLeft.getXAsInt(), topLeft.getYAsInt(), getWidth(), getHeight());
SlickUtils.drawText(graphics, Color.white, "Resources", topLeft.getXAsInt(), topLeft.getYAsInt() + (getHeight() / 2) - 8);
String creditsString = String.format("$ %d", player.getAnimatedCredits());
SlickUtils.drawShadowedText(graphics, Color.white, creditsString, (topLeft.getXAsInt() + getWidth()) - 100, topLeft.getYAsInt() + (getHeight() / 2) - 8);
int producing = player.getTotalPowerProduced();
int consumption = player.getTotalPowerConsumption();
String powerString = String.format("%d > %d", consumption, producing);
Color statusColor = Color.white;
if (consumption > (producing - 25)) statusColor = Color.yellow;
if (consumption > producing) statusColor = Colors.RED_BRIGHT;
int startX = (topLeft.getXAsInt() + getWidth()) - 250;
lightningImage.draw(startX - 40, topLeft.getYAsInt() + (getHeight() / 2) - 14);
SlickUtils.drawShadowedText(graphics, statusColor, powerString, startX, topLeft.getYAsInt() + (getHeight() / 2) - 8);
}
@Override
public void leftClicked() {
// do nothing because Dummy element
}
@Override
public void rightClicked() {
// do nothing because Dummy element
}
@Override
public void draggedToCoordinates(Vector2D coordinates) {
// do nothing because Dummy element
}
@Override
public void movedTo(Vector2D coordinates) {
// do nothing because Dummy element
}
@Override
public void leftButtonReleased() {
// do nothing because Dummy element
}
@Override
public void update(float deltaInSeconds) {
// do nothing because Dummy element
}
@Override
public String toString() {
return "Topbar";
}
}
|
3e16d49d0598da713ea35ab41e9d0647d92d0c48 | 1,715 | java | Java | webapp/src/main/java/com/neu/pojo/UserDetails.java | JanhaviPuniani/cloud-computing-fall2018 | b5fa31f3d483a527f5d509db0020b32f5c0bdcce | [
"Apache-2.0"
] | 1 | 2019-08-12T02:19:42.000Z | 2019-08-12T02:19:42.000Z | webapp/src/main/java/com/neu/pojo/UserDetails.java | JhalakGupta/Transaction-Web-API | 201f5f9198f0fc214e8659c35817c78750254e42 | [
"Apache-2.0"
] | 1 | 2019-03-02T21:52:03.000Z | 2019-03-02T21:52:17.000Z | webapp/src/main/java/com/neu/pojo/UserDetails.java | JanhaviPuniani/cloud-computing-fall2018 | b5fa31f3d483a527f5d509db0020b32f5c0bdcce | [
"Apache-2.0"
] | null | null | null | 22.866667 | 93 | 0.672303 | 9,730 | package com.neu.pojo;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.domain.Persistable;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.List;
@Entity
@Table(name = "UserInfo")
@EntityListeners(AuditingEntityListener.class)
public class UserDetails implements Persistable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
@NotBlank
private String username;
@NotBlank
private String password;
@OneToMany(mappedBy = "userDetails", cascade = CascadeType.ALL)
private List<TransactionDetails> transactionDetailsList;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public List<TransactionDetails> getTransactionDetailsList() {
return transactionDetailsList;
}
public void setTransactionDetailsList(List<TransactionDetails> transactionDetailsList) {
this.transactionDetailsList = transactionDetailsList;
}
@Override
public Serializable getId() {
return userId;
}
@Override
public boolean isNew() {
return true;
}
}
|
3e16d50ff21a5765a9fbdca43113716ebc14f3c8 | 867 | java | Java | Mage.Sets/src/mage/cards/s/ScaledBehemoth.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/s/ScaledBehemoth.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/s/ScaledBehemoth.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 22.230769 | 80 | 0.677047 | 9,731 |
package mage.cards.s;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.keyword.HexproofAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
/**
*
* @author fireshoes
*/
public final class ScaledBehemoth extends CardImpl {
public ScaledBehemoth(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{G}{G}");
this.subtype.add(SubType.CROCODILE);
this.power = new MageInt(6);
this.toughness = new MageInt(7);
// Hexproof
this.addAbility(HexproofAbility.getInstance());
}
private ScaledBehemoth(final ScaledBehemoth card) {
super(card);
}
@Override
public ScaledBehemoth copy() {
return new ScaledBehemoth(this);
}
}
|
3e16d5461a4e169c0112d1c13c6728166f729c36 | 466 | java | Java | src/main/java/six/com/crawler/exception/AbstractHttpException.java | lvjk/excrawler | 118fdc691eac028ced1acfc9f3ebc65e65e96d7e | [
"Apache-2.0"
] | 1 | 2021-01-04T07:11:43.000Z | 2021-01-04T07:11:43.000Z | src/main/java/six/com/crawler/exception/AbstractHttpException.java | lvjk/excrawler | 118fdc691eac028ced1acfc9f3ebc65e65e96d7e | [
"Apache-2.0"
] | null | null | null | src/main/java/six/com/crawler/exception/AbstractHttpException.java | lvjk/excrawler | 118fdc691eac028ced1acfc9f3ebc65e65e96d7e | [
"Apache-2.0"
] | 3 | 2017-08-06T05:00:27.000Z | 2020-08-19T02:21:19.000Z | 18.6 | 68 | 0.683871 | 9,732 | package six.com.crawler.exception;
/**
* @author 作者
* @E-mail: efpyi@example.com
* @date 创建时间:2016年9月12日 下午12:59:25
*/
public class AbstractHttpException extends BaseException{
/**
*
*/
private static final long serialVersionUID = -200418828733119023L;
public AbstractHttpException(String message) {
super(message, null);
}
public AbstractHttpException(String message, Throwable cause) {
super(message, cause);
}
}
|
3e16d772f7b698467d219c45d58ba2604be098c9 | 501 | java | Java | _src/Chapter03/Example16/Example16.java | paullewallencom/java-978-1-8389-8669-8 | 8a4a47441b503452db00d031923a68f967e4ac55 | [
"Apache-2.0"
] | null | null | null | _src/Chapter03/Example16/Example16.java | paullewallencom/java-978-1-8389-8669-8 | 8a4a47441b503452db00d031923a68f967e4ac55 | [
"Apache-2.0"
] | null | null | null | _src/Chapter03/Example16/Example16.java | paullewallencom/java-978-1-8389-8669-8 | 8a4a47441b503452db00d031923a68f967e4ac55 | [
"Apache-2.0"
] | null | null | null | 22.772727 | 63 | 0.596806 | 9,733 | class Container {
// inner class
private class Continent {
public void print() {
System.out.println("This is an inner class");
}
}
// method to give access to the private inner class' method
void printContinent() {
Continent continent = new Continent();
continent.print();
}
}
class Example16 {
public static void main(String[] args) {
Container container = new Container();
container.printContinent();
}
}
|
3e16d82a6e1bbfa18bda4377bce94845c2ae6d93 | 1,765 | java | Java | com.sap.cloud.lm.sl.cf.database/src/main/java/com/sap/cloud/lm/sl/cf/database/migration/extractor/DataSourceEnvironmentExtractor.java | theghost5800/cf-mta-deploy-service | 274ef5bfbff23978df309352cb22ec1473e318b3 | [
"Apache-2.0"
] | null | null | null | com.sap.cloud.lm.sl.cf.database/src/main/java/com/sap/cloud/lm/sl/cf/database/migration/extractor/DataSourceEnvironmentExtractor.java | theghost5800/cf-mta-deploy-service | 274ef5bfbff23978df309352cb22ec1473e318b3 | [
"Apache-2.0"
] | null | null | null | com.sap.cloud.lm.sl.cf.database/src/main/java/com/sap/cloud/lm/sl/cf/database/migration/extractor/DataSourceEnvironmentExtractor.java | theghost5800/cf-mta-deploy-service | 274ef5bfbff23978df309352cb22ec1473e318b3 | [
"Apache-2.0"
] | 1 | 2020-03-20T07:17:03.000Z | 2020-03-20T07:17:03.000Z | 39.222222 | 103 | 0.771671 | 9,734 | package com.sap.cloud.lm.sl.cf.database.migration.extractor;
import javax.sql.DataSource;
import org.postgresql.ds.PGSimpleDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.pivotal.cfenv.core.CfCredentials;
import io.pivotal.cfenv.core.CfEnv;
import io.pivotal.cfenv.core.CfService;
public class DataSourceEnvironmentExtractor {
private final static Logger LOGGER = LoggerFactory.getLogger(DataSourceEnvironmentExtractor.class);
public DataSource extractDataSource(String serviceName) {
LOGGER.info("Extracting datasource for service {}...", serviceName );
CfCredentials databaseServiceCredentials = extractDatabaseServiceCredentials(serviceName);
return extractDataSource(databaseServiceCredentials);
}
private CfCredentials extractDatabaseServiceCredentials(String serviceName) {
CfEnv cfEnv = new CfEnv();
CfService sourceService = cfEnv.findServiceByName(serviceName);
return sourceService.getCredentials();
}
private PGSimpleDataSource extractDataSource(CfCredentials databaseServiceCredentials) {
PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setServerName(databaseServiceCredentials.getHost());
dataSource.setUser(databaseServiceCredentials.getUsername());
dataSource.setPassword(databaseServiceCredentials.getPassword());
dataSource.setDatabaseName(databaseServiceCredentials.getString("dbname"));
dataSource.setPortNumber(getPort(databaseServiceCredentials));
dataSource.setSsl(false);
return dataSource;
}
private int getPort(CfCredentials databaseServiceCredentials) {
return Integer.valueOf(databaseServiceCredentials.getPort());
}
}
|
3e16d8a4328eb77e76392312a575055355d586d1 | 4,643 | java | Java | core/src/main/java/com/bj58/argo/thirdparty/ClassUtil.java | allen0010910/Argo | 083e851e1ed4f29a6e228fb1506224cbca6687eb | [
"Apache-2.0"
] | 515 | 2015-01-12T06:17:01.000Z | 2022-01-13T07:57:59.000Z | core/src/main/java/com/bj58/argo/thirdparty/ClassUtil.java | allen0010910/Argo | 083e851e1ed4f29a6e228fb1506224cbca6687eb | [
"Apache-2.0"
] | 3 | 2017-05-12T08:29:08.000Z | 2017-08-25T03:11:06.000Z | core/src/main/java/com/bj58/argo/thirdparty/ClassUtil.java | allen0010910/Argo | 083e851e1ed4f29a6e228fb1506224cbca6687eb | [
"Apache-2.0"
] | 323 | 2015-01-08T08:08:09.000Z | 2021-11-23T03:12:18.000Z | 38.008197 | 98 | 0.683847 | 9,735 | /*
* Copyright Beijing 58 Information Technology Co.,Ltd.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.bj58.argo.thirdparty;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
*
* ClassUtil
*
* 扫描指定包(包括jar)下的class文件 <br>
*
* @author Service Platform Architecture Team (anpch@example.com)
*/
public class ClassUtil {
/**
* Return all interfaces that the given class implements as array,
* including ones implemented by superclasses.
* <p>If the class itself is an interface, it gets returned as sole interface.
* @param clazz the class to analyze for interfaces
* @return all interfaces that the given object implements as array
*/
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
return getAllInterfacesForClass(clazz, null);
}
/**
* Return all interfaces that the given class implements as array,
* including ones implemented by superclasses.
* <p>If the class itself is an interface, it gets returned as sole interface.
* @param clazz the class to analyze for interfaces
* @param classLoader the ClassLoader that the interfaces need to be visible in
* (may be <code>null</code> when accepting all declared interfaces)
* @return all interfaces that the given object implements as array
*/
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) {
Set<Class> ifcs = getAllInterfacesForClassAsSet(clazz, classLoader);
return ifcs.toArray(new Class[ifcs.size()]);
}
/**
* Return all interfaces that the given class implements as Set,
* including ones implemented by superclasses.
* <p>If the class itself is an interface, it gets returned as sole interface.
* @param clazz the class to analyze for interfaces
* @param classLoader the ClassLoader that the interfaces need to be visible in
* (may be <code>null</code> when accepting all declared interfaces)
* @return all interfaces that the given object implements as Set
*/
public static Set<Class> getAllInterfacesForClassAsSet(Class clazz, ClassLoader classLoader) {
Preconditions.checkNotNull(clazz, "Class must not be null");
if (clazz.isInterface() && isVisible(clazz, classLoader)) {
return Collections.singleton(clazz);
}
Set<Class> interfaces = new LinkedHashSet<Class>();
while (clazz != null) {
Class<?>[] ifcs = clazz.getInterfaces();
for (Class<?> ifc : ifcs) {
interfaces.addAll(getAllInterfacesForClassAsSet(ifc, classLoader));
}
clazz = clazz.getSuperclass();
}
return interfaces;
}
/**
* Check whether the given class is visible in the given ClassLoader.
* @param clazz the class to check (typically an interface)
* @param classLoader the ClassLoader to check against (may be <code>null</code>,
* in which case this method will always return <code>true</code>)
*/
public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
Class<?> actualClass = classLoader.loadClass(clazz.getName());
return (clazz == actualClass);
// Else: different interface class found...
}
catch (ClassNotFoundException ex) {
// No interface class found...
return false;
}
}
}
|
3e16d91988f6d4fa082678e6415d6ac1f8321e35 | 3,631 | java | Java | flutter-hms-health/android/src/main/java/com/huawei/hms/flutter/health/modules/settingcontroller/service/DefaultSettingControllerService.java | nestorsgarzonc/hms-flutter-plugin | 6af48a976d29659a8d7e0055a663af9f04802fc0 | [
"Apache-2.0"
] | 192 | 2020-05-24T00:47:03.000Z | 2022-03-26T13:36:08.000Z | flutter-hms-health/android/src/main/java/com/huawei/hms/flutter/health/modules/settingcontroller/service/DefaultSettingControllerService.java | nestorsgarzonc/hms-flutter-plugin | 6af48a976d29659a8d7e0055a663af9f04802fc0 | [
"Apache-2.0"
] | 145 | 2020-07-22T10:31:19.000Z | 2022-03-30T09:31:54.000Z | flutter-hms-health/android/src/main/java/com/huawei/hms/flutter/health/modules/settingcontroller/service/DefaultSettingControllerService.java | nestorsgarzonc/hms-flutter-plugin | 6af48a976d29659a8d7e0055a663af9f04802fc0 | [
"Apache-2.0"
] | 82 | 2020-07-20T07:30:16.000Z | 2022-03-28T07:04:03.000Z | 41.735632 | 120 | 0.72184 | 9,736 | /*
Copyright 2020-2021. Huawei Technologies Co., Ltd. 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
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.huawei.hms.flutter.health.modules.settingcontroller.service;
import com.huawei.hms.flutter.health.foundation.listener.ResultListener;
import com.huawei.hms.flutter.health.foundation.listener.VoidResultListener;
import com.huawei.hms.hihealth.SettingController;
import com.huawei.hms.hihealth.data.DataType;
import com.huawei.hms.hihealth.options.DataTypeAddOptions;
/**
* Blueprint of {@link DefaultSettingController}.
*
* @since v.5.0.5
*/
public interface DefaultSettingControllerService {
/**
* Creates and adds a customized data type.
* <p>
* The name of the created data type must be prefixed with the package name of the app. Otherwise, the creation
* fails.
*
* @param settingController {@link SettingController} instance.
* @param options {@link DataTypeAddOptions} instance that includes request options for creating the data
* type.
* @param resultListener {@link ResultListener} listener
*/
void addDataType(final SettingController settingController, final DataTypeAddOptions options,
final ResultListener<DataType> resultListener);
/**
* Disables the Health Kit function, cancels user authorization, and cancels all data records. (The task takes
* effect in 24 hours.)
*
* @param settingController {@link SettingController} instance.
* @param voidResultListener {@link VoidResultListener} listener.
*/
void disableHiHealth(final SettingController settingController, final VoidResultListener voidResultListener);
/**
* Reads the data type based on the data type name.
* <p>
* This method is used to read the customized data types of the app.
*
* @param settingController {@link SettingController} instance.
* @param dataTypeName Data type name.
* @param resultListener {@link ResultListener} listener.
*/
void readDataType(final SettingController settingController, final String dataTypeName,
final ResultListener<DataType> resultListener);
/**
* Checks the user privacy authorization to Health Kit.
* <p>
* If the authorization has not been granted, the user will be redirected to the authorization screen where they can
* authorize the Huawei Health app to open data to Health Kit.
*
* @param settingController {@link SettingController} instance.
* @param voidResultListener {@link VoidResultListener} listener.
*/
void checkHealthAppAuthorization(final SettingController settingController,
final VoidResultListener voidResultListener);
/**
* Checks the user privacy authorization to Health Kit.
*
* @param settingController {@link SettingController} instance.
* @param resultListener {@link ResultListener} listener.
*/
void getHealthAppAuthorization(final SettingController settingController,
final ResultListener<Boolean> resultListener);
}
|
3e16d9ec4b3dd0f561757484fd38f5a9105856d6 | 1,920 | java | Java | src/main/java/com/booleanworks/bomworkshop2015a/entity/oagi10/bom/v1/SequencedTextType.java | mlecabellec/bomworkshop2015a | 1301ebfa6b14c4995fc318d33a163d8b9edcb7f7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/booleanworks/bomworkshop2015a/entity/oagi10/bom/v1/SequencedTextType.java | mlecabellec/bomworkshop2015a | 1301ebfa6b14c4995fc318d33a163d8b9edcb7f7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/booleanworks/bomworkshop2015a/entity/oagi10/bom/v1/SequencedTextType.java | mlecabellec/bomworkshop2015a | 1301ebfa6b14c4995fc318d33a163d8b9edcb7f7 | [
"Apache-2.0"
] | null | null | null | 27.826087 | 117 | 0.675521 | 9,737 | //
// Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.11
// Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source.
// Généré le : 2015.10.16 à 03:51:42 PM CEST
//
package com.booleanworks.bomworkshop2015a.entity.oagi10.bom.v1;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java pour SequencedTextType complex type.
*
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
*
* <pre>
* <complexType name="SequencedTextType">
* <simpleContent>
* <extension base="<http://www.openapplications.org/oagis/10>TextType">
* <attribute name="sequenceNumber" type="{http://www.openapplications.org/oagis/10}NumberType_B98233" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SequencedTextType")
public class SequencedTextType
extends TextType
{
@XmlAttribute(name = "sequenceNumber")
protected BigInteger sequenceNumber;
/**
* Obtient la valeur de la propriété sequenceNumber.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getSequenceNumber() {
return sequenceNumber;
}
/**
* Définit la valeur de la propriété sequenceNumber.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setSequenceNumber(BigInteger value) {
this.sequenceNumber = value;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.