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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923b1fb1b461fccaffdc80bcbe22a2466d96782d | 314 | java | Java | restpg-backend/restpg-api/src/main/java/com/restpg/domain/hero/reactive/feature/CreateHero.java | diegocamara/restpg | 0a85d96e07dda5e1eaa18d102d2743041ce63e73 | [
"MIT"
] | null | null | null | restpg-backend/restpg-api/src/main/java/com/restpg/domain/hero/reactive/feature/CreateHero.java | diegocamara/restpg | 0a85d96e07dda5e1eaa18d102d2743041ce63e73 | [
"MIT"
] | 1 | 2022-03-02T09:36:15.000Z | 2022-03-02T09:36:15.000Z | restpg-backend/restpg-api/src/main/java/com/restpg/domain/hero/reactive/feature/CreateHero.java | diegocamara/restpg | 0a85d96e07dda5e1eaa18d102d2743041ce63e73 | [
"MIT"
] | null | null | null | 28.545455 | 64 | 0.805732 | 999,464 | package com.restpg.domain.hero.reactive.feature;
import com.restpg.domain.account.model.Account;
import com.rpg.model.character.NewHero;
import com.rpg.model.character.type.Hero;
import reactor.core.publisher.Mono;
public interface CreateHero {
Mono<Hero> handle(Mono<NewHero> newHeroMono, Account account);
}
|
923b202db6ecd17e380d2016ccc5958742a0a0f5 | 141 | java | Java | src/main/java/no/nav/veilarbdemo/domain/Hello.java | navikt/fo-veilarbdemo | 0287887664587a94da104d71ad4ce64d586d1cb5 | [
"MIT"
] | null | null | null | src/main/java/no/nav/veilarbdemo/domain/Hello.java | navikt/fo-veilarbdemo | 0287887664587a94da104d71ad4ce64d586d1cb5 | [
"MIT"
] | null | null | null | src/main/java/no/nav/veilarbdemo/domain/Hello.java | navikt/fo-veilarbdemo | 0287887664587a94da104d71ad4ce64d586d1cb5 | [
"MIT"
] | null | null | null | 14.1 | 34 | 0.624113 | 999,465 | package no.nav.veilarbdemo.domain;
public class Hello {
public Hello(String name) {
this.name = name;
}
String name;
}
|
923b2062d0d8a0bd3d9785c54fe666a476959b68 | 1,015 | java | Java | src/main/java/io/github/mirromutth/r2dbc/mysql/exception/AuthTypeNotSupportException.java | mp911de/r2dbc-mysql | a00351e9a2f54e2acc1c76cd6544a9ea28f7121d | [
"Apache-2.0"
] | 1 | 2019-03-06T22:21:12.000Z | 2019-03-06T22:21:12.000Z | src/main/java/io/github/mirromutth/r2dbc/mysql/exception/AuthTypeNotSupportException.java | mp911de/r2dbc-mysql | a00351e9a2f54e2acc1c76cd6544a9ea28f7121d | [
"Apache-2.0"
] | null | null | null | src/main/java/io/github/mirromutth/r2dbc/mysql/exception/AuthTypeNotSupportException.java | mp911de/r2dbc-mysql | a00351e9a2f54e2acc1c76cd6544a9ea28f7121d | [
"Apache-2.0"
] | null | null | null | 33.833333 | 82 | 0.737931 | 999,466 | /*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.mirromutth.r2dbc.mysql.exception;
import io.r2dbc.spi.R2dbcException;
/**
* Authentication plugin type (aka. name) is not support.
*/
public final class AuthTypeNotSupportException extends R2dbcException {
public AuthTypeNotSupportException(String nativeName, Throwable e) {
super("Authentication plugin type \"" + nativeName + "\" not support", e);
}
}
|
923b21b9950b2fd07cca6b744792463557d7a928 | 2,839 | java | Java | core/src/main/java/com/helicalinsight/datasource/QuickConnectionTest.java | RevRebel/helicalinsight | e5ffe5aa2626b2a60009def1f40053f3f7ee6f0d | [
"Apache-2.0"
] | 238 | 2016-12-08T06:15:56.000Z | 2022-03-10T10:17:10.000Z | core/src/main/java/com/helicalinsight/datasource/QuickConnectionTest.java | RevRebel/helicalinsight | e5ffe5aa2626b2a60009def1f40053f3f7ee6f0d | [
"Apache-2.0"
] | 15 | 2017-05-11T20:20:43.000Z | 2020-09-30T20:14:43.000Z | core/src/main/java/com/helicalinsight/datasource/QuickConnectionTest.java | RevRebel/helicalinsight | e5ffe5aa2626b2a60009def1f40053f3f7ee6f0d | [
"Apache-2.0"
] | 99 | 2017-05-17T17:38:32.000Z | 2022-03-17T06:56:56.000Z | 35.4875 | 105 | 0.684396 | 999,467 | /**
* Copyright (C) 2013-2019 Helical IT Solutions (http://www.helicalinsight.com) - All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helicalinsight.datasource;
import com.helicalinsight.efw.controllerutils.ControllerUtils;
import com.helicalinsight.efw.serviceframework.IService;
import com.helicalinsight.efw.serviceframework.ServiceUtils;
import com.helicalinsight.efw.utility.JsonUtils;
import net.sf.json.JSONObject;
import java.util.List;
/**
* Created by author on 25-08-2015.
*
* @author Somen
*/
@SuppressWarnings("unused")
public class QuickConnectionTest implements IService {
@Override
public String doService(String type, String serviceType, String service, String formData) {
JSONObject requestFormData = JSONObject.fromObject(formData);
DataSourceReader dataSourceReader = new DataSourceReader();
String result = dataSourceReader.doService(type, serviceType, "read", formData);
JSONObject readServiceResult = JSONObject.fromObject(result);
if (readServiceResult.getString("status").equals("0")) {
return result;
}
JSONObject dataJson = ControllerUtils.getDataFromResponse(readServiceResult);
JSONObject freshRequest = removeAtFromJsonKey(dataJson);
String classifier = requestFormData.optString("classifier");
String dir = requestFormData.optString("dir");
freshRequest.accumulate("classifier", classifier);
freshRequest.accumulate("dir", dir);
return ServiceUtils.executeService(type, serviceType, "test", freshRequest.toString());
}
private JSONObject removeAtFromJsonKey(JSONObject dataJson) {
List<String> jsonKeys = JsonUtils.getKeys(dataJson);
JSONObject duplicateJson = new JSONObject();
for (String key : jsonKeys) {
String tempKey;
String tempValue;
if (key.startsWith("@")) {
tempKey = key.replace("@", "");
} else {
tempKey = key;
}
tempValue = dataJson.getString(key);
duplicateJson.accumulate(tempKey, tempValue);
}
return duplicateJson;
}
@Override
public boolean isThreadSafeToCache() {
return true;
}
}
|
923b2393a93c15ca826838a5aecc05010abd0719 | 3,986 | java | Java | app/src/main/java/com/example/pio/CheckPostData.java | infiniteLoopers/PIO | 1198397e46929ebc82c1fe0b6c28763e19da4fc2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/pio/CheckPostData.java | infiniteLoopers/PIO | 1198397e46929ebc82c1fe0b6c28763e19da4fc2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/pio/CheckPostData.java | infiniteLoopers/PIO | 1198397e46929ebc82c1fe0b6c28763e19da4fc2 | [
"Apache-2.0"
] | null | null | null | 55.361111 | 89 | 0.778726 | 999,468 | package com.example.pio;
import com.google.android.gms.maps.model.LatLng;
public abstract class CheckPostData {
//starting point
protected static Double CHECK_POST_START_LAT =25.415617;
protected static Double CHECK_POST_START_LNG =68.258274;
protected static LatLng CHECK_POST_START = new LatLng(25.415617,68.258274);
protected static LatLng MAIN_GATE = new LatLng(25.408053, 68.265921);
protected static LatLng FOREIGN_FACULTY_HOTEL = new LatLng(25.407374, 68.264059);
protected static LatLng MOSQ_MUET = new LatLng(25.406282, 68.264663);
protected static LatLng DEPT_SW = new LatLng(25.404605, 68.261487);
protected static LatLng ADMIN_BLOCK_MUET = new LatLng(25.401615, 68.259773);
protected static LatLng HBL_ATM = new LatLng(25.401702, 68.259253);
protected static LatLng MUISTD = new LatLng(25.398582, 68.264003);
protected static LatLng DEPT_ENGR_TELE = new LatLng(25.407316, 68.26326);
protected static LatLng MUET_LIB_INFO = new LatLng(25.407878, 68.261653);
protected static LatLng MUET_STC = new LatLng(25.410291, 68.258191);
protected static LatLng MUET_TCR = new LatLng(25.413402, 68.258979);
protected static LatLng MUET_CRICKET_GROUND = new LatLng(25.416251, 68.257413);
protected static LatLng CHECK_POST_FACULTY_ROAD = new LatLng(25.401672,68.257442);
protected static LatLng CHECK_POST_FACULTY_ROAD_1 = new LatLng(25.401699,68.257332);
protected static LatLng CHECK_POST_FACULTY_ROAD_2 = new LatLng(25.403666,68.257575);
protected static LatLng CHECK_POST_FACULTY_ROAD_3 = new LatLng(25.404252,68.258275);
protected static LatLng CHECK_POST_FACULTY_ROAD_4 = new LatLng(25.405435,68.260756);
protected static LatLng CHECK_POST_FACULTY_ROAD_5 = new LatLng(25.404921,68.260813);
protected static LatLng CHECK_POST_FACULTY_ROAD_6 = new LatLng(25.40479,68.260746);
protected static LatLng CHECK_POST_FACULTY_ROAD_7 = new LatLng(25.404751,68.260893);
protected static LatLng CHECK_POST_FACULTY_ROAD_8 = new LatLng(25.404839,68.260939);
protected static LatLng CHECK_POST_FACULTY_ROAD_9 = new LatLng(25.404897,68.260834);
protected static LatLng CHECK_POST_FACULTY_ROAD_10 = new LatLng(25.405454,68.260815);
protected static LatLng CHECK_POST_FACULTY_ROAD_11 = new LatLng(25.405754,68.261387);
protected static LatLng CHECK_POST_FACULTY_ROAD_12 = new LatLng(25.406157,68.261883);
protected static LatLng CHECK_POST_FACULTY_ROAD_13 = new LatLng(25.406597,68.263811);
protected static LatLng CHECK_POST_FACULTY_ROAD_14 = new LatLng(25.40808,68.263696);
protected static LatLng CHECK_POST_FACULTY_ROAD_15 = new LatLng(25.40808,68.263696);
protected static LatLng CHECK_POST_FACULTY_ROAD_16 = new LatLng(25.408313,68.260802);
protected static LatLng CHECK_POST_FACULTY_ROAD_17 = new LatLng(25.408206,68.260574);
protected static LatLng CHECK_POST_FACULTY_ROAD_18 = new LatLng(25.408337,68.260401);
protected static LatLng CHECK_POST_FACULTY_ROAD_19 = new LatLng(25.408453,68.2596);
protected static LatLng CHECK_POST_FACULTY_ROAD_20 = new LatLng(25.408623,68.259135);
protected static LatLng CHECK_POST_FACULTY_ROAD_21 = new LatLng(25.408797,68.258935);
protected static LatLng CHECK_POST_FACULTY_ROAD_22 = new LatLng(25.401584,68.25751);
protected static LatLng CHECK_POST_FACULTY_ROAD_23 = new LatLng(25.401675,68.257439);
protected static LatLng CHECK_POST_END = new LatLng(25.401579,68.258577);
//software dpt address
protected static Double CHECK_POST_SW_LAT =25.4054;
protected static Double CHECK_POST_SW_LNG =68.260797;
protected static LatLng CHECK_POST_SW = new LatLng(25.4054,68.260797);
//biomedical dpt address
protected static Double CHECK_POST_BM_LAT = 25.40454;
protected static Double CHECK_POST_BM_LNG =68.260008;
//Enging point
protected static Double CHECK_POST_END_LAT = 25.401579;
protected static Double CHECK_POST_END_LNG =68.258577;
}
|
923b23b49777170862c262b1031ffce62497b23c | 3,442 | java | Java | msb_study/src/main/java/org/imzdong/study/msb/day_09_tank_net/net/TankMovingMsg.java | imzdong/study | a789f7534637a95949c3a0a202b8c04dbdfb7916 | [
"Apache-2.0"
] | null | null | null | msb_study/src/main/java/org/imzdong/study/msb/day_09_tank_net/net/TankMovingMsg.java | imzdong/study | a789f7534637a95949c3a0a202b8c04dbdfb7916 | [
"Apache-2.0"
] | 2 | 2020-01-18T12:48:47.000Z | 2020-01-18T12:49:22.000Z | msb_study/src/main/java/org/imzdong/study/msb/day_09_tank_net/net/TankMovingMsg.java | imzdong/study | a789f7534637a95949c3a0a202b8c04dbdfb7916 | [
"Apache-2.0"
] | null | null | null | 24.239437 | 76 | 0.54968 | 999,469 | package org.imzdong.study.msb.day_09_tank_net.net;
import org.imzdong.study.msb.day_09_tank_net.TankFrame;
import org.imzdong.study.msb.day_09_tank_net.model.Dir;
import org.imzdong.study.msb.day_09_tank_net.model.Group;
import org.imzdong.study.msb.day_09_tank_net.model.Tank;
import java.io.*;
import java.util.Objects;
import java.util.UUID;
public class TankMovingMsg extends Msg{
private int x,y;
private Dir dir;
private boolean moving;
private UUID uuid;
public TankMovingMsg(){}
public TankMovingMsg(Tank tank) {
this.x = tank.getX();
this.y = tank.getY();
this.dir = tank.getDir();
this.moving = tank.isMoving();
this.uuid = tank.getUuid();
}
public TankMovingMsg(int x, int y, Dir dir, boolean moving, UUID uuid) {
this.x = x;
this.y = y;
this.dir = dir;
this.moving = moving;
this.uuid = uuid;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Dir getDir() {
return dir;
}
public void setDir(Dir dir) {
this.dir = dir;
}
public boolean isMoving() {
return moving;
}
public void setMoving(boolean moving) {
this.moving = moving;
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
@Override
public byte[] toBytes() {
ByteArrayOutputStream bot = new ByteArrayOutputStream();
DataOutputStream dot = new DataOutputStream(bot);
try {
dot.writeInt(x);
dot.writeInt(y);
dot.writeInt(dir.ordinal());
dot.writeBoolean(moving);
dot.writeLong(uuid.getMostSignificantBits());
dot.writeLong(uuid.getLeastSignificantBits());
} catch (IOException e) {
e.printStackTrace();
}
return bot.toByteArray();
}
@Override
public MsgType getMsgType() {
return MsgType.TANK_MOVING;
}
@Override
public void handle() {
String msgUuid = this.getUuid().toString();
TankFrame instance = TankFrame.getInstance();
Tank myTank = instance.getTank();
String myUuid = myTank.getUuid().toString();
if(Objects.equals(myUuid, msgUuid)){
return;
}
Tank tank = instance.enemyList.get(msgUuid);
tank.setDir(this.dir);
tank.setMoving(this.moving);
tank.setX(this.x);
tank.setY(this.y);
}
@Override
public Msg parse(byte[] bytes) {
ByteArrayInputStream bit = new ByteArrayInputStream(bytes);
DataInputStream dit = new DataInputStream(bit);
try {
x = dit.readInt();
y = dit.readInt();
dir = Dir.values()[dit.readInt()];
moving = dit.readBoolean();
uuid = new UUID(dit.readLong(), dit.readLong());
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
@Override
public String toString() {
return "TankMsg{" +
"x=" + x +
", y=" + y +
", dir=" + dir +
", moving=" + moving +
", uuid=" + uuid +
'}';
}
}
|
923b24aa5cb58f96a35edf00eac5c41f428b8aaf | 15,348 | java | Java | api-rest-service/src/test/java/edu/mit/ll/em/api/test/endpoint/mediastream/MediaStreamServiceEndpointTest.java | NATO-NICS/em-api | e22ee13f0968c701fe06cc66bb69ca369bb74893 | [
"BSD-3-Clause"
] | null | null | null | api-rest-service/src/test/java/edu/mit/ll/em/api/test/endpoint/mediastream/MediaStreamServiceEndpointTest.java | NATO-NICS/em-api | e22ee13f0968c701fe06cc66bb69ca369bb74893 | [
"BSD-3-Clause"
] | null | null | null | api-rest-service/src/test/java/edu/mit/ll/em/api/test/endpoint/mediastream/MediaStreamServiceEndpointTest.java | NATO-NICS/em-api | e22ee13f0968c701fe06cc66bb69ca369bb74893 | [
"BSD-3-Clause"
] | 1 | 2022-03-19T17:29:09.000Z | 2022-03-19T17:29:09.000Z | 39.761658 | 110 | 0.602033 | 999,470 | /*
* Copyright (c) 2008-2021, Massachusetts Institute of Technology (MIT)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 edu.mit.ll.em.api.test.endpoint.mediastream;
import edu.mit.ll.em.api.rs.MediaStreamResponse;
import edu.mit.ll.em.api.test.base.EndpointTest;
import edu.mit.ll.em.api.test.dataprovider.MediaStreamServiceDataProvider;
import edu.mit.ll.nics.common.entity.MediaStream;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.*;
import java.util.List;
import static javax.ws.rs.core.Response.Status;
import static org.testng.Assert.*;
import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
// Recommended in docs for json validation, but doesn't seem to exist
//import static io.restassured.module.jsv.JsonSchemaValidator.*;
@Test
public class MediaStreamServiceEndpointTest extends EndpointTest {
/**
* Logger
*/
private static final Logger LOG = LoggerFactory.getLogger(MediaStreamServiceEndpointTest.class.getName());
//private Header header = null;
long stream1Id;
long stream2Id;
@BeforeTest
@Override
public void before() {
// Set the endpoint this test suite will be covering
setEndpoint("ws/{workspaceId}/mediastreams");
LOG.info("Using base endpoint: {}", getApiPath());
// TODO: clean up anything inserted by previous test run
// not really a nice way to do this, for now have to delete at end by way of testing the delete
// endpoint, and if there's a fail, have to reset manually
if(streamExists(MediaStreamServiceDataProvider.VALID_STREAM1_TITLE)) {
// TODO: delete it
LOG.info("Test stream is already in database");
}
if(streamExists(MediaStreamServiceDataProvider.VALID_STREAM1_TITLE2)) {
// TODO: delete it
LOG.info("Test stream2 is already in database");
}
}
//private void deleteStream(String title)
private boolean streamExists(String title) {
try {
MediaStreamResponse response = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
queryParam("title", MediaStreamServiceDataProvider.VALID_STREAM1_TITLE).
queryParam("streamurl", MediaStreamServiceDataProvider.VALID_STREAM1_URL).
when().
get(String.format("%s/{title}/{streamurl}", getApiPath())).
then().
contentType(ContentType.JSON).
statusCode(Status.OK.getStatusCode()).
extract().
as(MediaStreamResponse.class);
if(response.getStreams().size() > 0) {
return true;
}
} catch(Exception e) {
return false;
}
return false;
}
@Test(testName = "testGet", description = "Attempts to streams",
groups = {"read"}, dependsOnGroups = {"connectivity", "write"},
dataProvider = "validMediaStreamProvider",
dataProviderClass = MediaStreamServiceDataProvider.class)
public void testGet(MediaStream stream) {
String url = getApiPath();
LOG.info("Using URL: GET {}", url);
Response response = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
when().
get(url).
then().
contentType(ContentType.JSON).
statusCode(Status.OK.getStatusCode()).
// Expect the json to have a message value of Success
body("message", equalTo("OK"))
.extract().response();
LOG.info("Response: {}", response.asString());
// TODO: process result and verify result stream
}
@Test(testName = "testFindByTitle", description = "Search streams",
groups = {"read"}, dependsOnGroups = {"connectivity", "write"})
public void testFind() {
String url = getApiPath();
MediaStreamResponse response = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
queryParam("title", MediaStreamServiceDataProvider.VALID_STREAM1_TITLE).
when().
get(url).
then().
contentType(ContentType.JSON).
statusCode(Status.OK.getStatusCode()).
//body("message", equalTo("OK")).
extract().
as(MediaStreamResponse.class);
//.response();
LOG.info("Got stream count: {}", response.getStreams().size());
List<MediaStream> streams = (List<MediaStream>) response.getStreams();
stream1Id = streams.get(0).getMsid();
// TODO: assert stream.get(0).getTitle().equals(VALID_STREAM1_TITLE)
assertEquals(streams.size(), 1);
assertEquals(streams.get(0).getTitle(), MediaStreamServiceDataProvider.VALID_STREAM1_TITLE);
// TODO: process result and verify result stream
// can also use "streams[0]" to get the first item?
//List<JsonObject> jsonStreams = response.jsonPath().getList("streams");
//LOG.info("Got stream?: {}", jsonStreams.toString());
/*Gson gson = new GsonBuilder().create();
HashMap<String, Object> stream = gson.fromJson(jsonStreams.get(0), HashMap<String, Object>.class);
LOG.info("GOT stream with title: {}", stream.getTitle());*/
// TODO: use JsonPath to extract response mediastream.streams
//List<MediaStream> results = gson.fromJson(response.as)
//LOG.info("Response {}", response.asString());
MediaStreamResponse responseBoth = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
queryParam("title", MediaStreamServiceDataProvider.VALID_STREAM1_TITLE).
queryParam("url", MediaStreamServiceDataProvider.VALID_STREAM1_URL).
when().
get(url).
then().
contentType(ContentType.JSON).
statusCode(Status.OK.getStatusCode()).
extract().
as(MediaStreamResponse.class);
List<MediaStream> bothStreams = (List<MediaStream>) responseBoth.getStreams();
assertEquals(bothStreams.size(), 1);
MediaStreamResponse responseFail = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
queryParam("title", "notitle").
queryParam("url", MediaStreamServiceDataProvider.VALID_STREAM1_URL).
when().
get(url).
then().
contentType(ContentType.JSON).
statusCode(Status.OK.getStatusCode()).
extract().
as(MediaStreamResponse.class);
LOG.info("Got response: {}", responseFail.toString());
List<MediaStream> failStreams = (List<MediaStream>) responseFail.getStreams();
assertEquals(failStreams.size(), 0); // Should be no results... maybe API should send 404
}
@Test(testName = "testPost", description = "Attempts to post a valid stream",
groups = {"write"}, dependsOnGroups = {"connectivity"},
dataProvider = "validMediaStreamProvider",
dataProviderClass = MediaStreamServiceDataProvider.class)
public void testPost(MediaStream stream) {
String url = getApiPath();
LOG.info("Using endpoint: {}", url);
MediaStreamResponse response = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
body(stream).
when().
post(url).
then().
//contentType(ContentType.JSON).
// Trouble with this status code line is it throws the fail exception w/o being able to read
// the rest out? Possibly wrap in try/catch and see if we can get a full response to help
// with reporting/debugging?
statusCode(Status.OK.getStatusCode()).
// Expect the json to have a message value of Success
body("message", equalTo("Success"))
.extract().as(MediaStreamResponse.class);
MediaStream postedStream = ((List<MediaStream>) response.getStreams()).get(0);
stream1Id = postedStream.getMsid();
assertTrue(stream1Id > 0);
// Can check Response for specific things, or parse response json body, etc
//String responseString = response.asString();
//LOG.info("Response: " + responseString);
}
@Test(testName = "testPostDuplicate", description = "Attempts to post a duplicate",
groups = {"write"}, dependsOnGroups = {"connectivity"},
dataProvider = "validMediaStreamProvider",
dataProviderClass = MediaStreamServiceDataProvider.class)
public void testPostDuplicate(MediaStream stream) {
String url = getApiPath();
LOG.info("Using endpoint: {}", url);
Response response = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
body(stream).
when().
post(url).
then().
contentType(ContentType.JSON).
// Expecting error
statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).
// Expect duplicate message content
body("message", containsString("already exists")).
extract().response();
}
@Test(testName = "testPost2", description = "Attempts to post a valid second stream",
groups = {"write"}, dependsOnGroups = {"connectivity"},
dataProvider = "validMediaStreamProvider2",
dataProviderClass = MediaStreamServiceDataProvider.class)
public void testPost2(MediaStream stream) {
String url = getApiPath();
LOG.info("Using endpoint: {}", url);
MediaStreamResponse response = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
body(stream).
when().
post(url).
then().
contentType(ContentType.JSON).
statusCode(Status.OK.getStatusCode()).
// Expect the json to have a message value of Success
body("message", equalTo("Success"))
.extract().as(MediaStreamResponse.class);
MediaStream resultStream = ((List<MediaStream>) response.getStreams()).get(0);
stream2Id = resultStream.getMsid();
assertTrue(stream2Id > 0);
}
// TODO: test get of title, should get 1 result
// TODO: test get of title+url
// TODO: test get of url
@Test(testName = "testUpdate", description = "Tests updating values on a stream",
groups = {"update"}, dependsOnGroups = {"connectivity", "write", "read"},
dataProvider = "validMediaStreamProvider2",
dataProviderClass = MediaStreamServiceDataProvider.class)
private void testUpdate(MediaStream stream) {
stream.setMsid(stream1Id);
stream.setTitle("Stream 1 Renamed");
MediaStreamResponse response = given().
header(getKeycloakHeader()).
contentType(ContentType.JSON).
pathParam("workspaceId", 1).
pathParam("streamId", stream1Id).
body(stream).
when().
put(String.format("%s/{streamId}", getApiPath())).
then().
statusCode(Status.OK.getStatusCode()).
extract().as(MediaStreamResponse.class);
MediaStream updatedStream = ((List<MediaStream>) response.getStreams()).get(0);
assertEquals(updatedStream.getTitle(), stream.getTitle());
}
@Test(testName = "testDelete1", description = "Attempts to delete stream1",
groups = {"delete"}, dependsOnGroups = {"connectivity", "write", "read", "update"})
private void testDelete() {
Response response = given().
header(getKeycloakHeader()).
pathParam("workspaceId", 1).
pathParam("streamId", stream1Id).
when().
delete(String.format("%s/{streamId}", getApiPath())).
then().
statusCode(Status.OK.getStatusCode()).
extract().response();
LOG.info("Delete stream 1 response: {}", response.asString());
Response response2 = given().
header(getKeycloakHeader()).
pathParam("workspaceId", 1).
pathParam("streamId", stream2Id).
when().
delete(String.format("%s/{streamId}", getApiPath())).
then().
statusCode(Status.OK.getStatusCode()).
extract().response();
LOG.info("Delete stream 2 response: {}", response.asString());
}
}
|
923b268afb5358fdea20a4935290aa239def355c | 2,206 | java | Java | src/stringalgorithms/LongestPalindromeSubStringSubSequence.java | tanmayghosh2507/LeetCode_Problems | 35e9221b1a18f650611a5d390909dbea6e69de23 | [
"MIT"
] | null | null | null | src/stringalgorithms/LongestPalindromeSubStringSubSequence.java | tanmayghosh2507/LeetCode_Problems | 35e9221b1a18f650611a5d390909dbea6e69de23 | [
"MIT"
] | null | null | null | src/stringalgorithms/LongestPalindromeSubStringSubSequence.java | tanmayghosh2507/LeetCode_Problems | 35e9221b1a18f650611a5d390909dbea6e69de23 | [
"MIT"
] | null | null | null | 27.234568 | 113 | 0.577516 | 999,471 | package stringalgorithms;
public class LongestPalindromeSubStringSubSequence {
public static void main(String[] args) {
String str = "bbbab";
LongestPalindromeSubStringSubSequence longestPalindromeSubString = new LongestPalindromeSubStringSubSequence();
System.out.println(longestPalindromeSubString.longestPalindromeSubString(str));
}
public String longestPalindromeSubString(String str) {
Boolean dp[][] = new Boolean[str.length()][str.length()];
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < str.length(); j++) {
dp[i][j] = false;
}
}
int maxLength = 1;
int startIndex = 0;
// All single characters are palindrome
for (int i = 0; i < str.length(); i++) {
dp[i][i] = true;
}
// All length 2 substrings
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == str.charAt(i + 1)) {
dp[i][i + 1] = true;
startIndex = i;
maxLength = 2;
}
}
for (int len = 3; len <= str.length(); len++) { // len: length of substring
for (int start = 0; start < str.length() - len + 1; start++) {
int end = start + len - 1; // j:end index
if (dp[start + 1][end - 1] && str.charAt(start) == str.charAt(end)) {
dp[start][end] = true;
if (len > maxLength) {
startIndex = start;
maxLength = len;
}
}
}
}
return str.substring(startIndex, startIndex + maxLength);
}
public int longestPalindromeSubSequence(String str) {
int dp[][] = new int[str.length()][str.length()];
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < str.length(); j++) {
dp[i][j] = 0;
}
}
// All single characters are palindrome
for (int i = 0; i < str.length(); i++) {
dp[i][i] = 1;
}
for (int len = 2; len <= str.length(); len++) { // len: length of substring
for (int start = 0; start < str.length() - len + 1; start++) {
int end = start + len - 1;
if (str.charAt(start) == str.charAt(end) && len == 2)
dp[start][end] = 2;
else if (str.charAt(start) == str.charAt(end))
dp[start][end] = dp[start + 1][end - 1] + 2;
else
dp[start][end] = Math.max(dp[start + 1][end], dp[start][end - 1]);
}
}
return dp[0][str.length() - 1];
}
}
|
923b26df5f52cf79deca36f99f0c0323dd921f8e | 412 | java | Java | src/main/java/com/example/demo/domain/Customer.java | M0squ3ra/database-web-app | 59201f0bfe27cfe754dca896e125833528da7980 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/domain/Customer.java | M0squ3ra/database-web-app | 59201f0bfe27cfe754dca896e125833528da7980 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/domain/Customer.java | M0squ3ra/database-web-app | 59201f0bfe27cfe754dca896e125833528da7980 | [
"MIT"
] | null | null | null | 18.727273 | 55 | 0.76699 | 999,472 | package com.example.demo.domain;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String firstName;
private String lastName;
private String email;
}
|
923b271c493b372f989a011803aa04a2504d41bb | 879 | java | Java | src/kr/dogfoot/hwplib/reader/bodytext/paragraph/ForParaCharShape.java | ictechgy/Excel-to-HWP-Converter | 32bce0c24ce224a5e0985aa6282f54f7461935af | [
"Apache-2.0"
] | 329 | 2016-12-23T04:15:13.000Z | 2022-03-28T06:03:48.000Z | src/kr/dogfoot/hwplib/reader/bodytext/paragraph/ForParaCharShape.java | ictechgy/Excel-to-HWP-Converter | 32bce0c24ce224a5e0985aa6282f54f7461935af | [
"Apache-2.0"
] | 167 | 2017-03-16T12:39:57.000Z | 2022-03-19T15:45:58.000Z | src/kr/dogfoot/hwplib/reader/bodytext/paragraph/ForParaCharShape.java | ictechgy/Excel-to-HWP-Converter | 32bce0c24ce224a5e0985aa6282f54f7461935af | [
"Apache-2.0"
] | 113 | 2016-12-23T04:16:32.000Z | 2022-03-30T02:32:08.000Z | 25.852941 | 77 | 0.639363 | 999,473 | package kr.dogfoot.hwplib.reader.bodytext.paragraph;
import kr.dogfoot.hwplib.object.bodytext.paragraph.Paragraph;
import kr.dogfoot.hwplib.util.compoundFile.reader.StreamReader;
import java.io.IOException;
/**
* 문단의 글자 모양 레코드를 읽기 위한 객체
*
* @author neolord
*/
public class ForParaCharShape {
/**
* 문단의 글자 모양 레코드를 읽는다.
*
* @param paragraph 문단 객체
* @param sr 스트림 리더
* @throws IOException
*/
public static void read(Paragraph paragraph, StreamReader sr)
throws IOException {
paragraph.createCharShape();
int count = paragraph.getHeader().getCharShapeCount();
for (int index = 0; index < count; index++) {
long position = sr.readUInt4();
long charShapeId = sr.readUInt4();
paragraph.getCharShape().addParaCharShape(position, charShapeId);
}
}
}
|
923b271ec1ed0cb24fa2b4c98dbb8d17bb9eaae6 | 22,587 | java | Java | webkit/src/main/java/androidx/webkit/WebViewAssetLoader.java | j420247/platform_frameworks_support | 32dee044b7f9341a6651ea28b2746b2ddbd0b5ba | [
"Apache-2.0"
] | null | null | null | webkit/src/main/java/androidx/webkit/WebViewAssetLoader.java | j420247/platform_frameworks_support | 32dee044b7f9341a6651ea28b2746b2ddbd0b5ba | [
"Apache-2.0"
] | null | null | null | webkit/src/main/java/androidx/webkit/WebViewAssetLoader.java | j420247/platform_frameworks_support | 32dee044b7f9341a6651ea28b2746b2ddbd0b5ba | [
"Apache-2.0"
] | null | null | null | 40.697297 | 111 | 0.620357 | 999,474 | /*
* Copyright 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 androidx.webkit;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import androidx.webkit.internal.AssetHelper;
import java.io.InputStream;
import java.net.URLConnection;
/**
* Helper class to enable accessing the application's static assets and resources under an
* http(s):// URL to be loaded by {@link android.webkit.WebView} class.
* Hosting assets and resources this way is desirable as it is compatible with the Same-Origin
* policy.
*
* <p>
* For more context about application's assets and resources and how to normally access them please
* refer to <a href="https://developer.android.com/guide/topics/resources/providing-resources">
* Android Developer Docs: App resources overview</a>.
*
* <p class='note'>
* This class is expected to be used within
* {@link android.webkit.WebViewClient#shouldInterceptRequest}, which is not invoked on the
* application's main thread. Although instances are themselves thread-safe (and may be safely
* constructed on the application's main thread), exercise caution when accessing private data or
* the view system.
*
* <p>
* Using http(s):// URLs to access local resources may conflict with a real website. This means
* that local resources should only be hosted on domains your organization owns (at paths reserved
* for this purpose) or the default domain Google has reserved for this:
* {@code appassets.androidplatform.net}.
*
* <p>
* A typical usage would be like:
* <pre class="prettyprint">
* WebViewAssetLoader.Builder assetLoaderBuilder = new WebViewAssetLoader.Builder(this);
* final WebViewAssetLoader assetLoader = assetLoaderBuilder.build();
* webView.setWebViewClient(new WebViewClient() {
* {@literal @}Override
* public WebResourceResponse shouldInterceptRequest(WebView view,
* WebResourceRequest request) {
* return assetLoader.shouldInterceptRequest(request);
* }
* });
* // Assets are hosted under http(s)://appassets.androidplatform.net/assets/... by default.
* // If the application's assets are in the "main/assets" folder this will read the file
* // from "main/assets/www/index.html" and load it as if it were hosted on:
* // https://appassets.androidplatform.net/assets/www/index.html
* webview.loadUrl(assetLoader.getAssetsHttpsPrefix().buildUpon()
* .appendPath("www")
* .appendPath("index.html")
* .build().toString());
*
* </pre>
*/
public class WebViewAssetLoader {
private static final String TAG = "WebViewAssetLoader";
/**
* An unused domain reserved by Google for Android applications to intercept requests
* for app assets.
* <p>
* It'll be used by default unless the user specified a different domain.
*/
public static final String KNOWN_UNUSED_AUTHORITY = "appassets.androidplatform.net";
private static final String HTTP_SCHEME = "http";
private static final String HTTPS_SCHEME = "https";
@NonNull private final PathHandler mAssetsHandler;
@NonNull private final PathHandler mResourcesHandler;
/**
* A handler that produces responses for the registered paths.
*
* Matches URIs on the form: {@code "http(s)://authority/path/**"}, HTTPS is always enabled.
*
* <p>
* Methods of this handler will be invoked on a background thread and care must be taken to
* correctly synchronize access to any shared state.
* <p>
* On Android KitKat and above these methods may be called on more than one thread. This thread
* may be different than the thread on which the shouldInterceptRequest method was invoked.
* This means that on Android KitKat and above it is possible to block in this method without
* blocking other resources from loading. The number of threads used to parallelize loading
* is an internal implementation detail of the WebView and may change between updates which
* means that the amount of time spent blocking in this method should be kept to an absolute
* minimum.
*/
@VisibleForTesting
/*package*/ abstract static class PathHandler {
final boolean mHttpEnabled;
@NonNull final String mAuthority;
@NonNull final String mPath;
/**
* @param authority the authority to match (For instance {@code "example.com"})
* @param path the prefix path to match, it should start and end with a {@code "/"}.
* @param httpEnabled enable hosting under the HTTP scheme, HTTPS is always enabled.
*/
PathHandler(@NonNull final String authority, @NonNull final String path,
boolean httpEnabled) {
if (path.isEmpty() || path.charAt(0) != '/') {
throw new IllegalArgumentException("Path should start with a slash '/'.");
}
if (!path.endsWith("/")) {
throw new IllegalArgumentException("Path should end with a slash '/'");
}
this.mAuthority = authority;
this.mPath = path;
this.mHttpEnabled = httpEnabled;
}
/**
* Open an {@link InputStream} for the requested URL.
* <p>
* This method should be called if {@code match(Uri)} returns true in order to
* open the file requested by this URL.
*
* @param url path that has been matched.
* @return {@link InputStream} for the requested URL, {@code null} if an error happens
* while opening the file or file doesn't exist.
*/
@Nullable
public abstract InputStream handle(@NonNull Uri url);
/**
* Match against registered scheme, authority and path prefix.
*
* Match happens when:
* <ul>
* <li>Scheme is "https" <b>or</b> the scheme is "http" and http is enabled.</li>
* <li>Authority exact matches the given URI's authority.</li>
* <li>Path is a prefix of the given URI's path.</li>
* </ul>
*
* @param uri the URI whose path we will match against.
*
* @return {@code true} if a match happens, {@code false} otherwise.
*/
public boolean match(@NonNull Uri uri) {
// Only match HTTP_SCHEME if caller enabled HTTP matches.
if (uri.getScheme().equals(HTTP_SCHEME) && !mHttpEnabled) {
return false;
}
// Don't match non-HTTP(S) schemes.
if (!uri.getScheme().equals(HTTP_SCHEME) && !uri.getScheme().equals(HTTPS_SCHEME)) {
return false;
}
if (!uri.getAuthority().equals(mAuthority)) {
return false;
}
return uri.getPath().startsWith(mPath);
}
}
static class AssetsPathHandler extends PathHandler {
private AssetHelper mAssetHelper;
AssetsPathHandler(@NonNull final String authority, @NonNull final String path,
boolean httpEnabled, @NonNull AssetHelper assetHelper) {
super(authority, path, httpEnabled);
mAssetHelper = assetHelper;
}
@Override
public InputStream handle(Uri url) {
String path = url.getPath().replaceFirst(this.mPath, "");
Uri.Builder assetUriBuilder = new Uri.Builder();
assetUriBuilder.path(path);
Uri assetUri = assetUriBuilder.build();
return mAssetHelper.openAsset(assetUri);
}
}
static class ResourcesPathHandler extends PathHandler {
private AssetHelper mAssetHelper;
ResourcesPathHandler(@NonNull final String authority, @NonNull final String path,
boolean httpEnabled, @NonNull AssetHelper assetHelper) {
super(authority, path, httpEnabled);
mAssetHelper = assetHelper;
}
@Override
public InputStream handle(Uri url) {
String path = url.getPath().replaceFirst(this.mPath, "");
Uri.Builder resourceUriBuilder = new Uri.Builder();
resourceUriBuilder.path(path);
Uri resourceUri = resourceUriBuilder.build();
return mAssetHelper.openResource(resourceUri);
}
}
/**
* A builder class for constructing {@link WebViewAssetLoader} objects.
*/
public static final class Builder {
private final Context mContext;
boolean mAllowHttp;
@NonNull Uri mAssetsUri;
@NonNull Uri mResourcesUri;
/**
* @param context {@link Context} used to resolve resources/assets.
*/
public Builder(@NonNull Context context) {
mContext = context;
mAllowHttp = false;
mAssetsUri = createUriPrefix(KNOWN_UNUSED_AUTHORITY, "/assets/");
mResourcesUri = createUriPrefix(KNOWN_UNUSED_AUTHORITY, "/res/");
}
/**
* Set the domain under which app assets and resources can be accessed.
* The default domain is {@code "appassets.androidplatform.net"}
*
* @param domain the domain on which app assets should be hosted.
* @return {@link Builder} object.
*/
@NonNull
public Builder setDomain(@NonNull String domain) {
mAssetsUri = createUriPrefix(domain, mAssetsUri.getPath());
mResourcesUri = createUriPrefix(domain, mResourcesUri.getPath());
return this;
}
/**
* Set the prefix path under which app assets should be hosted.
* The default path for assets is {@code "/assets/"}. The path must start and end with
* {@code "/"}.
* <p>
* A custom prefix path can be used in conjunction with a custom domain, to
* avoid conflicts with real paths which may be hosted at that domain.
*
* @param path the path under which app assets should be hosted.
* @return {@link Builder} object.
* @throws IllegalArgumentException if the path is invalid.
*/
@NonNull
public Builder setAssetsHostingPath(@NonNull String path) {
mAssetsUri = createUriPrefix(mAssetsUri.getAuthority(), path);
return this;
}
/**
* Set the prefix path under which app resources should be hosted.
* The default path for resources is {@code "/res/"}. The path must start and end with
* {@code "/"}. A custom prefix path can be used in conjunction with a custom domain, to
* avoid conflicts with real paths which may be hosted at that domain.
*
* @param path the path under which app resources should be hosted.
* @return {@link Builder} object.
* @throws IllegalArgumentException if the path is invalid.
*/
@NonNull
public Builder setResourcesHostingPath(@NonNull String path) {
mResourcesUri = createUriPrefix(mResourcesUri.getAuthority(), path);
return this;
}
/**
* Allow using the HTTP scheme in addition to HTTPS.
* The default is to not allow HTTP.
*
* @return {@link Builder} object.
*/
@NonNull
public Builder allowHttp() {
this.mAllowHttp = true;
return this;
}
/**
* Build and return a {@link WebViewAssetLoader} object.
*
* @return immutable {@link WebViewAssetLoader} object.
* @throws IllegalArgumentException if the {@code Builder} received conflicting inputs.
*/
@NonNull
public WebViewAssetLoader build() {
String assetsPath = mAssetsUri.getPath();
String resourcesPath = mResourcesUri.getPath();
if (assetsPath.startsWith(resourcesPath)) {
throw new
IllegalArgumentException("Resources path cannot be prefix of assets path");
}
if (resourcesPath.startsWith(assetsPath)) {
throw new
IllegalArgumentException("Assets path cannot be prefix of resources path");
}
AssetHelper assetHelper = new AssetHelper(mContext);
PathHandler assetHandler = new AssetsPathHandler(mAssetsUri.getAuthority(),
mAssetsUri.getPath(), mAllowHttp, assetHelper);
PathHandler resourceHandler = new ResourcesPathHandler(mResourcesUri.getAuthority(),
mResourcesUri.getPath(), mAllowHttp,
assetHelper);
return new WebViewAssetLoader(assetHandler, resourceHandler);
}
@VisibleForTesting
@NonNull
/*package*/ WebViewAssetLoader buildForTest(@NonNull AssetHelper assetHelper) {
PathHandler assetHandler = new AssetsPathHandler(mAssetsUri.getAuthority(),
mAssetsUri.getPath(), mAllowHttp, assetHelper);
PathHandler resourceHandler = new ResourcesPathHandler(mResourcesUri.getAuthority(),
mResourcesUri.getPath(), mAllowHttp,
assetHelper);
return new WebViewAssetLoader(assetHandler, resourceHandler);
}
@VisibleForTesting
@NonNull
/*package*/ WebViewAssetLoader buildForTest(@NonNull PathHandler assetHandler,
@NonNull PathHandler resourceHandler) {
return new WebViewAssetLoader(assetHandler, resourceHandler);
}
@NonNull
private static Uri createUriPrefix(@NonNull String domain, @NonNull String virtualPath) {
if (virtualPath.indexOf('*') != -1) {
throw new IllegalArgumentException(
"virtualPath cannot contain the '*' character.");
}
if (virtualPath.isEmpty() || virtualPath.charAt(0) != '/') {
throw new IllegalArgumentException(
"virtualPath should start with a slash '/'.");
}
if (!virtualPath.endsWith("/")) {
throw new IllegalArgumentException(
"virtualPath should end with a slash '/'.");
}
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority(domain);
uriBuilder.path(virtualPath);
return uriBuilder.build();
}
}
/*package*/ WebViewAssetLoader(@NonNull PathHandler assetHandler,
@NonNull PathHandler resourceHandler) {
this.mAssetsHandler = assetHandler;
this.mResourcesHandler = resourceHandler;
}
@Nullable
private static Uri parseAndVerifyUrl(@Nullable String url) {
if (url == null) {
return null;
}
Uri uri = Uri.parse(url);
if (uri == null) {
Log.e(TAG, "Malformed URL: " + url);
return null;
}
String path = uri.getPath();
if (path == null || path.length() == 0) {
Log.e(TAG, "URL does not have a path: " + url);
return null;
}
return uri;
}
/**
* Attempt to resolve the {@link WebResourceRequest} to an application resource or
* asset, and return a {@link WebResourceResponse} for the content.
* <p>
* The prefix path used shouldn't be a prefix of a real web path. Thus, in case of having a URL
* that matches a registered prefix path but the requested asset cannot be found or opened a
* {@link WebResourceResponse} object with a {@code null} {@link InputStream} will be returned
* instead of {@code null}. This saves the time of falling back to network and trying to
* resolve a path that doesn't exist. A {@link WebResourceResponse} with {@code null}
* {@link InputStream} will be received as an HTTP response with status code {@code 404} and
* no body.
* <p>
* This method should be invoked from within
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, WebResourceRequest)}.
*
* @param request the {@link WebResourceRequest} to process.
* @return {@link WebResourceResponse} if the request URL matches a registered url,
* {@code null} otherwise.
*/
@RequiresApi(21)
@Nullable
public WebResourceResponse shouldInterceptRequest(@NonNull WebResourceRequest request) {
return shouldInterceptRequestImpl(request.getUrl());
}
/**
* Attempt to resolve the {@code url} to an application resource or asset, and return
* a {@link WebResourceResponse} for the content.
* <p>
* The prefix path used shouldn't be a prefix of a real web path. Thus, in case of having a URL
* that matches a registered prefix path but the requested asset cannot be found or opened a
* {@link WebResourceResponse} object with a {@code null} {@link InputStream} will be returned
* instead of {@code null}. This saves the time of falling back to network and trying to
* resolve a path that doesn't exist. A {@link WebResourceResponse} with {@code null}
* {@link InputStream} will be received as an HTTP response with status code {@code 404} and
* no body.
* <p>
* This method should be invoked from within
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, String)}.
*
* @param url the URL string to process.
* @return {@link WebResourceResponse} if the request URL matches a registered URL,
* {@code null} otherwise.
*/
@Nullable
public WebResourceResponse shouldInterceptRequest(@NonNull String url) {
PathHandler handler = null;
Uri uri = parseAndVerifyUrl(url);
if (uri == null) {
return null;
}
return shouldInterceptRequestImpl(uri);
}
@Nullable
private WebResourceResponse shouldInterceptRequestImpl(@NonNull Uri url) {
PathHandler handler;
if (mAssetsHandler.match(url)) {
handler = mAssetsHandler;
} else if (mResourcesHandler.match(url)) {
handler = mResourcesHandler;
} else {
return null;
}
InputStream is = handler.handle(url);
String mimeType = URLConnection.guessContentTypeFromName(url.getPath());
return new WebResourceResponse(mimeType, null, is);
}
/**
* Get the HTTP URL prefix under which assets are hosted.
* <p>
* If HTTP is allowed, the prefix will be on the format:
* {@code "http://<domain>/<prefix-path>/"}, for example:
* {@code "http://appassets.androidplatform.net/assets/"}.
*
* @return the HTTP URL prefix under which assets are hosted, or {@code null} if HTTP is not
* enabled.
*/
@Nullable
public Uri getAssetsHttpPrefix() {
if (!mAssetsHandler.mHttpEnabled) {
return null;
}
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority(mAssetsHandler.mAuthority);
uriBuilder.path(mAssetsHandler.mPath);
uriBuilder.scheme(HTTP_SCHEME);
return uriBuilder.build();
}
/**
* Get the HTTPS URL prefix under which assets are hosted.
* <p>
* The prefix will be on the format: {@code "https://<domain>/<prefix-path>/"}, if the default
* values are used then it will be: {@code "https://appassets.androidplatform.net/assets/"}.
*
* @return the HTTPS URL prefix under which assets are hosted.
*/
@NonNull
public Uri getAssetsHttpsPrefix() {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority(mAssetsHandler.mAuthority);
uriBuilder.path(mAssetsHandler.mPath);
uriBuilder.scheme(HTTPS_SCHEME);
return uriBuilder.build();
}
/**
* Get the HTTP URL prefix under which resources are hosted.
* <p>
* If HTTP is allowed, the prefix will be on the format:
* {@code "http://<domain>/<prefix-path>/"}, for example
* {@code "http://appassets.androidplatform.net/res/"}.
*
* @return the HTTP URL prefix under which resources are hosted, or {@code null} if HTTP is not
* enabled.
*/
@Nullable
public Uri getResourcesHttpPrefix() {
if (!mResourcesHandler.mHttpEnabled) {
return null;
}
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority(mResourcesHandler.mAuthority);
uriBuilder.path(mResourcesHandler.mPath);
uriBuilder.scheme(HTTP_SCHEME);
return uriBuilder.build();
}
/**
* Get the HTTPS URL prefix under which resources are hosted.
* <p>
* The prefix will be on the format: {@code "https://<domain>/<prefix-path>/"}, if the default
* values are used then it will be: {@code "https://appassets.androidplatform.net/res/"}.
*
* @return the HTTPs URL prefix under which resources are hosted.
*/
@NonNull
public Uri getResourcesHttpsPrefix() {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority(mResourcesHandler.mAuthority);
uriBuilder.path(mResourcesHandler.mPath);
uriBuilder.scheme(HTTPS_SCHEME);
return uriBuilder.build();
}
}
|
923b273d86e1556f6497bcb405c886d6ecaad1a2 | 1,094 | java | Java | app/src/main/java/com/google/firebase/codelab/friendlychat/MyFirebaseMessagingService.java | thomasmburke/firebase-android-sandbox | 253bcc69ccc9460f4790f7a34e10a5ea66405356 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/google/firebase/codelab/friendlychat/MyFirebaseMessagingService.java | thomasmburke/firebase-android-sandbox | 253bcc69ccc9460f4790f7a34e10a5ea66405356 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/google/firebase/codelab/friendlychat/MyFirebaseMessagingService.java | thomasmburke/firebase-android-sandbox | 253bcc69ccc9460f4790f7a34e10a5ea66405356 | [
"Apache-2.0"
] | null | null | null | 35.290323 | 74 | 0.70841 | 999,475 | package com.google.firebase.codelab.friendlychat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.RemoteMessage;
import android.util.Log;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFMService";
private static final String FRIENDLY_ENGAGE_TOPIC = "friendly_engage";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
Log.d(TAG, "FCM Message Id: " + remoteMessage.getMessageId());
Log.d(TAG, "FCM Notification Message: " +
remoteMessage.getNotification());
Log.d(TAG, "FCM Data Message: " + remoteMessage.getData());
}
@Override
public void onNewToken(String token) {
Log.d(TAG, "FCM Token: " + token);
// Once a token is generated, we subscribe to topic.
FirebaseMessaging.getInstance()
.subscribeToTopic(FRIENDLY_ENGAGE_TOPIC);
}
} |
923b277b68375bac34d87f57b0012250dd255392 | 343 | java | Java | org.jhotdraw8.application/src/main/java/org.jhotdraw8.application/org/jhotdraw8/collection/IntEnumeratorSpliterator.java | simplysuvi/jhotdraw8 | 8867b019b6cd408fb933f09008d89e5a43960c4a | [
"MIT"
] | null | null | null | org.jhotdraw8.application/src/main/java/org.jhotdraw8.application/org/jhotdraw8/collection/IntEnumeratorSpliterator.java | simplysuvi/jhotdraw8 | 8867b019b6cd408fb933f09008d89e5a43960c4a | [
"MIT"
] | null | null | null | org.jhotdraw8.application/src/main/java/org.jhotdraw8.application/org/jhotdraw8/collection/IntEnumeratorSpliterator.java | simplysuvi/jhotdraw8 | 8867b019b6cd408fb933f09008d89e5a43960c4a | [
"MIT"
] | null | null | null | 21.4375 | 84 | 0.766764 | 999,476 | /*
* @(#)IntEnumeratorSpliterator.java
* Copyright © 2021 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.collection;
import java.util.Spliterator;
/**
* IntEnumeratorSpliterator.
*
* @author Werner Randelshofer
*/
public interface IntEnumeratorSpliterator extends IntEnumerator, Spliterator.OfInt {
}
|
923b2826397b5900fe69d024113262557349742e | 10,564 | java | Java | generated-test-cases/ArchiveScanner/24-run/MOSA_ArchiveScanner_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | null | null | null | generated-test-cases/ArchiveScanner/24-run/MOSA_ArchiveScanner_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | 1 | 2017-05-11T21:18:17.000Z | 2017-05-11T21:18:17.000Z | generated-test-cases/ArchiveScanner/24-run/MOSA_ArchiveScanner_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | null | null | null | 37.863799 | 135 | 0.664237 | 999,477 | /*
* This file was automatically generated by EvoSuite
* Fri Dec 11 19:15:00 GMT 2015
*/
package com.lts.io;
import static org.junit.Assert.*;
import org.junit.Test;
import com.lts.io.ArchiveScanner;
import com.lts.io.ImprovedFile;
import java.io.File;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.EvoSuiteLocalAddress;
import org.evosuite.runtime.testdata.EvoSuiteRemoteAddress;
import org.evosuite.runtime.testdata.EvoSuiteURL;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true)
public class ArchiveScanner_ESTest extends ArchiveScanner_ESTest_scaffolding {
//Test case number: 0
/*
* 1 covered goal:
* Goal 1. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I38 Branch 18 IF_ICMPGE L193 - true
*/
@Test
public void test0() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
archiveScanner0.scandir(improvedFile0, "", false);
assertEquals(0L, improvedFile0.length());
}
//Test case number: 1
/*
* 1 covered goal:
* Goal 1. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I11 Branch 17 IFNONNULL L179 - false
*/
@Test
public void test1() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile(".WAR");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
try {
archiveScanner0.scandir(improvedFile0, ".WAR", false);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// IO error scanning directory /Users/fabiopalomba/Documents/workspace/LunchEvosuite/.WAR
//
}
}
//Test case number: 2
/*
* 1 covered goal:
* Goal 1. com.lts.io.ArchiveScanner.processArchive(Ljava/io/File;Ljava/lang/String;)V: I27 Branch 16 IFEQ L165 - false
*/
@Test
public void test2() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile(".ear");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[1];
stringArray0[0] = "Jeqr";
archiveScanner0.excludes = stringArray0;
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.processArchive((File) improvedFile0, "Jeqr");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 3
/*
* 2 covered goals:
* Goal 1. com.lts.io.ArchiveScanner.processArchive(Ljava/io/File;Ljava/lang/String;)V: I8 Branch 15 IFNE L163 - true
* Goal 2. com.lts.io.ArchiveScanner.processArchive(Ljava/io/File;Ljava/lang/String;)V: I27 Branch 16 IFEQ L165 - true
*/
@Test
public void test3() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile(".ear");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
archiveScanner0.addDefaultExcludes();
String[] stringArray0 = new String[1];
stringArray0[0] = ".ear";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.processArchive((File) improvedFile0, ".ear");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 4
/*
* 8 covered goals:
* Goal 1. com.lts.io.ArchiveScanner.isArchive(Ljava/io/File;)Z: I19 Branch 1 IFNE L72 - true
* Goal 2. com.lts.io.ArchiveScanner.isArchive(Ljava/io/File;)Z: I19 Branch 1 IFNE L72 - false
* Goal 3. com.lts.io.ArchiveScanner.isArchive(Ljava/io/File;)Z: I26 Branch 2 IF_ICMPGE L72 - false
* Goal 4. com.lts.io.ArchiveScanner.toFileType(Ljava/io/File;)I: I11 Branch 3 IFEQ L86 - true
* Goal 5. com.lts.io.ArchiveScanner.toFileType(Ljava/io/File;)I: I28 Branch 4 IFEQ L88 - false
* Goal 6. com.lts.io.ArchiveScanner.processArchive(Ljava/io/File;Ljava/lang/String;)V: I8 Branch 15 IFNE L163 - false
* Goal 7. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I86 Branch 20 TABLESWITCH L198 Case 1 - false
* Goal 8. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I86 Branch 21 TABLESWITCH L198 Case 2 - true
*/
@Test
public void test4() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[7];
stringArray0[0] = "";
stringArray0[1] = "";
stringArray0[2] = ".war";
stringArray0[3] = "";
stringArray0[4] = "";
stringArray0[5] = "";
stringArray0[6] = "";
archiveScanner0.setIncludes(stringArray0);
ImprovedFile improvedFile1 = ImprovedFile.createTempDirectory("beget", "", (File) improvedFile0);
// Undeclared exception!
try {
archiveScanner0.scandir(improvedFile0, "", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 5
/*
* 2 covered goals:
* Goal 1. com.lts.io.ArchiveScanner.processFile(Ljava/lang/String;)V: I8 Branch 12 IFNE L131 - true
* Goal 2. com.lts.io.ArchiveScanner.processFile(Ljava/lang/String;)V: I27 Branch 13 IFEQ L133 - false
*/
@Test
public void test5() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[7];
stringArray0[0] = "";
stringArray0[1] = "";
stringArray0[2] = "";
stringArray0[3] = "";
stringArray0[4] = "";
stringArray0[5] = "";
archiveScanner0.excludes = stringArray0;
stringArray0[6] = "";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.processFile("");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 6
/*
* 1 covered goal:
* Goal 1. com.lts.io.ArchiveScanner.processFile(Ljava/lang/String;)V: I8 Branch 12 IFNE L131 - false
*/
@Test
public void test6() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
String[] stringArray0 = new String[7];
stringArray0[0] = "";
stringArray0[1] = "";
stringArray0[2] = ".wucar";
stringArray0[3] = "";
stringArray0[4] = "";
stringArray0[5] = "";
stringArray0[6] = "";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.processFile("@z\\<+]&A35f5");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 7
/*
* 1 covered goal:
* Goal 1. com.lts.io.ArchiveScanner.processDirectory(Ljava/io/File;Ljava/lang/String;Z)V: I8 Branch 6 IFEQ L101 - false
*/
@Test
public void test7() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("[j");
ImprovedFile improvedFile1 = ImprovedFile.createTempDirectory("&Ac*r.J", "&Ac*r.J", (File) improvedFile0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile1);
String[] stringArray0 = new String[3];
stringArray0[0] = "uz-z(a] ";
stringArray0[1] = "&Ac*r.J";
stringArray0[2] = "[j";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.scandir(improvedFile0, "&Ac*r.J", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 8
/*
* 9 covered goals:
* Goal 1. com.lts.io.ArchiveScanner.<init>(Lcom/lts/io/ImprovedFile;)V: root-Branch
* Goal 2. com.lts.io.ArchiveScanner.toFileType(Ljava/io/File;)I: I11 Branch 3 IFEQ L86 - false
* Goal 3. com.lts.io.ArchiveScanner.processDirectory(Ljava/io/File;Ljava/lang/String;Z)V: I8 Branch 6 IFEQ L101 - true
* Goal 4. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I11 Branch 17 IFNONNULL L179 - true
* Goal 5. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I38 Branch 18 IF_ICMPGE L193 - false
* Goal 6. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I86 Branch 19 TABLESWITCH L198 Case 0 - false
* Goal 7. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I86 Branch 20 TABLESWITCH L198 Case 1 - true
* Goal 8. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I86 Branch 21 TABLESWITCH L198 Case 2 - false
* Goal 9. com.lts.io.ArchiveScanner.scandir(Ljava/io/File;Ljava/lang/String;Z)V: I86 Branch 22 TABLESWITCH L198 Default-Case - false
*/
@Test
public void test8() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("[j");
ImprovedFile improvedFile1 = ImprovedFile.createTempDirectory("&Ac*r.J", "}-4Pj%NyT%[", (File) improvedFile0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile1);
String[] stringArray0 = new String[3];
stringArray0[0] = "uz-z(a] ";
stringArray0[1] = "}-4Pj%NyT%[";
stringArray0[2] = "}-4Pj%NyT%[";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.scandir(improvedFile0, "&Ac*r.J", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
}
|
923b289cb2c50bb666d4a384495214ba3356c4c1 | 1,529 | java | Java | src/test/java/collections/MapAssertionTest.java | ingmargoudt/Tester | 55787743bc9e3367b2b811b4283e54a496380e21 | [
"Apache-2.0"
] | 1 | 2020-04-27T18:31:03.000Z | 2020-04-27T18:31:03.000Z | src/test/java/collections/MapAssertionTest.java | ingmargoudt/veritas | 55787743bc9e3367b2b811b4283e54a496380e21 | [
"Apache-2.0"
] | null | null | null | src/test/java/collections/MapAssertionTest.java | ingmargoudt/veritas | 55787743bc9e3367b2b811b4283e54a496380e21 | [
"Apache-2.0"
] | null | null | null | 25.915254 | 90 | 0.606279 | 999,478 | package collections;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static io.github.ingmargoudt.veritas.Veritas.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class MapAssertionTest {
@Test
public void containsKey() {
Map<String, Integer> theMap = new HashMap<>();
theMap.put("A", 1);
String key = "A";
assertThat(theMap).containsKey(key);
}
@Test
public void notContainsKey() {
Map<String, Integer> theMap = new HashMap<>();
theMap.put("A", 1);
String key = "B";
assertThrows(AssertionError.class, () -> assertThat(theMap).containsKey(key));
}
@Test
public void isEmpty() {
Map<String, String> theMap = new HashMap<>();
assertThat(theMap).isEmpty();
}
@Test
public void isNotEmpty() {
Map<String, String> theMap = new HashMap<>();
theMap.put("A", "A");
assertThrows(AssertionError.class, () -> assertThat(theMap).isEmpty());
}
@Test
public void containsValue() {
Map<String, Integer> theMap = new HashMap<>();
theMap.put("A", 1);
int value = 1;
assertThat(theMap).containsValue(value);
}
@Test
public void notContainsValue() {
Map<String, Integer> theMap = new HashMap<>();
theMap.put("A", 1);
Integer value = 2;
assertThrows(AssertionError.class, () -> assertThat(theMap).containsValue(value));
}
}
|
923b2991f528757f88e334c48dd15e6d95e97984 | 3,392 | java | Java | higgs-agent/higgs-agent-engine/src/main/java/io/vilada/higgs/agent/engine/util/GcTypeUtil.java | gitter-badger/higgs | 7b2c8e9e90e231455e53232d9ad148d319ead10b | [
"Apache-2.0"
] | 1 | 2021-01-11T05:41:16.000Z | 2021-01-11T05:41:16.000Z | higgs-agent/higgs-agent-engine/src/main/java/io/vilada/higgs/agent/engine/util/GcTypeUtil.java | gitter-badger/higgs | 7b2c8e9e90e231455e53232d9ad148d319ead10b | [
"Apache-2.0"
] | null | null | null | higgs-agent/higgs-agent-engine/src/main/java/io/vilada/higgs/agent/engine/util/GcTypeUtil.java | gitter-badger/higgs | 7b2c8e9e90e231455e53232d9ad148d319ead10b | [
"Apache-2.0"
] | 1 | 2021-01-11T05:41:18.000Z | 2021-01-11T05:41:18.000Z | 42.4 | 101 | 0.67954 | 999,479 | /*
* Copyright 2018 The Higgs Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.vilada.higgs.agent.engine.util;
import io.vilada.higgs.serialization.thrift.dto.TJvmGcType;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
/**
* @author mjolnir
*/
public class GcTypeUtil {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("[\\s]+");
private static final String NAME_LINK = "-";
private static Map<String, TJvmGcType> CACHE_MAP = new ConcurrentHashMap<String, TJvmGcType>(10);
public static TJvmGcType parseGCType(String name) {
TJvmGcType jvmGcType = CACHE_MAP.get(name);
if (jvmGcType != null) {
return jvmGcType;
}
String lowercaseName = WHITESPACE_PATTERN.matcher(name)
.replaceAll(NAME_LINK).toLowerCase();
if (TJvmGcType.SERIAL_NEW.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.SERIAL_NEW);
return TJvmGcType.SERIAL_NEW;
} else if (TJvmGcType.SERIAL_OLD.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.SERIAL_OLD);
return TJvmGcType.SERIAL_OLD;
} else if (TJvmGcType.PARNEW_NEW.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.PARNEW_NEW);
return TJvmGcType.PARNEW_NEW;
} else if (TJvmGcType.PARALLEL_SCAVENGE_NEW.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.PARALLEL_SCAVENGE_NEW);
return TJvmGcType.PARALLEL_SCAVENGE_NEW;
} else if (TJvmGcType.PARALLEL_SCAVENGE_OLD.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.PARALLEL_SCAVENGE_OLD);
return TJvmGcType.PARALLEL_SCAVENGE_OLD;
} else if (TJvmGcType.CMS_OLD.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.CMS_OLD);
return TJvmGcType.CMS_OLD;
} else if (TJvmGcType.G1_NEW.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.G1_NEW);
return TJvmGcType.G1_NEW;
} else if (TJvmGcType.G1_OLD.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.G1_OLD);
return TJvmGcType.G1_OLD;
} else if (TJvmGcType.UNKNOWN_NEW.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.UNKNOWN_NEW);
return TJvmGcType.UNKNOWN_NEW;
} else if (TJvmGcType.UNKNOWN_OLD.getAlgorithm().indexOf(lowercaseName) != -1) {
CACHE_MAP.put(name, TJvmGcType.UNKNOWN_OLD);
return TJvmGcType.UNKNOWN_OLD;
}
CACHE_MAP.put(name, TJvmGcType.UNKNOWN);
return TJvmGcType.UNKNOWN;
}
}
|
923b2aa11e2bba7cd4a1be77a35c9a875d70eae9 | 2,829 | java | Java | ph-oton-html/src/main/java/com/helger/html/meta/IMetaElementList.java | phax/ph-oton | 13c6c707641bc32c77e36b157179dd209f8f5e0f | [
"Apache-2.0"
] | 4 | 2017-05-02T14:12:09.000Z | 2022-01-13T00:27:10.000Z | ph-oton-html/src/main/java/com/helger/html/meta/IMetaElementList.java | phax/ph-oton | 13c6c707641bc32c77e36b157179dd209f8f5e0f | [
"Apache-2.0"
] | 11 | 2016-02-15T19:23:23.000Z | 2021-09-01T17:48:38.000Z | ph-oton-html/src/main/java/com/helger/html/meta/IMetaElementList.java | phax/ph-oton | 13c6c707641bc32c77e36b157179dd209f8f5e0f | [
"Apache-2.0"
] | 4 | 2015-11-02T13:46:38.000Z | 2022-01-13T00:27:31.000Z | 30.75 | 79 | 0.71474 | 999,480 | /*
* Copyright (C) 2014-2021 Philip Helger (www.helger.com)
* philip[at]helger[dot]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.helger.html.meta;
import java.util.Collection;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.helger.commons.annotation.MustImplementEqualsAndHashcode;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.impl.ICommonsIterable;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.collection.impl.ICommonsOrderedSet;
/**
* Read only base interface for a list of {@link IMetaElement} objects.
*
* @author Philip Helger
*/
@MustImplementEqualsAndHashcode
public interface IMetaElementList extends ICommonsIterable <IMetaElement>
{
/**
* @return A set with used meta element names. Never <code>null</code>.
*/
@Nonnull
@ReturnsMutableCopy
ICommonsOrderedSet <String> getAllMetaElementNames ();
/**
* @return A list with all contained meta elements. Never <code>null</code>.
*/
@Nonnull
@ReturnsMutableCopy
ICommonsList <IMetaElement> getAllMetaElements ();
/**
* Add all contained meta elements to the passed container.
*
* @param aTarget
* The target container to be filled. May not be <code>null</code>.
*/
void getAllMetaElements (@Nonnull Collection <? super IMetaElement> aTarget);
/**
* Find the meta element with the given name.
*
* @param sName
* The name to search. May be <code>null</code> or empty.
* @return <code>null</code> if no such meta element exists.
*/
@Nullable
IMetaElement getMetaElementOfName (@Nullable String sName);
/**
* Check if a meta element with the given name exists.
*
* @param sName
* The name to check. May be <code>null</code> or empty.
* @return <code>true</code> if a meta element with the passed name exists.
*/
boolean containsMetaElementWithName (@Nullable String sName);
/**
* @return The number of contained meta elements. Always ≥ 0.
*/
@Nonnegative
int getMetaElementCount ();
/**
* @return <code>true</code> if at least one meta element is contained,
* <code>false</code> otherwise.
*/
boolean hasMetaElements ();
}
|
923b2b5637ccdb711b39c034ef812dd42d5a1d3a | 1,865 | java | Java | endpoints-framework/src/test/java/com/google/api/server/spi/handlers/EndpointsMethodHandlerRedirectLocationTest.java | Botffy/endpoints-java | 8fe0894ecbc4141976e98d4c67e563c19b81dead | [
"Apache-2.0"
] | 1 | 2019-09-03T17:29:09.000Z | 2019-09-03T17:29:09.000Z | endpoints-framework/src/test/java/com/google/api/server/spi/handlers/EndpointsMethodHandlerRedirectLocationTest.java | Botffy/endpoints-java | 8fe0894ecbc4141976e98d4c67e563c19b81dead | [
"Apache-2.0"
] | 44 | 2017-12-27T10:03:07.000Z | 2021-12-01T08:21:57.000Z | endpoints-framework/src/test/java/com/google/api/server/spi/handlers/EndpointsMethodHandlerRedirectLocationTest.java | Botffy/endpoints-java | 8fe0894ecbc4141976e98d4c67e563c19b81dead | [
"Apache-2.0"
] | 3 | 2017-05-27T23:23:53.000Z | 2022-03-25T10:10:30.000Z | 31.083333 | 128 | 0.762466 | 999,481 | package com.google.api.server.spi.handlers;
import static com.google.api.server.spi.handlers.EndpointsMethodHandler.getRedirectLocation;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import com.google.api.server.spi.EndpointsContext;
/**
* Tests for redirect location in {@link EndpointsMethodHandler}.
*/
@RunWith(JUnit4.class)
public class EndpointsMethodHandlerRedirectLocationTest {
private EndpointsContext context;
private MockHttpServletRequest request;
@Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
request.setRequestURI("/_ah/api/resource");
HttpServletResponse response = new MockHttpServletResponse();
context = new EndpointsContext("", "", request, response, false);
}
@Test
public void httpsUrl() {
Assert.assertEquals("https://example.com/resource", getRedirectLocation(context, "https://example.com/resource"));
}
@Test
public void httpsUrlWithPort() {
Assert.assertEquals("https://example.com:8443/resource", getRedirectLocation(context, "https://example.com:8443/resource"));
}
@Test
public void relativeToServer() {
Assert.assertEquals("/redirected/other", getRedirectLocation(context, "/redirected/other"));
}
@Test
public void relativeToRequest() {
Assert.assertEquals("/_ah/api/resource/redirect", getRedirectLocation(context, "redirect"));
}
@Test
public void relativeToRequest_trailingSlashInRequest() {
request.setRequestURI("/_ah/api/resource/");
Assert.assertEquals("/_ah/api/resource/redirect", getRedirectLocation(context, "redirect"));
}
}
|
923b2b6b3247e4cbbe7ec65b42bf9db3f79d7f97 | 4,270 | java | Java | java/operator/src/main/java/com/instaclustr/cassandra/operator/service/CassandraHealthCheckService.java | xek/cassandra-operator | d7041159bae37b7e9a3151e512ebd4f0f199dcae | [
"Apache-2.0"
] | null | null | null | java/operator/src/main/java/com/instaclustr/cassandra/operator/service/CassandraHealthCheckService.java | xek/cassandra-operator | d7041159bae37b7e9a3151e512ebd4f0f199dcae | [
"Apache-2.0"
] | null | null | null | java/operator/src/main/java/com/instaclustr/cassandra/operator/service/CassandraHealthCheckService.java | xek/cassandra-operator | d7041159bae37b7e9a3151e512ebd4f0f199dcae | [
"Apache-2.0"
] | null | null | null | 43.571429 | 179 | 0.68829 | 999,482 | package com.instaclustr.cassandra.operator.service;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.eventbus.EventBus;
import com.google.common.net.InetAddresses;
import com.google.common.util.concurrent.AbstractScheduledService;
import com.instaclustr.cassandra.operator.event.CassandraNodeStatusChangedEvent;
import com.instaclustr.cassandra.operator.jmx.CassandraConnection;
import com.instaclustr.cassandra.operator.jmx.CassandraConnectionFactory;
import com.instaclustr.cassandra.operator.model.DataCenter;
import com.instaclustr.cassandra.operator.model.key.DataCenterKey;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.models.V1Pod;
import io.kubernetes.client.models.V1PodList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class CassandraHealthCheckService extends AbstractScheduledService {
private static final Logger logger = LoggerFactory.getLogger(CassandraHealthCheckService.class);
private final CoreV1Api coreApi;
private final Map<DataCenterKey, DataCenter> dataCenterCache;
private final CassandraConnectionFactory cassandraConnectionFactory;
private final EventBus eventBus;
private Cache<InetAddress, CassandraConnection.Status> cassandraNodeStatuses = CacheBuilder.newBuilder()
.expireAfterWrite(3, TimeUnit.MINUTES)
.build();
@Inject
public CassandraHealthCheckService(final CoreV1Api coreApi,
final Map<DataCenterKey, DataCenter> dataCenterCache,
final CassandraConnectionFactory cassandraConnectionFactory,
final EventBus eventBus) {
this.coreApi = coreApi;
this.dataCenterCache = dataCenterCache;
this.cassandraConnectionFactory = cassandraConnectionFactory;
this.eventBus = eventBus;
}
@Override
protected void runOneIteration() throws Exception {
// TODO: maybe this would be better off querying k8s for the service endpoints rather than the pods themselves...
logger.debug("Checking health of cassandra instances...");
for (final Map.Entry<DataCenterKey, DataCenter> cacheEntry : dataCenterCache.entrySet()) {
final DataCenterKey dataCenterKey = cacheEntry.getKey();
final String labelSelector = String.format("cassandra-datacenter=%s", dataCenterKey.name);
final V1PodList podList = coreApi.listNamespacedPod(cacheEntry.getValue().getMetadata().getNamespace(), null, null, null, null, labelSelector, null, null, null, null);
for (final V1Pod pod : podList.getItems()) {
// Skip when a Pod is not in a "Running" state
if (!pod.getStatus().getPhase().equals("Running")) continue;
final InetAddress podIp = InetAddresses.forString(pod.getStatus().getPodIP());
try {
logger.debug("{} pod {} has IP {}", dataCenterKey, pod.getMetadata().getName(), podIp);
final CassandraConnection cassandraConnection = cassandraConnectionFactory.connectionForAddress(podIp);
final CassandraConnection.Status previousStatus = cassandraNodeStatuses.getIfPresent(podIp);
final CassandraConnection.Status status = cassandraConnection.status();
logger.debug("{}", status);
if (previousStatus != null && !previousStatus.equals(status)) {
eventBus.post(new CassandraNodeStatusChangedEvent(pod, dataCenterKey, previousStatus, status));
}
cassandraNodeStatuses.put(podIp, status);
} catch (Exception e) {
logger.warn("Failed to check the status of Cassandra node {} ({}). This will be an excpetion in the future.", pod.getMetadata().getName(), podIp, e);
}
}
}
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedDelaySchedule(0, 1, TimeUnit.MINUTES);
}
}
|
923b2ba4898fd7e8a57c3e393b8d015af5be7f63 | 3,685 | java | Java | src/main/java/uk/org/adamretter/maven/XSpecURIResolver.java | adamretter/xspec-maven-plugin | c02baead170d60f9a47f3cf48e15c0914758342a | [
"BSD-3-Clause"
] | 4 | 2015-10-22T20:46:03.000Z | 2017-01-31T10:01:59.000Z | src/main/java/uk/org/adamretter/maven/XSpecURIResolver.java | adamretter/xspec-maven-plugin | c02baead170d60f9a47f3cf48e15c0914758342a | [
"BSD-3-Clause"
] | 7 | 2015-08-19T08:37:28.000Z | 2018-07-01T13:00:40.000Z | src/main/java/uk/org/adamretter/maven/XSpecURIResolver.java | adamretter/xspec-maven-plugin | c02baead170d60f9a47f3cf48e15c0914758342a | [
"BSD-3-Clause"
] | 8 | 2015-04-24T06:07:33.000Z | 2017-10-23T19:20:39.000Z | 43.97619 | 129 | 0.708175 | 999,483 | /**
* Copyright © 2013, Adam Retter
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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 uk.org.adamretter.maven;
import net.sf.saxon.lib.StandardURIResolver;
import net.sf.saxon.trans.XPathException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
/**
* If Saxon fails to find a resource by URI
* we delegate to our Resource Resolver
* which will also look up the resource in the
* classpath and filesystem
*
* @author <a href="mailto:nnheo@example.com">Adam Retter</a>
*/
public class XSpecURIResolver extends StandardURIResolver {
private final ResourceResolver resourceResolver;
private final LogProvider logProvider;
public XSpecURIResolver(final LogProvider logProvider, final ResourceResolver resourceResolver) {
this.logProvider = logProvider;
this.resourceResolver = resourceResolver;
}
@Override
public Source resolve(final String href, final String base) throws XPathException {
final Source saxonSource = super.resolve(href, base);
if(saxonSource != null && new File(saxonSource.getSystemId()).exists()) {
getLogProvider().getLog().debug(String.format("Saxon Resolved URI href=%s ,base=%s to %s", href, base, saxonSource));
return saxonSource;
} else {
getLogProvider().getLog().debug(String.format("Saxon failed URIResolution for: %s", saxonSource.getSystemId()));
final String path = URI.create(saxonSource.getSystemId()).getPath();
getLogProvider().getLog().debug(String.format("Attempting URIResolution for XSpec from: %s", path));
final InputStream is = resourceResolver.getResource(path);
if(is != null) {
final StreamSource xspecSource = new StreamSource(is);
xspecSource.setSystemId(path);
return xspecSource;
} else {
getLogProvider().getLog().warn("Could not Resolve URI for XSpec!");
return null;
}
}
}
protected LogProvider getLogProvider() {
return logProvider;
}
}
|
923b2cb73a026cda5b1921547e7455addb170480 | 8,419 | java | Java | xinqu-video-player/src/main/java/com/xinqu/videoplayer/XinQuMediaSystem.java | YangChengTeam/english_study | 4d62f06204a6b700af2cb4295cccc24bf0d17b0e | [
"MIT"
] | null | null | null | xinqu-video-player/src/main/java/com/xinqu/videoplayer/XinQuMediaSystem.java | YangChengTeam/english_study | 4d62f06204a6b700af2cb4295cccc24bf0d17b0e | [
"MIT"
] | null | null | null | xinqu-video-player/src/main/java/com/xinqu/videoplayer/XinQuMediaSystem.java | YangChengTeam/english_study | 4d62f06204a6b700af2cb4295cccc24bf0d17b0e | [
"MIT"
] | null | null | null | 35.37395 | 314 | 0.61575 | 999,484 | package com.xinqu.videoplayer;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.Surface;
import com.ksyun.media.player.IMediaPlayer;
import com.ksyun.media.player.KSYMediaPlayer;
import com.xinqu.videoplayer.manager.XinQuMediaManager;
import com.xinqu.videoplayer.manager.XinQuVideoPlayerManager;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Created by Nathen on 2017/11/8.
* 实现系统的播放引擎
*/
public class XinQuMediaSystem extends XinQuMediaInterface implements IMediaPlayer.OnPreparedListener, IMediaPlayer.OnCompletionListener, IMediaPlayer.OnBufferingUpdateListener, IMediaPlayer.OnSeekCompleteListener, IMediaPlayer.OnErrorListener, IMediaPlayer.OnInfoListener, IMediaPlayer.OnVideoSizeChangedListener {
public KSYMediaPlayer mKsyMdiaPlayer = null;
public static boolean CURRENT_PLING_LOOP;
private final int RELOAD_CONNECT_COUNT=3;//视频播放错误时候的最大重试次数
private int CUREEN_RELOAD_CONNECT_COUNT=0;
@Override
public void start() {
if(null!=mKsyMdiaPlayer){
mKsyMdiaPlayer.start();
}
}
@Override
public void prepare() {
try {
if(null!=mKsyMdiaPlayer) mKsyMdiaPlayer.release();
mKsyMdiaPlayer = new KSYMediaPlayer.Builder(XinQuVideoPlayer.getmContext()).build();
mKsyMdiaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mKsyMdiaPlayer.setOnPreparedListener(XinQuMediaSystem.this);
mKsyMdiaPlayer.setOnCompletionListener(XinQuMediaSystem.this);
mKsyMdiaPlayer.setOnBufferingUpdateListener(XinQuMediaSystem.this);
mKsyMdiaPlayer.setScreenOnWhilePlaying(true);
mKsyMdiaPlayer.setOnSeekCompleteListener(XinQuMediaSystem.this);
mKsyMdiaPlayer.setOnErrorListener(XinQuMediaSystem.this);
mKsyMdiaPlayer.setOnInfoListener(XinQuMediaSystem.this);
mKsyMdiaPlayer.setOnVideoSizeChangedListener(XinQuMediaSystem.this);
mKsyMdiaPlayer.setLooping(CURRENT_PLING_LOOP);
Class<KSYMediaPlayer> clazz = KSYMediaPlayer.class;
Method method = clazz.getDeclaredMethod("setDataSource", String.class, Map.class);
if (null!=dataSourceObjects&&dataSourceObjects.length > 2) {
method.invoke(mKsyMdiaPlayer, currentDataSource.toString(), dataSourceObjects[2]);
} else {
method.invoke(mKsyMdiaPlayer, currentDataSource.toString(), null);
}
mKsyMdiaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void pause() {
if(null!=mKsyMdiaPlayer){
mKsyMdiaPlayer.pause();
}
}
@Override
public boolean isPlaying() {
if(null!=mKsyMdiaPlayer){
return mKsyMdiaPlayer.isPlaying();
}
return false;
}
@Override
public void seekTo(long time) {
if(null!=mKsyMdiaPlayer){
mKsyMdiaPlayer.seekTo((int) time);
}
}
@Override
public void release() {
if(null!=mKsyMdiaPlayer){
mKsyMdiaPlayer.release();
}
}
@Override
public long getCurrentPosition() {
if(null!=mKsyMdiaPlayer){
return mKsyMdiaPlayer.getCurrentPosition();
}
return 0;
}
@Override
public long getDuration() {
if(null!=mKsyMdiaPlayer){
return mKsyMdiaPlayer.getDuration();
}
return 0;
}
@Override
public void setSurface(Surface surface) {
if(null!=mKsyMdiaPlayer){
mKsyMdiaPlayer.setSurface(surface);
}
}
@Override
public void setLoop(boolean flag) {
this.CURRENT_PLING_LOOP=flag;
}
@Override
public void onPrepared(IMediaPlayer mediaPlayer) {
CUREEN_RELOAD_CONNECT_COUNT=0;
mediaPlayer.start();
if (currentDataSource.toString().toLowerCase().contains("mp3")) {
XinQuMediaManager.instance().mainThreadHandler.post(new Runnable() {
@Override
public void run() {
if (XinQuVideoPlayerManager.getCurrentJzvd() != null) {
XinQuVideoPlayerManager.getCurrentJzvd().onPrepared();
}
}
});
}
}
@Override
public void onCompletion(IMediaPlayer mediaPlayer) {
XinQuMediaManager.instance().mainThreadHandler.post(new Runnable() {
@Override
public void run() {
if (XinQuVideoPlayerManager.getCurrentJzvd() != null) {
XinQuVideoPlayerManager.getCurrentJzvd().onAutoCompletion();
}
}
});
}
@Override
public void onBufferingUpdate(IMediaPlayer mediaPlayer, final int percent) {
XinQuMediaManager.instance().mainThreadHandler.post(new Runnable() {
@Override
public void run() {
if (XinQuVideoPlayerManager.getCurrentJzvd() != null) {
XinQuVideoPlayerManager.getCurrentJzvd().setBufferProgress(percent);
}
}
});
}
@Override
public void onSeekComplete(IMediaPlayer mediaPlayer) {
XinQuMediaManager.instance().mainThreadHandler.post(new Runnable() {
@Override
public void run() {
if (XinQuVideoPlayerManager.getCurrentJzvd() != null) {
XinQuVideoPlayerManager.getCurrentJzvd().onSeekComplete();
}
}
});
}
@Override
public boolean onError(IMediaPlayer mediaPlayer, final int what, final int extra) {
if(null!=mKsyMdiaPlayer&&null!=dataSourceObjects&&dataSourceObjects.length>2&&CUREEN_RELOAD_CONNECT_COUNT<RELOAD_CONNECT_COUNT){
//播放失败,尝试重试5次
CUREEN_RELOAD_CONNECT_COUNT++;
mKsyMdiaPlayer.reload(dataSourceObjects[2].toString(),false);
//达到错误重连次数之后,显示为失败状态
}else{
XinQuMediaManager.instance().mainThreadHandler.post(new Runnable() {
@Override
public void run() {
if (XinQuVideoPlayerManager.getCurrentJzvd() != null) {
XinQuVideoPlayerManager.getCurrentJzvd().onError(what, extra);
}
}
});
}
return true;
}
@Override
public boolean onInfo(IMediaPlayer mediaPlayer, final int what, final int extra) {
XinQuMediaManager.instance().mainThreadHandler.post(new Runnable() {
@Override
public void run() {
if (XinQuVideoPlayerManager.getCurrentJzvd() != null) {
if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
XinQuVideoPlayerManager.getCurrentJzvd().onPrepared();
} else if(what==MediaPlayer.MEDIA_INFO_BUFFERING_END){
XinQuVideoPlayerManager.getCurrentJzvd().onRestarted();
}else {
XinQuVideoPlayerManager.getCurrentJzvd().onInfo(what, extra);
}
}
}
});
return false;
}
@Override
public void onVideoSizeChanged(IMediaPlayer iMediaPlayer, final int width, final int height, int i2, int i3) {
XinQuMediaManager.instance().currentVideoWidth = width;
XinQuMediaManager.instance().currentVideoHeight = height;
if(width==height){
Log.d("onVideoSizeChanged","视频:正方形");
XinQuVideoPlayer.widthRatio=1;
XinQuVideoPlayer.heightRatio=1;
}else if (width>height){
Log.d("onVideoSizeChanged","视频:宽形");
XinQuVideoPlayer.widthRatio=16;
XinQuVideoPlayer.heightRatio=9;
}else if(width<height){
Log.d("onVideoSizeChanged","视频:长方形");
XinQuVideoPlayer.widthRatio=3;
XinQuVideoPlayer.heightRatio=4;
}
XinQuMediaManager.instance().mainThreadHandler.post(new Runnable() {
@Override
public void run() {
if (XinQuVideoPlayerManager.getCurrentJzvd() != null) {
XinQuVideoPlayerManager.getCurrentJzvd().onVideoSizeChanged(width,height);
}
}
});
}
}
|
923b2e0a9ea6b8eeed0b123a87e7097b352add23 | 98 | java | Java | users/nfyfamr@gmail.com/c/src/e.java | nfyfamr/IDEEON | eb48a31f3aee3b58d301c331a48bbd33edd69acd | [
"MIT"
] | null | null | null | users/nfyfamr@gmail.com/c/src/e.java | nfyfamr/IDEEON | eb48a31f3aee3b58d301c331a48bbd33edd69acd | [
"MIT"
] | null | null | null | users/nfyfamr@gmail.com/c/src/e.java | nfyfamr/IDEEON | eb48a31f3aee3b58d301c331a48bbd33edd69acd | [
"MIT"
] | null | null | null | 19.6 | 44 | 0.571429 | 999,485 | class e {
public static void main(String[] args) {
System.out.println("1234");
}
} |
923b2e3e2f6b9dfa1deb7178db887e1e6814c55e | 633 | java | Java | src/main/java/com/xy/pattern/factory/simple/SimpleFactory.java | liushunshun/xutil | 97fe384ae34d9b9684cedfaafd2964290ee4f9bd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/xy/pattern/factory/simple/SimpleFactory.java | liushunshun/xutil | 97fe384ae34d9b9684cedfaafd2964290ee4f9bd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/xy/pattern/factory/simple/SimpleFactory.java | liushunshun/xutil | 97fe384ae34d9b9684cedfaafd2964290ee4f9bd | [
"Apache-2.0"
] | null | null | null | 14.386364 | 42 | 0.600316 | 999,486 | package com.xy.pattern.factory.simple;
/**
* 简单工厂
* @author liuss
*
*/
public class SimpleFactory {
public Product createProduct(int type){
switch (type) {
case 1:
return new Product("alex");
case 2:
return new Product("justin");
default:
return null;
}
}
public static void main(String[] args) {
new SimpleFactory().createProduct(1);
}
}
class Product{
private String name;
public Product(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} |
923b2ecd765c117d10e3ac302434aed9ccb92dd6 | 1,459 | java | Java | src/tierraMedia/soporte/Archivo.java | Kevin-Busy/tp-turismo-en-Tierramedia | 721bab25bd3d2cf05dde8c1596d25ac8af1fbbba | [
"MIT"
] | null | null | null | src/tierraMedia/soporte/Archivo.java | Kevin-Busy/tp-turismo-en-Tierramedia | 721bab25bd3d2cf05dde8c1596d25ac8af1fbbba | [
"MIT"
] | null | null | null | src/tierraMedia/soporte/Archivo.java | Kevin-Busy/tp-turismo-en-Tierramedia | 721bab25bd3d2cf05dde8c1596d25ac8af1fbbba | [
"MIT"
] | null | null | null | 26.053571 | 103 | 0.577793 | 999,487 | package tierraMedia.soporte;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
public class Archivo {
public static String DIRECTORIO = "";
public static void cambiarDirectorio (String camino) {
DIRECTORIO = camino;
}
public static String cargar(String nombreArchivo) {
String valor = "";
try {
//@-set-
String linea = "";
FileReader fs = new FileReader(DIRECTORIO + nombreArchivo);
BufferedReader reader = new BufferedReader(fs);
while((linea = reader.readLine()) != null)
valor += linea + ";";
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
return valor;
}
public static void salvar(String nombreArchivo, String Escribe) {
//@-set-
String[] valor = Escribe.split(";");
try {
//@-set-
BufferedWriter writer = new BufferedWriter(new FileWriter(DIRECTORIO + nombreArchivo));
for(int i = 0; i < valor.length; i++)
writer.write(valor[i] + "\n");
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public static void editar(String nombreArchivo, String Escribe) {
salvar(nombreArchivo, cargar(nombreArchivo) + Escribe);
}
}
|
923b2ee187dfa1e023209d9e65902eb8e7aa3ec8 | 748 | java | Java | src/main/java/kr/co/blossomedu/vocatest/users/controller/api/UserApiControllerAdvice.java | siyoon210/voca-test | 8958c3c64dc112c872cbba049a6ded81995800b8 | [
"MIT"
] | 1 | 2019-08-07T01:53:16.000Z | 2019-08-07T01:53:16.000Z | src/main/java/kr/co/blossomedu/vocatest/users/controller/api/UserApiControllerAdvice.java | siyoon210/voca-test | 8958c3c64dc112c872cbba049a6ded81995800b8 | [
"MIT"
] | null | null | null | src/main/java/kr/co/blossomedu/vocatest/users/controller/api/UserApiControllerAdvice.java | siyoon210/voca-test | 8958c3c64dc112c872cbba049a6ded81995800b8 | [
"MIT"
] | 1 | 2019-09-27T00:42:53.000Z | 2019-09-27T00:42:53.000Z | 39.368421 | 79 | 0.819519 | 999,488 | package kr.co.blossomedu.vocatest.users.controller.api;
import kr.co.blossomedu.vocatest.commons.ErrorMessage;
import kr.co.blossomedu.vocatest.commons.exception.CustomException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice(basePackageClasses = UserApiController.class)
public class UserApiControllerAdvice {
@ExceptionHandler({CustomException.class})
private ResponseEntity<ErrorMessage> handleException(Exception exception) {
ErrorMessage errorMessage = new ErrorMessage(exception.getMessage());
return ResponseEntity.badRequest().body(errorMessage);
}
}
|
923b2f07483ec9e29cc69593a77e307e1563d95a | 40,595 | java | Java | geode-cq/src/test/java/org/apache/geode/cache/query/cq/dunit/CqPerfDUnitTest.java | agingade/geode | 0f6e09c4a162dc2fec411e7c6267e9d1de8c697e | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2017-09-05T16:45:44.000Z | 2017-09-05T16:45:44.000Z | geode-cq/src/test/java/org/apache/geode/cache/query/cq/dunit/CqPerfDUnitTest.java | agingade/geode | 0f6e09c4a162dc2fec411e7c6267e9d1de8c697e | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | geode-cq/src/test/java/org/apache/geode/cache/query/cq/dunit/CqPerfDUnitTest.java | agingade/geode | 0f6e09c4a162dc2fec411e7c6267e9d1de8c697e | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 38.809751 | 100 | 0.676807 | 999,489 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.cq.dunit;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.query.CqAttributes;
import org.apache.geode.cache.query.CqAttributesFactory;
import org.apache.geode.cache.query.CqListener;
import org.apache.geode.cache.query.CqQuery;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.internal.DefaultQueryService;
import org.apache.geode.cache.query.internal.cq.CqService;
import org.apache.geode.cache.query.internal.cq.CqServiceImpl;
import org.apache.geode.cache.query.internal.cq.InternalCqQuery;
import org.apache.geode.cache.query.internal.cq.ServerCQImpl;
import org.apache.geode.cache30.CacheSerializableRunnable;
import org.apache.geode.cache30.CacheTestCase;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.Invoke;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.NetworkUtils;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.Wait;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.FlakyTest;
/**
* This class tests the ContiunousQuery mechanism in GemFire. This includes the test with diffetent
* data activities.
*/
@Category(DistributedTest.class)
public class CqPerfDUnitTest extends JUnit4CacheTestCase {
protected CqQueryDUnitTest cqDUnitTest = new CqQueryDUnitTest();
public CqPerfDUnitTest() {
super();
}
@Override
public final void postSetUp() throws Exception {
// avoid IllegalStateException from HandShake by connecting all vms tor
// system before creating connection pools
getSystem();
Invoke.invokeInEveryVM(new SerializableRunnable("getSystem") {
public void run() {
getSystem();
}
});
}
/**
* Tests the cq performance.
*
* @throws Exception
*/
@Ignore("perf")
@Test
public void testCQPerf() throws Exception {
final Host host = Host.getHost(0);
VM server = host.getVM(0);
VM client = host.getVM(1);
cqDUnitTest.createServer(server);
final int port = server.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server.getHost());
// Create client.
cqDUnitTest.createClient(client, port, host0);
final String cqName = "testCQPerf_0";
client.invoke(new CacheSerializableRunnable("Create CQ :" + cqName) {
public void run2() throws CacheException {
LogWriterUtils.getLogWriter().info("### Create CQ. ###" + cqName);
// Get CQ Service.
QueryService cqService = null;
try {
cqService = getCache().getQueryService();
} catch (Exception cqe) {
cqe.printStackTrace();
fail("Failed to getCQService.");
}
// Create CQ Attributes.
CqAttributesFactory cqf = new CqAttributesFactory();
CqListener[] cqListeners = {new CqTimeTestListener(LogWriterUtils.getLogWriter())};
((CqTimeTestListener) cqListeners[0]).cqName = cqName;
cqf.initCqListeners(cqListeners);
CqAttributes cqa = cqf.create();
// Create and Execute CQ.
try {
CqQuery cq1 = cqService.newCq(cqName, cqDUnitTest.cqs[0], cqa);
assertTrue("newCq() state mismatch", cq1.getState().isStopped());
cq1.execute();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("CqService is :" + cqService);
ex.printStackTrace();
AssertionError err = new AssertionError("Failed to create CQ " + cqName + " . ");
err.initCause(ex);
throw err;
}
}
});
final int size = 50;
// Create values.
cqDUnitTest.createValuesWithTime(client, cqDUnitTest.regions[0], size);
Wait.pause(5000);
// Update values
cqDUnitTest.createValuesWithTime(client, cqDUnitTest.regions[0], size);
client.invoke(new CacheSerializableRunnable("Validate CQs") {
public void run2() throws CacheException {
LogWriterUtils.getLogWriter().info("### Validating CQ. ### " + cqName);
// Get CQ Service.
QueryService cqService = null;
try {
cqService = getCache().getQueryService();
} catch (Exception cqe) {
cqe.printStackTrace();
fail("Failed to getCqService.");
}
CqQuery cQuery = cqService.getCq(cqName);
if (cQuery == null) {
fail("Failed to get CqQuery for CQ : " + cqName);
}
// CqAttributes cqAttr = cQuery.getCqAttributes();
// CqListener cqListeners[] = cqAttr.getCqListeners();
// CqTimeTestListener listener = (CqTimeTestListener) cqListeners[0];
// Wait for all the create to arrive.
// for (int i=1; i <= size; i++) {
// listener.waitForCreated(cqDUnitTest.KEY+i);
// }
// Wait for all the update to arrive.
// for (int i=1; i <= size; i++) {
// listener.waitForUpdated(cqDUnitTest.KEY+i);
// }
// getLogWriter().info("### Time taken for Creation of " + size + " events is :" +
// listener.getTotalQueryCreateTime());
// getLogWriter().info("### Time taken for Update of " + size + " events is :" +
// listener.getTotalQueryUpdateTime());
}
});
Wait.pause(10 * 60 * 1000);
// Close.
cqDUnitTest.closeClient(client);
cqDUnitTest.closeServer(server);
}
/**
* Test for maintaining keys for update optimization.
*
* @throws Exception
*/
@Test
public void testKeyMaintainance() throws Exception {
final Host host = Host.getHost(0);
VM server = host.getVM(0);
VM client = host.getVM(1);
cqDUnitTest.createServer(server);
final int port = server.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server.getHost());
cqDUnitTest.createClient(client, port, host0);
// HashSet for caching purpose will be created for cqs.
final int cqSize = 2;
// Cq1
cqDUnitTest.createCQ(client, "testKeyMaintainance_0", cqDUnitTest.cqs[0]);
cqDUnitTest.executeCQ(client, "testKeyMaintainance_0", false, null);
// Cq2
cqDUnitTest.createCQ(client, "testKeyMaintainance_1", cqDUnitTest.cqs[10]);
cqDUnitTest.executeCQ(client, "testKeyMaintainance_1", false, null);
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], 1);
cqDUnitTest.waitForCreated(client, "testKeyMaintainance_0", CqQueryDUnitTest.KEY + 1);
// Entry is made into the CQs cache hashset.
// testKeyMaintainance_0 with 1 entry and testKeyMaintainance_1 with 0
server.invoke(new CacheSerializableRunnable("LookForCachedEventKeys1") {
public void run2() throws CacheException {
CqService cqService = null;
try {
cqService = ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
Collection<? extends InternalCqQuery> cqs = cqService.getAllCqs();
for (InternalCqQuery cq : cqs) {
ServerCQImpl cqQuery = (ServerCQImpl) cq;
String serverCqName = (String) cqQuery.getServerCqName();
if (serverCqName.startsWith("testKeyMaintainance_0")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_0 is wrong.", 1,
cqQuery.getCqResultKeysSize());
} else if (serverCqName.startsWith("testKeyMaintainance_1")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_1 is wrong.", 0,
cqQuery.getCqResultKeysSize());
}
}
}
});
// Update 1.
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], 10);
cqDUnitTest.waitForCreated(client, "testKeyMaintainance_0", CqQueryDUnitTest.KEY + 10);
// Entry/check is made into the CQs cache hashset.
// testKeyMaintainance_0 with 1 entry and testKeyMaintainance_1 with 1
server.invoke(new CacheSerializableRunnable("LookForCachedEventKeysAfterUpdate1") {
public void run2() throws CacheException {
CqService cqService = null;
try {
cqService = ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
Collection<? extends InternalCqQuery> cqs = cqService.getAllCqs();
for (InternalCqQuery cq : cqs) {
ServerCQImpl cqQuery = (ServerCQImpl) cq;
String serverCqName = (String) cqQuery.getServerCqName();
if (serverCqName.startsWith("testKeyMaintainance_0")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_0 is wrong.", 10,
cqQuery.getCqResultKeysSize());
} else if (serverCqName.startsWith("testKeyMaintainance_1")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_1 is wrong.", 5,
cqQuery.getCqResultKeysSize());
}
}
}
});
// Update.
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], 12);
cqDUnitTest.waitForCreated(client, "testKeyMaintainance_0", CqQueryDUnitTest.KEY + 12);
// Entry/check is made into the CQs cache hashset.
// testKeyMaintainance_0 with 1 entry and testKeyMaintainance_1 with 1
server.invoke(new CacheSerializableRunnable("LookForCachedEventKeysAfterUpdate2") {
public void run2() throws CacheException {
CqService cqService = null;
try {
cqService = ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
Collection<? extends InternalCqQuery> cqs = cqService.getAllCqs();
for (InternalCqQuery cq : cqs) {
ServerCQImpl cqQuery = (ServerCQImpl) cq;
String serverCqName = (String) cqQuery.getServerCqName();
if (serverCqName.startsWith("testKeyMaintainance_0")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_0 is wrong.", 12,
cqQuery.getCqResultKeysSize());
} else if (serverCqName.startsWith("testKeyMaintainance_1")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_1 is wrong.", 6,
cqQuery.getCqResultKeysSize());
}
}
}
});
// Delete.
cqDUnitTest.deleteValues(server, cqDUnitTest.regions[0], 6);
cqDUnitTest.waitForDestroyed(client, "testKeyMaintainance_0", CqQueryDUnitTest.KEY + 6);
// Entry/check is made into the CQs cache hashset.
// testKeyMaintainance_0 with 1 entry and testKeyMaintainance_1 with 1
server.invoke(new CacheSerializableRunnable("LookForCachedEventKeysAfterUpdate2") {
public void run2() throws CacheException {
CqService cqService = null;
try {
cqService = ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
Collection<? extends InternalCqQuery> cqs = cqService.getAllCqs();
for (InternalCqQuery cq : cqs) {
ServerCQImpl cqQuery = (ServerCQImpl) cq;
String serverCqName = (String) cqQuery.getServerCqName();
if (serverCqName.startsWith("testKeyMaintainance_0")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_0 is wrong.", 6,
cqQuery.getCqResultKeysSize());
} else if (serverCqName.startsWith("testKeyMaintainance_1")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_1 is wrong.", 3,
cqQuery.getCqResultKeysSize());
}
}
}
});
// Stop CQ.
// This should still needs to process the events so that Results are up-to-date.
cqDUnitTest.stopCQ(client, "testKeyMaintainance_1");
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], 12);
server.invoke(new CacheSerializableRunnable("LookForCachedEventKeysAfterUpdate2") {
public void run2() throws CacheException {
CqService cqService = null;
try {
cqService = ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
Collection<? extends InternalCqQuery> cqs = cqService.getAllCqs();
for (InternalCqQuery cq : cqs) {
ServerCQImpl cqQuery = (ServerCQImpl) cq;
String serverCqName = (String) cqQuery.getServerCqName();
if (serverCqName.startsWith("testKeyMaintainance_0")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_0 is wrong.", 12,
cqQuery.getCqResultKeysSize());
} else if (serverCqName.startsWith("testKeyMaintainance_1")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_1 is wrong.", 6,
cqQuery.getCqResultKeysSize());
}
}
}
});
// re-start the CQ.
cqDUnitTest.executeCQ(client, "testKeyMaintainance_1", false, null);
// This will remove the caching for this CQ.
cqDUnitTest.closeCQ(client, "testKeyMaintainance_1");
server.invoke(new CacheSerializableRunnable("LookForCachedEventKeysAfterUpdate2") {
public void run2() throws CacheException {
CqService cqService = null;
try {
cqService = ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
Collection<? extends InternalCqQuery> cqs = cqService.getAllCqs();
for (InternalCqQuery cq : cqs) {
ServerCQImpl cqQuery = (ServerCQImpl) cq;
String serverCqName = (String) cqQuery.getServerCqName();
if (serverCqName.startsWith("testKeyMaintainance_0")) {
assertEquals("The number of keys cached for cq testKeyMaintainance_0 is wrong.", 12,
cqQuery.getCqResultKeysSize());
} else if (serverCqName.startsWith("testKeyMaintainance_1")) {
fail("The key maintainance should not be present for this CQ.");
}
}
}
});
// Close.
cqDUnitTest.closeClient(client);
cqDUnitTest.closeServer(server);
}
/**
* Test for common CQs. To test the changes relating to, executing CQ only once for all similar
* CQs.
*
* @throws Exception
*/
@Category(FlakyTest.class) // GEODE-1164: random ports, thread sleeps, time sensitive, eats
// exceptions (fixed 1), async behavior
@Test
public void testMatchingCqs() throws Exception {
final Host host = Host.getHost(0);
VM server = host.getVM(0);
VM client = host.getVM(1);
cqDUnitTest.createServer(server);
final int port = server.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server.getHost());
cqDUnitTest.createClient(client, port, host0);
// Create and Execute same kind of CQs.
for (int i = 0; i < 4; i++) {
cqDUnitTest.createCQ(client, "testMatchingCqs_" + i, cqDUnitTest.cqs[0]);
cqDUnitTest.executeCQ(client, "testMatchingCqs_" + i, false, null);
}
validateMatchingCqs(server, 1, cqDUnitTest.cqs[0], 4);
int size = 1;
// Create.
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
cqDUnitTest.waitForCreated(client, "testMatchingCqs_0", CqQueryDUnitTest.KEY + size);
cqDUnitTest.waitForCreated(client, "testMatchingCqs_3", CqQueryDUnitTest.KEY + size);
// Close one of the CQ.
cqDUnitTest.closeCQ(client, "testMatchingCqs_0");
validateMatchingCqs(server, 1, cqDUnitTest.cqs[0], 3);
// Update.
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
cqDUnitTest.waitForUpdated(client, "testMatchingCqs_3", CqQueryDUnitTest.KEY + size);
// Stop one of the CQ.
cqDUnitTest.stopCQ(client, "testMatchingCqs_1");
validateMatchingCqs(server, 1, cqDUnitTest.cqs[0], 2);
// Update - 2.
cqDUnitTest.clearCQListenerEvents(client, "testMatchingCqs_3");
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
cqDUnitTest.waitForUpdated(client, "testMatchingCqs_3", CqQueryDUnitTest.KEY + size);
// stopped CQ should not receive 2nd/previous updates.
cqDUnitTest.validateCQ(client, "testMatchingCqs_1", /* resultSize: */ CqQueryDUnitTest.noTest,
/* creates: */ size, /* updates: once */ size, /* deletes; */ 0, /* queryInserts: */ size,
/* queryUpdates: */ size, /* queryDeletes: */ 0, /* totalEvents: */ size * 2);
// Execute the stopped CQ.
cqDUnitTest.executeCQ(client, "testMatchingCqs_1", false, null);
// Update - 3.
cqDUnitTest.clearCQListenerEvents(client, "testMatchingCqs_3");
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
cqDUnitTest.waitForUpdated(client, "testMatchingCqs_3", CqQueryDUnitTest.KEY + size);
cqDUnitTest.validateCQ(client, "testMatchingCqs_1", /* resultSize: */ CqQueryDUnitTest.noTest,
/* creates: */ size, /* updates: 2 */ size * 2, /* deletes; */ 0, /* queryInserts: */ size,
/* queryUpdates: */ size * 2, /* queryDeletes: */ 0, /* totalEvents: */ size * 3);
// Create different kind of CQs.
cqDUnitTest.createCQ(client, "testMatchingCqs_4", cqDUnitTest.cqs[1]);
cqDUnitTest.executeCQ(client, "testMatchingCqs_4", false, null);
cqDUnitTest.createCQ(client, "testMatchingCqs_5", cqDUnitTest.cqs[1]);
cqDUnitTest.executeCQ(client, "testMatchingCqs_5", false, null);
cqDUnitTest.createCQ(client, "testMatchingCqs_6", cqDUnitTest.cqs[2]);
cqDUnitTest.executeCQ(client, "testMatchingCqs_6", false, null);
validateMatchingCqs(server, 3, cqDUnitTest.cqs[1], 2);
cqDUnitTest.closeCQ(client, "testMatchingCqs_6");
validateMatchingCqs(server, 2, cqDUnitTest.cqs[1], 2);
cqDUnitTest.closeCQ(client, "testMatchingCqs_5");
cqDUnitTest.closeCQ(client, "testMatchingCqs_4");
cqDUnitTest.closeCQ(client, "testMatchingCqs_3");
cqDUnitTest.closeCQ(client, "testMatchingCqs_2");
cqDUnitTest.closeCQ(client, "testMatchingCqs_1");
validateMatchingCqs(server, 0, null, 0);
// update 4
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
// Close.
cqDUnitTest.closeClient(client);
cqDUnitTest.closeServer(server);
}
/**
* Test for common CQs. To test the changes relating to, executing CQ only once for all similar
* CQs.
*
* @throws Exception
*/
@Test
public void testMatchingCQWithMultipleClients() throws Exception {
final Host host = Host.getHost(0);
VM server = host.getVM(0);
VM client1 = host.getVM(1);
VM client2 = host.getVM(2);
VM client3 = host.getVM(3);
VM clients[] = new VM[] {client1, client2, client3};
cqDUnitTest.createServer(server);
final int port = server.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server.getHost());
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.createClient(clients[clientIndex], port, host0);
// Create and Execute same kind of CQs.
for (int i = 0; i < 4; i++) {
cqDUnitTest.createCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_" + i,
cqDUnitTest.cqs[0]);
cqDUnitTest.executeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_" + i, false,
null);
}
}
validateMatchingCqs(server, 1, cqDUnitTest.cqs[0], clients.length * 4);
int size = 1;
// Create.
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.waitForCreated(clients[clientIndex], "testMatchingCQWithMultipleClients_0",
CqQueryDUnitTest.KEY + size);
cqDUnitTest.waitForCreated(clients[clientIndex], "testMatchingCQWithMultipleClients_3",
CqQueryDUnitTest.KEY + size);
}
// Close one of the CQ.
cqDUnitTest.closeCQ(client1, "testMatchingCQWithMultipleClients_0");
validateMatchingCqs(server, 1, cqDUnitTest.cqs[0], (clients.length * 4) - 1);
// Update.
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.waitForUpdated(clients[clientIndex], "testMatchingCQWithMultipleClients_3",
CqQueryDUnitTest.KEY + size);
}
// Stop one of the CQ.
cqDUnitTest.stopCQ(client2, "testMatchingCQWithMultipleClients_1");
validateMatchingCqs(server, 1, cqDUnitTest.cqs[0], (clients.length * 4) - 2);
// Update - 2.
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.clearCQListenerEvents(clients[clientIndex],
"testMatchingCQWithMultipleClients_3");
}
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.waitForUpdated(clients[clientIndex], "testMatchingCQWithMultipleClients_3",
CqQueryDUnitTest.KEY + size);
}
// stopped CQ should not receive 2nd/previous updates.
cqDUnitTest.validateCQ(client2, "testMatchingCQWithMultipleClients_1",
/* resultSize: */ CqQueryDUnitTest.noTest, /* creates: */ size, /* updates: once */ size,
/* deletes; */ 0, /* queryInserts: */ size, /* queryUpdates: */ size, /* queryDeletes: */ 0,
/* totalEvents: */ size * 2);
// Execute the stopped CQ.
cqDUnitTest.executeCQ(client2, "testMatchingCQWithMultipleClients_1", false, null);
// Update - 3.
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.clearCQListenerEvents(clients[clientIndex],
"testMatchingCQWithMultipleClients_3");
}
validateMatchingCqs(server, 1, cqDUnitTest.cqs[0], (clients.length * 4) - 1);
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.waitForUpdated(clients[clientIndex], "testMatchingCQWithMultipleClients_3",
CqQueryDUnitTest.KEY + size);
}
cqDUnitTest.validateCQ(client2, "testMatchingCQWithMultipleClients_1",
/* resultSize: */ CqQueryDUnitTest.noTest, /* creates: */ size, /* updates: 2 */ size * 2,
/* deletes; */ 0, /* queryInserts: */ size, /* queryUpdates: */ size * 2,
/* queryDeletes: */ 0, /* totalEvents: */ size * 3);
// Create different kind of CQs.
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.createCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_4",
cqDUnitTest.cqs[1]);
cqDUnitTest.executeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_4", false,
null);
cqDUnitTest.createCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_5",
cqDUnitTest.cqs[1]);
cqDUnitTest.executeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_5", false,
null);
cqDUnitTest.createCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_6",
cqDUnitTest.cqs[2]);
cqDUnitTest.executeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_6", false,
null);
}
validateMatchingCqs(server, 3, cqDUnitTest.cqs[1], 2 * clients.length);
for (int clientIndex = 0; clientIndex < 3; clientIndex++) {
cqDUnitTest.closeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_6");
}
validateMatchingCqs(server, 2, cqDUnitTest.cqs[1], 2 * clients.length);
// update 4
cqDUnitTest.createValues(server, cqDUnitTest.regions[0], size);
// Close.
cqDUnitTest.closeClient(client3);
validateMatchingCqs(server, 2, cqDUnitTest.cqs[1], 2 * (clients.length - 1));
for (int clientIndex = 0; clientIndex < 2; clientIndex++) {
cqDUnitTest.closeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_5");
cqDUnitTest.closeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_4");
cqDUnitTest.closeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_3");
cqDUnitTest.closeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_2");
cqDUnitTest.closeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_1");
if (clientIndex != 0) {
cqDUnitTest.closeCQ(clients[clientIndex], "testMatchingCQWithMultipleClients_0");
}
}
validateMatchingCqs(server, 0, null, 0);
cqDUnitTest.closeClient(client2);
cqDUnitTest.closeClient(client1);
cqDUnitTest.closeServer(server);
}
@Test
public void testMatchingCQsWithMultipleServers() throws Exception {
final Host host = Host.getHost(0);
VM server1 = host.getVM(0);
VM server2 = host.getVM(1);
VM client1 = host.getVM(2);
VM client2 = host.getVM(3);
cqDUnitTest.createServer(server1);
VM clients[] = new VM[] {client1, client2};
final int port1 = server1.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server1.getHost());
// Create client.
// Create client with redundancyLevel -1
final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(1);
cqDUnitTest.createClient(client1, new int[] {port1, ports[0]}, host0, "-1");
cqDUnitTest.createClient(client2, new int[] {port1, ports[0]}, host0, "-1");
int numCQs = 3;
for (int i = 0; i < numCQs; i++) {
cqDUnitTest.createCQ(client1, "testMatchingCQsWithMultipleServers_" + i, cqDUnitTest.cqs[i]);
cqDUnitTest.executeCQ(client1, "testMatchingCQsWithMultipleServers_" + i, false, null);
cqDUnitTest.createCQ(client2, "testMatchingCQsWithMultipleServers_" + i, cqDUnitTest.cqs[i]);
cqDUnitTest.executeCQ(client2, "testMatchingCQsWithMultipleServers_" + i, false, null);
}
validateMatchingCqs(server1, numCQs, cqDUnitTest.cqs[0], 1 * clients.length);
validateMatchingCqs(server1, numCQs, cqDUnitTest.cqs[1], 1 * clients.length);
Wait.pause(1 * 1000);
// CREATE.
cqDUnitTest.createValues(server1, cqDUnitTest.regions[0], 10);
cqDUnitTest.createValues(server1, cqDUnitTest.regions[1], 10);
for (int i = 1; i <= 10; i++) {
cqDUnitTest.waitForCreated(client1, "testMatchingCQsWithMultipleServers_0",
CqQueryDUnitTest.KEY + i);
}
cqDUnitTest.createServer(server2, ports[0]);
final int port2 = server2.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
System.out
.println("### Port on which server1 running : " + port1 + " Server2 running : " + port2);
// UPDATE - 1.
for (int k = 0; k < numCQs; k++) {
cqDUnitTest.clearCQListenerEvents(client1, "testMatchingCQsWithMultipleServers_" + k);
cqDUnitTest.clearCQListenerEvents(client2, "testMatchingCQsWithMultipleServers_" + k);
}
cqDUnitTest.createValues(server1, cqDUnitTest.regions[0], 10);
cqDUnitTest.createValues(server1, cqDUnitTest.regions[1], 10);
// Wait for updates on regions[0]
for (int i = 1; i <= 10; i++) {
cqDUnitTest.waitForUpdated(client1, "testMatchingCQsWithMultipleServers_0",
CqQueryDUnitTest.KEY + i);
cqDUnitTest.waitForUpdated(client2, "testMatchingCQsWithMultipleServers_0",
CqQueryDUnitTest.KEY + i);
}
// Wait for updates on regions[1] - Waiting for last key is good enough.
cqDUnitTest.waitForUpdated(client1, "testMatchingCQsWithMultipleServers_2",
CqQueryDUnitTest.KEY + 4);
cqDUnitTest.waitForUpdated(client2, "testMatchingCQsWithMultipleServers_2",
CqQueryDUnitTest.KEY + 4);
int[] resultsCnt = new int[] {10, 1, 2};
for (int i = 0; i < numCQs; i++) {
cqDUnitTest.validateCQ(client1, "testMatchingCQsWithMultipleServers_" + i,
CqQueryDUnitTest.noTest, resultsCnt[i], resultsCnt[i], CqQueryDUnitTest.noTest);
cqDUnitTest.validateCQ(client2, "testMatchingCQsWithMultipleServers_" + i,
CqQueryDUnitTest.noTest, resultsCnt[i], resultsCnt[i], CqQueryDUnitTest.noTest);
}
cqDUnitTest.closeClient(client2);
cqDUnitTest.closeServer(server2);
}
@Test
public void testFailOverMatchingCQsWithMultipleServers() throws Exception {
final Host host = Host.getHost(0);
VM server1 = host.getVM(0);
VM server2 = host.getVM(1);
VM client1 = host.getVM(2);
VM client2 = host.getVM(3);
cqDUnitTest.createServer(server1);
VM clients[] = new VM[] {client1, client2};
final int port1 = server1.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server1.getHost());
// Create client.
// Create client with redundancyLevel -1
final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(1);
cqDUnitTest.createClient(client1, new int[] {port1, ports[0]}, host0, "-1");
cqDUnitTest.createClient(client2, new int[] {port1, ports[0]}, host0, "-1");
int numCQs = 3;
for (int i = 0; i < numCQs; i++) {
cqDUnitTest.createCQ(client1, "testMatchingCQsWithMultipleServers_" + i, cqDUnitTest.cqs[i]);
cqDUnitTest.executeCQ(client1, "testMatchingCQsWithMultipleServers_" + i, false, null);
cqDUnitTest.createCQ(client2, "testMatchingCQsWithMultipleServers_" + i, cqDUnitTest.cqs[i]);
cqDUnitTest.executeCQ(client2, "testMatchingCQsWithMultipleServers_" + i, false, null);
}
validateMatchingCqs(server1, numCQs, cqDUnitTest.cqs[0], 1 * clients.length);
validateMatchingCqs(server1, numCQs, cqDUnitTest.cqs[1], 1 * clients.length);
cqDUnitTest.createServer(server2, ports[0]);
// Close server1.
cqDUnitTest.closeServer(server1);
validateMatchingCqs(server2, numCQs, cqDUnitTest.cqs[0], clients.length);
// Close.
cqDUnitTest.closeClient(client1);
validateMatchingCqs(server2, numCQs, cqDUnitTest.cqs[0], (clients.length - 1));
cqDUnitTest.closeClient(client2);
cqDUnitTest.closeServer(server2);
}
/**
* Test for CQ Fail over.
*
* @throws Exception
*/
@Test
public void testMatchingCQsOnDataNodeWithMultipleServers() throws Exception {
final Host host = Host.getHost(0);
VM server1 = host.getVM(0);
VM server2 = host.getVM(1);
VM client1 = host.getVM(2);
VM client2 = host.getVM(3);
cqDUnitTest.createServerOnly(server1, 0);
cqDUnitTest.createServerOnly(server2, 0);
cqDUnitTest.createPartitionRegion(server1, cqDUnitTest.regions);
cqDUnitTest.createPartitionRegion(server2, cqDUnitTest.regions);
VM clients[] = new VM[] {client1, client2};
final int port1 = server1.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server1.getHost());
final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(1);
cqDUnitTest.createLocalRegion(client1, new int[] {port1, ports[0]}, host0, "-1",
cqDUnitTest.regions);
cqDUnitTest.createLocalRegion(client2, new int[] {port1, ports[0]}, host0, "-1",
cqDUnitTest.regions);
int numCQs = cqDUnitTest.prCqs.length;
for (int i = 0; i < numCQs; i++) {
cqDUnitTest.createCQ(client1, "testMatchingCQsWithMultipleServers_" + i,
cqDUnitTest.prCqs[i]);
cqDUnitTest.executeCQ(client1, "testMatchingCQsWithMultipleServers_" + i, false, null);
cqDUnitTest.createCQ(client2, "testMatchingCQsWithMultipleServers_" + i,
cqDUnitTest.prCqs[i]);
cqDUnitTest.executeCQ(client2, "testMatchingCQsWithMultipleServers_" + i, false, null);
}
validateMatchingCqs(server1, numCQs, cqDUnitTest.prCqs[0], 1 * clients.length);
validateMatchingCqs(server1, numCQs, cqDUnitTest.prCqs[1], 1 * clients.length);
validateMatchingCqs(server2, numCQs, cqDUnitTest.prCqs[0], 1 * clients.length);
validateMatchingCqs(server2, numCQs, cqDUnitTest.prCqs[1], 1 * clients.length);
// Close.
cqDUnitTest.closeClient(client1);
cqDUnitTest.closeClient(client2);
cqDUnitTest.closeServer(server1);
cqDUnitTest.closeServer(server2);
}
/**
* Performance test for Matching CQ optimization changes.
*
* @throws Exception
*/
@Ignore("perf")
@Test
public void testPerformanceForMatchingCQs() throws Exception {
final Host host = Host.getHost(0);
VM server1 = host.getVM(0);
VM server2 = host.getVM(1);
VM client1 = host.getVM(2);
VM client2 = host.getVM(3);
cqDUnitTest.createServer(server1);
cqDUnitTest.createServer(server2);
// VM clients[] = new VM[]{client1, client2};
final int port1 = server1.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final int port2 = server2.invoke(() -> CqQueryDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(server1.getHost());
// Create client.
// final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(1);
// Client1 connects to server1.
cqDUnitTest.createClient(client1, new int[] {port1}, host0, "-1");
// Client2 connects to server2.
cqDUnitTest.createClient(client2, new int[] {port2}, host0, "-1");
// Client1 registers matching CQs on server1.
boolean uniqueQueries = false;
String[] matchingCqs = this.generateCqQueries(uniqueQueries);
for (int i = 0; i < matchingCqs.length; i++) {
cqDUnitTest.createCQ(client1, "testPerformanceForMatchingCQs_" + i, matchingCqs[i]);
cqDUnitTest.executeCQ(client1, "testPerformanceForMatchingCQs_" + i, false, null);
}
// Client2 registers non-matching CQs on server2.
uniqueQueries = true;
matchingCqs = this.generateCqQueries(uniqueQueries);
for (int i = 0; i < matchingCqs.length; i++) {
cqDUnitTest.createCQ(client2, "testPerformanceForMatchingCQs_" + i, matchingCqs[i]);
cqDUnitTest.executeCQ(client2, "testPerformanceForMatchingCQs_" + i, false, null);
}
Wait.pause(1 * 1000);
// CREATE.
int size = 1000;
cqDUnitTest.createValues(server1, cqDUnitTest.regions[0], size);
cqDUnitTest.createValues(server2, cqDUnitTest.regions[1], size);
// Update couple of times;
for (int j = 0; j < 5; j++) {
cqDUnitTest.createValues(server1, cqDUnitTest.regions[0], size - 1);
cqDUnitTest.createValues(server2, cqDUnitTest.regions[1], size - 1);
}
for (int j = 0; j < 4; j++) {
cqDUnitTest.createValues(server2, cqDUnitTest.regions[0], size - 1);
cqDUnitTest.createValues(server1, cqDUnitTest.regions[1], size - 1);
}
// Update the last key.
cqDUnitTest.createValues(server2, cqDUnitTest.regions[0], size);
cqDUnitTest.createValues(server1, cqDUnitTest.regions[1], size);
for (int k = 1; k <= size; k++) {
cqDUnitTest.waitForUpdated(client1, "testPerformanceForMatchingCQs_0",
CqQueryDUnitTest.KEY + k);
}
Wait.pause(1 * 1000);
printCqQueryExecutionTime(server1);
printCqQueryExecutionTime(server2);
// Close.
cqDUnitTest.closeClient(client1);
cqDUnitTest.closeClient(client2);
cqDUnitTest.closeServer(server2);
cqDUnitTest.closeServer(server1);
}
public void validateMatchingCqs(VM server, final int mapSize, final String query,
final int numCqSize) {
server.invoke(new CacheSerializableRunnable("validateMatchingCqs") {
public void run2() throws CacheException {
CqServiceImpl cqService = null;
try {
cqService =
(CqServiceImpl) ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
Map matchedCqMap = cqService.getMatchingCqMap();
assertEquals("The number of matched cq is not as expected.", mapSize, matchedCqMap.size());
if (query != null) {
if (!matchedCqMap.containsKey(query)) {
fail("Query not found in the matched cq map. Query:" + query);
}
Collection cqs = (Collection) matchedCqMap.get(query);
assertEquals("Number of matched cqs are not equal to the expected matched cqs", numCqSize,
cqs.size());
}
}
});
}
public void printCqQueryExecutionTime(VM server) {
server.invoke(new CacheSerializableRunnable("printCqQueryExecutionTime") {
public void run2() throws CacheException {
CqServiceImpl cqService = null;
try {
cqService =
(CqServiceImpl) ((DefaultQueryService) getCache().getQueryService()).getCqService();
} catch (Exception ex) {
LogWriterUtils.getLogWriter().info("Failed to get the internal CqService.", ex);
Assert.fail("Failed to get the internal CqService.", ex);
}
long timeTaken = cqService.getCqServiceVsdStats().getCqQueryExecutionTime();
LogWriterUtils.getLogWriter().info("Total Time taken to Execute CQ Query :" + timeTaken);
// System.out.println("Total Time taken to Execute CQ Query :" + timeTaken);
}
});
}
public String[] generateCqQueries(boolean uniqueQueries) {
ArrayList initQueries = new ArrayList();
// From Portfolio object.
String[] names = {"aaa", "bbb", "ccc", "ddd"};
int nameIndex = 0;
// Construct few unique Queries.
for (int i = 0; i < 3; i++) {
for (int cnt = 0; cnt < 5; cnt++) {
String query = cqDUnitTest.cqs[i];
if (cnt > 0) {
nameIndex = (cnt % names.length);
query += " or p.names[" + nameIndex + "] = '" + names[nameIndex] + cnt + "'";
}
initQueries.add(query);
}
}
int numMatchedQueries = 10;
ArrayList cqQueries = new ArrayList();
Iterator iter = initQueries.iterator();
while (iter.hasNext()) {
String query = (String) iter.next();
for (int cnt = 0; cnt < numMatchedQueries; cnt++) {
if (uniqueQueries) {
// Append blank string, so that query string is different but the
// Query constraint remains same.
query += " ";
}
cqQueries.add(query);
}
}
String[] queries = new String[cqQueries.size()];
cqQueries.toArray(queries);
return queries;
}
}
|
923b2fef5fb976d541b9e4eae4d68a314d840930 | 863 | java | Java | Assignments/2019_Fall/04_Assignment/RandomWalker.java | USMC1941/CS111-Rutgers | 9eb1e7608fa1a394dc5997bf4b8e36fa86006054 | [
"MIT"
] | 10 | 2018-01-06T00:09:48.000Z | 2021-09-10T17:06:03.000Z | Assignments/2019_Fall/04_Assignment/RandomWalker.java | rosalogia/CS111-Rutgers | 8ea8f8e4ffe003901e2c63075438131337ce0e68 | [
"MIT"
] | null | null | null | Assignments/2019_Fall/04_Assignment/RandomWalker.java | rosalogia/CS111-Rutgers | 8ea8f8e4ffe003901e2c63075438131337ce0e68 | [
"MIT"
] | 6 | 2019-09-09T00:49:56.000Z | 2021-07-29T23:13:28.000Z | 23.972222 | 75 | 0.507532 | 999,490 | /*************************************************************************
* Compilation: javac RandomWalker.java
* Execution: java RandomWalker 10
*
* @author:
*
* The program RandomWalker that takes an int command-line argument n
* and simulates the motion of a random walk for n steps. Print the
* location at each step (including the starting point), treating the
* starting point as the origin (0, 0). Also, print the square of the
* final Euclidean distance from the origin.
*
* % java RandomWalker 10
* (0,0)
* (-1,0)
* (-1,-1)
* (-1,-2)
* (-1,-3)
* (-1,-4)
* (-1,-5)
* (0,-5)
* (-1,-5)
* (-2,-5)
* (-2,-4)
* Squared distance = 20.0
*
*************************************************************************/
public class RandomWalker {
public static void main(String[] args) {
// WRITE YOUR CODE HERE
}
}
|
923b30698da9553e6b608aac129864cce4407c1a | 1,076 | java | Java | src/main/java/io/rancher/service/RegisterService.java | cloudatio/rancher-java-sdk | 95401486500f2dc543d1871df6d65904da0bf289 | [
"Apache-2.0"
] | 37 | 2016-02-03T14:09:29.000Z | 2022-03-06T10:28:51.000Z | src/main/java/io/rancher/service/RegisterService.java | cloudatio/rancher-java-sdk | 95401486500f2dc543d1871df6d65904da0bf289 | [
"Apache-2.0"
] | 5 | 2016-06-27T16:09:16.000Z | 2019-02-27T07:56:39.000Z | src/main/java/io/rancher/service/RegisterService.java | cloudatio/rancher-java-sdk | 95401486500f2dc543d1871df6d65904da0bf289 | [
"Apache-2.0"
] | 25 | 2016-04-23T11:48:13.000Z | 2022-03-22T09:07:51.000Z | 25.023256 | 78 | 0.738848 | 999,491 | package io.rancher.service;
import io.rancher.base.Filters;
import io.rancher.base.TypeCollection;
import io.rancher.type.Register;
import io.rancher.type.InstanceStop;
import io.rancher.type.Instance;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
public interface RegisterService {
@GET("register")
Call<TypeCollection<Register>> list();
@GET("register")
Call<TypeCollection<Register>> list(@QueryMap Filters filters);
@GET("register/{id}")
Call<Register> get(@Path("id") String id);
@POST("register")
Call<Register> create(@Body Register register);
@PUT("register/{id}")
Call<Register> update(@Path("id") String id, @Body Register register);
@DELETE("register/{id}")
Call<Response> delete(@Path("id") String id);
@POST("register/{id}?action=stop")
Call<Instance> stop(@Path("id") String id, @Body InstanceStop instanceStop);
}
|
923b308bf4db5e3af06c6522319d46626c25bbd2 | 1,676 | java | Java | unify-core/src/main/java/com/tcdng/unify/core/business/internal/ProxyBusinessServiceMethodRelay.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 5 | 2019-01-06T21:32:02.000Z | 2021-09-26T04:13:49.000Z | unify-core/src/main/java/com/tcdng/unify/core/business/internal/ProxyBusinessServiceMethodRelay.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 5 | 2020-01-02T11:09:48.000Z | 2021-05-03T12:12:53.000Z | unify-core/src/main/java/com/tcdng/unify/core/business/internal/ProxyBusinessServiceMethodRelay.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 3 | 2020-04-07T11:20:04.000Z | 2021-01-15T17:37:28.000Z | 32.862745 | 81 | 0.683771 | 999,492 | /*
* Copyright 2018-2020 The Code Department.
*
* 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.tcdng.unify.core.business.internal;
import com.tcdng.unify.core.UnifyComponent;
import com.tcdng.unify.core.UnifyException;
import com.tcdng.unify.core.annotation.Expirable;
import com.tcdng.unify.core.annotation.Taskable;
/**
* Proxy business service method information relay.
*
* @author Lateef
* @since 1.0
*/
public interface ProxyBusinessServiceMethodRelay extends UnifyComponent {
/**
* Returns taskable annotation for method with supplied signature if found.
*
* @param signature
* the supplied signature
* @throws UnifyException
* if an error occur
*/
Taskable getTaskable(String signature) throws UnifyException;
/**
* Returns expirable annotation for method with supplied signature if found.
*
* @param signature
* the supplied signature
* @throws UnifyException
* if an error occur
*/
Expirable getExpirable(String signature) throws UnifyException;
}
|
923b30e6a910bb6e1242e4f8a03e8d7380af7aaa | 2,411 | java | Java | nabl2.solver/src/main/java/mb/nabl2/solver/ISolution.java | MeAmAnUsername/nabl | 0e81e5efc07a7edf7c919a00c880b02dca302121 | [
"Apache-2.0"
] | 8 | 2016-01-19T15:17:02.000Z | 2021-12-20T12:10:48.000Z | nabl2.solver/src/main/java/mb/nabl2/solver/ISolution.java | MeAmAnUsername/nabl | 0e81e5efc07a7edf7c919a00c880b02dca302121 | [
"Apache-2.0"
] | 57 | 2015-04-25T19:51:10.000Z | 2022-03-24T11:48:05.000Z | nabl2.solver/src/main/java/mb/nabl2/solver/ISolution.java | MeAmAnUsername/nabl | 0e81e5efc07a7edf7c919a00c880b02dca302121 | [
"Apache-2.0"
] | 12 | 2016-06-15T12:18:33.000Z | 2022-02-15T08:34:04.000Z | 33.027397 | 100 | 0.785566 | 999,493 | package mb.nabl2.solver;
import java.util.Map;
import com.google.common.collect.Multimap;
import mb.nabl2.constraints.IConstraint;
import mb.nabl2.relations.variants.IVariantRelation;
import mb.nabl2.solver.messages.IMessages;
import mb.nabl2.solver.messages.Messages;
import mb.nabl2.symbolic.ISymbolicConstraints;
import mb.nabl2.terms.ITerm;
import mb.nabl2.terms.stratego.TermIndex;
import mb.nabl2.terms.unification.u.IUnifier;
import mb.nabl2.util.collections.IProperties;
import mb.scopegraph.pepm16.esop15.IEsopNameResolution;
import mb.scopegraph.pepm16.esop15.IEsopScopeGraph;
import mb.scopegraph.pepm16.terms.Label;
import mb.scopegraph.pepm16.terms.Occurrence;
import mb.scopegraph.pepm16.terms.OccurrenceIndex;
import mb.scopegraph.pepm16.terms.Scope;
public interface ISolution {
SolverConfig config();
IProperties.Immutable<TermIndex, ITerm, ITerm> astProperties();
ISolution withAstProperties(IProperties.Immutable<TermIndex, ITerm, ITerm> astProperties);
IEsopScopeGraph.Immutable<Scope, Label, Occurrence, ITerm> scopeGraph();
Multimap<OccurrenceIndex, Occurrence> astRefs();
Multimap<OccurrenceIndex, Occurrence> astDecls();
ISolution withScopeGraph(IEsopScopeGraph.Immutable<Scope, Label, Occurrence, ITerm> scopeGraph);
IEsopNameResolution<Scope, Label, Occurrence> nameResolution();
IEsopNameResolution.IResolutionCache<Scope, Label, Occurrence> nameResolutionCache();
IProperties.Immutable<Occurrence, ITerm, ITerm> declProperties();
ISolution withDeclProperties(IProperties.Immutable<Occurrence, ITerm, ITerm> declProperties);
Map<String, IVariantRelation.Immutable<ITerm>> relations();
ISolution withRelations(Map<String, ? extends IVariantRelation.Immutable<ITerm>> relations);
ISymbolicConstraints symbolic();
ISolution withSymbolic(ISymbolicConstraints symbolic);
IUnifier.Immutable unifier();
ISolution withUnifier(IUnifier.Immutable unifier);
IMessages.Immutable messages();
ISolution withMessages(IMessages.Immutable messages);
default IMessages.Immutable messagesAndUnsolvedErrors() {
IMessages.Transient messages = messages().melt();
messages.addAll(Messages.unsolvedErrors(constraints()));
return messages.freeze();
}
java.util.Set<IConstraint> constraints();
ISolution withConstraints(Iterable<? extends IConstraint> constraints);
} |
923b310e777c90d40b59950d43d505f5516551de | 2,605 | java | Java | ejb3/src/main/org/jboss/ejb3/JmxDependencyPolicy.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | ejb3/src/main/org/jboss/ejb3/JmxDependencyPolicy.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | ejb3/src/main/org/jboss/ejb3/JmxDependencyPolicy.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | 28.911111 | 83 | 0.682168 | 999,494 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ejb3;
import java.util.Collection;
import java.util.HashSet;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
/**
* Old JMX Kernel dependency registry
*
* @author <a href="mailto:upchh@example.com">Bill Burke</a>
* @version $Revision: 60233 $
*/
public class JmxDependencyPolicy implements DependencyPolicy
{
protected HashSet<ObjectName> dependencies = new HashSet<ObjectName>();
public void addDependency(String dependency)
{
ObjectName on = null;
try
{
on = new ObjectName(dependency);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(dependency, e);
}
dependencies.add(on);
}
public Collection getDependencies()
{
return dependencies;
}
public Collection getDependencies(Collection currentDependencies)
{
dependencies.addAll(currentDependencies);
return dependencies;
}
public void addDatasource(String jndiName)
{
String ds = jndiName;
if (ds.startsWith("java:/"))
{
ds = ds.substring(6);
}
else if (ds.startsWith("java:"))
{
ds = ds.substring(5);
}
//tring onStr = "jboss.jca:name=" + ds + ",service=ManagedConnectionFactory";
String onStr = "jboss.jca:name=" + ds + ",service=DataSourceBinding";
try
{
dependencies.add(new ObjectName(onStr));
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
}
|
923b316eba3152c3f9ec9af2050e2c2f1205b71d | 11,144 | java | Java | api/api-config-repos-v3/src/main/java/com/thoughtworks/go/apiv3/configrepos/ConfigReposControllerV3.java | elgorro/gocd | 2ab2cad150e51a3c5fbbf7d0820091bd6cfb60db | [
"Apache-2.0"
] | 2 | 2015-12-06T01:40:12.000Z | 2016-12-01T22:19:28.000Z | api/api-config-repos-v3/src/main/java/com/thoughtworks/go/apiv3/configrepos/ConfigReposControllerV3.java | elgorro/gocd | 2ab2cad150e51a3c5fbbf7d0820091bd6cfb60db | [
"Apache-2.0"
] | 154 | 2016-07-08T15:02:12.000Z | 2019-09-23T17:37:38.000Z | api/api-config-repos-v3/src/main/java/com/thoughtworks/go/apiv3/configrepos/ConfigReposControllerV3.java | elgorro/gocd | 2ab2cad150e51a3c5fbbf7d0820091bd6cfb60db | [
"Apache-2.0"
] | 2 | 2016-05-20T23:20:43.000Z | 2017-05-25T12:13:47.000Z | 40.376812 | 222 | 0.715721 | 999,495 | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.apiv3.configrepos;
import com.thoughtworks.go.api.ApiController;
import com.thoughtworks.go.api.ApiVersion;
import com.thoughtworks.go.api.CrudController;
import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.api.representers.JsonReader;
import com.thoughtworks.go.api.spring.ApiAuthenticationHelper;
import com.thoughtworks.go.api.util.GsonTransformer;
import com.thoughtworks.go.api.util.MessageJson;
import com.thoughtworks.go.apiv3.configrepos.representers.ConfigRepoConfigRepresenterV3;
import com.thoughtworks.go.apiv3.configrepos.representers.ConfigReposConfigRepresenterV3;
import com.thoughtworks.go.apiv3.configrepos.representers.PartialConfigRepresenter;
import com.thoughtworks.go.config.exceptions.EntityType;
import com.thoughtworks.go.config.exceptions.RecordNotFoundException;
import com.thoughtworks.go.config.remote.ConfigRepoConfig;
import com.thoughtworks.go.config.remote.ConfigReposConfig;
import com.thoughtworks.go.config.remote.PartialConfig;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.server.materials.MaterialUpdateService;
import com.thoughtworks.go.server.service.ConfigRepoService;
import com.thoughtworks.go.server.service.EntityHashingService;
import com.thoughtworks.go.server.service.MaterialConfigConverter;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import com.thoughtworks.go.spark.Routes;
import com.thoughtworks.go.spark.spring.SparkSpringController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import spark.Request;
import spark.Response;
import java.util.function.Consumer;
import static com.thoughtworks.go.api.util.HaltApiResponses.haltBecauseEntityAlreadyExists;
import static com.thoughtworks.go.api.util.HaltApiResponses.haltBecauseEtagDoesNotMatch;
import static com.thoughtworks.go.config.policy.SupportedEntity.CONFIG_REPO;
import static com.thoughtworks.go.util.CachedDigestUtils.sha256Hex;
import static java.util.stream.Collectors.toCollection;
import static spark.Spark.*;
@Component
public class ConfigReposControllerV3 extends ApiController implements SparkSpringController, CrudController<ConfigRepoConfig> {
private final ApiAuthenticationHelper authHelper;
private final ConfigRepoService service;
private final EntityHashingService entityHashingService;
private final MaterialUpdateService materialUpdateService;
private final MaterialConfigConverter converter;
@Autowired
public ConfigReposControllerV3(ApiAuthenticationHelper authHelper, ConfigRepoService service, EntityHashingService entityHashingService, MaterialUpdateService materialUpdateService, MaterialConfigConverter converter) {
super(ApiVersion.v3);
this.authHelper = authHelper;
this.service = service;
this.entityHashingService = entityHashingService;
this.materialUpdateService = materialUpdateService;
this.converter = converter;
}
@Override
public String controllerBasePath() {
return Routes.ConfigRepos.BASE;
}
@Override
public void setupRoutes() {
path(controllerBasePath(), () -> {
before("", mimeType, this::setContentType);
before("", mimeType, this::verifyContentType);
before("", mimeType, (request, response) -> {
String resourceToOperateOn = "*";
if (request.requestMethod().equalsIgnoreCase("GET")) {
authHelper.checkUserAnd403(request, response);
return;
}
if (request.requestMethod().equalsIgnoreCase("POST")) {
resourceToOperateOn = GsonTransformer.getInstance().jsonReaderFrom(request.body()).getString("id");
}
authHelper.checkUserHasPermissions(currentUsername(), getAction(request), CONFIG_REPO, resourceToOperateOn);
});
before("/*", mimeType, this::setContentType);
before("/*", mimeType, this::verifyContentType);
before(Routes.ConfigRepos.REPO_PATH, mimeType, this::authorize);
before(Routes.ConfigRepos.STATUS_PATH, mimeType, this::authorize);
before(Routes.ConfigRepos.TRIGGER_UPDATE_PATH, mimeType, this::authorize);
before(Routes.ConfigRepos.DEFINITIONS_PATH, mimeType, this::authorize);
get(Routes.ConfigRepos.INDEX_PATH, mimeType, this::index);
get(Routes.ConfigRepos.REPO_PATH, mimeType, this::showRepo);
post(Routes.ConfigRepos.CREATE_PATH, mimeType, this::createRepo);
put(Routes.ConfigRepos.UPDATE_PATH, mimeType, this::updateRepo);
delete(Routes.ConfigRepos.DELETE_PATH, mimeType, this::deleteRepo);
get(Routes.ConfigRepos.STATUS_PATH, mimeType, this::inProgress);
post(Routes.ConfigRepos.TRIGGER_UPDATE_PATH, mimeType, this::triggerUpdate);
get(Routes.ConfigRepos.DEFINITIONS_PATH, mimeType, this::definedConfigs);
});
}
String index(Request req, Response res) {
ConfigReposConfig repos = allRepos();
ConfigReposConfig userSpecificRepos = repos.stream()
.filter(configRepoConfig -> authHelper.doesUserHasPermissions(currentUsername(), getAction(req), CONFIG_REPO, configRepoConfig.getId()))
.collect(toCollection(ConfigReposConfig::new));
String etag = userSpecificRepos.etag();
setEtagHeader(res, etag);
if (fresh(req, etag)) {
return notModified(res);
}
return jsonizeAsTopLevelObject(req, w -> ConfigReposConfigRepresenterV3.toJSON(w, userSpecificRepos));
}
String showRepo(Request req, Response res) {
ConfigRepoConfig repo = fetchEntityFromConfig(req.params(":id"));
String etag = etagFor(repo);
setEtagHeader(res, etag);
if (fresh(req, etag)) {
return notModified(res);
}
return jsonize(req, repo);
}
String createRepo(Request req, Response res) {
ConfigRepoConfig repo = buildEntityFromRequestBody(req);
haltIfEntityWithSameIdExists(repo);
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
service.createConfigRepo(repo, currentUsername(), result);
return handleCreateOrUpdateResponse(req, res, repo, result);
}
String updateRepo(Request req, Response res) {
String id = req.params(":id");
ConfigRepoConfig repoFromConfig = fetchEntityFromConfig(id);
ConfigRepoConfig repoFromRequest = buildEntityFromRequestBody(req);
if (isPutRequestStale(req, repoFromConfig)) {
throw haltBecauseEtagDoesNotMatch();
}
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
service.updateConfigRepo(id, repoFromRequest, etagFor(repoFromConfig), currentUsername(), result);
return handleCreateOrUpdateResponse(req, res, repoFromRequest, result);
}
String deleteRepo(Request req, Response res) {
ConfigRepoConfig repo = fetchEntityFromConfig(req.params(":id"));
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
service.deleteConfigRepo(repo.getId(), currentUsername(), result);
return handleSimpleMessageResponse(res, result);
}
String inProgress(Request req, Response res) {
MaterialConfig materialConfig = repoFromRequest(req).getRepo();
final boolean state = materialUpdateService.isInProgress(converter.toMaterial(materialConfig));
return String.format("{\"in_progress\":%b}", state);
}
String triggerUpdate(Request req, Response res) {
MaterialConfig materialConfig = repoFromRequest(req).getRepo();
if (materialUpdateService.updateMaterial(converter.toMaterial(materialConfig))) {
res.status(HttpStatus.CREATED.value());
return MessageJson.create("OK");
} else {
res.status(HttpStatus.CONFLICT.value());
return MessageJson.create("Update already in progress.");
}
}
String definedConfigs(Request req, Response res) {
ConfigRepoConfig repo = repoFromRequest(req);
PartialConfig def = service.partialConfigDefinedBy(repo);
final String etag = etagFor(def);
setEtagHeader(res, etag);
if (fresh(req, etag)) {
return notModified(res);
}
return jsonizeAsTopLevelObject(req, (w) -> PartialConfigRepresenter.toJSON(w, def));
}
private ConfigRepoConfig repoFromRequest(Request req) {
String repoId = req.params(":id");
ConfigRepoConfig repo = service.getConfigRepo(repoId);
if (null == repo) {
throw new RecordNotFoundException(EntityType.ConfigRepo, repoId);
}
return repo;
}
@Override
public String etagFor(ConfigRepoConfig repo) {
return entityHashingService.md5ForEntity(repo);
}
private String etagFor(PartialConfig entity) {
return sha256Hex(Integer.toString(entity.hashCode()));
}
@Override
public EntityType getEntityType() {
return EntityType.ConfigRepo;
}
@Override
public ConfigRepoConfig doFetchEntityFromConfig(String id) {
return service.getConfigRepo(id);
}
@Override
public ConfigRepoConfig buildEntityFromRequestBody(Request req) {
JsonReader jsonReader = GsonTransformer.getInstance().jsonReaderFrom(req.body());
return ConfigRepoConfigRepresenterV3.fromJSON(jsonReader);
}
@Override
public Consumer<OutputWriter> jsonWriter(ConfigRepoConfig repo) {
return w -> ConfigRepoConfigRepresenterV3.toJSON(w, repo);
}
private ConfigReposConfig allRepos() {
return service.getConfigRepos();
}
private void haltIfEntityWithSameIdExists(ConfigRepoConfig repo) {
String id = repo.getId();
if (doFetchEntityFromConfig(id) == null) {
return;
}
repo.addError("id", "ConfigRepo ids should be unique. A ConfigRepo with the same id already exists.");
throw haltBecauseEntityAlreadyExists(jsonWriter(repo), "config-repo", id);
}
private void authorize(Request request, Response response) {
authHelper.checkUserHasPermissions(currentUsername(), getAction(request), CONFIG_REPO, request.params(":id"));
}
}
|
923b324cf9c0d83f1f55967451115a648560e134 | 22,589 | java | Java | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/Recommender.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | 1 | 2022-01-04T04:11:16.000Z | 2022-01-04T04:11:16.000Z | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/Recommender.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/Recommender.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | 31.114325 | 144 | 0.590376 | 999,496 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a recommendation generator for a Domain dataset group. You create a recommender in a Domain dataset group
* for a specific domain use case (domain recipe), and specify the recommender in a <a
* href="https://docs.aws.amazon.com/personalize/latest/dg/API_RS_GetRecommendations.html">GetRecommendations</a>
* request.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/Recommender" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Recommender implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The Amazon Resource Name (ARN) of the recommender.
* </p>
*/
private String recommenderArn;
/**
* <p>
* The Amazon Resource Name (ARN) of the Domain dataset group that contains the recommender.
* </p>
*/
private String datasetGroupArn;
/**
* <p>
* The name of the recommender.
* </p>
*/
private String name;
/**
* <p>
* The Amazon Resource Name (ARN) of the recipe (Domain dataset group use case) that the recommender was created
* for.
* </p>
*/
private String recipeArn;
/**
* <p>
* The configuration details of the recommender.
* </p>
*/
private RecommenderConfig recommenderConfig;
/**
* <p>
* The date and time (in Unix format) that the recommender was created.
* </p>
*/
private java.util.Date creationDateTime;
/**
* <p>
* The date and time (in Unix format) that the recommender was last updated.
* </p>
*/
private java.util.Date lastUpdatedDateTime;
/**
* <p>
* The status of the recommender.
* </p>
* <p>
* A recommender can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
* </p>
* </li>
* <li>
* <p>
* DELETE PENDING > DELETE IN_PROGRESS
* </p>
* </li>
* </ul>
*/
private String status;
/**
* <p>
* If a recommender fails, the reason behind the failure.
* </p>
*/
private String failureReason;
/**
* <p>
* Provides a summary of the latest updates to the recommender.
* </p>
*/
private RecommenderUpdateSummary latestRecommenderUpdate;
/**
* <p>
* The Amazon Resource Name (ARN) of the recommender.
* </p>
*
* @param recommenderArn
* The Amazon Resource Name (ARN) of the recommender.
*/
public void setRecommenderArn(String recommenderArn) {
this.recommenderArn = recommenderArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the recommender.
* </p>
*
* @return The Amazon Resource Name (ARN) of the recommender.
*/
public String getRecommenderArn() {
return this.recommenderArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the recommender.
* </p>
*
* @param recommenderArn
* The Amazon Resource Name (ARN) of the recommender.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withRecommenderArn(String recommenderArn) {
setRecommenderArn(recommenderArn);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Domain dataset group that contains the recommender.
* </p>
*
* @param datasetGroupArn
* The Amazon Resource Name (ARN) of the Domain dataset group that contains the recommender.
*/
public void setDatasetGroupArn(String datasetGroupArn) {
this.datasetGroupArn = datasetGroupArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Domain dataset group that contains the recommender.
* </p>
*
* @return The Amazon Resource Name (ARN) of the Domain dataset group that contains the recommender.
*/
public String getDatasetGroupArn() {
return this.datasetGroupArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Domain dataset group that contains the recommender.
* </p>
*
* @param datasetGroupArn
* The Amazon Resource Name (ARN) of the Domain dataset group that contains the recommender.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withDatasetGroupArn(String datasetGroupArn) {
setDatasetGroupArn(datasetGroupArn);
return this;
}
/**
* <p>
* The name of the recommender.
* </p>
*
* @param name
* The name of the recommender.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the recommender.
* </p>
*
* @return The name of the recommender.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the recommender.
* </p>
*
* @param name
* The name of the recommender.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the recipe (Domain dataset group use case) that the recommender was created
* for.
* </p>
*
* @param recipeArn
* The Amazon Resource Name (ARN) of the recipe (Domain dataset group use case) that the recommender was
* created for.
*/
public void setRecipeArn(String recipeArn) {
this.recipeArn = recipeArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the recipe (Domain dataset group use case) that the recommender was created
* for.
* </p>
*
* @return The Amazon Resource Name (ARN) of the recipe (Domain dataset group use case) that the recommender was
* created for.
*/
public String getRecipeArn() {
return this.recipeArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the recipe (Domain dataset group use case) that the recommender was created
* for.
* </p>
*
* @param recipeArn
* The Amazon Resource Name (ARN) of the recipe (Domain dataset group use case) that the recommender was
* created for.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withRecipeArn(String recipeArn) {
setRecipeArn(recipeArn);
return this;
}
/**
* <p>
* The configuration details of the recommender.
* </p>
*
* @param recommenderConfig
* The configuration details of the recommender.
*/
public void setRecommenderConfig(RecommenderConfig recommenderConfig) {
this.recommenderConfig = recommenderConfig;
}
/**
* <p>
* The configuration details of the recommender.
* </p>
*
* @return The configuration details of the recommender.
*/
public RecommenderConfig getRecommenderConfig() {
return this.recommenderConfig;
}
/**
* <p>
* The configuration details of the recommender.
* </p>
*
* @param recommenderConfig
* The configuration details of the recommender.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withRecommenderConfig(RecommenderConfig recommenderConfig) {
setRecommenderConfig(recommenderConfig);
return this;
}
/**
* <p>
* The date and time (in Unix format) that the recommender was created.
* </p>
*
* @param creationDateTime
* The date and time (in Unix format) that the recommender was created.
*/
public void setCreationDateTime(java.util.Date creationDateTime) {
this.creationDateTime = creationDateTime;
}
/**
* <p>
* The date and time (in Unix format) that the recommender was created.
* </p>
*
* @return The date and time (in Unix format) that the recommender was created.
*/
public java.util.Date getCreationDateTime() {
return this.creationDateTime;
}
/**
* <p>
* The date and time (in Unix format) that the recommender was created.
* </p>
*
* @param creationDateTime
* The date and time (in Unix format) that the recommender was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withCreationDateTime(java.util.Date creationDateTime) {
setCreationDateTime(creationDateTime);
return this;
}
/**
* <p>
* The date and time (in Unix format) that the recommender was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time (in Unix format) that the recommender was last updated.
*/
public void setLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
this.lastUpdatedDateTime = lastUpdatedDateTime;
}
/**
* <p>
* The date and time (in Unix format) that the recommender was last updated.
* </p>
*
* @return The date and time (in Unix format) that the recommender was last updated.
*/
public java.util.Date getLastUpdatedDateTime() {
return this.lastUpdatedDateTime;
}
/**
* <p>
* The date and time (in Unix format) that the recommender was last updated.
* </p>
*
* @param lastUpdatedDateTime
* The date and time (in Unix format) that the recommender was last updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withLastUpdatedDateTime(java.util.Date lastUpdatedDateTime) {
setLastUpdatedDateTime(lastUpdatedDateTime);
return this;
}
/**
* <p>
* The status of the recommender.
* </p>
* <p>
* A recommender can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
* </p>
* </li>
* <li>
* <p>
* DELETE PENDING > DELETE IN_PROGRESS
* </p>
* </li>
* </ul>
*
* @param status
* The status of the recommender.</p>
* <p>
* A recommender can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
* </p>
* </li>
* <li>
* <p>
* DELETE PENDING > DELETE IN_PROGRESS
* </p>
* </li>
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the recommender.
* </p>
* <p>
* A recommender can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
* </p>
* </li>
* <li>
* <p>
* DELETE PENDING > DELETE IN_PROGRESS
* </p>
* </li>
* </ul>
*
* @return The status of the recommender.</p>
* <p>
* A recommender can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
* </p>
* </li>
* <li>
* <p>
* DELETE PENDING > DELETE IN_PROGRESS
* </p>
* </li>
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the recommender.
* </p>
* <p>
* A recommender can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
* </p>
* </li>
* <li>
* <p>
* DELETE PENDING > DELETE IN_PROGRESS
* </p>
* </li>
* </ul>
*
* @param status
* The status of the recommender.</p>
* <p>
* A recommender can be in one of the following states:
* </p>
* <ul>
* <li>
* <p>
* CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED
* </p>
* </li>
* <li>
* <p>
* DELETE PENDING > DELETE IN_PROGRESS
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* If a recommender fails, the reason behind the failure.
* </p>
*
* @param failureReason
* If a recommender fails, the reason behind the failure.
*/
public void setFailureReason(String failureReason) {
this.failureReason = failureReason;
}
/**
* <p>
* If a recommender fails, the reason behind the failure.
* </p>
*
* @return If a recommender fails, the reason behind the failure.
*/
public String getFailureReason() {
return this.failureReason;
}
/**
* <p>
* If a recommender fails, the reason behind the failure.
* </p>
*
* @param failureReason
* If a recommender fails, the reason behind the failure.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withFailureReason(String failureReason) {
setFailureReason(failureReason);
return this;
}
/**
* <p>
* Provides a summary of the latest updates to the recommender.
* </p>
*
* @param latestRecommenderUpdate
* Provides a summary of the latest updates to the recommender.
*/
public void setLatestRecommenderUpdate(RecommenderUpdateSummary latestRecommenderUpdate) {
this.latestRecommenderUpdate = latestRecommenderUpdate;
}
/**
* <p>
* Provides a summary of the latest updates to the recommender.
* </p>
*
* @return Provides a summary of the latest updates to the recommender.
*/
public RecommenderUpdateSummary getLatestRecommenderUpdate() {
return this.latestRecommenderUpdate;
}
/**
* <p>
* Provides a summary of the latest updates to the recommender.
* </p>
*
* @param latestRecommenderUpdate
* Provides a summary of the latest updates to the recommender.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Recommender withLatestRecommenderUpdate(RecommenderUpdateSummary latestRecommenderUpdate) {
setLatestRecommenderUpdate(latestRecommenderUpdate);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRecommenderArn() != null)
sb.append("RecommenderArn: ").append(getRecommenderArn()).append(",");
if (getDatasetGroupArn() != null)
sb.append("DatasetGroupArn: ").append(getDatasetGroupArn()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getRecipeArn() != null)
sb.append("RecipeArn: ").append(getRecipeArn()).append(",");
if (getRecommenderConfig() != null)
sb.append("RecommenderConfig: ").append(getRecommenderConfig()).append(",");
if (getCreationDateTime() != null)
sb.append("CreationDateTime: ").append(getCreationDateTime()).append(",");
if (getLastUpdatedDateTime() != null)
sb.append("LastUpdatedDateTime: ").append(getLastUpdatedDateTime()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus()).append(",");
if (getFailureReason() != null)
sb.append("FailureReason: ").append(getFailureReason()).append(",");
if (getLatestRecommenderUpdate() != null)
sb.append("LatestRecommenderUpdate: ").append(getLatestRecommenderUpdate());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Recommender == false)
return false;
Recommender other = (Recommender) obj;
if (other.getRecommenderArn() == null ^ this.getRecommenderArn() == null)
return false;
if (other.getRecommenderArn() != null && other.getRecommenderArn().equals(this.getRecommenderArn()) == false)
return false;
if (other.getDatasetGroupArn() == null ^ this.getDatasetGroupArn() == null)
return false;
if (other.getDatasetGroupArn() != null && other.getDatasetGroupArn().equals(this.getDatasetGroupArn()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getRecipeArn() == null ^ this.getRecipeArn() == null)
return false;
if (other.getRecipeArn() != null && other.getRecipeArn().equals(this.getRecipeArn()) == false)
return false;
if (other.getRecommenderConfig() == null ^ this.getRecommenderConfig() == null)
return false;
if (other.getRecommenderConfig() != null && other.getRecommenderConfig().equals(this.getRecommenderConfig()) == false)
return false;
if (other.getCreationDateTime() == null ^ this.getCreationDateTime() == null)
return false;
if (other.getCreationDateTime() != null && other.getCreationDateTime().equals(this.getCreationDateTime()) == false)
return false;
if (other.getLastUpdatedDateTime() == null ^ this.getLastUpdatedDateTime() == null)
return false;
if (other.getLastUpdatedDateTime() != null && other.getLastUpdatedDateTime().equals(this.getLastUpdatedDateTime()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getFailureReason() == null ^ this.getFailureReason() == null)
return false;
if (other.getFailureReason() != null && other.getFailureReason().equals(this.getFailureReason()) == false)
return false;
if (other.getLatestRecommenderUpdate() == null ^ this.getLatestRecommenderUpdate() == null)
return false;
if (other.getLatestRecommenderUpdate() != null && other.getLatestRecommenderUpdate().equals(this.getLatestRecommenderUpdate()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRecommenderArn() == null) ? 0 : getRecommenderArn().hashCode());
hashCode = prime * hashCode + ((getDatasetGroupArn() == null) ? 0 : getDatasetGroupArn().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getRecipeArn() == null) ? 0 : getRecipeArn().hashCode());
hashCode = prime * hashCode + ((getRecommenderConfig() == null) ? 0 : getRecommenderConfig().hashCode());
hashCode = prime * hashCode + ((getCreationDateTime() == null) ? 0 : getCreationDateTime().hashCode());
hashCode = prime * hashCode + ((getLastUpdatedDateTime() == null) ? 0 : getLastUpdatedDateTime().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode + ((getFailureReason() == null) ? 0 : getFailureReason().hashCode());
hashCode = prime * hashCode + ((getLatestRecommenderUpdate() == null) ? 0 : getLatestRecommenderUpdate().hashCode());
return hashCode;
}
@Override
public Recommender clone() {
try {
return (Recommender) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.personalize.model.transform.RecommenderMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
923b3262d773219bcf161701f9d8e1d3429c4f3e | 2,089 | java | Java | java/BigDecimal.java | NSnietol/hacker-rank | bdf378bc21ce1e9e5da6e013a8983d7e2f92de2b | [
"MIT"
] | 2 | 2019-12-16T03:12:37.000Z | 2020-03-04T18:54:23.000Z | java/BigDecimal.java | NSnietol/hacker-rank | bdf378bc21ce1e9e5da6e013a8983d7e2f92de2b | [
"MIT"
] | null | null | null | java/BigDecimal.java | NSnietol/hacker-rank | bdf378bc21ce1e9e5da6e013a8983d7e2f92de2b | [
"MIT"
] | null | null | null | 33.693548 | 390 | 0.66539 | 999,497 |
/*
Given an array, s, of n real number strings, sort them in descending order — but wait, there's more! Each number must be printed in the exact same format as it was read from stdin, meaning .1 that 0.1 is printed as 0.1 , and is printed as . If two numbers represent numerically equivalent values (e.g., 0.1 = .1), then they must be listed in the same order as they were received as input).
Complete the code in the unlocked section of the editor below. You must rearrange array S 's elements according to the instructions above.
Input format
The first line consists of a single integer, n , denoting the number of integer strings.
Each line i of n the subsequent lines contains a real number denoting the value of Si.
Output Format
Locked stub code in the editor will print the contents of array S to stdout. You are only responsible for reordering the array's elements.
Reference
https://www.hackerrank.com/challenges/java-bigdecimal/problem
**/
import java.math.BigDecimal;
import java.util.*;
class Solution{
public static void main(String []args){
//Input
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String []s=new String[n+2];
// La persona que propuso el reto asignò String[n+2]
for(int i=0;i<n;i++){
s[i]=sc.next();
}
sc.close();
// The idea is to keep the string format stored in vector
// In order for the ordering criterion is based on representation
// BigDecimal of each value so that the numerical value is not altered.
// that is formatted as a string for example: .1 does not become 0.1
// when casting to numerical value
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
BigDecimal a = new BigDecimal(s1);
BigDecimal b = new BigDecimal(s2);
return b.compareTo(a);
}
};
Arrays.sort(s, 0, n, comparator);
//Output
for(int i=0;i<n;i++)
{
System.out.println(s[i]);
}
}
} |
923b32942dcbf405a91505c04bad347616855b9e | 391 | java | Java | catalog-nosql/src/main/java/com/store/catalog/mongo/config/CatalogMongoFactoryBean.java | chaimaTPT/chaima | 21cdd1205b4486f43d49b440055cbda9c15e4693 | [
"Apache-2.0"
] | null | null | null | catalog-nosql/src/main/java/com/store/catalog/mongo/config/CatalogMongoFactoryBean.java | chaimaTPT/chaima | 21cdd1205b4486f43d49b440055cbda9c15e4693 | [
"Apache-2.0"
] | null | null | null | catalog-nosql/src/main/java/com/store/catalog/mongo/config/CatalogMongoFactoryBean.java | chaimaTPT/chaima | 21cdd1205b4486f43d49b440055cbda9c15e4693 | [
"Apache-2.0"
] | null | null | null | 16.291667 | 63 | 0.777494 | 999,498 | package com.store.catalog.mongo.config;
import org.springframework.data.mongodb.core.MongoFactoryBean;
public class CatalogMongoFactoryBean extends MongoFactoryBean {
public CatalogMongoFactoryBean(){
}
private String portAsString;
public void setPortAsString(String portAsString) {
this.portAsString = portAsString;
setPort(Integer.parseInt(portAsString));
}
}
|
923b32d144e7b4ddb8f5f87f0f7f22261e99b1a0 | 1,448 | java | Java | JavaSE/src/site/pwjworks/thread/syn/UnsafeBank.java | pwjworks/Java-learning-record | 4b201642c3f92981911cd1818484bd5ea7206a18 | [
"MIT"
] | null | null | null | JavaSE/src/site/pwjworks/thread/syn/UnsafeBank.java | pwjworks/Java-learning-record | 4b201642c3f92981911cd1818484bd5ea7206a18 | [
"MIT"
] | null | null | null | JavaSE/src/site/pwjworks/thread/syn/UnsafeBank.java | pwjworks/Java-learning-record | 4b201642c3f92981911cd1818484bd5ea7206a18 | [
"MIT"
] | null | null | null | 26.814815 | 77 | 0.555939 | 999,499 | package site.pwjworks.thread.syn;
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(1000, "基金");
Drawing you = new Drawing(account, 50, "你");
Drawing gf = new Drawing(account, 100, "gf");
you.start();
gf.start();
}
}
class Account {
public int money;
public String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
class Drawing extends Thread {
public Account account;
public int drawingMoney;
public int nowMoney;
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
super.run();
synchronized (account) {
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System.out.println((account.name + "余额为:" + account.money));
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
}
|
923b3358a3adf7f3eddb10127856eff0be081ef0 | 7,683 | java | Java | easymoneywidgetslibrary/src/main/java/com/wajahatkarim3/easymoneywidgets/EasyMoneyEditText.java | applibgroup/EasyMoney-Widgets | 510e8bf3bbbd42af340d3b1131a0b5e614ba93bd | [
"Apache-2.0"
] | null | null | null | easymoneywidgetslibrary/src/main/java/com/wajahatkarim3/easymoneywidgets/EasyMoneyEditText.java | applibgroup/EasyMoney-Widgets | 510e8bf3bbbd42af340d3b1131a0b5e614ba93bd | [
"Apache-2.0"
] | 3 | 2021-07-29T09:40:39.000Z | 2021-09-13T09:16:20.000Z | easymoneywidgetslibrary/src/main/java/com/wajahatkarim3/easymoneywidgets/EasyMoneyEditText.java | applibgroup/EasyMoney-Widgets | 510e8bf3bbbd42af340d3b1131a0b5e614ba93bd | [
"Apache-2.0"
] | 1 | 2021-07-16T15:44:00.000Z | 2021-07-16T15:44:00.000Z | 31.747934 | 112 | 0.599636 | 999,500 | package com.wajahatkarim3.easymoneywidgets;
import com.wajahatkarim3.easymoneywidgets.util.AttrUtil;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.app.Context;
/**
* The EditText widget for support of money requirements like currency, number formatting, comma formatting etc.
* Add com.wajahatkarim3.easymoneywidgets.EasyMoneyEditText into your XML layouts and you are done!
* For more information, check http://github.com/wajahatkarim3/EasyMoney-Widgets
*
* @author Wajahat Karim (http://wajahatkarim.com)
* @version 1.0.0 01/20/2017
*/
public class EasyMoneyEditText extends TextField {
private String currencySymbolEditText;
private boolean showCurrencyEditText;
private boolean showCommasEditText;
/**
* Constructor.
*
* @param context Context.
*/
public EasyMoneyEditText(Context context) {
super(context);
initView(context, null);
}
/**
* Constructor.
*
* @param context Context.
* @param attrs AttributeSet.
*/
public EasyMoneyEditText(Context context, AttrSet attrs) {
super(context, attrs);
initView(context, attrs);
}
private void initView(Context context, AttrSet attrs) {
// Setting Default Parameters
currencySymbolEditText = Currency.getInstance(Locale.getDefault()).getSymbol();
showCurrencyEditText = true;
showCommasEditText = true;
// Check for the attributes
if (attrs != null) {
// Attribute initialization
String currency = AttrUtil.getStringValue(attrs,
AttrUtil.getString(context, ResourceTable.String_currency_symbol_edit_text), null);
if (currency == null) {
currency = Currency.getInstance(Locale.getDefault()).getSymbol();
}
setCurrency(currency);
showCurrencyEditText = AttrUtil.getBooleanValue(attrs,
AttrUtil.getString(context, ResourceTable.String_show_currency_edit_text), true);
showCommasEditText = AttrUtil.getBooleanValue(attrs,
AttrUtil.getString(context, ResourceTable.String_show_commas_edit_text), true);
}
// Add Text Watcher for Decimal formatting
initTextWatchers();
}
private void initTextWatchers() {
this.addTextObserver(new Text.TextObserver() {
@Override
public void onTextUpdated(String s, int i, int i1, int i2) {
EasyMoneyEditText.this.removeTextObserver(this);
setValue(s);
EasyMoneyEditText.this.addTextObserver(this);
}
});
}
private void setValue(String valueEditText) {
try {
long longval;
valueEditText = getValueString();
longval = (Long.parseLong(valueEditText));
String formattedString = getDecoratedStringFromNumber(longval);
// setting text after format to EditText
setText(formattedString);
} catch (NumberFormatException nfe) {
setText(valueEditText);
String valEditText = getValueString();
if (valEditText.equals("")) {
long val = 0;
setText(getDecoratedStringFromNumber(val));
} else {
// Some decimal number
if (valEditText.contains(".")) {
if (valEditText.indexOf(".") == valEditText.length() - 1) {
// decimal has been currently put
String front = getDecoratedStringFromNumber(
Long.parseLong(valEditText.substring(0, valEditText.length() - 1)));
setText(front + ".");
} else {
String[] nums = getValueString().split("\\.");
String front = getDecoratedStringFromNumber(Long.parseLong(nums[0]));
setText(front + "." + nums[1]);
}
}
}
}
}
private String getDecoratedStringFromNumber(long number) {
String numberPattern = "#,###,###,###";
String decoStr;
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.getDefault());
if (showCommasEditText && !showCurrencyEditText) {
formatter.applyPattern(numberPattern);
} else if (showCommasEditText) {
formatter.applyPattern(currencySymbolEditText + " " + numberPattern);
} else if (showCurrencyEditText) {
formatter.applyPattern(currencySymbolEditText + " ");
} else {
decoStr = number + "";
return decoStr;
}
decoStr = formatter.format(number);
return decoStr;
}
private void setShowCurrency(boolean value) {
showCurrencyEditText = value;
setValue(getText());
}
/**
* Get the value of the text without any commas and currency.
* For example, if the edit text value is $ 1,34,000.60 then this method will return 134000.60
*
* @return A string of the raw value in the text field.
*/
public String getValueString() {
String string = getText();
if (string.contains(",")) {
string = string.replace(",", "");
}
if (string.contains(" ")) {
string = string.substring(string.indexOf(" ") + 1);
}
return string;
}
/**
* Get the value of the text with formatted commas and currency.
* For example, if the edit text value is $ 1,34,000.60 then this method will return exactly $ 1,34,000.60
*
* @return A string of the text value in the text field
*/
public String getFormattedString() {
return getText();
}
/**
* Set the currency symbol for the edit text.
*
* @param newSymbol the new symbol of currency in string
*/
public void setCurrency(String newSymbol) {
currencySymbolEditText = newSymbol;
setValue(getText());
}
/**
* Set the currency symbol for the edit text.
*
* @param locale the locale of new symbol. (Default is Locale)
*/
public void setCurrency(Locale locale) {
setCurrency(Currency.getInstance(locale).getSymbol());
}
/**
* Set the currency symbol for the edit text.
*
* @param currency the currency object of new symbol. (Defaul is Locale.Default)
*/
public void setCurrency(Currency currency) {
setCurrency(currency.getSymbol());
}
/**
* Whether currency is shown in the text or not. (Default is true)
*
* @return true if the currency is shown otherwise false.
*/
public boolean isShowCurrency() {
return showCurrencyEditText;
}
/**
* Shows the currency in the text. (Default is shown).
*/
public void showCurrencySymbol() {
setShowCurrency(true);
}
/**
* Hides the currency in the text. (Default is shown).
*/
public void hideCurrencySymbol() {
setShowCurrency(false);
}
/**
* Shows the commas in the text. (Default is shown).
*/
public void showCommas() {
showCommasEditText = true;
setValue(getText());
}
/**
* Hides the commas in the text. (Default is shown).
*/
public void hideCommas() {
showCommasEditText = false;
setValue(getText());
}
}
|
923b338c76dc7d2acd30c86e036d63131bcd7adc | 274 | java | Java | platform/mds/mds-test-bundle/src/main/java/org/motechproject/mds/test/service/inheritancestrategies/GoldfishDataService.java | afijal/motech | 82b73483740e7e5130d8b0656ce150555716a909 | [
"BSD-3-Clause"
] | 17 | 2015-08-11T07:39:39.000Z | 2021-08-30T04:24:51.000Z | platform/mds/mds-test-bundle/src/main/java/org/motechproject/mds/test/service/inheritancestrategies/GoldfishDataService.java | afijal/motech | 82b73483740e7e5130d8b0656ce150555716a909 | [
"BSD-3-Clause"
] | 474 | 2015-08-11T08:15:03.000Z | 2018-03-29T16:11:11.000Z | platform/mds/mds-test-bundle/src/main/java/org/motechproject/mds/test/service/inheritancestrategies/GoldfishDataService.java | afijal/motech | 82b73483740e7e5130d8b0656ce150555716a909 | [
"BSD-3-Clause"
] | 71 | 2015-09-03T15:09:11.000Z | 2018-07-24T04:34:30.000Z | 34.25 | 74 | 0.864964 | 999,501 | package org.motechproject.mds.test.service.inheritancestrategies;
import org.motechproject.mds.service.MotechDataService;
import org.motechproject.mds.test.domain.inheritancestrategies.Goldfish;
public interface GoldfishDataService extends MotechDataService<Goldfish> {
}
|
923b3523754c873dc5752bf8563f3221256cc17f | 9,015 | java | Java | app/src/main/java/test/demo/Ramadan/surahrecitation/SurahRecitationActivity.java | w3leed/Ramadna | 998de5c317d48254cb3e2f55972e601a8c094a96 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/test/demo/Ramadan/surahrecitation/SurahRecitationActivity.java | w3leed/Ramadna | 998de5c317d48254cb3e2f55972e601a8c094a96 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/test/demo/Ramadan/surahrecitation/SurahRecitationActivity.java | w3leed/Ramadna | 998de5c317d48254cb3e2f55972e601a8c094a96 | [
"Apache-2.0"
] | null | null | null | 29.850993 | 80 | 0.596007 | 999,502 | package test.demo.Ramadan.surahrecitation;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.content.res.AssetManager;
import android.widget.RelativeLayout;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.demo.musilmguide.R;
import test.demo.Ramadan.universal.Utils;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
/**
* Created by Shahzad Ahmad on 22-Jun-15.
*/
public class SurahRecitationActivity extends AppCompatActivity {
public String AD_UNIT_ID= "";
private AdView adView;
private InterstitialAd interstitial;
private MediaPlayer player;
Context context;
RelativeLayout readQuran;
int fatiha,rehman,mulk,waqiya,yaseen=0;
ImageView btnfatiha,btnrehman,btnmulk,btnwaqiya,btnyaseen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surah_recitation);
getSupportActionBar ().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar ().setCustomView(R.layout.customactionbar);
context=this;
AD_UNIT_ID= Utils.Banner;
// AD_UNIT_ID= Utils.Banner;
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Create the interstitial.
interstitial = new InterstitialAd(context);
interstitial.setAdUnitId(Utils.Interstitial);
AdRequest adRequest1 = new AdRequest.Builder().build();
interstitial.loadAd(adRequest1);
adView = new AdView(context);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
LinearLayout layout = (LinearLayout)findViewById(R.id.adlayout);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
readQuran = (RelativeLayout)findViewById(R.id.rlReadQuran);
readQuran.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CopyReadAssets();
}
});
btnfatiha= (ImageView)findViewById(R.id.btn_surah_fatiha);
btnfatiha.setOnClickListener(new View.OnClickListener()
{ public void onClick(View v)
{
SurahFatiha();
}
});
btnmulk= (ImageView)findViewById(R.id.btn_surah_mulk);
btnmulk.setOnClickListener(new View.OnClickListener()
{ public void onClick(View v)
{
SurahMulk();
}
});
btnrehman= (ImageView)findViewById(R.id.btn_surah_rahman);
btnrehman.setOnClickListener(new View.OnClickListener()
{ public void onClick(View v)
{
SurahRehman();
}
});
btnwaqiya= (ImageView)findViewById(R.id.btn_surah_waqia);
btnwaqiya.setOnClickListener(new View.OnClickListener()
{ public void onClick(View v)
{
SurahWaqiya();
}
});
btnyaseen= (ImageView)findViewById(R.id.btn_surah_yaseen);
btnyaseen.setOnClickListener(new View.OnClickListener()
{ public void onClick(View v)
{
SurahYaseen();
}
});
}
public void playerChecker(){
if(fatiha==1||rehman==1||waqiya==1||yaseen==1||mulk==1){
player.pause();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (interstitial.isLoaded()) {
interstitial.show();
}
playerChecker();
}
public void SurahYaseen(){
if(fatiha==1||rehman==1||waqiya==1||mulk==1){
player.pause();
}
if (yaseen == 0) {
player = MediaPlayer.create(context, R.raw.syaseen);
yaseen = 1;
player.start();
btnyaseen.setBackgroundResource(R.drawable.stop);
btnmulk.setBackgroundResource(R.drawable.play);
btnrehman.setBackgroundResource(R.drawable.play);
btnwaqiya.setBackgroundResource(R.drawable.play);
btnfatiha.setBackgroundResource(R.drawable.play);
}else{
player.pause();
yaseen = 0;
btnyaseen.setBackgroundResource(R.drawable.play);
}
}
public void SurahMulk(){
if(fatiha==1||rehman==1||waqiya==1||yaseen==1){
player.pause();
}
if (mulk == 0) {
player = MediaPlayer.create(context, R.raw.smulk);
mulk = 1;
player.start();
btnmulk.setBackgroundResource(R.drawable.stop);
btnyaseen.setBackgroundResource(R.drawable.play);
btnrehman.setBackgroundResource(R.drawable.play);
btnwaqiya.setBackgroundResource(R.drawable.play);
btnfatiha.setBackgroundResource(R.drawable.play);
}else{
player.pause();
mulk = 0;
btnmulk.setBackgroundResource(R.drawable.play);
}
}
public void SurahWaqiya(){
if(fatiha==1||rehman==1||yaseen==1||mulk==1){
player.pause();
}
if (waqiya == 0) {
player = MediaPlayer.create(context, R.raw.swaqya);
waqiya = 1;
player.start();
btnwaqiya.setBackgroundResource(R.drawable.stop);
btnmulk.setBackgroundResource(R.drawable.play);
btnrehman.setBackgroundResource(R.drawable.play);
btnyaseen.setBackgroundResource(R.drawable.play);
btnfatiha.setBackgroundResource(R.drawable.play);
}else{
player.pause();
waqiya = 0;
btnwaqiya.setBackgroundResource(R.drawable.play);
}
}
public void SurahFatiha(){
if(rehman==1||waqiya==1||yaseen==1||mulk==1){
player.pause();
}
if (fatiha == 0) {
player = MediaPlayer.create(context, R.raw.sfatiha);
fatiha = 1;
player.start();
btnfatiha.setBackgroundResource(R.drawable.stop);
btnmulk.setBackgroundResource(R.drawable.play);
btnrehman.setBackgroundResource(R.drawable.play);
btnwaqiya.setBackgroundResource(R.drawable.play);
btnyaseen.setBackgroundResource(R.drawable.play);
}else{
player.pause();
fatiha = 0;
btnfatiha.setBackgroundResource(R.drawable.play);
}
}
public void SurahRehman(){
if(fatiha==1||waqiya==1||yaseen==1||mulk==1){
player.pause();
}
if (rehman == 0) {
player = MediaPlayer.create(context, R.raw.srahman);
rehman = 1;
player.start();
btnrehman.setBackgroundResource(R.drawable.stop);
btnmulk.setBackgroundResource(R.drawable.play);
btnfatiha.setBackgroundResource(R.drawable.play);
btnwaqiya.setBackgroundResource(R.drawable.play);
btnyaseen.setBackgroundResource(R.drawable.play);
}else{
player.pause();
rehman = 0;
btnrehman.setBackgroundResource(R.drawable.play);
}
}
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "quraan.pdf");
try
{
in = assetManager.open("quraan.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/quraan.pdf"),
"application/pdf");
startActivity(intent);
// finish();
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
|
923b35372a2a4e46a5e963aaa05d56f6651b46b3 | 971 | java | Java | src/main/java/com/github/vlachenal/webservice/bench/client/soap/api/StatisticsClient.java | vlachenal/webservices-bench-client | 8893ac635797762298ac6eb3882d591136dd2e68 | [
"WTFPL"
] | null | null | null | src/main/java/com/github/vlachenal/webservice/bench/client/soap/api/StatisticsClient.java | vlachenal/webservices-bench-client | 8893ac635797762298ac6eb3882d591136dd2e68 | [
"WTFPL"
] | null | null | null | src/main/java/com/github/vlachenal/webservice/bench/client/soap/api/StatisticsClient.java | vlachenal/webservices-bench-client | 8893ac635797762298ac6eb3882d591136dd2e68 | [
"WTFPL"
] | null | null | null | 24.275 | 75 | 0.717817 | 999,503 | /*
* Copyright © 2017 Vincent Lachenal
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See the COPYING file for more details.
*/
package com.github.vlachenal.webservice.bench.client.soap.api;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
/**
* SOAP statistics client
*
* @author Vincent Lachenal
*/
public class StatisticsClient extends WebServiceGatewaySupport {
// Methods +
/**
* Consolidate statistics
*
* @param test the test suite
*/
public void consolidate(final TestSuite test) {
final ConsolidateRequest req = new ConsolidateRequest();
req.setTest(test);
getWebServiceTemplate().marshalSendAndReceive(req);
}
/**
* Purge statistics
*/
public void purge() {
getWebServiceTemplate().marshalSendAndReceive(new PurgeRequest());
}
// Methods -
}
|
923b3537c6f52e45f96f8b8ac2b7503802a12291 | 1,277 | java | Java | src/com/sun/org/apache/xerces/internal/impl/dv/DVFactoryException.java | yonxao/jdk202 | a3b1e4e94cd9230052770cd42168e7bc19764e84 | [
"MIT"
] | 1,305 | 2018-03-11T15:04:26.000Z | 2022-03-30T16:02:34.000Z | jdk/src/main/java/com/sun/org/apache/xerces/internal/impl/dv/DVFactoryException.java | dibt/spring-framework | ce2dfa68e2331a07d36bdcf7aa92597c91a391ee | [
"Apache-2.0"
] | 7 | 2019-03-20T09:43:08.000Z | 2021-08-20T03:19:24.000Z | jdk/src/main/java/com/sun/org/apache/xerces/internal/impl/dv/DVFactoryException.java | dibt/spring-framework | ce2dfa68e2331a07d36bdcf7aa92597c91a391ee | [
"Apache-2.0"
] | 575 | 2018-03-11T15:15:41.000Z | 2022-03-30T16:03:48.000Z | 29.697674 | 79 | 0.718089 | 999,504 | /*
* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 2001, 2002,2004 The Apache Software Foundation.
*
* 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.sun.org.apache.xerces.internal.impl.dv;
/**
* A runtime exception that's thrown if an error happens when the application
* tries to get a DV factory instance.
*
* @xerces.internal
*
*/
public class DVFactoryException extends RuntimeException {
/** Serialization version. */
static final long serialVersionUID = -3738854697928682412L;
public DVFactoryException() {
super();
}
public DVFactoryException(String msg) {
super(msg);
}
}
|
923b35535065eda0b5d74ca20ec2eb232a4f154c | 1,261 | java | Java | algo/37_Greedy/RemoveKDigits.java | escray/geektime | 87ddbe5f01d458dcaad16e28c611a8ecb8311e5b | [
"MIT"
] | null | null | null | algo/37_Greedy/RemoveKDigits.java | escray/geektime | 87ddbe5f01d458dcaad16e28c611a8ecb8311e5b | [
"MIT"
] | null | null | null | algo/37_Greedy/RemoveKDigits.java | escray/geektime | 87ddbe5f01d458dcaad16e28c611a8ecb8311e5b | [
"MIT"
] | null | null | null | 30.756098 | 89 | 0.492466 | 999,505 | public class RemoveKDigits {
/**
* 删除整数的 k 个数字,获得删除后的最小值
* @param num 原整数
* @param k 删除数量
* @return 删除后的得到的数字
*/
public static String removeKDigits(String num, int k) {
// 新整数的最终长度 = 原整数长度 - k
int newLength = num.length() - k;
// 创建一个栈,用于接收所有的数字
char[] stack = new char[num.length()];
int top = 0;
for (int i = 0; i < num.length(); ++i) {
// 遍历当前数字
char c = num.charAt(i);
// 当栈顶数字大于遍历到的当前数字
// 栈顶数字出栈(相当于删除数字)
while (top > 0 && stack[top - 1] > c && k > 0) {
top -= 1;
k -= 1;
}
// 遍历到的当前数字入栈
stack[top++] = c;
}
// 找到栈中第 1 个非领数字的位置,以此构建新的整数字符串
int offset = 0;
while (offset < newLength && stack[offset] == '0') {
offset++;
}
return offset == newLength ? "0" : new String(stack, offset, newLength - offset);
}
public static void main(String[] args) {
System.out.println(removeKDigits("1593212", 3));
System.out.println(removeKDigits("30200", 1));
System.out.println(removeKDigits("10", 2));
System.out.println(removeKDigits("541270936", 3));
}
}
|
923b3575f18dcd1ff54654aa09999ef774fc8d6e | 351 | java | Java | lohnpap-service/src/main/java/de/powerproject/lohnpap/service/LohnpapServiceApplication.java | bcoding/Lohnsteuer | bf9e445e58a944bdaed5e98841caee2452dd7f58 | [
"Apache-2.0"
] | null | null | null | lohnpap-service/src/main/java/de/powerproject/lohnpap/service/LohnpapServiceApplication.java | bcoding/Lohnsteuer | bf9e445e58a944bdaed5e98841caee2452dd7f58 | [
"Apache-2.0"
] | null | null | null | lohnpap-service/src/main/java/de/powerproject/lohnpap/service/LohnpapServiceApplication.java | bcoding/Lohnsteuer | bf9e445e58a944bdaed5e98841caee2452dd7f58 | [
"Apache-2.0"
] | null | null | null | 27 | 69 | 0.806268 | 999,506 | package de.powerproject.lohnpap.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LohnpapServiceApplication {
public static void main(String[] args) {
SpringApplication.run(LohnpapServiceApplication.class, args);
}
}
|
923b3674a0fc2c1d82854ff8ab2f57de15f6e968 | 3,207 | java | Java | oauth/src/main/java/pl/edu/icm/unity/oauth/as/token/TokenInfoResource.java | barti271/unity | 318fb9c7cd1f78b13c7dccfc7297818d8086052c | [
"BSD-3-Clause"
] | 20 | 2017-10-15T19:29:10.000Z | 2021-12-13T20:22:48.000Z | oauth/src/main/java/pl/edu/icm/unity/oauth/as/token/TokenInfoResource.java | barti271/unity | 318fb9c7cd1f78b13c7dccfc7297818d8086052c | [
"BSD-3-Clause"
] | 19 | 2017-11-02T18:08:58.000Z | 2022-02-16T00:37:05.000Z | oauth/src/main/java/pl/edu/icm/unity/oauth/as/token/TokenInfoResource.java | barti271/unity | 318fb9c7cd1f78b13c7dccfc7297818d8086052c | [
"BSD-3-Clause"
] | 8 | 2017-11-17T13:40:47.000Z | 2020-09-11T13:06:44.000Z | 30.836538 | 110 | 0.740256 | 999,507 | /*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.oauth.as.token;
import java.util.Date;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Lists;
import com.nimbusds.jwt.util.DateUtils;
import net.minidev.json.JSONObject;
import pl.edu.icm.unity.base.utils.Log;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.oauth.as.OAuthTokenRepository;
/**
* Non standard functionality: allows for validation of a given access token.
* <p>
* The request must be authorized with the bearer access token.
* <p>
* The successful response is the same as obtained when the access token is issued by the token endpoint.
* If the token is invalid then the error Bearer Token error is returned.
* <p>
* Successful response includes expiration date of the token, its scopes, associated user and client.
* <code>
* {
* "sub": "subject id",
* "client_id": "client id",
* "exp": "12345678",
* "scope": ["scope1", "scope2"]
* }
* </code>
*
* @author K. Benedyczak
*/
@Produces("application/json")
@Path(OAuthTokenEndpoint.TOKEN_INFO_PATH)
public class TokenInfoResource extends BaseTokenResource
{
private static final Logger log = Log.getLogger(Log.U_SERVER_OAUTH, TokenInfoResource.class);
public static final String SCOPE = "scope";
public static final String EXPIRATION = "exp";
public static final String SUBJECT = "sub";
public static final String CLIENT = "client_id";
public static final String AUDIENCE = "aud";
public TokenInfoResource(OAuthTokenRepository tokensDAO)
{
super(tokensDAO);
}
@Path("/")
@GET
public Response getToken(@HeaderParam("Authorization") String bearerToken)
throws EngineException, JsonProcessingException
{
TokensPair tokens;
try
{
tokens = super.resolveBearerToken(bearerToken);
log.debug("Get token {} info returning status with expiration {}",
tokenToLog(bearerToken), tokens.tokenSrc.getExpires());
} catch (OAuthTokenException e)
{
log.debug("Get token info returning error {} for token {}",
e.getErrorResponse().getStatusInfo(), tokenToLog(bearerToken));
return e.getErrorResponse();
}
JSONObject contents = toJSON(tokens.parsedToken.getSubject(), tokens.parsedToken.getClientUsername(),
tokens.tokenSrc.getExpires(),
tokens.parsedToken.getEffectiveScope(), tokens.parsedToken.getAudience());
return toResponse(Response.ok(contents.toJSONString()));
}
private JSONObject toJSON(String subject, String clientId, Date expiration, String[] scopes, String audience)
{
JSONObject ret = new JSONObject();
ret.put(SUBJECT, subject);
ret.put(CLIENT, clientId);
ret.put(EXPIRATION, DateUtils.toSecondsSinceEpoch(expiration));
if (scopes != null)
{
List<String> scopesAsList = Lists.newArrayList(scopes);
ret.put(SCOPE, scopesAsList);
}
ret.put(AUDIENCE, audience);
return ret;
}
}
|
923b3780725d648ef70d74a04b7d0755452f40a5 | 1,953 | java | Java | vtp-mock/model/src/main/java/no/nav/foreldrepenger/fpmock2/testmodell/util/TestdataUtil.java | navikt/spsak | ede4770de33bd896d62225a9617b713878d1efa5 | [
"MIT"
] | 1 | 2019-11-15T10:37:38.000Z | 2019-11-15T10:37:38.000Z | vtp-mock/model/src/main/java/no/nav/foreldrepenger/fpmock2/testmodell/util/TestdataUtil.java | navikt/spsak | ede4770de33bd896d62225a9617b713878d1efa5 | [
"MIT"
] | null | null | null | vtp-mock/model/src/main/java/no/nav/foreldrepenger/fpmock2/testmodell/util/TestdataUtil.java | navikt/spsak | ede4770de33bd896d62225a9617b713878d1efa5 | [
"MIT"
] | 1 | 2019-11-15T10:37:41.000Z | 2019-11-15T10:37:41.000Z | 32.55 | 113 | 0.698925 | 999,508 | package no.nav.foreldrepenger.fpmock2.testmodell.util;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Random;
public class TestdataUtil {
static public LocalDate generateRandomPlausibleBirtdayParent(){
LocalDate startRange = LocalDate.of(1960,1,1);
LocalDate endRange = LocalDate.of(2000,1,1);
long startEpoch = startRange.toEpochDay();
long endEpoch = endRange.toEpochDay();
Random random = new Random();
long randomEpochDay = startEpoch + (long)(random.nextDouble()*endEpoch - startEpoch);
LocalDate randomLocalDate = LocalDate.ofEpochDay(randomEpochDay);
return randomLocalDate;
}
static public LocalDate generateBirthdateNowMinusThreeYears(){
LocalDate endRange = LocalDateTime.now().toLocalDate();
LocalDate startRange = endRange.minus(3, ChronoUnit.YEARS);
long startEpoch = startRange.toEpochDay();
long endEpoch = endRange.toEpochDay();
Random random = new Random();
long randomEpochDay = startEpoch + (long)(random.nextDouble() * (endEpoch - startEpoch));
LocalDate randomLocalDate = LocalDate.ofEpochDay(randomEpochDay);
return randomLocalDate;
}
static public LocalDate generateBirthdayYoungerThanSixMonths(){
//Note: this actually returns younger than five months, but ok since it's also younger than six months...
LocalDate endRange = LocalDateTime.now().toLocalDate();
LocalDate startRange = endRange.minus(5, ChronoUnit.MONTHS);
long startEpoch = startRange.toEpochDay();
long endEpoch = endRange.toEpochDay();
Random random = new Random();
long randomEpochDay = startEpoch + (long)(random.nextDouble() * (endEpoch - startEpoch));
LocalDate randomLocalDate = LocalDate.ofEpochDay(randomEpochDay);
return randomLocalDate;
}
}
|
923b393fe4e1be4be4859e8b085087a6158bdf8f | 3,026 | java | Java | PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.core/src/com/microsoft/azure/toolkit/eclipse/common/component/AzWizardPageWrapper.java | G-arj/azure-tools-for-java | 4780137b1b07c59cb16475c9f5698fe9d3acf19b | [
"MIT"
] | 131 | 2016-03-24T05:34:57.000Z | 2019-04-23T14:41:48.000Z | PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.core/src/com/microsoft/azure/toolkit/eclipse/common/component/AzWizardPageWrapper.java | G-arj/azure-tools-for-java | 4780137b1b07c59cb16475c9f5698fe9d3acf19b | [
"MIT"
] | 2,277 | 2016-03-23T06:19:19.000Z | 2019-05-06T11:35:49.000Z | PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.core/src/com/microsoft/azure/toolkit/eclipse/common/component/AzWizardPageWrapper.java | G-arj/azure-tools-for-java | 4780137b1b07c59cb16475c9f5698fe9d3acf19b | [
"MIT"
] | 98 | 2016-03-25T03:23:42.000Z | 2019-04-09T17:42:50.000Z | 37.825 | 146 | 0.689359 | 999,509 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.toolkit.eclipse.common.component;
import com.microsoft.azure.toolkit.lib.common.form.AzureForm;
import com.microsoft.azure.toolkit.lib.common.form.AzureValidationInfo;
import com.microsoft.azure.toolkit.lib.common.task.AzureTaskManager;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public abstract class AzWizardPageWrapper<T> extends WizardPage {
protected AzWizardPageWrapper(String pageName) {
super(pageName);
}
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
this.getForm().getInputs().forEach(t -> t.addValueChangedListener(this::valueChanged));
}
}
public boolean isPageComplete() {
final List<AzureValidationInfo> infos = this.doValidateAllSync();
return infos.stream().allMatch(AzureValidationInfo::isValid);
}
private void valueChanged(Object o) {
validateAll();
}
private boolean validateAll() {
final List<AzureValidationInfo> errors = this.doValidateAllSync();
boolean valid = Objects.isNull(errors) || errors.isEmpty();
AzureTaskManager.getInstance().runLater(() -> showValidationErrors(errors));
return valid;
}
protected final void showValidationErrors(List<AzureValidationInfo> infos) {
final String titleErrorMessage = infos.isEmpty() ? null : infos.get(0).getMessage();
List<AzureValidationInfo> errors = infos.stream().filter(i -> i.getType() == AzureValidationInfo.Type.ERROR).collect(Collectors.toList());
this.setErrorMessage(errors.isEmpty() ? null : errors.get(0).getMessage());
setOkButtonEnabled(titleErrorMessage == null);
}
protected List<AzureValidationInfo> doValidateAllSync() {
List<AzureValidationInfo> infos = this.getForm().getInputs().stream().map(input ->
((AzureFormInputControl<?>) input).validateSync()
).collect(Collectors.toList());
return infos.stream().filter(i -> !i.isValid()).collect(Collectors.toList());
}
public void setOkButtonEnabled(boolean enabled) {
setPageComplete(enabled);
}
public abstract AzureForm<T> getForm();
@Override
public IWizardPage getNextPage() {
// get the code from: https://www.eclipse.org/forums/index.php/t/1008105/ to know the event when user clicks 'next'
final boolean isNextPressed = "nextPressed".equalsIgnoreCase(Thread.currentThread().getStackTrace()[2].getMethodName());
if (isNextPressed) {
final boolean validatedNextPress = validateAll();
if (!validatedNextPress) {
return this;
}
}
return super.getNextPage();
}
}
|
923b3a91b9b440c827604a0b68be038dfb05cfa3 | 4,385 | java | Java | src/test/java/com/github/msemys/esjc/ITCreatePersistentSubscription.java | dunfield-synopsys/esjc | ded2c3ea843a68f86181fe019ed1cc633af1ffd5 | [
"MIT"
] | 116 | 2016-03-11T22:24:12.000Z | 2022-02-02T07:46:34.000Z | src/test/java/com/github/msemys/esjc/ITCreatePersistentSubscription.java | dunfield-synopsys/esjc | ded2c3ea843a68f86181fe019ed1cc633af1ffd5 | [
"MIT"
] | 65 | 2016-03-25T08:54:05.000Z | 2021-09-17T08:02:13.000Z | src/test/java/com/github/msemys/esjc/ITCreatePersistentSubscription.java | dunfield-synopsys/esjc | ded2c3ea843a68f86181fe019ed1cc633af1ffd5 | [
"MIT"
] | 38 | 2016-05-28T07:07:29.000Z | 2022-03-08T14:45:54.000Z | 34.801587 | 103 | 0.673204 | 999,510 | package com.github.msemys.esjc;
import com.github.msemys.esjc.operation.AccessDeniedException;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class ITCreatePersistentSubscription extends AbstractEventStoreTest {
public ITCreatePersistentSubscription(EventStore eventstore) {
super(eventstore);
}
@Test
public void createsPersistentSubscriptionOnExistingStream() {
final String stream = generateStreamName();
final String group = "existing";
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.newBuilder()
.resolveLinkTos(false)
.startFromCurrent()
.build();
eventstore.appendToStream(stream, ExpectedVersion.ANY, newTestEvent()).join();
eventstore.createPersistentSubscription(stream, group, settings).join();
}
@Test
public void createsPersistentSubscriptionOnNonExistingStream() {
final String stream = generateStreamName();
final String group = "nonexistinggroup";
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.newBuilder()
.resolveLinkTos(false)
.startFromCurrent()
.build();
eventstore.createPersistentSubscription(stream, group, settings).join();
}
@Test
public void failsToCreateDuplicatePersistentSubscriptionGroup() {
final String stream = generateStreamName();
final String group = "group32";
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.newBuilder()
.resolveLinkTos(false)
.startFromCurrent()
.build();
eventstore.createPersistentSubscription(stream, group, settings).join();
try {
eventstore.createPersistentSubscription(stream, group, settings).join();
fail("should fail with 'IllegalStateException'");
} catch (Exception e) {
assertThat(e.getCause(), instanceOf(IllegalStateException.class));
}
}
@Test
public void createsDuplicatePersistentSubscriptionGroupNameOnDifferentStreams() {
final String stream = generateStreamName();
final String group = "group3211";
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.newBuilder()
.resolveLinkTos(false)
.startFromCurrent()
.build();
eventstore.createPersistentSubscription(stream, group, settings).join();
eventstore.createPersistentSubscription("other-" + stream, group, settings).join();
}
@Test
public void failsToCreatePersistentSubscriptionGroupWithoutPermissions() {
final String stream = "$" + generateStreamName();
final String group = "group57";
EventStore unauthenticatedEventstore = EventStoreBuilder.newBuilder(eventstore.settings())
.noUserCredentials()
.defaultExecutor()
.build();
try {
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.newBuilder()
.resolveLinkTos(false)
.startFromCurrent()
.build();
try {
unauthenticatedEventstore.createPersistentSubscription(stream, group, settings).join();
fail("should fail with 'AccessDeniedException'");
} catch (Exception e) {
assertThat(e.getCause(), instanceOf(AccessDeniedException.class));
}
} finally {
unauthenticatedEventstore.shutdown();
}
}
@Test
public void createsPersistentSubscriptionAfterDeletingTheSame() {
final String stream = generateStreamName();
final String group = "existing";
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.newBuilder()
.resolveLinkTos(false)
.startFromCurrent()
.build();
eventstore.appendToStream(stream, ExpectedVersion.ANY, newTestEvent()).join();
eventstore.createPersistentSubscription(stream, group, settings).join();
eventstore.deletePersistentSubscription(stream, group).join();
eventstore.createPersistentSubscription(stream, group, settings).join();
}
}
|
923b3b1a701c8c4bd253c4807f3c5bc7e8b9b21b | 128 | java | Java | java/java-tests/testData/codeInsight/endAction/WhiteSpaceInsertionOnJavadocDescriptionPositionNavigation.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | java/java-tests/testData/codeInsight/endAction/WhiteSpaceInsertionOnJavadocDescriptionPositionNavigation.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | java/java-tests/testData/codeInsight/endAction/WhiteSpaceInsertionOnJavadocDescriptionPositionNavigation.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | 12.8 | 36 | 0.4375 | 999,511 | class Test {
/**
*
* @param i<caret>
* @param argument
*/
void test(int i, int argument) {
}
} |
923b3b206cd69292cc5cbfe54fde3db1f7c7bddc | 170 | java | Java | src/com/colt/enigma/bottomnav/BubbleNavigationChangeListener.java | ziasam/platform_packages_apps_ColtEnigma | 6b1d1e35cbd5a8cbb0c3849c6c2ad0266a472d2c | [
"Apache-2.0"
] | null | null | null | src/com/colt/enigma/bottomnav/BubbleNavigationChangeListener.java | ziasam/platform_packages_apps_ColtEnigma | 6b1d1e35cbd5a8cbb0c3849c6c2ad0266a472d2c | [
"Apache-2.0"
] | null | null | null | src/com/colt/enigma/bottomnav/BubbleNavigationChangeListener.java | ziasam/platform_packages_apps_ColtEnigma | 6b1d1e35cbd5a8cbb0c3849c6c2ad0266a472d2c | [
"Apache-2.0"
] | 5 | 2021-07-25T03:02:52.000Z | 2022-02-26T05:03:48.000Z | 21.25 | 54 | 0.805882 | 999,512 | package com.colt.enigma.bottomnav;
import android.view.View;
public interface BubbleNavigationChangeListener {
void onNavigationChanged(View view, int position);
}
|
923b3c15e43952b8d2149483a7b35369c3adb0ed | 479 | java | Java | DAP/library/api/fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/all_definition/network_service_message/message/NetworkServiceDaoMessage.java | jorgeejgonzalez/fermat | d5f0f7c98510f19f485ac908501df46f24444190 | [
"MIT"
] | 3 | 2016-03-23T05:26:51.000Z | 2016-03-24T14:33:05.000Z | DAP/library/api/fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/all_definition/network_service_message/message/NetworkServiceDaoMessage.java | yalayn/fermat | f0a912adb66a439023ec4e70b821ba397e0f7760 | [
"MIT"
] | 17 | 2015-11-20T20:43:17.000Z | 2016-07-25T20:35:49.000Z | DAP/library/api/fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/all_definition/network_service_message/message/NetworkServiceDaoMessage.java | yalayn/fermat | f0a912adb66a439023ec4e70b821ba397e0f7760 | [
"MIT"
] | 26 | 2015-11-20T13:20:23.000Z | 2022-03-11T07:50:06.000Z | 31.933333 | 112 | 0.822547 | 999,513 | package com.bitdubai.fermat_dap_api.layer.all_definition.network_service_message.message;
import com.bitdubai.fermat_api.layer.all_definition.enums.Actors;
import com.bitdubai.fermat_dap_api.layer.all_definition.network_service_message.enums.NetworkServiceMessageType;
/**
* Created by rodrigo on 10/8/15.
*/
public class NetworkServiceDaoMessage {
NetworkServiceMessageType messageType;
Actors sourceActor;
Actors destinationActor;
Object messageContent;
} |
923b3c7a55dd787b0066b95482060e318dd2a9f1 | 1,473 | java | Java | WebAPI/src/main/java/org/ohdsi/webapi/shiro/Entities/UserEntity.java | JamesSWiggins/aws-ohdsi-automated-deployment | 743648a82140534d42a487d86956ae727207bf6e | [
"Apache-2.0"
] | 14 | 2018-03-27T01:19:16.000Z | 2019-12-04T06:20:03.000Z | WebAPI/src/main/java/org/ohdsi/webapi/shiro/Entities/UserEntity.java | JamesSWiggins/aws-ohdsi-automated-deployment | 743648a82140534d42a487d86956ae727207bf6e | [
"Apache-2.0"
] | 1 | 2019-08-09T18:30:53.000Z | 2019-08-09T18:30:53.000Z | WebAPI/src/main/java/org/ohdsi/webapi/shiro/Entities/UserEntity.java | JamesSWiggins/aws-ohdsi-automated-deployment | 743648a82140534d42a487d86956ae727207bf6e | [
"Apache-2.0"
] | 4 | 2019-02-04T23:20:08.000Z | 2019-12-09T19:33:33.000Z | 23.015625 | 135 | 0.700611 | 999,514 | package org.ohdsi.webapi.shiro.Entities;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.*;
/**
* Created by GMalikov on 24.08.2015.
*/
@Entity(name = "UserEntity")
@Table(name = "SEC_USER")
public class UserEntity implements Serializable{
private static final long serialVersionUID = -2697485161468660016L;
private Long id;
private String login;
private String password;
private String salt;
private String name;
private Set<UserRoleEntity> userRoles = new LinkedHashSet<>();
@Id
@Column(name = "ID")
@SequenceGenerator(name = "SEC_USER_SEQUENCE_GENERATOR", sequenceName = "SEC_USER_SEQUENCE", allocationSize = 1, initialValue = 1000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEC_USER_SEQUENCE_GENERATOR")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "LOGIN")
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
@Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
public Set<UserRoleEntity> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRoleEntity> userRoles) {
this.userRoles = userRoles;
}
}
|
923b3c8ef20f8d257d0cf15f915664667ae1c52a | 3,449 | java | Java | src/main/java/org/beigesoft/ws/mdlp/CartTxLn.java | demidenko05/beige-acc | 0c629794ef42947602e71d8d647d3f2e5f63bc4b | [
"BSD-2-Clause"
] | 1 | 2020-11-22T11:13:40.000Z | 2020-11-22T11:13:40.000Z | src/main/java/org/beigesoft/ws/mdlp/CartTxLn.java | demidenko05/beige-acc | 0c629794ef42947602e71d8d647d3f2e5f63bc4b | [
"BSD-2-Clause"
] | 1 | 2020-09-13T08:42:23.000Z | 2020-09-13T08:42:23.000Z | src/main/java/org/beigesoft/ws/mdlp/CartTxLn.java | demidenko05/beige-acc | 0c629794ef42947602e71d8d647d3f2e5f63bc4b | [
"BSD-2-Clause"
] | 1 | 2021-04-22T14:49:36.000Z | 2021-04-22T14:49:36.000Z | 24.992754 | 78 | 0.686286 | 999,515 | /*
BSD 2-Clause License
Copyright (c) 2019, Beigesoft™
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.
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 org.beigesoft.ws.mdlp;
import org.beigesoft.mdl.IOwneda;
import org.beigesoft.ws.mdlb.ATxLn;
import org.beigesoft.ws.mdlb.IHsSeSel;
import java.math.BigDecimal;
/**
* <p>Shoping Cart Tax Line model.
* It holds total taxes grouped by invoice (seller).</p>
*
* @author Yury Demidenko
*/
public class CartTxLn extends ATxLn implements IOwneda<Cart>, IHsSeSel<Long> {
/**
* <p>Shopping Cart.</p>
**/
private Cart ownr;
/**
* <p>SeSel which items presents in cart,
* NULL means web-store owner's items.</p>
**/
private SeSel selr;
/**
* <p>Txble amount for invoice basis, 0 - item basis..</p>
**/
private BigDecimal txb = BigDecimal.ZERO;
/**
* <p>Do not show in cart, it's for performance,
* old purchased cart emptied with this flag,
* when buyer add new goods to cart then it's used any disabled
* line (if exist) otherwise new line will be created.</p>
**/
private Boolean disab = Boolean.FALSE;
/**
* <p>Getter for ownr.</p>
* @return Cart
**/
@Override
public final Cart getOwnr() {
return this.ownr;
}
/**
* <p>Setter for ownr.</p>
* @param pOwnr reference
**/
@Override
public final void setOwnr(final Cart pOwnr) {
this.ownr = pOwnr;
}
/**
* <p>Getter for seller.</p>
* @return SeSel
**/
@Override
public final SeSel getSelr() {
return this.selr;
}
/**
* <p>Setter for seller.</p>
* @param pSeller reference
**/
@Override
public final void setSelr(final SeSel pSeller) {
this.selr = pSeller;
}
//SGS:
/**
* <p>Getter for disab.</p>
* @return Boolean
**/
public final Boolean getDisab() {
return this.disab;
}
/**
* <p>Setter for disab.</p>
* @param pDisab reference
**/
public final void setDisab(final Boolean pDisab) {
this.disab = pDisab;
}
/**
* <p>Getter for txb.</p>
* @return BigDecimal
**/
public final BigDecimal getTxb() {
return this.txb;
}
/**
* <p>Setter for txb.</p>
* @param pTxb reference
**/
public final void setTxb(final BigDecimal pTxb) {
this.txb = pTxb;
}
}
|
923b3d09692132da3d2c3e6473f18d38d5e5401b | 12,427 | java | Java | src/test/java/com/habeebcycle/demo/api/ReactiveApiRedisApplicationTests.java | HabeebCycle/spring-reactive-redis-api | 7814633db8d59dea4b1d020576183bfbe037ecc6 | [
"Apache-2.0"
] | 6 | 2021-02-06T10:55:16.000Z | 2022-01-15T06:58:44.000Z | src/test/java/com/habeebcycle/demo/api/ReactiveApiRedisApplicationTests.java | HabeebCycle/spring-reactive-redis-api | 7814633db8d59dea4b1d020576183bfbe037ecc6 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/habeebcycle/demo/api/ReactiveApiRedisApplicationTests.java | HabeebCycle/spring-reactive-redis-api | 7814633db8d59dea4b1d020576183bfbe037ecc6 | [
"Apache-2.0"
] | null | null | null | 34.816901 | 116 | 0.711246 | 999,516 | package com.habeebcycle.demo.api;
import com.habeebcycle.demo.api.model.User;
import com.habeebcycle.demo.api.service.UserService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import redis.embedded.RedisServer;
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"spring.redis.password="}
)
class ReactiveApiRedisApplicationTests {
@Autowired
private WebTestClient client;
@Autowired
private UserService userService;
private static final RedisServer REDISSERVER = new RedisServer(6379);
@BeforeAll
static void startUpRedisServer() {
REDISSERVER.start();
}
@AfterAll
static void shutDownRedisServer() {
REDISSERVER.stop();
}
@BeforeEach
void setUpDB() {
userService.deleteAllUsers().block();
Assertions.assertEquals(0L, userService.userCount().block());
}
@Test
void createUserTest() {
User userA = new User("username", "email", "name");
postAndVerifyUser(userA, HttpStatus.OK)
.jsonPath("$.id").isNotEmpty()
.jsonPath("$.username").isEqualTo("username")
.jsonPath("$.email").isEqualTo("email")
.jsonPath("$.name").isEqualTo("name");
// Return error for empty username
User userB = new User("", "envkt@example.com", "name");
postAndVerifyUser(userB, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user")
.jsonPath("$.message").isEqualTo("Cannot be saved: username and email are required, but one or both is empty.");
// Return error for empty email
User userC = new User("usernameC", "", "name");
postAndVerifyUser(userB, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user")
.jsonPath("$.message").isEqualTo("Cannot be saved: username and email are required, but one or both is empty.");
StepVerifier.create(userService.userCount())
.expectNext(1L)
.verifyComplete();
Assertions.assertEquals(1L, userService.userCount().block());
}
@Test
void getUserByIdTest() {
User user = new User("username", "envkt@example.com", "name");
postAndVerifyUser(user, HttpStatus.OK)
.jsonPath("$.id").isNotEmpty();
User foundUser = userService.getUserByUsername(user.getUsername()).block();
Assertions.assertNotNull(foundUser);
Assertions.assertNotNull(foundUser.getId());
Assertions.assertEquals(user.getUsername(), foundUser.getUsername());
Assertions.assertEquals(user.getEmail(), foundUser.getEmail());
Assertions.assertEquals(user.getName(), foundUser.getName());
getAndVerifyUserById(foundUser.getId(), HttpStatus.OK)
.jsonPath("$.username").isEqualTo(user.getUsername())
.jsonPath("$.email").isEqualTo(user.getEmail())
.jsonPath("$.name").isEqualTo(user.getName());
StepVerifier.create(userService.userCount())
.expectNext(1L)
.verifyComplete();
}
@Test
void getAllUsersTest() {
User user1 = new User("username1", "ychag@example.com", "name1");
User user2 = new User("username2", "anpch@example.com", "name2");
User user3 = new User("username3", "envkt@example.com", "name3");
postAndVerifyUser(user1, HttpStatus.OK);
postAndVerifyUser(user2, HttpStatus.OK);
postAndVerifyUser(user3, HttpStatus.OK);
getAndVerifyUser("", HttpStatus.OK)
.jsonPath("$.length()").isEqualTo(3);
StepVerifier.create(userService.userCount())
.expectNext(3L)
.verifyComplete();
}
@Test
void duplicateErrorTest() {
// Create and save userA, verify it has saved correctly
User userA = new User("username", "envkt@example.com", "name");
postAndVerifyUser(userA, HttpStatus.OK)
.jsonPath("$.id").isNotEmpty()
.jsonPath("$.username").isEqualTo("username")
.jsonPath("$.email").isEqualTo("envkt@example.com")
.jsonPath("$.name").isEqualTo("name");
// Create and try to save userB with the same username and verify it fails
User userB = new User("username", "envkt@example.com", "name");
postAndVerifyUser(userB, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user")
.jsonPath("$.message").isEqualTo("Duplicate key, Username: " +
userB.getUsername() + " or Email: " + userB.getEmail() + " exists.");
// Create and try to save userB with the same email and verify it fails
userB = new User("new_username", "envkt@example.com", "name");
postAndVerifyUser(userB, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user")
.jsonPath("$.message").isEqualTo("Duplicate key, Username: " +
userB.getUsername() + " or Email: " + userB.getEmail() + " exists.");
// Create and try to save userB with the same username and email and verify it fails
userB = new User("username", "envkt@example.com", "name");
postAndVerifyUser(userB, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user")
.jsonPath("$.message").isEqualTo("Duplicate key, Username: " +
userB.getUsername() + " or Email: " + userB.getEmail() + " exists.");
// Create and try to save userB with the different username and email and verify it works
userB = new User("new_username", "envkt@example.com", "name");
postAndVerifyUser(userB, HttpStatus.OK)
.jsonPath("$.id").isNotEmpty()
.jsonPath("$.username").isEqualTo("new_username")
.jsonPath("$.email").isEqualTo("envkt@example.com")
.jsonPath("$.name").isEqualTo("name");
// Try to update userA with the same email of userB and verify it fails
userA = userService.getUserByUsername(userA.getUsername()).block();
Assertions.assertNotNull(userA);
Assertions.assertNotNull(userA.getId());
userA.setEmail(userB.getEmail());
updateAndVerifyUser(userA, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user/" + userA.getId())
.jsonPath("$.message").isEqualTo("Duplicate key, Username: " +
userA.getUsername() + " or Email: " + userA.getEmail() + " exists.");
// Try to update userA with the same username of userB and verify it fails
userA.setUsername(userB.getUsername());
updateAndVerifyUser(userA, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user/" + userA.getId())
.jsonPath("$.message").isEqualTo("Duplicate key, Username: " +
userA.getUsername() + " or Email: " + userA.getEmail() + " exists.");
// Try to update userA with the same username and email of userB and verify it fails
userA.setUsername(userB.getUsername());
userA.setEmail(userB.getEmail());
updateAndVerifyUser(userA, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user/" + userA.getId())
.jsonPath("$.message").isEqualTo("Duplicate key, Username: " +
userA.getUsername() + " or Email: " + userA.getEmail() + " exists.");
// Try to update userA with the new username and verify it works
String newUsername = "updated_username";
String userAEmail = "envkt@example.com";
userA.setUsername(newUsername);
userA.setEmail(userAEmail);
updateAndVerifyUser(userA, HttpStatus.OK)
.jsonPath("$.id").isEqualTo(userA.getId())
.jsonPath("$.username").isEqualTo(newUsername)
.jsonPath("$.email").isEqualTo(userAEmail)
.jsonPath("$.name").isEqualTo(userA.getName())
.jsonPath("$.version").isEqualTo(1);
//Make sure we have two entities in the database
StepVerifier.create(userService.userCount())
.expectNext(2L)
.verifyComplete();
}
@Test
void optimisticErrorTest() {
User user = new User("username", "envkt@example.com", "name");
postAndVerifyUser(user, HttpStatus.OK)
.jsonPath("$.username").isEqualTo("username")
.jsonPath("$.email").isEqualTo("envkt@example.com")
.jsonPath("$.name").isEqualTo("name");
User user1 = userService.getUserByUsername(user.getUsername()).block();
User user2 = userService.getUserByEmail(user.getEmail()).block();
Assertions.assertNotNull(user1);
Assertions.assertNotNull(user2);
Assertions.assertEquals(user1.getId(), user2.getId());
Assertions.assertEquals(user1.getVersion(), user2.getVersion());
user1.setName("updated-name");
user2.setName("updated-name");
updateAndVerifyUser(user1, HttpStatus.OK)
.jsonPath("$.username").isEqualTo("username")
.jsonPath("$.email").isEqualTo("envkt@example.com")
.jsonPath("$.name").isEqualTo("updated-name")
.jsonPath("$.version").isEqualTo(1);
updateAndVerifyUser(user2, HttpStatus.INTERNAL_SERVER_ERROR)
.jsonPath("$.path").isEqualTo("/user/" + user2.getId())
.jsonPath("$.message").isEqualTo("This record has already been updated earlier by another object.");
getAndVerifyUserById(user2.getId(), HttpStatus.OK)
.jsonPath("$.username").isEqualTo("username")
.jsonPath("$.email").isEqualTo("envkt@example.com")
.jsonPath("$.name").isEqualTo("updated-name")
.jsonPath("$.version").isEqualTo(1);
StepVerifier.create(userService.userCount())
.expectNext(1L)
.verifyComplete();
}
@Test
void updateUserTest() {
User user = new User("username", "envkt@example.com", "name");
postAndVerifyUser(user, HttpStatus.OK)
.jsonPath("$.username").isEqualTo("username")
.jsonPath("$.email").isEqualTo("envkt@example.com")
.jsonPath("$.name").isEqualTo("name");
user = userService.getUserByUsername(user.getUsername()).block();
Assertions.assertNotNull(user);
Assertions.assertNotNull(user.getId());
user.setUsername("updated-username");
updateAndVerifyUser(user, HttpStatus.OK);
getAndVerifyUserById(user.getId(), HttpStatus.OK)
.jsonPath("$.username").isEqualTo("updated-username")
.jsonPath("$.version").isEqualTo(1);
StepVerifier.create(userService.userCount())
.expectNext(1L)
.verifyComplete();
}
@Test
void deleteUserTest() {
User user1 = new User("username1", "ychag@example.com", "name1");
User user2 = new User("username2", "anpch@example.com", "name2");
User user3 = new User("username3", "envkt@example.com", "name3");
postAndVerifyUser(user1, HttpStatus.OK);
postAndVerifyUser(user2, HttpStatus.OK);
postAndVerifyUser(user3, HttpStatus.OK);
getAndVerifyUser("", HttpStatus.OK)
.jsonPath("$.length()").isEqualTo(3);
StepVerifier.create(userService.userCount())
.expectNext(3L)
.verifyComplete();
user1 = userService.getUserByEmail(user1.getEmail()).block();
Assertions.assertNotNull(user1);
Assertions.assertNotNull(user1.getId());
deleteAndVerifyUserById(user1.getId(), HttpStatus.OK);
StepVerifier.create(userService.userCount())
.expectNext(2L)
.verifyComplete();
deleteAndVerifyUserById("", HttpStatus.OK);
StepVerifier.create(userService.userCount())
.expectNext(0L)
.verifyComplete();
deleteAndVerifyUserById("", HttpStatus.OK);
}
// Utility Methods
private WebTestClient.BodyContentSpec getAndVerifyUserById(String userId, HttpStatus expectedStatus) {
return getAndVerifyUser("/" + userId, expectedStatus);
}
private WebTestClient.BodyContentSpec getAndVerifyUser(String path, HttpStatus expectedStatus) {
return client.get()
.uri("/user" + path)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isEqualTo(expectedStatus)
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody();
}
private WebTestClient.BodyContentSpec postAndVerifyUser(User user, HttpStatus expectedStatus) {
return client.post()
.uri("/user")
.body(Mono.just(user), User.class)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isEqualTo(expectedStatus)
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody();
}
private WebTestClient.BodyContentSpec deleteAndVerifyUserById(String userId, HttpStatus expectedStatus) {
return client.delete()
.uri("/user/" + userId)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isEqualTo(expectedStatus)
.expectBody();
}
private WebTestClient.BodyContentSpec updateAndVerifyUser(User user, HttpStatus expectedStatus) {
return client.put()
.uri("/user/" + user.getId())
.body(Mono.just(user), User.class)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isEqualTo(expectedStatus)
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody();
}
}
|
923b3df6d0b90a83ccb9827c44bec0820facfacc | 1,019 | java | Java | pinyougou_dao/src/main/java/com/pinyougou/mapper/TbSpecificationMapper.java | WuliGitH/ProductOptimal | c6e7d9caeb71df97245c5e683e46ce9b60ad09be | [
"Apache-2.0"
] | 15 | 2019-03-18T08:19:32.000Z | 2019-07-11T11:28:07.000Z | pinyougou_dao/src/main/java/com/pinyougou/mapper/TbSpecificationMapper.java | JacianLiu/ProductOptimal | c6e7d9caeb71df97245c5e683e46ce9b60ad09be | [
"Apache-2.0"
] | 1 | 2019-01-03T02:02:45.000Z | 2019-02-19T16:10:07.000Z | pinyougou_dao/src/main/java/com/pinyougou/mapper/TbSpecificationMapper.java | RickyLiuJ/ProductOptimal | c6e7d9caeb71df97245c5e683e46ce9b60ad09be | [
"Apache-2.0"
] | 7 | 2019-01-25T09:20:13.000Z | 2019-03-13T01:35:14.000Z | 29.114286 | 124 | 0.795878 | 999,517 | package com.pinyougou.mapper;
import com.pinyougou.pojo.TbSpecification;
import com.pinyougou.pojo.TbSpecificationExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface TbSpecificationMapper {
int countByExample(TbSpecificationExample example);
int deleteByExample(TbSpecificationExample example);
int deleteByPrimaryKey(Long id);
int insert(TbSpecification record);
int insertSelective(TbSpecification record);
List<TbSpecification> selectByExample(TbSpecificationExample example);
TbSpecification selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TbSpecification record, @Param("example") TbSpecificationExample example);
int updateByExample(@Param("record") TbSpecification record, @Param("example") TbSpecificationExample example);
int updateByPrimaryKeySelective(TbSpecification record);
int updateByPrimaryKey(TbSpecification record);
List<Map> selectBrandList();
} |
923b3ef46f58e5ce206b0a3562a67502ced2548a | 5,396 | java | Java | code/java/QuotesAPIforDigitalPortals/v2/src/main/java/com/factset/sdk/QuotesAPIforDigitalPortals/models/InlineResponse20051DataCurrency.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 6 | 2022-02-07T16:34:18.000Z | 2022-03-30T08:04:57.000Z | code/java/QuotesAPIforDigitalPortals/v2/src/main/java/com/factset/sdk/QuotesAPIforDigitalPortals/models/InlineResponse20051DataCurrency.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 2 | 2022-02-07T05:25:57.000Z | 2022-03-07T14:18:04.000Z | code/java/QuotesAPIforDigitalPortals/v2/src/main/java/com/factset/sdk/QuotesAPIforDigitalPortals/models/InlineResponse20051DataCurrency.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | null | null | null | 29.648352 | 137 | 0.732024 | 999,518 | /*
* Prime Developer Trial
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.factset.sdk.QuotesAPIforDigitalPortals.models;
import java.util.Objects;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigDecimal;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.factset.sdk.QuotesAPIforDigitalPortals.JSON;
/**
* Main currency of the coupon payments. See endpoint `/basic/valueUnit/currency/main/list` for possible values.
*/
@ApiModel(description = "Main currency of the coupon payments. See endpoint `/basic/valueUnit/currency/main/list` for possible values. ")
@JsonPropertyOrder({
InlineResponse20051DataCurrency.JSON_PROPERTY_ID,
InlineResponse20051DataCurrency.JSON_PROPERTY_CODE,
InlineResponse20051DataCurrency.JSON_PROPERTY_ISO_CODE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class InlineResponse20051DataCurrency implements Serializable {
private static final long serialVersionUID = 1L;
public static final String JSON_PROPERTY_ID = "id";
private BigDecimal id;
public static final String JSON_PROPERTY_CODE = "code";
private String code;
public static final String JSON_PROPERTY_ISO_CODE = "isoCode";
private String isoCode;
public InlineResponse20051DataCurrency() {
}
public InlineResponse20051DataCurrency id(BigDecimal id) {
this.id = id;
return this;
}
/**
* Identifier of the main currency.
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Identifier of the main currency.")
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public BigDecimal getId() {
return id;
}
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setId(BigDecimal id) {
this.id = id;
}
public InlineResponse20051DataCurrency code(String code) {
this.code = code;
return this;
}
/**
* Code of the currency: If assigned, a code according to ISO 4217, otherwise a local code.
* @return code
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Code of the currency: If assigned, a code according to ISO 4217, otherwise a local code.")
@JsonProperty(JSON_PROPERTY_CODE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getCode() {
return code;
}
@JsonProperty(JSON_PROPERTY_CODE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setCode(String code) {
this.code = code;
}
public InlineResponse20051DataCurrency isoCode(String isoCode) {
this.isoCode = isoCode;
return this;
}
/**
* ISO 4217 code of the value unit. Empty if the ISO 4217 standard does not define a code for the currency.
* @return isoCode
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "ISO 4217 code of the value unit. Empty if the ISO 4217 standard does not define a code for the currency.")
@JsonProperty(JSON_PROPERTY_ISO_CODE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getIsoCode() {
return isoCode;
}
@JsonProperty(JSON_PROPERTY_ISO_CODE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}
/**
* Return true if this inline_response_200_51_data_currency object is equal to o.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InlineResponse20051DataCurrency inlineResponse20051DataCurrency = (InlineResponse20051DataCurrency) o;
return Objects.equals(this.id, inlineResponse20051DataCurrency.id) &&
Objects.equals(this.code, inlineResponse20051DataCurrency.code) &&
Objects.equals(this.isoCode, inlineResponse20051DataCurrency.isoCode);
}
@Override
public int hashCode() {
return Objects.hash(id, code, isoCode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InlineResponse20051DataCurrency {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" isoCode: ").append(toIndentedString(isoCode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
923b3f661629aad09a5909ca8c41cfecdff3a70d | 847 | java | Java | app/src/main/java/com/example/ashi/coolweather/db/County.java | AlanShiai/coolweather | 86eaa4ff9fa05ad4a97e89039495c22c99eb6f4f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/ashi/coolweather/db/County.java | AlanShiai/coolweather | 86eaa4ff9fa05ad4a97e89039495c22c99eb6f4f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/ashi/coolweather/db/County.java | AlanShiai/coolweather | 86eaa4ff9fa05ad4a97e89039495c22c99eb6f4f | [
"Apache-2.0"
] | null | null | null | 16.607843 | 50 | 0.612751 | 999,519 | package com.example.ashi.coolweather.db;
import org.litepal.crud.DataSupport;
/**
* Created by ashi on 6/30/18.
*/
public class County extends DataSupport {
private int id;
private String countyName;
private String weatherId;
private int cityId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getWeatherId() {
return weatherId;
}
public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
|
923b4015ccb1464aa611dbd6b37aa24cc55e028d | 2,308 | java | Java | java/classes2/com/xiaomi/push/service/h.java | gaoht/house | b9e63db1a4975b614c422fed3b5b33ee57ea23fd | [
"Apache-2.0"
] | 1 | 2020-05-08T05:35:32.000Z | 2020-05-08T05:35:32.000Z | java/classes2/com/xiaomi/push/service/h.java | gaoht/house | b9e63db1a4975b614c422fed3b5b33ee57ea23fd | [
"Apache-2.0"
] | null | null | null | java/classes2/com/xiaomi/push/service/h.java | gaoht/house | b9e63db1a4975b614c422fed3b5b33ee57ea23fd | [
"Apache-2.0"
] | 3 | 2018-09-07T08:15:08.000Z | 2020-05-22T03:59:12.000Z | 29.974026 | 128 | 0.64818 | 999,520 | package com.xiaomi.push.service;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;
import com.xiaomi.channel.commonutils.logger.b;
import com.xiaomi.metok.geofencing.a;
import com.xiaomi.xmpush.thrift.j;
import java.util.ArrayList;
import java.util.Iterator;
public class h
{
public static void a(Context paramContext, String paramString)
{
Object localObject = e.a(paramContext).b(paramString);
if ((localObject == null) || (((ArrayList)localObject).size() < 1)) {}
for (;;)
{
return;
if (e.a(paramContext).e(paramString) == 0) {
b.a("appIsUninstalled. failed to delete geofencing with package name. name:" + paramString);
}
localObject = ((ArrayList)localObject).iterator();
while (((Iterator)localObject).hasNext())
{
j localj = (j)((Iterator)localObject).next();
if (localj == null)
{
b.a("appIsUninstalled. failed to find geofence with package name. name:" + paramString);
return;
}
a(localj.a(), paramContext);
if (g.a(paramContext).b(localj.a()) == 0) {
b.a("appIsUninstalled. failed to delete geoMessage with package name. name:" + paramString + ", geoId:" + localj.a());
}
}
}
}
public static void a(String paramString, Context paramContext)
{
new a(paramContext).a(paramContext, "com.xiaomi.xmsf", paramString);
}
public static boolean a(Context paramContext)
{
try
{
paramContext = paramContext.getPackageManager().getPackageInfo("com.xiaomi.metok", 8192);
if ((paramContext != null) && (paramContext.versionCode >= 20)) {
return true;
}
}
catch (PackageManager.NameNotFoundException paramContext)
{
for (;;)
{
paramContext = null;
}
}
return false;
}
public static boolean b(Context paramContext)
{
return TextUtils.equals(paramContext.getPackageName(), "com.xiaomi.xmsf");
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/xiaomi/push/service/h.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
923b408d91da6d88ecf4d7930eb32bc164fee27f | 3,325 | java | Java | projo-template-annotation/src/main/java/pro/projo/template/annotation/Configuration.java | raner/projo | f011596d7db780955b287d0ea6713e49eecc20f0 | [
"Apache-2.0"
] | 1 | 2020-08-14T22:02:17.000Z | 2020-08-14T22:02:17.000Z | projo-template-annotation/src/main/java/pro/projo/template/annotation/Configuration.java | raner/projo | f011596d7db780955b287d0ea6713e49eecc20f0 | [
"Apache-2.0"
] | 79 | 2017-02-02T07:14:16.000Z | 2022-03-29T05:57:20.000Z | projo-template-annotation/src/main/java/pro/projo/template/annotation/Configuration.java | raner/projo | f011596d7db780955b287d0ea6713e49eecc20f0 | [
"Apache-2.0"
] | null | null | null | 39.117647 | 105 | 0.578045 | 999,521 | // //
// Copyright 2018 - 2021 Mirko Raner //
// //
// 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 pro.projo.template.annotation;
import java.io.Writer;
import java.util.Map;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import pro.projo.interfaces.annotation.Options;
/**
* The {@link Configuration} interface describes the fully-qualified class name and the input
* parameters for an individual template invocation. A template can be invoke multiple times
* with different configurations.
*
* @author Mirko Raner
**/
public interface Configuration
{
/**
* @return the fully qualified name of the class to be generated
**/
String fullyQualifiedClassName();
/**
* @return additional parameters that need to be inserted into the code generation template
**/
Map<String, Object> parameters();
/**
* @return an operator that wraps the output writer into a filtering writer for post-processing
**/
default UnaryOperator<Writer> postProcessor()
{
return UnaryOperator.identity();
}
/**
* Retrieves additional configuration options that were provided as an annotation parameter or
* package annotation.
*
* @return the specified {@link Options} or a default {@link Options} object if not specified
**/
default Options options()
{
return defaults();
}
/**
* Checks if the specified option is set to the default value. This method will also return true
* if an option parameter was specified but happens to be identical to the default value
* (e.g., {@code @Option(fileExtension=".java")}).
*
* @param option the option to check (typically as a method reference)
* @return {@code true} if the option value is identical to the default value, {@code false} otherwise
**/
default boolean isDefault(Function<Options, ?> option)
{
return isDefault(options(), option);
}
default boolean isDefault(Options options, Function<Options, ?> option)
{
return option.apply(defaults()).equals(option.apply(options));
}
static Options defaults()
{
return Options.class.getPackage().getAnnotation(Options.class);
}
}
|
923b40a5f92c46f788615c30d47698e1ba1756ee | 4,847 | java | Java | classpath-0.98/gnu/javax/crypto/jce/GnuSasl.java | nmldiegues/jvm-stm | d422d78ba8efc99409ecb49efdb4edf4884658df | [
"Apache-2.0"
] | 2 | 2015-09-08T15:40:04.000Z | 2017-02-09T15:19:33.000Z | llvm-gcc-4.2-2.9/libjava/classpath/gnu/javax/crypto/jce/GnuSasl.java | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/libjava/classpath/gnu/javax/crypto/jce/GnuSasl.java | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | 38.776 | 76 | 0.712812 | 999,522 | /* GnuSasl.java -- javax.security.sasl algorithms.
Copyright (C) 2004, 2006 Free Software Foundation, Inc.
This file is a part of GNU Classpath.
GNU Classpath 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.
GNU Classpath 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 GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.jce;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.ClientFactory;
import gnu.javax.crypto.sasl.ServerFactory;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.Provider;
import java.util.Set;
public final class GnuSasl
extends Provider
{
public GnuSasl()
{
super(Registry.GNU_SASL, 2.1, "GNU SASL Provider");
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
// SASL Client and Server mechanisms
put("SaslClientFactory.ANONYMOUS",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslClientFactory.PLAIN",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslClientFactory.CRAM-MD5",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslClientFactory.SRP",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslServerFactory.ANONYMOUS",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.PLAIN",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.CRAM-MD5",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-MD5",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-SHA-160",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-RIPEMD128",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-RIPEMD160",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-TIGER",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-WHIRLPOOL",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("Alg.Alias.SaslServerFactory.SRP-SHS", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA1", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA-1", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA160", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-RIPEMD-128", "SRP-RIPEMD128");
put("Alg.Alias.SaslServerFactory.SRP-RIPEMD-160", "SRP-RIPEMD160");
return null;
}
});
}
/**
* Returns a {@link Set} of names of SASL Client mechanisms available from
* this {@link Provider}.
*
* @return a {@link Set} of SASL Client mechanisms (Strings).
*/
public static final Set getSaslClientMechanismNames()
{
return ClientFactory.getNames();
}
/**
* Returns a {@link Set} of names of SASL Server mechanisms available from
* this {@link Provider}.
*
* @return a {@link Set} of SASL Server mechanisms (Strings).
*/
public static final Set getSaslServerMechanismNames()
{
return ServerFactory.getNames();
}
}
|
923b40ed1cff5e7dae5d79243e41f0a5c61cd0d4 | 398 | java | Java | city/src/main/java/com/silencedut/city/repository/db/CityDatabase.java | ccoder7/KnowWeather | 08f2fedcf2bf20958150c174182dd571b5d27ccb | [
"Apache-2.0"
] | 1,301 | 2016-12-07T06:26:30.000Z | 2022-03-18T12:58:12.000Z | city/src/main/java/com/silencedut/city/repository/db/CityDatabase.java | willpyshan13/KnowWeather | 08f2fedcf2bf20958150c174182dd571b5d27ccb | [
"Apache-2.0"
] | 24 | 2016-12-08T09:37:56.000Z | 2021-01-30T04:25:47.000Z | city/src/main/java/com/silencedut/city/repository/db/CityDatabase.java | willpyshan13/KnowWeather | 08f2fedcf2bf20958150c174182dd571b5d27ccb | [
"Apache-2.0"
] | 305 | 2016-12-07T06:26:08.000Z | 2022-03-17T06:18:21.000Z | 23.411765 | 57 | 0.773869 | 999,523 | package com.silencedut.city.repository.db;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.RoomDatabase;
import com.silencedut.weather_core.api.cityprovider.City;
/**
* Created by SilenceDut on 2018/1/5 .
*/
@Database(entities = {City.class}, version = 1)
public abstract class CityDatabase extends RoomDatabase {
public abstract CityDao cityDao();
}
|
923b41771ee7d149148273a39b074e01063eda19 | 3,182 | java | Java | spring-batch-core/src/test/java/org/springframework/batch/core/SpringBeanJobTests.java | rchandavaram/spring-batch | d3fa7d084b95938b1c91f11bd76b70c7f6a76ae7 | [
"Apache-2.0"
] | 1,909 | 2015-01-01T15:28:52.000Z | 2022-03-31T15:07:45.000Z | spring-batch-core/src/test/java/org/springframework/batch/core/SpringBeanJobTests.java | AlanBinu007/spring-batch | d6419f4479157ac666159403f7ba0908d817fab6 | [
"Apache-2.0"
] | 929 | 2015-01-02T17:33:55.000Z | 2022-03-30T14:48:19.000Z | spring-batch-core/src/test/java/org/springframework/batch/core/SpringBeanJobTests.java | AlanBinu007/spring-batch | d6419f4479157ac666159403f7ba0908d817fab6 | [
"Apache-2.0"
] | 1,987 | 2015-01-05T05:10:29.000Z | 2022-03-30T21:06:47.000Z | 37.435294 | 76 | 0.778441 | 999,524 | /*
* Copyright 2006-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.batch.core.job.JobSupport;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.ChildBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
public class SpringBeanJobTests {
@Test
public void testBeanName() throws Exception {
StaticApplicationContext context = new StaticApplicationContext();
JobSupport configuration = new JobSupport();
context.getAutowireCapableBeanFactory().initializeBean(configuration,
"bean");
context.refresh();
assertNotNull(configuration.getName());
configuration.setBeanName("foo");
context.getAutowireCapableBeanFactory().initializeBean(configuration,
"bean");
assertEquals("bean", configuration.getName());
context.close();
}
@Test
public void testBeanNameWithBeanDefinition() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
ConstructorArgumentValues args = new ConstructorArgumentValues();
args.addGenericArgumentValue("foo");
context.registerBeanDefinition("bean", new RootBeanDefinition(
JobSupport.class, args, null));
context.refresh();
JobSupport configuration = (JobSupport) context
.getBean("bean");
assertNotNull(configuration.getName());
assertEquals("foo", configuration.getName());
configuration.setBeanName("bar");
assertEquals("foo", configuration.getName());
context.close();
}
@Test
public void testBeanNameWithParentBeanDefinition() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
ConstructorArgumentValues args = new ConstructorArgumentValues();
args.addGenericArgumentValue("bar");
context.registerBeanDefinition("parent", new RootBeanDefinition(
JobSupport.class, args, null));
context.registerBeanDefinition("bean", new ChildBeanDefinition("parent"));
context.refresh();
JobSupport configuration = (JobSupport) context
.getBean("bean");
assertNotNull(configuration.getName());
assertEquals("bar", configuration.getName());
configuration.setBeanName("foo");
assertEquals("bar", configuration.getName());
configuration.setName("foo");
assertEquals("foo", configuration.getName());
context.close();
}
}
|
923b428a09cb11aac1007ccfb2df25c39d783d14 | 4,225 | java | Java | sample/src/main/java/biz/kasual/materialnumberpickersample/MainActivity.java | bskim45/MaterialNumberPicker | 1b0b884fdc15197683b84135c31342c7acd32901 | [
"Apache-2.0"
] | 158 | 2015-10-11T17:58:41.000Z | 2022-02-22T20:27:26.000Z | sample/src/main/java/biz/kasual/materialnumberpickersample/MainActivity.java | bskim45/MaterialNumberPicker | 1b0b884fdc15197683b84135c31342c7acd32901 | [
"Apache-2.0"
] | 25 | 2015-10-15T11:53:41.000Z | 2021-03-01T08:30:31.000Z | sample/src/main/java/biz/kasual/materialnumberpickersample/MainActivity.java | bskim45/MaterialNumberPicker | 1b0b884fdc15197683b84135c31342c7acd32901 | [
"Apache-2.0"
] | 27 | 2016-01-21T15:00:39.000Z | 2022-02-27T04:37:28.000Z | 37.061404 | 155 | 0.624379 | 999,525 | package biz.kasual.materialnumberpickersample;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import biz.kasual.materialnumberpicker.MaterialNumberPicker;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mDefaultButton;
private Button mSimpleButton;
private Button mCustomButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDefaultButton = (Button)findViewById(R.id.default_number_picker_button);
mSimpleButton = (Button)findViewById(R.id.simple_number_picker_button);
mCustomButton = (Button)findViewById(R.id.custom_number_picker_button);
mDefaultButton.setOnClickListener(this);
mSimpleButton.setOnClickListener(this);
mCustomButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final NumberPicker picker;
String alertTitle = null;
if (v.equals(mDefaultButton)) {
alertTitle = getString(R.string.alert_default_title);
picker = new NumberPicker(this);
picker.setMinValue(1);
picker.setMaxValue(10);
}
else {
MaterialNumberPicker.Builder numberPickerBuilder = new MaterialNumberPicker.Builder(this);
if (v.equals(mSimpleButton)) {
alertTitle = getString(R.string.alert_simple_title);
}
else if (v.equals(mCustomButton)) {
alertTitle = getString(R.string.alert_custom_title);
numberPickerBuilder
.minValue(1)
.maxValue(50)
.defaultValue(10)
.separatorColor(ContextCompat.getColor(this, R.color.colorAccent))
.textColor(ContextCompat.getColor(this, R.color.colorPrimary))
.textSize(25)
.formatter(new NumberPicker.Formatter() {
@Override
public String format(int value) {
return "Formatted text for value " + value;
}
});
}
picker = numberPickerBuilder.build();
}
new AlertDialog.Builder(this)
.setTitle(alertTitle)
.setView(picker)
.setNegativeButton(getString(android.R.string.cancel), null)
.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Snackbar.make(findViewById(R.id.main_container), getString(R.string.picker_value, picker.getValue()), Snackbar.LENGTH_LONG).show();
}
})
.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
923b43e04f0181ecd756eac05548602d87f8f985 | 175 | java | Java | src/org.xtuml.bp.core/src/org/xtuml/bp/core/ui/IDelegateWizard.java | FMAY-Software/bridgepoint | 90d95f21441dfc90568a2e88ccc221f06a2480db | [
"Apache-2.0"
] | 29 | 2015-04-08T04:02:08.000Z | 2022-03-16T07:32:13.000Z | src/org.xtuml.bp.core/src/org/xtuml/bp/core/ui/IDelegateWizard.java | FMAY-Software/bridgepoint | 90d95f21441dfc90568a2e88ccc221f06a2480db | [
"Apache-2.0"
] | 92 | 2015-03-24T21:05:19.000Z | 2021-09-24T01:48:33.000Z | src/org.xtuml.bp.core/src/org/xtuml/bp/core/ui/IDelegateWizard.java | FMAY-Software/bridgepoint | 90d95f21441dfc90568a2e88ccc221f06a2480db | [
"Apache-2.0"
] | 82 | 2015-01-09T16:50:50.000Z | 2022-03-25T03:16:16.000Z | 17.5 | 50 | 0.76 | 999,526 | package org.xtuml.bp.core.ui;
import org.eclipse.jface.wizard.IWizard;
public interface IDelegateWizard extends IWizard {
public void setExtraData(Object data);
}
|
923b4465e398c2f68184aae8b968c055f97ea81c | 2,165 | java | Java | src/io/ph/bot/commands/Command.java | hortenio97/momo-2 | 7a7276324a50ce8769527cf49ac344683b8c844a | [
"MIT"
] | 5 | 2018-11-30T19:55:29.000Z | 2019-08-21T19:31:10.000Z | src/io/ph/bot/commands/Command.java | hortenio97/momo-2 | 7a7276324a50ce8769527cf49ac344683b8c844a | [
"MIT"
] | 1 | 2018-11-30T22:06:51.000Z | 2018-12-01T19:16:13.000Z | src/io/ph/bot/commands/Command.java | hortenio97/momo-2 | 7a7276324a50ce8769527cf49ac344683b8c844a | [
"MIT"
] | 5 | 2018-12-28T14:17:15.000Z | 2021-04-15T13:24:38.000Z | 25.77381 | 109 | 0.68545 | 999,527 | package io.ph.bot.commands;
import io.ph.bot.model.Permission;
import io.ph.util.Util;
import net.dv8tion.jda.core.entities.Message;
public abstract class Command {
private int commandCount = 0;
/**
* Execute this command
* @param msg Original Message. Can infer guild, user, etc off of this
*/
public abstract void executeCommand(Message msg);
/**
* Get default command syntax
* @return Default syntax
*/
public String getDefaultCommand() {
return this.getClass().getAnnotation(CommandData.class).defaultSyntax();
}
/**
* Check if user has permissions
* @param msg Original message
* @return True if good to go, false if not
*/
public boolean hasPermissions(Message msg) {
return Util.memberHasPermission(msg.getGuild().getMember(msg.getAuthor()), getPermission());
}
/**
* Get permission required
* @return Permission required
*/
public Permission getPermission() {
return this.getClass().getAnnotation(CommandData.class).permission();
}
/**
* Get aliases of command
* @return Aliases of this command
*/
public String[] getAliases() {
return this.getClass().getAnnotation(CommandData.class).aliases();
}
/**
* Get description
* @return Description of command
*/
public String getDescription() {
return this.getClass().getAnnotation(CommandData.class).description();
}
/**
* Get example. Do not include the default command, as that is automatically appended
* If you have multiple examples, use a \n linebreak to designate. Again, do not include the command itself
* @return Example in annotation
*/
public String getExample() {
return this.getClass().getAnnotation(CommandData.class).example();
}
/**
* Get the number of times this command has been called
* @return Number of times this command has been executed
*/
public int getCommandCount() {
return this.commandCount;
}
/**
* Increment the command counter
*/
public void incrementCommandCount() {
this.commandCount++;
}
@Override
public String toString() {
return getDefaultCommand().toLowerCase();
}
}
|
923b4790b390de7151b123d9112f274219a572f7 | 987 | java | Java | src/main/java/org/jretty/socket/tcp/SocketTools.java | jretty-org/socket-tool | 2761c155779b7400423195c3aec6bb3f682b216f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/jretty/socket/tcp/SocketTools.java | jretty-org/socket-tool | 2761c155779b7400423195c3aec6bb3f682b216f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/jretty/socket/tcp/SocketTools.java | jretty-org/socket-tool | 2761c155779b7400423195c3aec6bb3f682b216f | [
"Apache-2.0"
] | null | null | null | 23.5 | 64 | 0.500507 | 999,528 | package org.jretty.socket.tcp;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
class SocketTools {
private SocketTools() {
}
static String copyToString(Reader in) throws IOException {
StringWriter out = new StringWriter();
clone(in, out);
return out.toString();
}
static int clone(Reader in, Writer out) throws IOException {
try {
int byteCount = 0;
char[] buffer = new char[4096];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
return byteCount;
} finally {
try {
out.flush();
} catch (IOException e) {
}
try {
out.close();
} catch (IOException ex) {
}
}
}
}
|
923b479a5030e9033328cdc808728a1aeb2e221b | 1,532 | java | Java | sample/webservice/eBayDemoApp/src/com/ebay/trading/api/PayoutMethodType.java | 4everalone/nano | 71779b1ad546663ee90a29f1c2d4236a6948a621 | [
"Apache-2.0"
] | 3 | 2016-01-27T20:05:27.000Z | 2018-01-16T13:11:38.000Z | sample/hello-ebay-trading/src/main/java/com/ebay/trading/api/PayoutMethodType.java | maxep/NanoKit | 7bb39fdd456f9af4f2d2dad937d482620c797a4e | [
"Apache-2.0"
] | null | null | null | sample/hello-ebay-trading/src/main/java/com/ebay/trading/api/PayoutMethodType.java | maxep/NanoKit | 7bb39fdd456f9af4f2d2dad937d482620c797a4e | [
"Apache-2.0"
] | 1 | 2015-09-02T02:40:36.000Z | 2015-09-02T02:40:36.000Z | 25.114754 | 113 | 0.617493 | 999,529 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
/**
*
* Enumeration type that contains the payout methods available to DE and AT sellers for orders going through the
* new eBay payment process flow. Once a DE or AT seller has accepted the supplemental user agreement for the new
* eBay payment process, that seller must set the default payout account in My eBay preferences. eBay will
* distribute seller payouts to this account.
*
*/
public enum PayoutMethodType {
/**
*
* This value indicates that the seller wants eBay to distribute payouts to their PayPal account.
*
*/
PAYPAL("PAYPAL"),
/**
*
* This value indicates that the seller wants eBay to distribute payouts to their bank account via EFT
* (Electronic Funds Transfer).
*
*/
EFT("EFT"),
/**
*
* This value indicates that the seller wants eBay to distribute payouts to their Moneybookers (Skrill)
* account.
*
*/
MONEYBOOKERS("MONEYBOOKERS");
private final String value;
PayoutMethodType(String v) {
value = v;
}
public String value() {
return value;
}
public static PayoutMethodType fromValue(String v) {
if (v != null) {
for (PayoutMethodType c: PayoutMethodType.values()) {
if (c.value.equals(v)) {
return c;
}
}
}
throw new IllegalArgumentException(v);
}
} |
923b481a9f9daa00a13360fa49bc3cf0b11fb43a | 2,925 | java | Java | hadooptool/src/main/java/com/robin/comm/fileaccess/iterator/AvroFileIterator.java | robinhood-jim/JavaFramework | 5a23c33fe5bd49b5d35b582733d8622e8b3e9bf7 | [
"Apache-2.0"
] | 16 | 2019-11-15T06:11:00.000Z | 2022-01-17T02:45:06.000Z | hadooptool/src/main/java/com/robin/comm/fileaccess/iterator/AvroFileIterator.java | robinhood-jim/JavaFramework | 5a23c33fe5bd49b5d35b582733d8622e8b3e9bf7 | [
"Apache-2.0"
] | 7 | 2020-04-23T18:52:06.000Z | 2022-02-26T00:46:20.000Z | hadooptool/src/main/java/com/robin/comm/fileaccess/iterator/AvroFileIterator.java | robinhood-jim/JavaFramework | 5a23c33fe5bd49b5d35b582733d8622e8b3e9bf7 | [
"Apache-2.0"
] | 1 | 2021-09-02T13:07:39.000Z | 2021-09-02T13:07:39.000Z | 27.59434 | 94 | 0.754188 | 999,530 | package com.robin.comm.fileaccess.iterator;
import com.robin.core.base.util.IOUtils;
import com.robin.core.base.util.ResourceConst;
import com.robin.core.fileaccess.iterator.AbstractFileIterator;
import com.robin.core.fileaccess.meta.DataCollectionMeta;
import com.robin.core.fileaccess.util.AvroUtils;
import com.robin.hadoop.hdfs.HDFSUtil;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.FileReader;
import org.apache.avro.file.SeekableByteArrayInput;
import org.apache.avro.file.SeekableInput;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.hadoop.fs.AvroFSInput;
import org.apache.hadoop.fs.FSDataInputStream;
import org.springframework.util.Assert;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AvroFileIterator extends AbstractFileIterator {
private Schema schema;
private GenericDatumReader<GenericRecord> dreader=null;
private FileReader<GenericRecord> fileReader;
public AvroFileIterator(DataCollectionMeta colmeta) {
super(colmeta);
}
@Override
public boolean hasNext() {
try{
return fileReader.hasNext();
}catch(Exception ex){
logger.error("",ex);
}
return false;
}
@Override
public void beforeProcess(String resourcePath) {
SeekableInput input=null;
try {
schema= AvroUtils.getSchemaFromMeta(colmeta);
if(colmeta.getSourceType().equals(ResourceConst.InputSourceType.TYPE_HDFS.getValue())){
HDFSUtil util=new HDFSUtil(colmeta);
instream=util.getHDFSDataByInputStream(resourcePath);
input=new AvroFSInput(new FSDataInputStream(instream),util.getHDFSFileSize(resourcePath));
}else {
instream=accessUtil.getInResourceByStream(colmeta,resourcePath);
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
IOUtils.copyBytes(instream, byteout, 8064);
input = new SeekableByteArrayInput(byteout.toByteArray());
}
Assert.notNull(input,"Seekable input is null");
dreader=new GenericDatumReader<>(schema);
fileReader=new DataFileReader<>(input,dreader);
}catch (Exception ex){
logger.error("Exception {0}",ex);
}
}
@Override
public Map<String, Object> next() {
Map<String,Object> retmap=new HashMap<>();
try{
GenericRecord records=fileReader.next();
List<Field> flist=schema.getFields();
for (Field f:flist) {
retmap.put(f.name(), records.get(f.name()).toString());
}
}catch(Exception ex){
logger.error("",ex);
}
return retmap;
}
public Schema getSchema() {
return schema;
}
@Override
public void remove() {
try{
fileReader.next();
}catch(Exception ex){
logger.error("",ex);
}
}
@Override
public void close() throws IOException {
if(fileReader!=null){
fileReader.close();
}
super.close();
}
}
|
923b488669b78c727552d7545e2adbc8f9c5cbc6 | 538 | java | Java | j2e-chapter-6/shiroweb/src/main/java/com/woniu/entity/RolePermission.java | tlhhup/JavaEE-EFD | 672240565afc1f302abd174541a199bafc9ad702 | [
"Apache-2.0"
] | null | null | null | j2e-chapter-6/shiroweb/src/main/java/com/woniu/entity/RolePermission.java | tlhhup/JavaEE-EFD | 672240565afc1f302abd174541a199bafc9ad702 | [
"Apache-2.0"
] | 11 | 2021-05-08T18:09:01.000Z | 2022-03-31T20:52:56.000Z | j2e-chapter-6/shiroweb/src/main/java/com/woniu/entity/RolePermission.java | tlhhup/JavaEE-EFD | 672240565afc1f302abd174541a199bafc9ad702 | [
"Apache-2.0"
] | 1 | 2020-06-17T04:52:03.000Z | 2020-06-17T04:52:03.000Z | 20.692308 | 56 | 0.700743 | 999,531 | package com.woniu.entity;
public class RolePermission {
private Integer id;
private String permissionname;
private Integer roleId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPermissionname() {
return permissionname;
}
public void setPermissionname(String permissionname) {
this.permissionname = permissionname;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
}
|
923b4886a038f004a55a53c8a15b5701e81b0015 | 966 | java | Java | extra-Huurder/test/TestOpgave2.java | coenribbens/Avans_programming1 | 2fbe0da7ede0c45dbd04454fd4f2ca94145b26f4 | [
"MIT"
] | null | null | null | extra-Huurder/test/TestOpgave2.java | coenribbens/Avans_programming1 | 2fbe0da7ede0c45dbd04454fd4f2ca94145b26f4 | [
"MIT"
] | null | null | null | extra-Huurder/test/TestOpgave2.java | coenribbens/Avans_programming1 | 2fbe0da7ede0c45dbd04454fd4f2ca94145b26f4 | [
"MIT"
] | null | null | null | 28.411765 | 168 | 0.726708 | 999,532 |
import org.junit.Test;
import org.junit.Rule;
import java.lang.reflect.Field;
import static org.junit.Assert.*;
import fi.helsinki.cs.tmc.edutestutils.Points;
import fi.helsinki.cs.tmc.edutestutils.MockStdio;
import fi.helsinki.cs.tmc.edutestutils.ReflectionUtils;
import fi.helsinki.cs.tmc.edutestutils.Reflex;
import org.junit.Before;
@Points("extra2")
public class TestOpgave2 {
@Rule
public MockStdio io = new MockStdio();
Reflex.ClassRef<Object> huurderKlasse;
@Before
public void init() {
huurderKlasse = Reflex.reflect("Huurder");
}
@Test
public void testGetters()
{
assertTrue("Huurder has to have a getNaam() getter", huurderKlasse.method("getNaam").returning(String.class).takingNoParams().withNiceError().isPublic());
assertTrue("Huurder has to have a getMaxHuur() getter", huurderKlasse.method("getMaxHuur").returning(double.class).takingNoParams().withNiceError().isPublic());
}
}
|
923b4926d36f0db66cacfff9e49a9080fb009a21 | 576 | java | Java | retrofitlibrary/src/main/java/top/zfandlove/retrofitlibrary/SSLi.java | Dhaojie6688/retrofitDemo | 993a3faa834895712d3f51c648cb87b13c00f890 | [
"Apache-2.0"
] | null | null | null | retrofitlibrary/src/main/java/top/zfandlove/retrofitlibrary/SSLi.java | Dhaojie6688/retrofitDemo | 993a3faa834895712d3f51c648cb87b13c00f890 | [
"Apache-2.0"
] | null | null | null | retrofitlibrary/src/main/java/top/zfandlove/retrofitlibrary/SSLi.java | Dhaojie6688/retrofitDemo | 993a3faa834895712d3f51c648cb87b13c00f890 | [
"Apache-2.0"
] | null | null | null | 17.454545 | 43 | 0.645833 | 999,533 | package top.zfandlove.retrofitlibrary;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
/**
* Created by zfan on 2017/12/27.
*/
public interface SSLi {
/**
* 获取证书工厂
*
* @return SSLSocketFactory
*/
SSLSocketFactory getSSLCertification();
/**
* 域名验证
*
* @return HostnameVerifier
*/
HostnameVerifier getHostnameVerifier();
/**
* X509TrustManager
*
* @return X509TrustManager
*/
X509TrustManager getX509TrustManager();
}
|
923b4a5999798c8cce4349e1043e91c756527bd0 | 4,106 | java | Java | src/android/GpsDetector.java | Hyperonic/gps.detector | 8cc129756375306ba70bc01108f762e485a4bbc0 | [
"MIT"
] | null | null | null | src/android/GpsDetector.java | Hyperonic/gps.detector | 8cc129756375306ba70bc01108f762e485a4bbc0 | [
"MIT"
] | null | null | null | src/android/GpsDetector.java | Hyperonic/gps.detector | 8cc129756375306ba70bc01108f762e485a4bbc0 | [
"MIT"
] | null | null | null | 37.669725 | 131 | 0.651486 | 999,534 | package com.butterflyeffect.plugins;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GpsDetector extends CordovaPlugin implements LocationListener {
boolean alertShown = false;
@Override
public boolean execute(String action, final JSONArray args, CallbackContext callbackContext) {
PluginResult result = null;
boolean gpsEnabled = false;
String GPSDetectionAction = "gpsDetection";
if (action.equals(GPSDetectionAction)) {
//android.content.ContentResolver contentResolver = cordova.getActivity().getApplicationContext().getContentResolver();
//gpsEnabled = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
Context ctx = cordova.getActivity().getApplicationContext();
LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
try {
if(!gpsEnabled && !args.getBoolean(0)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
showGPSDisabledAlertToUser();
}
else alertShown = false;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = new PluginResult(Status.OK, gpsEnabled);
Log.i("gpsEnabled", (gpsEnabled) ? "yes" : "no");
}
else {
result = new PluginResult(Status.INVALID_ACTION);
}
callbackContext.sendPluginResult(result);
return true;
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(cordova.getActivity());
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
cordova.getActivity().startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
if(LocationManager.GPS_PROVIDER.equals(s)){
Toast.makeText(cordova.getActivity(),"GPS on",Toast.LENGTH_SHORT).show();
Log.i("onProviderEnabled", "enabled");
}
}
@Override
public void onProviderDisabled(String s) {
if(LocationManager.GPS_PROVIDER.equals(s)){
Toast.makeText(cordova.getActivity(),"GPS off",Toast.LENGTH_SHORT).show();
Log.i("onProviderDisabled", "disabled");
}
}
} |
923b4a9e4c0bd37ba416dfdf777032dc6ffca8e9 | 2,167 | java | Java | guns-admin/src/main/java/com/stylefeng/guns/cache/PlcConfigCache.java | 438483836/centre | bfe3c8be53a0d9ba5201e2fdb86715a7027d8981 | [
"Apache-2.0"
] | null | null | null | guns-admin/src/main/java/com/stylefeng/guns/cache/PlcConfigCache.java | 438483836/centre | bfe3c8be53a0d9ba5201e2fdb86715a7027d8981 | [
"Apache-2.0"
] | null | null | null | guns-admin/src/main/java/com/stylefeng/guns/cache/PlcConfigCache.java | 438483836/centre | bfe3c8be53a0d9ba5201e2fdb86715a7027d8981 | [
"Apache-2.0"
] | null | null | null | 31.867647 | 104 | 0.702353 | 999,535 | package com.stylefeng.guns.cache;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.PLC.service.IPlcConfigService;
import com.stylefeng.guns.modular.system.model.PlcConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Vincent on 2018-08-22.
*/
@Service
@Cacheable(value = "plcCache")
public class PlcConfigCache implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(PlcConfigCache.class);
private static ApplicationContext applicationContext;
private static List<PlcConfig> plcConfigList = new ArrayList<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
startService();
}
private void startService(){
init();
}
public static PlcConfig getSortPlcConfig() {
for (PlcConfig plcConfig : plcConfigList){
if (ToolUtil.equals("1",plcConfig.getType()) && ToolUtil.equals("1",plcConfig.getIsUsed())){
return plcConfig;
}
}
return null;
}
public static PlcConfig getBuMaPlcConfig(){
for (PlcConfig plcConfig:plcConfigList){
if (ToolUtil.equals("2",plcConfig.getType())&&ToolUtil.equals("1",plcConfig.getIsUsed())){
return plcConfig;
}
}
return null;
}
public static void init() {
IPlcConfigService plcConfigService = applicationContext.getBean(IPlcConfigService.class);
plcConfigList = plcConfigService.selectList(null);
if (ToolUtil.isEmpty(plcConfigList)){
logger.info("init cache fail,tbl_plc_config is null");
}else {
logger.info("init cache success");
}
}
}
|
923b4aa51a836ede23f9cdba15b2d4d19468b466 | 2,167 | java | Java | core/src/test/java/org/infinispan/tx/recovery/InDoubtXidReturnedOnceTest.java | clara0/infinispan | f2cb717bbd51dd8e3e4265679585cd637a55bed5 | [
"Apache-2.0"
] | 713 | 2015-01-06T02:14:17.000Z | 2022-03-29T10:22:07.000Z | core/src/test/java/org/infinispan/tx/recovery/InDoubtXidReturnedOnceTest.java | clara0/infinispan | f2cb717bbd51dd8e3e4265679585cd637a55bed5 | [
"Apache-2.0"
] | 5,732 | 2015-01-01T19:13:35.000Z | 2022-03-31T16:31:11.000Z | core/src/test/java/org/infinispan/tx/recovery/InDoubtXidReturnedOnceTest.java | clara0/infinispan | f2cb717bbd51dd8e3e4265679585cd637a55bed5 | [
"Apache-2.0"
] | 402 | 2015-01-05T23:23:42.000Z | 2022-03-25T08:14:32.000Z | 35.52459 | 107 | 0.72958 | 999,536 | package org.infinispan.tx.recovery;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.AssertJUnit.assertEquals;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.recovery.InDoubtXidReturnedOnceTest")
public class InDoubtXidReturnedOnceTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
configuration
.locking()
.useLockStriping(false)
.transaction()
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery()
.enable()
.clustering()
.stateTransfer()
.fetchInMemoryState(false)
.hash()
.numOwners(3);
createCluster(configuration, 4);
waitForClusterToForm();
}
public void testXidReturnedOnlyOnce() throws Throwable {
EmbeddedTransaction tx = beginAndSuspendTx(this.cache(3));
prepareTransaction(tx);
manager(3).stop();
TestingUtil.blockUntilViewsReceived(60000, false, cache(0), cache(1), cache(2));
TestingUtil.waitForNoRebalance(cache(0), cache(1), cache(2));
EmbeddedTransaction tx2 = beginAndSuspendTx(this.cache(0));
Xid[] recover = tx2.firstEnlistedResource().recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);
assertEquals(recover.length,1);
assertEquals(tx.getXid(), recover[0]);
}
}
|
923b4acfd4aed865e48c5b2e2ce15886221f553d | 1,856 | java | Java | jena-text/src/main/java/org/apache/jena/query/text/analyzer/LowerCaseKeywordAnalyzer.java | costas80/jena | 7d146c5c265196c9c2740948fd1cd22b21aca033 | [
"Apache-2.0"
] | null | null | null | jena-text/src/main/java/org/apache/jena/query/text/analyzer/LowerCaseKeywordAnalyzer.java | costas80/jena | 7d146c5c265196c9c2740948fd1cd22b21aca033 | [
"Apache-2.0"
] | 1 | 2022-02-05T16:08:39.000Z | 2022-02-05T16:08:41.000Z | jena-text/src/main/java/org/apache/jena/query/text/analyzer/LowerCaseKeywordAnalyzer.java | costas80/jena | 7d146c5c265196c9c2740948fd1cd22b21aca033 | [
"Apache-2.0"
] | null | null | null | 38.666667 | 76 | 0.731142 | 999,537 | /**
* 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.jena.query.text.analyzer ;
import org.apache.lucene.analysis.Analyzer ;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.KeywordTokenizer ;
import org.apache.lucene.analysis.core.LowerCaseFilter ;
/**
* Lucene Analyzer implementation that works like KeywordAnalyzer (i.e.
* doesn't tokenize the input, keeps it as a single token), but forces text
* to lowercase and is thus case-insensitive.
*/
public class LowerCaseKeywordAnalyzer extends Analyzer {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
KeywordTokenizer source = new KeywordTokenizer();
LowerCaseFilter filter = new LowerCaseFilter(source);
return new TokenStreamComponents(source, filter);
}
// As a consequence of LUCENE-7355 now need to Override normalize
@Override
protected TokenStream normalize(String fieldName, TokenStream in) {
return new LowerCaseFilter(in);
}
}
|
923b4ad970e0cf911b0e8f5671636f6ef5de47a0 | 170 | java | Java | src/itens/armaduras/ArmaduraPesada.java | Joao-Pedro-MB/MC322-HeroQuest | 6411b93a217d636bd2e9cde1b0cdd0a4cc5a2da8 | [
"MIT"
] | null | null | null | src/itens/armaduras/ArmaduraPesada.java | Joao-Pedro-MB/MC322-HeroQuest | 6411b93a217d636bd2e9cde1b0cdd0a4cc5a2da8 | [
"MIT"
] | null | null | null | src/itens/armaduras/ArmaduraPesada.java | Joao-Pedro-MB/MC322-HeroQuest | 6411b93a217d636bd2e9cde1b0cdd0a4cc5a2da8 | [
"MIT"
] | null | null | null | 17 | 46 | 0.735294 | 999,538 | package itens.armaduras;
import itens.Armadura;
public class ArmaduraPesada extends Armadura {
public ArmaduraPesada() {
super("Armadura pesada", 2, 3, true);
}
}
|
923b4c185296d5b2d766b66ee9f225f7912ae3c4 | 499 | java | Java | sources/com/google/android/gms/auth/api/signin/C8615a.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2019-10-01T11:34:10.000Z | 2019-10-01T11:34:10.000Z | sources/com/google/android/gms/auth/api/signin/C8615a.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | null | null | null | sources/com/google/android/gms/auth/api/signin/C8615a.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2020-05-26T05:10:33.000Z | 2020-05-26T05:10:33.000Z | 26.263158 | 77 | 0.683367 | 999,539 | package com.google.android.gms.auth.api.signin;
import com.google.android.gms.common.api.Scope;
import java.util.Comparator;
/* renamed from: com.google.android.gms.auth.api.signin.a */
final /* synthetic */ class C8615a implements Comparator {
/* renamed from: a */
static final Comparator f19462a = new C8615a();
private C8615a() {
}
public final int compare(Object obj, Object obj2) {
return ((Scope) obj).mo27412a().compareTo(((Scope) obj2).mo27412a());
}
}
|
923b4c4c8e5ad9ac101d11e1f5819e21be03245e | 226 | java | Java | src/main/java/by/jackraidenph/dragonsurvival/network/RefreshDragons.java | DragonMak/DragonSurvival | 948800beff90265e808d8b1505baf5470f47bc2b | [
"Apache-2.0"
] | 20 | 2021-04-23T04:54:01.000Z | 2022-03-30T11:59:42.000Z | src/main/java/by/jackraidenph/dragonsurvival/network/RefreshDragons.java | BlackAures1/DragonSurvival | b6eb83de3c08ef39c7652cf9a3ae30df702dbb8a | [
"Apache-2.0"
] | 82 | 2021-04-17T12:15:23.000Z | 2022-03-31T22:59:12.000Z | src/main/java/by/jackraidenph/dragonsurvival/network/RefreshDragons.java | BlackAures1/DragonSurvival | b6eb83de3c08ef39c7652cf9a3ae30df702dbb8a | [
"Apache-2.0"
] | 17 | 2020-10-19T10:11:29.000Z | 2022-03-01T05:31:32.000Z | 17.384615 | 47 | 0.685841 | 999,540 | package by.jackraidenph.dragonsurvival.network;
public class RefreshDragons {
public int playerId;
public RefreshDragons(int playerId) {
this.playerId = playerId;
}
public RefreshDragons() {
}
}
|
923b4cd83238b1210478071adc2a0517bdaaeb81 | 2,298 | java | Java | src/main/java/io/atomix/client/channel/ChannelConfig.java | adibrastegarnia/java-client | 94f7ab76de594132e1e375bda8ab78a595c185a1 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/atomix/client/channel/ChannelConfig.java | adibrastegarnia/java-client | 94f7ab76de594132e1e375bda8ab78a595c185a1 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/atomix/client/channel/ChannelConfig.java | adibrastegarnia/java-client | 94f7ab76de594132e1e375bda8ab78a595c185a1 | [
"Apache-2.0"
] | null | null | null | 26.72093 | 124 | 0.649695 | 999,541 | /*
* Copyright 2019-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.client.channel;
/**
* TLS configuration.
*/
public class ChannelConfig {
private boolean enabled = Boolean.parseBoolean(System.getProperty("io.atomix.enableNettyTLS", Boolean.toString(false)));
private String certPath = System.getProperty("io.atomix.messaging.tls.certPath");
private String keyPath = System.getProperty("io.atomix.messaging.tls.keyPath");
/**
* Returns whether TLS is enabled.
*
* @return indicates whether TLS is enabled
*/
public boolean isTlsEnabled() {
return enabled;
}
/**
* Sets whether TLS is enabled.
*
* @param enabled whether TLS is enabled
* @return the TLS configuration
*/
public ChannelConfig setTlsEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Returns the certificate chain path.
*
* @return the certificate chain path
*/
public String getCertPath() {
return certPath;
}
/**
* Sets the certificate chain path.
*
* @param certPath the certificate chain path
* @return the TLS configuration
*/
public ChannelConfig setCertPath(String certPath) {
this.certPath = certPath;
return this;
}
/**
* Returns the private key path.
*
* @return the private key path
*/
public String getKeyPath() {
return keyPath;
}
/**
* Sets the private key path.
*
* @param keyPath the private key path
* @return the TLS configuration
*/
public ChannelConfig setKeyPath(String keyPath) {
this.keyPath = keyPath;
return this;
}
}
|
923b4df2419968e0a97c7b055308b54f0ddecf87 | 2,013 | java | Java | src/net/sf/jazzlib/DeflaterPending.java | sorlok/ornagai-mobile | 643e7dafb8d346dc6c2f9828edf876d6383ab957 | [
"MIT"
] | 1 | 2021-11-01T13:15:59.000Z | 2021-11-01T13:15:59.000Z | src/net/sf/jazzlib/DeflaterPending.java | sorlok/ornagai-mobile | 643e7dafb8d346dc6c2f9828edf876d6383ab957 | [
"MIT"
] | null | null | null | src/net/sf/jazzlib/DeflaterPending.java | sorlok/ornagai-mobile | 643e7dafb8d346dc6c2f9828edf876d6383ab957 | [
"MIT"
] | null | null | null | 36.6 | 70 | 0.785892 | 999,542 | /* net.sf.jazzlib.DeflaterPending
Copyright (C) 2001 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package net.sf.jazzlib;
/**
* This class stores the pending output of the Deflater.
*
* @author Jochen Hoenicke
* @date Jan 5, 2000
*/
class DeflaterPending extends PendingBuffer
{
public DeflaterPending()
{
super(DeflaterConstants.PENDING_BUF_SIZE);
}
}
|
923b4e5c38385c1f7ec556339b82efcac534df33 | 1,126 | java | Java | src/main/java/com/shimizukenta/jsoncommunicator/SimpleJsonCommunicatorServerBindLog.java | kenta-shimizu/secs-cli-simulator | b3d093860ceb328e3ebea58be90ffef170fe45eb | [
"Apache-2.0"
] | 9 | 2020-08-18T09:28:48.000Z | 2021-12-29T09:52:07.000Z | src/main/java/com/shimizukenta/jsoncommunicator/SimpleJsonCommunicatorServerBindLog.java | kenta-shimizu/secs-cli-simulator | b3d093860ceb328e3ebea58be90ffef170fe45eb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/shimizukenta/jsoncommunicator/SimpleJsonCommunicatorServerBindLog.java | kenta-shimizu/secs-cli-simulator | b3d093860ceb328e3ebea58be90ffef170fe45eb | [
"Apache-2.0"
] | 4 | 2020-12-30T02:59:59.000Z | 2022-03-30T03:28:19.000Z | 35.1875 | 124 | 0.818828 | 999,543 | package com.shimizukenta.jsoncommunicator;
import java.net.SocketAddress;
public final class SimpleJsonCommunicatorServerBindLog extends AbstractJsonCommunicatorServerBindLog {
private static final long serialVersionUID = -123468483221227445L;
private SimpleJsonCommunicatorServerBindLog(CharSequence subject, SocketAddress addr, boolean isBinded, boolean isClosed) {
super(subject, addr, isBinded, isClosed);
}
private static final String commonTryBind = "server-Try-Bind";
public static SimpleJsonCommunicatorServerBindLog tryBind(SocketAddress addr) {
return new SimpleJsonCommunicatorServerBindLog(commonTryBind, addr, false, false);
}
private static final String commonBinded = "Server-Binded";
public static SimpleJsonCommunicatorServerBindLog binded(SocketAddress addr) {
return new SimpleJsonCommunicatorServerBindLog(commonBinded, addr, true, false);
}
private static final String commonClosed = "Server-Closed";
public static SimpleJsonCommunicatorServerBindLog closed(SocketAddress addr) {
return new SimpleJsonCommunicatorServerBindLog(commonClosed, addr, false, true);
}
}
|
923b5002dd6b908012eaff0c65be67d7716519ae | 920 | java | Java | app/src/main/java/com/misterright/ui/mine/NoticeActivity.java | ruiaa/MisterRight | 13abe6a22d8a9e2a85e2cfe5a169edabb8b839bf | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/misterright/ui/mine/NoticeActivity.java | ruiaa/MisterRight | 13abe6a22d8a9e2a85e2cfe5a169edabb8b839bf | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/misterright/ui/mine/NoticeActivity.java | ruiaa/MisterRight | 13abe6a22d8a9e2a85e2cfe5a169edabb8b839bf | [
"Apache-2.0"
] | null | null | null | 27.878788 | 85 | 0.716304 | 999,544 | package com.misterright.ui.mine;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import com.misterright.R;
import com.misterright.databinding.ActivityMeNoticeBinding;
import com.misterright.ui.base.ToolbarActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
public class NoticeActivity extends ToolbarActivity {
@BindView(R.id.me_notice_list)
RecyclerView noticeList;
private ActivityMeNoticeBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_me_notice);
ButterKnife.bind(this);
initToolbar();
setTitle(R.string.notice);
setToolbarLeftShow(v -> {
onBackPressed();
});
}
}
|
923b502c97ed17118e7d5fe7274f0e75b266c900 | 4,589 | java | Java | hazelcast/src/main/java/com/hazelcast/internal/util/DirectoryLock.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 4,283 | 2015-01-02T03:56:10.000Z | 2022-03-29T23:07:45.000Z | hazelcast/src/main/java/com/hazelcast/internal/util/DirectoryLock.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 14,014 | 2015-01-01T04:29:38.000Z | 2022-03-31T21:47:55.000Z | hazelcast/src/main/java/com/hazelcast/internal/util/DirectoryLock.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 1,608 | 2015-01-04T09:57:08.000Z | 2022-03-31T12:05:26.000Z | 33.253623 | 117 | 0.635868 | 999,545 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.util;
import com.hazelcast.core.HazelcastException;
import com.hazelcast.logging.ILogger;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import static com.hazelcast.internal.nio.IOUtil.closeResource;
/**
* A DirectoryLock represents a lock on a specific directory.
* <p>
* DirectoryLock is acquired by calling {@link #lockForDirectory(File, ILogger)}.
*/
public final class DirectoryLock {
public static final String FILE_NAME = "lock";
private final File dir;
private final FileChannel channel;
private final FileLock lock;
private final ILogger logger;
private DirectoryLock(File dir, FileChannel channel, FileLock lock, ILogger logger) {
this.dir = dir;
this.channel = channel;
this.lock = lock;
this.logger = logger;
}
/**
* Returns the locked directory.
*/
public File getDir() {
return dir;
}
/**
* Returns the actual {@link FileLock}.
*/
FileLock getLock() {
return lock;
}
/**
* Releases the lock on directory.
*/
public void release() {
if (logger.isFineEnabled()) {
logger.fine("Releasing lock on " + lockFile().getAbsolutePath());
}
try {
lock.release();
} catch (ClosedChannelException e) {
EmptyStatement.ignore(e);
} catch (IOException e) {
logger.severe("Problem while releasing the lock on " + lockFile(), e);
}
try {
channel.close();
} catch (IOException e) {
logger.severe("Problem while closing the channel " + lockFile(), e);
}
}
private File lockFile() {
return new File(dir, FILE_NAME);
}
/**
* Acquires a lock for given directory. A special file, named <strong>lock</strong>,
* is created inside the directory and that file is locked.
*
* @param dir the directory
* @param logger logger
* @throws HazelcastException If lock file cannot be created or it's already locked
*/
public static DirectoryLock lockForDirectory(File dir, ILogger logger) {
File lockFile = new File(dir, FILE_NAME);
FileChannel channel = openChannel(lockFile);
FileLock lock = acquireLock(lockFile, channel);
if (logger.isFineEnabled()) {
logger.fine("Acquired lock on " + lockFile.getAbsolutePath());
}
return new DirectoryLock(dir, channel, lock, logger);
}
private static FileChannel openChannel(File lockFile) {
try {
return new RandomAccessFile(lockFile, "rw").getChannel();
} catch (IOException e) {
throw new HazelcastException("Cannot create lock file " + lockFile.getAbsolutePath(), e);
}
}
private static FileLock acquireLock(File lockFile, FileChannel channel) {
FileLock fileLock = null;
try {
fileLock = channel.tryLock();
if (fileLock == null) {
throw new HazelcastException("Cannot acquire lock on " + lockFile.getAbsolutePath()
+ ". Directory is already being used by another member.");
}
return fileLock;
} catch (OverlappingFileLockException e) {
throw new HazelcastException("Cannot acquire lock on " + lockFile.getAbsolutePath()
+ ". Directory is already being used by another member.", e);
} catch (IOException e) {
throw new HazelcastException("Unknown failure while acquiring lock on " + lockFile.getAbsolutePath(), e);
} finally {
if (fileLock == null) {
closeResource(channel);
}
}
}
}
|
923b50aa489ce5ee164cfdd07dd8a88b43ab0c11 | 2,610 | java | Java | opsli-modulars/opsli-modulars-system/src/main/java/org/opsli/modulars/system/user/service/IUserService.java | wuchunfu/opsli-boot | 0dfe674a4f0612e1f03ac5747b41a7484fb41d27 | [
"Apache-2.0"
] | 457 | 2020-09-13T10:07:11.000Z | 2022-03-31T07:44:40.000Z | opsli-modulars/opsli-modulars-system/src/main/java/org/opsli/modulars/system/user/service/IUserService.java | dvlp-org/opsli-boot | 9f1399bc9643385144751c1877e12ad2c763f961 | [
"Apache-2.0"
] | 10 | 2020-11-22T06:54:50.000Z | 2022-01-29T09:08:19.000Z | opsli-modulars/opsli-modulars-system/src/main/java/org/opsli/modulars/system/user/service/IUserService.java | dvlp-org/opsli-boot | 9f1399bc9643385144751c1877e12ad2c763f961 | [
"Apache-2.0"
] | 138 | 2020-09-13T14:20:59.000Z | 2022-03-23T13:20:12.000Z | 25.096154 | 89 | 0.676628 | 999,546 | /**
* Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.opsli.modulars.system.user.service;
import org.opsli.api.wrapper.system.user.ToUserPassword;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.api.wrapper.system.user.UserPassword;
import org.opsli.api.wrapper.system.user.UserWebModel;
import org.opsli.core.base.service.interfaces.CrudServiceInterface;
import org.opsli.core.persistence.Page;
import org.opsli.modulars.system.user.entity.SysUser;
import org.opsli.modulars.system.user.entity.SysUserWeb;
/**
* 用户信息 Service
*
* @author Parker
* @date 2020-09-16 17:33
*/
public interface IUserService extends CrudServiceInterface<SysUser, UserModel> {
/**
* 根据 用户名 获得当前用户
* @param username 用户名
* @return UserModel
*/
UserModel queryByUserName(String username);
/**
* 修改密码 验证旧密码
* @param userPassword 账户密码
* @return boolean
*/
boolean updatePasswordByCheckOld(UserPassword userPassword);
/**
* 修改密码 不验证旧密码
* @param userPassword 账户密码
* @return boolean
*/
boolean updatePasswordByNotCheckOld(ToUserPassword userPassword);
/**
* 重置密码
* @param userPassword 账户密码
* @return boolean
*/
boolean resetPassword(UserPassword userPassword);
/**
* 更新用户最后登录IP
* @param model 模型
* @return boolean
*/
boolean updateLoginIp(UserModel model);
/**
* 更新用户头像
* @param model 模型
* @return boolean
*/
boolean updateAvatar(UserModel model);
/**
* 变更账户状态
* @param userId 用户ID
* @param enable 状态
* @return boolean
*/
boolean enableAccount(String userId, String enable);
/**
* 查询分页数据 自定义
* @param page 分页
* @return Page<T>
*/
Page<SysUserWeb, UserWebModel> findPageByCus(Page<SysUserWeb, UserWebModel> page);
/**
* 查询分页数据 租户
* @param page 分页
* @return Page<T>
*/
Page<SysUserWeb, UserWebModel> findPageByTenant(Page<SysUserWeb, UserWebModel> page);
}
|
923b50c9d332641dc2353956df60250ebac38865 | 576 | java | Java | designer/designer-model/src/main/java/com/neusfot/designer/domain/dto/LayoutDTO.java | kangkang321/mysource | 6228f88bb1babac72f8503dfe4f8b4280f32d9c7 | [
"Apache-2.0"
] | null | null | null | designer/designer-model/src/main/java/com/neusfot/designer/domain/dto/LayoutDTO.java | kangkang321/mysource | 6228f88bb1babac72f8503dfe4f8b4280f32d9c7 | [
"Apache-2.0"
] | null | null | null | designer/designer-model/src/main/java/com/neusfot/designer/domain/dto/LayoutDTO.java | kangkang321/mysource | 6228f88bb1babac72f8503dfe4f8b4280f32d9c7 | [
"Apache-2.0"
] | null | null | null | 17.454545 | 69 | 0.607639 | 999,547 | package com.neusfot.designer.domain.dto;
import java.io.Serializable;
import lombok.Data;
/**
* 类LayoutDTO.java的实现描述:模式对象 FIXME 后续考虑放入redis缓存
*
* @author Administrator 2017年3月16日 上午10:19:03
*/
@Data
public class LayoutDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 834927158116599864L;
private String id;
private String name;
private boolean df;
/**
* 1列表模式,2图卡模式,3查询条件
*/
private int type;
private String objId;
}
|
923b515006752844d58d0e31d556059617eda9da | 647 | java | Java | CS102A/0x03/exercise3.java | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 22 | 2018-08-07T06:55:10.000Z | 2021-06-12T02:12:19.000Z | CS102A/0x03/exercise3.java | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 28 | 2020-03-04T23:47:22.000Z | 2022-02-26T18:50:00.000Z | CS102A/0x03/exercise3.java | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 4 | 2019-11-09T15:41:26.000Z | 2021-10-10T08:56:57.000Z | 30.809524 | 76 | 0.570325 | 999,548 | import java.util.Scanner;
import java.lang.Math;
public class exercise3 {
private static void ex3(Scanner sc) {
System.out.printf("Input x1 and y1:");
double x1 = sc.nextDouble();
double y1 = sc.nextDouble();
System.out.printf("Input x2 and y2:");
double x2 = sc.nextDouble();
double y2 = sc.nextDouble();
System.out.printf("The distance of the two points is %.10f\n",
Math.pow(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2), 0.5));
}
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
ex3(sc);
sc.close();
}
} |
923b519163037d57d48c31598b5236cb0fa48d50 | 5,541 | java | Java | src/main/java/Tetris/Shapes/Board.java | Johnthestudent/TETRIS | 702cb08514d3556bb7680797405a0abee3bbd499 | [
"Apache-2.0"
] | null | null | null | src/main/java/Tetris/Shapes/Board.java | Johnthestudent/TETRIS | 702cb08514d3556bb7680797405a0abee3bbd499 | [
"Apache-2.0"
] | null | null | null | src/main/java/Tetris/Shapes/Board.java | Johnthestudent/TETRIS | 702cb08514d3556bb7680797405a0abee3bbd499 | [
"Apache-2.0"
] | null | null | null | 31.482955 | 99 | 0.616676 | 999,549 | package Tetris.Shapes;
import Tetris.*;
/**
* A {@code Board} osztálya, ahol a pálya megvalósítása, az ütközésvizsgálat, a lehelyezett alakzat
* elmentésének megvalósítása és a teli sor eltüntetésének megvalósítása van.
*
* @see Shape
*/
public class Board extends Matrix
{
/**
* Ez tárolja a pálya szélességét.
*/
private int width;
/**
* Ez tárolja a pálya magasságát.
*/
private int height;
/**
* A {@code Board} mátrixának elkészítése. 12*20-as méretű mátrix lesz.
*
* @see Matrix
*/
public Board()
{
super(); //Matrix ősosztály konstruktora
this.width = 12;
this.height = 20;
this.matrix = new int[this.width][this.height]; //tényleges mátrix elkészítése
initBoard();
}
/**
* Konstruktor, mely egy megadott szélességű és magasságú {@code Board} objektumot hoz létre.
*
* @param width a pálya szélessége
* @param height a pálya magassága
*/
public Board(int width, int height)
{
super();
this.width = width;
this.height = height;
this.matrix = new int[height][width];
initBoard();
}
/**
* Visszaadja a {@code Board} szélességét.
*
* @return a {@code Board} szélessége
*/
public int getWidth()
{
return this.width;
}
/**
* A {@code Board} inicializálása. Itt lesz a mátrix összes eleme nulla.
* Új játék megkezdése előtt ezen mátrix minden elemét ki kell nullázni.
*
* @see MatrixHelper
*/
public void initBoard()
{
for(int i = 0; i < MatrixHelper.getRowNum(this.matrix); i++)
{
for(int j = 0; j < MatrixHelper.getColNum(this.matrix); j++)
{
this.matrix[i][j] = 0; //kinullázása a pályának (alaphelyzetbe hozás)
}
}
}
/**
* Az {@link Shape} ütközésének a vizsgálata. A vizsgálathoz szükség van az {@link Shape}
* mátrixára, és a pozíciójára, ami az eltolása a pályához képest. Csak a nem
* nulla helyek ütközhetnek. Négy különböző helyen ütközhet az {@link Shape}: a
* {@code Board} aljával, jobb és bal oldalával, és egy a pályán már lehelyezett
* alakzattal.
*
* @param shape a {@link Shape} alakzat
* @return {@code true}, ha van ütközés, egyébként {@code false}
*/
public boolean hasCollision(Shape shape)
{
int[][] shapeMatrix = shape.getMatrix(); //elkérem a mátrixot a művelethez
Position shapePosition = shape.getPosition(); //az alakzat az eltolása a boardhoz képest
for(int i = 0; i < MatrixHelper.getRowNum(shapeMatrix); i++)
{
for(int j = 0; j < MatrixHelper.getColNum(shapeMatrix); j++)
{
//csak a nem nulla helyek ütközhetnek
//a this.matrix a pályámnak a mátrixa
//annyi oszlopa a mátrixnak, ahány eleme az első sorának
if (shapeMatrix[i][j] != 0 && (
//lefelé kimentem a pályáról
i + shapePosition.getY() >= MatrixHelper.getRowNum(this.matrix) ||
//balra kimentem a pályáról
j + shapePosition.getX() < 0 ||
//jobbra kimentem a pályáról az alakzattal
j + shapePosition.getX() >= MatrixHelper.getColNum(this.matrix) ||
//az alakzattal a már a pályán lévő alakzattal ütköztem
//megtolom a helyére az alakzatot, és ott nézem, hogy ott ütközik-e
this.matrix[i + shapePosition.getY()][j + shapePosition.getX()] != 0))
return true; //van ütközés
}
}
return false;
}
/**
* Az {@link Shape} mentése a pályára. Ehhez szükség van az {@link Shape} mátrixára és a
* pozíciójára. Az {@link Shape} mátrixának a nullától különböző elemei rámásolódnak
* a {@code Board} mátrixának a megfelelő pozícióira. Minden egyes {@link Shape} lehelyezése
* után módosul a {@code Board} mátrixa.
*
* @param shape a {@code Shape} alakzat
* @see Shape
*/
public void saveShape(Shape shape)
{
int[][] shapeMatrix = shape.getMatrix(); //elkérem az alakzat mátrixát
Position shapePosition = shape.getPosition(); //elkérem az alakzat pozícióját
//bejárom az alakzat mátrixát
for(int i = 0; i < MatrixHelper.getRowNum(shapeMatrix); i++)
{
for(int j = 0; j < MatrixHelper.getColNum(shapeMatrix); j++)
{
if (shapeMatrix[i][j] != 0)
{
//az alakzat mátrixának elemeit rámásolom a pálya mátrixának a megfelelő pozícióira
this.matrix[i + shapePosition.getY()][j + shapePosition.getX()] = shapeMatrix[i][j];
}
}
}
}
/**
* A teli sor eltüntetésének megvalósítása a pályáról. Teli a sor, ha nincsbenne 0 elem.
* A teli sor fölötti sorok rácsúsznak a teli sorra, és felül csupa 0 sor jön be.
* Minden egyes eltüntetett sor 10 pontot ér a játékban.
*
* @return a pontok száma
*/
public int boardSweep()
{
int points = 0; //alaphelyzetben 0 pontom van
for (int row = 0; row < MatrixHelper.getRowNum(this.matrix); row++)
{
boolean canSweep = true; //eltüntethető-e a sor
for (int column = 0; column < MatrixHelper.getColNum(this.matrix); column++)
{
if (this.matrix[row][column] == 0)
{
canSweep = false; //a sor nem törölhető
break; //nincs értelme tovább vizsgálni ezt a sort
}
}
if (canSweep) //ha viszont teli a sor
{
MatrixHelper.sweepRow(this.matrix, row); //mátrix sorainak cseréje
points += 10; //tíz pontot ér egy eltüntetett sor
}
}
return points;
}
}
|
923b51ccf7fa8c6af5941b6d25ef50116f5cf10c | 1,025 | java | Java | Java Projets (TPs - Autres)/Autres/Data-structures-and-Algorithm/ZeroOneKnapsack_DC.java | Bernardinhouessou/Projets_Autres | 4daa0c9fd117b84de1f9c4dd1d4d8d36220c3451 | [
"MIT"
] | null | null | null | Java Projets (TPs - Autres)/Autres/Data-structures-and-Algorithm/ZeroOneKnapsack_DC.java | Bernardinhouessou/Projets_Autres | 4daa0c9fd117b84de1f9c4dd1d4d8d36220c3451 | [
"MIT"
] | null | null | null | Java Projets (TPs - Autres)/Autres/Data-structures-and-Algorithm/ZeroOneKnapsack_DC.java | Bernardinhouessou/Projets_Autres | 4daa0c9fd117b84de1f9c4dd1d4d8d36220c3451 | [
"MIT"
] | null | null | null | 35.344828 | 119 | 0.699512 | 999,550 | public class ZeroOneKnapsack_DC {
public int knapsack(int[] profits, int[] weights, int capacity) {
return this.knapsackAux(profits, weights, capacity, 0);
}//end of method
private int knapsackAux(int[] profits, int[] weights, int capacity, int currentIndex) {
if (capacity <= 0 || currentIndex < 0 || currentIndex >= profits.length)//Base case
return 0;
int profit1 = 0;
if (weights[currentIndex] <= capacity) // Taking current element
profit1 = profits[currentIndex] + knapsackAux(profits, weights, capacity - weights[currentIndex], currentIndex + 1);
int profit2 = knapsackAux(profits, weights, capacity, currentIndex + 1); // Not taking current element
return Math.max(profit1, profit2);
}//end of method
public static void main(String[] args) {
ZeroOneKnapsack_DC ks = new ZeroOneKnapsack_DC();
int[] profits = { 31, 26, 72, 17 };
int[] weights = { 3, 1, 5, 2 };
int maxProfit = ks.knapsack(profits, weights, 7);
System.out.println(maxProfit);
}//end of method
}//end of class
|
923b52e16696ef319399eb6572701600f7e87bb1 | 6,546 | java | Java | analytics_lib/src/main/java/com/ccj/client/android/analytics/JJEventManager.java | ccj659/JJV | 6a55b44262e59bd610137a5d5df0681917398966 | [
"Apache-2.0"
] | 392 | 2018-10-10T09:57:38.000Z | 2022-03-01T05:58:48.000Z | analytics_lib/src/main/java/com/ccj/client/android/analytics/JJEventManager.java | ccj659/JJView | 6a55b44262e59bd610137a5d5df0681917398966 | [
"Apache-2.0"
] | 6 | 2018-10-19T01:31:53.000Z | 2020-05-03T05:49:07.000Z | analytics_lib/src/main/java/com/ccj/client/android/analytics/JJEventManager.java | ccj659/JJV | 6a55b44262e59bd610137a5d5df0681917398966 | [
"Apache-2.0"
] | 67 | 2018-10-10T10:06:34.000Z | 2022-02-17T08:13:47.000Z | 26.609756 | 118 | 0.571494 | 999,551 | package com.ccj.client.android.analytics;
import android.app.Application;
import android.content.Context;
import android.os.Process;
import com.ccj.client.android.analytics.exception.EventException;
import com.ccj.client.android.analytics.intercept.CookieFacade;
import com.ccj.client.android.analytics.utils.EDeviceUtils;
import static com.ccj.client.android.analytics.EConstant.TAG;
/**
* 事件管理
* Created by chenchangjun on 18/2/8.
*/
public final class JJEventManager {
public static boolean IS_DEBUG = EConstant.DEVELOP_MODE;
private static Application app;//全局持有app,保证sdk正常运转. app引用与进程同生命周期, 即 进程被销毁, jvm会随之销毁,app引用会随之销毁. so不存在内存泄漏.
protected volatile static boolean hasInit = false;
/**
* 获取application 上下文
*
* @return
*/
public static Context getContext() {
if (app == null) {
throw new EventException("请先在application中实例化JJEventManager");
}
return app;
}
/**
* 初始化sdk, 要在application中的onCreate() 方法中进行初始化.
*
* @param application 全局上下文
* @param cookie 宿主app中的通用cookie
* @param isDebug 是否是debug模式(控制开启log等)
*/
public static void init(Application application, String cookie,boolean isDebug) {
if (application==null){
ELogger.logWrite(EConstant.TAG, " JJEventManager application==null!");
return;
}
//处理app拥有多个进程
String processName = EDeviceUtils.getProcessName(application, Process.myPid());
if (processName==null||!processName.equals(application.getPackageName()+"")) {
ELogger.logWrite(EConstant.TAG, " JJEventManager 初始化进程为:" + processName + ",不在主进程中!");
return;
}
if (hasInit) {
ELogger.logWrite(EConstant.TAG, " JJEventManager 已经初始化init(),请勿重复操作!!!!!!");
// throw new EventException("JJEventManager 已经初始化init()");
return;
}
hasInit = true;
EConstant.SWITCH_OFF = false;//开启一切统计事务
EConstant.DEVELOP_MODE = isDebug;//是否是开发模式
/****************进行初始化*************************/
app = application;
EPushService.startService();
EventDecorator.initCookie(cookie);
ELogger.logWrite(EConstant.TAG, " JJEventManager run on thread-->" + Thread.currentThread().getName());
ELogger.logWrite(TAG, "----JJEvent sdk init success!----");
}
public static void pushEvent() {
EPushService.getSingleInstance().excutePushEvent();
}
/**
* 用于刷新Cookie
*
* @param cookie
*/
public static void refreshCookie(String cookie) {
EventDecorator.initCookie(cookie);
}
/**
* 停止sdk所有服务(停止事件统计,停止事件推送)
*/
public static void destoryEventService() {
hasInit = false;//变为 可初始化
EConstant.SWITCH_OFF = true;//关闭一切统计事务
EPushService.getSingleInstance().stopEventService();
ELogger.logWrite(EConstant.TAG, " ----JJEvent sdk is destoryEventService!---");
}
/**
* 停止事件的上传任务(仍会记录事件,停止事件推送)
*/
public static void cancelEventPush() {
hasInit = false;//变为 可初始化
EPushService.getSingleInstance().stopEventService();
ELogger.logWrite(EConstant.TAG, " ----JJEvent sdk is cancelEventPush---");
}
/**
* 内部构建类
* 优势:可以根据需求,在不改变原有架构API的基础上,灰常灵活的进行构建修改,方便的很~
*/
public static class Builder {
private Application application;
private boolean DEVELOP_MODE = EConstant.DEVELOP_MODE;
private int PUSH_CUT_NUMBER = EConstant.PUSH_CUT_NUMBER;
private double PUSH_CUT_DATE = EConstant.PUSH_CUT_DATE;
private int PUSH_FINISH_DATE = EConstant.PUSH_FINISH_DATE;
private String cookie = "";
private CookieFacade cookieIntercept;
public Builder(Application application) {
this.application = application;
}
/**
* 宿主 cookie
* @param cookie
* @return
*/
public Builder setHostCookie(String cookie) {
this.cookie = cookie;
return this;
}
/**
* 是否是开发者模式
* @param isDebug
* @return
*/
public Builder setDebug(boolean isDebug) {
DEVELOP_MODE = isDebug;
return this;
}
/**
* 主动推送上限数
* @param num
* @return
*/
public Builder setPushLimitNum(int num) {
PUSH_CUT_NUMBER = num;
return this;
}
/**
* 推送周期
* @param minutes
* @return
*/
public Builder setPushLimitMinutes(double minutes) {
PUSH_CUT_DATE = minutes;
return this;
}
/**
* sid 改变周期
* @param minutes
* @return
*/
public Builder setSidPeriodMinutes(int minutes) {
PUSH_FINISH_DATE = minutes;
return this;
}
/**
* 设置服务器的请求接口
* @param url
* @return
*/
public Builder setPushUrl(String url) {
EConstant. COLLECT_URL = url;
return this;
}
/**
* cookie 动态注入接口
* @param cookieIntercept
* @return
*/
public Builder setCookieIntercept(CookieFacade cookieIntercept) {
this.cookieIntercept=cookieIntercept;
return this;
}
/**
* 开始构建
*/
public void start() {
ELogger.logWrite(EConstant.TAG, " JJEventManager.Builder#start() " );
if (application == null) {
ELogger.logWrite(EConstant.TAG, " JJEventManager.Builder#start() application:" + "不能为空!");
return;
}
//处理app拥有多个进程
String processName = EDeviceUtils.getProcessName(application, Process.myPid());
if (!processName.equals(application.getPackageName())) {
ELogger.logWrite(EConstant.TAG, " JJEventManager.Builder#start() 初始化进程为:" + processName + " 不在主进程中!");
return;
}
EConstant.PUSH_CUT_NUMBER = PUSH_CUT_NUMBER;
EConstant.PUSH_CUT_DATE = PUSH_CUT_DATE;
EConstant.PUSH_FINISH_DATE = PUSH_FINISH_DATE;
EGsonRequest.cookieIntercept=cookieIntercept;
JJEventManager.init(application, cookie, DEVELOP_MODE);
}
}
}
|
923b54837d85dc0565e970adf8c98b958b621661 | 5,546 | java | Java | java/form/src/org/netbeans/modules/form/PersistenceManager.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | java/form/src/org/netbeans/modules/form/PersistenceManager.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | java/form/src/org/netbeans/modules/form/PersistenceManager.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 38.248276 | 84 | 0.666787 | 999,552 | /*
* 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.form;
import java.util.*;
import org.openide.*;
import org.openide.util.Lookup;
/**
* An abstract class which defines interface for persistence managers (being
* responsible for loading and saving forms) and provides a basic registration
* facility.
* PersistenceManager implementations should be able to deal with multiple
* forms being saved and loaded by one instance of persistence manager (but
* not concurrently).
*
* @author Ian Formanek, Tomas Pavek
*/
public abstract class PersistenceManager {
// -------------------
// abstract interface
/** This method is used to check if the persistence manager can read the
* given form (if it understands the form file format).
*
* @param formObject form data object representing the form.
* @return true if this persistence manager can load the form
* @exception PersistenceException if any unexpected problem occurred
*/
public abstract boolean canLoadForm(FormDataObject formObject)
throws PersistenceException;
/** This method loads the form from given data object.
* @param formObject FormDataObject representing the form files
* @param formModel FormModel to be filled with loaded data
* @param nonfatalErrors List to be filled with errors occurred during
* loading which are not fatal (but should be reported)
* @exception PersistenceException if some fatal problem occurred which
* prevents loading the form
*/
public abstract void loadForm(FormDataObject formObject,
FormModel formModel,
List<Throwable> nonfatalErrors)
throws PersistenceException;
/** This method saves the form to given data object.
* @param formObject FormDataObject representing the form files
* @param formModel FormModel to be saved
* @param nonfatalErrors List to be filled with errors occurred during
* saving which are not fatal (but should be reported)
* @exception PersistenceException if some fatal problem occurred which
* prevents saving the form
*/
public abstract void saveForm(FormDataObject formObject,
FormModel formModel,
List<Throwable> nonfatalErrors)
throws PersistenceException;
// ------------
// static registry [provisional only]
private static List<PersistenceManager> managers;
private static List<String> managersByName;
public static void registerManager(PersistenceManager manager) {
getManagersList().add(manager);
}
public static void unregisterManager(PersistenceManager manager) {
getManagersList().remove(manager);
}
static void registerManager(String managerClassName) {
getManagersNamesList().add(managerClassName);
}
public static Iterator<PersistenceManager> getManagers() {
ClassLoader classLoader = null;
Iterator<String> iter = getManagersNamesList().iterator();
while (iter.hasNext()) { // create managers registered by name
if (classLoader == null)
classLoader = Lookup.getDefault().lookup(ClassLoader.class);
String pmClassName = iter.next();
try {
PersistenceManager manager = (PersistenceManager)
classLoader.loadClass(pmClassName).newInstance();
getManagersList().add(manager);
}
catch (Exception ex1) {
notifyError(ex1, pmClassName);
}
catch (LinkageError ex2) {
notifyError(ex2, pmClassName);
}
}
getManagersNamesList().clear(); // [is it OK to lose unsuccessful managers?]
return getManagersList().iterator();
}
private static List<PersistenceManager> getManagersList() {
if (managers == null) {
managers = new ArrayList<PersistenceManager>();
managers.add(new GandalfPersistenceManager());
}
return managers;
}
private static List<String> getManagersNamesList() {
if (managersByName == null)
managersByName = new ArrayList<String>();
return managersByName;
}
private static void notifyError(Throwable th, String pmClassName) {
String msg = FormUtils.getFormattedBundleString(
"FMT_ERR_PersistenceManagerInstantiation", // NOI18N
new Object[] { pmClassName });
ErrorManager errorManager = ErrorManager.getDefault();
errorManager.annotate(th, msg);
errorManager.notify(ErrorManager.EXCEPTION, th);
}
}
|
923b54cb779c90372fe7a0d9ea9fdb3df8d5a481 | 9,725 | java | Java | common/java/common-controls/src/com/epam/indigo/controls/SelectIDColumnDialog.java | 00Green27/Indigo | dc09f838b8b05d4bba2f79d0af5617d637f0b70e | [
"Apache-2.0"
] | null | null | null | common/java/common-controls/src/com/epam/indigo/controls/SelectIDColumnDialog.java | 00Green27/Indigo | dc09f838b8b05d4bba2f79d0af5617d637f0b70e | [
"Apache-2.0"
] | null | null | null | common/java/common-controls/src/com/epam/indigo/controls/SelectIDColumnDialog.java | 00Green27/Indigo | dc09f838b8b05d4bba2f79d0af5617d637f0b70e | [
"Apache-2.0"
] | null | null | null | 39.693878 | 162 | 0.682262 | 999,553 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* SelectIDColumnDialog.java
*
* Created on May 10, 2011, 4:01:18 PM
*/
package com.epam.indigo.controls;
import com.epam.indigo.IndigoException;
import com.epam.indigo.IndigoObject;
import com.epam.indigo.controls.IndigoCheckedException;
import com.epam.indigo.controls.RenderableObject;
import java.awt.Frame;
import java.util.Collection;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* @author rybalkin
*/
public class SelectIDColumnDialog extends javax.swing.JDialog
{
List<? extends RenderableObject> _molecules;
int _active_index;
boolean _show_name, _show_serial;
boolean _canceled = false;
public static final String SERIAL_NUMBER_ID = "$Serial number$";
public static final String NAME_ID = "$Name$";
/** Creates new form SelectIDColumnDialog */
public SelectIDColumnDialog (Frame parent,
List<? extends RenderableObject> molecules,
boolean show_name,
boolean show_serial)
{
super(parent);
initComponents();
_show_name = show_name;
_show_serial = show_serial;
_molecules = molecules;
_active_index = 0;
showCurrent();
done_button.requestFocus();
setLocationRelativeTo(parent);
pack();
}
public String getSelectedProperty ()
{
return molecule_with_properties.getSelectedPropertyName();
}
public void setSelectedPropertyIndex (int index)
{
molecule_with_properties.setSelectedPropertyIndex(index);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
molecule_with_properties = new com.epam.indigo.controls.IndigoObjectWithPropertiesViewPanel();
prev_button = new javax.swing.JButton();
next_button = new javax.swing.JButton();
done_button = new javax.swing.JButton();
help_info = new javax.swing.JLabel();
setTitle("Select ID field");
setModal(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
prev_button.setText("Prev");
prev_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
prev_buttonActionPerformed(evt);
}
});
next_button.setText("Next");
next_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
next_buttonActionPerformed(evt);
}
});
done_button.setText("Done");
done_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
done_buttonActionPerformed(evt);
}
});
help_info.setText("<html>Choose a property field that will be used as an identifier for all the molecules in this set. </html>");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(molecule_with_properties, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(prev_button, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(next_button, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 236, Short.MAX_VALUE)
.addComponent(done_button, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(help_info, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(help_info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(molecule_with_properties, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(done_button)
.addComponent(prev_button)
.addComponent(next_button))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void done_buttonActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_done_buttonActionPerformed
{//GEN-HEADEREND:event_done_buttonActionPerformed
if (molecule_with_properties.getSelectedPropertyName() == null)
JOptionPane.showMessageDialog(this, "You need to select property field");
else
setVisible(false);
}//GEN-LAST:event_done_buttonActionPerformed
private void prev_buttonActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_prev_buttonActionPerformed
{//GEN-HEADEREND:event_prev_buttonActionPerformed
_active_index--;
showCurrent();
}//GEN-LAST:event_prev_buttonActionPerformed
private void next_buttonActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_next_buttonActionPerformed
{//GEN-HEADEREND:event_next_buttonActionPerformed
_active_index++;
showCurrent();
}//GEN-LAST:event_next_buttonActionPerformed
private void formWindowClosing (java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowClosing
{//GEN-HEADEREND:event_formWindowClosing
_canceled = true;
}//GEN-LAST:event_formWindowClosing
public boolean isCanceled ()
{
return _canceled;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton done_button;
private javax.swing.JLabel help_info;
private com.epam.indigo.controls.IndigoObjectWithPropertiesViewPanel molecule_with_properties;
private javax.swing.JButton next_button;
private javax.swing.JButton prev_button;
// End of variables declaration//GEN-END:variables
public String getSerialNumber (int index)
{
return String.format("#%d", index + 1);
}
public String getMoleculeID (RenderableObject rend_obj, int index) throws IndigoCheckedException
{
String prop = molecule_with_properties.getSelectedPropertyName();
if (prop.equals(SERIAL_NUMBER_ID))
return getSerialNumber(index);
try
{
IndigoObject ind_obj = rend_obj.getRenderableObject();
if (ind_obj == null)
return getSerialNumber(index);
if (prop.equals(NAME_ID))
return ind_obj.name();
return ind_obj.getProperty(prop);
}
catch (IndigoException ex)
{
throw new IndigoCheckedException(ex.getMessage());
}
}
private void showCurrent ()
{
if (_active_index >= _molecules.size())
throw new RuntimeException("Internal error");
int selected = molecule_with_properties.getSelectedPropertyIndex();
RenderableObject rend_obj = _molecules.get(_active_index);
final IndigoObject ind_obj = rend_obj.getRenderableObject();
molecule_with_properties.setObject(ind_obj, rend_obj.getIndigoRenderer());
molecule_with_properties.setInformationMessage(rend_obj.getErrorMessageToRender());
if (_show_serial)
{
molecule_with_properties.addCustomProperty(0,
"$Serial number$", getSerialNumber(_active_index));
// Select serial number by default
if (selected == -1)
molecule_with_properties.setSelectedPropertyIndex(0);
}
if (_show_name && ind_obj != null)
molecule_with_properties.addCustomProperty(0,
"$Name$", ind_obj.name());
if (selected >= 0 && selected < molecule_with_properties.getPropertiesCount())
molecule_with_properties.setSelectedPropertyIndex(selected);
next_button.setEnabled(_active_index < _molecules.size() - 1);
prev_button.setEnabled(_active_index > 0);
}
}
|
923b556efcde7bac4c28749389b6de92fba1c3b4 | 1,083 | java | Java | com/lukflug/panelstudio/tabgui/TabGUI.java | noom1337/hawk-client | 7f62687c62709c595e2945d71678984ba1b832ea | [
"MIT"
] | 2 | 2021-07-09T22:20:10.000Z | 2021-10-10T15:41:01.000Z | com/lukflug/panelstudio/tabgui/TabGUI.java | noom1337/hawk-client | 7f62687c62709c595e2945d71678984ba1b832ea | [
"MIT"
] | null | null | null | com/lukflug/panelstudio/tabgui/TabGUI.java | noom1337/hawk-client | 7f62687c62709c595e2945d71678984ba1b832ea | [
"MIT"
] | null | null | null | 25.186047 | 90 | 0.700831 | 999,554 | package com.lukflug.panelstudio.tabgui;
import com.lukflug.panelstudio.Animation;
import com.lukflug.panelstudio.FixedComponent;
import com.lukflug.panelstudio.Interface;
import com.lukflug.panelstudio.PanelConfig;
import java.awt.Point;
public class TabGUI extends TabGUIContainer implements FixedComponent {
protected Point position;
protected int width;
public void saveConfig(Interface var1, PanelConfig var2) {
var2.savePositon(this.position);
}
public int getWidth(Interface var1) {
return this.width;
}
public void loadConfig(Interface var1, PanelConfig var2) {
Point var3 = var2.loadPosition();
if (var3 != null) {
this.position = var3;
}
}
public TabGUI(String var1, TabGUIRenderer var2, Animation var3, Point var4, int var5) {
super(var1, var2, var3);
this.position = var4;
this.width = var5;
}
public void setPosition(Interface var1, Point var2) {
this.position = var2;
}
public Point getPosition(Interface var1) {
return new Point(this.position);
}
}
|
923b55e47babc12f2f647cb210fc0b1a6f290d57 | 7,445 | java | Java | docusign-restclient-core/src/main/java/uk/co/techblue/docusign/client/resources/EnvelopeResource.java | dheerajarora/docusign-restclient | b4fa1e4ed611792a852721282683d8581dc9bd0d | [
"Apache-2.0"
] | null | null | null | docusign-restclient-core/src/main/java/uk/co/techblue/docusign/client/resources/EnvelopeResource.java | dheerajarora/docusign-restclient | b4fa1e4ed611792a852721282683d8581dc9bd0d | [
"Apache-2.0"
] | null | null | null | docusign-restclient-core/src/main/java/uk/co/techblue/docusign/client/resources/EnvelopeResource.java | dheerajarora/docusign-restclient | b4fa1e4ed611792a852721282683d8581dc9bd0d | [
"Apache-2.0"
] | null | null | null | 32.797357 | 171 | 0.686232 | 999,555 | /*******************************************************************************
* Copyright 2012 Technology Blueprint Ltd
*
* 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 uk.co.techblue.docusign.client.resources;
import java.io.File;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.james.mime4j.field.FieldName;
import org.jboss.resteasy.annotations.Form;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
import uk.co.techblue.docusign.client.Resource;
import uk.co.techblue.docusign.client.dto.EnvelopeStatusQueryForm;
import uk.co.techblue.docusign.client.dto.StatusChangeRequest;
import uk.co.techblue.docusign.client.dto.VoidEnvelopeRequest;
import uk.co.techblue.docusign.client.dto.recipients.Signers;
import uk.co.techblue.docusign.client.utils.DocuSignConstants;
/**
* The Interface EnvelopeResource.
*/
@Path(DocuSignConstants.RESOURCE_CONTEXT_PATH)
public interface EnvelopeResource extends Resource {
/**
* Response.
*
* @param envelopeId the envelope id
* @param VoidEnvelopeRequest the void envelope request
* @return the response
*/
@PUT
@Path("envelopes/{envelopeId}")
@Consumes(MediaType.APPLICATION_JSON)
public Response voidEnvelope(@PathParam("envelopeId") String envelopeId, VoidEnvelopeRequest VoidEnvelopeRequest);
/**
* Response.
*
* @param envelopeId the envelope id
* @param statusChangeRequest the status change request
* @return the response
*/
@PUT
@Path("envelopes/{envelopeId}/status")
@Consumes(MediaType.APPLICATION_JSON)
public Response changeStatus(@PathParam("envelopeId") String envelopeId, StatusChangeRequest statusChangeRequest);
/**
* Response.
*
* @param contentDisposition the content disposition
* @param envelopeId the envelope id
* @param documentId the document id
* @param docFile the doc file
* @return the response
*/
@PUT
@Path("envelopes/{envelopeId}/documents/{documentId}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response addDocumentToDraftEnvelope(@HeaderParam(FieldName.CONTENT_DISPOSITION) String contentDisposition, @PathParam("envelopeId") String envelopeId,
@PathParam("documentId") String documentId, File docFile);
/**
* Gets the audit events.
*
* @param envelopeId the envelope id
* @return the audit events
*/
@GET
@Path("envelopes/{envelopeId}/audit_events")
@Produces(MediaType.APPLICATION_JSON)
public Response getAuditEvents(@PathParam("envelopeId") String envelopeId);
/**
* Gets the envelope.
*
* @param envelopeId the envelope id
* @return the envelope
*/
@GET
@Path("envelopes/{envelopeId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getEnvelope(@PathParam("envelopeId") String envelopeId);
/**
* Response.
*
* @param formDataOutput the form data output
* @return the response
*/
@POST
@Path("folders/draft")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response saveToDrafts(MultipartFormDataOutput formDataOutput);
/**
* Gets the envelope status.
*
* @param statusQueryForm the status query form
* @return the envelope status
*/
@GET
@Path("envelopes")
@Produces(MediaType.APPLICATION_JSON)
public Response getEnvelopeStatus(@Form EnvelopeStatusQueryForm statusQueryForm);
/**
* Gets the certificate.
*
* @param envelopeId the envelope id
* @param watermark the watermark
* @param certificate the certificate
* @return the certificate
*/
@GET
@Path("envelopes/{envelopeId}/documents/certificate")
public Response getCertificate(@PathParam("envelopeId") String envelopeId, @QueryParam("watermark") Boolean watermark, @QueryParam("certificate") Boolean certificate);
/**
* Gets the documents combined.
*
* @param envelopeId the envelope id
* @return the documents combined
*/
@GET
@Path("envelopes/{envelopeId}/documents/combined")
public Response getDocumentsCombined(@PathParam("envelopeId") String envelopeId);
/**
* Gets the documents info.
*
* @param envelopeId the envelope id
* @return the documents info
*/
@GET
@Path("envelopes/{envelopeId}/documents")
@Produces(MediaType.APPLICATION_JSON)
public Response getDocumentsInfo(@PathParam("envelopeId") String envelopeId);
/**
* Gets the document.
*
* @param envelopeId the envelope id
* @param documentId the document id
* @return the document
*/
@GET
@Path("/envelopes/{envelopeId}/documents/{documentId}")
public Response getDocument(@PathParam("envelopeId") String envelopeId, @PathParam("documentId") String documentId);
/**
* Gets the custom fields.
*
* @param envelopeId the envelope id
* @return the custom fields
*/
@GET
@Path("/envelopes/{envelopeId}/custom_fields")
@Produces(MediaType.APPLICATION_JSON)
public Response getCustomFields(@PathParam("envelopeId") String envelopeId);
/**
* Gets the notification info.
*
* @param envelopeId the envelope id
* @return the notification info
*/
@GET
@Path("/envelopes/{envelopeId}/notification")
@Produces(MediaType.APPLICATION_JSON)
public Response getNotificationInfo(@PathParam("envelopeId") String envelopeId);
/**
* Gets the recipient status.
*
* @param envelopeId the envelope id
* @param includeTabs the include tabs
* @param includeExtended the include extended
* @return the recipient status
*/
@GET
@Path("/envelopes/{envelopeId}/recipients")
@Produces(MediaType.APPLICATION_JSON)
public Response getRecipientStatus(@PathParam("envelopeId") String envelopeId, @QueryParam("include_tabs") Boolean includeTabs,
@QueryParam("include_extended") Boolean includeExtended);
/**
* Response.
*
* @author : Amit Choudhary Created At: Aug 16, 2018, 1:26:18 PM
* @param envelopeId the envelope id
* @param resendEnvelope the resend envelope
* @param signersList the signers list
* @return the response
*/
@PUT
@Path("/envelopes/{envelopeId}/recipients")
@Consumes(MediaType.APPLICATION_JSON)
public Response resendEnvelope(@PathParam("envelopeId") String envelopeId, @QueryParam("resend_envelope") final boolean resendEnvelope, Signers signersList);
}
|
923b568b2636ce1fbe0b89d362fe50a99491d49b | 27,991 | java | Java | MockMi-Ne Sweeper/MineSweeper.java | saehyuns/Projects | 81b50d18419aaab9f62571f35fb63a36b33388c5 | [
"Apache-2.0"
] | null | null | null | MockMi-Ne Sweeper/MineSweeper.java | saehyuns/Projects | 81b50d18419aaab9f62571f35fb63a36b33388c5 | [
"Apache-2.0"
] | null | null | null | MockMi-Ne Sweeper/MineSweeper.java | saehyuns/Projects | 81b50d18419aaab9f62571f35fb63a36b33388c5 | [
"Apache-2.0"
] | null | null | null | 30.391965 | 225 | 0.495016 | 999,556 | /********************************************************************************************************
*
* NAME: Sae Hyun Song
* Raven Robles
* Lee Ann Cauilan
*
*
* HOMEWORK: Group Project - Minesweeper
*
* CLASS: ICS 211
*
* INSTRUCTOR: Scott Robertson
*
* DATE: May 4, 2016
*
* FILE: MineSweeper.java
*
* DESCRIPTION: This class contains the GUI and methods needed to run the MineSweeper program.
*
*******************************************************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class MineSweeper {
Grid grid = new Grid(0,0);
private ArrayList<Integer> begScores, mediumScores, hardScores;
private JFrame highFrame, frame;
private JPanel highPanel, panel = new JPanel();
private JLabel easy, medium, hard, scores, timerText = new JLabel();
private JButton btnBeginner = new JButton("Beginner");
private JButton btnMedium = new JButton("Medium");
private JButton btnHard = new JButton("Hard");
private JButton btnReset = new JButton("Reset");
private JButton btnScore = new JButton("High Score");
private JButton chngDiff = new JButton("Change Difficulty");
private int height, width, mines, timer, pressedbuttons, totalbuttons, flagsRemaining = 0;
private javax.swing.Timer time;
int frameW = 483;
int frameH = 575;
/****************************************************************************************************
*
* Method: main
*
* Description: Launches the MineSweeper program.
*
* @param args the command line arguments
*
* @return None
*
***************************************************************************************************/
public static void main(String[] args) {
MineSweeper mine = new MineSweeper();
mine.frame.setVisible(true);
}
/****************************************************************************************************
*
* Method: MineSweeper
*
* Description: Constructor which will start up the MineSweeper program.
*
* @param None
*
* @return None
*
***************************************************************************************************/
public MineSweeper(){
initialize();
}
/****************************************************************************************************
*
* Method: initialize
*
* Description: Creates the window and panels for the program and sets it to the difficulty
* selection screen.
*
* @param None
*
* @return None
*
***************************************************************************************************/
public void initialize(){
height = 0;
width = 0;
mines = 0;
begScores = new ArrayList<>();
mediumScores = new ArrayList<>();
hardScores = new ArrayList<>();
frame = new JFrame();
frame.setTitle("MINE SWEEPER");
frame.setBounds(0, 0, frameW, frameH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
btnBeginner.setBounds(frameW/2 - 50, frameH/2 - 200, 100, 100);
btnBeginner.setFont(new Font("Times New Roman", Font.ITALIC, 14));
btnBeginner.addActionListener(new easyButton());
btnMedium.setBounds(frameW/2 - 50, frameH/2 - 100, 100, 100);
btnMedium.setFont(new Font("Times New Roman", Font.ITALIC, 14));
btnMedium.addActionListener(new mediumButton());
btnHard.setBounds(frameW/2 - 50, frameH/2 + 0, 100, 100);
btnHard.setFont(new Font("Times New Roman", Font.ITALIC, 14));
btnHard.addActionListener(new hardButton());
btnScore.setBounds(frameW/2 - 50, frameH/2 + 100, 100, 100);
btnScore.setFont(new Font("Times New Roman", Font.ITALIC, 14));
btnScore.addActionListener(new highScoreButton());
btnReset.setBounds(200, 490, 60, 40);
btnReset.setFont(new Font("Times New Roman", Font.ITALIC, 14));
btnReset.addActionListener(new resetButton());
btnReset.setEnabled(false);
btnReset.hide();
chngDiff.setBounds(200, 490, 60, 40);
chngDiff.setFont(new Font("Times New Roman", Font.ITALIC, 14));
chngDiff.addActionListener(new changeDifficulty());
chngDiff.setEnabled(false);
chngDiff.hide();
panel.setBounds(0, 0, frameW, frameH);
panel.setLayout(null);
panel.add(btnBeginner);
panel.add(btnMedium);
panel.add(btnHard);
panel.add(btnReset);
panel.add(btnScore);
panel.add(chngDiff);
}
private class easyButton implements ActionListener{
/************************************************************************************************
*
* Method: actionPerformed
*
* Description: Loads the easy difficulty when the easy button is clicked.
*
* @param e the event when the button is left clicked
*
* @return None
*
***********************************************************************************************/
public void actionPerformed(ActionEvent e) {
height = 10;
width = 10;
pressedbuttons = 0;
totalbuttons = height * width;
grid = new Grid(height, width);
frame.setSize(320, 400);
hideButtons();
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.setButton(i, j, new JToggleButton());
grid.getButton(i, j).setSize(32,32);
grid.getButton(i, j).setLocation(j*575/18, i*575/18);
grid.getButton(i, j).addMouseListener(tButton);
panel.add(grid.getButton(i, j));
}
}
setMines();
setValues();
btnReset.setVisible(true);
btnReset.setEnabled(true);
btnReset.setBounds(130, 333, 60, 40);
chngDiff.setVisible(true);
chngDiff.setEnabled(true);
chngDiff.setBounds(195, 333, 120, 40);
startTimer();
}
}
private class mediumButton implements ActionListener{
/************************************************************************************************
*
* Method: actionPerformed
*
* Description: Loads the medium difficulty when the medium button is clicked.
*
* @param e the event when the button is left clicked
*
* @return None
*
***********************************************************************************************/
public void actionPerformed(ActionEvent e) {
height = 15;
width = 15;
pressedbuttons = 0;
totalbuttons = height * width;
grid = new Grid(height, width);
hideButtons();
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.setButton(i, j, new JToggleButton());
grid.getButton(i, j).setSize(32,32);
panel.add(grid.getButton(i, j));
grid.getButton(i, j).setLocation(j*575/18, i*575/18);
grid.getButton(i, j).addMouseListener(tButton);
}
}
setMines();
setValues();
btnReset.setVisible(true);
btnReset.setEnabled(true);
btnReset.setBounds(200, 490, 60, 40);
chngDiff.setVisible(true);
chngDiff.setEnabled(true);
chngDiff.setBounds(350, 490, 120, 40);
startTimer();
}
}
private class hardButton implements ActionListener{
/************************************************************************************************
*
* Method: actionPerformed
*
* Description: Loads the hard difficulty when the hard button is clicked.
*
* @param e the event when the button is left clicked
*
* @return None
*
***********************************************************************************************/
public void actionPerformed(ActionEvent e) {
height = 20;
width = 20;
pressedbuttons = 0;
totalbuttons = height * width;
grid = new Grid(height, width);
frame.setSize(frameW + 155, frameH + 200);
hideButtons();
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.setButton(i, j, new JToggleButton());
grid.getButton(i, j).setSize(32,32);
panel.add(grid.getButton(i, j));
grid.getButton(i, j).setLocation(j*575/18, i*575/18);
grid.getButton(i, j).addMouseListener(tButton);
}
}
setMines();
setValues();
btnReset.setVisible(true);
btnReset.setEnabled(true);
btnReset.setBounds(290, 645, 60, 40);
chngDiff.setVisible(true);
chngDiff.setEnabled(true);
chngDiff.setBounds(500, 645, 120, 40);
startTimer();
}
}
private class highScoreButton implements ActionListener{
/************************************************************************************************
*
* Method: actionPerformed
*
* Description: Loads the High Scores when the highscore button is clicked
*
* @param e the event when the button is left clicked
*
* @return None
*
***********************************************************************************************/
public void actionPerformed(ActionEvent e){
highPanel = new JPanel();
highFrame = new JFrame();
highFrame.setTitle("HIGH SCORES");
highFrame.setBounds(500, 0, 300, 400);
highFrame.setDefaultCloseOperation(highFrame.HIDE_ON_CLOSE);
highFrame.setVisible(true);
highFrame.add(highPanel);
easy = new JLabel();
easy.setText("EASY");
easy.setBounds(45, 10, 50, 50);
easy.setVisible(true);
medium = new JLabel();
medium.setText("MEDIUM");
medium.setBounds(125, 10, 100, 50);
medium.setVisible(true);
hard = new JLabel();
hard.setText("HARD");
hard.setBounds(225, 10, 100, 50);
hard.setVisible(true);
highPanel.setBounds(0, 0, frameW, frameH);
highPanel.setLayout(null);
highPanel.add(easy);
highPanel.add(medium);
highPanel.add(hard);
highPanel.setVisible(true);
readHighScores();
int y = 30;
for(int i = 0; i < begScores.size() && i < 10; i++){
scores = new JLabel();
scores.setText(begScores.get(i) + "");
scores.setBounds(50, y, 100, 50);
scores.setVisible(true);
highPanel.add(scores);
y+=30;
}
y = 30;
for(int i = 0; i < mediumScores.size() && i < 10; i++){
scores = new JLabel();
scores.setText(mediumScores.get(i) + "");
scores.setBounds(142, y, 100, 50);
scores.setVisible(true);
highPanel.add(scores);
y+=30;
}
y = 30;
for(int i = 0; i < hardScores.size() && i < 10; i++){
scores = new JLabel();
scores.setText(hardScores.get(i) + "");
scores.setBounds(235, y, 100, 50);
scores.setVisible(true);
highPanel.add(scores);
y+=30;
}
}
}
MouseListener tButton = new MouseListener(){
/************************************************************************************************
*
* Method: mouseClicked
*
* Description: Invokes an action when the mouse is left clicked or right clicked.
*
* @param e the action
*
* @return None
*
***********************************************************************************************/
public void mouseClicked(MouseEvent e){
boolean found = false;
int i = 0;
int j = 0;
for (i = 0; i < height; i++){
for (j = 0; j < width; j++){
if(e.getSource().equals(grid.getButton(i, j))){
found = true;
break;
}
}
if(found){
break;
}
}
if(SwingUtilities.isLeftMouseButton(e)){
if (grid.getData(i, j) > 0 && grid.getButton(i, j).getText() != "F" && grid.getButton(i, j).isEnabled()){
pressedbuttons++;
grid.getButton(i, j).setText(grid.getData(i, j) + "");
grid.getButton(i, j).setEnabled(false);
}
else if (grid.getData(i, j) == 0 && grid.getButton(i, j).getText() != "F" && grid.getButton(i, j).isEnabled()){
traverseTo(grid.getCell(i, j));
}
else if(grid.getData(i, j) == -1 && grid.getButton(i, j).getText() != "F" && grid.getButton(i, j).isEnabled()){
grid.getButton(i, j).setText("B");
JOptionPane.showMessageDialog(panel, "GAME OVER");
time.stop();
reset();
}
else if (grid.getButton(i, j).getText() == "F"){
grid.getButton(i, j).setSelected(false);
}
}
if(SwingUtilities.isRightMouseButton(e)){
if(grid.getData(i, j) >= -1 && grid.getButton(i, j).getText() != "F" && flagsRemaining > 0 && grid.getButton(i, j).isEnabled()){
grid.getButton(i, j).setEnabled(false);
grid.getButton(i, j).setText("F");
flagsRemaining --;
}
else{
if(grid.getData(i, j) == -1 && grid.getButton(i, j).getText() == "F"){
grid.getButton(i, j).setEnabled(true);
grid.getButton(i, j).setText("");
flagsRemaining ++;
}
else if (grid.getData(i, j) >= 0 && grid.getButton(i, j).getText() == "F"){
grid.getButton(i, j).setEnabled(true);
grid.getButton(i, j).setText("");
flagsRemaining ++;
}
}
}
if(pressedbuttons == (totalbuttons - mines)){
time.stop();
int option = JOptionPane.showConfirmDialog(panel, "You have cleared all the mines in " + timer + " seconds! Press Yes if you want your score inputed into the high scores.", "High Scores Input", JOptionPane.YES_NO_OPTION);
if (option == 0) {
switch (totalbuttons) {
case 100:
enterHighScore("easy.txt", timer);
break;
case 225:
enterHighScore("medium.txt", timer);
break;
case 400:
enterHighScore("hard.txt", timer);
break;
}
}
reset();
}
}
/************************************************************************************************
*
* Method: mousePressed
*
* Description: Invokes an action when the mouse is pressed over a component.
* This method is not used.
*
* @param e the action
*
* @return None
*
***********************************************************************************************/
public void mousePressed(MouseEvent e) {
}
/************************************************************************************************
*
* Method: mouseReleased
*
* Description: Invokes an action when the mouse is released over a component.
* This method is not used.
*
* @param e the action
*
* @return None
*
***********************************************************************************************/
public void mouseReleased(MouseEvent e) {
}
/************************************************************************************************
*
* Method: mouseEntered
*
* Description: Invokes an action when the mouse is entered over a component.
* This method is not used.
*
* @param e the action
*
* @return None
*
***********************************************************************************************/
public void mouseEntered(MouseEvent e) {
}
/************************************************************************************************
*
* Method: mouseExited
*
* Description: Invokes an action when the mouse is exited over a component.
* This method is not used.
*
* @param e the action
*
* @return None
*
***********************************************************************************************/
public void mouseExited(MouseEvent e) {
}
};
/****************************************************************************************************
*
* Method: setMines
*
* Description: Places mines into random cells in the grid. The amount of mines set depends on
* the difficulty selected
*
* @param None
*
* @return None
*
***************************************************************************************************/
public void setMines() {
mines = 0;
Random rng = new Random();
int mineCounter = 0;
int minesNeeded = 0;
if (this.height == 10 || this.width == 10) {
minesNeeded = 9;
}
else if (this.height == 15 || this.width == 15) {
minesNeeded = 50;
}
else if (this.height == 20 || this.width == 20) {
minesNeeded = 100;
}
while (mineCounter < minesNeeded) {
int mineRow = rng.nextInt(width);
int mineCol = rng.nextInt(height);
if (grid.getData(mineRow, mineCol) != -1) {
grid.setData(mineRow, mineCol, -1);
mineCounter++;
mines = minesNeeded;
flagsRemaining = minesNeeded;
}
}
}
/****************************************************************************************************
*
* Method: setValues
*
* Description: Sets the values of the cells in the game board.
*
* @param None
*
* @return None
*
***************************************************************************************************/
public void setValues(){
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
if(grid.getData(i, j) != -1){
grid.setData(i, j, 0);
}
}
}
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
int counter = 1;
if(grid.getData(i, j) == 0){
if(grid.getCell(i, j).getNorth() != null && grid.getCell(i, j).getNorth().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
if(grid.getCell(i, j).getNorthEast() != null && grid.getCell(i, j).getNorthEast().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
if(grid.getCell(i, j).getNorthWest() != null && grid.getCell(i, j).getNorthWest().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
if(grid.getCell(i, j).getEast() != null && grid.getCell(i, j).getEast().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
if(grid.getCell(i, j).getWest() != null && grid.getCell(i, j).getWest().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
if(grid.getCell(i, j).getSouth() != null && grid.getCell(i, j).getSouth().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
if(grid.getCell(i, j).getSouthEast() != null && grid.getCell(i, j).getSouthEast().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
if(grid.getCell(i, j).getSouthWest() != null && grid.getCell(i, j).getSouthWest().getData() == -1){
grid.setData(i, j, counter);
counter++;
}
}
}
}
}
/****************************************************************************************************
*
* Method: traverseTo
*
* Description: Reveals the adjacent cells. Cells stop traversing to other cells when its current
* data is not 0.
*
* @param cell the cell which will be revealed
*
* @return None
*
***************************************************************************************************/
private void traverseTo(Cell cell) {
JToggleButton button = cell.getButton();
button.setSelected(true);
button.setEnabled(false);
pressedbuttons++;
if (cell.getData() == 0) {
if (cell.getNorth() != null && cell.getNorth().getButton().isEnabled()) {
traverseTo(cell.getNorth());
}
if (cell.getNorthEast() != null && cell.getNorthEast().getButton().isEnabled()) {
traverseTo(cell.getNorthEast());
}
if (cell.getNorthWest() != null && cell.getNorthWest().getButton().isEnabled()) {
traverseTo(cell.getNorthWest());
}
if (cell.getSouth() != null && cell.getSouth().getButton().isEnabled()) {
traverseTo(cell.getSouth());
}
if (cell.getSouthEast() != null && cell.getSouthEast().getButton().isEnabled()) {
traverseTo(cell.getSouthEast());
}
if (cell.getSouthWest() != null && cell.getSouthWest().getButton().isEnabled()) {
traverseTo(cell.getSouthWest());
}
if (cell.getEast() != null && cell.getEast().getButton().isEnabled()) {
traverseTo(cell.getEast());
}
if (cell.getWest() != null && cell.getWest().getButton().isEnabled()) {
traverseTo(cell.getWest());
}
}
if (cell.getData() > 0){
cell.getButton().setText(cell.getData() + "");
}
}
/***********************************************************************************************
*
* Method: startTimer
*
* Description: Creates a timer which runs while the game is being played.
*
* @param None
*
* @return None
*
**********************************************************************************************/
private void startTimer() {
timerText = new JLabel("Time elapsed: ");
if(height == 10 && width == 10){
timerText.setBounds(9, 325, 150, 50);
}
else if (height == 15 && width == 15){
timerText.setBounds(9, 485, 150, 50);
}
else{
timerText.setBounds(9, 640, 150, 50);
}
panel.add(timerText);
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
timer++;
timerText.setText("Time elapsed: " + timer);
}
};
time = new Timer(1000, taskPerformer);
time.start();
}
/****************************************************************************************************
*
* Method: hideButtons
*
* Description: Hides the buttons that are in the main menu.
*
* @param None
*
* @return None
*
***************************************************************************************************/
public void hideButtons(){
btnScore.setEnabled(false);
btnScore.hide();
btnBeginner.setEnabled(false);
btnBeginner.hide();
btnMedium.setEnabled(false);
btnMedium.hide();
btnHard.setEnabled(false);
btnHard.hide();
}
/****************************************************************************************************
*
* Method: reset
*
* Description: Change the current screen to the main menu.
*
* @param None
*
* @return None
*
***************************************************************************************************/
public void reset(){
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.getButton(i, j).hide();
grid.getButton(i, j).setEnabled(false);
}
}
pressedbuttons = 0;
timer = 0;
frame.setSize(frameW, frameH);
btnBeginner.setEnabled(true);
btnBeginner.show();
btnMedium.setEnabled(true);
btnMedium.show();
btnHard.setEnabled(true);
btnHard.show();
btnReset.setEnabled(false);
btnReset.hide();
btnScore.setEnabled(true);
btnScore.show();
chngDiff.setEnabled(false);
chngDiff.hide();
timerText.setEnabled(false);
timerText.hide();
}
/****************************************************************************************************
*
* Method: enterHighScore
*
* Description: Writes the name of the player and the time taken to a text file
*
* @param textfile the file to write the player and time taken
* @param time the time taken for the player to successfully sweep the board
*
* @return None
*
***************************************************************************************************/
private void enterHighScore(String textfile, int time) {
try {
FileWriter fw = new FileWriter(new File(textfile), true);
fw.write(time + String.format("%n"));
fw.close();
}
catch (java.io.IOException e) {
}
}
/**************************************************************************************************
*
* Method: readHighScores
*
* Description: Reads the times stored in the text files and places them into an array
* list.
*
* @param None
*
* @return None
*
*************************************************************************************************/
private void readHighScores() {
try {
Scanner sc1 = new Scanner(new File("easy.txt"));
Scanner sc2 = new Scanner(new File("medium.txt"));
Scanner sc3 = new Scanner(new File("hard.txt"));
while (sc1.hasNext()) {
begScores.add(sc1.nextInt());
}
while (sc2.hasNext()) {
mediumScores.add(sc2.nextInt());
}
while (sc3.hasNext()) {
hardScores.add(sc3.nextInt());
}
sc1.close();
sc2.close();
sc3.close();
InsertionSort(begScores);
InsertionSort(mediumScores);
InsertionSort(hardScores);
}
catch (java.io.IOException e) {
}
}
public class resetButton implements ActionListener{
/****************************************************************************************************
*
* Method: actionPerformed
*
* Description: Creates a button to reset the maze during the game if the user chooses to do so.
*
* @param e whenever the button is clicked
*
* @return None
*
***************************************************************************************************/
public void actionPerformed(ActionEvent e) {
time.stop();
reset();
hideButtons();
startTimer();
grid = new Grid(height, width);
if (width == 10 && height == 10){
frame.setSize(320, 400);
chngDiff.setEnabled(true);
chngDiff.setVisible(true);
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.setButton(i, j, new JToggleButton());
grid.getButton(i, j).setSize(32,32);
panel.add(grid.getButton(i, j));
grid.getButton(i, j).setLocation(j*575/18, i*575/18);
grid.getButton(i, j).addMouseListener(tButton);
}
}
}
else if (width == 15 && height == 15){
chngDiff.setEnabled(true);
chngDiff.setVisible(true);
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.setButton(i, j, new JToggleButton());
grid.getButton(i, j).setSize(32,32);
panel.add(grid.getButton(i, j));
grid.getButton(i, j).setLocation(j*575/18, i*575/18);
grid.getButton(i, j).addMouseListener(tButton);
}
}
}
else{
frame.setSize(frameW + 155, frameH + 200);
chngDiff.setEnabled(true);
chngDiff.setVisible(true);
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
grid.setButton(i, j, new JToggleButton());
grid.getButton(i, j).setSize(32,32);
panel.add(grid.getButton(i, j));
grid.getButton(i, j).setLocation(j*575/18, i*575/18);
grid.getButton(i, j).addMouseListener(tButton);
}
}
}
btnReset.show();
btnReset.setEnabled(true);
setMines();
setValues();
}
}
public class changeDifficulty implements ActionListener{
/****************************************************************************************************
*
* Method: changeDifficulty
*
* Description: Creates a change difficulty button which allows the user to change difficulty if
* they choose to do so.
*
* @param e when the button is clicked
*
* @return None
*
***************************************************************************************************/
public void actionPerformed(ActionEvent e) {
time.stop();
reset();
}
}
/********************************************************************************************************
*
* METHOD: InsertionSort()
*
* DESCRIPTION: This method called InsertionSort, sorts the elements in the list using the algorithm for Insertion Sort.
*
* @param none
*
* @return toString()
*
********************************************************************************************************/
public void InsertionSort(ArrayList<Integer> list){
int temp = 0;
for (int k = 1; k < list.size(); k++){
while(k > 0 && list.get(k-1) > list.get(k)){
temp = list.get(k);
list.set(k, list.get(k-1));
list.set(k-1, temp);
k--;
}
}
}
}
|
923b56c79be0c608940aef2a34512702f57f84df | 1,598 | java | Java | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/sink/compactor/IdenticalFileCompactor.java | raymondk/flink | 2738c02db7100ff172b4ca7bd4c294419fe7ba7c | [
"Apache-2.0"
] | 9 | 2016-09-22T22:53:13.000Z | 2019-11-30T03:07:29.000Z | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/sink/compactor/IdenticalFileCompactor.java | raymondk/flink | 2738c02db7100ff172b4ca7bd4c294419fe7ba7c | [
"Apache-2.0"
] | 1 | 2022-02-25T03:04:41.000Z | 2022-02-25T03:04:41.000Z | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/sink/compactor/IdenticalFileCompactor.java | raymondk/flink | 2738c02db7100ff172b4ca7bd4c294419fe7ba7c | [
"Apache-2.0"
] | 1 | 2022-03-09T08:50:44.000Z | 2022-03-09T08:50:44.000Z | 35.511111 | 99 | 0.754068 | 999,557 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.connector.file.sink.compactor;
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.fs.Path;
import java.io.OutputStream;
import java.util.List;
import static org.apache.flink.util.Preconditions.checkState;
/**
* A simple {@link OutputStreamBasedFileCompactor} implementation that directly copy the content of
* the only input file to the output.
*/
@Internal
public class IdenticalFileCompactor extends ConcatFileCompactor {
public IdenticalFileCompactor() {
super();
}
public void compact(List<Path> inputFiles, OutputStream outputStream) throws Exception {
checkState(inputFiles.size() == 1, "IdenticalFileCompactor can only copy one input file");
super.compact(inputFiles, outputStream);
}
}
|
923b575ed1f835f6e46487940adda3b02bc2a2dd | 730 | java | Java | billing/src/main/java/ca/ulaval/glo4002/billing/exceptions/InvoiceForClientNotFoundException.java | BongHighlander/API_QML | 9af354af0e1d44c397373ff0e758f4940b45a369 | [
"MIT"
] | null | null | null | billing/src/main/java/ca/ulaval/glo4002/billing/exceptions/InvoiceForClientNotFoundException.java | BongHighlander/API_QML | 9af354af0e1d44c397373ff0e758f4940b45a369 | [
"MIT"
] | null | null | null | billing/src/main/java/ca/ulaval/glo4002/billing/exceptions/InvoiceForClientNotFoundException.java | BongHighlander/API_QML | 9af354af0e1d44c397373ff0e758f4940b45a369 | [
"MIT"
] | null | null | null | 23.548387 | 85 | 0.739726 | 999,558 | package ca.ulaval.glo4002.billing.exceptions;
public class InvoiceForClientNotFoundException extends BillingException {
private static final long serialVersionUID = 1L;
private static final String ERROR = "not found";
private static final String ENTITY = "Invoice";
private static final String ERROR_DESCRIPTION = "No invoice exists for the client";
private String description;
public InvoiceForClientNotFoundException(String clientId) {
this.description = ERROR_DESCRIPTION + " " + clientId;
}
@Override
public String getError() {
return ERROR;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public String getEntity() {
return ENTITY;
}
}
|
923b58852f15ea84c10e04a421e6d0c303ffb4c0 | 10,957 | java | Java | viritin-compatibility/src/main/java/org/vaadin/viritinv7/fields/MTextField.java | boniechacha/viritin | 3ff3b20d4f8bbcba9a81730c2aa751fdba3e1383 | [
"Apache-2.0"
] | 164 | 2015-01-26T09:11:34.000Z | 2021-06-15T11:52:58.000Z | viritin-compatibility/src/main/java/org/vaadin/viritinv7/fields/MTextField.java | boniechacha/viritin | 3ff3b20d4f8bbcba9a81730c2aa751fdba3e1383 | [
"Apache-2.0"
] | 298 | 2015-01-09T15:08:32.000Z | 2021-05-12T21:06:47.000Z | viritin-compatibility/src/main/java/org/vaadin/viritinv7/fields/MTextField.java | boniechacha/viritin | 3ff3b20d4f8bbcba9a81730c2aa751fdba3e1383 | [
"Apache-2.0"
] | 112 | 2015-01-21T08:44:28.000Z | 2022-01-16T13:27:57.000Z | 31.66763 | 168 | 0.635028 | 999,559 | /*
* Copyright 2014 mattitahvonenitmill.
*
* 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.vaadin.viritinv7.fields;
import java.util.EventObject;
import java.util.Map;
import org.vaadin.viritin.util.HtmlElementPropertySetter;
import org.vaadin.viritinv7.fluency.ui.FluentTextField;
import com.vaadin.server.AbstractErrorMessage;
import com.vaadin.server.CompositeErrorMessage;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.Resource;
import com.vaadin.v7.data.Property;
import com.vaadin.v7.data.Validator;
import com.vaadin.v7.data.util.converter.Converter;
import com.vaadin.v7.data.util.converter.ConverterUtil;
import com.vaadin.v7.event.FieldEvents;
import com.vaadin.v7.event.FieldEvents.TextChangeEvent;
import com.vaadin.v7.ui.TextField;
/**
* A an extension to basic Vaadin TextField. Uses the only sane default for
* "nullRepresentation" (""), adds support for "eager validation" (~ validate
* while typing) and adds some fluent APIs.
*/
public class MTextField extends TextField
implements EagerValidateable, FluentTextField<MTextField> {
private static final long serialVersionUID = -9001913175922725871L;
private boolean eagerValidation = false;
private boolean eagerValidationStatus;
private String lastKnownTextChangeValue;
private Validator.InvalidValueException eagerValidationError;
private AutoComplete autocomplete;
private AutoCapitalize autocapitalize;
private AutoCorrect autocorrect;
private Boolean spellcheck;
boolean userValueChange;
public MTextField() {
configureMaddonStuff();
}
private void configureMaddonStuff() {
setNullRepresentation("");
}
public MTextField(String caption) {
super(caption);
configureMaddonStuff();
}
public MTextField(Property dataSource) {
super(dataSource);
configureMaddonStuff();
}
public MTextField(String caption, Property dataSource) {
super(caption, dataSource);
configureMaddonStuff();
}
public MTextField(String caption, String value) {
super(caption, value);
}
@Override
protected void setValue(String newFieldValue, boolean repaintIsNotNeeded) throws ReadOnlyException, Converter.ConversionException, Validator.InvalidValueException {
lastKnownTextChangeValue = null;
eagerValidationError = null;
super.setValue(newFieldValue, repaintIsNotNeeded);
}
@Override
public boolean isEagerValidation() {
return eagerValidation;
}
@Override
public void setEagerValidation(boolean eagerValidation) {
this.eagerValidation = eagerValidation;
}
@Override
protected void fireEvent(EventObject event) {
if (isEagerValidation() && event instanceof TextChangeEvent) {
lastKnownTextChangeValue = ((TextChangeEvent) event).getText();
doEagerValidation();
}
super.fireEvent(event);
}
/**
*
* @return the value of the field or if a text change event have sent a
* value to the server since last value changes, then that.
*/
public String getLastKnownTextContent() {
return lastKnownTextChangeValue;
}
public void setSpellcheck(Boolean spellcheck) {
this.spellcheck = spellcheck;
}
public Boolean getSpellcheck() {
return spellcheck;
}
public MTextField withSpellCheckOff() {
setSpellcheck(false);
return this;
}
public enum AutoComplete {
on, off
}
public enum AutoCorrect {
on, off
}
public enum AutoCapitalize {
on, off
}
public MTextField withAutocompleteOff() {
return setAutocomplete(AutoComplete.off);
}
public MTextField setAutocomplete(AutoComplete autocomplete) {
this.autocomplete = autocomplete;
return this;
}
public AutoComplete getAutocomplete() {
return autocomplete;
}
public MTextField withAutoCapitalizeOff() {
return setAutoCapitalize(AutoCapitalize.off);
}
public MTextField setAutoCapitalize(AutoCapitalize autoCapitalize) {
this.autocapitalize = autoCapitalize;
return this;
}
public AutoCapitalize getAutoCapitalize() {
return autocapitalize;
}
public MTextField withAutoCorrectOff() {
return setAutoCorrect(AutoCorrect.off);
}
public MTextField setAutoCorrect(AutoCorrect autoCorrect) {
this.autocorrect = autoCorrect;
return this;
}
public AutoCorrect getAutoCorrect() {
return autocorrect;
}
private HtmlElementPropertySetter heps;
protected HtmlElementPropertySetter getHtmlElementPropertySetter() {
if (heps == null) {
heps = new HtmlElementPropertySetter(this);
}
return heps;
}
@Override
public void beforeClientResponse(boolean initial) {
super.beforeClientResponse(initial);
if (initial) {
if(spellcheck != null) {
getHtmlElementPropertySetter().setProperty(
"spellcheck", spellcheck);
}
if (autocomplete != null) {
// sending here to keep value if toggling visibility
getHtmlElementPropertySetter().setProperty("autocomplete",
autocomplete.toString());
}
if (autocorrect != null) {
// sending here to keep value if toggling visibility
getHtmlElementPropertySetter().setProperty("autocorrect",
autocorrect.toString());
}
if (autocapitalize != null) {
// sending here to keep value if toggling visibility
getHtmlElementPropertySetter().setProperty("autocapitalize",
autocapitalize.toString());
}
}
}
@Override
public ErrorMessage getErrorMessage() {
Validator.InvalidValueException validationError = getValidationError();
final ErrorMessage superError = getComponentError();
if (superError == null && validationError == null
&& getCurrentBufferedSourceException() == null) {
return null;
}
// Throw combination of the error types
return new CompositeErrorMessage(
new ErrorMessage[]{
superError,
AbstractErrorMessage
.getErrorMessageForException(validationError),
AbstractErrorMessage
.getErrorMessageForException(
getCurrentBufferedSourceException())});
}
protected Validator.InvalidValueException getValidationError() {
if (isEagerValidation() && lastKnownTextChangeValue != null) {
return eagerValidationError;
}
/*
* Check validation errors only if automatic validation is enabled.
* Empty, required fields will generate a validation error containing
* the requiredError string. For these fields the exclamation mark will
* be hidden but the error must still be sent to the client.
*/
Validator.InvalidValueException validationError = null;
if (isValidationVisible()) {
try {
validate();
} catch (Validator.InvalidValueException e) {
if (!e.isInvisible()) {
validationError = e;
}
}
}
return validationError;
}
protected void doEagerValidation() {
final boolean wasvalid = eagerValidationStatus;
eagerValidationStatus = true;
eagerValidationError = null;
try {
if (isRequired() && getLastKnownTextContent().isEmpty()) {
throw new Validator.EmptyValueException(getRequiredError());
}
validate(getLastKnownTextContent());
if (!wasvalid) {
markAsDirty();
}
// Also eagerly pass content to backing bean to make top level
// validation eager, but do not listen the value back in value change
// event
if (getPropertyDataSource() != null) {
skipValueChangeEvent = true;
Object convertedValue = ConverterUtil.convertToModel(
getLastKnownTextContent(), getPropertyDataSource().
getType(), getConverter(),
getLocale());
getPropertyDataSource().setValue(convertedValue);
skipValueChangeEvent = false;
}
} catch (Validator.InvalidValueException e) {
eagerValidationError = e;
eagerValidationStatus = false;
markAsDirty();
}
}
private boolean skipValueChangeEvent = false;
@Override
public void valueChange(Property.ValueChangeEvent event) {
if (!skipValueChangeEvent) {
super.valueChange(event);
} else {
skipValueChangeEvent = false;
}
}
@Override
public boolean isValid() {
if (isEagerValidation() && lastKnownTextChangeValue != null) {
return eagerValidationStatus;
} else {
return super.isValid();
}
}
@Override
public void validate() throws Validator.InvalidValueException {
if (isEagerValidation() && lastKnownTextChangeValue != null) {
// This is most likely not executed, unless someone, for some weird
// reason calls this explicitly
if (isRequired() && getLastKnownTextContent().isEmpty()) {
throw new Validator.EmptyValueException(getRequiredError());
}
validate(getLastKnownTextContent());
} else {
super.validate();
}
}
@Override
public void changeVariables(Object source, Map<String, Object> variables) {
userValueChange = true;
super.changeVariables(source, variables); //To change body of generated methods, choose Tools | Templates.
userValueChange = false;
}
/**
* @return true if the current value change event is created by a user
* action.
*/
public boolean isUserValueChange() {
return userValueChange;
}
}
|
923b5924c625ddac6fedf7e21cd71295d25f90c9 | 2,817 | java | Java | src/main/java/org/aoju/lancia/option/MouseOption.java | aoju/lancia | fb7d5549390b8ff1418e7bde7f20e202c8395649 | [
"MIT"
] | 149 | 2019-08-05T10:06:25.000Z | 2022-03-03T08:20:16.000Z | src/main/java/org/aoju/lancia/option/MouseOption.java | aoju/lancia | fb7d5549390b8ff1418e7bde7f20e202c8395649 | [
"MIT"
] | 3 | 2019-09-01T10:20:53.000Z | 2021-09-17T03:25:26.000Z | src/main/java/org/aoju/lancia/option/MouseOption.java | aoju/lancia | fb7d5549390b8ff1418e7bde7f20e202c8395649 | [
"MIT"
] | 13 | 2019-08-09T03:20:57.000Z | 2021-12-13T07:31:11.000Z | 40.826087 | 82 | 0.466454 | 999,560 | /*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2021 aoju.org and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *
********************************************************************************/
package org.aoju.lancia.option;
/**
* 鼠标选项参数
*
* @author Kimi Liu
* @version 1.2.8
* @since JDK 1.8+
*/
public class MouseOption {
/**
* 'none' | 'left' | 'right' | 'middle';
*/
private String button;
private int clickCount;
public MouseOption() {
super();
}
public MouseOption(String button, int clickCount) {
this.button = button;
this.clickCount = clickCount;
}
public String getButton() {
return button;
}
public void setButton(String button) {
this.button = button;
}
public int getClickCount() {
return clickCount;
}
public void setClickCount(int clickCount) {
this.clickCount = clickCount;
}
}
|
923b5946994ace100a1ec282a0970a4356f3a147 | 3,513 | java | Java | deeplearning4j-scaleout/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/sequencevectors/sequence/Sequence.java | atollFP/deeplearning4j | f38dfce2cfbf3bf19c63d2f452b514f058b0b47f | [
"Apache-2.0"
] | 1 | 2019-07-04T07:07:26.000Z | 2019-07-04T07:07:26.000Z | deeplearning4j-scaleout/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/sequencevectors/sequence/Sequence.java | atollFP/deeplearning4j | f38dfce2cfbf3bf19c63d2f452b514f058b0b47f | [
"Apache-2.0"
] | 1 | 2021-08-02T17:26:06.000Z | 2021-08-02T17:26:06.000Z | deeplearning4j-scaleout/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/sequencevectors/sequence/Sequence.java | atollFP/deeplearning4j | f38dfce2cfbf3bf19c63d2f452b514f058b0b47f | [
"Apache-2.0"
] | 1 | 2020-04-25T06:34:37.000Z | 2020-04-25T06:34:37.000Z | 22.670968 | 157 | 0.588503 | 999,561 | package org.deeplearning4j.models.sequencevectors.sequence;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import java.io.Serializable;
import java.util.*;
/**
* Sequence for SequenceVectors is defined as limited set of SequenceElements. It can also contain label, if you're going to learn Sequence features as well.
*
* @author anpch@example.com
*/
public class Sequence<T extends SequenceElement> implements Serializable {
private static final long serialVersionUID = 2223750736522624732L;
protected List<T> elements = new ArrayList<>();
// elements map needed to speedup searches againt elements in sequence
protected Map<String, T> elementsMap = new LinkedHashMap<>();
// each document can have multiple labels
protected List<T> labels = new ArrayList<>();
protected T label;
@Getter @Setter protected int sequenceId;
/**
* Creates new empty sequence
*
*/
public Sequence() {
}
/**
* Creates new sequence from collection of elements
*
* @param set
*/
public Sequence(@NonNull Collection<T> set) {
this();
addElements(set);
}
/**
* Adds single element to sequence
*
* @param element
*/
public synchronized void addElement(@NonNull T element) {
this.elementsMap.put(element.getLabel(), element);
this.elements.add(element);
}
/**
* Adds collection of elements to the sequence
*
* @param set
*/
public void addElements(Collection<T> set) {
for (T element : set) {
addElement(element);
}
}
/**
* Returns this sequence as list of labels
* @return
*/
public List<String> asLabels() {
List<String> labels = new ArrayList<>();
for(T element: getElements()) {
labels.add(element.getLabel());
}
return labels;
}
/**
* Returns single element out of this sequence by its label
*
* @param label
* @return
*/
public T getElementByLabel(@NonNull String label) {
return elementsMap.get(label);
}
/**
* Returns ordered list of elements from this sequence
*
* @return
*/
public List<T> getElements() {
return Collections.unmodifiableList(elements);
}
/**
* Returns label for this sequence
*
* @return label for this sequence, null if label was not defined
*/
public T getSequenceLabel() {
return label;
}
/**
* Returns all labels for this sequence
*
* @return
*/
public List<T> getSequenceLabels() {
return labels;
}
/**
* Sets sequence labels
* @param labels
*/
public void setSequenceLabels(List<T> labels) {
this.labels = labels;
}
/**
* Set sequence label
*
* @param label
*/
public void setSequenceLabel(@NonNull T label) {
this.label = label;
if (!labels.contains(label)) labels.add(label);
}
/**
* Adds sequence label. In this case sequence will have multiple labels
*
* @param label
*/
public void addSequenceLabel(@NonNull T label) {
this.labels.add(label);
if (this.label == null) this.label = label;
}
@Override
public String toString() {
return "Sequence{" +
" labels=" + labels +
", elements=" + elements +
'}';
}
}
|
923b5a66721e880d630d0812f24bca9a39053271 | 527 | java | Java | quickstart-design-pattern/src/test/java/org/quickstart/design/pattern/iterator/example/Test.java | youngzil/quickstart-framework | 5252ab4ffe089461969ed54420d3f9f8980baa03 | [
"Apache-2.0"
] | 6 | 2019-01-02T11:02:38.000Z | 2021-01-30T16:35:20.000Z | quickstart-design-pattern/src/test/java/org/quickstart/design/pattern/iterator/example/Test.java | youngzil/quickstart-framework | 5252ab4ffe089461969ed54420d3f9f8980baa03 | [
"Apache-2.0"
] | 31 | 2019-11-13T02:06:18.000Z | 2022-03-31T20:51:49.000Z | quickstart-design-pattern/src/test/java/org/quickstart/design/pattern/iterator/example/Test.java | youngzil/quickstart-framework | 5252ab4ffe089461969ed54420d3f9f8980baa03 | [
"Apache-2.0"
] | 3 | 2018-07-10T15:08:02.000Z | 2020-09-02T06:48:07.000Z | 18.37931 | 55 | 0.615385 | 999,562 | /**
* 项目名称:quickstart-design-pattern
* 文件名:Test.java
* 版本信息:
* 日期:2018年1月27日
* Copyright yangzl Corporation 2018
* 版权所有 *
*/
package org.quickstart.design.pattern.iterator.example;
/**
* Test
*
* @ychag@example.com
* @2018年1月27日 上午9:14:38
* @since 1.0
*/
public class Test {
public static void main(String[] args) {
Collection collection = new MyCollection();
Iterator it = collection.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
|
923b5a6a56d643d0da0d8e5967aa6e451160903e | 1,237 | java | Java | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/DeploymentListResourceProvider.java | rpau/arquillian-cube | 00ef748aaacaa1a0550b28cbcf2715a9be35ddd7 | [
"Apache-2.0"
] | 1 | 2017-12-27T06:47:26.000Z | 2017-12-27T06:47:26.000Z | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/DeploymentListResourceProvider.java | rpau/arquillian-cube | 00ef748aaacaa1a0550b28cbcf2715a9be35ddd7 | [
"Apache-2.0"
] | 2 | 2018-07-28T21:40:24.000Z | 2018-07-28T21:40:24.000Z | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/DeploymentListResourceProvider.java | rpau/arquillian-cube | 00ef748aaacaa1a0550b28cbcf2715a9be35ddd7 | [
"Apache-2.0"
] | null | null | null | 37.484848 | 125 | 0.745352 | 999,563 | package org.arquillian.cube.kubernetes.impl.enricher.internal;
import java.lang.annotation.Annotation;
import java.util.Map;
import io.fabric8.kubernetes.api.model.v3_1.extensions.DeploymentList;
import org.arquillian.cube.kubernetes.impl.enricher.AbstractKubernetesResourceProvider;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
/**
* A {@link ResourceProvider} for {@link DeploymentList}.
* It refers to deplotments that have been created during the current session.
*/
public class DeploymentListResourceProvider extends AbstractKubernetesResourceProvider {
@Override
public boolean canProvide(Class<?> type) {
return DeploymentList.class.isAssignableFrom(type);
}
@Override
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
Map<String, String> labels = getLabels(qualifiers);
if (labels.isEmpty()) {
return getClient().extensions().deployments().inNamespace(getSession().getNamespace()).list();
} else {
return getClient().extensions().deployments().inNamespace(getSession().getNamespace()).withLabels(labels).list();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.