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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e09bf22990115bab2780203def75727446f103c | 1,016 | java | Java | selene-device-peripheral/src/main/java/moonstone/selene/device/peripheral/devices/grovepi/Buzzer.java | konexios/moonstone | 47f7b874e68833e19314dd9bc5fdf1755a82a42f | [
"Apache-2.0"
] | 3 | 2019-12-24T05:28:11.000Z | 2021-05-02T21:20:16.000Z | selene-device-peripheral/src/main/java/moonstone/selene/device/peripheral/devices/grovepi/Buzzer.java | arrow-acs/moonstone | 47f7b874e68833e19314dd9bc5fdf1755a82a42f | [
"Apache-2.0"
] | 4 | 2019-11-20T17:10:45.000Z | 2020-06-18T15:09:12.000Z | selene-device-peripheral/src/main/java/moonstone/selene/device/peripheral/devices/grovepi/Buzzer.java | arrow-acs/moonstone | 47f7b874e68833e19314dd9bc5fdf1755a82a42f | [
"Apache-2.0"
] | 1 | 2021-05-02T21:20:30.000Z | 2021-05-02T21:20:30.000Z | 22.086957 | 95 | 0.719488 | 4,118 | package moonstone.selene.device.peripheral.devices.grovepi;
import java.util.Map;
import java.util.Objects;
import moonstone.selene.device.peripheral.ControlledPeripheralDevice;
import moonstone.selene.engine.state.State;
public class Buzzer extends GrovePiDevice<BuzzerStates> implements ControlledPeripheralDevice {
private static final String ON_VALUE = "on";
@Override
public boolean changeState(Map<String, State> states) {
BuzzerStates buzzerStates = populate(states);
String buzzer = buzzerStates.getBuzzer().getValue();
String value = buzzerStates.getValue().getValue();
if (buzzer != null) {
if (Objects.equals(buzzer, ON_VALUE)) {
on();
} else {
off();
}
} else if (value != null) {
value(Integer.parseInt(value));
}
return true;
}
@Override
public BuzzerStates createStates() {
return new BuzzerStates();
}
private void on() {
digitalWrite(1);
}
private void off() {
digitalWrite(0);
}
private void value(int value) {
analogWrite(value);
}
}
|
3e09bf6b140c4ca3cb150cdc9c352f0202e09454 | 1,534 | java | Java | Communicator/src/main/java/com/george200150/bsc/util/BitmapFormatAdapter.java | george200150/Licenta | 9c3f7d86abf3cc5d90204db0acc956eb8bee26dc | [
"MIT"
] | null | null | null | Communicator/src/main/java/com/george200150/bsc/util/BitmapFormatAdapter.java | george200150/Licenta | 9c3f7d86abf3cc5d90204db0acc956eb8bee26dc | [
"MIT"
] | null | null | null | Communicator/src/main/java/com/george200150/bsc/util/BitmapFormatAdapter.java | george200150/Licenta | 9c3f7d86abf3cc5d90204db0acc956eb8bee26dc | [
"MIT"
] | null | null | null | 28.943396 | 64 | 0.520209 | 4,119 | package com.george200150.bsc.util;
import com.george200150.bsc.model.Bitmap;
public class BitmapFormatAdapter {
public static Bitmap convertColorToRGB(Bitmap bitmap) {
int h = bitmap.getHeight();
int w = bitmap.getWidth();
int[] androidPixels = bitmap.getPixels();
int[] pixels = new int[3 * h * w];
int index = 0;
for (int intPix : androidPixels) {
int r = (intPix >> 16) & 0xff;
int g = (intPix >> 8) & 0xff;
int b = intPix & 0xff;
pixels[index] = r;
pixels[index + 1] = g;
pixels[index + 2] = b;
index += 3;
}
bitmap.setPixels(pixels);
return bitmap;
}
public static Bitmap convertRGBToColor(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = bitmap.getPixels();
//convert flat RGB to Color(R,G,B)
int[] array = new int[3 * width * height];
int index = 0;
int arrayIndex = 0;
while (index + 2 < pixels.length) {
int red = pixels[index];
int green = pixels[index + 1];
int blue = pixels[index + 2];
array[arrayIndex] = rgb(red, green, blue);
index += 3;
arrayIndex += 1;
}
bitmap.setPixels(array);
return bitmap;
}
private static int rgb(int red, int green, int blue) {
return (0xFF << 24) | (red << 16) | (green << 8) | blue;
}
}
|
3e09c08dd8f8c179568509d7fe033f6b5b229133 | 651 | java | Java | src/test/java/org/otaibe/eureka/client/TestControllerTest.java | tpenakov/org-otaibe-eureka-client | 3b8ddde837fbb5f24dcae678763f305642ed622c | [
"MIT"
] | 8 | 2019-10-14T09:21:41.000Z | 2021-08-16T12:04:50.000Z | src/test/java/org/otaibe/eureka/client/TestControllerTest.java | tpenakov/org-otaibe-eureka-client | 3b8ddde837fbb5f24dcae678763f305642ed622c | [
"MIT"
] | null | null | null | src/test/java/org/otaibe/eureka/client/TestControllerTest.java | tpenakov/org-otaibe-eureka-client | 3b8ddde837fbb5f24dcae678763f305642ed622c | [
"MIT"
] | 1 | 2021-08-05T18:35:01.000Z | 2021-08-05T18:35:01.000Z | 22.448276 | 67 | 0.680492 | 4,120 | package org.otaibe.eureka.client;
import io.quarkus.test.junit.QuarkusTest;
import lombok.Getter;
import org.junit.jupiter.api.Test;
import org.otaibe.eureka.client.utils.ControllerUtils;
import javax.inject.Inject;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
@QuarkusTest
@Getter
public class TestControllerTest {
@Inject
ControllerUtils controllerUtils;
@Test
public void testHelloEndpoint() {
given()
.when().get(getControllerUtils().getBasePath() + "/test")
.then()
.statusCode(200)
.body(is("hello"));
}
} |
3e09c12be9bb43a3efcf7006a410111e58c804ed | 8,562 | java | Java | webrtc-peerconnection/src/test/java/com/bitbreeds/webrtc/sctp/impl/buffer/ReceiveBufferOrderedUnfragmentedTest.java | IIlllII/bitbreeds-webrtc | 863dbcbcad115a8a505bb4b64be8479bac059ba0 | [
"MIT"
] | 11 | 2017-04-08T16:12:44.000Z | 2021-09-20T21:07:07.000Z | webrtc-peerconnection/src/test/java/com/bitbreeds/webrtc/sctp/impl/buffer/ReceiveBufferOrderedUnfragmentedTest.java | IIlllII/bitbreeds-webrtc | 863dbcbcad115a8a505bb4b64be8479bac059ba0 | [
"MIT"
] | 4 | 2017-03-04T18:26:08.000Z | 2020-01-06T23:37:43.000Z | webrtc-peerconnection/src/test/java/com/bitbreeds/webrtc/sctp/impl/buffer/ReceiveBufferOrderedUnfragmentedTest.java | IIlllII/bitbreeds-webrtc | 863dbcbcad115a8a505bb4b64be8479bac059ba0 | [
"MIT"
] | 3 | 2018-05-07T11:46:48.000Z | 2021-01-17T05:48:58.000Z | 36.434043 | 140 | 0.663046 | 4,121 | package com.bitbreeds.webrtc.sctp.impl.buffer;
import com.bitbreeds.webrtc.model.sctp.SCTPPayloadProtocolId;
import com.bitbreeds.webrtc.model.sctp.SackUtil;
import com.bitbreeds.webrtc.model.webrtc.Deliverable;
import com.bitbreeds.webrtc.sctp.impl.SCTPReliability;
import com.bitbreeds.webrtc.sctp.impl.model.ReceivedData;
import com.bitbreeds.webrtc.sctp.model.SCTPOrderFlag;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* Copyright (c) 20/02/2018, Jonas Waage
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* <p>
* 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.
*/
public class ReceiveBufferOrderedUnfragmentedTest {
private ReceivedData makeDsStream1(long tsn, int ssn, byte[] data) {
return new ReceivedData(tsn,
1,
ssn,
SCTPOrderFlag.ORDERED_UNFRAGMENTED,
SCTPPayloadProtocolId.WEBRTC_BINARY,
SCTPReliability.createOrdered(),
data);
}
private ReceivedData makeDsStream2(long tsn, int ssn, byte[] data) {
return new ReceivedData(tsn,
2,
ssn,
SCTPOrderFlag.ORDERED_UNFRAGMENTED,
SCTPPayloadProtocolId.WEBRTC_BINARY,
SCTPReliability.createOrdered(),
data);
}
@Test
public void testReceiveOneOrdered() {
ReceiveBuffer buffer = new ReceiveBuffer(6,100);
buffer.setInitialTSN(1);
ReceivedData ds = makeDsStream1(1,0,new byte[]{0,1,2});
buffer.store(ds);
List<Deliverable> del = buffer.getMessagesForDelivery();
assertEquals(Collections.singletonList(new Deliverable(ds.getPayload(),0,del.get(0).getStreamId(),del.get(0).getProtocolId())),del);
SackData sack = buffer.getSackDataToSend();
assertEquals(1,sack.getCumulativeTSN());
assertEquals(sack.getTsns(),Collections.emptyList());
assertEquals(sack.getDuplicates(),Collections.emptyList());
}
@Test
public void testReceiveManyOrdered() {
ReceiveBuffer buffer = new ReceiveBuffer(6,100);
buffer.setInitialTSN(1);
buffer.store(makeDsStream1(1,0,new byte[]{0,1,2}));
buffer.store(makeDsStream1(2,1,new byte[]{0,1,2}));
buffer.store(makeDsStream1(3,2,new byte[]{0,1,2}));
buffer.store(makeDsStream1(4,3,new byte[]{0,1,2}));
List<Deliverable> del = buffer.getMessagesForDelivery();
assertEquals(4,del.size());
SackData sack = buffer.getSackDataToSend();
assertEquals(4,sack.getCumulativeTSN());
assertEquals(sack.getTsns(),Collections.emptyList());
assertEquals(sack.getDuplicates(),Collections.emptyList());
}
@Test
public void testReceiveOutOfOrderMissing0ne() {
ReceiveBuffer buffer = new ReceiveBuffer(6,100);
buffer.setInitialTSN(1);
buffer.store(makeDsStream1(1,0,new byte[]{0,1,2}));
buffer.store(makeDsStream1(2,1,new byte[]{0,1,2}));
buffer.store(makeDsStream1(4,3,new byte[]{0,1,2}));
List<Deliverable> del = buffer.getMessagesForDelivery();
assertEquals(2,del.size());
SackData sack = buffer.getSackDataToSend();
assertEquals(2,sack.getCumulativeTSN());
assertEquals( SackUtil.getGapAckList(0L,Stream.of(2L).collect(Collectors.toSet())),sack.getTsns());
assertEquals(sack.getDuplicates(),Collections.emptyList());
}
@Test
public void testReceiveOutOfOrderDifferentStream() {
ReceiveBuffer buffer = new ReceiveBuffer(6,100);
buffer.setInitialTSN(1);
buffer.store(makeDsStream1(1,0,new byte[]{0,1,2}));
buffer.store(makeDsStream1(2,1,new byte[]{0,1,2}));
buffer.store(makeDsStream2(4,0,new byte[]{0,1,2}));
buffer.store(makeDsStream2(5,1,new byte[]{0,1,2}));
List<Deliverable> del = buffer.getMessagesForDelivery();
assertEquals(4,del.size());
SackData sack = buffer.getSackDataToSend();
assertEquals(2,sack.getCumulativeTSN());
assertEquals( SackUtil.getGapAckList(0L,Stream.of(2L,3L).collect(Collectors.toSet())),sack.getTsns());
assertEquals(sack.getDuplicates(),Collections.emptyList());
}
@Test
public void testReceiveDuplicate() {
ReceiveBuffer buffer = new ReceiveBuffer(6,100);
buffer.setInitialTSN(1);
buffer.store(makeDsStream1(1,0,new byte[]{0,1,2}));
buffer.store(makeDsStream1(2,1,new byte[]{0,1,2}));
buffer.store(makeDsStream1(2,1,new byte[]{0,1,2}));
buffer.store(makeDsStream1(1,0,new byte[]{0,1,2}));
List<Deliverable> del = buffer.getMessagesForDelivery();
assertEquals(2,del.size());
SackData sack = buffer.getSackDataToSend();
assertEquals(2,sack.getCumulativeTSN());
assertEquals(Collections.emptyList(),sack.getTsns());
assertEquals(Stream.of(2L,1L).collect(Collectors.toList()),sack.getDuplicates());
}
@Test
public void testWrapBuffer() {
ReceiveBuffer buffer = new ReceiveBuffer(6,100);
buffer.setInitialTSN(1);
buffer.store(makeDsStream1(1,0,new byte[]{0,1,2}));
buffer.store(makeDsStream1(2,1,new byte[]{0,1,2}));
List<Deliverable> del = buffer.getMessagesForDelivery();
assertEquals(2,del.size());
SackData sack = buffer.getSackDataToSend();
assertEquals(2,sack.getCumulativeTSN());
buffer.store(makeDsStream1(3,2,new byte[]{0,1,2}));
buffer.store(makeDsStream1(4,3,new byte[]{0,1,2}));
List<Deliverable> del2 = buffer.getMessagesForDelivery();
assertEquals(2,del2.size());
SackData sack2 = buffer.getSackDataToSend();
assertEquals(4,sack2.getCumulativeTSN());
buffer.store(makeDsStream1(5,4,new byte[]{0,0,0}));
buffer.store(makeDsStream1(6,5,new byte[]{1,1,1}));
buffer.store(makeDsStream1(7,6,new byte[]{2,2,2}));
buffer.store(makeDsStream1(8,7,new byte[]{3,3,3}));
List<Deliverable> del3 = buffer.getMessagesForDelivery();
assertEquals(4,del3.size());
List<byte[]> data = del3.stream()
.map(Deliverable::getData)
.collect(Collectors.toList());
assertArrayEquals(new byte[]{0,0,0},data.get(0));
assertArrayEquals(new byte[]{1,1,1},data.get(1));
assertArrayEquals(new byte[]{2,2,2},data.get(2));
assertArrayEquals(new byte[]{3,3,3},data.get(3));
SackData sack3 = buffer.getSackDataToSend();
assertEquals(8,sack3.getCumulativeTSN());
assertEquals(Collections.emptyList(),sack3.getTsns());
assertEquals(Collections.emptyList(),sack3.getDuplicates());
}
@Test(expected = OutOfBufferSpaceError.class)
public void testWrapBufferNoClearFull() {
ReceiveBuffer buffer = new ReceiveBuffer(6,100);
buffer.setInitialTSN(1);
buffer.store(makeDsStream1(1,1,new byte[]{0,1,2}));
buffer.store(makeDsStream1(2,2,new byte[]{0,1,2}));
buffer.store(makeDsStream1(3,3,new byte[]{0,1,2}));
buffer.store(makeDsStream1(4,4,new byte[]{0,1,2}));
buffer.store(makeDsStream1(5,5,new byte[]{0,1,2}));
buffer.store(makeDsStream1(6,6,new byte[]{0,1,2}));
buffer.store(makeDsStream1(7,7,new byte[]{0,1,2}));
buffer.store(makeDsStream1(8,8,new byte[]{0,1,2}));
}
}
|
3e09c191bfaab91946c4c923495eb95141f505c0 | 2,306 | java | Java | bundles/gw4e-eclipse-plugin/src/org/gw4e/eclipse/builder/marker/MultipleMarkerResolution.java | gw4e/gw4e-project | 148127b1ab4f68762d22c33104fce656d094cbbf | [
"MIT"
] | 4 | 2017-06-02T16:43:01.000Z | 2020-04-02T15:23:07.000Z | bundles/gw4e-eclipse-plugin/src/org/gw4e/eclipse/builder/marker/MultipleMarkerResolution.java | gw4e/gw4e-project | 148127b1ab4f68762d22c33104fce656d094cbbf | [
"MIT"
] | 2 | 2020-04-02T13:47:02.000Z | 2021-10-14T06:00:52.000Z | bundles/gw4e-eclipse-plugin/src/org/gw4e/eclipse/builder/marker/MultipleMarkerResolution.java | gw4e/gw4e-project | 148127b1ab4f68762d22c33104fce656d094cbbf | [
"MIT"
] | 1 | 2020-10-08T07:49:40.000Z | 2020-10-08T07:49:40.000Z | 31.589041 | 111 | 0.728534 | 4,122 | package org.gw4e.eclipse.builder.marker;
/*-
* #%L
* gw4e
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2017 gw4e-project
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IMarkerResolution;
public abstract class MultipleMarkerResolution extends org.eclipse.ui.views.markers.WorkbenchMarkerResolution {
public MultipleMarkerResolution() {
}
@Override
public String getDescription() {
return getLabel();
}
@Override
public Image getImage() {
return null;
}
@Override
public IMarker[] findOtherMarkers(IMarker[] markers) {
List<IMarker> similars = new ArrayList<IMarker>();
MarkerResolutionGenerator mrg = new MarkerResolutionGenerator();
for (int i = 0; i < markers.length; i++) {
IMarker marker = markers[i];
IMarkerResolution[] resolutions = mrg.getResolutions(marker);
if (resolutions==null) continue;
for (int j = 0; j < resolutions.length; j++) {
if (resolutions[j].getClass().getName().equals(this.getClass().getName())){
similars.add(marker);
}
}
}
IMarker[] ret = new IMarker[similars.size()];
similars.toArray(ret);
return ret;
}
}
|
3e09c222a5099cc89837f31789316873949d63df | 974 | java | Java | crd-generator/api/src/test/java/io/fabric8/crd/example/person/Person.java | see-quick/kubernetes-client | 34f37509a37cbc156ed1a458cf7e03ec55d2639b | [
"Apache-2.0"
] | 2,460 | 2015-08-26T08:44:49.000Z | 2022-03-31T09:52:23.000Z | crd-generator/api/src/test/java/io/fabric8/crd/example/person/Person.java | see-quick/kubernetes-client | 34f37509a37cbc156ed1a458cf7e03ec55d2639b | [
"Apache-2.0"
] | 3,934 | 2015-07-16T14:51:50.000Z | 2022-03-31T20:14:44.000Z | crd-generator/api/src/test/java/io/fabric8/crd/example/person/Person.java | see-quick/kubernetes-client | 34f37509a37cbc156ed1a458cf7e03ec55d2639b | [
"Apache-2.0"
] | 1,259 | 2015-07-16T14:36:46.000Z | 2022-03-31T09:52:26.000Z | 27.828571 | 75 | 0.732033 | 4,123 | /**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.crd.example.person;
import java.util.List;
import java.util.Optional;
public class Person {
private String firstName;
private Optional<String> middleName;
private String lastName;
private int birthYear;
private List<String> hobbies;
private List<Address> addresses;
private Type type;
public enum Type {
crazy, crazier
}
}
|
3e09c285cb8c08b40a87fb9e5cd5f615165e48a7 | 1,039 | java | Java | mantis-tests/src/test/java/ru/stqa/b28/mantis/appmanager/SessionHelper.java | olgamit/java_b28 | e4a1bbb6abf0fb8a9fa3d35f8d45af24c494405e | [
"Apache-2.0"
] | null | null | null | mantis-tests/src/test/java/ru/stqa/b28/mantis/appmanager/SessionHelper.java | olgamit/java_b28 | e4a1bbb6abf0fb8a9fa3d35f8d45af24c494405e | [
"Apache-2.0"
] | null | null | null | mantis-tests/src/test/java/ru/stqa/b28/mantis/appmanager/SessionHelper.java | olgamit/java_b28 | e4a1bbb6abf0fb8a9fa3d35f8d45af24c494405e | [
"Apache-2.0"
] | null | null | null | 32.46875 | 72 | 0.640038 | 4,124 | package ru.stqa.b28.mantis.appmanager;
import org.openqa.selenium.By;
public class SessionHelper extends HelperBase {
public SessionHelper(ApplicationManager app) {
super(app);
}
public void login() {
wd.get(app.getProperty("web.baseUrl") + "/login_page.php");
type(By.name("username"), app.getProperty("web.adminLogin"));
type(By.name("password"), app.getProperty("web.adminPassword"));
click(By.cssSelector("input[type='submit']"));
}
public void signup(String username, String email) {
wd.get(app.getProperty("web.baseUrl") + "/signup_page.php");
type(By.name("username"), username);
type(By.name("email"), email);
click(By.cssSelector("input[type='submit']"));
}
public void complete(String confirmationLink, String password) {
wd.get(confirmationLink);
type(By.name("password"), password);
type(By.name("password_confirm"), password);
click(By.cssSelector("input[value='Update User']"));
}
}
|
3e09c488ca518383e29fa9f8dc912043d0ff290b | 1,088 | java | Java | src/test/java/refreshable/service/RefreshableServiceSendTest.java | valliappanr/refreshable-beans | b3ff30c436174a107487366c2f51959ef87fa278 | [
"Apache-2.0"
] | 2 | 2017-12-10T07:47:34.000Z | 2022-01-29T03:00:07.000Z | src/test/java/refreshable/service/RefreshableServiceSendTest.java | valliappanr/refreshable-beans | b3ff30c436174a107487366c2f51959ef87fa278 | [
"Apache-2.0"
] | null | null | null | src/test/java/refreshable/service/RefreshableServiceSendTest.java | valliappanr/refreshable-beans | b3ff30c436174a107487366c2f51959ef87fa278 | [
"Apache-2.0"
] | null | null | null | 30.222222 | 90 | 0.773897 | 4,125 | package refreshable.service;
import javax.jms.JMSException;
import javax.jms.Message;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessagePostProcessor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Tests for the {@link Helper} class.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" })
public class RefreshableServiceSendTest {
@Autowired
private JmsTemplate jmsTemplate;
@Test
public void testSendMessage() {
final String messageContent="10";
jmsTemplate.convertAndSend((Object)messageContent,new MessagePostProcessor() {
public Message postProcessMessage(Message message) throws JMSException {
message.setStringProperty("CamelBeanMethodName", "execute");
return message;
}
});
}
}
|
3e09c5cb50446963bf0591b8de17cc4ac955a637 | 2,485 | java | Java | src/test/java/services/RegistrationServiceNegativeTest.java | juagarfer4/Acme-Pilgrim | babb009558e61f62524218a149059bf105694439 | [
"MIT"
] | null | null | null | src/test/java/services/RegistrationServiceNegativeTest.java | juagarfer4/Acme-Pilgrim | babb009558e61f62524218a149059bf105694439 | [
"MIT"
] | null | null | null | src/test/java/services/RegistrationServiceNegativeTest.java | juagarfer4/Acme-Pilgrim | babb009558e61f62524218a149059bf105694439 | [
"MIT"
] | null | null | null | 27.307692 | 78 | 0.767404 | 4,126 | package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.*;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import com.mchange.util.AssertException;
import domain.CreditCard;
import domain.Innkeeper;
import domain.Lodge;
import domain.LodgeAssessment;
import domain.Pilgrim;
import domain.Registration;
import domain.Request;
import domain.Route;
import domain.Stage;
import security.LoginService;
import utilities.AbstractTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/datasource.xml",
"classpath:spring/config/packages.xml" })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class RegistrationServiceNegativeTest extends AbstractTest {
// Service under test ------------------------------------------------
@Autowired
private RegistrationService registrationService;
// Tests --------------------------------------------------------------
// Registrarse a una ruta como posadero. ------------------------
@Test(expected=java.lang.IllegalArgumentException.class)
public void testNegativeCreateRegistration(){
authenticate("innkeeper1");
Registration registration;
registration=registrationService.create(24);
registrationService.save(registration);
unauthenticate();
}
// Route and stage history.
@Test(expected = java.lang.IllegalArgumentException.class)
public void testNegativeRouteHistory() {
this.authenticate("pilgrim1");
ArrayList<Route> collection;
collection = new ArrayList<>(registrationService.findAllRoutesByPilgrim());
Assert.isTrue(collection.get(0).getId()==25);
this.unauthenticate();
}
}
|
3e09c5d2767081c9118ed06d7a86405d96893c59 | 4,735 | java | Java | geoportal/src/com/esri/gpt/catalog/harvest/history/HeUpdateRequest.java | tomkralidis/geoportal-server | 9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee | [
"Apache-2.0"
] | 176 | 2015-01-08T19:00:40.000Z | 2022-03-23T10:17:30.000Z | geoportal/src/com/esri/gpt/catalog/harvest/history/HeUpdateRequest.java | tomkralidis/geoportal-server | 9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee | [
"Apache-2.0"
] | 224 | 2015-01-05T16:17:21.000Z | 2021-08-30T22:39:28.000Z | geoportal/src/com/esri/gpt/catalog/harvest/history/HeUpdateRequest.java | tomkralidis/geoportal-server | 9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee | [
"Apache-2.0"
] | 88 | 2015-01-15T11:47:05.000Z | 2022-03-10T02:06:46.000Z | 31.778523 | 98 | 0.651954 | 4,127 | /* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.esri.gpt.catalog.harvest.history;
import com.esri.gpt.catalog.harvest.repository.HrRecord;
import com.esri.gpt.control.webharvest.engine.Harvester;
import com.esri.gpt.framework.context.RequestContext;
import com.esri.gpt.framework.sql.ManagedConnection;
import com.esri.gpt.framework.util.UuidUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
/**
* Updates harvest history event.
*/
public class HeUpdateRequest extends HeRequest {
// class variables =============================================================
// instance variables ==========================================================
/** Event to update. */
private HeRecord _event = new HeRecord(new HrRecord());
// constructors ================================================================
/**
* Create instance of the request.
* @param requestContext request context
* @param event event to update
*/
public HeUpdateRequest(RequestContext requestContext,
HeRecord event) {
super(requestContext, new HeCriteria(), new HeResult());
setEvent(event);
}
// properties ==================================================================
/**
* Gets event to update.
* @return event
*/
public HeRecord getEvent() {
return _event;
}
/**
* Sets event to update.
* @param event event
*/
public void setEvent(HeRecord event) {
_event = event!=null? event: new HeRecord(new HrRecord());
}
// methods =====================================================================
/**
* Executes event.
* @throws java.sql.SQLException if accessing database failed
*/
public void execute() throws SQLException {
// intitalize
PreparedStatement stInsert = null;
PreparedStatement stUpdate = null;
try {
StringBuilder sbInsertSql = new StringBuilder();
StringBuilder sbUpdateSql = new StringBuilder();
sbInsertSql.append("INSERT INTO ").append(getHarvestingHistoryTableName()).append(" ");
sbInsertSql.append("(HARVEST_ID,HARVEST_DATE,HARVESTED_COUNT,");
sbInsertSql.append("VALIDATED_COUNT,PUBLISHED_COUNT,UUID) ");
sbInsertSql.append("VALUES (?,?,?,?,?,?)");
sbUpdateSql.append("UPDATE ").append(getHarvestingHistoryTableName()).append(" ");
sbUpdateSql.append("SET HARVEST_ID=?,HARVEST_DATE=?,HARVESTED_COUNT=?,");
sbUpdateSql.append("VALIDATED_COUNT=?,PUBLISHED_COUNT=? ");
sbUpdateSql.append("WHERE UPPER(UUID)=?");
// establish the connection
ManagedConnection mc = returnConnection();
Connection con = mc.getJdbcConnection();
stInsert = con.prepareStatement(sbInsertSql.toString());
stUpdate = con.prepareStatement(sbUpdateSql.toString());
PreparedStatement st = null;
boolean isUpdate = false;
String sUuid = "";
Date harvestDate = new Date();
if (UuidUtil.isUuid(getEvent().getUuid())) {
sUuid = getEvent().getUuid().toUpperCase();
harvestDate = getEvent().getHarvestDate();
st = stUpdate;
isUpdate = true;
} else {
sUuid = UuidUtil.makeUuid(true);
st = stInsert;
}
int n = 1;
st.setString(n++, getEvent().getRepository().getUuid());
st.setTimestamp(n++,
new java.sql.Timestamp(harvestDate.getTime()));
st.setInt(n++, getEvent().getHarvestedCount());
st.setInt(n++, getEvent().getValidatedCount());
st.setInt(n++, getEvent().getPublishedCount());
st.setString(n++, sUuid);
if (isUpdate) {
logExpression(sbUpdateSql.toString());
} else {
logExpression(sbInsertSql.toString());
}
int nRowCount = st.executeUpdate();
getActionResult().setNumberOfRecordsModified(nRowCount);
if (!isUpdate && nRowCount==1) {
getEvent().setUuid(sUuid);
getEvent().setHarvestDate(harvestDate);
Harvester harvestEngine = getRequestContext().getApplicationContext().getHarvestingEngine();
harvestEngine.reselect();
}
} finally {
closeStatement(stInsert);
closeStatement(stUpdate);
}
}
}
|
3e09c5e523f92ee13f9d6f284c6aecf24df09463 | 2,259 | java | Java | spring-web/src/test/java/org/springframework/web/method/support/ModelAndViewContainerTests.java | ericbottard/spring-framework | 859e1e800345d528b17f23e74dfaf8bf4185b070 | [
"Apache-2.0"
] | 2 | 2017-02-06T04:00:57.000Z | 2017-02-06T04:01:01.000Z | spring-web/src/test/java/org/springframework/web/method/support/ModelAndViewContainerTests.java | ericbottard/spring-framework | 859e1e800345d528b17f23e74dfaf8bf4185b070 | [
"Apache-2.0"
] | null | null | null | spring-web/src/test/java/org/springframework/web/method/support/ModelAndViewContainerTests.java | ericbottard/spring-framework | 859e1e800345d528b17f23e74dfaf8bf4185b070 | [
"Apache-2.0"
] | 4 | 2018-02-05T23:49:37.000Z | 2021-08-12T20:14:01.000Z | 29.723684 | 83 | 0.749447 | 4,128 | /*
* Copyright 2002-2012 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 org.springframework.web.method.support;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ui.ModelMap;
/**
* Test fixture for {@link ModelAndViewContainer}.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
public class ModelAndViewContainerTests {
private ModelAndViewContainer mavContainer;
@Before
public void setup() {
this.mavContainer = new ModelAndViewContainer();
}
@Test
public void getModel() {
this.mavContainer.addAttribute("name", "value");
assertEquals(1, this.mavContainer.getModel().size());
}
@Test
public void getModelRedirectModel() {
ModelMap redirectModel = new ModelMap("name", "redirectValue");
this.mavContainer.setRedirectModel(redirectModel);
this.mavContainer.addAttribute("name", "value");
assertEquals("Default model should be used if not in redirect scenario",
"value", this.mavContainer.getModel().get("name"));
this.mavContainer.setRedirectModelScenario(true);
assertEquals("Redirect model should be used in redirect scenario",
"redirectValue", this.mavContainer.getModel().get("name"));
}
@Test
public void getModelIgnoreDefaultModelOnRedirect() {
this.mavContainer.addAttribute("name", "value");
this.mavContainer.setRedirectModelScenario(true);
assertEquals("Default model should be used since no redirect model was provided",
1, this.mavContainer.getModel().size());
this.mavContainer.setIgnoreDefaultModelOnRedirect(true);
assertEquals("Empty model should be returned if no redirect model is available",
0, this.mavContainer.getModel().size());
}
}
|
3e09c65e80fcea426afa67e184f5b6e87f2f3b1f | 1,469 | java | Java | example-v2/concurrent/src/main/java/cn/enjoyedu/ch4/future/MyFutureTaskToo.java | ZuRun/xstudy | 6364d7f3c1a4a29ec2bea31632bbdd2c98e2f92e | [
"MIT"
] | 1 | 2019-04-17T01:59:46.000Z | 2019-04-17T01:59:46.000Z | example-v2/concurrent/src/main/java/cn/enjoyedu/ch4/future/MyFutureTaskToo.java | ZuRun/xstudy | 6364d7f3c1a4a29ec2bea31632bbdd2c98e2f92e | [
"MIT"
] | 20 | 2020-04-23T18:29:24.000Z | 2022-02-01T00:59:15.000Z | example-v2/concurrent/src/main/java/cn/enjoyedu/ch4/future/MyFutureTaskToo.java | ZuRun/xstudy | 6364d7f3c1a4a29ec2bea31632bbdd2c98e2f92e | [
"MIT"
] | null | null | null | 21.289855 | 68 | 0.588155 | 4,129 | package cn.enjoyedu.ch4.future;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* 类说明:FutureTask的get方法实现:
*/
public class MyFutureTaskToo <V> implements Runnable,Future<V> {
Callable<V> callable ; //封装业务逻辑
V result = null ; //执行结果
public MyFutureTaskToo(Callable<V> callable){
this.callable = callable;
}
//多线程执行run
@Override
public void run() {
try {
result = callable.call();
} catch (Exception e) {
e.printStackTrace();
}
synchronized(this){
System.out.println("-----");
this.notifyAll();
}
}
@Override
public V get() throws InterruptedException, ExecutionException {
if(result != null){
return result;
}
System.out.println("等待执行结果……等待中");
synchronized (this) {
this.wait(); //等待futurtask执行完,全部线程…………。
}
return result;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException {
return null;
}
}
|
3e09c7748f036de3d2586f9de9ecdaba67f15915 | 5,733 | java | Java | org.conqat.engine.core/test-src/org/conqat/engine/core/driver/specification/ProcessorSpecificationParameterTest.java | assessorgeneral/ConQAT | 2a462f23f22c22aa9d01a7a204453d1be670ba60 | [
"Apache-2.0"
] | 1 | 2020-04-28T20:06:30.000Z | 2020-04-28T20:06:30.000Z | org.conqat.engine.core/test-src/org/conqat/engine/core/driver/specification/ProcessorSpecificationParameterTest.java | assessorgeneral/ConQAT | 2a462f23f22c22aa9d01a7a204453d1be670ba60 | [
"Apache-2.0"
] | null | null | null | org.conqat.engine.core/test-src/org/conqat/engine/core/driver/specification/ProcessorSpecificationParameterTest.java | assessorgeneral/ConQAT | 2a462f23f22c22aa9d01a7a204453d1be670ba60 | [
"Apache-2.0"
] | null | null | null | 46.233871 | 107 | 0.729461 | 4,130 | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT 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 org.conqat.engine.core.driver.specification;
import org.conqat.engine.core.driver.error.DriverException;
import org.conqat.engine.core.driver.error.EDriverExceptionType;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithDuplicateAttributeName;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithEmptyParameterInterval;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithNonPublicFieldParameter;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithNonPublicMethodParameter;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithNonPublicParameterObjectClass;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithNonPublicParameterObjectField;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithOptionalPipelineMultiplicity;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithParameterObjectWithoutInterface;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithStaticFieldParameter;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithStaticMethodParameter;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithUnannotatedParameter;
import org.conqat.engine.core.driver.specification.processors.ProcessorWithValidPipelineMultiplicity;
/**
* Tests for {@link ProcessorSpecificationParameter}.
*
* @author $Author: hummelb $
* @version $Rev: 49408 $
* @ConQAT.Rating GREEN Hash: B480C0D98BFD7C4EEE50FAD60C14D237
*/
public class ProcessorSpecificationParameterTest extends
ProcessorSpecificationTestBase {
/** Test processor with a method where a parameter annotation is missing. */
public void testParameterNotAnnotated() {
checkException(ProcessorWithUnannotatedParameter.class,
EDriverExceptionType.FORMAL_PARAMETER_NOT_ANNOTATED);
}
/** Test processor with parameter having invalid parameter interval. */
public void testEmptyParameterInterval() {
checkException(ProcessorWithEmptyParameterInterval.class,
EDriverExceptionType.EMPTY_PARAMETER_INTERVAL);
}
/** Test processor with pipeline parameter and wrong multiplicity. */
public void testPipelineParameterMultiplicity() throws DriverException {
// both should be valid and throw no exceptions
new ProcessorSpecification(
ProcessorWithValidPipelineMultiplicity.class.getName());
new ProcessorSpecification(
ProcessorWithOptionalPipelineMultiplicity.class.getName());
}
/** Test processor with duplicate name for attribute. */
public void testProcessorWithDuplicateAttributeName() {
checkException(ProcessorWithDuplicateAttributeName.class,
EDriverExceptionType.DUPLICATE_ATTRIBUTE_NAME);
}
/** Test processor with private annotated method. */
public void testProcessorWithNonPublicMethodParameter() {
checkException(ProcessorWithNonPublicMethodParameter.class,
EDriverExceptionType.NOT_PUBLIC_PARAMETER);
}
/** Test processor with private annotated field. */
public void testProcessorWithNonPublicFieldParameter() {
checkException(ProcessorWithNonPublicFieldParameter.class,
EDriverExceptionType.NOT_PUBLIC_PARAMETER);
}
/** Test processor with static annotated method. */
public void testProcessorWithStaticMethodParameter() {
checkException(ProcessorWithStaticMethodParameter.class,
EDriverExceptionType.STATIC_PARAMETER);
}
/** Test processor with static annotated field. */
public void testProcessorWithStaticFieldParameter() {
checkException(ProcessorWithStaticFieldParameter.class,
EDriverExceptionType.STATIC_PARAMETER);
}
/**
* Test processor with a parameter object where the parameter interface is
* missing.
*/
public void testParameterObjectWithoutInterface() {
checkException(
ProcessorWithParameterObjectWithoutInterface.class,
EDriverExceptionType.PARAMETER_OBJECT_CLASS_NOT_IMPLEMENTS_INTERFACE);
}
/**
* Test processor with a parameter object that is not accessible (on field
* level).
*/
public void testNonPublicParameterObjectField() {
checkException(ProcessorWithNonPublicParameterObjectField.class,
EDriverExceptionType.NOT_PUBLIC_PARAMETER);
}
/**
* Test processor with a parameter object that is not accessible (on class
* level).
*/
public void testNonPublicParameterObjectClass() {
checkException(ProcessorWithNonPublicParameterObjectClass.class,
EDriverExceptionType.PARAMETER_OBJECT_CLASS_NOT_PUBLIC);
}
} |
3e09c88583d18d074258a30ca979b7926bf7fe21 | 434 | java | Java | src/mygame/generators/RandomPointWorldGenerator.java | SteveSmith16384/Blocky | 031653c7c2b07db8cc95c034ebb5e7ffa357c769 | [
"MIT"
] | 9 | 2019-01-15T21:11:42.000Z | 2022-03-30T12:17:21.000Z | src/mygame/generators/RandomPointWorldGenerator.java | toshnika/Blocky | 031653c7c2b07db8cc95c034ebb5e7ffa357c769 | [
"MIT"
] | null | null | null | src/mygame/generators/RandomPointWorldGenerator.java | toshnika/Blocky | 031653c7c2b07db8cc95c034ebb5e7ffa357c769 | [
"MIT"
] | 1 | 2019-12-12T01:19:06.000Z | 2019-12-12T01:19:06.000Z | 21.7 | 67 | 0.645161 | 4,131 | package mygame.generators;
import java.util.Random;
public class RandomPointWorldGenerator implements IWorldGenerator {
@Override
public float[][] createWorld(int width, int height) {
float[][] map = new float[width][height];
Random r = new Random();
for(int x = 0; x<map.length; x++) {
for(int y = 0; y < map[x].length; y++) {
map[x][y] = r.nextFloat(); //Random value between 0 and 1;
}
}
return map;
}
} |
3e09c956f6c004a6f7a785992b0fb1a6d43c2bb7 | 3,771 | java | Java | src/main/java/org/openapitools/client/model/EzsignfolderGetListV1ResponseMPayload.java | ezmaxinc/eZmax-SDK-android | 7e9ced5809702199cd8664aabfe2625aea81960c | [
"MIT"
] | null | null | null | src/main/java/org/openapitools/client/model/EzsignfolderGetListV1ResponseMPayload.java | ezmaxinc/eZmax-SDK-android | 7e9ced5809702199cd8664aabfe2625aea81960c | [
"MIT"
] | null | null | null | src/main/java/org/openapitools/client/model/EzsignfolderGetListV1ResponseMPayload.java | ezmaxinc/eZmax-SDK-android | 7e9ced5809702199cd8664aabfe2625aea81960c | [
"MIT"
] | null | null | null | 36.640777 | 197 | 0.732909 | 4,132 | /**
* eZmax API Definition (Full)
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.9
* Contact: dycjh@example.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.*;
import org.openapitools.client.model.CommonGetListV1ResponseMPayload;
import org.openapitools.client.model.EzsignfolderGetListV1ResponseMPayloadAllOf;
import org.openapitools.client.model.EzsignfolderListElement;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
/**
* Payload for GET /1/object/ezsignfolder/getList
**/
@ApiModel(description = "Payload for GET /1/object/ezsignfolder/getList")
public class EzsignfolderGetListV1ResponseMPayload {
@SerializedName("a_objEzsignfolder")
private List<EzsignfolderListElement> aObjEzsignfolder = null;
@SerializedName("iRowReturned")
private Integer iRowReturned = null;
@SerializedName("iRowFiltered")
private Integer iRowFiltered = null;
/**
**/
@ApiModelProperty(required = true, value = "")
public List<EzsignfolderListElement> getAObjEzsignfolder() {
return aObjEzsignfolder;
}
public void setAObjEzsignfolder(List<EzsignfolderListElement> aObjEzsignfolder) {
this.aObjEzsignfolder = aObjEzsignfolder;
}
/**
* The number of rows returned
**/
@ApiModelProperty(required = true, value = "The number of rows returned")
public Integer getIRowReturned() {
return iRowReturned;
}
public void setIRowReturned(Integer iRowReturned) {
this.iRowReturned = iRowReturned;
}
/**
* The number of rows matching your filters (if any) or the total number of rows
**/
@ApiModelProperty(required = true, value = "The number of rows matching your filters (if any) or the total number of rows")
public Integer getIRowFiltered() {
return iRowFiltered;
}
public void setIRowFiltered(Integer iRowFiltered) {
this.iRowFiltered = iRowFiltered;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EzsignfolderGetListV1ResponseMPayload ezsignfolderGetListV1ResponseMPayload = (EzsignfolderGetListV1ResponseMPayload) o;
return (this.aObjEzsignfolder == null ? ezsignfolderGetListV1ResponseMPayload.aObjEzsignfolder == null : this.aObjEzsignfolder.equals(ezsignfolderGetListV1ResponseMPayload.aObjEzsignfolder)) &&
(this.iRowReturned == null ? ezsignfolderGetListV1ResponseMPayload.iRowReturned == null : this.iRowReturned.equals(ezsignfolderGetListV1ResponseMPayload.iRowReturned)) &&
(this.iRowFiltered == null ? ezsignfolderGetListV1ResponseMPayload.iRowFiltered == null : this.iRowFiltered.equals(ezsignfolderGetListV1ResponseMPayload.iRowFiltered));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (this.aObjEzsignfolder == null ? 0: this.aObjEzsignfolder.hashCode());
result = 31 * result + (this.iRowReturned == null ? 0: this.iRowReturned.hashCode());
result = 31 * result + (this.iRowFiltered == null ? 0: this.iRowFiltered.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EzsignfolderGetListV1ResponseMPayload {\n");
sb.append(" aObjEzsignfolder: ").append(aObjEzsignfolder).append("\n");
sb.append(" iRowReturned: ").append(iRowReturned).append("\n");
sb.append(" iRowFiltered: ").append(iRowFiltered).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
3e09c9db9595a4e530be275e3cde69a17168b0d0 | 7,072 | java | Java | loopa/src/main/java/org/loopa/monitor/MonitorCreatorSocial.java | Martouta/loopa | 5e359aa8adc9e47d5ba53ef83172fdc488b1ba31 | [
"Apache-2.0"
] | null | null | null | loopa/src/main/java/org/loopa/monitor/MonitorCreatorSocial.java | Martouta/loopa | 5e359aa8adc9e47d5ba53ef83172fdc488b1ba31 | [
"Apache-2.0"
] | null | null | null | loopa/src/main/java/org/loopa/monitor/MonitorCreatorSocial.java | Martouta/loopa | 5e359aa8adc9e47d5ba53ef83172fdc488b1ba31 | [
"Apache-2.0"
] | null | null | null | 51.620438 | 162 | 0.793269 | 4,133 | package org.loopa.monitor;
import java.util.HashMap;
import java.util.Map;
import org.loopa.element.adaptationlogic.AdaptationLogic;
import org.loopa.element.adaptationlogic.IAdaptationLogic;
import org.loopa.element.adaptationlogic.enactor.AdaptationLogicEnactor;
import org.loopa.element.adaptationlogic.enactor.IAdaptationLogicEnactor;
import org.loopa.element.functionallogic.FunctionalLogic;
import org.loopa.element.functionallogic.IFunctionalLogic;
import org.loopa.element.functionallogic.enactor.IFunctionalLogicEnactor;
import org.loopa.element.functionallogic.enactor.monitor.IMonitorManager;
import org.loopa.element.functionallogic.enactor.monitor.MonitorManagerSocial;
import org.loopa.element.functionallogic.enactor.monitor.MonitorFunctionalLogicEnactor;
import org.loopa.element.knowledgemanager.IKnowledgeManager;
import org.loopa.element.knowledgemanager.KnowledgeManager;
import org.loopa.element.knowledgemanager.adaptiveknowledgemanager.AdaptiveKnowledgeManager;
import org.loopa.element.knowledgemanager.adaptiveknowledgemanager.IAdaptiveKnowledgeManager;
import org.loopa.element.logicselector.ILogicSelector;
import org.loopa.element.logicselector.LogicSelector;
import org.loopa.element.logicselector.messagedispatcher.ILogicMessageDispatcher;
import org.loopa.element.logicselector.messagedispatcher.LogicMessageDispatcher;
import org.loopa.element.messagecomposer.IMessageComposer;
import org.loopa.element.messagecomposer.MessageComposer;
import org.loopa.element.messagecomposer.dataformatter.DataFormatter;
import org.loopa.element.messagecomposer.dataformatter.IDataFormatter;
import org.loopa.element.messagecomposer.messagecreator.IMessageCreator;
import org.loopa.element.messagecomposer.messagecreator.MessageCreator;
import org.loopa.element.receiver.IReceiver;
import org.loopa.element.receiver.Receiver;
import org.loopa.element.receiver.messageprocessor.IMessageProcessor;
import org.loopa.element.receiver.messageprocessor.MessageProcessor;
import org.loopa.element.sender.ISender;
import org.loopa.element.sender.Sender;
import org.loopa.element.sender.messagesender.IMessageSender;
import org.loopa.element.sender.messagesender.MessageSenderSocial;
import org.loopa.generic.documents.IPolicy;
import org.loopa.generic.documents.Policy;
import org.loopa.generic.documents.managers.IPolicyManager;
import org.loopa.generic.documents.managers.PolicyManager;
import org.loopa.generic.element.component.ILoopAElementComponent;
import org.loopa.monitor.IMonitor;
import org.loopa.monitor.Monitor;
import org.loopa.comm.message.IMessage;
import org.loopa.comm.message.Message;
import org.loopa.externalservice.KafkaService;
public class MonitorCreatorSocial {
public static IMonitor create(String monitorID, KafkaService kafkaService, int monFreq) {
String ksID = kafkaService.getID();
IMonitor monitor = new Monitor(monitorID, createReceiver(monitorID), createLogicSelector(monitorID), createFunctionalLogic(monitorID, monFreq),
createAdaptationLogic(monitorID), createMessageComposer(monitorID, ksID), createSender(monitorID, ksID), createKnowledgeManager(monitorID));
monitor.addRecipient(ksID, kafkaService);
return monitor;
}
public static void startMonitoring(IMonitor monitor){
HashMap<String, String> hmBodyMessage = new HashMap();
hmBodyMessage.put("type", "getMonData");
IMessage m = new Message("Main", monitor.getReceiver().getComponentId(), 1, "request", hmBodyMessage);
monitor.getReceiver().doOperation(m);
}
private static IReceiver createReceiver(String monitorID){
HashMap hmpReceiver = new HashMap<String, String>();
hmpReceiver.put("1", "logicSelector" + monitorID);
IPolicy rP = new Policy("receiverPolicy" + monitorID, hmpReceiver);
IPolicyManager rPM = new PolicyManager(rP);
IMessageProcessor rMP = new MessageProcessor();
rP.addListerner(rMP);
return new Receiver("receiver" + monitorID, rPM, rMP);
}
private static ILogicSelector createLogicSelector(String monitorID){
HashMap hmpLogicSelector = new HashMap<String, String>();
hmpLogicSelector.put("1", "functionalLogic" + monitorID);
IPolicy lsP = new Policy("logicSelectorPolicy" + monitorID, hmpLogicSelector);
IPolicyManager lsPM = new PolicyManager(lsP);
ILogicMessageDispatcher lsMD = new LogicMessageDispatcher();
lsP.addListerner(lsMD);
return new LogicSelector("logicSelector" + monitorID, lsPM, lsMD);
}
private static IFunctionalLogic createFunctionalLogic(String monitorID, int monFreq) {
HashMap hmpFunctionalLogic = new HashMap<String, String>();
hmpFunctionalLogic.put("1", "messageComposer" + monitorID);
hmpFunctionalLogic.put("monFreq", Integer.toString(monFreq));
IPolicy flP = new Policy("functionalLogicPolicy" + monitorID, hmpFunctionalLogic);
IPolicyManager flPM = new PolicyManager(flP);
IMonitorManager mm = new MonitorManagerSocial();
IFunctionalLogicEnactor flE = new MonitorFunctionalLogicEnactor(mm);
flP.addListerner(flE);
return new FunctionalLogic("functionalLogic" + monitorID, flPM, flE);
}
private static IMessageComposer createMessageComposer(String monitorID, String kafkaServiceID) {
HashMap hmpMessageComposer = new HashMap<String, String>();
hmpMessageComposer.put("1", "sender" + monitorID);
hmpMessageComposer.put("getMonData", kafkaServiceID);
hmpMessageComposer.put("receivedMonData", kafkaServiceID);
IPolicy mcP = new Policy("messageComposerPolicy" + monitorID, hmpMessageComposer);
IPolicyManager mcPM = new PolicyManager(mcP);
IDataFormatter mcDF = new DataFormatter();
IMessageCreator mcMC = new MessageCreator();
mcP.addListerner(mcDF);
mcP.addListerner(mcMC);
return new MessageComposer("messageComposer" + monitorID, mcPM, mcDF, mcMC);
}
private static ISender createSender(String monitorID, String kafkaServiceID) {
HashMap hmpSender = new HashMap<String, String>();
hmpSender.put("1", kafkaServiceID);
IPolicy sP = new Policy("senderPolicy" + monitorID, hmpSender);
IPolicyManager sPM = new PolicyManager(sP);
IMessageSender sMS = new MessageSenderSocial();
sP.addListerner(sMS);
return new Sender("sender" + monitorID, sPM, sMS);
}
private static IAdaptationLogic createAdaptationLogic(String monitorID) { // (empty)
IPolicy alP = new Policy("adaptationLogicPolicy" + monitorID, new HashMap<String, String>());
IPolicyManager alPM = new PolicyManager(alP);
IAdaptationLogicEnactor alE = new AdaptationLogicEnactor();
alP.addListerner(alE);
return new AdaptationLogic("adaptationLogic" + monitorID, alPM, alE);
}
private static IKnowledgeManager createKnowledgeManager(String monitorID) { // (empty)
IPolicy kP = new Policy("knowledgeManagerPolicy" + monitorID, new HashMap<String, String>());
IPolicyManager kPM = new PolicyManager(kP);
IAdaptiveKnowledgeManager kAKM = new AdaptiveKnowledgeManager();
kP.addListerner(kAKM);
return new KnowledgeManager("knowledgeManager" + monitorID, kPM, kAKM);
}
}
|
3e09ca1b7b3be749a1034dc724947e5d2f175c18 | 1,267 | java | Java | pet-clinic-data/src/test/java/guru/springframework/sfgpetclinic/services/map/PetMapServiceTest.java | MihaiTudorP/SFG-Pet-clinic | 0605d4696bba817a7a255d808ae8e0eafe6ef818 | [
"Apache-2.0"
] | null | null | null | pet-clinic-data/src/test/java/guru/springframework/sfgpetclinic/services/map/PetMapServiceTest.java | MihaiTudorP/SFG-Pet-clinic | 0605d4696bba817a7a255d808ae8e0eafe6ef818 | [
"Apache-2.0"
] | 64 | 2020-11-28T13:20:53.000Z | 2021-01-09T11:19:27.000Z | pet-clinic-data/src/test/java/guru/springframework/sfgpetclinic/services/map/PetMapServiceTest.java | MihaiTudorP/SFG-Pet-clinic | 0605d4696bba817a7a255d808ae8e0eafe6ef818 | [
"Apache-2.0"
] | null | null | null | 26.957447 | 136 | 0.664562 | 4,134 | package guru.springframework.sfgpetclinic.services.map;
import guru.springframework.sfgpetclinic.model.Pet;
import guru.springframework.sfgpetclinic.model.PetType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PetMapServiceTest {
PetMapService petMapService;
@BeforeEach
void setUp() {
petMapService = new PetMapService();
petMapService.save(Pet.builder().name("Duke").petType(PetType.builder().name("Dog").build()).build());
}
@Test
void findAll() {
assertEquals(1, petMapService.findAll().size());
}
@Test
void findById() {
assertEquals("Duke", petMapService.findById(1L).getName());
}
@Test
void save() {
assertEquals(2L, petMapService.save(Pet.builder().name("Lucy").petType(PetType.builder().name("Cat").build()).build()).getId());
assertEquals(2, petMapService.findAll().size());
}
@Test
void delete() {
petMapService.delete(petMapService.findById(1L));
assertTrue(petMapService.findAll().isEmpty());
}
@Test
void deleteById() {
petMapService.deleteById(1L);
assertTrue(petMapService.findAll().isEmpty());
}
} |
3e09cacbbd93c1f37dd237e86f0b2925fcc266b5 | 1,612 | java | Java | src/main/java/com/github/vvorks/builder/server/extender/QueryExtender.java | vvorks/builder | 17e0bf3455ddcf07fe4f294662b4eac3ea3bbe7a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/vvorks/builder/server/extender/QueryExtender.java | vvorks/builder | 17e0bf3455ddcf07fe4f294662b4eac3ea3bbe7a | [
"Apache-2.0"
] | 21 | 2021-12-10T07:31:15.000Z | 2022-03-19T14:33:39.000Z | src/main/java/com/github/vvorks/builder/server/extender/QueryExtender.java | vvorks/builder | 17e0bf3455ddcf07fe4f294662b4eac3ea3bbe7a | [
"Apache-2.0"
] | null | null | null | 29.309091 | 104 | 0.7866 | 4,135 | package com.github.vvorks.builder.server.extender;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.github.vvorks.builder.common.lang.Strings;
import com.github.vvorks.builder.server.domain.ClassContent;
import com.github.vvorks.builder.server.domain.FieldContent;
import com.github.vvorks.builder.server.domain.QueryContent;
import com.github.vvorks.builder.server.grammar.ExprParser;
import com.github.vvorks.builder.server.mapper.QueryMapper;
@Component
public class QueryExtender {
private SqlWriter sqlWriter = SqlWriter.get();
@Autowired
private QueryMapper queryMapper;
@Autowired
private ClassExtender classExtender;
public String getTitleOrName(QueryContent q) {
if (!Strings.isEmpty(q.getTitle())) {
return q.getTitle();
} else {
return q.getQueryName();
}
}
public String getUpperName(QueryContent q) {
return Strings.toFirstUpper(q.getQueryName());
}
public List<ClassExtender.JoinInfo> getJoins(QueryContent q) {
return classExtender.getJoins(queryMapper.getOwner(q));
}
public String getSqlExpr(QueryContent q) {
ClassContent cls = queryMapper.getOwner(q);
ClassExtender.ExprInfo info = classExtender.referExpr(cls, q.getFilter(), ExprParser.CODE_TYPE_WHERE);
return info.getExpr().accept(sqlWriter, null);
}
public List<FieldContent> getArguments(QueryContent q) {
ClassContent cls = queryMapper.getOwner(q);
ClassExtender.ExprInfo info = classExtender.referExpr(cls, q.getFilter(), ExprParser.CODE_TYPE_WHERE);
return info.getArguments();
}
}
|
3e09cad639e47e9be46efe30ad583d76a976bec8 | 2,816 | java | Java | Export_and_Visualization_Schemas_Versions_from_JSON_Data/src/data_processing/JsonProcessing.java | SiozosThomas/Diploma | 979ffd217c295b00cb0b3f39459848171b2fec2f | [
"MIT"
] | 1 | 2020-07-18T19:40:28.000Z | 2020-07-18T19:40:28.000Z | Export_and_Visualization_Schemas_Versions_from_JSON_Data/src/data_processing/JsonProcessing.java | SiozosThomas/Diploma | 979ffd217c295b00cb0b3f39459848171b2fec2f | [
"MIT"
] | 2 | 2020-04-23T21:04:48.000Z | 2020-05-21T20:36:10.000Z | Export_and_Visualization_Schemas_Versions_from_JSON_Data/src/data_processing/JsonProcessing.java | SiozosThomas/Export-and-Visualization-Schema-s-Versions-from-JSON-Data | 979ffd217c295b00cb0b3f39459848171b2fec2f | [
"MIT"
] | null | null | null | 27.881188 | 67 | 0.705611 | 4,136 | package data_processing;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonProcessing {
private SchemaHistory schemaHistory;
private VersionComparison versionComparison;
private ObjectNodeProcessing objectNodeProcessing;
//private JsonOutputFile jsonOutputFile;
private int id;
public JsonProcessing() {
schemaHistory = new SchemaHistory();
versionComparison = new VersionComparison();
id = 1;
}
public void processingJsonFile(String file) {
JsonFactory factory = new JsonFactory();
JsonParser parser = null;
boolean json_array = true;
try {
parser = factory.createParser(new File(file));
} catch (IOException e) {
System.out.println("IO Exception in JsonParser...");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("Can't open this file...");
e.printStackTrace();
}
if (parser != null) {
while(hasJsonObject(parser)) {
json_array = false;
process(parser);
}
if (json_array == true) {
JsonToken token = null;
while(true) {
try {
token = parser.nextToken();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!JsonToken.START_OBJECT.equals(token)) break;
if (token == null) break;
process(parser);
}
}
}
System.out.println("Total json objects : " + (id - 1));
schemaHistory.printVersionsNumber();
if (schemaHistory.createOutputFiles()) {
System.out.println("All Version Files Created Successfully...");
} else {
System.out.println("An error occurred while "
+ "creating version files...");
}
}
private void process(JsonParser parser) {
parser.setCodec(new ObjectMapper());
JsonNode jsonNode = null;
try {
jsonNode = parser.readValueAsTree();
} catch (IOException e) {
System.out.println("IO Exception in JsonNode...");
e.printStackTrace();
}
objectNodeProcessing = new ObjectNodeProcessing();
objectNodeProcessing.setObjectNode(jsonNode);
objectNodeProcessing.setId(id);
ObjectNode currentObject = objectNodeProcessing
.processObject("root");
versionComparison.compareVersions(schemaHistory, currentObject);
id++;
}
private boolean hasJsonObject(JsonParser parser) {
try {
try {
if (parser.nextToken() == JsonToken.START_OBJECT) return true;
} catch (JsonParseException e) {
System.out.println("Not valid Json Format...");
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
|
3e09cb91a505c0c5cc6b3fc421f4be3f09d05f38 | 5,274 | java | Java | src/main/java/XmlInputFormat.java | zychn/wikimedia | 0b5c49f7f3a2f57c2c30de3c2cc2494acb013ea5 | [
"Apache-2.0"
] | null | null | null | src/main/java/XmlInputFormat.java | zychn/wikimedia | 0b5c49f7f3a2f57c2c30de3c2cc2494acb013ea5 | [
"Apache-2.0"
] | null | null | null | src/main/java/XmlInputFormat.java | zychn/wikimedia | 0b5c49f7f3a2f57c2c30de3c2cc2494acb013ea5 | [
"Apache-2.0"
] | null | null | null | 35.395973 | 125 | 0.557452 | 4,137 | package main.java;
import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
public class XmlInputFormat extends TextInputFormat {
// 1. create record reader
@Override
public RecordReader<LongWritable, Text> createRecordReader(InputSplit inputSplit, TaskAttemptContext context) {
try {
return new XmlRecordReader(inputSplit, context.getConfiguration());
} catch (IOException e) {
return null;
}
}
// 2. is splitable?
@Override
protected boolean isSplitable(JobContext context, Path file) {
return super.isSplitable(context, file);
}
// 3. record reader
public class XmlRecordReader extends RecordReader<LongWritable, Text> {
private long start, end;
private FSDataInputStream fsin;
private DataOutputBuffer buffer = new DataOutputBuffer();
private byte[] startTag, endTag;
private LongWritable currentKey;
private Text currentValue;
public static final String START_TAG = "xmlinput.start";
public static final String END_TAG = "xmlinput.end";
public XmlRecordReader() {}
public XmlRecordReader(InputSplit inputSplit, Configuration context) throws IOException {
// start/end tag
startTag = context.get(START_TAG).getBytes("UTF-8");
endTag = context.get(END_TAG).getBytes("UTF-8");
// the start and end of the split
FileSplit fileSplit = (FileSplit) inputSplit;
start = fileSplit.getStart();
end = start + fileSplit.getLength();
Path file = fileSplit.getPath();
// input stream
FileSystem fs = file.getFileSystem(context);
fsin = fs.open(fileSplit.getPath());
// start
fsin.seek(start);
}
// close file inpute stream
@Override
public void close() throws IOException {
fsin.close();
}
@Override
public LongWritable getCurrentKey() throws IOException, InterruptedException {
return currentKey;
}
@Override
public Text getCurrentValue() throws IOException, InterruptedException {
return currentValue;
}
// progress
@Override
public float getProgress() throws IOException, InterruptedException {
return fsin.getPos() - start / (float) end - start;
}
@Override
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException {}
// new key-value
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
currentKey = new LongWritable();
currentValue = new Text();
return next(currentKey, currentValue);
}
private boolean next(LongWritable key, Text value) throws IOException {
if( fsin.getPos() < end && readUntilMatch(startTag, false)) {
// start tag found!
// write start tag into buffer
buffer.write(startTag);
try {
// try to match end tag, while writing into buffer
if(readUntilMatch(endTag, true)) {
// end tag found!
// the relative position -> key
// xml segment in buffer -> value
key.set(fsin.getPos() - buffer.getLength());
value.set(buffer.getData(), 0, buffer.getLength());
return true;
}
} finally {
buffer.reset();
}
}
return false;
}
// try to match start/end tag
private boolean readUntilMatch(byte[] tag, boolean isWrite) throws IOException {
int i = 0;
while(true) {
// read 1 byte
int b = fsin.read();
if( b == -1) {
return false;
}
// write bytes while trying to match
if(isWrite) {
buffer.write(b);
}
// match start/end tag
if(b == tag[i]) {
i ++;
if( i >= tag.length) {
return true;
}
} else {
i = 0;
}
// match?
if (!isWrite && i == 0 && fsin.getPos() >= end) {
return false;
}
}
}
}
} |
3e09cbb6a7a30a99019ff302d9a355f9c738eec4 | 1,058 | java | Java | app/src/main/java/com/gautam/medicinetime/medicine/MedicineContract.java | battleplayer02/medicine | cef206f82c63d8d76650bf3f596e39b86a52be9d | [
"Apache-2.0"
] | 1 | 2019-04-03T11:38:44.000Z | 2019-04-03T11:38:44.000Z | app/src/main/java/com/gautam/medicinetime/medicine/MedicineContract.java | battleplayer02/medicine | cef206f82c63d8d76650bf3f596e39b86a52be9d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/gautam/medicinetime/medicine/MedicineContract.java | battleplayer02/medicine | cef206f82c63d8d76650bf3f596e39b86a52be9d | [
"Apache-2.0"
] | null | null | null | 19.592593 | 69 | 0.706049 | 4,138 | package com.gautam.medicinetime.medicine;
import android.support.annotation.NonNull;
import com.gautam.medicinetime.BasePresenter;
import com.gautam.medicinetime.BaseView;
import com.gautam.medicinetime.data.source.MedicineAlarm;
import java.util.Date;
import java.util.List;
/**
* Created by gautam on 13/07/17.
*/
public interface MedicineContract {
interface View extends BaseView<Presenter>{
void showLoadingIndicator(boolean active);
void showMedicineList(List<MedicineAlarm> medicineAlarmList);
void showAddMedicine();
void showMedicineDetails(long medId, String medName);
void showLoadingMedicineError();
void showNoMedicine();
void showSuccessfullySavedMessage();
boolean isActive();
}
interface Presenter extends BasePresenter{
void onStart(int day);
void reload(int day);
void result(int requestCode, int resultCode);
void loadMedicinesByDay(int day, boolean showIndicator);
void addNewMedicine();
}
}
|
3e09cbd99ccb008ecdbc5a6c30b803d673bfb41a | 1,496 | java | Java | src/main/java/se/kth/iv1201/grupp13/recruiterapplication/repository/ApplicationRepository.java | anga13/recruiter-application | b05ae475429313306555cab2d59a9c673a4178e9 | [
"MIT"
] | null | null | null | src/main/java/se/kth/iv1201/grupp13/recruiterapplication/repository/ApplicationRepository.java | anga13/recruiter-application | b05ae475429313306555cab2d59a9c673a4178e9 | [
"MIT"
] | 3 | 2019-02-07T10:38:01.000Z | 2019-02-27T15:12:33.000Z | src/main/java/se/kth/iv1201/grupp13/recruiterapplication/repository/ApplicationRepository.java | anga13/recruiter-application | b05ae475429313306555cab2d59a9c673a4178e9 | [
"MIT"
] | 1 | 2019-03-05T10:58:19.000Z | 2019-03-05T10:58:19.000Z | 35.619048 | 140 | 0.772059 | 4,139 | package se.kth.iv1201.grupp13.recruiterapplication.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import se.kth.iv1201.grupp13.recruiterapplication.domain.User;
import se.kth.iv1201.grupp13.recruiterapplication.domain.Application;
import se.kth.iv1201.grupp13.recruiterapplication.domain.ApplicationDTO;
/**
* Contains all database access concerning users.
*/
@Repository
@Transactional(propagation = Propagation.MANDATORY) // Support current transaction, throw an exception if there is no transaction currently.
public interface ApplicationRepository extends JpaRepository<Application, Long> {
/**
* Returns the applications with the specified users.
*
* @param uers The users to search for.
* @return A list containing all applications with the specified users.
*/
List<Application> findByUserIn(List<User> users);
/**
* Returns the applications with the specified application date.
*
* @param date The application date to search for.
* @return A list containing all applications with the specified application date.
*/
List<Application> findByApplicationDate(Date date);
Application save(Application application);
Application findByUser(User user);
}
|
3e09cbf653d26a25f46d50f7f339708a6afd1bdd | 12,542 | java | Java | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/protocol/preparator/GOSTClientKeyExchangePreparator.java | woniuxia/TLS-Attacker | 09dd837deb49f79158c99177c2f1ec6b7dcbc106 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-02-11T01:13:15.000Z | 2021-02-11T01:13:15.000Z | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/protocol/preparator/GOSTClientKeyExchangePreparator.java | woniuxia/TLS-Attacker | 09dd837deb49f79158c99177c2f1ec6b7dcbc106 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/protocol/preparator/GOSTClientKeyExchangePreparator.java | woniuxia/TLS-Attacker | 09dd837deb49f79158c99177c2f1ec6b7dcbc106 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 46.798507 | 121 | 0.692952 | 4,140 | /**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2020 Ruhr University Bochum, Paderborn University,
* and Hackmanit GmbH
*
* Licensed under Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package de.rub.nds.tlsattacker.core.protocol.preparator;
import de.rub.nds.modifiablevariable.util.ArrayConverter;
import de.rub.nds.tlsattacker.core.constants.AlgorithmResolver;
import de.rub.nds.tlsattacker.core.constants.DigestAlgorithm;
import de.rub.nds.tlsattacker.core.crypto.ec.CurveFactory;
import de.rub.nds.tlsattacker.core.crypto.ec.EllipticCurve;
import de.rub.nds.tlsattacker.core.crypto.ec.Point;
import de.rub.nds.tlsattacker.core.crypto.ec.PointFormatter;
import de.rub.nds.tlsattacker.core.crypto.gost.GOST28147WrapEngine;
import de.rub.nds.tlsattacker.core.crypto.gost.TLSGostKeyTransportBlob;
import de.rub.nds.tlsattacker.core.exceptions.WorkflowExecutionException;
import de.rub.nds.tlsattacker.core.protocol.message.GOSTClientKeyExchangeMessage;
import de.rub.nds.tlsattacker.core.util.GOSTUtils;
import de.rub.nds.tlsattacker.core.workflow.chooser.Chooser;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
import org.bouncycastle.asn1.cryptopro.Gost2814789EncryptedKey;
import org.bouncycastle.asn1.cryptopro.GostR3410KeyTransport;
import org.bouncycastle.asn1.cryptopro.GostR3410TransportParameters;
import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers;
import org.bouncycastle.asn1.util.ASN1Dump;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.engines.GOST28147Engine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithSBox;
import org.bouncycastle.crypto.params.ParametersWithUKM;
public abstract class GOSTClientKeyExchangePreparator extends ClientKeyExchangePreparator<GOSTClientKeyExchangeMessage> {
private final static Logger LOGGER = LogManager.getLogger();
private static Map<ASN1ObjectIdentifier, String> oidMappings = new HashMap<>();
static {
oidMappings.put(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_TestParamSet, "E-TEST");
oidMappings.put(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_A_ParamSet, "E-A");
oidMappings.put(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_B_ParamSet, "E-B");
oidMappings.put(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_C_ParamSet, "E-C");
oidMappings.put(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_D_ParamSet, "E-D");
oidMappings.put(RosstandartObjectIdentifiers.id_tc26_gost_28147_param_Z, "Param-Z");
}
private final GOSTClientKeyExchangeMessage msg;
public GOSTClientKeyExchangePreparator(Chooser chooser, GOSTClientKeyExchangeMessage msg) {
super(chooser, msg);
this.msg = msg;
}
@Override
protected void prepareHandshakeMessageContents() {
prepareAfterParse(true);
}
@Override
public void prepareAfterParse(boolean clientMode) {
try {
LOGGER.debug("Preparing GOST EC VKO. Client mode: " + clientMode);
msg.prepareComputations();
prepareClientServerRandom();
prepareUkm();
if (clientMode) {
preparePms();
msg.getComputations().setPrivateKey(chooser.getClientEcPrivateKey());
prepareEphemeralKey();
prepareKek(msg.getComputations().getPrivateKey().getValue(), chooser.getServerEcPublicKey());
prepareEncryptionParams();
prepareCek();
prepareKeyBlob();
} else {
TLSGostKeyTransportBlob transportBlob = TLSGostKeyTransportBlob.getInstance(msg.getKeyTransportBlob()
.getValue());
LOGGER.debug("Received GOST key blob: " + ASN1Dump.dumpAsString(transportBlob, true));
GostR3410KeyTransport keyBlob = transportBlob.getKeyBlob();
if (!Arrays
.equals(keyBlob.getTransportParameters().getUkm(), msg.getComputations().getUkm().getValue())) {
LOGGER.warn("Client UKM != Server UKM");
}
SubjectPublicKeyInfo ephemeralKey = keyBlob.getTransportParameters().getEphemeralPublicKey();
Point publicKey = chooser.getClientEcPublicKey();
prepareKek(chooser.getServerEcPrivateKey(), publicKey);
byte[] wrapped = ArrayConverter.concatenate(keyBlob.getSessionEncryptedKey().getEncryptedKey(), keyBlob
.getSessionEncryptedKey().getMacKey());
String sBoxName = oidMappings.get(keyBlob.getTransportParameters().getEncryptionParamSet());
byte[] pms = wrap(false, wrapped, sBoxName);
msg.getComputations().setPremasterSecret(pms);
}
} catch (GeneralSecurityException | IOException e) {
throw new WorkflowExecutionException("Could not prepare the key agreement!", e);
}
}
private void prepareClientServerRandom() {
byte[] random = ArrayConverter.concatenate(chooser.getClientRandom(), chooser.getServerRandom());
msg.getComputations().setClientServerRandom(random);
LOGGER.debug("ClientServerRandom: "
+ ArrayConverter.bytesToHexString(msg.getComputations().getClientServerRandom().getValue()));
}
private void prepareUkm() throws NoSuchAlgorithmException {
DigestAlgorithm digestAlgorithm = AlgorithmResolver.getDigestAlgorithm(chooser.getSelectedProtocolVersion(),
chooser.getSelectedCipherSuite());
MessageDigest digest = MessageDigest.getInstance(digestAlgorithm.getJavaName());
byte[] hash = digest.digest(msg.getComputations().getClientServerRandom().getValue());
byte[] ukm = new byte[8];
System.arraycopy(hash, 0, ukm, 0, ukm.length);
msg.getComputations().setUkm(ukm);
LOGGER.debug("UKM: " + ArrayConverter.bytesToHexString(msg.getComputations().getUkm()));
}
private void prepareKek(BigInteger privateKey, Point publicKey) throws GeneralSecurityException {
EllipticCurve curve = CurveFactory.getCurve(chooser.getSelectedGostCurve());
Point sharedPoint = curve.mult(privateKey, publicKey);
byte[] pms = PointFormatter.toRawFormat(sharedPoint);
Digest digest = getKeyAgreementDigestAlgorithm();
digest.update(pms, 0, pms.length);
byte[] kek = new byte[digest.getDigestSize()];
digest.doFinal(kek, 0);
msg.getComputations().setKeyEncryptionKey(kek);
LOGGER.debug("KEK: " + ArrayConverter.bytesToHexString(msg.getComputations().getKeyEncryptionKey()));
}
private void preparePms() {
byte[] pms = chooser.getContext().getPreMasterSecret();
if (pms != null) {
LOGGER.debug("Using preset PreMasterSecret from context.");
} else {
LOGGER.debug("Generating random PreMasterSecret.");
pms = new byte[32];
chooser.getContext().getRandom().nextBytes(pms);
}
msg.getComputations().setPremasterSecret(pms);
}
private void prepareEphemeralKey() {
EllipticCurve curve = CurveFactory.getCurve(chooser.getSelectedGostCurve());
LOGGER.debug("Using key from context.");
msg.getComputations().setPrivateKey(chooser.getClientEcPrivateKey());
Point publicKey = curve.mult(msg.getComputations().getPrivateKey().getValue(), curve.getBasePoint());
msg.getComputations().setClientPublicKey(publicKey);
}
private byte[] wrap(boolean wrap, byte[] bytes, String sBoxName) {
byte[] sBox = GOST28147Engine.getSBox(sBoxName);
KeyParameter keySpec = new KeyParameter(msg.getComputations().getKeyEncryptionKey().getValue());
ParametersWithSBox withSBox = new ParametersWithSBox(keySpec, sBox);
ParametersWithUKM withIV = new ParametersWithUKM(withSBox, msg.getComputations().getUkm().getValue());
GOST28147WrapEngine cipher = new GOST28147WrapEngine();
cipher.init(wrap, withIV);
byte[] result;
if (wrap) {
LOGGER.debug("Wrapping GOST PMS: " + ArrayConverter.bytesToHexString(bytes));
result = cipher.wrap(bytes, 0, bytes.length);
} else {
LOGGER.debug("Unwrapping GOST PMS: " + ArrayConverter.bytesToHexString(bytes));
result = cipher.unwrap(bytes, 0, bytes.length);
}
LOGGER.debug("Wrap result: " + ArrayConverter.bytesToHexString(result));
return result;
}
private void prepareCek() {
ASN1ObjectIdentifier param = new ASN1ObjectIdentifier(msg.getComputations().getEncryptionParamSet().getValue());
String sBoxName = oidMappings.get(param);
byte[] wrapped = wrap(true, msg.getComputations().getPremasterSecret().getValue(), sBoxName);
byte[] cek = new byte[32];
try {
if (wrapped.length <= cek.length) {
System.arraycopy(wrapped, 0, cek, 0, cek.length);
} else {
// This case is for fuzzing purposes only.
System.arraycopy(wrapped, 0, cek, 0, wrapped.length - 1);
}
} catch (ArrayIndexOutOfBoundsException E) {
LOGGER.warn("Something going wrong here...");
}
msg.getComputations().setEncryptedKey(cek);
byte[] mac = new byte[wrapped.length - cek.length];
System.arraycopy(wrapped, cek.length, mac, 0, mac.length);
msg.getComputations().setMacKey(mac);
}
private void prepareEncryptionParams() {
msg.getComputations().setEncryptionParamSet(getEncryptionParameters());
}
private void prepareKeyBlob() throws IOException {
try {
Point ecPoint = Point.createPoint(msg.getComputations().getClientPublicKeyX().getValue(), msg
.getComputations().getClientPublicKeyY().getValue(), chooser.getSelectedGostCurve());
SubjectPublicKeyInfo ephemeralKey = SubjectPublicKeyInfo.getInstance(GOSTUtils.generatePublicKey(
chooser.getSelectedGostCurve(), ecPoint).getEncoded());
Gost2814789EncryptedKey encryptedKey = new Gost2814789EncryptedKey(msg.getComputations().getEncryptedKey()
.getValue(), getMaskKey(), msg.getComputations().getMacKey().getValue());
ASN1ObjectIdentifier paramSet = new ASN1ObjectIdentifier(msg.getComputations().getEncryptionParamSet()
.getValue());
GostR3410TransportParameters params = new GostR3410TransportParameters(paramSet, ephemeralKey, msg
.getComputations().getUkm().getValue());
GostR3410KeyTransport transport = new GostR3410KeyTransport(encryptedKey, params);
DERSequence proxyKeyBlobs = (DERSequence) DERSequence.getInstance(getProxyKeyBlobs());
TLSGostKeyTransportBlob blob = new TLSGostKeyTransportBlob(transport, proxyKeyBlobs);
msg.setKeyTransportBlob(blob.getEncoded());
LOGGER.debug("GOST key blob: " + ASN1Dump.dumpAsString(blob, true));
} catch (Exception E) {
msg.setKeyTransportBlob(new byte[0]);
LOGGER.warn("Could not compute correct GOST key blob: using byte[0]");
}
}
private byte[] getProxyKeyBlobs() {
if (msg.getComputations().getProxyKeyBlobs() != null) {
return msg.getComputations().getProxyKeyBlobs().getValue();
} else {
return null;
}
}
private byte[] getMaskKey() {
if (msg.getComputations().getMaskKey() != null) {
return msg.getComputations().getMaskKey().getValue();
} else {
return null;
}
}
protected abstract ASN1ObjectIdentifier getEncryptionParameters();
protected abstract Digest getKeyAgreementDigestAlgorithm();
protected abstract String getKeyPairGeneratorAlgorithm();
}
|
3e09cc7b920939ca84df6cc178239f90c7047b66 | 296 | java | Java | podium-common/src/main/java/nl/thehyve/podium/common/enumeration/Classifier.java | thehyve/podium | 158e222bd03d23a4696c94b1e45aa1bfcead8038 | [
"Apache-2.0"
] | 13 | 2017-02-23T07:33:44.000Z | 2022-02-17T12:01:08.000Z | podium-common/src/main/java/nl/thehyve/podium/common/enumeration/Classifier.java | thehyve/podium | 158e222bd03d23a4696c94b1e45aa1bfcead8038 | [
"Apache-2.0"
] | 119 | 2017-02-20T17:13:44.000Z | 2022-02-26T12:23:37.000Z | podium-common/src/main/java/nl/thehyve/podium/common/enumeration/Classifier.java | thehyve/podium | 158e222bd03d23a4696c94b1e45aa1bfcead8038 | [
"Apache-2.0"
] | 5 | 2017-08-21T03:47:54.000Z | 2019-05-24T23:24:06.000Z | 19.733333 | 93 | 0.652027 | 4,141 | package nl.thehyve.podium.common.enumeration;
/**
* Indicates a type as a status or outcome type, used as classifier, which should be an enum.
*/
public interface Classifier {
/**
* The name of the enum value.
* @return the name of the enum value.
*/
String name();
}
|
3e09ccb34d52fd92c56f36bd3c3fd260833bc3f2 | 768 | java | Java | prosolo-main/src/main/java/org/prosolo/services/common/data/SelectableData.java | prosolotechnologies/prosolo | fb2058577002f9dce362375afb2ca72bb51deef7 | [
"BSD-3-Clause"
] | null | null | null | prosolo-main/src/main/java/org/prosolo/services/common/data/SelectableData.java | prosolotechnologies/prosolo | fb2058577002f9dce362375afb2ca72bb51deef7 | [
"BSD-3-Clause"
] | 11 | 2020-02-08T21:54:11.000Z | 2021-12-09T22:02:13.000Z | prosolo-main/src/main/java/org/prosolo/services/common/data/SelectableData.java | prosolotechnologies/prosolo | fb2058577002f9dce362375afb2ca72bb51deef7 | [
"BSD-3-Clause"
] | null | null | null | 20.756757 | 98 | 0.643229 | 4,142 | package org.prosolo.services.common.data;
/**
* Represents selectable data with arbitrary object that represents data and a flag that indicates
* whether this piece of data (object) is selected (enabled).
*
* @author stefanvuckovic
* @date 2018-11-16
* @since 1.2.0
*/
public class SelectableData<T> {
private final T data;
private boolean selected;
public SelectableData(T data, boolean selected) {
this.data = data;
this.selected = selected;
}
public SelectableData(T data) {
this(data, false);
}
public T getData() {
return data;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
|
3e09cd0dbdb3fa3d76b5f379c76b8e5548bb2274 | 8,347 | java | Java | actor-apps/app-android/src/main/java/im/actor/messenger/app/Intents.java | liruqi/actor-platform-v0.9 | 29724f0028f84b642e935b6381d5effe556b4a24 | [
"MIT"
] | 1 | 2015-10-10T22:49:13.000Z | 2015-10-10T22:49:13.000Z | actor-apps/app-android/src/main/java/im/actor/messenger/app/Intents.java | liruqi/actor-platform-v0.9 | 29724f0028f84b642e935b6381d5effe556b4a24 | [
"MIT"
] | null | null | null | actor-apps/app-android/src/main/java/im/actor/messenger/app/Intents.java | liruqi/actor-platform-v0.9 | 29724f0028f84b642e935b6381d5effe556b4a24 | [
"MIT"
] | null | null | null | 37.097778 | 113 | 0.693662 | 4,143 | package im.actor.messenger.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileOutputStream;
import im.actor.core.entity.FileReference;
import im.actor.core.entity.Peer;
import im.actor.core.utils.IOUtils;
import im.actor.messenger.app.activity.AddContactActivity;
import im.actor.messenger.app.activity.TakePhotoActivity;
import im.actor.messenger.app.fragment.chat.ChatActivity;
import im.actor.messenger.app.fragment.group.GroupInfoActivity;
import im.actor.messenger.app.fragment.group.IntegrationTokenActivity;
import im.actor.messenger.app.fragment.group.InviteLinkActivity;
import im.actor.messenger.app.fragment.preview.PictureActivity;
import im.actor.messenger.app.fragment.profile.ProfileActivity;
import im.actor.messenger.app.fragment.settings.EditAboutActivity;
import im.actor.messenger.app.fragment.settings.EditNameActivity;
/**
* Created by ex3ndr on 07.10.14.
*/
public class Intents {
public static final String EXTRA_UID = "uid";
public static final String EXTRA_GROUP_ID = "group_id";
public static final String EXTRA_CHAT_PEER = "chat_peer";
public static final String EXTRA_CHAT_COMPOSE = "compose";
public static final String EXTRA_EDIT_TYPE = "edit_type";
public static final String EXTRA_EDIT_ID = "edit_id";
public static final int RESULT_DELETE = 0;
public static final int RESULT_IMAGE = 1;
public static final String EXTRA_ALLOW_DELETE = "allow_delete";
public static final String EXTRA_RESULT = "result";
public static final String EXTRA_IMAGE = "image";
public static Intent pickAvatar(boolean isAllowDelete, Context context) {
return new Intent(context, TakePhotoActivity.class)
.putExtra(EXTRA_ALLOW_DELETE, isAllowDelete);
}
public static Intent editMyName(Context context) {
return new Intent(context, EditNameActivity.class)
.putExtra(EXTRA_EDIT_TYPE, EditNameActivity.TYPE_ME)
.putExtra(EXTRA_EDIT_ID, 0);
}
public static Intent editUserName(int uid, Context context) {
return new Intent(context, EditNameActivity.class)
.putExtra(EXTRA_EDIT_TYPE, EditNameActivity.TYPE_USER)
.putExtra(EXTRA_EDIT_ID, uid);
}
public static Intent editGroupTitle(int groupId, Context context) {
return new Intent(context, EditNameActivity.class)
.putExtra(EXTRA_EDIT_TYPE, EditNameActivity.TYPE_GROUP)
.putExtra(EXTRA_EDIT_ID, groupId);
}
public static Intent editGroupTheme(int groupId, Context context) {
return new Intent(context, EditNameActivity.class)
.putExtra(EXTRA_EDIT_TYPE, EditNameActivity.TYPE_GROUP_THEME)
.putExtra(EXTRA_EDIT_ID, groupId);
}
public static Intent editUserAbout(Context context) {
return new Intent(context, EditAboutActivity.class)
.putExtra(EXTRA_EDIT_TYPE, EditAboutActivity.TYPE_ME)
.putExtra(EXTRA_EDIT_ID, 0);
}
public static Intent editGroupAbout(int groupId, Context context) {
return new Intent(context, EditAboutActivity.class)
.putExtra(EXTRA_EDIT_TYPE, EditAboutActivity.TYPE_GROUP)
.putExtra(EXTRA_EDIT_ID, groupId);
}
public static Intent openGroup(int chatId, Context context) {
Intent res = new Intent(context, GroupInfoActivity.class);
res.putExtra(EXTRA_GROUP_ID, chatId);
return res;
}
public static Intent inviteLink(int chatId, Context context) {
Intent res = new Intent(context, InviteLinkActivity.class);
res.putExtra(EXTRA_GROUP_ID, chatId);
return res;
}
public static Intent integrationToken(int chatId, Context context) {
Intent res = new Intent(context, IntegrationTokenActivity.class);
res.putExtra(EXTRA_GROUP_ID, chatId);
return res;
}
public static Intent openDialog(Peer peer, boolean compose, Context context) {
final Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra(EXTRA_CHAT_PEER, peer.getUnuqueId());
intent.putExtra(EXTRA_CHAT_COMPOSE, compose);
return intent;
}
public static Intent openPrivateDialog(int uid, boolean compose, Context context) {
return openDialog(Peer.user(uid), compose, context);
}
public static Intent openGroupDialog(int chatId, boolean compose, Context context) {
return openDialog(Peer.group(chatId), compose, context);
}
public static Intent openProfile(int uid, Context context) {
return new Intent(context, ProfileActivity.class).putExtra(EXTRA_UID, uid);
}
public static Intent call(long phone) {
return call(phone + "");
}
public static Intent call(String phone) {
return new Intent(Intent.ACTION_DIAL).setData(Uri.parse("tel:+" + phone));
}
public static Intent findContacts(Context context) {
return new Intent(context, AddContactActivity.class);
}
// External intents
private static Uri getAvatarUri(FileReference location) {
return Uri.parse("content://im.actor.avatar/" + location.getFileId());
}
public static Intent openDoc(String fileName, String downloadFileName) {
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(IOUtils.getFileExtension(fileName));
if (mimeType == null) {
mimeType = "*/*";
}
return new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.fromFile(new File(downloadFileName)), mimeType);
}
public static Intent shareDoc(String fileName, String downloadFileName) {
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(IOUtils.getFileExtension(fileName));
if (mimeType == null) {
mimeType = "*/*";
}
return new Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(downloadFileName)))
.setType(mimeType);
}
public static Intent shareAvatar(FileReference location) {
return new Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_STREAM, getAvatarUri(location))
.setType("image/jpeg");
}
public static Intent openAvatar(FileReference location) {
return new Intent(Intent.ACTION_VIEW)
.setDataAndType(getAvatarUri(location), "image/jpeg");
}
public static Intent setAsAvatar(FileReference location) {
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(getAvatarUri(location), "image/jpg");
intent.putExtra("mimeType", "image/jpg");
return intent;
}
public static Intent pickFile(Context context) {
return com.droidkit.pickers.Intents.pickFile(context);
}
public static void openMedia(Activity activity, View photoView, String path, int senderId) {
PictureActivity.launchPhoto(activity, photoView, path, senderId);
}
public static void savePicture(Context context, Bitmap bitmap) {
File actorPicturesFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
actorPicturesFolder = new File(actorPicturesFolder, "Actor");
actorPicturesFolder.mkdirs();
try {
File pictureFile = new File(actorPicturesFolder, System.currentTimeMillis()+".jpg");
pictureFile.createNewFile();
FileOutputStream ostream = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
ostream.close();
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(pictureFile);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
Log.d("Picture saving", "Saved as " + pictureFile.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
3e09cd6fc2522c417772ceb13a080aac00633cb0 | 834 | java | Java | src/main/java/burlap/visualizer/StatePainter.java | dohona/burlap | cc3b09de81f33e6bed8154144a3183dee8595e32 | [
"Apache-2.0"
] | 293 | 2015-01-25T21:33:30.000Z | 2022-01-23T13:26:30.000Z | src/main/java/burlap/visualizer/StatePainter.java | dohona/burlap | cc3b09de81f33e6bed8154144a3183dee8595e32 | [
"Apache-2.0"
] | 31 | 2015-04-27T19:40:39.000Z | 2021-11-21T19:48:47.000Z | src/main/java/burlap/visualizer/StatePainter.java | dohona/burlap | cc3b09de81f33e6bed8154144a3183dee8595e32 | [
"Apache-2.0"
] | 201 | 2015-01-15T15:36:55.000Z | 2021-11-20T21:57:07.000Z | 27.8 | 85 | 0.742206 | 4,144 | package burlap.visualizer;
import burlap.mdp.core.state.State;
import java.awt.*;
/**
* This class paints general properties of a state/domain that may not be represented
* by any specific object instance data. For instance, the GridWorld class
* may have walls that need to be painted, but the walls are part of the transition
* dynamics of the domain and not captured in the object instance values assignments.
* @author James MacGlashan
*
*/
public interface StatePainter {
/**
* Paints general state information not to graphics context g2
* @param g2 graphics context to which the static data should be painted
* @param s the state to be painted
* @param cWidth the width of the canvas
* @param cHeight the height of the canvas
*/
void paint(Graphics2D g2, State s, float cWidth, float cHeight);
}
|
3e09cd9d6fdab6d6b5abf73656abb3cd42d12306 | 1,558 | java | Java | app/src/main/java/com/touchlogger/capture/CapturePreparation.java | bbragap/Android-TouchLoggerModified | 40701ef18eb0d35bba8c94963e3b70cecf2dae3e | [
"MIT"
] | 12 | 2017-09-26T23:39:52.000Z | 2022-03-26T21:30:22.000Z | app/src/main/java/com/touchlogger/capture/CapturePreparation.java | bbragap/Android-TouchLoggerModified | 40701ef18eb0d35bba8c94963e3b70cecf2dae3e | [
"MIT"
] | null | null | null | app/src/main/java/com/touchlogger/capture/CapturePreparation.java | bbragap/Android-TouchLoggerModified | 40701ef18eb0d35bba8c94963e3b70cecf2dae3e | [
"MIT"
] | 3 | 2018-05-03T20:38:41.000Z | 2019-07-17T19:47:39.000Z | 31.16 | 101 | 0.633504 | 4,145 | package com.touchlogger.capture;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by Owner on 03.06.2016.
*/
public class CapturePreparation {
private static final String LOGTAG = "CapturePreparation";
private CaptureService service;
public CapturePreparation(CaptureService service) {
this.service = service;
}
public String getAdbPath() throws IOException {
String dataFolder = service.getApplicationContext().getApplicationInfo().dataDir;
copyFile("adb", dataFolder, "adb");
copyFile("adb", dataFolder, "libcrypto.so");
copyFile("adb", dataFolder, "libssl.so");
return dataFolder + "/adb";
}
private void copyFile(String assetDir, String localDir, String filename) throws IOException {
File outFile = new File(localDir + "/" + filename);
if(outFile.exists()) {
Log.w(LOGTAG, filename + " already exists");
return;
}
Log.d(LOGTAG, "copying " + filename);
InputStream in = service.getApplicationContext().getAssets().open(assetDir + "/" + filename);
FileOutputStream out = new FileOutputStream(outFile);
int read;
byte[] buffer = new byte[4096];
while ((read = in.read(buffer)) > 0) {
out.write(buffer, 0, read);
}
out.close();
in.close();
outFile.setExecutable(true);
Log.d(LOGTAG, "finished copying " + filename);
}
}
|
3e09cda88644347a2868636183a152de60129a0a | 11,534 | java | Java | acuity-etl/src/main/java/com/acuity/visualisations/model/output/entities/AdverseEvent.java | digital-ECMT/acuity-admin | 79d0ac4c5f76594c2c96349da319a523263c6fa4 | [
"Apache-2.0"
] | null | null | null | acuity-etl/src/main/java/com/acuity/visualisations/model/output/entities/AdverseEvent.java | digital-ECMT/acuity-admin | 79d0ac4c5f76594c2c96349da319a523263c6fa4 | [
"Apache-2.0"
] | null | null | null | acuity-etl/src/main/java/com/acuity/visualisations/model/output/entities/AdverseEvent.java | digital-ECMT/acuity-admin | 79d0ac4c5f76594c2c96349da319a523263c6fa4 | [
"Apache-2.0"
] | 1 | 2022-01-26T14:52:56.000Z | 2022-01-26T14:52:56.000Z | 27.527446 | 122 | 0.686492 | 4,146 | /*
* Copyright 2021 The University of Manchester
*
* 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.acuity.visualisations.model.output.entities;
import com.acuity.visualisations.model.acuityfield.AcuityField;
import com.acuity.visualisations.model.acuityfield.AcuityFieldTransformation;
import com.acuity.visualisations.data.util.Util;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.time.LocalDateTime;
@NoArgsConstructor
public class AdverseEvent extends TimestampedEntity implements Cloneable {
private String eventTypeGuid;
private String patientGuid;
private String aeText;
private String comment;
private String outcome;
private String doseLimitingToxicity;
private String timePoint;
private String immuneMediated;
private String infusionReaction;
private String requiredTreatment;
private String causedSubjectWithdrawal;
private String suspectedEndpoint;
private String suspectedEndpointCategory;
private String aeOfSpecialInterest;
public String getSuspectedEndpoint() {
return suspectedEndpoint;
}
public void setSuspectedEndpoint(String suspectedEndpoint) {
this.suspectedEndpoint = suspectedEndpoint;
}
public String getSuspectedEndpointCategory() {
return suspectedEndpointCategory;
}
public void setSuspectedEndpointCategory(String suspectedEndpointCategory) {
this.suspectedEndpointCategory = suspectedEndpointCategory;
}
@AcuityField(transform = AcuityFieldTransformation.INITIATING_EVENT_00_00_01)
private LocalDateTime startDate;
@AcuityField(transform = AcuityFieldTransformation.TERMINATING_EVENT_23_59_59)
private LocalDateTime endDate;
private String serious;
private String causality;
private String maxSeverity;
private String actionTaken;
private String subject;
private String part;
private String pt;
private String hlt;
private String soc;
private String llt;
private Integer number;
private transient String startingCtcGrade;
private transient Object[] ctcGradeChanges;
private transient Object[] ctcGradeChangeDates;
private transient Object[] ipDrugs;
private transient Object[] adDrugs;
private transient Object[] initialActionTakenForIpDrugs;
private transient Object[] initialActionTakenForAdDrugs;
private transient Object[] changedActionTakenForIpDrugs;
private transient Object[] changedActionTakenForAdDrugs;
private transient Object[] causalityForIpDrugs;
private transient Object[] causalityForAdDrugs;
private String groupGuid;
@Override
public Object clone() throws CloneNotSupportedException {
return (AdverseEvent) super.clone();
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Object[] getIpDrugs() {
return ipDrugs;
}
public void setIpDrugs(Object[] ipDrugs) {
this.ipDrugs = ipDrugs;
}
public Object[] getAdDrugs() {
return adDrugs;
}
public void setAdDrugs(Object[] adDrugs) {
this.adDrugs = adDrugs;
}
public Object[] getInitialActionTakenForIpDrugs() {
return initialActionTakenForIpDrugs;
}
public void setInitialActionTakenForIpDrugs(Object[] initialActionTakenForIpDrugs) {
this.initialActionTakenForIpDrugs = initialActionTakenForIpDrugs;
}
public Object[] getInitialActionTakenForAdDrugs() {
return initialActionTakenForAdDrugs;
}
public void setInitialActionTakenForAdDrugs(Object[] initialActionTakenForAdDrugs) {
this.initialActionTakenForAdDrugs = initialActionTakenForAdDrugs;
}
public Object[] getChangedActionTakenForIpDrugs() {
return changedActionTakenForIpDrugs;
}
public void setChangedActionTakenForIpDrugs(Object[] changedActionTakenForIpDrugs) {
this.changedActionTakenForIpDrugs = changedActionTakenForIpDrugs;
}
public Object[] getChangedActionTakenForAdDrugs() {
return changedActionTakenForAdDrugs;
}
public void setChangedActionTakenForAdDrugs(Object[] changedActionTakenForAdDrugs) {
this.changedActionTakenForAdDrugs = changedActionTakenForAdDrugs;
}
public Object[] getCausalityForIpDrugs() {
return causalityForIpDrugs;
}
public void setCausalityForIpDrugs(Object[] causalityForIpDrugs) {
this.causalityForIpDrugs = causalityForIpDrugs;
}
public Object[] getCausalityForAdDrugs() {
return causalityForAdDrugs;
}
public void setCausalityForAdDrugs(Object[] causalityForAdDrugs) {
this.causalityForAdDrugs = causalityForAdDrugs;
}
public String getGroupGuid() {
return groupGuid;
}
public void setGroupGuid(String groupGuid) {
this.groupGuid = groupGuid;
}
public String getStartingCtcGrade() {
return startingCtcGrade;
}
public void setStartingCtcGrade(String startingCtcGrade) {
this.startingCtcGrade = startingCtcGrade;
}
public Object[] getCtcGradeChanges() {
return ctcGradeChanges;
}
public void setCtcGradeChanges(Object[] ctcGradeChanges) {
this.ctcGradeChanges = ctcGradeChanges;
}
public Object[] getCtcGradeChangeDates() {
return ctcGradeChangeDates;
}
public void setCtcGradeChangeDates(Object[] ctcGradeChangeDates) {
this.ctcGradeChangeDates = ctcGradeChangeDates;
}
public String getEventTypeGuid() {
return eventTypeGuid;
}
public void setEventTypeGuid(String eventTypeId) {
this.eventTypeGuid = eventTypeId;
}
public String getPatientGuid() {
return patientGuid;
}
public void setPatientGuid(String patient) {
this.patientGuid = patient;
}
public String getAeText() {
return aeText;
}
public void setAeText(String aeText) {
this.aeText = aeText;
}
public LocalDateTime getStartDate() {
return startDate;
}
public void setStartDate(LocalDateTime startDate) {
this.startDate = startDate;
}
public LocalDateTime getEndDate() {
return endDate;
}
public void setEndDate(LocalDateTime endDate) {
this.endDate = endDate;
}
public String getSerious() {
return serious;
}
public void setSerious(String serious) {
this.serious = serious;
}
public String getCausality() {
return causality;
}
public void setCausality(String causality) {
this.causality = causality;
}
public String getMaxSeverity() {
return maxSeverity;
}
public void setMaxSeverity(String maxSeverity) {
this.maxSeverity = maxSeverity;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPart() {
return part;
}
public void setPart(String part) {
this.part = part;
}
public String getActionTaken() {
return actionTaken;
}
public void setActionTaken(String actionTaken) {
this.actionTaken = actionTaken;
}
public String getPT() {
return pt == null ? null : pt.toUpperCase();
}
public void setPT(String pt) {
this.pt = pt == null ? null : pt.toUpperCase();
}
public String getLLT() {
return llt;
}
public void setLLT(String llt) {
this.llt = llt;
}
public String getHLT() {
return hlt == null ? null : hlt.toUpperCase();
}
public void setHLT(String hlt) {
this.hlt = hlt == null ? null : hlt.toUpperCase();
}
public String getSOC() {
return soc == null ? null : soc.toUpperCase();
}
public void setSOC(String soc) {
this.soc = soc == null ? null : soc.toUpperCase();
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getOutcome() {
return outcome;
}
public void setOutcome(String outcome) {
this.outcome = outcome;
}
public String getDoseLimitingToxicity() {
return doseLimitingToxicity;
}
public void setDoseLimitingToxicity(String doseLimitingToxicity) {
this.doseLimitingToxicity = doseLimitingToxicity;
}
public String getTimePoint() {
return timePoint;
}
public void setTimePoint(String timePoint) {
this.timePoint = timePoint;
}
public String getImmuneMediated() {
return immuneMediated;
}
public void setImmuneMediated(String immuneMediated) {
this.immuneMediated = immuneMediated;
}
public String getInfusionReaction() {
return infusionReaction;
}
public void setInfusionReaction(String infusionReaction) {
this.infusionReaction = infusionReaction;
}
public String getRequiredTreatment() {
return requiredTreatment;
}
public void setRequiredTreatment(String requiredTreatment) {
this.requiredTreatment = requiredTreatment;
}
public String getCausedSubjectWithdrawal() {
return causedSubjectWithdrawal;
}
public void setCausedSubjectWithdrawal(String causedSubjectWithdrawal) {
this.causedSubjectWithdrawal = causedSubjectWithdrawal;
}
public String getAeOfSpecialInterest() {
return aeOfSpecialInterest;
}
public void setAeOfSpecialInterest(String aeOfSpecialInterest) {
this.aeOfSpecialInterest = aeOfSpecialInterest;
}
@Override
public String uniqueFieldsToString() {
return new ToStringBuilder(this, Util.getToStringStyle()).append("subject", subject).append("part", part)
.append("startDate", startDate).append("PT", pt).append("HLT", hlt).append("SOC", soc).toString();
}
@Override
public String allFieldsToString() {
return new ToStringBuilder(this, Util.getToStringStyle()).append("subject", subject).append("part", part)
.append("startDate", startDate).append("PT", pt).append("HLT", hlt).append("SOC", soc)
.append("LLT", llt).append("endDate", endDate).append("serious", serious)
.append("causality", causality).append("maxSeverity", maxSeverity).append("aeText", aeText)
.append("comment", comment).append("number", number).append("outcome", outcome)
.append("doseLimitingToxicity", doseLimitingToxicity).append("timePoint", timePoint)
.append("immuneMediated", immuneMediated).append("infusionReaction", infusionReaction)
.append("requiredTreatment", requiredTreatment).append("causedSubjectWithdrawal", causedSubjectWithdrawal)
.toString();
}
}
|
3e09ce3060298db4969736eb37b2a8708c1a55f6 | 1,440 | java | Java | app/src/main/java/com/example/cybersafetyapp/UtilityPackage/ErrorMessageVariables.java | RahatIbnRafiq/CyberbullyingAndroidAppOngoing | e67999f15bce15c22c349313d09e3fd40ee03a4f | [
"FSFAP"
] | null | null | null | app/src/main/java/com/example/cybersafetyapp/UtilityPackage/ErrorMessageVariables.java | RahatIbnRafiq/CyberbullyingAndroidAppOngoing | e67999f15bce15c22c349313d09e3fd40ee03a4f | [
"FSFAP"
] | null | null | null | app/src/main/java/com/example/cybersafetyapp/UtilityPackage/ErrorMessageVariables.java | RahatIbnRafiq/CyberbullyingAndroidAppOngoing | e67999f15bce15c22c349313d09e3fd40ee03a4f | [
"FSFAP"
] | null | null | null | 49.655172 | 144 | 0.769444 | 4,147 | package com.example.cybersafetyapp.UtilityPackage;
/**
* Created by RahatIbnRafiq on 11/16/2016.
*/
public class ErrorMessageVariables {
public static final String NOT_VALID_PHONE_NUMBER = "Sorry. This is not a valid phone number.";
public static final String NOT_VALID_EMAIL = "Sorry. This is not a valid email.";
public static final String NOT_VALID_PASSWORD = "Sorry. This is not a valid password.";
public static final String LOGIN_CREDENTIALS_FAIL = "Login Credentials failed.Check your username and password and then try again, please.";
public static final String LOGIN_UNEXPECTED_ERROR = "Oops! Something wrong must have happened. Please try again.";
public static final String EMAILS_DO_NOT_MATCH = "Emails do not match.";
public static final String PASSWORDS_DO_NOT_MATCH = "Passwords do not match.";
public static final String PASSWORD_LENGTH_ERROR = "password length must be at least 3";
public static final String ERROR_WHILE_GETTING_USERS = "Error while getting the users. Check your internet or try again.";
public static final String UNEXPECTED_DATABASE_ERROR = "Ops, something unexpected must have happened. Please try again.";
public static final String CANNOT_MONITOR_MORE_THAN_TWO = "Sorry! You cannot monitor more than two users per social network!";
public static final String DID_NOT_SELECT_ANY = "You have not selected any. Please select at least one.";
}
|
3e09ce8019bea69b96d95e81174cd122d5c4ca79 | 1,034 | java | Java | src/main/java/com/codeborne/selenide/logevents/ErrorsCollector.java | anilreddy/selenide | 3f48053e3c42cc22257a0d267a32c0786d72d3a0 | [
"MIT"
] | null | null | null | src/main/java/com/codeborne/selenide/logevents/ErrorsCollector.java | anilreddy/selenide | 3f48053e3c42cc22257a0d267a32c0786d72d3a0 | [
"MIT"
] | null | null | null | src/main/java/com/codeborne/selenide/logevents/ErrorsCollector.java | anilreddy/selenide | 3f48053e3c42cc22257a0d267a32c0786d72d3a0 | [
"MIT"
] | null | null | null | 25.85 | 73 | 0.637331 | 4,148 | package com.codeborne.selenide.logevents;
import java.util.ArrayList;
import java.util.List;
import static com.codeborne.selenide.logevents.LogEvent.EventStatus.FAIL;
public class ErrorsCollector implements LogEventListener {
private final List<Throwable> errors = new ArrayList<>();
@Override
public void onEvent(LogEvent event) {
if (event.getStatus() == FAIL) {
errors.add(event.getError());
}
}
public void clear() {
errors.clear();
}
public void failIfErrors(String testName) {
if (errors.size() == 1) {
throw new AssertionError(errors.get(0).toString());
}
if (!errors.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("Test ").append(testName).append(" failed.\n");
sb.append(errors.size()).append(" checks failed\n");
int i = 0;
for (Throwable error : errors) {
sb.append("\nFAIL #").append(++i).append(": ");
sb.append(error).append('\n');
}
throw new AssertionError(sb.toString());
}
}
}
|
3e09cf685730c3d98d73b9f59f1455f0051b6675 | 3,220 | java | Java | src/main/java/com/jaskulski/app/UI/CalculatedSquaresUI/SingleCalculatedSquare.java | Jaskulski94/Leveler | 3ac8856f1fe91b4c5a5a5722b16993cd5196eb95 | [
"MIT"
] | null | null | null | src/main/java/com/jaskulski/app/UI/CalculatedSquaresUI/SingleCalculatedSquare.java | Jaskulski94/Leveler | 3ac8856f1fe91b4c5a5a5722b16993cd5196eb95 | [
"MIT"
] | null | null | null | src/main/java/com/jaskulski/app/UI/CalculatedSquaresUI/SingleCalculatedSquare.java | Jaskulski94/Leveler | 3ac8856f1fe91b4c5a5a5722b16993cd5196eb95 | [
"MIT"
] | null | null | null | 25.354331 | 64 | 0.599379 | 4,149 | package com.jaskulski.app.UI.CalculatedSquaresUI;
import com.jaskulski.app.UI.UIParameters;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import static org.apache.commons.lang3.StringUtils.rightPad;
public class SingleCalculatedSquare extends JPanel {
private JLabel lblIndex;
private JLabel lblOrdXYText;
private JLabel lblAddAText;
private JLabel lblAddVText;
private JLabel lblSubAText;
private JLabel lblSubVText;
private GridBagConstraints GBC;
public SingleCalculatedSquare(int index1){
GridBagLayout GBL = new GridBagLayout();
GBC = new GridBagConstraints();
GBC.insets = new Insets(1,3,1,5);
this.setLayout(GBL);
initiateSingleSquareLabels();
lblIndex.setText("Nr "+ index1);
setSquareStyle();
}
public void setXYText(double x1, double y1){
String xY = String.format("%.2f-%.2f", x1, y1);
xY = rightPad(xY, 10, ' ');
lblOrdXYText.setText(xY);
}
public void setAddAText(double addA1) {
String addArea = String.format("P = %.1f", addA1);
addArea = rightPad(addArea, 8, ' ');
lblAddAText.setText(addArea);
}
public void setAddVText(double addV1) {
String addVolume = String.format("V = %.2f", addV1);
addVolume = rightPad(addVolume, 15, ' ');
lblAddVText.setText(addVolume);
}
public void setSubAText(double subA1) {
String subArea = String.format("P = %.2f", subA1);
subArea = rightPad(subArea, 8, ' ');
lblSubAText.setText(subArea);
}
public void setSubVText(double subV1) {
String subVolume = String.format("V = %.2f", subV1);
subVolume = rightPad(subVolume, 15, ' ');
lblSubVText.setText(subVolume);
}
private void initiateSingleSquareLabels(){
lblIndex = new JLabel("Nr: ");
JLabel lblOrdXY = new JLabel("X - Y: ");
JLabel lblAdd = new JLabel("Nasyp");
JLabel lblSub = new JLabel("Wykop");
JLabel lblIndexText = new JLabel();
lblOrdXYText = new JLabel();
lblAddAText = new JLabel();
lblAddVText = new JLabel();
lblSubAText = new JLabel();
lblSubVText = new JLabel();
GBC.anchor = GridBagConstraints.WEST;
GBC.gridx = 0;
GBC.gridy = 0;
this.add(lblIndex, GBC);
GBC.gridx = 1;
this.add(lblIndexText);
GBC.gridx = 2;
this.add(lblOrdXY, GBC);
GBC.gridx = 3;
this.add(lblOrdXYText, GBC);
GBC.gridwidth = 2;
GBC.gridx = 0;
GBC.gridy = 1;
this.add(lblAdd, GBC);
GBC.gridx = 2;
this.add(lblSub, GBC);
GBC.gridx = 0;
GBC.gridy = 2;
this.add(lblAddAText,GBC);
GBC.gridy = 3;
this.add(lblAddVText,GBC);
GBC.gridx = 2;
GBC.gridy = 2;
this.add(lblSubAText,GBC);
GBC.gridy = 3;
this.add(lblSubVText,GBC);
}
private void setSquareStyle(){
this.setBackground(Color.white);
UIParameters.setFontToAll(this, UIParameters.fontSmall);
this.setBorder(new LineBorder(Color.black));
}
}
|
3e09d081c80f7f27b26680e34037d7e10177439b | 9,028 | java | Java | src/main/java/io/vertx/core/http/RequestOptions.java | broadmind-admin/vert.x | d1b48e6557038553bfe31b1d7ad0f62b5796e696 | [
"Apache-2.0"
] | 1 | 2021-05-10T11:39:14.000Z | 2021-05-10T11:39:14.000Z | src/main/java/io/vertx/core/http/RequestOptions.java | broadmind-admin/vert.x | d1b48e6557038553bfe31b1d7ad0f62b5796e696 | [
"Apache-2.0"
] | 1 | 2021-12-14T21:45:10.000Z | 2021-12-14T21:45:10.000Z | src/main/java/io/vertx/core/http/RequestOptions.java | broadmind-admin/vert.x | d1b48e6557038553bfe31b1d7ad0f62b5796e696 | [
"Apache-2.0"
] | null | null | null | 24.745205 | 112 | 0.654119 | 4,150 | /*
* Copyright (c) 2011-2019 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.codegen.annotations.GenIgnore;
import io.vertx.core.MultiMap;
import io.vertx.core.VertxException;
import io.vertx.core.json.JsonObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
/**
* Options describing how an {@link HttpClient} will connect to make a request.
*
* @author <a href="mailto:efpyi@example.com">Julien Viet</a>
*/
@DataObject(generateConverter = true)
public class RequestOptions {
/**
* The default value for HTTP method = {@link HttpMethod#GET}
*/
public static final HttpMethod DEFAULT_HTTP_METHOD = HttpMethod.GET;
/**
* The default value for host name = {@code null}
*/
public static final String DEFAULT_HOST = null;
/**
* The default value for port = {@code null}
*/
public static final Integer DEFAULT_PORT = null;
/**
* The default value for SSL = {@code null}
*/
public static final Boolean DEFAULT_SSL = null;
/**
* The default relative request URI = ""
*/
public static final String DEFAULT_URI = "";
/**
* Follow redirection by default = {@code false}
*/
public static final boolean DEFAULT_FOLLOW_REDIRECTS = false;
/**
* The default request timeout = {@code 0} (disabled)
*/
public static final long DEFAULT_TIMEOUT = 0;
private HttpMethod method;
private String host;
private Integer port;
private Boolean ssl;
private String uri;
private MultiMap headers;
private boolean followRedirects;
private long timeout;
/**
* Default constructor
*/
public RequestOptions() {
method = DEFAULT_HTTP_METHOD;
host = DEFAULT_HOST;
port = DEFAULT_PORT;
ssl = DEFAULT_SSL;
uri = DEFAULT_URI;
followRedirects = DEFAULT_FOLLOW_REDIRECTS;
timeout = DEFAULT_TIMEOUT;
}
/**
* Copy constructor
*
* @param other the options to copy
*/
public RequestOptions(RequestOptions other) {
setMethod(other.method);
setHost(other.host);
setPort(other.port);
setSsl(other.ssl);
setURI(other.uri);
setFollowRedirects(other.followRedirects);
setTimeout(other.timeout);
if (other.headers != null) {
setHeaders(MultiMap.caseInsensitiveMultiMap().setAll(other.headers));
}
}
/**
* Create options from JSON
*
* @param json the JSON
*/
public RequestOptions(JsonObject json) {
RequestOptionsConverter.fromJson(json, this);
}
/**
* Get the HTTP method to be used by the client request.
*
* @return the HTTP method
*/
public HttpMethod getMethod() {
return method;
}
/**
* Set the HTTP method to be used by the client request.
*
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setMethod(HttpMethod method) {
this.method = method;
return this;
}
/**
* Get the host name to be used by the client request.
*
* @return the host name
*/
public String getHost() {
return host;
}
/**
* Set the host name to be used by the client request.
*
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setHost(String host) {
this.host = host;
return this;
}
/**
* Get the port to be used by the client request.
*
* @return the port
*/
public Integer getPort() {
return port;
}
/**
* Set the port to be used by the client request.
*
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setPort(Integer port) {
this.port = port;
return this;
}
/**
* @return is SSL/TLS enabled?
*/
public Boolean isSsl() {
return ssl;
}
/**
* Set whether SSL/TLS is enabled
*
* @param ssl true if enabled
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setSsl(Boolean ssl) {
this.ssl = ssl;
return this;
}
/**
* @return the request relative URI
*/
public String getURI() {
return uri;
}
/**
* Set the request relative URI
*
* @param uri the relative uri
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setURI(String uri) {
this.uri = uri;
return this;
}
/**
* @return {@code true} when the client should follow redirection
*/
public Boolean getFollowRedirects() {
return followRedirects;
}
/**
* Set whether to follow HTTP redirect
*
* @param followRedirects whether to follow redirect
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setFollowRedirects(Boolean followRedirects) {
this.followRedirects = followRedirects;
return this;
}
/**
* @return the amount of time after which if the request does not return any data within the timeout period an
* {@link java.util.concurrent.TimeoutException} will be passed to the exception handler and
* the request will be closed.
*/
public long getTimeout() {
return timeout;
}
/**
* Sets the amount of time after which if the request does not return any data within the timeout period an
* {@link java.util.concurrent.TimeoutException} will be passed to the exception handler and
* the request will be closed.
*
* @param timeout the amount of time in milliseconds.
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setTimeout(long timeout) {
this.timeout = timeout;
return this;
}
private URL parseUrl(String surl) {
// Note - parsing a URL this way is slower than specifying host, port and relativeURI
try {
return new URL(surl);
} catch (MalformedURLException e) {
throw new VertxException("Invalid url: " + surl, e);
}
}
/**
* Parse an absolute URI to use, this will update the {@code ssl}, {@code host},
* {@code port} and {@code uri} fields.
*
* @param absoluteURI the uri to use
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions setAbsoluteURI(String absoluteURI) {
Objects.requireNonNull(absoluteURI, "Cannot set a null absolute URI");
URL url = parseUrl(absoluteURI);
Boolean ssl = false;
int port = url.getPort();
String relativeUri = url.getPath().isEmpty() ? "/" + url.getFile() : url.getFile();
String protocol = url.getProtocol();
switch (protocol) {
case "http":
if (port == -1) {
port = 80;
}
break;
case "https": {
ssl = true;
if (port == -1) {
port = 443;
}
break;
}
default:
throw new IllegalArgumentException();
}
this.uri = relativeUri;
this.port = port;
this.ssl = ssl;
this.host = url.getHost();
return this;
}
/**
* Add a request header.
*
* @param key the header key
* @param value the header value
* @return a reference to this, so the API can be used fluently
*/
public RequestOptions addHeader(String key, String value) {
return addHeader((CharSequence) key, value);
}
/**
* Add a request header.
*
* @param key the header key
* @param value the header value
* @return a reference to this, so the API can be used fluently
*/
@GenIgnore
public RequestOptions addHeader(CharSequence key, CharSequence value) {
checkHeaders();
Objects.requireNonNull(key, "no null key accepted");
Objects.requireNonNull(value, "no null value accepted");
headers.add(key, value);
return this;
}
@GenIgnore
public RequestOptions addHeader(CharSequence key, Iterable<CharSequence> values) {
checkHeaders();
Objects.requireNonNull(key, "no null key accepted");
Objects.requireNonNull(values, "no null values accepted");
headers.add(key, values);
return this;
}
/**
* Set request headers from a multi-map.
*
* @param headers the headers
* @return a reference to this, so the API can be used fluently
*/
@GenIgnore
public RequestOptions setHeaders(MultiMap headers) {
this.headers = headers;
return this;
}
/**
* Get the request headers
*
* @return the headers
*/
@GenIgnore
public MultiMap getHeaders() {
return headers;
}
private void checkHeaders() {
if (headers == null) {
headers = MultiMap.caseInsensitiveMultiMap();
}
}
public JsonObject toJson() {
JsonObject json = new JsonObject();
RequestOptionsConverter.toJson(this, json);
return json;
}
}
|
3e09d0a05a1b54527cd1501c4f5be474e41f489b | 91 | java | Java | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/joinDeclaration/afterParenthesis.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/joinDeclaration/afterParenthesis.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | null | null | null | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/joinDeclaration/afterParenthesis.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 1 | 2018-10-03T12:35:06.000Z | 2018-10-03T12:35:06.000Z | 15.166667 | 43 | 0.527473 | 4,151 | // "Join declaration and assignment" "true"
class Test {
{
int i = 4 * (2 + 3);
}
} |
3e09d0e7ade724f1e2c90919318f8a47f90d5953 | 3,046 | java | Java | jdk11/openj9.dtfj/com/ibm/j9ddr/vm29/structure/BuildResult.java | 1446554749/jdk_11_src_read | b9c070d7232ee3cf5f2f6270e748ada74cbabb3f | [
"Apache-2.0"
] | null | null | null | jdk11/openj9.dtfj/com/ibm/j9ddr/vm29/structure/BuildResult.java | 1446554749/jdk_11_src_read | b9c070d7232ee3cf5f2f6270e748ada74cbabb3f | [
"Apache-2.0"
] | null | null | null | jdk11/openj9.dtfj/com/ibm/j9ddr/vm29/structure/BuildResult.java | 1446554749/jdk_11_src_read | b9c070d7232ee3cf5f2f6270e748ada74cbabb3f | [
"Apache-2.0"
] | null | null | null | 34.613636 | 135 | 0.722259 | 4,152 | /*******************************************************************************
* Copyright (c) 1991, 2021 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
package com.ibm.j9ddr.vm29.structure;
/**
* Structure: BuildResult
*
* This stub class represents a class that can return in memory offsets
* to VM C and C++ structures.
*
* This particular implementation exists only to allow StructurePointer code to
* compile at development time. This is never loaded at run time.
*
* At runtime generated byte codes returning actual offset values from the core file
* will be loaded by the StructureClassLoader.
*/
public final class BuildResult {
// VM Constants
public static final long SIZEOF;
public static final long BytecodeTranslationFailed;
public static final long ClassNameMismatch;
public static final long ClassRead;
public static final long GenericError;
public static final long IllegalPackageName;
public static final long InvalidAnnotation;
public static final long InvalidBytecode;
public static final long InvalidBytecodeSize;
public static final long LineNumberTableDecompressFailed;
public static final long NeedWideBranches;
public static final long OK;
public static final long OutOfMemory;
public static final long OutOfROM;
public static final long StackMapFailed;
public static final long UnknownAnnotation;
public static final long VerifyErrorInlining;
// Static Initializer
private static final boolean RUNTIME = false;
static {
if (!RUNTIME) {
throw new IllegalArgumentException("This stub class should not be on your classpath");
}
SIZEOF = 0;
BytecodeTranslationFailed = 0;
ClassNameMismatch = 0;
ClassRead = 0;
GenericError = 0;
IllegalPackageName = 0;
InvalidAnnotation = 0;
InvalidBytecode = 0;
InvalidBytecodeSize = 0;
LineNumberTableDecompressFailed = 0;
NeedWideBranches = 0;
OK = 0;
OutOfMemory = 0;
OutOfROM = 0;
StackMapFailed = 0;
UnknownAnnotation = 0;
VerifyErrorInlining = 0;
}
}
|
3e09d15ae234cf19bf79ac7f23b130896b0df988 | 8,092 | java | Java | runtime/Java/src/org/antlr/v4/runtime/Recognizer.java | xsIceman/antlr4 | 527118197f89b5fbd1fb938c6445ccd5063eee48 | [
"BSD-3-Clause"
] | 11,811 | 2015-01-01T02:40:39.000Z | 2022-03-31T16:11:19.000Z | runtime/Java/src/org/antlr/v4/runtime/Recognizer.java | xsIceman/antlr4 | 527118197f89b5fbd1fb938c6445ccd5063eee48 | [
"BSD-3-Clause"
] | 2,364 | 2015-01-01T00:29:19.000Z | 2022-03-31T21:26:34.000Z | runtime/Java/src/org/antlr/v4/runtime/Recognizer.java | xsIceman/antlr4 | 527118197f89b5fbd1fb938c6445ccd5063eee48 | [
"BSD-3-Clause"
] | 3,240 | 2015-01-05T02:34:15.000Z | 2022-03-30T18:26:29.000Z | 29.212996 | 108 | 0.712803 | 4,153 | /*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.ATNSimulator;
import org.antlr.v4.runtime.atn.ParseInfo;
import org.antlr.v4.runtime.misc.Utils;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public abstract class Recognizer<Symbol, ATNInterpreter extends ATNSimulator> {
public static final int EOF=-1;
private static final Map<Vocabulary, Map<String, Integer>> tokenTypeMapCache =
new WeakHashMap<Vocabulary, Map<String, Integer>>();
private static final Map<String[], Map<String, Integer>> ruleIndexMapCache =
new WeakHashMap<String[], Map<String, Integer>>();
private List<ANTLRErrorListener> _listeners =
new CopyOnWriteArrayList<ANTLRErrorListener>() {{
add(ConsoleErrorListener.INSTANCE);
}};
protected ATNInterpreter _interp;
private int _stateNumber = -1;
/** Used to print out token names like ID during debugging and
* error reporting. The generated parsers implement a method
* that overrides this to point to their String[] tokenNames.
*
* @deprecated Use {@link #getVocabulary()} instead.
*/
@Deprecated
public abstract String[] getTokenNames();
public abstract String[] getRuleNames();
/**
* Get the vocabulary used by the recognizer.
*
* @return A {@link Vocabulary} instance providing information about the
* vocabulary used by the grammar.
*/
@SuppressWarnings("deprecation")
public Vocabulary getVocabulary() {
return VocabularyImpl.fromTokenNames(getTokenNames());
}
/**
* Get a map from token names to token types.
*
* <p>Used for XPath and tree pattern compilation.</p>
*/
public Map<String, Integer> getTokenTypeMap() {
Vocabulary vocabulary = getVocabulary();
synchronized (tokenTypeMapCache) {
Map<String, Integer> result = tokenTypeMapCache.get(vocabulary);
if (result == null) {
result = new HashMap<String, Integer>();
for (int i = 0; i <= getATN().maxTokenType; i++) {
String literalName = vocabulary.getLiteralName(i);
if (literalName != null) {
result.put(literalName, i);
}
String symbolicName = vocabulary.getSymbolicName(i);
if (symbolicName != null) {
result.put(symbolicName, i);
}
}
result.put("EOF", Token.EOF);
result = Collections.unmodifiableMap(result);
tokenTypeMapCache.put(vocabulary, result);
}
return result;
}
}
/**
* Get a map from rule names to rule indexes.
*
* <p>Used for XPath and tree pattern compilation.</p>
*/
public Map<String, Integer> getRuleIndexMap() {
String[] ruleNames = getRuleNames();
if (ruleNames == null) {
throw new UnsupportedOperationException("The current recognizer does not provide a list of rule names.");
}
synchronized (ruleIndexMapCache) {
Map<String, Integer> result = ruleIndexMapCache.get(ruleNames);
if (result == null) {
result = Collections.unmodifiableMap(Utils.toMap(ruleNames));
ruleIndexMapCache.put(ruleNames, result);
}
return result;
}
}
public int getTokenType(String tokenName) {
Integer ttype = getTokenTypeMap().get(tokenName);
if ( ttype!=null ) return ttype;
return Token.INVALID_TYPE;
}
/**
* If this recognizer was generated, it will have a serialized ATN
* representation of the grammar.
*
* <p>For interpreters, we don't know their serialized ATN despite having
* created the interpreter from it.</p>
*/
public String getSerializedATN() {
throw new UnsupportedOperationException("there is no serialized ATN");
}
/** For debugging and other purposes, might want the grammar name.
* Have ANTLR generate an implementation for this method.
*/
public abstract String getGrammarFileName();
/**
* Get the {@link ATN} used by the recognizer for prediction.
*
* @return The {@link ATN} used by the recognizer for prediction.
*/
public abstract ATN getATN();
/**
* Get the ATN interpreter used by the recognizer for prediction.
*
* @return The ATN interpreter used by the recognizer for prediction.
*/
public ATNInterpreter getInterpreter() {
return _interp;
}
/** If profiling during the parse/lex, this will return DecisionInfo records
* for each decision in recognizer in a ParseInfo object.
*
* @since 4.3
*/
public ParseInfo getParseInfo() {
return null;
}
/**
* Set the ATN interpreter used by the recognizer for prediction.
*
* @param interpreter The ATN interpreter used by the recognizer for
* prediction.
*/
public void setInterpreter(ATNInterpreter interpreter) {
_interp = interpreter;
}
/** What is the error header, normally line/character position information? */
public String getErrorHeader(RecognitionException e) {
int line = e.getOffendingToken().getLine();
int charPositionInLine = e.getOffendingToken().getCharPositionInLine();
return "line "+line+":"+charPositionInLine;
}
/** How should a token be displayed in an error message? The default
* is to display just the text, but during development you might
* want to have a lot of information spit out. Override in that case
* to use t.toString() (which, for CommonToken, dumps everything about
* the token). This is better than forcing you to override a method in
* your token objects because you don't have to go modify your lexer
* so that it creates a new Java type.
*
* @deprecated This method is not called by the ANTLR 4 Runtime. Specific
* implementations of {@link ANTLRErrorStrategy} may provide a similar
* feature when necessary. For example, see
* {@link DefaultErrorStrategy#getTokenErrorDisplay}.
*/
@Deprecated
public String getTokenErrorDisplay(Token t) {
if ( t==null ) return "<no token>";
String s = t.getText();
if ( s==null ) {
if ( t.getType()==Token.EOF ) {
s = "<EOF>";
}
else {
s = "<"+t.getType()+">";
}
}
s = s.replace("\n","\\n");
s = s.replace("\r","\\r");
s = s.replace("\t","\\t");
return "'"+s+"'";
}
/**
* @exception NullPointerException if {@code listener} is {@code null}.
*/
public void addErrorListener(ANTLRErrorListener listener) {
if (listener == null) {
throw new NullPointerException("listener cannot be null.");
}
_listeners.add(listener);
}
public void removeErrorListener(ANTLRErrorListener listener) {
_listeners.remove(listener);
}
public void removeErrorListeners() {
_listeners.clear();
}
public List<? extends ANTLRErrorListener> getErrorListeners() {
return _listeners;
}
public ANTLRErrorListener getErrorListenerDispatch() {
return new ProxyErrorListener(getErrorListeners());
}
// subclass needs to override these if there are sempreds or actions
// that the ATN interp needs to execute
public boolean sempred(RuleContext _localctx, int ruleIndex, int actionIndex) {
return true;
}
public boolean precpred(RuleContext localctx, int precedence) {
return true;
}
public void action(RuleContext _localctx, int ruleIndex, int actionIndex) {
}
public final int getState() {
return _stateNumber;
}
/** Indicate that the recognizer has changed internal state that is
* consistent with the ATN state passed in. This way we always know
* where we are in the ATN as the parser goes along. The rule
* context objects form a stack that lets us see the stack of
* invoking rules. Combine this and we have complete ATN
* configuration information.
*/
public final void setState(int atnState) {
// System.err.println("setState "+atnState);
_stateNumber = atnState;
// if ( traceATNStates ) _ctx.trace(atnState);
}
public abstract IntStream getInputStream();
public abstract void setInputStream(IntStream input);
public abstract TokenFactory<?> getTokenFactory();
public abstract void setTokenFactory(TokenFactory<?> input);
}
|
3e09d160903f3d87840b2dfc6d9e291223b3567d | 2,519 | java | Java | src/main/java/techreborn/api/recipe/ScrapboxRecipeCrafter.java | trobol/TechReborn | 0f94cbd2857a76d94e96fcc1f301ffdda96a1142 | [
"MIT"
] | 318 | 2015-04-10T08:40:29.000Z | 2022-03-19T21:31:03.000Z | src/main/java/techreborn/api/recipe/ScrapboxRecipeCrafter.java | trobol/TechReborn | 0f94cbd2857a76d94e96fcc1f301ffdda96a1142 | [
"MIT"
] | 2,574 | 2015-04-11T23:01:42.000Z | 2022-03-31T18:46:14.000Z | src/main/java/techreborn/api/recipe/ScrapboxRecipeCrafter.java | trobol/TechReborn | 0f94cbd2857a76d94e96fcc1f301ffdda96a1142 | [
"MIT"
] | 332 | 2015-05-19T20:39:56.000Z | 2022-03-27T09:17:10.000Z | 38.753846 | 118 | 0.759428 | 4,154 | /*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 TechReborn
*
* 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 techreborn.api.recipe;
import net.minecraft.block.entity.BlockEntity;
import reborncore.common.crafting.RebornRecipe;
import reborncore.common.recipes.RecipeCrafter;
import reborncore.common.util.RebornInventory;
import techreborn.init.ModRecipes;
import java.util.List;
/**
* @author drcrazy
*/
public class ScrapboxRecipeCrafter extends RecipeCrafter {
/**
* @param parent Tile having this crafter
* @param inventory Inventory from parent blockEntity
* @param inputSlots Slot IDs for input
* @param outputSlots Slot IDs for output
*/
public ScrapboxRecipeCrafter(BlockEntity parent, RebornInventory<?> inventory, int[] inputSlots, int[] outputSlots) {
super(ModRecipes.SCRAPBOX, parent, 1, 1, inventory, inputSlots, outputSlots);
}
@Override
public void updateCurrentRecipe() {
List<RebornRecipe> scrapboxRecipeList = ModRecipes.SCRAPBOX.getRecipes(blockEntity.getWorld());
if (scrapboxRecipeList.isEmpty()) {
setCurrentRecipe(null);
return;
}
int random = blockEntity.getWorld().random.nextInt(scrapboxRecipeList.size());
// Sets the current recipe then syncs
setCurrentRecipe(scrapboxRecipeList.get(random));
this.currentNeededTicks = Math.max((int) (currentRecipe.getTime() * (1.0 - getSpeedMultiplier())), 1);
this.currentTickTime = 0;
setIsActive();
}
}
|
3e09d1dc7b2e5120def883429e54f16833dacda8 | 144 | java | Java | Java/java-snippet/src/main/java/com/sununiq/snippet/jianzhioffer/Question8.java | Sitrone/coding-notes | 121f32be35281b857e8a9082644013d0d19d74d9 | [
"MIT"
] | null | null | null | Java/java-snippet/src/main/java/com/sununiq/snippet/jianzhioffer/Question8.java | Sitrone/coding-notes | 121f32be35281b857e8a9082644013d0d19d74d9 | [
"MIT"
] | 1 | 2021-12-14T21:15:32.000Z | 2021-12-14T21:15:32.000Z | Java/java-snippet/src/main/java/com/sununiq/snippet/jianzhioffer/Question8.java | Sitrone/coding-notes | 121f32be35281b857e8a9082644013d0d19d74d9 | [
"MIT"
] | null | null | null | 13.090909 | 42 | 0.6875 | 4,155 | package com.sununiq.snippet.jianzhioffer;
/**
* 旋转数组最小的数字 TODO
*/
public class Question8 {
public static void main(String[] args) {
}
}
|
3e09d2217f15c82404db1042b9f23787566f5e8b | 2,712 | java | Java | src/test/java/com/epam/digital/data/platform/starter/actuator/readinessprobe/UrlAvailabilityCheckerTest.java | epam/edp-ddm-starter-actuator | 41a476b3e311f54332980d440046555e4b6e0a2e | [
"Apache-2.0"
] | null | null | null | src/test/java/com/epam/digital/data/platform/starter/actuator/readinessprobe/UrlAvailabilityCheckerTest.java | epam/edp-ddm-starter-actuator | 41a476b3e311f54332980d440046555e4b6e0a2e | [
"Apache-2.0"
] | null | null | null | src/test/java/com/epam/digital/data/platform/starter/actuator/readinessprobe/UrlAvailabilityCheckerTest.java | epam/edp-ddm-starter-actuator | 41a476b3e311f54332980d440046555e4b6e0a2e | [
"Apache-2.0"
] | null | null | null | 32.674699 | 75 | 0.763274 | 4,156 | /*
* Copyright 2021 EPAM Systems.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.digital.data.platform.starter.actuator.readinessprobe;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
@ExtendWith(MockitoExtension.class)
class UrlAvailabilityCheckerTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private UrlAvailabilityChecker urlAvailabilityChecker;
@Test
void shouldReturnNoServicesIfAllRequestsSuccessful() {
when(restTemplate.exchange("stub", HttpMethod.GET, null, String.class))
.thenReturn(successfulResponse());
var result = urlAvailabilityChecker.getDownServices(Set.of("stub"));
assertThat(result.size()).isZero();
}
@Test
void shouldReturnServicesHostnameIfRequestUnsuccessful() {
when(restTemplate.exchange("stub", HttpMethod.GET, null, String.class))
.thenReturn(unsuccessfulResponse());
var result = urlAvailabilityChecker.getDownServices(Set.of("stub"));
assertThat(result).hasSize(1)
.contains("stub");
}
@Test
void shouldReturnServicesHostnameIfRequestUnsuccessfulIoException() {
when(restTemplate.exchange("stub", HttpMethod.GET, null, String.class))
.thenThrow(new ResourceAccessException("", new IOException()));
var result = urlAvailabilityChecker.getDownServices(Set.of("stub"));
assertThat(result).hasSize(1)
.contains("stub");
}
private ResponseEntity<String> successfulResponse() {
return new ResponseEntity<>(null, HttpStatus.OK);
}
private ResponseEntity<String> unsuccessfulResponse() {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
3e09d3743cabe074e1e67f6bd59c4b73dbed7856 | 2,451 | java | Java | ksql-parser/src/main/java/io/confluent/ksql/parser/tree/CreateStream.java | bbejeck/ksql | 011e7e66bdc4dbfff1d185636781050d654c7188 | [
"Apache-2.0"
] | 1 | 2019-05-03T19:31:00.000Z | 2019-05-03T19:31:00.000Z | ksql-parser/src/main/java/io/confluent/ksql/parser/tree/CreateStream.java | bbejeck/ksql | 011e7e66bdc4dbfff1d185636781050d654c7188 | [
"Apache-2.0"
] | null | null | null | ksql-parser/src/main/java/io/confluent/ksql/parser/tree/CreateStream.java | bbejeck/ksql | 011e7e66bdc4dbfff1d185636781050d654c7188 | [
"Apache-2.0"
] | null | null | null | 28.172414 | 82 | 0.699306 | 4,157 | /*
* Copyright 2018 Confluent Inc.
*
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.parser.tree;
import static com.google.common.base.MoreObjects.toStringHelper;
import com.google.errorprone.annotations.Immutable;
import io.confluent.ksql.name.SourceName;
import io.confluent.ksql.parser.NodeLocation;
import io.confluent.ksql.parser.properties.with.CreateSourceProperties;
import java.util.Optional;
@Immutable
public class CreateStream extends CreateSource implements ExecutableDdlStatement {
public CreateStream(
final SourceName name,
final TableElements elements,
final boolean notExists,
final CreateSourceProperties properties
) {
this(Optional.empty(), name, elements, notExists, properties);
}
public CreateStream(
final Optional<NodeLocation> location,
final SourceName name,
final TableElements elements,
final boolean notExists,
final CreateSourceProperties properties
) {
super(location, name, elements, notExists, properties);
}
@Override
public CreateSource copyWith(
final TableElements elements,
final CreateSourceProperties properties
) {
return new CreateStream(
getLocation(),
getName(),
elements,
isNotExists(),
properties);
}
@Override
public <R, C> R accept(final AstVisitor<R, C> visitor, final C context) {
return visitor.visitCreateStream(this, context);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
return super.equals(obj);
}
@Override
public String toString() {
return toStringHelper(this)
.add("name", getName())
.add("elements", getElements())
.add("notExists", isNotExists())
.add("properties", getProperties())
.toString();
}
}
|
3e09d3c5e5513474a1322b91c03bc75daa929cc8 | 1,815 | java | Java | core/src/test/java/com/google/errorprone/bugpatterns/DepAnnTest.java | gaul/error-prone | 03495e209823c554a2733d5a37764ab310cb3ddb | [
"Apache-2.0"
] | 1 | 2016-11-23T10:18:47.000Z | 2016-11-23T10:18:47.000Z | core/src/test/java/com/google/errorprone/bugpatterns/DepAnnTest.java | andrewgaul/error-prone | 03495e209823c554a2733d5a37764ab310cb3ddb | [
"Apache-2.0"
] | null | null | null | core/src/test/java/com/google/errorprone/bugpatterns/DepAnnTest.java | andrewgaul/error-prone | 03495e209823c554a2733d5a37764ab310cb3ddb | [
"Apache-2.0"
] | null | null | null | 29.274194 | 84 | 0.748209 | 4,158 | /*
* Copyright 2013 Google 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.google.errorprone.bugpatterns;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class DepAnnTest {
private CompilationTestHelper compilationHelper;
@Before
public void setUp() {
compilationHelper = CompilationTestHelper.newInstance(DepAnn.class, getClass());
}
@Test
public void testPositiveCase() throws Exception {
compilationHelper.addSourceFile("DepAnnPositiveCases.java").doTest();
}
@Test
public void testNegativeCase1() throws Exception {
compilationHelper.addSourceFile("DepAnnNegativeCase1.java").doTest();
}
@Test
@Ignore("blocked on javac7 bug")
public void testNegativeCase2() throws Exception {
compilationHelper.addSourceFile("DepAnnNegativeCase2.java").doTest();
}
@Test
public void testDisableable() throws Exception {
compilationHelper.setArgs(ImmutableList.of("-Xep:DepAnn:OFF"))
.expectNoDiagnostics()
.addSourceFile("DepAnnPositiveCases.java")
.doTest();
}
}
|
3e09d3d298efe8cf6de88a76dd9da66518894a3d | 2,543 | java | Java | richedit/classes/src/com/ibm/richtext/textapps/MTextToString.java | srl295/icu | 7c7f805b917476f269babc853fb1eb3e0a17a88b | [
"ICU",
"Unlicense"
] | 1 | 2018-07-24T21:03:12.000Z | 2018-07-24T21:03:12.000Z | richedit/classes/src/com/ibm/richtext/textapps/MTextToString.java | srl295/icu | 7c7f805b917476f269babc853fb1eb3e0a17a88b | [
"ICU",
"Unlicense"
] | null | null | null | richedit/classes/src/com/ibm/richtext/textapps/MTextToString.java | srl295/icu | 7c7f805b917476f269babc853fb1eb3e0a17a88b | [
"ICU",
"Unlicense"
] | 1 | 2018-07-13T15:52:46.000Z | 2018-07-13T15:52:46.000Z | 31.012195 | 77 | 0.621313 | 4,159 | /*
* (C) Copyright IBM Corp. 1998-2004. All Rights Reserved.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/
package com.ibm.richtext.textapps;
import com.ibm.richtext.styledtext.MConstText;
import java.io.*;
public final class MTextToString {
static final String COPYRIGHT =
"(C) Copyright IBM Corp. 1998-1999 - All Rights Reserved";
public static void main(String[] args) {
if (args.length != 2) {
usage();
}
else {
writeMTextAsString(args[0], args[1]);
}
}
private static void usage() {
System.out.println("Usage: MTextToString inFile outFile");
System.out.println("inFile must be a serialized MConstText");
System.out.println("On exit, outFile will be a serialized String ");
System.out.println("containing the characters in the text.");
System.out.println("inFile and outFile must not be the same.");
System.exit(1);
}
public static void writeMTextAsString(String inFile, String outFile) {
File file = new File(inFile);
MConstText text = FileUtils.loadMText(file);
if (text != null) {
char[] ch = new char[text.length()];
text.extractChars(0, ch.length, ch, 0);
String str = new String(ch);
writeString(str, outFile);
}
else {
System.out.println("Can't read inFile.");
}
}
public static void writeString(String stringToWrite, String outFile) {
File file = new File(outFile);
Throwable error = null;
try {
OutputStream outStream = new FileOutputStream(file);
ObjectOutputStream objStream = new ObjectOutputStream(outStream);
objStream.writeObject(stringToWrite);
outStream.close();
return;
}
catch(IOException e) {
error = e;
}
catch(ClassCastException e) {
error = e;
}
error.printStackTrace();
}
} |
3e09d4bbe49dc109a86822a888b7a31c75111327 | 504 | java | Java | sandbox/src/test/java/test_exercise4/PrimeTests.java | vori1987/java_pft2 | 70d8b4b33e66260acc4a5e08bd284062b7dda3a8 | [
"Apache-2.0"
] | null | null | null | sandbox/src/test/java/test_exercise4/PrimeTests.java | vori1987/java_pft2 | 70d8b4b33e66260acc4a5e08bd284062b7dda3a8 | [
"Apache-2.0"
] | null | null | null | sandbox/src/test/java/test_exercise4/PrimeTests.java | vori1987/java_pft2 | 70d8b4b33e66260acc4a5e08bd284062b7dda3a8 | [
"Apache-2.0"
] | null | null | null | 18.666667 | 64 | 0.69246 | 4,160 | package test_exercise4;
import exercise4.Primes;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PrimeTests {
@Test
public void testPrime() {
Assert.assertTrue(Primes.isPrimeFast(Integer.MAX_VALUE));
}
/*
@Test
public void testNonPrime() {
Assert.assertFalse(Primes.isPrime(Integer.MAX_VALUE - 2));
}
*/
@Test (enabled = false)
public void testPrimeLong() {
long n = Integer.MAX_VALUE;
Assert.assertTrue(Primes.isPrime(n));
}
}
|
3e09d4e2ca63231091417fad5b55f651526afbdf | 1,742 | java | Java | src/main/java/org/spongepowered/common/interfaces/world/IMixinDimensionType.java | Limeth/SpongeCommon | a73c930b1692340cc61c1742a957dd00c1191533 | [
"MIT"
] | null | null | null | src/main/java/org/spongepowered/common/interfaces/world/IMixinDimensionType.java | Limeth/SpongeCommon | a73c930b1692340cc61c1742a957dd00c1191533 | [
"MIT"
] | null | null | null | src/main/java/org/spongepowered/common/interfaces/world/IMixinDimensionType.java | Limeth/SpongeCommon | a73c930b1692340cc61c1742a957dd00c1191533 | [
"MIT"
] | null | null | null | 37.06383 | 80 | 0.764638 | 4,161 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) 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.spongepowered.common.interfaces.world;
import org.spongepowered.api.service.context.Context;
import org.spongepowered.common.config.SpongeConfig;
import org.spongepowered.common.config.type.DimensionConfig;
import java.nio.file.Path;
public interface IMixinDimensionType {
SpongeConfig<DimensionConfig> getDimensionConfig();
Context getContext();
String getEnumName();
String getModId();
Path getConfigPath();
boolean shouldGenerateSpawnOnLoad();
}
|
3e09d54dbc2b34781a8cde3a55a462cdbb6d5590 | 16,604 | java | Java | output/089e9594bb39456eadbfe1f30469afa8.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/089e9594bb39456eadbfe1f30469afa8.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/089e9594bb39456eadbfe1f30469afa8.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | 38.258065 | 383 | 0.485726 | 4,162 | class d8mNLjdHbmgm {
public int[] w () {
( !null[ !682019202[ ( ( !mmTR3FcFT1h.ir64k9ujp3FIBy())[ -new boolean[ this[ !!RT8F4CUoEI.J0BUAqqO6nhVad]].bSpGDRlZ]).zBcsNC4H3XxFSn()]]).S0u;
-8.w6Q();
return;
AIAj0h8tBK AGLdnCW = new iFup().ggOP = true[ !-!---!--this.HhEMJW];
!!true.IZ5;
boolean[][] MXp4oY7EzOP = --new gWo8zYPMQbAoeV().gjdA;
boolean cict;
return ( -null.MzCe_OT1()).PGa8();
}
public int[] tWPBL3TW () throws ofm {
void Y7r;
int UivbpWfFMcC;
void[][] yleWXLvW3XOV;
void[] JleIpm7l;
{
void Ot;
nwb0H2 T;
boolean[][] u7iAxyJ0v7;
--3559[ false._oqJQ];
boolean LxSouAl0w;
int[] SpWxZW7te;
return;
void[][] kjxov;
}
pYTBJoiYaW xxU63 = e6CYp_.Y1WJSK3w;
if ( !202401785.E8iv9) ;else ;
Tir8IXyXpzFI le = null.bVRbDqVckTW57P();
!!new rchQcZ2me[ --!3553[ --true.Kh]].F15JLRCmBn4XSQ();
if ( new u4N6_UcRKjh()[ -new N4D2XjNyCB4j4R().GBUbYmMxLT6JX()]) if ( !!!-false[ null.K1nxY0SBKzys]) while ( true.dQwGF5s4vM47()) return;
977478724.vLQxAm3IX();
new boolean[ null.W()].QNBiTLBUXlgC8();
int Lurk_diX;
if ( !!-true[ !-GxiV18[ new void[ new QQZkpVLr_[ true[ !false.Da_]].GydR5X()].bTwCW7S9()]]) if ( false.Bo) while ( new void[ new void[ ( null.yBEJZ).P8U7VtRM()][ new xL4vdOae[ 99611[ --5.oI]][ !new int[ !new o_NNc()[ false._Ke()]][ ---true.rjDGuxMnnX()]]]][ --rUGQ5Q0JXUf4[ Jfkfsk[ ( --this.Mk5FrSOboDfT())[ --new PQ_Sw5T_D988().h()]]]]) ;else while ( -!null.YFs) N.ndVIwZk;
while ( -false[ false[ jRkEC_Bfbd0TE().le()]]) ;
void CujjPF;
false[ !JzW.VxK3];
return;
}
public static void GDq5zApwoFU85 (String[] d1vsPjL2) throws cXCom_ {
boolean[][][][] fuA8Bq_dzZ;
{
while ( HQW4VNDwxmgbik.BUnKIhcf3()) return;
{
void wv;
}
{
boolean knz;
}
false[ -( new Bn8Zxdvc29Oo().qdTbZRw2PB0I).E0tNUI()];
int[] PfCEXij_FG;
I1tBHA_.QFQ8r4();
if ( ( null.Vm).FrR7ol) if ( zBk9s73().xx0RFfWMGC()) !-!-new boolean[ ( gfZMYi7u0gRO.jY()).p0()].cwa;
}
void[] t8T_LD8x_I_ud;
int W17bTLfd1GOchJ = new EK[ true.v_BkQhYZg0S7].mfmiYr5mh = jwjPtIW8fxcSD().ar0tv36qG();
return;
if ( ( --!true.VMzd)[ !-gF0jv[ -0[ 608784[ !-!new int[ ( --!-!( true.u())[ --true[ -j2p5.hnO_Cp_KiI]]).J3q].TKtrQYHTlbam5k()]]]]) while ( D2PrNGcvsEp.pOthxrgeCdq4()) while ( -true.yT3_eg2Aa()) !!!!!-true.vCXE();else !-( 37.Rxuc0nXVevJEX).l4JXyferpGExwP;
int[][][] ZltimEv1A;
Jw315oaE().LE952APIPHan;
while ( -false.s6E()) return;
ZejyYT4d XfrsM9kxXjs = new y().Lidgv = dS0x4hCSnV393().FirSzdFNR();
false[ -null.w_i()];
while ( ( !true.kEc()).HvWSOM()) while ( -!!-!!-true.WeKq3Glg7DNZLu) ;
{
{
void fgFuhw3lQF0Z;
}
while ( null.V0CONlhpbS) {
while ( -!null[ !true.UE()]) {
void[][] IbGZFO;
}
}
void AAZR;
void rDpE;
{
void TWSKXVzDN;
}
while ( 04.JVkU9()) if ( Nr[ ---tqWwm.Uf]) ;
UC[] hZ2sF8;
boolean bp;
{
if ( aAsTb5vYiGP.WL7KUtvBU4aGwK()) if ( new ZdhrkI3fh4Y().P5bjo()) return;
}
while ( false.M_w0U1s()) return;
int[] _OL0;
while ( null.RN) {
return;
}
boolean HoUuN;
int aT2lpUqoT81;
return;
;
{
boolean uyvp;
}
pqYDcjlZsTv[][] AstC;
void mU5cG8;
int[][][] ZSW3;
}
int KRejZU = -!--!true[ !!true.YAsgW] = !!!new boolean[ false.jt20MIjXFOAK5Z()].XG();
return --!( !--12856357[ !null.sGzr3])[ -( !-!t5j_kOi.p4kFX7g86M()).hczZ()];
!true.gHSFC1Gv5nC();
{
while ( !true.TNrTf2DIrYQ()) return;
boolean[][] jPKfO;
boolean[][][] rXxu1TtkIof3t_;
tUh[] URxfqQVmwomA;
if ( this.XHGT2O()) --!!new XHP_0GLq1nR().DoI();
boolean NedPAK;
{
JyRLDD[] TiXIyd;
}
OKF1lOZfpW[][] eDe8;
int QAnUynIM8dut;
nBs6XaO g3rBIjRAZGoLC;
void Lga2skVKKPU;
;
int Z5OXEN;
while ( -!F5eSkL902[ this.ry5wXgl324R()]) while ( !!this.o9ly3K36g5()) ;
return;
int[] Cb0omICQgQ;
boolean woNR;
!!-new AQ().zL6pivOS8();
boolean l3mtYuPj;
void[] u559;
}
}
public static void xgn2shbLSBoIDo (String[] T) throws KGMIJO {
boolean[][][][] e06Be = -gbSK9Bjdguxnku().B5h47vs();
-new boolean[ !wmItPopi9_08n9()[ this[ R.b()]]][ !!!!16[ !!new d()[ false[ -this.So7C5KVmIP()]]]];
boolean[] B;
void OQ7Uy7DG;
int[][][][][][] sX;
return;
return ----!--!-new boolean[ !-!!this.yV][ 02299[ n5F8oE_IoR().F__J6dZLJ]];
if ( -null.xGD) {
if ( this[ ( !!( V().h8x())[ 0[ -!false.E()]]).X()]) ;
}else if ( true.aEf9e) {
boolean TV;
}
}
public MWM[] iQQXAjlEsSi_ (int Cj9H, artF3DXd0Y[] lStwikisO7O9, void[][][][] jjUCBd05o2Ed, void yOB, boolean[][][][] v67sw4) {
HX[] rTWWgPVUxjm = true.X5xN1ifCmf7r() = EHDgHzdnrANMcU[ --this[ 248[ !( 2983040.Od).HisTDir()]]];
m2Zk3XrybQ I;
boolean[][] WFeJNHNs2X = this[ !new void[ true[ ---!!!!!-new void[ eOS9UqTNakRShG.aOHzKhu3Ka][ this.MBgLgq2Rxir]]][ new int[ !-!this.HTvkj8Q51Tlm4()][ !new boolean[ 64911[ !!!null.auQUun7Qqv]][ false.CNzIOTxvJJ]]]];
return !!( this[ -this.arkSGO_Iki])[ WphszGFbOUQRv.USC6XPZhVo_s()];
boolean[][][][] cHyyeblYIwf = gvTokbxuwHpWT.Njz3uD962cB();
int f_t9 = -g3z3f3().dk0eMEX() = -new aBSixl_IhVNfA4().bzuM24qWqwMIE();
;
;
;
void[] pJG9co5s = !!false[ !!!( 91642.OaaM9BVX6())[ -!!-d_tLWP()[ !-false[ -new Jk[ null[ rn4FJXJf2v.oLJCArIkbUDC]].Apvlf()]]]];
;
OrYmqAvyVjf3N[][][] IBa6 = -!--79.jz8ecRmftz = null.cQ();
int[] tn = !ZXgKtTQmhDCSdm.B2vH5zRbLo8 = !--Prg_tDc2UgPFg4.X1PXTznl();
void BC65 = new N2NFR()[ false.tRv5bn()] = ( TjFa2i().K6a()).MiAiN;
boolean mmxXlCDyYRC7;
while ( Rek4l1gsjjs9ai.DD5wNmNN4D()) ;
( 578[ -Wsgc_j84dX[ !false.rH03byL()]])[ -!( --!--( null.vz_FTVkH).ZZclGvjvQ9J()).VMQ5vYISHO()];
;
{
int o;
{
uA5[][] I4XUsmqsVg9t;
}
void EWsDqjBde;
{
boolean[] tCZqoEFDWPgk;
}
;
boolean[][][] gLKOB7usn;
if ( -new int[ vOCdTLsB()[ InUoC2PMRkL_[ !-false.mp2e9C]]][ RVqUTs9Tn1pp().G559fSh()]) while ( !true.wrVcpI_()) while ( new boolean[ --Z793BWd0nL7.QLwvb1HwOSnqpW()][ -( !new JviOxMlQmZPMn().K).NfS4xubTcaVd()]) !122769.EMPrbe;
b4P3MkLeF[][] RKAL9TqA;
goe m;
boolean[] hoHoo9GJSKP;
if ( true.mefyABREyj7y()) ;
;
int[] TTl5Ai87Y0EK;
{
return;
}
if ( !-eCpZ().XeLxJpq()) while ( --new boolean[ -!!new Osmqy6DFU()[ -!!--this.uEoWkZEH]][ -!!!true.vSEz]) this[ 2.htttcgfvmO];
Z1GPq[][] Sq0ya2bi5nbkjv;
m _ltN9coVG;
}
int Az;
}
public boolean[] gzB;
}
class p {
}
class sBIDMlZoUW {
public static void TSB (String[] lFAla) throws ZeBqOQ {
void[] Yasyce_m97v;
}
public boolean LXspjgJr_Nprms (uWdh2ajOAF8[] CbWyukEr6Rg, void WVoHIfA, void WscWl) {
while ( false[ this.GZg()]) ;
iY8_ohUs ej = -!!this[ h8lW1MiWU05KjO().PU_Z()] = -112[ false.jnOzqB4];
if ( --true.kl7xdaN6DCEh()) return;else -( --bUDV8().d2vc1aO0uXiR7).Om9m196C();
;
void[][][] y;
f4NlJyy mxgdLiJp = true.S5 = false.B8C9E();
NB8Ire9MOpP m;
return;
ndvgiV _Jyg;
}
public void[] Ca3Kv;
public int[][] m5ZhTrn_ (boolean[] zSYam, void[][][][][] lyv7S, void p38GTXCaVD0d) throws l96bHmplcxqP {
;
boolean MoSvjWjjmR;
return -new mH()[ false.Nk1lTdragC];
;
boolean Z6;
while ( o.AMWdX) if ( !this.oKCQHK4h()) {
void AdocMfPIPm;
}
boolean EEH8pWlLrd5 = this.QvfnX45spxLaHB();
{
return;
{
;
}
!this.tcRe;
void[] jxLquHKd3NntE;
while ( !!true.BL_eI6GAdE) {
;
}
if ( !!Chce.FjF6GUg()) while ( new Q0MJO().UsOIY()) return;
;
hL[] OT;
}
;
return;
}
public static void ax5iwuhXt1Y3 (String[] LGiA3WJ0Dza) {
Md[][][][] W9bVK;
return;
int fbe6cVBWjY7jf1 = !697222704[ ( !000[ !new int[ !UsRPzmJrfW().dlK8ao3DKo][ -new _7C[ new A8gC5()[ !--( -!!!-new void[ -dD7eLMa.W47IURmewa791()].WMgKtt())[ paVqtJG1y2iO.CyaxQMVuO4R]]].Dng1_9q8()]])[ !-!!null.meRMVP73p5YRgt()]];
MxjJXVyEZ[] SqxZ2iWFgUb;
{
int[][][] wtQCv0JDv;
int UziBwCtQaMMO4E;
-this[ Twcztggx()[ !new xNsbrFC()[ !new kSp[ !!new isof9YS5NfFU2().GVN_We].QBcunUnua]]];
NUZn[] Hb1Qd_5JfYj;
D_v[] Nqh;
boolean[] wo1Khe;
boolean uB1Er5_isBw5V;
YbI8b8vF xIDsygMco58;
return;
boolean vG;
if ( 91970328.i7F7jjzaW()) while ( -55.i()) return;
void yF4Vx;
}
if ( new i().p3AF7ISM42cBD) -new DSpV7NJu()[ new nQfHX().XXSrwO()];
W[][][][][][][][] Qm = 173032.DfmUDTkZ_Hkb = 7698418.B5;
ML9M6YHVZXUk[][] UbndshIHANSUl = -true.Nt1();
boolean[] ERgyQBHk;
}
public int l;
public int[] F8CQrfz8jGn;
public static void u7o (String[] A9WWQ1Z) throws F0eON9STXEyo {
return;
if ( true[ !true.ZerhJkFtrcQHm()]) -!-( this[ !XNpBE_PNAsO[ --new int[ 7.RgNrJ].mldk]]).l5wxrQv5EXgGw9;else if ( new nDCQG2z[ ( this.f).o9udgEQiwYPP()].PJ) return;
boolean XNA4q;
int[][][][][] P3SdIX;
{
if ( --false.OlMu) ;
{
boolean Wy0e745;
}
boolean[][] Cu57Tn7Y;
boolean[] rejuStbOFew;
boolean[] GJouyBN0b;
yMTJD6I()[ false[ --( new cx2aV().yVh3df()).lMk2A_DT1eR]];
;
boolean fVyu;
!!--rwW.qR();
while ( wDH33fpKAP._2w6()) !( ----new int[ -2338[ -null.utz7ZGyAM]].LwQdSh())[ -false.KIE];
int[][] oSwY;
{
int VW;
}
void[] edpALBRiQm9;
boolean Ngn9uT;
{
Ccl42khQNZs[] eJwprPHan;
}
void[][][][] pcGv2VGQ2Osrx;
boolean[][] i23m3vyJtW;
boMB0dtEy3fX2 SVW39Jh9dHfsr;
}
boolean[][] tC;
boolean[][][] PbyeFPMGmu2;
if ( this.We6lHvF()) {
{
return;
}
}else if ( !this.sBt) if ( !!-aZDHvvki63a[ LP7lSpc2Ad().tFDdzHQV3]) while ( this.gEmnRu1) {
XE_9jSjfK[] LK7_FeRZ0;
}
int[][][] NwUxT = -false.jO();
if ( !new cAR5ZQCsk1().u9iHm()) {
return;
}else NIGlz9().F;
{
return;
boolean rt;
int D2cPQp0;
if ( YmCWvW().SHL9oP7) --null.sf4iktocaIU;
{
ocvY6zdruTp60i v;
}
{
;
}
return;
ckKJQV kn2tHi8QIB_1;
void[][] othWCuGAqTRCZ;
if ( ndhvNIg0Cp.EelqvoFEWaRbl) ;
boolean[] vUo;
boolean QGVHLfSgR_;
{
void g7v7Odx;
}
int f6XHVq8_z_v3SG;
}
{
boolean cc;
return;
void[] AUX;
void[] jW3ETqjwZ5;
while ( this.vuVIxmqaBf) new s6vT9O()[ !!!-!-!--!null[ !!6731015.OLuuTEB]];
int VI2o;
boolean[][][] UZkC8;
return;
void YObOP;
while ( fyJKJxs2_()[ !!( false.No_WGq)[ !true.lrh9CY6UR()]]) while ( null[ -Y.bsOjTwdaZ1aJkJ]) if ( !true.GqNyqfStZ()) !new boolean[ !-this.kFbGsQWZeHW][ false.k];
return;
int lNWD;
void[][] x5;
boolean azKwB2kKkpokMR;
true.c5kB42nWUKFC_P();
;
;
;
}
}
public static void OZbC (String[] Rv018U0) {
boolean m4qssu8T94P0s = new int[ ---new Psx78r0Duip5()[ false[ 26596387.BNy3v7_UqGzWnh]]].y2tO;
int Lme_x4q;
cxf[][][] txJ = !( -J8tj4wwIYw7AH7.jVkPPNHCnhb_())[ !ulpP0()[ ( -!-!!-true[ false.StjJqcIu()]).YIZ]] = !-!( -StTNad_N22.sRV_k8).pnzT_HQHVwtGsM();
{
int cl3zYdfDows;
int[][][][][][][][][][][] _Wl38TQJAZSsl;
{
true.nQAAcYJ;
}
( !!true.iaNbB_qBA()).w5DbZIx;
void l9gh;
boolean TOB10QMYI6C;
int f8EaNIU_vjck;
int[][] EH6X;
int[] qNe0qnlgeZk;
int _2vHVRdW3;
return;
if ( !dx5()[ false[ null[ tKgdo9().N()]]]) return;
boolean qCBXd_;
if ( pa.fuUN9ldNGJeg7K) ;
{
rybOJNBgvOraXI DMg98V;
}
;
while ( !-( !H4xv().GlMDv()).ju6EW6FnG()) while ( b2A3fB.rE2uDZWg) ( -nq_S.RA2MkhKQ)[ !( this.F5QnW9Na)[ new boolean[ !-!!!-( ( -new void[ !-false.LDpdPxd()].u7nc_rl1FbP).kVoM).Aqa].brH()]];
int Me54skSHEp3AuB;
boolean[] H03;
int[] w3_1tqJ7c;
}
;
while ( new int[ --!true.e38pvrF5cTM].qX_l7a) while ( --!!!YswwY8FV3gkQ().CNxN3n91I()) return;
{
int[] iI9BS;
int[][] xawg;
int[][] r;
while ( null.OQTJxRwUJNgZ) if ( !( wpUSoeJ().xrJ1pq9lz()).MzTvh()) while ( !null.Vyk) return;
--!-( this[ this.JEQAidcfQ()]).QG8D27CVd8;
}
;
void TGrWJcUzJyQ;
boolean[] lmYOQX3Roz55jc;
-!-7633[ LDN.T66];
while ( !!null.SEd1FM()) ;
AZW[] HIupmyHbdfl = new void[ !true.W()].V_qtp9iu;
int[] jDCB;
while ( -pFihIg().iCbAdfjig()) ;
By9XZ8_z s = --null.Z2GcZ();
int[][][][] _0nkCgNn = TBBYf.C8Rt4loMfmOAF;
void z7OwSFU = !!this[ K().j8euxt2q()] = aOqe6o7ezU2RK().AIutGjoeTEVE();
}
public static void b_nL (String[] gF) throws MJbX {
void[][][] IX6ZB0dWeiB_t;
void[] t = 6113.a8m_eF6QbR8azR;
boolean PPTSOOLm = true.u5dkRcM() = true.OgEAP;
PD3Zw6USqF[] smQXbrpb;
cvsGw0[][][][][][][][] vnOHKwNOMs = !false.rhHg = null[ -true.XZRExR];
void D9LXpIRK1tfAf = !!!-49.tS77PQ6okVh() = this.YP;
;
}
public RgwxWc3MZ6[][][] Kv (k6YOwfo0SkfbM JHkHtNrz2OaR, void Kd5YCDCLCZO, boolean[] b76AtT, pJgObKTNmzCv3[][][] QGfF2cMDNhves, DUIU65Dkjjz wCvfl, void XI, U[] wjB8N) throws g_pX {
{
kA7VI6W[][] OnB;
}
void[] Tq3e = false[ null.oNeR()] = !false.Baj5sX9m();
int GWRZH9AGT4SGKF = -BOeG5fy_yGo6j()[ new sORP4VkYs898y[ --!( 323149681[ -33082.NarZPirhll()]).F4d].fj2HBpH36OQTC1()];
while ( --false.vbYRYcBD4T8C()) return;
return;
void[][] hVmG35Ab;
boolean[][][][] D0e;
void bfb = -( -!null.Hrv).xtH6f() = new uKL1().LQ9G;
void[] N4Mj8SU = this.jR7wDsWBd01H() = sJkcqI.xBnPyu8;
N()[ !-ud()[ this.hSV2q()]];
int x = --this.qcP3E26RF2t5W() = true[ new int[ -!4098.Y][ -( false.W_2A0s3cgTA()).g]];
int[][][] qU7XX3CwgB94;
null.JuAqIJ_IjW4LB();
if ( -this.zvDvXIyt) !-h4TMluxCd8Ibtv[ 93.RbF1];else if ( pJPy7daoe()[ -this[ -uEKHLGDyw.Yr6lK6Jy]]) false.KFw8qlw9KpvJ;
aEJj UqmKbvR = --( !null[ null.z7J_c()])[ aVPO7().EiS2InLs];
gfpv[][][][][] mG9qiuB8z_tM8 = wV9wot3BB.XvHfxBnwOg() = !new void[ -( new ZD[ true.OK7()].uQ20oxgu2lHO).ZxBdTbvgKbDll6()].wMiQsqLQL();
}
}
|
3e09d7b40e6b446687c66be2da3dc9d7f878bba0 | 1,932 | java | Java | app/src/main/java/ws/mochaa/biometricpay/view/MessageView.java | traidento/FingerprintPay | d17f6e7960989680930361ccc8763ff78a2d5915 | [
"BSD-2-Clause"
] | null | null | null | app/src/main/java/ws/mochaa/biometricpay/view/MessageView.java | traidento/FingerprintPay | d17f6e7960989680930361ccc8763ff78a2d5915 | [
"BSD-2-Clause"
] | 1 | 2022-01-08T07:36:44.000Z | 2022-01-08T07:36:44.000Z | app/src/main/java/ws/mochaa/biometricpay/view/MessageView.java | traidento/BiometricPay | d17f6e7960989680930361ccc8763ff78a2d5915 | [
"BSD-2-Clause"
] | null | null | null | 26.833333 | 98 | 0.687888 | 4,163 | package ws.mochaa.biometricpay.view;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import ws.mochaa.biometricpay.Lang;
import ws.mochaa.biometricpay.R;
import ws.mochaa.biometricpay.util.DpUtils;
import ws.mochaa.biometricpay.util.StyleUtils;
/**
* Created by Jason on 2021/8/29.
*/
public class MessageView extends DialogFrameLayout {
private TextView mMessageText;
private String mTitle;
public MessageView(@NonNull Context context) {
super(context);
init(context);
}
public MessageView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MessageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mMessageText = new TextView(context);
int paddingH = DpUtils.dip2px(context, 20);
mMessageText.setPadding(paddingH, DpUtils.dip2px(context, 5), paddingH, 0);
StyleUtils.apply(mMessageText);
this.addView(mMessageText);
withPositiveButtonText(Lang.getString(R.id.ok));
}
public MessageView text(CharSequence s) {
mMessageText.setText(s);
return this;
}
public MessageView title(String s) {
mTitle = s;
return this;
}
@Override
public String getDialogTitle() {
String title = mTitle;
return TextUtils.isEmpty(title) ? Lang.getString(R.string.app_name) : title;
}
@Override
public AlertDialog showInDialog() {
AlertDialog dialog = super.showInDialog();
dialog.setCancelable(false);
return dialog;
}
}
|
3e09d7e710fbe9b10e850e71ff9d134c8bd531bc | 630 | java | Java | src/main/java/com/aryaman/load/CheckDate.java | Aryaman91999/Load-Inventory-Manager | e412faede98eb839e0a9963fbd46aa3d468615a2 | [
"MIT"
] | null | null | null | src/main/java/com/aryaman/load/CheckDate.java | Aryaman91999/Load-Inventory-Manager | e412faede98eb839e0a9963fbd46aa3d468615a2 | [
"MIT"
] | null | null | null | src/main/java/com/aryaman/load/CheckDate.java | Aryaman91999/Load-Inventory-Manager | e412faede98eb839e0a9963fbd46aa3d468615a2 | [
"MIT"
] | null | null | null | 39.375 | 380 | 0.45873 | 4,164 | package com.aryaman.load;
import java.util.regex.Pattern;
public class CheckDate {
private final Pattern pattern;
public CheckDate() {
pattern = Pattern.compile("^(?:(?:31(x\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[13-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$");
}
public boolean check(String date) {
return pattern.matcher(date).matches();
}
}
|
3e09d825d15df19307d50ce3b54258073d78c0af | 5,983 | java | Java | src/main/java/com/xero/models/payroll/PayTemplate.java | FullStopAccounts/Xero-Java | 5add1395a83f9cbe45638555a25cb43f19906f01 | [
"MIT"
] | null | null | null | src/main/java/com/xero/models/payroll/PayTemplate.java | FullStopAccounts/Xero-Java | 5add1395a83f9cbe45638555a25cb43f19906f01 | [
"MIT"
] | null | null | null | src/main/java/com/xero/models/payroll/PayTemplate.java | FullStopAccounts/Xero-Java | 5add1395a83f9cbe45638555a25cb43f19906f01 | [
"MIT"
] | null | null | null | 30.065327 | 134 | 0.73408 | 4,165 | /*
* Payroll API
*/
package com.xero.models.payroll;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.xero.models.accounting.ValidationError;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* PayTemplates
*/
public class PayTemplate {
@JsonProperty("employeeID")
private UUID employeeID;
@JsonProperty("earningTemplates")
private List<EarningsTemplate> earningTemplates;
@JsonProperty("deductionTemplates")
private List<EarningsTemplate> deductionTemplates;
@JsonProperty("benefitTemplates")
private List<EarningsTemplate> benefitTemplates;
@JsonProperty("reimbursementTemplates")
private List<EarningsTemplate> reimbursementTemplates;
@JsonProperty("validationErrors")
private List<ValidationError> validationErrors = null;
public PayTemplate employeeID(UUID employeeID) {
this.employeeID = employeeID;
return this;
}
/**
* The Xero identifier for payroll employee
* @return employeeID
**/
@ApiModelProperty(value = "The Xero identifier for payroll employee")
public UUID getEmployeeID() {
return employeeID;
}
public void setEmployeeID(UUID employeeID) {
this.employeeID = employeeID;
}
public PayTemplate earningTemplates(List<EarningsTemplate> earningTemplates) {
this.earningTemplates = earningTemplates;
return this;
}
/**
* See EarningsTemplate
* @return earningTemplates
**/
@ApiModelProperty(value = "See EarningsTemplate")
public List<EarningsTemplate> getEarningTemplates() {
return earningTemplates;
}
public void setEarningTemplates(List<EarningsTemplate> earningTemplates) {
this.earningTemplates = earningTemplates;
}
public PayTemplate deductionTemplates(List<EarningsTemplate> deductionTemplates) {
this.deductionTemplates = deductionTemplates;
return this;
}
/**
* future
* @return deductionTemplates
**/
@ApiModelProperty(value = "future")
public List<EarningsTemplate> getDeductionTemplates() {
return deductionTemplates;
}
public void setDeductionTemplates(List<EarningsTemplate> deductionTemplates) {
this.deductionTemplates = deductionTemplates;
}
public PayTemplate benefitTemplates(List<EarningsTemplate> benefitTemplates) {
this.benefitTemplates = benefitTemplates;
return this;
}
/**
* future
* @return deductionTemplates
**/
@ApiModelProperty(value = "future")
public List<EarningsTemplate> getBenefitTemplates() {
return benefitTemplates;
}
public void setBenefitTemplates(List<EarningsTemplate> benefitTemplates) {
this.benefitTemplates = benefitTemplates;
}
public PayTemplate reimbursementTemplates(List<EarningsTemplate> reimbursementTemplates) {
this.reimbursementTemplates = reimbursementTemplates;
return this;
}
/**
* future
* @return deductionTemplates
**/
@ApiModelProperty(value = "future")
public List<EarningsTemplate> getReimbursementTemplates() {
return reimbursementTemplates;
}
public void setReimbursementTemplates(List<EarningsTemplate> reimbursementTemplates) {
this.reimbursementTemplates = reimbursementTemplates;
}
public PayTemplate validationErrors(List<ValidationError> validationErrors) {
this.validationErrors = validationErrors;
return this;
}
public PayTemplate addValidationErrorsItem(ValidationError validationErrorsItem) {
if (this.validationErrors == null) {
this.validationErrors = new ArrayList<ValidationError>();
}
this.validationErrors.add(validationErrorsItem);
return this;
}
/**
* Displays array of validation error messages from the API
* @return validationErrors
**/
@ApiModelProperty(value = "Displays array of validation error messages from the API")
public List<ValidationError> getValidationErrors() {
return validationErrors;
}
public void setValidationErrors(List<ValidationError> validationErrors) {
this.validationErrors = validationErrors;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PayTemplate payTemplate = (PayTemplate) o;
return Objects.equals(this.employeeID, payTemplate.employeeID) &&
Objects.equals(this.earningTemplates, payTemplate.earningTemplates) &&
Objects.equals(this.deductionTemplates, payTemplate.deductionTemplates) &&
Objects.equals(this.benefitTemplates, payTemplate.benefitTemplates) &&
Objects.equals(this.reimbursementTemplates, payTemplate.reimbursementTemplates) &&
Objects.equals(this.validationErrors, payTemplate.validationErrors);
}
@Override
public int hashCode() {
return Objects.hash(employeeID, earningTemplates, deductionTemplates, benefitTemplates, reimbursementTemplates, validationErrors);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PayTemplate {\n");
sb.append(" employeeID: ").append(toIndentedString(employeeID)).append("\n");
sb.append(" earningTemplates: ").append(toIndentedString(earningTemplates)).append("\n");
sb.append(" deductionTemplates: ").append(toIndentedString(deductionTemplates)).append("\n");
sb.append(" benefitTemplates: ").append(toIndentedString(benefitTemplates)).append("\n");
sb.append(" reimbursementTemplates: ").append(toIndentedString(reimbursementTemplates)).append("\n");
sb.append(" validationErrors: ").append(toIndentedString(validationErrors)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e09d82a938a4ae65fcaeda120fef0d028691b89 | 209 | java | Java | corpus/class/eclipse.jdt.ui/9301.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/eclipse.jdt.ui/9301.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/eclipse.jdt.ui/9301.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 11.611111 | 42 | 0.526316 | 4,166 | package p;
class A {
B fB;
public void doit(String doitArg) {
subroutine(1.2f);
}
public void subroutine(float subArg) {
subsub();
}
public void subsub() {
}
}
|
3e09d86a213a7d6defdff7aad49defbc03c7c71e | 2,560 | java | Java | src/main/java/fr/laposte/sv/project/back/controller/CorrespondantController.java | robthebear/sv.project.back | 7fcb8f83e17b5e08bc6f71cb8a298c7d7790559f | [
"MIT"
] | null | null | null | src/main/java/fr/laposte/sv/project/back/controller/CorrespondantController.java | robthebear/sv.project.back | 7fcb8f83e17b5e08bc6f71cb8a298c7d7790559f | [
"MIT"
] | 1 | 2020-03-31T10:16:56.000Z | 2020-03-31T10:16:56.000Z | src/main/java/fr/laposte/sv/project/back/controller/CorrespondantController.java | robthebear/sv.project.back | 7fcb8f83e17b5e08bc6f71cb8a298c7d7790559f | [
"MIT"
] | null | null | null | 34.594595 | 136 | 0.733594 | 4,167 | package fr.laposte.sv.project.back.controller;
import fr.laposte.sv.project.back.model.Correspondant;
import fr.laposte.sv.project.back.repository.CorrespondantRepository;
import fr.laposte.sv.project.back.service.CorrespondantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Collection;
import java.util.Optional;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/correspondant")
public class CorrespondantController {
@Autowired
private CorrespondantRepository correspondantRepository;
@Autowired
private CorrespondantService correspondantService;
@GetMapping
public Collection<Correspondant> findAll() {
return correspondantRepository.findAll();
}
@GetMapping("/id/{id}")
public Optional<Correspondant> findById(@PathVariable String id) {
return correspondantRepository.findById(id);
}
@GetMapping("/{nom}")
public Optional<Correspondant> findByNom(@PathVariable String nom) {
return correspondantRepository.findByNom(nom);
}
@GetMapping("/{fonction}")
public Optional<Correspondant> findByFonction(@PathVariable String fonction) {
return correspondantRepository.findByFonction(fonction);
}
@GetMapping("/{email}")
public Optional<Correspondant> findByEmail(@PathVariable String email) {
return correspondantRepository.findByEmail(email);
}
@DeleteMapping("/{id}")
public void delCorrespondant(@PathVariable String id) {
Optional<Correspondant> optionalCorrespondant = correspondantRepository.findById(id);
if (optionalCorrespondant.isPresent()) {
correspondantRepository.deleteById(id);
System.out.print("Correspondant supprimé");
// } else {
// System.out.print("Pas de correspondant à supprimer");
}
}
// @PutMapping("/update")
// public ResponseEntity<Correspondant> updateCorrespondant(@RequestBody(required = false) Correspondant correspondant) {
// System.out.println(correspondant);
// return correspondantService.updateCorrespondant(correspondant);
// }
@PutMapping("/update/{id}")
public ResponseEntity<Correspondant> updateCorrespondant(@PathVariable String id, @Valid @RequestBody Correspondant correspondant) {
return correspondantService.updateCorrespondant(id, correspondant);
}
}
|
3e09d8812bf9aef7fe6f02c2fded2d088bd3784e | 960 | java | Java | app/src/main/java/com/example/hahaha/musicplayer/feature/common/CollectViewHolder.java | nh632343/MusicPlayer | 7ff7cf3b874a892fea1b7af26fb2342669bbf037 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/hahaha/musicplayer/feature/common/CollectViewHolder.java | nh632343/MusicPlayer | 7ff7cf3b874a892fea1b7af26fb2342669bbf037 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/hahaha/musicplayer/feature/common/CollectViewHolder.java | nh632343/MusicPlayer | 7ff7cf3b874a892fea1b7af26fb2342669bbf037 | [
"Apache-2.0"
] | null | null | null | 34.285714 | 88 | 0.792708 | 4,168 | package com.example.hahaha.musicplayer.feature.common;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.example.hahaha.musicplayer.R;
import com.example.hahaha.musicplayer.app.MusicApp;
import com.example.hahaha.musicplayer.feature.base.BaseViewHolder;
import com.example.hahaha.musicplayer.model.entity.internal.Collect;
public class CollectViewHolder extends BaseViewHolder<Collect> {
@BindView(R.id.txt_collect_name) TextView mTxtCollectName;
@BindView(R.id.txt_num) TextView mTxtNum;
public CollectViewHolder(Context context, ViewGroup parent) {
super(context, parent, R.layout.item_collect);
}
@Override public void bindTo(int position, Collect value) {
mTxtCollectName.setText(value.getName());
mTxtNum.setText(
MusicApp.appResources().getString(R.string.collect_song_num, value.getSongNum())
);
}
}
|
3e09d8b08e0d0608909a73711d212222d706c233 | 1,031 | java | Java | opensrp-chw-anc/src/main/java/org/smartregister/chw/anc/listener/BaseAncBottomNavigationListener.java | opensrp/opensrp-client-chw-anc | f4726a3109e5b599fd045861b233f12d2f7b75d2 | [
"Apache-2.0"
] | null | null | null | opensrp-chw-anc/src/main/java/org/smartregister/chw/anc/listener/BaseAncBottomNavigationListener.java | opensrp/opensrp-client-chw-anc | f4726a3109e5b599fd045861b233f12d2f7b75d2 | [
"Apache-2.0"
] | 318 | 2019-04-12T06:58:24.000Z | 2020-10-02T08:54:47.000Z | opensrp-chw-anc/src/main/java/org/smartregister/chw/anc/listener/BaseAncBottomNavigationListener.java | opensrp/opensrp-client-chw-anc | f4726a3109e5b599fd045861b233f12d2f7b75d2 | [
"Apache-2.0"
] | 2 | 2019-05-20T09:49:04.000Z | 2019-10-12T07:54:20.000Z | 31.242424 | 83 | 0.739088 | 4,169 | package org.smartregister.chw.anc.listener;
import android.app.Activity;
import androidx.annotation.NonNull;
import android.view.MenuItem;
import org.smartregister.chw.opensrp_chw_anc.R;
import org.smartregister.listener.BottomNavigationListener;
import org.smartregister.view.activity.BaseRegisterActivity;
public class BaseAncBottomNavigationListener extends BottomNavigationListener {
private Activity context;
public BaseAncBottomNavigationListener(Activity context) {
super(context);
this.context = context;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
super.onNavigationItemSelected(item);
BaseRegisterActivity baseRegisterActivity = (BaseRegisterActivity) context;
if (item.getItemId() == R.id.action_family) {
baseRegisterActivity.switchToBaseFragment();
} else if (item.getItemId() == R.id.action_scan_qr) {
baseRegisterActivity.startQrCodeScanner();
}
return true;
}
} |
3e09d8d2c58a9cee2003a19e921d949506d5d8eb | 1,683 | java | Java | lichkin-framework-utils/src/main/java/com/lichkin/framework/utils/LKRandomUtils.java | LichKinContributor/lichkin-framework | 855d919e0a8bbdc08e0e2d7e4482dd1af288eb9c | [
"MIT"
] | null | null | null | lichkin-framework-utils/src/main/java/com/lichkin/framework/utils/LKRandomUtils.java | LichKinContributor/lichkin-framework | 855d919e0a8bbdc08e0e2d7e4482dd1af288eb9c | [
"MIT"
] | null | null | null | lichkin-framework-utils/src/main/java/com/lichkin/framework/utils/LKRandomUtils.java | LichKinContributor/lichkin-framework | 855d919e0a8bbdc08e0e2d7e4482dd1af288eb9c | [
"MIT"
] | null | null | null | 22.144737 | 116 | 0.713607 | 4,170 | package com.lichkin.framework.utils;
import java.util.Random;
import com.lichkin.framework.defines.enums.LKPairEnum;
import com.lichkin.framework.defines.enums.impl.LKDateTimeTypeEnum;
import com.lichkin.framework.defines.enums.impl.LKRangeTypeEnum;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* 随机数工具类
* @author SuZhou LichKin Information Technology Co., Ltd.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LKRandomUtils {
/**
* 生成随机字符串(数字(常用)和字母(常用))
* @param length 字符串长度
* @return 随机字符串
*/
public static String create(final int length) {
return create(length, LKRangeTypeEnum.NUMBER_NORMAL_AND_LETTER_NORMAL);
}
/**
* 生成随机数字符串
* @param length 字符串长度
* @return 随机字符串
*/
public static String createNumber(final int length) {
return create(length, LKRangeTypeEnum.NUMBER_WITHOUT_ZERO);
}
/**
* 生成随机字符串
* @param length 字符串长度
* @param rangeTypeEnum 取值范围枚举
* @return 随机字符串
*/
public static String create(final int length, final LKPairEnum rangeTypeEnum) {
final String rangeStr = rangeTypeEnum.getName();
final char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
result[i] = rangeStr.charAt(randomInRange(0, rangeStr.length() - 1));
}
return new String(result);
}
/**
* 生成随机值
* @param min 最小值
* @param max 最大值
* @return 随机值
*/
public static int randomInRange(int min, int max) {
return new Random().nextInt((max + 1) - min) + min;
}
/**
* 创建17位时间戳+47位随机数
* @return 64位字符串
*/
public static String create64() {
return LKDateTimeUtils.now(LKDateTimeTypeEnum.TIMESTAMP_MIN) + create(47, LKRangeTypeEnum.NUMBER_AND_LETTER_FULL);
}
}
|
3e09db27f58f48ca0b68872eb830c00c9fb960ae | 14,516 | java | Java | igloo/igloo-components/igloo-component-jpa/src/main/java/org/iglooproject/jpa/batch/executor/SimpleHibernateBatchExecutor.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 17 | 2017-10-19T07:03:44.000Z | 2022-01-17T20:44:22.000Z | igloo/igloo-components/igloo-component-jpa/src/main/java/org/iglooproject/jpa/batch/executor/SimpleHibernateBatchExecutor.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 38 | 2018-01-22T15:57:35.000Z | 2022-01-14T16:28:45.000Z | igloo/igloo-components/igloo-component-jpa/src/main/java/org/iglooproject/jpa/batch/executor/SimpleHibernateBatchExecutor.java | igloo-project/igloo-parent | bd4ef874aad99e96b9b1bc3ebf9f74db5f41f999 | [
"Apache-2.0"
] | 6 | 2017-10-19T07:03:50.000Z | 2020-08-06T16:12:35.000Z | 35.404878 | 130 | 0.742422 | 4,171 | package org.iglooproject.jpa.batch.executor;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.SimpleTransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionOperations;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.iglooproject.functional.Joiners;
import org.iglooproject.jpa.batch.runnable.IBatchRunnable;
import org.iglooproject.jpa.batch.runnable.Writeability;
import org.iglooproject.jpa.batch.util.IBeforeClearListener;
import org.iglooproject.jpa.business.generic.model.GenericEntity;
import org.iglooproject.jpa.business.generic.model.GenericEntityCollectionReference;
import org.iglooproject.jpa.exception.ServiceException;
import org.iglooproject.jpa.query.IQuery;
import org.iglooproject.jpa.query.Queries;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SimpleHibernateBatchExecutor extends AbstractBatchExecutor<SimpleHibernateBatchExecutor> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleHibernateBatchExecutor.class);
@Autowired(required = false)
private Collection<IBeforeClearListener> clearListeners = ImmutableList.of();
private ExecutionStrategyFactory executionStrategyFactory = ExecutionStrategyFactory.COMMIT_ON_END;
private List<Class<?>> classesToReindex = Lists.newArrayListWithCapacity(0);
/**
* Use one transaction for the whole execution, periodically flushing the Hibernate session and the Hibernate Search
* indexes.
* <p>This is the default.
* <p>If an error occurs, this strategy will leave the database unchanged (with no modification), but <strong>will
* leave Hibernate Search indexes half-changed</strong> (with only the changes of the successfully executed
* previous steps).
* <p>Thus this strategy is fully transactional, but may <strong>corrupt your indexes</strong> on error, leaving
* them out-of-sync with your database. This requires particular caution when handling errors (for instance full
* reindex).
*/
public SimpleHibernateBatchExecutor commitOnEnd() {
this.executionStrategyFactory = ExecutionStrategyFactory.COMMIT_ON_END;
return this;
}
/**
* Use one transaction for each step of the execution:
* <ul>
* <li>{@link IBatchRunnable#preExecute()}</li>
* <li>each {@link IBatchRunnable#executePartition(List)}
* <li>{@link IBatchRunnable#postExecute()}</li>
* </ul>
* <p>If an error occurs, this strategy will leave the database and the Hibernate Search indices half-changed
* (with only the changes of the successfully executed previous steps).
* <p>Thus this strategy <strong>is not fully transactional</strong>, but will ensure your indexes stay in sync
* with your database on error.
*/
public SimpleHibernateBatchExecutor commitOnStep() {
this.executionStrategyFactory = ExecutionStrategyFactory.COMMIT_ON_STEP;
return this;
}
/**
* Triggers a full reindex of the given classes at the end of the execution.
* <p>Mostly useful when using {@link #commitOnEnd()} transaction strategy.
*/
public SimpleHibernateBatchExecutor reindexClasses(Class<?> clazz, Class<?>... classes) {
classesToReindex = Lists.asList(clazz, classes);
return this;
}
/**
* Runs a batch execution against a given list of entities (given by their IDs).
*/
public <E extends GenericEntity<Long, ?>> void run(final Class<E> clazz, final List<Long> entityIds,
final IBatchRunnable<E> batchRunnable) {
GenericEntityCollectionReference<Long, E> reference =
new GenericEntityCollectionReference<>(clazz, entityIds);
runNonConsuming(String.format("class %s", clazz), entityService.getQuery(reference), batchRunnable);
}
/**
* Runs a batch execution against a {@link IQuery query}'s result, <strong>expecting that the execution
* won't change the query's results</strong>.
* <p>This last requirement allows us to safely break down the execution this way:
* first execute on <code>query.list(0, 100)</code>, then (if there was a result) <code>query.list(100, 100)</code>,
* and so on.
* <p>The <code>query</code> may be:
* <ul>
* <li>Your own implementation (of IQuery, or more particularly of ISearchQuery)
* <li>Retrieved from a DAO that used {@link Queries#fromQueryDsl(com.querydsl.core.support.FetchableQueryBase)} to
* adapt a QueryDSL query
* </ul>
*/
public <E extends GenericEntity<Long, ?>> void runNonConsuming(String loggerContext, final IQuery<E> query,
final IBatchRunnable<E> batchRunnable) {
doRun(loggerContext, query, false, batchRunnable);
}
/**
* Runs a batch execution against a {@link IQuery query}'s result, <strong>expecting that the execution
* will remove all processed elements from the query's results</strong>.
* <p>This last requirement allows us to safely break down the execution this way:
* first execute on <code>query.list(0, 100)</code>, then (if there was a result) execute on
* <code>query.list(0, 100)</code> <strong>again</strong>, and so on.
* <p>The <code>query</code> may be:
* <ul>
* <li>Your own implementation (of IQuery, or more particularly of ISearchQuery)
* <li>Retrieved from a DAO that used {@link Queries#fromQueryDsl(com.querydsl.core.support.FetchableQueryBase)} to
* adapt a QueryDSL query
* </ul>
*/
public <E extends GenericEntity<Long, ?>> void runConsuming(String loggerContext, final IQuery<E> query,
final IBatchRunnable<E> batchRunnable) {
Preconditions.checkArgument(
Writeability.READ_WRITE.equals(batchRunnable.getWriteability()),
"runConsuming() must be used with a read/write runnable, but %s is read-only", batchRunnable
);
doRun(loggerContext, query, true, batchRunnable);
}
private <E extends GenericEntity<Long, ?>> void doRun(final String loggerContext, final IQuery<E> query, final boolean consuming,
final IBatchRunnable<E> batchRunnable) {
final ExecutionStrategy<E> executionStrategy = executionStrategyFactory.create(this, query, batchRunnable);
executionStrategy.getExecuteTransactionOperations().execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
doRun(executionStrategy, loggerContext, consuming);
}
});
}
private <E extends GenericEntity<Long, ?>> void doRun(ExecutionStrategy<E> executionStrategy, String loggerContext,
boolean consuming) {
long expectedTotalCount = executionStrategy.getExpectedTotalCount();
long offset = 0;
LOGGER.info("Beginning batch for %1$s: %2$d objects", loggerContext, expectedTotalCount);
try {
LOGGER.info(" preExecute start");
try {
executionStrategy.preExecute();
} catch (RuntimeException e) {
throw new ExecutionException("Exception on preExecute", e);
}
LOGGER.info(" preExecute end");
LOGGER.info(" starting batch executions");
try {
int partitionSize;
do {
partitionSize = executionStrategy.executePartition(
// Don't use the offset if the runnable is consuming the query's results
consuming ? 0 : offset, batchSize
);
offset += partitionSize;
LOGGER.info(" treated %1$d/%2$d objects", offset, expectedTotalCount);
} while (partitionSize > 0);
} catch (RuntimeException e) {
throw new ExecutionException("Exception on executePartition", e);
}
LOGGER.info(" end of batch executions");
LOGGER.info(" postExecute start");
try {
executionStrategy.postExecute();
} catch (RuntimeException e) {
throw new ExecutionException("Exception on postExecute", e);
}
LOGGER.info(" postExecute end");
if (classesToReindex.size() > 0) {
LOGGER.info(" reindexing classes %1$s", Joiners.onComma().join(classesToReindex));
try {
hibernateSearchService.reindexClasses(classesToReindex);
} catch (ServiceException e) {
LOGGER.error(" reindexing failure", e);
}
LOGGER.info(" end of reindexing");
}
LOGGER.info("End of batch for %1$s: %2$d/%3$d objects treated", loggerContext, offset, expectedTotalCount);
} catch (ExecutionException e) {
LOGGER.info("End of batch for %1$s: %2$d/%3$d objects treated, but caught exception '%s'",
loggerContext, offset, expectedTotalCount, e);
try {
LOGGER.info(" onError start");
executionStrategy.onError(e);
LOGGER.info(" onError end (exception was NOT propagated)");
} catch (RuntimeException e2) {
LOGGER.info(" onError end (exception WAS propagated)");
throw e2;
}
}
}
protected <E extends GenericEntity<Long, ?>> List<E> listEntitiesByIds(Class<E> clazz, Collection<Long> entityIds) {
return entityService.listEntity(clazz, entityIds);
}
@Override
protected SimpleHibernateBatchExecutor thisAsT() {
return this;
}
private enum ExecutionStrategyFactory {
COMMIT_ON_STEP {
@Override
<T> ExecutionStrategy<T> create(SimpleHibernateBatchExecutor executor, IQuery<T> query,
IBatchRunnable<T> runnable) {
return new CommitOnStepExecutionStrategy<>(executor, query, runnable);
}
},
COMMIT_ON_END {
@Override
<T> ExecutionStrategy<T> create(SimpleHibernateBatchExecutor executor, IQuery<T> query,
IBatchRunnable<T> runnable) {
return new CommitOnEndExecutionStrategy<>(executor, query, runnable);
}
};
abstract <T> ExecutionStrategy<T> create(SimpleHibernateBatchExecutor executor, IQuery<T> query, IBatchRunnable<T> runnable);
}
private abstract static class ExecutionStrategy<T> {
protected final SimpleHibernateBatchExecutor executor;
protected final IQuery<T> query;
protected final IBatchRunnable<T> runnable;
public ExecutionStrategy(SimpleHibernateBatchExecutor executor, IQuery<T> query, IBatchRunnable<T> runnable) {
super();
this.executor = executor;
this.query = query;
this.runnable = runnable;
}
public abstract TransactionOperations getExecuteTransactionOperations();
public abstract long getExpectedTotalCount();
public abstract void preExecute();
/**
* @param offset
* @param limit
* @return The number of items in the partition.
*/
public abstract int executePartition(long offset, long limit);
public abstract void postExecute();
public void onError(ExecutionException e) {
runnable.onError(e);
}
}
private final static class CommitOnEndExecutionStrategy<T> extends ExecutionStrategy<T> {
private final boolean isReadOnly = Writeability.READ_ONLY.equals(runnable.getWriteability());
private CommitOnEndExecutionStrategy(SimpleHibernateBatchExecutor executor, IQuery<T> query,
IBatchRunnable<T> runnable) {
super(executor, query, runnable);
}
@Override
public TransactionOperations getExecuteTransactionOperations() {
return executor.newTransactionTemplate(
runnable.getWriteability(), TransactionDefinition.PROPAGATION_REQUIRED
);
}
@Override
public long getExpectedTotalCount() {
return query.count();
}
private void afterStep() {
if (!isReadOnly) {
executor.entityService.flush();
}
for (IBeforeClearListener beforeClearListener : executor.clearListeners) {
beforeClearListener.beforeClear();
}
if (!isReadOnly) {
executor.hibernateSearchService.flushToIndexes();
}
executor.entityService.clear();
}
@Override
public void preExecute() {
runnable.preExecute();
afterStep();
}
@Override
public int executePartition(long offset, long limit) {
final List<T> partition = query.list(offset, limit);
int partitionSize = partition.size();
if (partitionSize > 0) {
runnable.executePartition(partition);
afterStep();
}
return partitionSize;
}
@Override
public void postExecute() {
runnable.postExecute();
afterStep();
}
}
private final static class CommitOnStepExecutionStrategy<T> extends ExecutionStrategy<T> {
private final TransactionOperations stepTransactionTemplate = executor.newTransactionTemplate(
runnable.getWriteability(), TransactionDefinition.PROPAGATION_REQUIRES_NEW
);
private CommitOnStepExecutionStrategy(SimpleHibernateBatchExecutor executor, IQuery<T> query,
IBatchRunnable<T> runnable) {
super(executor, query, runnable);
}
@Override
public TransactionOperations getExecuteTransactionOperations() {
return new TransactionOperations() {
@Override
public <T2> T2 execute(TransactionCallback<T2> action) throws TransactionException {
return action.doInTransaction(new SimpleTransactionStatus());
}
};
}
@Override
public long getExpectedTotalCount() {
return stepTransactionTemplate.execute(new TransactionCallback<Long>() {
@Override
public Long doInTransaction(TransactionStatus status) {
return query.count();
}
});
}
@Override
public void preExecute() {
stepTransactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
runnable.preExecute();
}
});
}
@Override
public int executePartition(final long offset, final long limit) {
return stepTransactionTemplate.execute(new TransactionCallback<Integer>() {
@Override
public Integer doInTransaction(TransactionStatus status) {
final List<T> partition = query.list(offset, limit);
int partitionSize = partition.size();
if (partitionSize > 0) {
runnable.executePartition(partition);
}
return partitionSize;
}
});
}
@Override
public void postExecute() {
stepTransactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
runnable.postExecute();
}
});
}
}
}
|
3e09db2d4ab6c335ca29d88f41e249ff4c00f598 | 366 | java | Java | gmall-sms/src/main/java/com/atguigu/gmall/sms/dao/SkuLadderDao.java | LOOSERJ/gmall | c70c84f1cfeabd3976e05c7c3ef4e2c2a8246053 | [
"Apache-2.0"
] | null | null | null | gmall-sms/src/main/java/com/atguigu/gmall/sms/dao/SkuLadderDao.java | LOOSERJ/gmall | c70c84f1cfeabd3976e05c7c3ef4e2c2a8246053 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:06:21.000Z | 2021-09-20T20:57:18.000Z | gmall-sms/src/main/java/com/atguigu/gmall/sms/dao/SkuLadderDao.java | LOOSERJ/gmall | c70c84f1cfeabd3976e05c7c3ef4e2c2a8246053 | [
"Apache-2.0"
] | null | null | null | 20.277778 | 67 | 0.758904 | 4,172 | package com.atguigu.gmall.sms.dao;
import com.atguigu.gmall.sms.entity.SkuLadderEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品阶梯价格
*
* @author dong
* @email anpch@example.com
* @date 2020-03-30 18:58:58
*/
@Mapper
public interface SkuLadderDao extends BaseMapper<SkuLadderEntity> {
}
|
3e09dc1d2f7c77eca1877559b989c7bf42693114 | 290 | java | Java | ezm-server/src/main/java/com/fangjc1986/ezmpro/sys/mapper/UploadMapper.java | fangjc1986/easy-management | a08e746633a50f5229aacb492a6f7c7868c2c855 | [
"MIT"
] | 23 | 2020-05-07T01:17:26.000Z | 2022-02-08T10:09:36.000Z | ezm-server/src/main/java/com/fangjc1986/ezmpro/sys/mapper/UploadMapper.java | fangjc1986/easy-management | a08e746633a50f5229aacb492a6f7c7868c2c855 | [
"MIT"
] | 5 | 2020-12-04T20:29:12.000Z | 2022-02-27T04:14:48.000Z | ezm-server/src/main/java/com/fangjc1986/ezmpro/sys/mapper/UploadMapper.java | fangjc1986/easy-management | a08e746633a50f5229aacb492a6f7c7868c2c855 | [
"MIT"
] | 7 | 2020-05-06T14:31:46.000Z | 2020-09-04T03:07:39.000Z | 17.058824 | 58 | 0.72069 | 4,173 | package com.fangjc1986.ezmpro.sys.mapper;
import com.fangjc1986.ezmpro.sys.model.Upload;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author EricFang
* @since 2020-04-02
*/
public interface UploadMapper extends BaseMapper<Upload> {
}
|
3e09dd1e00b33e0c4e07e5b215d9e7d0eb089435 | 35,070 | java | Java | client/src/main/java/com/bcs/bm/catalog_of_instruments_rudata/client/grpc/InfoFintoolReferenceDataResponse.java | ZacParize/x5 | 602a207e8a3f1b0c472b2977aa4f8bc64038e110 | [
"MIT"
] | null | null | null | client/src/main/java/com/bcs/bm/catalog_of_instruments_rudata/client/grpc/InfoFintoolReferenceDataResponse.java | ZacParize/x5 | 602a207e8a3f1b0c472b2977aa4f8bc64038e110 | [
"MIT"
] | null | null | null | client/src/main/java/com/bcs/bm/catalog_of_instruments_rudata/client/grpc/InfoFintoolReferenceDataResponse.java | ZacParize/x5 | 602a207e8a3f1b0c472b2977aa4f8bc64038e110 | [
"MIT"
] | null | null | null | 39.272116 | 279 | 0.70864 | 4,174 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: GrpcService.proto
package com.bcs.bm.catalog_of_instruments_rudata.client.grpc;
/**
* Protobuf type {@code InfoFintoolReferenceDataResponse}
*/
public final class InfoFintoolReferenceDataResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:InfoFintoolReferenceDataResponse)
InfoFintoolReferenceDataResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use InfoFintoolReferenceDataResponse.newBuilder() to construct.
private InfoFintoolReferenceDataResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private InfoFintoolReferenceDataResponse() {
reqId_ = "";
fintoolReferenceData_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new InfoFintoolReferenceDataResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private InfoFintoolReferenceDataResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
reqId_ = s;
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
fintoolReferenceData_ = new java.util.ArrayList<com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData>();
mutable_bitField0_ |= 0x00000001;
}
fintoolReferenceData_.add(
input.readMessage(com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.parser(), extensionRegistry));
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
fintoolReferenceData_ = java.util.Collections.unmodifiableList(fintoolReferenceData_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.bcs.bm.catalog_of_instruments_rudata.client.grpc.GrpcService.internal_static_InfoFintoolReferenceDataResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.bcs.bm.catalog_of_instruments_rudata.client.grpc.GrpcService.internal_static_InfoFintoolReferenceDataResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse.class, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse.Builder.class);
}
public static final int REQID_FIELD_NUMBER = 1;
private volatile java.lang.Object reqId_;
/**
* <code>string reqId = 1;</code>
*/
public java.lang.String getReqId() {
java.lang.Object ref = reqId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
reqId_ = s;
return s;
}
}
/**
* <code>string reqId = 1;</code>
*/
public com.google.protobuf.ByteString
getReqIdBytes() {
java.lang.Object ref = reqId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
reqId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FINTOOLREFERENCEDATA_FIELD_NUMBER = 2;
private java.util.List<com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData> fintoolReferenceData_;
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public java.util.List<com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData> getFintoolReferenceDataList() {
return fintoolReferenceData_;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public java.util.List<? extends com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceDataOrBuilder>
getFintoolReferenceDataOrBuilderList() {
return fintoolReferenceData_;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public int getFintoolReferenceDataCount() {
return fintoolReferenceData_.size();
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData getFintoolReferenceData(int index) {
return fintoolReferenceData_.get(index);
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceDataOrBuilder getFintoolReferenceDataOrBuilder(
int index) {
return fintoolReferenceData_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getReqIdBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, reqId_);
}
for (int i = 0; i < fintoolReferenceData_.size(); i++) {
output.writeMessage(2, fintoolReferenceData_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getReqIdBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, reqId_);
}
for (int i = 0; i < fintoolReferenceData_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, fintoolReferenceData_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse)) {
return super.equals(obj);
}
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse other = (com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse) obj;
if (!getReqId()
.equals(other.getReqId())) return false;
if (!getFintoolReferenceDataList()
.equals(other.getFintoolReferenceDataList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + REQID_FIELD_NUMBER;
hash = (53 * hash) + getReqId().hashCode();
if (getFintoolReferenceDataCount() > 0) {
hash = (37 * hash) + FINTOOLREFERENCEDATA_FIELD_NUMBER;
hash = (53 * hash) + getFintoolReferenceDataList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code InfoFintoolReferenceDataResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:InfoFintoolReferenceDataResponse)
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.bcs.bm.catalog_of_instruments_rudata.client.grpc.GrpcService.internal_static_InfoFintoolReferenceDataResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.bcs.bm.catalog_of_instruments_rudata.client.grpc.GrpcService.internal_static_InfoFintoolReferenceDataResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse.class, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse.Builder.class);
}
// Construct using com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getFintoolReferenceDataFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
reqId_ = "";
if (fintoolReferenceDataBuilder_ == null) {
fintoolReferenceData_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
fintoolReferenceDataBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.bcs.bm.catalog_of_instruments_rudata.client.grpc.GrpcService.internal_static_InfoFintoolReferenceDataResponse_descriptor;
}
@java.lang.Override
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse getDefaultInstanceForType() {
return com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse.getDefaultInstance();
}
@java.lang.Override
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse build() {
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse buildPartial() {
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse result = new com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse(this);
int from_bitField0_ = bitField0_;
result.reqId_ = reqId_;
if (fintoolReferenceDataBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
fintoolReferenceData_ = java.util.Collections.unmodifiableList(fintoolReferenceData_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.fintoolReferenceData_ = fintoolReferenceData_;
} else {
result.fintoolReferenceData_ = fintoolReferenceDataBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse) {
return mergeFrom((com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse other) {
if (other == com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse.getDefaultInstance()) return this;
if (!other.getReqId().isEmpty()) {
reqId_ = other.reqId_;
onChanged();
}
if (fintoolReferenceDataBuilder_ == null) {
if (!other.fintoolReferenceData_.isEmpty()) {
if (fintoolReferenceData_.isEmpty()) {
fintoolReferenceData_ = other.fintoolReferenceData_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.addAll(other.fintoolReferenceData_);
}
onChanged();
}
} else {
if (!other.fintoolReferenceData_.isEmpty()) {
if (fintoolReferenceDataBuilder_.isEmpty()) {
fintoolReferenceDataBuilder_.dispose();
fintoolReferenceDataBuilder_ = null;
fintoolReferenceData_ = other.fintoolReferenceData_;
bitField0_ = (bitField0_ & ~0x00000001);
fintoolReferenceDataBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getFintoolReferenceDataFieldBuilder() : null;
} else {
fintoolReferenceDataBuilder_.addAllMessages(other.fintoolReferenceData_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object reqId_ = "";
/**
* <code>string reqId = 1;</code>
*/
public java.lang.String getReqId() {
java.lang.Object ref = reqId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
reqId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string reqId = 1;</code>
*/
public com.google.protobuf.ByteString
getReqIdBytes() {
java.lang.Object ref = reqId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
reqId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string reqId = 1;</code>
*/
public Builder setReqId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
reqId_ = value;
onChanged();
return this;
}
/**
* <code>string reqId = 1;</code>
*/
public Builder clearReqId() {
reqId_ = getDefaultInstance().getReqId();
onChanged();
return this;
}
/**
* <code>string reqId = 1;</code>
*/
public Builder setReqIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
reqId_ = value;
onChanged();
return this;
}
private java.util.List<com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData> fintoolReferenceData_ =
java.util.Collections.emptyList();
private void ensureFintoolReferenceDataIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
fintoolReferenceData_ = new java.util.ArrayList<com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData>(fintoolReferenceData_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceDataOrBuilder> fintoolReferenceDataBuilder_;
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public java.util.List<com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData> getFintoolReferenceDataList() {
if (fintoolReferenceDataBuilder_ == null) {
return java.util.Collections.unmodifiableList(fintoolReferenceData_);
} else {
return fintoolReferenceDataBuilder_.getMessageList();
}
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public int getFintoolReferenceDataCount() {
if (fintoolReferenceDataBuilder_ == null) {
return fintoolReferenceData_.size();
} else {
return fintoolReferenceDataBuilder_.getCount();
}
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData getFintoolReferenceData(int index) {
if (fintoolReferenceDataBuilder_ == null) {
return fintoolReferenceData_.get(index);
} else {
return fintoolReferenceDataBuilder_.getMessage(index);
}
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder setFintoolReferenceData(
int index, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData value) {
if (fintoolReferenceDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.set(index, value);
onChanged();
} else {
fintoolReferenceDataBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder setFintoolReferenceData(
int index, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder builderForValue) {
if (fintoolReferenceDataBuilder_ == null) {
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.set(index, builderForValue.build());
onChanged();
} else {
fintoolReferenceDataBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder addFintoolReferenceData(com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData value) {
if (fintoolReferenceDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.add(value);
onChanged();
} else {
fintoolReferenceDataBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder addFintoolReferenceData(
int index, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData value) {
if (fintoolReferenceDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.add(index, value);
onChanged();
} else {
fintoolReferenceDataBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder addFintoolReferenceData(
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder builderForValue) {
if (fintoolReferenceDataBuilder_ == null) {
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.add(builderForValue.build());
onChanged();
} else {
fintoolReferenceDataBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder addFintoolReferenceData(
int index, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder builderForValue) {
if (fintoolReferenceDataBuilder_ == null) {
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.add(index, builderForValue.build());
onChanged();
} else {
fintoolReferenceDataBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder addAllFintoolReferenceData(
java.lang.Iterable<? extends com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData> values) {
if (fintoolReferenceDataBuilder_ == null) {
ensureFintoolReferenceDataIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, fintoolReferenceData_);
onChanged();
} else {
fintoolReferenceDataBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder clearFintoolReferenceData() {
if (fintoolReferenceDataBuilder_ == null) {
fintoolReferenceData_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
fintoolReferenceDataBuilder_.clear();
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public Builder removeFintoolReferenceData(int index) {
if (fintoolReferenceDataBuilder_ == null) {
ensureFintoolReferenceDataIsMutable();
fintoolReferenceData_.remove(index);
onChanged();
} else {
fintoolReferenceDataBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder getFintoolReferenceDataBuilder(
int index) {
return getFintoolReferenceDataFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceDataOrBuilder getFintoolReferenceDataOrBuilder(
int index) {
if (fintoolReferenceDataBuilder_ == null) {
return fintoolReferenceData_.get(index); } else {
return fintoolReferenceDataBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public java.util.List<? extends com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceDataOrBuilder>
getFintoolReferenceDataOrBuilderList() {
if (fintoolReferenceDataBuilder_ != null) {
return fintoolReferenceDataBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(fintoolReferenceData_);
}
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder addFintoolReferenceDataBuilder() {
return getFintoolReferenceDataFieldBuilder().addBuilder(
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.getDefaultInstance());
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder addFintoolReferenceDataBuilder(
int index) {
return getFintoolReferenceDataFieldBuilder().addBuilder(
index, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.getDefaultInstance());
}
/**
* <code>repeated .FintoolReferenceData fintoolReferenceData = 2;</code>
*/
public java.util.List<com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder>
getFintoolReferenceDataBuilderList() {
return getFintoolReferenceDataFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceDataOrBuilder>
getFintoolReferenceDataFieldBuilder() {
if (fintoolReferenceDataBuilder_ == null) {
fintoolReferenceDataBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceData.Builder, com.bcs.bm.catalog_of_instruments_rudata.client.grpc.FintoolReferenceDataOrBuilder>(
fintoolReferenceData_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
fintoolReferenceData_ = null;
}
return fintoolReferenceDataBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:InfoFintoolReferenceDataResponse)
}
// @@protoc_insertion_point(class_scope:InfoFintoolReferenceDataResponse)
private static final com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse();
}
public static com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<InfoFintoolReferenceDataResponse>
PARSER = new com.google.protobuf.AbstractParser<InfoFintoolReferenceDataResponse>() {
@java.lang.Override
public InfoFintoolReferenceDataResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new InfoFintoolReferenceDataResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<InfoFintoolReferenceDataResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<InfoFintoolReferenceDataResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.bcs.bm.catalog_of_instruments_rudata.client.grpc.InfoFintoolReferenceDataResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
3e09dd3450ef9b227cbb488dd9c40323f1379830 | 3,521 | java | Java | bytx_web/src/main/java/com/bytx/admin/controller/NewsController.java | Baymax6/bytx_admin | 42485e1f9e78f5519d2a016d60f14297fe41125b | [
"Apache-2.0"
] | null | null | null | bytx_web/src/main/java/com/bytx/admin/controller/NewsController.java | Baymax6/bytx_admin | 42485e1f9e78f5519d2a016d60f14297fe41125b | [
"Apache-2.0"
] | null | null | null | bytx_web/src/main/java/com/bytx/admin/controller/NewsController.java | Baymax6/bytx_admin | 42485e1f9e78f5519d2a016d60f14297fe41125b | [
"Apache-2.0"
] | null | null | null | 32.302752 | 107 | 0.684465 | 4,175 | package com.bytx.admin.controller;
import com.bytx.admin.entity.NewsCenter;
import com.bytx.admin.service.NewsCenterPersistenceService;
import com.bytx.admin.util.SFTPUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController
{
@Autowired
private NewsCenterPersistenceService newsCenterPersistenceService;
@RequestMapping("/addNews")
@ResponseBody
public Integer addNews(MultipartFile imageFile, HttpServletRequest request, NewsCenter newsCenter)
{
String basePath = request.getServletContext().getRealPath("/");
String imgFileName = imageFile.getOriginalFilename();
String rootPath = basePath + storageImagePath + "/news";
String imgPath = rootPath + "/img/" + imgFileName;
String remoteImgPath = "/data/wwwroot/default" + storageImagePath + "/news/img";
String remoteImgUrl = accessImageUrl + storageImagePath + "/news/img/" + imgFileName;
File tmpImgFile = new File(imgPath);
try
{
FileUtils.forceMkdir(tmpImgFile.getParentFile());
imageFile.transferTo(tmpImgFile);
SFTPUtil.uploadFile(BaseController.channelSftp, imgPath, remoteImgPath);
newsCenter.setImageSrc(remoteImgUrl);
newsCenter.setParentId(2);
}
catch (IOException e)
{
e.printStackTrace();
}
return newsCenterPersistenceService.addNews(newsCenter);
}
@RequestMapping("/updateNews")
@ResponseBody
public Integer updateNews(HttpServletRequest request, NewsCenter newsCenter)
{
MultipartFile updateImageFile = ((MultipartHttpServletRequest) request).getFile("updateImageFile");
String basePath = request.getServletContext().getRealPath("/");
newsCenter.setParentId(2);
if (updateImageFile != null)
{
String imgFileName = updateImageFile.getOriginalFilename();
String rootPath = basePath + storageImagePath + "/news";
String imgPath = rootPath + "/img/" + imgFileName;
String remoteImgPath = "/data/wwwroot/default" + storageImagePath + "/news/img";
String remoteImgUrl = accessImageUrl + storageImagePath + "/news/img/" + imgFileName;
File tmpImgFile = new File(imgPath);
try
{
FileUtils.forceMkdir(tmpImgFile.getParentFile());
updateImageFile.transferTo(tmpImgFile);
SFTPUtil.uploadFile(BaseController.channelSftp, imgPath, remoteImgPath);
newsCenter.setImageSrc(remoteImgUrl);
}
catch (IOException e)
{
e.printStackTrace();
}
}
return newsCenterPersistenceService.updateNews(newsCenter);
}
@RequestMapping("/updateStatus")
@ResponseBody
public Integer updateNewsStatus(NewsCenter newsCenter)
{
return newsCenterPersistenceService.updateNews(newsCenter);
}
}
|
3e09dd5d12d64c426c64fe47973a24f90feec082 | 717 | java | Java | src/Tarea2/Cuadrado.java | martinezmizael/EjerciciosPOO | dc6cfefd5a5b74f1103e493b5b5210f77839d9b9 | [
"MIT"
] | null | null | null | src/Tarea2/Cuadrado.java | martinezmizael/EjerciciosPOO | dc6cfefd5a5b74f1103e493b5b5210f77839d9b9 | [
"MIT"
] | 3 | 2022-01-11T02:38:26.000Z | 2022-01-11T03:25:05.000Z | src/Tarea2/Cuadrado.java | martinezmizael/EjerciciosPOO | dc6cfefd5a5b74f1103e493b5b5210f77839d9b9 | [
"MIT"
] | null | null | null | 17.071429 | 50 | 0.564854 | 4,176 | package Tarea2;
public class Cuadrado implements FiguraGeometrica{
private int lado;
private String color;
public Cuadrado(int lado)
{
this.lado=lado;
}
@Override
public float perimetro()
{
return 4*this.lado;
}
@Override
public float area()
{
return this.lado*this.lado;
}
public int getLado() {
return lado;
}
public void setLado(int lado) {
this.lado = lado;
}
//métodos adicionales
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String color() {
return this.color;
}
}
|
3e09dd6ed867d4ca8edfc902be4d55236f4c98e0 | 96 | java | Java | src/telerik/enumerators/GameStateButtons.java | smt-test/NinjaDefense | bdf85ad1a27d1bebd78b0f00e82a32a451098b90 | [
"MIT"
] | null | null | null | src/telerik/enumerators/GameStateButtons.java | smt-test/NinjaDefense | bdf85ad1a27d1bebd78b0f00e82a32a451098b90 | [
"MIT"
] | null | null | null | src/telerik/enumerators/GameStateButtons.java | smt-test/NinjaDefense | bdf85ad1a27d1bebd78b0f00e82a32a451098b90 | [
"MIT"
] | 1 | 2019-04-24T07:36:25.000Z | 2019-04-24T07:36:25.000Z | 16 | 32 | 0.75 | 4,177 | package telerik.enumerators;
public enum GameStateButtons {
PLAY, PAUSE, NEW_GAME, EXIT;
}
|
3e09dd81af956132bba928b2514296394e176794 | 2,758 | java | Java | mall-order/src/main/java/com/ylkget/gmall/order/entity/OrderEntity.java | ylksty/gulimall | f03ad44cf77340ef2c004fd4fd377f9584d6c256 | [
"MIT"
] | null | null | null | mall-order/src/main/java/com/ylkget/gmall/order/entity/OrderEntity.java | ylksty/gulimall | f03ad44cf77340ef2c004fd4fd377f9584d6c256 | [
"MIT"
] | null | null | null | mall-order/src/main/java/com/ylkget/gmall/order/entity/OrderEntity.java | ylksty/gulimall | f03ad44cf77340ef2c004fd4fd377f9584d6c256 | [
"MIT"
] | null | null | null | 14.201031 | 53 | 0.626134 | 4,178 | package com.ylkget.gmall.order.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 订单
*
* @author yanglk
* @email upchh@example.com
* @date 2021-01-30 15:22:59
*/
@Data
@TableName("oms_order")
public class OrderEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* member_id
*/
private Long memberId;
/**
* 订单号
*/
private String orderSn;
/**
* 使用的优惠券
*/
private Long couponId;
/**
* create_time
*/
private Date createTime;
/**
* 用户名
*/
private String memberUsername;
/**
* 订单总额
*/
private BigDecimal totalAmount;
/**
* 应付总额
*/
private BigDecimal payAmount;
/**
* 运费金额
*/
private BigDecimal freightAmount;
/**
* 促销优化金额(促销价、满减、阶梯价)
*/
private BigDecimal promotionAmount;
/**
* 积分抵扣金额
*/
private BigDecimal integrationAmount;
/**
* 优惠券抵扣金额
*/
private BigDecimal couponAmount;
/**
* 后台调整订单使用的折扣金额
*/
private BigDecimal discountAmount;
/**
* 支付方式【1->支付宝;2->微信;3->银联; 4->货到付款;】
*/
private Integer payType;
/**
* 订单来源[0->PC订单;1->app订单]
*/
private Integer sourceType;
/**
* 订单状态【0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭;5->无效订单】
*/
private Integer status;
/**
* 物流公司(配送方式)
*/
private String deliveryCompany;
/**
* 物流单号
*/
private String deliverySn;
/**
* 自动确认时间(天)
*/
private Integer autoConfirmDay;
/**
* 可以获得的积分
*/
private Integer integration;
/**
* 可以获得的成长值
*/
private Integer growth;
/**
* 发票类型[0->不开发票;1->电子发票;2->纸质发票]
*/
private Integer billType;
/**
* 发票抬头
*/
private String billHeader;
/**
* 发票内容
*/
private String billContent;
/**
* 收票人电话
*/
private String billReceiverPhone;
/**
* 收票人邮箱
*/
private String billReceiverEmail;
/**
* 收货人姓名
*/
private String receiverName;
/**
* 收货人电话
*/
private String receiverPhone;
/**
* 收货人邮编
*/
private String receiverPostCode;
/**
* 省份/直辖市
*/
private String receiverProvince;
/**
* 城市
*/
private String receiverCity;
/**
* 区
*/
private String receiverRegion;
/**
* 详细地址
*/
private String receiverDetailAddress;
/**
* 订单备注
*/
private String note;
/**
* 确认收货状态[0->未确认;1->已确认]
*/
private Integer confirmStatus;
/**
* 删除状态【0->未删除;1->已删除】
*/
private Integer deleteStatus;
/**
* 下单时使用的积分
*/
private Integer useIntegration;
/**
* 支付时间
*/
private Date paymentTime;
/**
* 发货时间
*/
private Date deliveryTime;
/**
* 确认收货时间
*/
private Date receiveTime;
/**
* 评价时间
*/
private Date commentTime;
/**
* 修改时间
*/
private Date modifyTime;
}
|
3e09de7304e0dd738b1c0cb51e4c396c401175e9 | 1,726 | java | Java | mobi.chouette.exchange.neptune/src/main/java/mobi/chouette/exchange/neptune/model/NeptuneObjectFactory.java | JLLeitschuh/chouette | 1a05aa9467a7108bd22c4235e56052bcd09e7096 | [
"CECILL-B"
] | 30 | 2015-01-21T07:26:30.000Z | 2022-01-26T21:50:01.000Z | mobi.chouette.exchange.neptune/src/main/java/mobi/chouette/exchange/neptune/model/NeptuneObjectFactory.java | JLLeitschuh/chouette | 1a05aa9467a7108bd22c4235e56052bcd09e7096 | [
"CECILL-B"
] | 141 | 2020-10-26T15:32:24.000Z | 2022-03-29T21:52:52.000Z | mobi.chouette.exchange.neptune/src/main/java/mobi/chouette/exchange/neptune/model/NeptuneObjectFactory.java | JLLeitschuh/chouette | 1a05aa9467a7108bd22c4235e56052bcd09e7096 | [
"CECILL-B"
] | 23 | 2015-01-06T12:55:29.000Z | 2020-02-11T03:34:36.000Z | 20.795181 | 67 | 0.701622 | 4,179 | package mobi.chouette.exchange.neptune.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import mobi.chouette.model.Route;
public class NeptuneObjectFactory {
@Getter
@Setter
private Map<String, AreaCentroid> areaCentroid = new HashMap<>();
@Getter
@Setter
private Map<String, PTLink> ptLink = new HashMap<>();
@Getter
@Setter
private Map<Route, List<PTLink>> ptLinksOnRoute = new HashMap<>();
@Getter
@Setter
private Map<String, TimeSlot> timeSlots = new HashMap<>();
public PTLink getPTLink(String objectId) {
PTLink result = ptLink.get(objectId);
if (result == null) {
result = new PTLink();
result.setObjectId(objectId);
ptLink.put(objectId, result);
}
return result;
}
public AreaCentroid getAreaCentroid(String objectId) {
AreaCentroid result = areaCentroid.get(objectId);
if (result == null) {
result = new AreaCentroid();
result.setObjectId(objectId);
areaCentroid.put(objectId, result);
}
return result;
}
public List<PTLink> getPTLinksOnRoute(Route route) {
List<PTLink> result = ptLinksOnRoute.get(route);
if(result == null){
result = new ArrayList<PTLink>();
ptLinksOnRoute.put(route, result);
}
return result;
}
public TimeSlot getTimeSlot(String objectId) {
TimeSlot timeSlot = timeSlots.get(objectId);
if (timeSlot == null) {
timeSlot = new TimeSlot();
timeSlot.setObjectId(objectId);
timeSlots.put(objectId, timeSlot);
}
return timeSlot;
}
public void clear(){
ptLink.clear();
ptLinksOnRoute.clear();
timeSlots.clear();
}
public void dispose()
{
clear();
areaCentroid.clear();
}
}
|
3e09de7d19d2b9441805003c6e18c6695ef080c2 | 565 | java | Java | sample/src/main/java/com/github/florent37/carpaccio/sample/MainActivityParallax.java | florent37/Carpaccio | 837fc8a8cfdadf7659b78798d7304aacc9dfe59f | [
"Apache-2.0"
] | 485 | 2015-07-29T13:53:03.000Z | 2021-11-09T10:12:24.000Z | sample/src/main/java/com/github/florent37/carpaccio/sample/MainActivityParallax.java | florent37/BadView | 837fc8a8cfdadf7659b78798d7304aacc9dfe59f | [
"Apache-2.0"
] | 10 | 2015-07-30T13:57:08.000Z | 2017-06-16T23:15:29.000Z | sample/src/main/java/com/github/florent37/carpaccio/sample/MainActivityParallax.java | florent37/BadView | 837fc8a8cfdadf7659b78798d7304aacc9dfe59f | [
"Apache-2.0"
] | 81 | 2015-07-29T15:49:11.000Z | 2020-02-07T14:20:01.000Z | 23.541667 | 65 | 0.79469 | 4,180 | package com.github.florent37.carpaccio.sample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.florent37.carpaccio.Carpaccio;
import com.github.florent37.carpaccio.sample.factory.UserFactory;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivityParallax extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_scroll);
}
}
|
3e09decffa4e8802d72725a00a26bf7f85e11545 | 829 | java | Java | src/main/java/org/italiangrid/storm/webdav/authz/pdp/PathAuthorizationPdp.java | italiangrid/storm-webdav | 99262faa7b166ca8351e4db45b0eb1af5bf7fb11 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/italiangrid/storm/webdav/authz/pdp/PathAuthorizationPdp.java | italiangrid/storm-webdav | 99262faa7b166ca8351e4db45b0eb1af5bf7fb11 | [
"Apache-2.0"
] | 2 | 2015-02-03T15:03:48.000Z | 2020-03-30T16:15:25.000Z | src/main/java/org/italiangrid/storm/webdav/authz/pdp/PathAuthorizationPdp.java | italiangrid/storm-webdav | 99262faa7b166ca8351e4db45b0eb1af5bf7fb11 | [
"Apache-2.0"
] | 1 | 2020-05-07T10:48:36.000Z | 2020-05-07T10:48:36.000Z | 34.541667 | 77 | 0.761158 | 4,181 | /**
* Copyright (c) Istituto Nazionale di Fisica Nucleare, 2014-2021.
*
* 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.italiangrid.storm.webdav.authz.pdp;
@FunctionalInterface
public interface PathAuthorizationPdp {
PathAuthorizationResult authorizeRequest(PathAuthorizationRequest request);
}
|
3e09df1cfefbc6ca1e84560cad347462c55ae074 | 3,378 | java | Java | app/src/main/java/de/kai_morich/simple_bluetooth_terminal/MainMenuFragment.java | limyingjie/mimicareApp | 5657c5505eeec4b070b76832c122bbe8b36497ef | [
"MIT"
] | null | null | null | app/src/main/java/de/kai_morich/simple_bluetooth_terminal/MainMenuFragment.java | limyingjie/mimicareApp | 5657c5505eeec4b070b76832c122bbe8b36497ef | [
"MIT"
] | null | null | null | app/src/main/java/de/kai_morich/simple_bluetooth_terminal/MainMenuFragment.java | limyingjie/mimicareApp | 5657c5505eeec4b070b76832c122bbe8b36497ef | [
"MIT"
] | null | null | null | 33.117647 | 112 | 0.656898 | 4,182 | package de.kai_morich.simple_bluetooth_terminal;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.Random;
public class MainMenuFragment extends Fragment {
private String[][] messages = {
{"The weather\nlooks good~", "Let's go for\na walk shall we?"},
{"Ahhh...\nI am starving...", "Shall we go\nget some food?"},
{"Cheese Burger!!!","Control yourself\nplease!"}
};
private int minInterval = 10000;
private int maxInterval = 15000;
private Handler handler;
private Random rng = new Random();
private TextView speechBubbleLeft;
private TextView speechBubbleRight;
class ShowSpeech implements Runnable {
private TextView speechBubble;
private String message;
public ShowSpeech(TextView speechBubble, String message){
this.speechBubble = speechBubble;
this.message = message;
}
public void run() {
speechBubble.setText(message);
speechBubble.setVisibility(View.VISIBLE);
}
};
class HideSpeech implements Runnable {
private TextView speechBubble;
public HideSpeech(TextView speechBubble){
this.speechBubble = speechBubble;
}
public void run() {
speechBubble.setVisibility(View.INVISIBLE);
}
};
private Runnable Speak = new Runnable() {
@Override
public void run() {
try {
int i = rng.nextInt(messages.length);
handler.postDelayed(new ShowSpeech(speechBubbleLeft, messages[i][0]), 0);
handler.postDelayed(new ShowSpeech(speechBubbleRight, messages[i][1]), 1000);
handler.postDelayed(new HideSpeech(speechBubbleLeft), 6000);
handler.postDelayed(new HideSpeech(speechBubbleRight), 6000);
} finally {
handler.postDelayed(Speak, (long) rng.nextFloat()*(maxInterval-minInterval)+minInterval);
}
}
};
public MainMenuFragment() {
}
/*
* Lifecycle
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
}
@Override
public void onDestroy() {
handler.removeCallbacksAndMessages(null);
super.onDestroy();
}
/*
* UI
*/
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mainmenu, container, false);
speechBubbleLeft = view.findViewById(R.id.speechleft);
speechBubbleRight = view.findViewById(R.id.speechright);
handler = new Handler();
handler.postDelayed(Speak, (long) rng.nextFloat()*(maxInterval-minInterval)+5000);
return view;
}
} |
3e09e08f9d860a3d5ff2f6f214f7eb1a7b95f553 | 338 | java | Java | chapter_001/src/main/java/ru/job4j/Calculate.java | Basil135/vkucyh | bd286cbb465ddf8cded21454a1e7ee27bae0aa01 | [
"Apache-2.0"
] | null | null | null | chapter_001/src/main/java/ru/job4j/Calculate.java | Basil135/vkucyh | bd286cbb465ddf8cded21454a1e7ee27bae0aa01 | [
"Apache-2.0"
] | null | null | null | chapter_001/src/main/java/ru/job4j/Calculate.java | Basil135/vkucyh | bd286cbb465ddf8cded21454a1e7ee27bae0aa01 | [
"Apache-2.0"
] | null | null | null | 14.652174 | 75 | 0.661721 | 4,183 | package ru.job4j;
/**
* Class Calculate is the solution of the problem from package 001 lesson 1.
*
* @author Kucyh Vasily (mailto:nnheo@example.com)
* @since 29.03.2017
*/
public class Calculate {
/**
* Method main.
*
* @param args - args
*/
public static void main(String... args) {
System.out.println("Hello world");
}
}
|
3e09e0a19c44a0a97976ac591d1930905d2ca688 | 982 | java | Java | ambry-clustermap/src/main/java/com/github/ambry/clustermap/HelixClusterSpectatorFactory.java | CoppernicSoftware/ambry | 40387ae668351000db3e9faf211fd6c07dcd966f | [
"Apache-2.0"
] | 1 | 2019-01-11T11:49:58.000Z | 2019-01-11T11:49:58.000Z | ambry-clustermap/src/main/java/com/github/ambry/clustermap/HelixClusterSpectatorFactory.java | CoppernicSoftware/ambry | 40387ae668351000db3e9faf211fd6c07dcd966f | [
"Apache-2.0"
] | null | null | null | ambry-clustermap/src/main/java/com/github/ambry/clustermap/HelixClusterSpectatorFactory.java | CoppernicSoftware/ambry | 40387ae668351000db3e9faf211fd6c07dcd966f | [
"Apache-2.0"
] | null | null | null | 32.733333 | 107 | 0.771894 | 4,184 | /*
* Copyright 2019 LinkedIn Corp. 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.
*/
package com.github.ambry.clustermap;
import com.github.ambry.config.CloudConfig;
import com.github.ambry.config.ClusterMapConfig;
/**
* A factory to create {@link ClusterSpectator} object.
*/
public class HelixClusterSpectatorFactory implements ClusterSpectatorFactory {
@Override
public ClusterSpectator getClusterSpectator(CloudConfig cloudConfig, ClusterMapConfig clusterMapConfig) {
return new HelixClusterSpectator(cloudConfig, clusterMapConfig);
}
}
|
3e09e1c9516eb5e794f22a783be72345fc68f6db | 4,736 | java | Java | BCH/plugin/crypto_router/fermat-bch-plugin-crypto-router-incoming-crypto-bitdubai/src/main/java/com/bitdubai/fermat_bch_plugin/layer/crypto_router/incoming_crypto/developer/bitdubai/version_1/util/SpecialistSelector.java | guillermo20/fermat | f0a912adb66a439023ec4e70b821ba397e0f7760 | [
"MIT"
] | 3 | 2016-03-23T05:26:51.000Z | 2016-03-24T14:33:05.000Z | BCH/plugin/crypto_router/fermat-bch-plugin-crypto-router-incoming-crypto-bitdubai/src/main/java/com/bitdubai/fermat_bch_plugin/layer/crypto_router/incoming_crypto/developer/bitdubai/version_1/util/SpecialistSelector.java | yalayn/fermat | f0a912adb66a439023ec4e70b821ba397e0f7760 | [
"MIT"
] | 17 | 2015-11-20T20:43:17.000Z | 2016-07-25T20:35:49.000Z | BCH/plugin/crypto_router/fermat-bch-plugin-crypto-router-incoming-crypto-bitdubai/src/main/java/com/bitdubai/fermat_bch_plugin/layer/crypto_router/incoming_crypto/developer/bitdubai/version_1/util/SpecialistSelector.java | yalayn/fermat | f0a912adb66a439023ec4e70b821ba397e0f7760 | [
"MIT"
] | 26 | 2015-11-20T13:20:23.000Z | 2022-03-11T07:50:06.000Z | 57.756098 | 275 | 0.71875 | 4,185 | package com.bitdubai.fermat_bch_plugin.layer.crypto_router.incoming_crypto.developer.bitdubai.version_1.util;
import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress;
import com.bitdubai.fermat_api.layer.all_definition.transaction_transference_protocol.Specialist;
import com.bitdubai.fermat_api.layer.all_definition.transaction_transference_protocol.crypto_transactions.CryptoTransaction;
import com.bitdubai.fermat_bch_api.layer.crypto_module.crypto_address_book.exceptions.CantGetCryptoAddressBookRecordException;
import com.bitdubai.fermat_bch_api.layer.crypto_module.crypto_address_book.exceptions.CryptoAddressBookRecordNotFoundException;
import com.bitdubai.fermat_bch_api.layer.crypto_module.crypto_address_book.interfaces.CryptoAddressBookManager;
import com.bitdubai.fermat_bch_api.layer.crypto_module.crypto_address_book.interfaces.CryptoAddressBookRecord;
import com.bitdubai.fermat_bch_plugin.layer.crypto_router.incoming_crypto.developer.bitdubai.version_1.exceptions.CantSelectSpecialistException;
/**
* Created by eze on 12/06/15.
* The purpose of this class is to indicate the correct
* destination for a given transaction
*/
public class SpecialistSelector {
private final CryptoAddressBookManager cryptoAddressBookManager;
public SpecialistSelector(final CryptoAddressBookManager cryptoAddressBookManager) {
this.cryptoAddressBookManager = cryptoAddressBookManager;
}
public Specialist getSpecialist(CryptoTransaction cryptoTransaction) throws CantSelectSpecialistException {
CryptoAddress cryptoAddress = new CryptoAddress();
cryptoAddress.setAddress(cryptoTransaction.getAddressTo().getAddress());
cryptoAddress.setCryptoCurrency(cryptoTransaction.getCryptoCurrency());
try {
CryptoAddressBookRecord cryptoAddressBookRecord = cryptoAddressBookManager.getCryptoAddressBookRecordByCryptoAddress(cryptoAddress);
switch (cryptoAddressBookRecord.getDeliveredToActorType()) {
case DEVICE_USER:
return Specialist.DEVICE_USER_SPECIALIST;
case INTRA_USER:
return Specialist.INTRA_USER_SPECIALIST;
case EXTRA_USER:
return Specialist.EXTRA_USER_SPECIALIST;
case DAP_ASSET_ISSUER:
return Specialist.ASSET_ISSUER_SPECIALIST;
case DAP_ASSET_USER:
return Specialist.ASSET_USER_SPECIALIST;
default:
// Here we have a serious problem
throw new CantSelectSpecialistException("NO SPECIALIST FOUND",null,"Actor: " + cryptoAddressBookRecord.getDeliveredToActorType() + " with code " + cryptoAddressBookRecord.getDeliveredToActorType().getCode(),"Actor not considered in switch statement");
}
} catch (CantGetCryptoAddressBookRecordException|CryptoAddressBookRecordNotFoundException e) {
cryptoAddress.setAddress(cryptoTransaction.getAddressFrom().getAddress());
cryptoAddress.setCryptoCurrency(cryptoTransaction.getCryptoCurrency());
try {
CryptoAddressBookRecord cryptoAddressBookRecord = cryptoAddressBookManager.getCryptoAddressBookRecordByCryptoAddress(cryptoAddress);
switch (cryptoAddressBookRecord.getDeliveredToActorType()) {
case DEVICE_USER:
return Specialist.DEVICE_USER_SPECIALIST;
case INTRA_USER:
return Specialist.INTRA_USER_SPECIALIST;
case EXTRA_USER:
return Specialist.EXTRA_USER_SPECIALIST;
case DAP_ASSET_ISSUER:
return Specialist.ASSET_ISSUER_SPECIALIST;
case DAP_ASSET_USER:
return Specialist.ASSET_USER_SPECIALIST;
default:
// Here we have a serious problem
throw new CantSelectSpecialistException("NO SPECIALIST FOUND",null,"Actor: " + cryptoAddressBookRecord.getDeliveredToActorType() + " with code " + cryptoAddressBookRecord.getDeliveredToActorType().getCode(),"Actor not considered in switch statement");
}
} catch (CantGetCryptoAddressBookRecordException|CryptoAddressBookRecordNotFoundException e1) {
// todo ver como manejar CryptoAddressBookRecordNotFoundException
// This exception will be managed by the relay agent
throw new CantSelectSpecialistException("Can't get actor address from registry", e1,"CryptoAddress: "+ cryptoAddress.getAddress(),"Address not stored");
}
}
}
}
|
3e09e211a490b4ae4c39e4cb6f084fdc460994fb | 674 | java | Java | Grammar/src/org/fundacionjala/oblivion/apex/grammar/ast/SOQLGroupByExpressionTree.java | fundacionjala/oblivion-netbeans-plugin | 2b4023988c743519799b55fb824b4c215396ba97 | [
"MIT"
] | 6 | 2016-11-03T18:28:55.000Z | 2018-08-03T13:00:51.000Z | Grammar/src/org/fundacionjala/oblivion/apex/grammar/ast/SOQLGroupByExpressionTree.java | fundacionjala/oblivion-netbeans-plugin | 2b4023988c743519799b55fb824b4c215396ba97 | [
"MIT"
] | 5 | 2016-08-10T15:28:15.000Z | 2019-03-05T00:26:44.000Z | Grammar/src/org/fundacionjala/oblivion/apex/grammar/ast/SOQLGroupByExpressionTree.java | fundacionjala/oblivion-netbeans-plugin | 2b4023988c743519799b55fb824b4c215396ba97 | [
"MIT"
] | 8 | 2016-11-03T18:29:01.000Z | 2021-12-18T09:32:10.000Z | 29.304348 | 101 | 0.778932 | 4,186 | /*
* Copyright (c) Fundacion Jala. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package org.fundacionjala.oblivion.apex.grammar.ast;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodInvocationTree;
import java.util.List;
/**
* Defines necessary methods to create SOQL GroupByExpression tree nodes.
*
* @author sergio_daza
*/
public interface SOQLGroupByExpressionTree extends ExpressionTree {
public List<IdentifierTree> getIdentifiers();
public List<MethodInvocationTree> getMethodInvocations();
}
|
3e09e2cf00a863350846f7fae0791b1602ec8bd2 | 1,261 | java | Java | src/main/resources/templates/azure-active-directory/AADOAuth2LoginSecurityConfig.java | songshansitulv/spring-cloud-playground | ace0e29ba565fd07387e40110648e500b7b47775 | [
"MIT"
] | 10 | 2018-06-13T07:20:40.000Z | 2018-10-19T07:44:11.000Z | src/main/resources/templates/azure-active-directory/AADOAuth2LoginSecurityConfig.java | songshansitulv/spring-cloud-playground | ace0e29ba565fd07387e40110648e500b7b47775 | [
"MIT"
] | 79 | 2018-06-12T02:11:33.000Z | 2018-10-08T09:40:44.000Z | src/main/resources/templates/azure-active-directory/AADOAuth2LoginSecurityConfig.java | songshansitulv/spring-cloud-playground | ace0e29ba565fd07387e40110648e500b7b47775 | [
"MIT"
] | 5 | 2019-11-03T16:29:54.000Z | 2020-08-05T15:03:59.000Z | 43.482759 | 102 | 0.776368 | 4,187 | package {{packageName}};
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AADOAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
.userInfoEndpoint()
.oidcUserService(oidcUserService);
}
}
|
3e09e3852be640f00cba40fdb0a6a51be776ab2b | 5,156 | java | Java | test/edu/washington/escience/myria/operator/SampleWRTest.java | UFFeScience/Myria | bf2c64e7816a990e64fe893bd88143770e76aaed | [
"BSD-3-Clause"
] | 103 | 2015-01-24T08:29:44.000Z | 2021-11-25T08:26:55.000Z | test/edu/washington/escience/myria/operator/SampleWRTest.java | UFFeScience/Myria | bf2c64e7816a990e64fe893bd88143770e76aaed | [
"BSD-3-Clause"
] | 257 | 2015-01-01T04:56:13.000Z | 2019-04-11T01:02:41.000Z | test/edu/washington/escience/myria/operator/SampleWRTest.java | UFFeScience/Myria | bf2c64e7816a990e64fe893bd88143770e76aaed | [
"BSD-3-Clause"
] | 39 | 2015-01-07T20:54:35.000Z | 2022-02-28T10:36:23.000Z | 31.439024 | 99 | 0.695112 | 4,188 | package edu.washington.escience.myria.operator;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import edu.washington.escience.myria.DbException;
import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.Type;
import edu.washington.escience.myria.storage.TupleBatch;
import edu.washington.escience.myria.storage.TupleBatchBuffer;
import edu.washington.escience.myria.util.TestEnvVars;
/**
* Tests SampleWR by verifying the results of various scenarios.
*/
public class SampleWRTest {
final long RANDOM_SEED = 42;
final int[] INPUT_VALS = {0, 1, 2, 3, 4, 5};
// values generated by rand.nextInt(INPUT_VALS.length) w/ seed=42
final int[] SEED_OUTPUT = {2, 3, 0, 2, 0, 1, 5, 2, 1, 5, 2, 2};
final Schema LEFT_SCHEMA =
Schema.ofFields(
"WorkerID",
Type.INT_TYPE,
"PartitionSize",
Type.INT_TYPE,
"SampleSize",
Type.INT_TYPE,
"SampleType",
Type.STRING_TYPE);
final Schema RIGHT_SCHEMA = Schema.ofFields(Type.INT_TYPE, "SomeValue");
final Schema OUTPUT_SCHEMA = RIGHT_SCHEMA;
TupleBatchBuffer leftInput;
TupleBatchBuffer rightInput;
Sample sampOp;
@Before
public void setup() {
leftInput = new TupleBatchBuffer(LEFT_SCHEMA);
leftInput.putInt(0, -1); // WorkerID for testing
rightInput = new TupleBatchBuffer(RIGHT_SCHEMA);
for (int val : INPUT_VALS) {
rightInput.putInt(0, val);
}
}
/** Sample size 0. */
@Test
public void testSampleSizeZero() throws DbException {
int partitionSize = INPUT_VALS.length;
int sampleSize = 0;
int[] expected = Arrays.copyOf(SEED_OUTPUT, sampleSize);
Arrays.sort(expected);
verifyExpectedResults(partitionSize, sampleSize, expected);
}
/** Sample size 1. */
@Test
public void testSampleSizeOne() throws DbException {
int partitionSize = INPUT_VALS.length;
int sampleSize = 1;
int[] expected = Arrays.copyOf(SEED_OUTPUT, sampleSize);
Arrays.sort(expected);
verifyExpectedResults(partitionSize, sampleSize, expected);
}
/** Sample size 50%. */
@Test
public void testSampleSizeHalf() throws DbException {
int partitionSize = INPUT_VALS.length;
int sampleSize = INPUT_VALS.length / 2;
int[] expected = Arrays.copyOf(SEED_OUTPUT, sampleSize);
Arrays.sort(expected);
verifyExpectedResults(partitionSize, sampleSize, expected);
}
/** Sample size all. */
@Test
public void testSampleSizeAll() throws DbException {
int partitionSize = INPUT_VALS.length;
int sampleSize = INPUT_VALS.length;
int[] expected = Arrays.copyOf(SEED_OUTPUT, sampleSize);
Arrays.sort(expected);
verifyExpectedResults(partitionSize, sampleSize, expected);
}
/** Sample size 200%. */
@Test
public void testSampleSizeDouble() throws DbException {
int partitionSize = INPUT_VALS.length;
int sampleSize = INPUT_VALS.length * 2;
int[] expected = Arrays.copyOf(SEED_OUTPUT, sampleSize);
Arrays.sort(expected);
verifyExpectedResults(partitionSize, sampleSize, expected);
}
/** Cannot have a negative sample size. */
@Test(expected = IllegalStateException.class)
public void testSampleSizeNegative() throws DbException {
int partitionSize = INPUT_VALS.length;
int sampleSize = -1;
drainOperator(partitionSize, sampleSize);
}
/** Cannot have a negative partition size. */
@Test(expected = IllegalStateException.class)
public void testSamplePartitionNegative() throws DbException {
int partitionSize = -1;
int sampleSize = 3;
drainOperator(partitionSize, sampleSize);
}
@After
public void cleanup() throws DbException {
if (sampOp != null && sampOp.isOpen()) {
sampOp.close();
}
}
/** Tests the correctness of a sampling operation using a seeded value. */
private void verifyExpectedResults(int partitionSize, int sampleSize, int[] expected)
throws DbException {
leftInput.putInt(1, partitionSize);
leftInput.putInt(2, sampleSize);
leftInput.putString(3, "WithReplacement");
sampOp =
new Sample(new BatchTupleSource(leftInput), new BatchTupleSource(rightInput), RANDOM_SEED);
sampOp.open(TestEnvVars.get());
int rowIdx = 0;
while (!sampOp.eos()) {
TupleBatch result = sampOp.nextReady();
if (result != null) {
assertEquals(OUTPUT_SCHEMA, result.getSchema());
for (int i = 0; i < result.numTuples(); ++i, ++rowIdx) {
assertEquals(result.getInt(0, i), expected[rowIdx]);
}
}
}
assertEquals(sampleSize, rowIdx);
}
/** Run through all results without doing anything. */
private void drainOperator(int partitionSize, int sampleSize) throws DbException {
leftInput.putInt(1, partitionSize);
leftInput.putInt(2, sampleSize);
leftInput.putString(3, "WithReplacement");
sampOp =
new Sample(new BatchTupleSource(leftInput), new BatchTupleSource(rightInput), RANDOM_SEED);
sampOp.open(TestEnvVars.get());
while (!sampOp.eos()) {
sampOp.nextReady();
}
}
}
|
3e09e3a403fc3113926e3aaa42377289a2745275 | 3,687 | java | Java | src/main/java/info/gianlucacosta/arcontes/fx/rendering/metainfo/DefaultLinkLabelConnectorRenderingInfo.java | giancosta86/Arcontes-fx | 5b0db13e3d3c18d5a87f87a10a749b14e9478198 | [
"Apache-2.0"
] | null | null | null | src/main/java/info/gianlucacosta/arcontes/fx/rendering/metainfo/DefaultLinkLabelConnectorRenderingInfo.java | giancosta86/Arcontes-fx | 5b0db13e3d3c18d5a87f87a10a749b14e9478198 | [
"Apache-2.0"
] | null | null | null | src/main/java/info/gianlucacosta/arcontes/fx/rendering/metainfo/DefaultLinkLabelConnectorRenderingInfo.java | giancosta86/Arcontes-fx | 5b0db13e3d3c18d5a87f87a10a749b14e9478198 | [
"Apache-2.0"
] | null | null | null | 29.97561 | 96 | 0.623 | 4,189 | /*§
===========================================================================
Arcontes - FX
===========================================================================
Copyright (C) 2013-2015 Gianluca Costa
===========================================================================
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 info.gianlucacosta.arcontes.fx.rendering.metainfo;
import info.gianlucacosta.helios.collections.general.CollectionItems;
import info.gianlucacosta.helios.fx.serialization.SerializableColor;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
/**
* Basic implementation of LinkLabelConnectorRenderingInfo
*/
public class DefaultLinkLabelConnectorRenderingInfo implements LinkLabelConnectorRenderingInfo {
private SerializableColor color;
private double lineSize;
private double opacity;
private Collection<Double> lineDashItems;
public DefaultLinkLabelConnectorRenderingInfo() {
color = new SerializableColor(Color.RED);
lineSize = 1;
opacity = 0;
lineDashItems = new ArrayList<>();
lineDashItems.add(5.0);
lineDashItems.add(5.0);
}
public DefaultLinkLabelConnectorRenderingInfo(LinkLabelConnectorRenderingInfo source) {
color = new SerializableColor(source.getColor());
lineSize = source.getLineSize();
opacity = source.getOpacity();
lineDashItems = new ArrayList<>(source.getLineDashItems());
}
@Override
public Color getColor() {
return color.getFxColor();
}
public void setColor(Color color) {
this.color = new SerializableColor(color);
}
@Override
public double getLineSize() {
return lineSize;
}
public void setLineSize(double lineSize) {
if (lineSize < 0) {
throw new IllegalArgumentException();
}
this.lineSize = lineSize;
}
@Override
public Collection<Double> getLineDashItems() {
return Collections.unmodifiableCollection(lineDashItems);
}
public void setLineDashItems(Collection<Double> lineDashItems) {
this.lineDashItems = lineDashItems;
}
@Override
public double getOpacity() {
return opacity;
}
public void setOpacity(double opacity) {
if (opacity < 0 || opacity > 1) {
throw new IllegalArgumentException();
}
this.opacity = opacity;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LinkLabelConnectorRenderingInfo)) {
return false;
}
LinkLabelConnectorRenderingInfo other = (LinkLabelConnectorRenderingInfo) obj;
return Objects.equals(color, other.getColor())
&& (lineSize == other.getLineSize())
&& (opacity == other.getOpacity())
&& CollectionItems.equals(getLineDashItems(), other.getLineDashItems());
}
@Override
public int hashCode() {
return super.hashCode();
}
}
|
3e09e49144fee8d54529bcab99efaee8e268b218 | 5,753 | java | Java | jobs/pacman-awsrules/src/test/java/com/tmobile/cloud/awsrules/iam/ServiceAccountPrivilegesRuleTest.java | lifer84/pacbot | 997c240c123d81cf3f55ff5093127c5fda6119c3 | [
"Apache-2.0"
] | 1,165 | 2018-10-05T19:07:34.000Z | 2022-03-28T19:34:27.000Z | jobs/pacman-awsrules/src/test/java/com/tmobile/cloud/awsrules/iam/ServiceAccountPrivilegesRuleTest.java | lifer84/pacbot | 997c240c123d81cf3f55ff5093127c5fda6119c3 | [
"Apache-2.0"
] | 334 | 2018-10-10T14:00:41.000Z | 2022-03-19T16:32:08.000Z | jobs/pacman-awsrules/src/test/java/com/tmobile/cloud/awsrules/iam/ServiceAccountPrivilegesRuleTest.java | lifer84/pacbot | 997c240c123d81cf3f55ff5093127c5fda6119c3 | [
"Apache-2.0"
] | 268 | 2018-10-05T19:53:25.000Z | 2022-03-31T07:39:47.000Z | 47.941667 | 182 | 0.733009 | 4,190 | /*******************************************************************************
* Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://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.tmobile.cloud.awsrules.iam;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient;
import com.amazonaws.services.identitymanagement.model.AccessKeyMetadata;
import com.amazonaws.services.identitymanagement.model.AttachedPolicy;
import com.amazonaws.services.identitymanagement.model.GetPolicyResult;
import com.amazonaws.services.identitymanagement.model.GetPolicyVersionResult;
import com.amazonaws.services.identitymanagement.model.ListAccessKeysResult;
import com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesResult;
import com.amazonaws.services.identitymanagement.model.ListAttachedUserPoliciesResult;
import com.amazonaws.services.identitymanagement.model.Policy;
import com.amazonaws.services.identitymanagement.model.PolicyVersion;
import com.tmobile.cloud.awsrules.utils.CommonTestUtils;
import com.tmobile.cloud.awsrules.utils.IAMUtils;
import com.tmobile.cloud.awsrules.utils.PacmanUtils;
import com.tmobile.pacman.commons.exception.InvalidInputException;
import com.tmobile.pacman.commons.exception.RuleExecutionFailedExeption;
import com.tmobile.pacman.commons.rule.BaseRule;
@PowerMockIgnore({"javax.net.ssl.*","javax.management.*"})
@RunWith(PowerMockRunner.class)
@PrepareForTest({URLDecoder.class, PacmanUtils.class,IAMUtils.class})
public class ServiceAccountPrivilegesRuleTest {
@InjectMocks
ServiceAccountPrivilegesRule serviceAccountPrivilegesRule;
@Mock
AmazonIdentityManagementClient identityManagementClient;
@Before
public void setUp() throws Exception{
identityManagementClient = PowerMockito.mock(AmazonIdentityManagementClient.class);
}
@Test
public void test()throws Exception{
AttachedPolicy attachedPolicies = new AttachedPolicy();
attachedPolicies.setPolicyName("IAMFullAccess");
List<AttachedPolicy> policies = new ArrayList<>();
policies.add(attachedPolicies);
mockStatic(PacmanUtils.class);
when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString(),anyString(),anyString())).thenReturn(
true);
Map<String,Object>map=new HashMap<String, Object>();
map.put("client", identityManagementClient);
ServiceAccountPrivilegesRule spy = Mockito.spy(new ServiceAccountPrivilegesRule());
Mockito.doReturn(map).when((BaseRule)spy).getClientFor(anyObject(), anyString(), anyObject());
mockStatic(IAMUtils.class);
when(PacmanUtils.splitStringToAList(anyString(),anyString())).thenReturn(CommonTestUtils.getListString());
when(IAMUtils.getAllowedActionsByUserPolicy(anyObject(),anyString())).thenReturn(CommonTestUtils.getSetString("svc_123"));
spy.execute(CommonTestUtils.getMapString("svc_123 "),CommonTestUtils.getMapString("svc_123 "));
spy.execute(CommonTestUtils.getMapString("svec_123 "),CommonTestUtils.getMapString("svec_123 "));
when(IAMUtils.getAttachedPolicyOfIAMUser(anyString(),anyObject())).thenThrow(new RuleExecutionFailedExeption());
assertThatThrownBy(
() -> serviceAccountPrivilegesRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString(),anyString(),anyString())).thenReturn(
false);
assertThatThrownBy(
() -> serviceAccountPrivilegesRule.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
}
@Test
public void getHelpTextTest(){
assertThat(serviceAccountPrivilegesRule.getHelpText(), is(notNullValue()));
}
}
|
3e09e4ee31a86213ab95c14859df50db4c8b1424 | 10,869 | java | Java | src/main/java/org/ohdsi/webapi/audittrail/AuditTrailServiceImpl.java | cumc-dbmi/WebAPI | 51f56718dc1807c601192b19f41005f40ad31b1e | [
"Apache-2.0"
] | 99 | 2015-01-06T18:24:25.000Z | 2022-03-10T16:34:04.000Z | src/main/java/org/ohdsi/webapi/audittrail/AuditTrailServiceImpl.java | cumc-dbmi/WebAPI | 51f56718dc1807c601192b19f41005f40ad31b1e | [
"Apache-2.0"
] | 1,261 | 2015-01-01T17:33:35.000Z | 2022-03-28T18:16:27.000Z | src/main/java/org/ohdsi/webapi/audittrail/AuditTrailServiceImpl.java | cumc-dbmi/WebAPI | 51f56718dc1807c601192b19f41005f40ad31b1e | [
"Apache-2.0"
] | 159 | 2015-01-12T13:39:42.000Z | 2022-03-15T13:39:31.000Z | 41.643678 | 130 | 0.654154 | 4,191 | package org.ohdsi.webapi.audittrail;
import com.cloudbees.syslog.Facility;
import com.cloudbees.syslog.Severity;
import com.cloudbees.syslog.SyslogMessage;
import org.apache.commons.lang3.StringUtils;
import org.ohdsi.webapi.Constants;
import org.ohdsi.webapi.cohortsample.dto.CohortSampleDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import javax.ws.rs.core.Response;
import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Component
class AuditTrailServiceImpl implements AuditTrailService {
private final Logger AUDIT_LOGGER = LoggerFactory.getLogger("audit");
private final Logger AUDIT_EXTRA_LOGGER = LoggerFactory.getLogger("audit-extra");
private static final int MAX_ENTRY_LENGTH = 2048;
private static final String EXTRA_LOG_REFERENCE_MESSAGE =
"... Log entry exceeds 2048 chars length. Please see the whole message in extra log file, entry id = %s";
private static final String USER_LOGIN_SUCCESS_TEMPLATE = "User successfully logged in: %s, sessionId = %s, remote-host = %s";
private static final String USER_LOGIN_FAILURE_TEMPLATE = "User login failed: %s, remote-host = %s";
private static final String USER_LOGOUT_SUCCESS_TEMPLATE = "User successfully logged out: %s";
private static final String USER_LOGOUT_FAILURE_TEMPLATE = "User logout failed: %s";
private static final String JOB_STARTED_TEMPLATE = "%s - Job %s execution started: %s";
private static final String JOB_COMPLETED_TEMPLATE = "%s - Job %s execution completed successfully: %s";
private static final String JOB_FAILED_TEMPLATE = "%s - Job %s execution failed: %s";
private static final String LIST_OF_TEMPLATE = "list of %s objects %s";
private static final String MAP_OF_TEMPLATE = "map (key: %s) of %s objects %s";
private static final String FILE_TEMPLATE = "file %s (%s bytes)";
private static final String PATIENT_IDS_TEMPLATE = " Patient IDs (%s): ";
private static final String FIELD_DIVIDER = " - ";
private static final String SPACE = " ";
private static final String FAILURE = "FAILURE (see application log for details)";
private static final String ANONYMOUS = "anonymous";
private static final String NO_SESSION = "NO_SESSION";
private static final String NO_LOCATION = "NO_LOCATION";
private static final String EMPTY_LIST = "empty list";
private static final String EMPTY_MAP = "empty map";
private final AtomicInteger extraLogIdSuffix = new AtomicInteger();
@Override
public void logSuccessfulLogin(final String login, final String sessionId, final String remoteHost) {
log(String.format(USER_LOGIN_SUCCESS_TEMPLATE, login, sessionId, remoteHost));
}
@Override
public void logFailedLogin(final String login, final String remoteHost) {
log(String.format(USER_LOGIN_FAILURE_TEMPLATE, login, remoteHost));
}
@Override
public void logSuccessfulLogout(final String login) {
log(String.format(USER_LOGOUT_SUCCESS_TEMPLATE, login));
}
@Override
public void logFailedLogout(final String login) {
log(String.format(USER_LOGOUT_FAILURE_TEMPLATE, login));
}
@Override
public void logRestCall(final AuditTrailEntry entry, final boolean success) {
final StringBuilder logEntry = new StringBuilder();
final String currentUserField = getCurrentUserField(entry);
logEntry.append(currentUserField).append(SPACE)
.append(entry.getRemoteHost()).append(SPACE)
.append(getSessionIdField(entry))
.append(FIELD_DIVIDER)
.append(getActionLocationField(entry))
.append(FIELD_DIVIDER)
.append(getRestCallField(entry));
if (success) {
final String additionalInfo = getAdditionalInfo(entry);
if (!StringUtils.isBlank(additionalInfo)) {
logEntry.append(FIELD_DIVIDER).append(additionalInfo);
}
} else {
logEntry.append(FIELD_DIVIDER).append(FAILURE);
}
log(logEntry.toString());
}
@Override
public void logJobStart(final JobExecution jobExecution) {
logJob(jobExecution, JOB_STARTED_TEMPLATE);
}
@Override
public void logJobCompleted(final JobExecution jobExecution) {
logJob(jobExecution, JOB_COMPLETED_TEMPLATE);
}
@Override
public void logJobFailed(JobExecution jobExecution) {
logJob(jobExecution, JOB_FAILED_TEMPLATE);
}
private void log(final String message) {
final SyslogMessage syslogMessage = new SyslogMessage()
.withFacility(Facility.AUDIT)
.withSeverity(Severity.INFORMATIONAL)
.withAppName("Atlas")
.withMsg(message);
final StringBuilder logEntry = new StringBuilder(syslogMessage.toRfc5424SyslogMessage());
if (logEntry.length() >= MAX_ENTRY_LENGTH) {
final String currentExtraSuffix = String.format("%02d", this.extraLogIdSuffix.getAndIncrement());
final String entryId = System.currentTimeMillis() + "_" + currentExtraSuffix;
AUDIT_EXTRA_LOGGER.info(entryId + FIELD_DIVIDER + message);
final String extraLogReferenceMessage = String.format(EXTRA_LOG_REFERENCE_MESSAGE, entryId);
logEntry.setLength(MAX_ENTRY_LENGTH - extraLogReferenceMessage.length() - 1);
logEntry.append(extraLogReferenceMessage);
AUDIT_LOGGER.info(logEntry.toString());
if (this.extraLogIdSuffix.get() > 99) {
this.extraLogIdSuffix.set(0);
}
} else {
AUDIT_LOGGER.info(logEntry.toString());
}
}
private String getSessionIdField(final AuditTrailEntry entry) {
return entry.getSessionId() != null ? entry.getSessionId() : NO_SESSION;
}
private String getCurrentUserField(final AuditTrailEntry entry) {
return (entry.getCurrentUser() != null ? String.valueOf(entry.getCurrentUser()) : ANONYMOUS);
}
private String getActionLocationField(final AuditTrailEntry entry) {
return entry.getActionLocation() != null ? entry.getActionLocation() : NO_LOCATION;
}
private String getRestCallField(final AuditTrailEntry entry) {
final StringBuilder sb = new StringBuilder();
sb.append(entry.getRequestMethod())
.append(" ")
.append(entry.getRequestUri());
if (!StringUtils.isBlank(entry.getQueryString())) {
sb.append("?").append(entry.getQueryString());
}
return sb.toString();
}
private String getAdditionalInfo(final AuditTrailEntry entry) {
final StringBuilder additionalInfo = new StringBuilder();
final String returnedObjectFields = getReturnedObjectFields(entry.getReturnedObject());
if (!StringUtils.isBlank(returnedObjectFields)) {
additionalInfo.append(returnedObjectFields);
}
// File entry log
if (entry.getReturnedObject() instanceof Response) {
try {
final Object entity = ((Response) entry.getReturnedObject()).getEntity();
if (entity instanceof File) {
final File file = (File) entity;
return String.format(FILE_TEMPLATE, file.getName(), file.length());
}
return null;
} catch (final Exception e) {
return null;
}
}
// Patient IDs log
if (entry.getReturnedObject() instanceof CohortSampleDTO) {
final CohortSampleDTO sampleDto = (CohortSampleDTO) entry.getReturnedObject();
if (sampleDto.getElements().isEmpty()) {
additionalInfo.append(String.format(PATIENT_IDS_TEMPLATE, 0)).append("none");
} else {
additionalInfo.append(String.format(PATIENT_IDS_TEMPLATE, sampleDto.getElements().size()));
sampleDto.getElements().forEach((e) -> {
additionalInfo.append(e.getPersonId()).append(" ");
});
}
}
return additionalInfo.toString();
}
private String getReturnedObjectFields(final Object returnedObject) {
if (returnedObject == null) {
return null;
}
if (returnedObject instanceof Collection) {
final Collection<?> c = (Collection<?>) returnedObject;
if (!c.isEmpty()) {
final String fields = collectClassFieldNames(c.iterator().next().getClass());
return fields != null ? String.format(LIST_OF_TEMPLATE, c.size(), fields) : null;
}
return EMPTY_LIST;
} if (returnedObject instanceof Map) {
final Map<?, ?> map = (Map<?, ?>) returnedObject;
if (!map.isEmpty()) {
final Map.Entry<?, ?> entry = map.entrySet().iterator().next();
final Class<?> keyClass = entry.getKey().getClass();
final Class<?> valueClass = entry.getValue().getClass();
final String valueFields = collectClassFieldNames(valueClass);
return valueFields != null ?
String.format(MAP_OF_TEMPLATE, keyClass.getSimpleName(), map.size(), valueFields) : null;
}
return EMPTY_MAP;
} else {
return collectClassFieldNames(returnedObject.getClass());
}
}
private String collectClassFieldNames(final Class<?> klass) {
if (!klass.getPackage().getName().startsWith("org.ohdsi.")) {
return null;
}
// collect only first level field names
final StringBuilder sb = new StringBuilder();
sb.append("{");
ReflectionUtils.doWithFields(klass,
field -> sb.append(field.getName()).append("::").append(field.getType().getSimpleName()).append(","));
if (sb.length() > 1) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("}");
return sb.toString();
}
private void logJob(final JobExecution jobExecution, final String template) {
final JobParameters jobParameters = jobExecution.getJobParameters();
final String author = jobParameters.getString(Constants.Params.JOB_AUTHOR);
if (author.equals("anonymous")) { // system jobs
return;
}
final String jobName = jobParameters.getString(Constants.Params.JOB_NAME);
log(String.format(template, author, jobExecution.getJobId(), jobName));
}
}
|
3e09e52e38fd0457c9aacba363c12e812df55e30 | 3,294 | java | Java | src/main/java/ec/edu/espe/saturn/model/Ptrtenr.java | NinjaDevelopersEspeYavirac/SATURN2017 | f62dff91c9b82456d6c350140b2c64523a46b52d | [
"Apache-2.0"
] | null | null | null | src/main/java/ec/edu/espe/saturn/model/Ptrtenr.java | NinjaDevelopersEspeYavirac/SATURN2017 | f62dff91c9b82456d6c350140b2c64523a46b52d | [
"Apache-2.0"
] | null | null | null | src/main/java/ec/edu/espe/saturn/model/Ptrtenr.java | NinjaDevelopersEspeYavirac/SATURN2017 | f62dff91c9b82456d6c350140b2c64523a46b52d | [
"Apache-2.0"
] | null | null | null | 31.075472 | 284 | 0.702186 | 4,192 | package ec.edu.espe.saturn.model;
// Generated 27-oct-2017 9:54:16 by Hibernate Tools 4.3.1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Ptrtenr generated by hbm2java
*/
public class Ptrtenr implements java.io.Serializable {
private String ptrtenrCode;
private String ptrtenrDesc;
private String ptrtenrDateInd;
private String ptrtenrReviewDateInd;
private String ptrtenrEeoTenureInd;
private Date ptrtenrActivityDate;
private Set perappts = new HashSet(0);
public Ptrtenr() {
}
public Ptrtenr(String ptrtenrCode, String ptrtenrDesc, String ptrtenrDateInd, String ptrtenrReviewDateInd, String ptrtenrEeoTenureInd, Date ptrtenrActivityDate) {
this.ptrtenrCode = ptrtenrCode;
this.ptrtenrDesc = ptrtenrDesc;
this.ptrtenrDateInd = ptrtenrDateInd;
this.ptrtenrReviewDateInd = ptrtenrReviewDateInd;
this.ptrtenrEeoTenureInd = ptrtenrEeoTenureInd;
this.ptrtenrActivityDate = ptrtenrActivityDate;
}
public Ptrtenr(String ptrtenrCode, String ptrtenrDesc, String ptrtenrDateInd, String ptrtenrReviewDateInd, String ptrtenrEeoTenureInd, Date ptrtenrActivityDate, Set perappts) {
this.ptrtenrCode = ptrtenrCode;
this.ptrtenrDesc = ptrtenrDesc;
this.ptrtenrDateInd = ptrtenrDateInd;
this.ptrtenrReviewDateInd = ptrtenrReviewDateInd;
this.ptrtenrEeoTenureInd = ptrtenrEeoTenureInd;
this.ptrtenrActivityDate = ptrtenrActivityDate;
this.perappts = perappts;
}
public String getPtrtenrCode() {
return this.ptrtenrCode;
}
public void setPtrtenrCode(String ptrtenrCode) {
this.ptrtenrCode = ptrtenrCode;
}
public String getPtrtenrDesc() {
return this.ptrtenrDesc;
}
public void setPtrtenrDesc(String ptrtenrDesc) {
this.ptrtenrDesc = ptrtenrDesc;
}
public String getPtrtenrDateInd() {
return this.ptrtenrDateInd;
}
public void setPtrtenrDateInd(String ptrtenrDateInd) {
this.ptrtenrDateInd = ptrtenrDateInd;
}
public String getPtrtenrReviewDateInd() {
return this.ptrtenrReviewDateInd;
}
public void setPtrtenrReviewDateInd(String ptrtenrReviewDateInd) {
this.ptrtenrReviewDateInd = ptrtenrReviewDateInd;
}
public String getPtrtenrEeoTenureInd() {
return this.ptrtenrEeoTenureInd;
}
public void setPtrtenrEeoTenureInd(String ptrtenrEeoTenureInd) {
this.ptrtenrEeoTenureInd = ptrtenrEeoTenureInd;
}
public Date getPtrtenrActivityDate() {
return this.ptrtenrActivityDate;
}
public void setPtrtenrActivityDate(Date ptrtenrActivityDate) {
this.ptrtenrActivityDate = ptrtenrActivityDate;
}
public Set getPerappts() {
return this.perappts;
}
public void setPerappts(Set perappts) {
this.perappts = perappts;
}
@Override
public String toString() {
return "Ptrtenr{" + "ptrtenrCode=" + ptrtenrCode + ", ptrtenrDesc=" + ptrtenrDesc + ", ptrtenrDateInd=" + ptrtenrDateInd + ", ptrtenrReviewDateInd=" + ptrtenrReviewDateInd + ", ptrtenrEeoTenureInd=" + ptrtenrEeoTenureInd + ", ptrtenrActivityDate=" + ptrtenrActivityDate + '}';
}
}
|
3e09e5869dcbdc0cb4169d63a2fcfd61e9adfe3a | 13,863 | java | Java | oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/CommitQueueTest.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 288 | 2015-01-11T04:09:03.000Z | 2022-03-28T22:20:09.000Z | oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/CommitQueueTest.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 154 | 2016-10-30T11:31:04.000Z | 2022-03-31T14:20:52.000Z | oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/CommitQueueTest.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 405 | 2015-01-15T16:15:56.000Z | 2022-03-24T08:27:08.000Z | 35.007576 | 107 | 0.537618 | 4,193 | /*
* 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.jackrabbit.oak.plugins.document;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.commit.Observer;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.collect.ImmutableSet.of;
import static com.google.common.collect.Sets.union;
import static java.util.Collections.synchronizedList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/**
* Tests for {@link CommitQueue}.
*/
public class CommitQueueTest {
@Rule
public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();
private static final Logger LOG = LoggerFactory.getLogger(CommitQueueTest.class);
private static final int NUM_WRITERS = 10;
private static final int COMMITS_PER_WRITER = 100;
private List<Exception> exceptions = synchronizedList(new ArrayList<Exception>());
@Test
public void concurrentCommits() throws Exception {
final DocumentNodeStore store = builderProvider.newBuilder().getNodeStore();
AtomicBoolean running = new AtomicBoolean(true);
Closeable observer = store.addObserver(new Observer() {
private RevisionVector before = new RevisionVector(
new Revision(0, 0, store.getClusterId()));
@Override
public void contentChanged(@NotNull NodeState root, @Nullable CommitInfo info) {
DocumentNodeState after = (DocumentNodeState) root;
RevisionVector r = after.getRootRevision();
LOG.debug("seen: {}", r);
if (r.compareTo(before) < 0) {
exceptions.add(new Exception(
"Inconsistent revision sequence. Before: " +
before + ", after: " + r));
}
before = r;
}
});
// perform commits with multiple threads
List<Thread> writers = new ArrayList<Thread>();
for (int i = 0; i < NUM_WRITERS; i++) {
final Random random = new Random(i);
writers.add(new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < COMMITS_PER_WRITER; i++) {
Commit commit = store.newCommit(nop -> {}, null, null);
try {
Thread.sleep(0, random.nextInt(1000));
} catch (InterruptedException e) {
// ignore
}
if (random.nextInt(5) == 0) {
// cancel 20% of the commits
store.canceled(commit);
} else {
boolean isBranch = random.nextInt(5) == 0;
store.done(commit, isBranch, CommitInfo.EMPTY);
}
}
} catch (Exception e) {
exceptions.add(e);
}
}
}));
}
for (Thread t : writers) {
t.start();
}
for (Thread t : writers) {
t.join();
}
running.set(false);
observer.close();
store.dispose();
assertNoExceptions();
}
@Test
public void concurrentCommits2() throws Exception {
final CommitQueue queue = new CommitQueue(DummyRevisionContext.INSTANCE);
final CommitQueue.Callback c = new CommitQueue.Callback() {
private Revision before = Revision.newRevision(1);
@Override
public void headOfQueue(@NotNull Revision r) {
LOG.debug("seen: {}", r);
if (r.compareRevisionTime(before) < 0) {
exceptions.add(new Exception(
"Inconsistent revision sequence. Before: " +
before + ", after: " + r));
}
before = r;
}
};
// perform commits with multiple threads
List<Thread> writers = new ArrayList<Thread>();
for (int i = 0; i < NUM_WRITERS; i++) {
final Random random = new Random(i);
writers.add(new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < COMMITS_PER_WRITER; i++) {
Revision r = queue.createRevision();
try {
Thread.sleep(0, random.nextInt(1000));
} catch (InterruptedException e) {
// ignore
}
if (random.nextInt(5) == 0) {
// cancel 20% of the commits
queue.canceled(r);
} else {
queue.done(r, c);
}
}
} catch (Exception e) {
exceptions.add(e);
}
}
}));
}
for (Thread t : writers) {
t.start();
}
for (Thread t : writers) {
t.join();
}
assertNoExceptions();
}
// OAK-2868
@Test
public void branchCommitMustNotBlockTrunkCommit() throws Exception {
final DocumentNodeStore ds = builderProvider.newBuilder().getNodeStore();
// simulate start of a branch commit
Commit c = ds.newCommit(nop -> {}, ds.getHeadRevision().asBranchRevision(ds.getClusterId()), null);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
NodeBuilder builder = ds.getRoot().builder();
builder.child("foo");
ds.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
} catch (CommitFailedException e) {
exceptions.add(e);
}
}
});
t.start();
t.join(3000);
assertFalse("Commit did not succeed within 3 seconds", t.isAlive());
ds.canceled(c);
assertNoExceptions();
}
@Test
public void suspendUntil() throws Exception {
final AtomicReference<RevisionVector> headRevision = new AtomicReference<RevisionVector>();
RevisionContext context = new DummyRevisionContext() {
@NotNull
@Override
public RevisionVector getHeadRevision() {
return headRevision.get();
}
};
headRevision.set(new RevisionVector(context.newRevision()));
final CommitQueue queue = new CommitQueue(context);
final Revision newHeadRev = context.newRevision();
final Set<Revision> revisions = queue.createRevisions(10);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
queue.suspendUntilAll(union(of(newHeadRev), revisions));
}
});
t.start();
// wait until t is suspended
for (int i = 0; i < 100; i++) {
if (queue.numSuspendedThreads() > 0) {
break;
}
Thread.sleep(10);
}
assertEquals(1, queue.numSuspendedThreads());
queue.headRevisionChanged();
// must still be suspended
assertEquals(1, queue.numSuspendedThreads());
headRevision.set(new RevisionVector(newHeadRev));
queue.headRevisionChanged();
// must still be suspended
assertEquals(1, queue.numSuspendedThreads());
for (Revision rev : revisions) {
queue.canceled(rev);
}
// must not be suspended anymore
assertEquals(0, queue.numSuspendedThreads());
}
@Test
public void suspendUntilTimeout() throws Exception {
final AtomicReference<RevisionVector> headRevision = new AtomicReference<RevisionVector>();
RevisionContext context = new DummyRevisionContext() {
@NotNull
@Override
public RevisionVector getHeadRevision() {
return headRevision.get();
}
};
headRevision.set(new RevisionVector(context.newRevision()));
final CommitQueue queue = new CommitQueue(context);
queue.setSuspendTimeoutMillis(0);
final Revision r = context.newRevision();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
queue.suspendUntilAll(of(r));
}
});
t.start();
t.join(1000);
assertFalse(t.isAlive());
}
@Test
public void concurrentSuspendUntil() throws Exception {
final AtomicReference<RevisionVector> headRevision = new AtomicReference<RevisionVector>();
RevisionContext context = new DummyRevisionContext() {
@NotNull
@Override
public RevisionVector getHeadRevision() {
return headRevision.get();
}
};
headRevision.set(new RevisionVector(context.newRevision()));
List<Thread> threads = new ArrayList<Thread>();
List<Revision> allRevisions = new ArrayList<Revision>();
final CommitQueue queue = new CommitQueue(context);
for (int i = 0; i < 10; i++) { // threads count
final Set<Revision> revisions = new HashSet<Revision>();
for (int j = 0; j < 10; j++) { // revisions per thread
Revision r = queue.createRevision();
revisions.add(r);
allRevisions.add(r);
}
Thread t = new Thread(new Runnable() {
public void run() {
queue.suspendUntilAll(revisions);
}
});
threads.add(t);
t.start();
}
for (int i = 0; i < 100; i++) {
if (queue.numSuspendedThreads() == 10) {
break;
}
Thread.sleep(10);
}
assertEquals(10, queue.numSuspendedThreads());
Collections.shuffle(allRevisions);
for (Revision r : allRevisions) {
queue.canceled(r);
Thread.sleep(10);
}
for (int i = 0; i < 100; i++) {
if (queue.numSuspendedThreads() == 0) {
break;
}
Thread.sleep(10);
}
assertEquals(0, queue.numSuspendedThreads());
for (Thread t : threads) {
t.join(1000);
assertFalse(t.isAlive());
}
}
// OAK-4540
@Test
public void headOfQueueMustNotBlockNewRevision() throws Exception {
RevisionContext context = new DummyRevisionContext();
final CommitQueue queue = new CommitQueue(context);
final Revision r1 = queue.createRevision();
final Semaphore s1 = new Semaphore(0);
final CommitQueue.Callback c = new CommitQueue.Callback() {
@Override
public void headOfQueue(@NotNull Revision revision) {
s1.acquireUninterruptibly();
}
};
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
queue.done(r1, c);
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
queue.createRevision();
}
});
t2.start();
t2.join(3000);
try {
if (t2.isAlive()) {
fail("CommitQueue.Callback.headOfQueue() must not " +
"block CommitQueue.createRevision()");
}
} finally {
s1.release();
t1.join();
t2.join();
}
}
private void assertNoExceptions() throws Exception {
if (!exceptions.isEmpty()) {
throw exceptions.get(0);
}
}
}
|
3e09e59bd6a718dfb64a36eba99902b7512552a8 | 555 | java | Java | hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/mapping/SyntheticProperty.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | 1 | 2021-11-11T01:36:23.000Z | 2021-11-11T01:36:23.000Z | hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/mapping/SyntheticProperty.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/mapping/SyntheticProperty.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | 25.227273 | 99 | 0.727928 | 4,194 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.mapping;
/**
* Models a property which does not actually exist in the model. It is created by Hibernate during
* the metamodel binding process.
*
* @author Steve Ebersole
*/
public class SyntheticProperty extends Property {
@Override
public boolean isSynthetic() {
return true;
}
}
|
3e09e60009a3ad164e80d87020257f4eddf38201 | 1,842 | java | Java | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/ClientException.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/ClientException.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/ClientException.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 27.492537 | 119 | 0.684582 | 4,195 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. 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.directory.model;
import javax.annotation.Generated;
/**
* <p>
* A client exception has occurred.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ClientException extends com.amazonaws.services.directory.model.AWSDirectoryServiceException {
private static final long serialVersionUID = 1L;
private String requestId;
/**
* Constructs a new ClientException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public ClientException(String message) {
super(message);
}
/**
* @param requestId
*/
@com.fasterxml.jackson.annotation.JsonProperty("RequestId")
public void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* @return
*/
@com.fasterxml.jackson.annotation.JsonProperty("RequestId")
public String getRequestId() {
return this.requestId;
}
/**
* @param requestId
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ClientException withRequestId(String requestId) {
setRequestId(requestId);
return this;
}
}
|
3e09e643a7c4a36731c8ee16e3364f4f745163f9 | 4,617 | java | Java | Java/00-Code/Imooc-Socket/Java-Socket/src/main/chat-room-stream/clink/impl/SocketChannelAdapter.java | hiloWang/notes | 64a637a86f734e4e80975f4aa93ab47e8d7e8b64 | [
"Apache-2.0"
] | 2 | 2020-10-08T13:22:08.000Z | 2021-07-28T14:45:41.000Z | Java/Imooc-Socket/Java-Socket/src/main/chat-room-stream/clink/impl/SocketChannelAdapter.java | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | null | null | null | Java/Imooc-Socket/Java-Socket/src/main/chat-room-stream/clink/impl/SocketChannelAdapter.java | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | 6 | 2020-08-20T07:19:17.000Z | 2022-03-02T08:16:21.000Z | 33.456522 | 161 | 0.649773 | 4,196 | package clink.impl;
import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicBoolean;
import clink.core.IoArgs;
import clink.core.IoProvider;
import clink.core.Receiver;
import clink.core.Sender;
import clink.utils.CloseUtils;
/**
* SocketChannel 对读写的实现。
*/
public class SocketChannelAdapter implements Sender, Receiver, Cloneable {
private final AtomicBoolean mIsClosed = new AtomicBoolean(false);
private final SocketChannel mChannel;
private final IoProvider mIoProvider;
private final OnChannelStatusChangedListener mOnChannelStatusChangedListener;
private IoArgs.IoArgsEventProcessor mReceiveIoEventListener;
private IoArgs.IoArgsEventProcessor mSendIoEventListener;
public SocketChannelAdapter(SocketChannel channel, IoProvider ioProvider, OnChannelStatusChangedListener onChannelStatusChangedListener) throws IOException {
this.mChannel = channel;
this.mIoProvider = ioProvider;
this.mOnChannelStatusChangedListener = onChannelStatusChangedListener;
this.mChannel.configureBlocking(false);
}
@Override
public void close() throws IOException {
if (mIsClosed.compareAndSet(false, true)) {
// 解除注册回调
mIoProvider.unRegisterInput(mChannel);
mIoProvider.unRegisterOutput(mChannel);
// 关闭
CloseUtils.close(mChannel);
// 回调当前Channel已关闭
mOnChannelStatusChangedListener.onChannelClosed(mChannel);
}
}
@Override
public boolean postSendAsync() throws IOException {
//检查是否已经关闭
checkState();
//向 IoProvider 注册读回调,当可写时,mHandleOutputCallback 会被回调
return mIoProvider.registerOutput(mChannel, mHandleOutputCallback);
}
@Override
public void setSendListener(IoArgs.IoArgsEventProcessor ioArgsEventProcessor) {
//保存 IO 事件监听器
mSendIoEventListener = ioArgsEventProcessor;
}
private void checkState() throws IOException {
if (mIsClosed.get()) {
throw new IOException("Current channel is closed!");
}
}
@Override
public boolean postReceiveAsync() throws IOException {
//检查是否已经关闭
checkState();
//向 IoProvider 注册读回调,当可读时,mHandleInputCallback 会被回调
return mIoProvider.registerInput(mChannel, mHandleInputCallback);
}
@Override
public void setReceiveListener(IoArgs.IoArgsEventProcessor ioArgsEventProcessor) {
mReceiveIoEventListener = ioArgsEventProcessor;
}
public interface OnChannelStatusChangedListener {
void onChannelClosed(SocketChannel channel);
}
/*当选择器选择对应的Channel可读时,将回调此接口*/
private IoProvider.HandleInputCallback mHandleInputCallback = new IoProvider.HandleInputCallback() {
@Override
protected void canProviderInput() {
if (mIsClosed.get()) {
return;
}
IoArgs.IoArgsEventProcessor listener = mReceiveIoEventListener;
//回调读取开始
IoArgs ioArgs = listener.provideIoArgs();
//具体的读取操作
try {
if (ioArgs.readFrom(mChannel) > 0) {
// 读取完成回调
listener.onConsumeCompleted(ioArgs);
} else {//Selector 选择后却又读不到数据,说明连接出问题了
listener.consumeFailed(ioArgs, new IOException("Cannot read any data!"));
}
} catch (IOException e) {
e.printStackTrace();
CloseUtils.close(SocketChannelAdapter.this);
}
}
};// mHandleInputCallback end
/*当选择器选择对应的Channel可写时,将回调此接口*/
private final IoProvider.HandleOutputCallback mHandleOutputCallback = new IoProvider.HandleOutputCallback() {
@Override
protected void canProviderOutput() {
if (mIsClosed.get()) {
return;
}
IoArgs.IoArgsEventProcessor listener = mSendIoEventListener;
IoArgs ioArgs = listener.provideIoArgs();
try {
if (ioArgs.writeTo(mChannel) > 0) {//具体的写操作
//此次写完回调回去,继续下一步操作
mSendIoEventListener.onConsumeCompleted(ioArgs);
} else {//Selector 选择后却又写不出数据,说明连接出问题了
mSendIoEventListener.consumeFailed(ioArgs, new IOException("Cannot write any data!"));
}
} catch (IOException e) {
e.printStackTrace();
CloseUtils.close(SocketChannelAdapter.this);
}
}
};//mHandleOutputCallback end
} |
3e09e6b7337ee62e55c7bef2796cc2fbcad22ce6 | 128 | java | Java | Bingo Client/src/me/dylanmullen/bingo/gfx/ui/buttons/ButtonListener.java | DylanMullen/Bingo | a1e33dd0c88768474f496e7cc2119151761af7c9 | [
"CC0-1.0"
] | 1 | 2021-02-19T12:18:41.000Z | 2021-02-19T12:18:41.000Z | Bingo Client/src/me/dylanmullen/bingo/gfx/ui/buttons/ButtonListener.java | DylanMullen/Bingo | a1e33dd0c88768474f496e7cc2119151761af7c9 | [
"CC0-1.0"
] | null | null | null | Bingo Client/src/me/dylanmullen/bingo/gfx/ui/buttons/ButtonListener.java | DylanMullen/Bingo | a1e33dd0c88768474f496e7cc2119151761af7c9 | [
"CC0-1.0"
] | null | null | null | 14.222222 | 45 | 0.742188 | 4,197 | package me.dylanmullen.bingo.gfx.ui.buttons;
@FunctionalInterface
public interface ButtonListener
{
void invoke();
}
|
3e09e806553e8b853ef3394d5e4408306f262875 | 796 | java | Java | src/main/java/com/fun/project/admin/monitor/entity/JobLog.java | mrdjun/funboot-redis | 88c86b09f8d6874e5658bcca562c4b94c247a690 | [
"MIT"
] | null | null | null | src/main/java/com/fun/project/admin/monitor/entity/JobLog.java | mrdjun/funboot-redis | 88c86b09f8d6874e5658bcca562c4b94c247a690 | [
"MIT"
] | null | null | null | src/main/java/com/fun/project/admin/monitor/entity/JobLog.java | mrdjun/funboot-redis | 88c86b09f8d6874e5658bcca562c4b94c247a690 | [
"MIT"
] | null | null | null | 13.964912 | 52 | 0.591709 | 4,198 | package com.fun.project.admin.monitor.entity;
import com.fun.framework.web.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 定时任务调度日志表
*
* @author DJun
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class JobLog extends BaseEntity {
private static final long serialVersionUID = 1L;
private Long jobLogId;
/**
* 任务名称
*/
private String jobName;
/**
* 任务组名
*/
private String jobGroup;
/**
* 调用目标字符串
*/
private String invokeTarget;
/**
* 日志信息
*/
private String jobMessage;
/**
* 异常信息
*/
private String exceptionInfo;
/**
* 开始时间
*/
private Date startTime;
/**
* 结束时间
*/
private Date endTime;
}
|
3e09e8b227f3f030f39d60f14f0ba23b3f12e2d9 | 2,334 | java | Java | ebean-test/src/test/java/io/ebeaninternal/server/type/BasePlatformArrayTypeFactoryTest.java | tibco-jufernan/ebean-h2-fix | acfd882078ad154886a81c7baf193d88d58877f8 | [
"Apache-2.0"
] | 1,041 | 2016-08-03T12:27:03.000Z | 2022-03-31T20:06:05.000Z | ebean-test/src/test/java/io/ebeaninternal/server/type/BasePlatformArrayTypeFactoryTest.java | tibco-jufernan/ebean-h2-fix | acfd882078ad154886a81c7baf193d88d58877f8 | [
"Apache-2.0"
] | 1,501 | 2016-08-03T11:37:04.000Z | 2022-03-31T20:03:05.000Z | ebean-test/src/test/java/io/ebeaninternal/server/type/BasePlatformArrayTypeFactoryTest.java | tibco-jufernan/ebean-h2-fix | acfd882078ad154886a81c7baf193d88d58877f8 | [
"Apache-2.0"
] | 196 | 2016-08-09T03:26:24.000Z | 2022-03-27T15:12:06.000Z | 24.829787 | 79 | 0.674379 | 4,199 | package io.ebeaninternal.server.type;
import io.ebean.core.type.ScalarType;
import org.postgresql.util.PGobject;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BasePlatformArrayTypeFactoryTest {
void assertBindNullTo_Null(ScalarType<?> type) throws SQLException {
TestDoubleDataBind bind = new TestDoubleDataBind();
type.bind(bind, null);
assertTrue(bind.wasSetNull);
}
void assertBindNullTo_EmptyArray(ScalarType<?> type) throws SQLException {
TestDoubleDataBind bind = new TestDoubleDataBind();
type.bind(bind, null);
assertTrue(bind.wasEmptyArray);
}
void assertBindNullTo_EmptyString(ScalarType<?> type) throws SQLException {
TestDoubleDataBind bind = new TestDoubleDataBind();
type.bind(bind, null);
assertTrue(bind.setEmptyString);
}
void assertBindNullTo_PGObjectNull(ScalarType<?> type) throws SQLException {
TestDoubleDataBind bind = new TestDoubleDataBind();
type.bind(bind, null);
assertTrue(bind.wasPgoNull);
}
void assertBindNullTo_PGObjectEmpty(ScalarType<?> type) throws SQLException {
TestDoubleDataBind bind = new TestDoubleDataBind();
type.bind(bind, null);
assertTrue(bind.wasPgoEmpty);
}
static class TestDoubleDataBind extends DataBind {
boolean setEmptyString;
boolean wasSetNull;
boolean setArray;
boolean wasNull;
boolean wasEmptyArray;
boolean wasPgoNull;
boolean wasPgoEmpty;
TestDoubleDataBind() {
super(null, null, null);
}
@Override
public void setNull(int jdbcType) {
wasSetNull = true;
}
@Override
public void setString(String s) {
setEmptyString = "[]".equals(s);
}
@Override
public void setObject(Object value) {
wasNull = value == null;
if (!wasNull) {
if (value instanceof Object[]) {
wasEmptyArray = ((Object[]) value).length == 0;
} else {
PGobject pgo = (PGobject) value;
wasPgoEmpty = "[]".equals(pgo.getValue());
wasPgoNull = pgo.getValue() == null;
}
}
}
@Override
public void setArray(String arrayType, Object[] elements) {
setArray = true;
wasNull = elements == null;
wasEmptyArray = (elements != null && elements.length == 0);
}
}
}
|
3e09e98198d3c7e62b5077f8f80396f29b00b34c | 628 | java | Java | java-core/src/main/java/com/sayemahmed/example/executor/ExpensiveComputation.java | sayembd/java-examples | 0cd455fd011269f45b610133da7a8593688e3a20 | [
"Apache-2.0"
] | 19 | 2017-03-22T06:42:15.000Z | 2019-08-24T04:08:53.000Z | java-core/src/main/java/com/sayemahmed/example/executor/ExpensiveComputation.java | sayembd/java-examples | 0cd455fd011269f45b610133da7a8593688e3a20 | [
"Apache-2.0"
] | 2 | 2017-03-16T16:41:22.000Z | 2017-06-26T16:06:05.000Z | java-core/src/main/java/com/sayemahmed/example/executor/ExpensiveComputation.java | sayembd/java-examples | 0cd455fd011269f45b610133da7a8593688e3a20 | [
"Apache-2.0"
] | 21 | 2017-03-16T14:25:08.000Z | 2021-03-15T17:02:49.000Z | 25.12 | 103 | 0.646497 | 4,200 | package com.sayemahmed.example.executor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
class ExpensiveComputation {
private final int id;
ExpensiveComputation(int id) {
this.id = id;
}
void compute() {
try {
log.info("{} - I am trying to compute some heavy stuff. Current thread interruption status: {}.",
id, Thread.currentThread().isInterrupted());
Thread.sleep(1000);
log.info("{} - I finished my computation", id);
} catch (InterruptedException e) {
log.error("{} - I was interrupted during my computation.", id, e);
Thread.currentThread().interrupt();
}
}
}
|
3e09e9fb1aada529e31b06f0f53767d3c1e84ade | 1,204 | java | Java | src/main/java/org/isouth/cat/tomcat/CatEndpoint.java | qiyi/cat | 795bb710b4e35b1c295bb92403b3046bdbdd46f3 | [
"MIT"
] | null | null | null | src/main/java/org/isouth/cat/tomcat/CatEndpoint.java | qiyi/cat | 795bb710b4e35b1c295bb92403b3046bdbdd46f3 | [
"MIT"
] | null | null | null | src/main/java/org/isouth/cat/tomcat/CatEndpoint.java | qiyi/cat | 795bb710b4e35b1c295bb92403b3046bdbdd46f3 | [
"MIT"
] | null | null | null | 30.871795 | 96 | 0.730066 | 4,201 | package org.isouth.cat.tomcat;
import org.isouth.cat.Cat;
import org.isouth.cat.Subscriber;
import org.isouth.cat.Subscription;
import javax.websocket.CloseReason;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class CatEndpoint extends Endpoint {
private final Cat cat;
private final ConcurrentMap<String, Subscription> subscriptions = new ConcurrentHashMap<>();
public CatEndpoint(Cat cat) {
this.cat = cat;
}
@Override
public void onOpen(Session session, EndpointConfig config) {
session.addMessageHandler(String.class, new CatMessageHandler(this, session));
}
public void onClose(Session session, CloseReason closeReason) {
Subscription subscription = subscriptions.remove(session.getId());
if (subscription != null) {
subscription.cancel();
}
}
public void subscribe(Session session, Subscriber<String> subscriber) {
Subscription subscription = cat.subscribe(subscriber);
subscriptions.put(session.getId(), subscription);
}
}
|
3e09ea4ae45c335d7464f9297adf1e84b1284362 | 3,744 | java | Java | aliyun-java-sdk-afs/src/main/java/com/aliyuncs/afs/model/v20180112/DescribeCaptchaDayResponse.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 3 | 2021-01-25T16:15:23.000Z | 2021-01-25T16:15:54.000Z | aliyun-java-sdk-afs/src/main/java/com/aliyuncs/afs/model/v20180112/DescribeCaptchaDayResponse.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 27 | 2021-06-11T21:08:40.000Z | 2022-03-11T21:25:09.000Z | aliyun-java-sdk-afs/src/main/java/com/aliyuncs/afs/model/v20180112/DescribeCaptchaDayResponse.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 1 | 2020-03-05T07:30:16.000Z | 2020-03-05T07:30:16.000Z | 22.023529 | 84 | 0.719551 | 4,202 | /*
* 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.aliyuncs.afs.model.v20180112;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.afs.transform.v20180112.DescribeCaptchaDayResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class DescribeCaptchaDayResponse extends AcsResponse {
private String requestId;
private String bizCode;
private Boolean hasData;
private CaptchaDay captchaDay;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getBizCode() {
return this.bizCode;
}
public void setBizCode(String bizCode) {
this.bizCode = bizCode;
}
public Boolean getHasData() {
return this.hasData;
}
public void setHasData(Boolean hasData) {
this.hasData = hasData;
}
public CaptchaDay getCaptchaDay() {
return this.captchaDay;
}
public void setCaptchaDay(CaptchaDay captchaDay) {
this.captchaDay = captchaDay;
}
public static class CaptchaDay {
private Integer init;
private Integer askForVerify;
private Integer direcetStrategyInterception;
private Integer twiceVerify;
private Integer pass;
private Integer checkTested;
private Integer uncheckTested;
private Integer legalSign;
private Integer maliciousFlow;
public Integer getInit() {
return this.init;
}
public void setInit(Integer init) {
this.init = init;
}
public Integer getAskForVerify() {
return this.askForVerify;
}
public void setAskForVerify(Integer askForVerify) {
this.askForVerify = askForVerify;
}
public Integer getDirecetStrategyInterception() {
return this.direcetStrategyInterception;
}
public void setDirecetStrategyInterception(Integer direcetStrategyInterception) {
this.direcetStrategyInterception = direcetStrategyInterception;
}
public Integer getTwiceVerify() {
return this.twiceVerify;
}
public void setTwiceVerify(Integer twiceVerify) {
this.twiceVerify = twiceVerify;
}
public Integer getPass() {
return this.pass;
}
public void setPass(Integer pass) {
this.pass = pass;
}
public Integer getCheckTested() {
return this.checkTested;
}
public void setCheckTested(Integer checkTested) {
this.checkTested = checkTested;
}
public Integer getUncheckTested() {
return this.uncheckTested;
}
public void setUncheckTested(Integer uncheckTested) {
this.uncheckTested = uncheckTested;
}
public Integer getLegalSign() {
return this.legalSign;
}
public void setLegalSign(Integer legalSign) {
this.legalSign = legalSign;
}
public Integer getMaliciousFlow() {
return this.maliciousFlow;
}
public void setMaliciousFlow(Integer maliciousFlow) {
this.maliciousFlow = maliciousFlow;
}
}
@Override
public DescribeCaptchaDayResponse getInstance(UnmarshallerContext context) {
return DescribeCaptchaDayResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
|
3e09ea70a9cd295ac4e5704709855a646cccff53 | 371 | java | Java | src/main/java/cn/wuxia/project/basic/mvc/filter/WeixinAuthHandler.java | wuxiatech/wuxia-project-core | 992a30d070268555d7bc3a79b2a2994cedd3103f | [
"Apache-2.0"
] | 1 | 2020-06-10T23:13:04.000Z | 2020-06-10T23:13:04.000Z | src/main/java/cn/wuxia/project/basic/mvc/filter/WeixinAuthHandler.java | wuxiatech/wuxia-project-core | 992a30d070268555d7bc3a79b2a2994cedd3103f | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/wuxia/project/basic/mvc/filter/WeixinAuthHandler.java | wuxiatech/wuxia-project-core | 992a30d070268555d7bc3a79b2a2994cedd3103f | [
"Apache-2.0"
] | 1 | 2020-06-10T23:13:25.000Z | 2020-06-10T23:13:25.000Z | 33.727273 | 132 | 0.851752 | 4,203 | package cn.wuxia.project.basic.mvc.filter;
import cn.wuxia.common.exception.AppSecurityException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class WeixinAuthHandler {
public abstract boolean handlerWeixinAuth(HttpServletRequest request, HttpServletResponse response) throws AppSecurityException;
}
|
3e09eb9cb3690b5fefbec1e1faaab2e83de225ed | 301 | java | Java | threatconnect-sdk/threatconnect-sdk-core/src/main/java/com/threatconnect/sdk/client/fluent/AdversaryBuilder.java | ThreatConnect-Inc/threatconnect-java | af1397e9e9d49c4391e321cbd627340bfd3003bc | [
"Apache-2.0"
] | 4 | 2015-07-09T20:53:08.000Z | 2018-06-12T21:47:42.000Z | threatconnect-sdk/threatconnect-sdk-core/src/main/java/com/threatconnect/sdk/client/fluent/AdversaryBuilder.java | ThreatConnect-Inc/threatconnect-java | af1397e9e9d49c4391e321cbd627340bfd3003bc | [
"Apache-2.0"
] | 6 | 2017-03-08T20:42:53.000Z | 2020-03-10T14:02:11.000Z | threatconnect-sdk/threatconnect-sdk-core/src/main/java/com/threatconnect/sdk/client/fluent/AdversaryBuilder.java | ThreatConnect-Inc/threatconnect-java | af1397e9e9d49c4391e321cbd627340bfd3003bc | [
"Apache-2.0"
] | 2 | 2016-07-27T16:37:18.000Z | 2017-03-08T19:43:57.000Z | 27.363636 | 77 | 0.803987 | 4,204 | package com.threatconnect.sdk.client.fluent;
import com.threatconnect.sdk.server.entity.Adversary;
public class AdversaryBuilder extends AbstractGroupBuilder<AdversaryBuilder>
{
public Adversary createAdversary()
{
return new Adversary(id, name, type, owner, ownerName, dateAdded, webLink);
}
} |
3e09ebf2f188853c51f293764394f19f3ec011f0 | 1,323 | java | Java | lyj-core/src/org/lyj/commons/io/cache/filecache/registry/IRegistry.java | botikasm/lyj-framework | a806711a5dbe73643f1659774d353def3ecaef24 | [
"MIT"
] | 2 | 2018-12-12T21:13:33.000Z | 2019-03-18T14:20:14.000Z | lyj-core/src/org/lyj/commons/io/cache/filecache/registry/IRegistry.java | botikasm/lyj-framework | a806711a5dbe73643f1659774d353def3ecaef24 | [
"MIT"
] | null | null | null | lyj-core/src/org/lyj/commons/io/cache/filecache/registry/IRegistry.java | botikasm/lyj-framework | a806711a5dbe73643f1659774d353def3ecaef24 | [
"MIT"
] | 1 | 2018-12-12T21:13:36.000Z | 2018-12-12T21:13:36.000Z | 20.045455 | 95 | 0.633409 | 4,205 | package org.lyj.commons.io.cache.filecache.registry;
import java.io.IOException;
public interface IRegistry {
public enum Mode {
File((byte) 0),
Memory((byte) 1);
private final byte _value;
private Mode(byte value) {
_value = value;
}
public byte getValue() {
return _value;
}
public static IRegistry.Mode getEnum(byte value) {
for (IRegistry.Mode v : values())
if (v.getValue() == value) return v;
throw new IllegalArgumentException();
}
}
void start();
void interrupt();
void join();
void clear();
void reloadSettings();
long getCheck();
void setCheck(final long value);
boolean trySave();
void save() throws IOException;
boolean has(final String key);
IRegistryItem get(final String key);
boolean addItem(final String path, final long duration) throws Exception;
boolean addItem(final String key, final String path, final long duration) throws Exception;
boolean removeItem(final IRegistryItem item) throws Exception;
boolean removeItem(final String key) throws Exception;
boolean removeItemByPath(final String path) throws Exception;
String[] removeExpired() throws Exception;
}
|
3e09edf003f2437b73229cea7e96393e20a8092c | 264 | java | Java | src/main/java/com/awslabs/iam/data/RoleName.java | awslabs/results-iterator-for-aws-java-sdk | 17f77da7c85d2fda408a208d466b298cd1059e8e | [
"Apache-2.0"
] | 8 | 2019-07-08T23:51:41.000Z | 2022-03-06T08:18:26.000Z | src/main/java/com/awslabs/iam/data/RoleName.java | awslabs/results-iterator-for-aws-java-sdk | 17f77da7c85d2fda408a208d466b298cd1059e8e | [
"Apache-2.0"
] | 817 | 2019-07-10T14:04:34.000Z | 2022-03-10T13:07:48.000Z | src/main/java/com/awslabs/iam/data/RoleName.java | awslabs/results-iterator-for-aws-java-sdk | 17f77da7c85d2fda408a208d466b298cd1059e8e | [
"Apache-2.0"
] | 4 | 2019-10-23T02:30:27.000Z | 2022-03-28T13:20:50.000Z | 22 | 51 | 0.799242 | 4,206 | package com.awslabs.iam.data;
import com.awslabs.data.NoToString;
import org.immutables.gson.Gson;
import org.immutables.value.Value;
@Gson.TypeAdapters
@Value.Immutable
public abstract class RoleName extends NoToString {
public abstract String getName();
}
|
3e09ee9f1696ebc114dbc707eef75388bd5b8c52 | 15,074 | java | Java | src/main/java/alemiz/bettersurvival/addons/myland/MyLandProtect.java | Quartyn/BetterSurvival | b0f4b09f26baecbcc810156e57a1f55b1a5c6f64 | [
"Apache-2.0"
] | null | null | null | src/main/java/alemiz/bettersurvival/addons/myland/MyLandProtect.java | Quartyn/BetterSurvival | b0f4b09f26baecbcc810156e57a1f55b1a5c6f64 | [
"Apache-2.0"
] | null | null | null | src/main/java/alemiz/bettersurvival/addons/myland/MyLandProtect.java | Quartyn/BetterSurvival | b0f4b09f26baecbcc810156e57a1f55b1a5c6f64 | [
"Apache-2.0"
] | null | null | null | 40.521505 | 138 | 0.601765 | 4,207 | package alemiz.bettersurvival.addons.myland;
import alemiz.bettersurvival.commands.LandCommand;
import alemiz.bettersurvival.utils.Addon;
import alemiz.bettersurvival.utils.ConfigManager;
import alemiz.bettersurvival.utils.SuperConfig;
import cn.nukkit.Player;
import cn.nukkit.block.Block;
import cn.nukkit.event.EventHandler;
import cn.nukkit.event.block.BlockBreakEvent;
import cn.nukkit.event.block.BlockPlaceEvent;
import cn.nukkit.event.player.PlayerInteractEvent;
import cn.nukkit.math.Vector3f;
import cn.nukkit.utils.Config;
import java.util.*;
public class MyLandProtect extends Addon {
private Map<String, List<Block>> selectors = new HashMap<>();
private Map<String, LandRegion> lands = new HashMap<>();
public static String WAND = "§6LandWand";
public static String PERM_VIP = "bettersurvival.land.vip";
public static String PERM_ACCESS = "bettersurvival.land.access";
public MyLandProtect(String path){
super("mylandprotect", path);
WAND = configFile.getString("wandName");
PERM_VIP = configFile.getString("landsVipPermission");
PERM_ACCESS = configFile.getString("landsAccessPermission");
for (SuperConfig config : ConfigManager.getInstance().loadAllPlayers()){
loadLand(config);
}
}
@Override
public void loadConfig() {
if (!configFile.exists("enable")){
configFile.set("enable", true);
configFile.set("wandName", "§6Land§eWand");
configFile.set("landsLimit", 2);
configFile.set("landsLimitSize", 50);
configFile.set("landsLimitSizeVip", 100);
configFile.set("landsVipPermission", "bettersurvival.land.vip");
configFile.set("landsAccessPermission", "bettersurvival.land.access");
configFile.set("landNotExists", "§6»§7Land §6{land}§7 not found!");
configFile.set("landWithNameExists", "§6»§7Land §6{land}§7 already exists§7!");
configFile.set("landWarn", "§6»§7Hey §6@{player}§7, this is not your region! Ask §6@{owner} §7to access §6{land}§7!");
configFile.set("landTooBig", "§6»§7Selected land is bigger than maximum allowed limit §6{limit} blocks§7!");
configFile.set("landPosSelected", "§6»§7Successfully selected {select} position at §6{pos}§7!");
configFile.set("landLimitWarn", "§6»§7Lands limit reached!");
configFile.set("landHereNotFound", "§6»§7This land is free§7!");
configFile.set("landCreate", "§6»§7You have created new land §6{land}§7!");
configFile.set("landRemove", "§6»§7You have removed your land §6{land}§7!");
configFile.set("landSetPos", "§6»§7Touch 2 blocks with wand to select border positions§7!");
configFile.set("landWhitelist", "§6»§7Whitelist for §6{land}§7 saved§7!");
configFile.set("landWhitelistList", "§6»{land}§7 access: {players}");
configFile.set("landHere", "§6»§7The land §6{land}§7 is owned by §6{owner}§7!");
configFile.set("landList", "§6»§7Your lands: {lands}");
configFile.set("landWhitelistAdd", "§6»§7You gain access §6@{player}§7 to your land §6{land}§7!");
configFile.set("landWhitelistRemove", "§6»§7You restrict §6@{player}§7's access to your land §6{land}§7!");
configFile.save();
}
}
@Override
public void registerCommands() {
if (configFile.getBoolean("enable", true)){
registerCommand("land", new LandCommand("land", this));
}
}
@EventHandler
public void onBlockTouch(PlayerInteractEvent event){
Player player = event.getPlayer();
String item = player.getInventory().getItemInHand().getName();
if (event.getAction() == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK && item.equals(WAND)){
List<Block> blocks = new ArrayList<>();
if (selectors.containsKey(player.getName().toLowerCase())){
blocks = selectors.get(player.getName().toLowerCase());
}
if (blocks.size() >= 2) blocks.clear();
blocks.add(event.getBlock());
selectors.put(player.getName().toLowerCase(), blocks);
String message = configFile.getString("landPosSelected");
message = message.replace("{pos}", event.getBlock().x +", "+ event.getBlock().y +", "+ event.getBlock().z);
message = message.replace("{player}", player.getName());
message = message.replace("{select}", (blocks.size() == 1)? "first" : "second");
player.sendMessage(message);
event.setCancelled();
}
LandRegion region = getLandByBlock(event.getBlock());
if (!interact(player, region)) event.setCancelled();
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event){
Block block = event.getBlock();
Player player = event.getPlayer();
LandRegion region = getLandByBlock(block);
if (!interact(player, region)){
event.setCancelled();
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event){
Block block = event.getBlock();
Player player = event.getPlayer();
LandRegion region = getLandByBlock(block);
if (!interact(player, region)){
event.setCancelled();
}
}
public boolean interact(Player player, LandRegion region){
if (region == null) return true;
if (region.owner.equals(player.getName().toLowerCase()) || region.whitelist.contains(player.getName().toLowerCase())) return true;
if (player.isOp() || player.hasPermission(PERM_ACCESS)) return true;
String message = configFile.getString("landWarn");
message = message.replace("{land}", region.land);
message = message.replace("{player}", player.getName());
message = message.replace("{owner}", region.owner);
player.sendMessage(message);
return false;
}
public LandRegion getLandByBlock(Block block){
for (LandRegion region : this.lands.values()){
if (block.x >= Math.min(region.pos1.x, region.pos2.x) && block.x <= Math.max(region.pos1.x, region.pos2.x)
&& block.y >= Math.min(region.pos1.y, region.pos2.y) && block.y <= Math.max(region.pos1.y, region.pos2.y)
&& block.z >= Math.min(region.pos1.z, region.pos2.z) && block.z <= Math.max(region.pos1.z, region.pos2.z))
return region;
}
return null;
}
public Set<String> getLands(Player player){
return getLands(player.getName());
}
public Set<String> getLands(String player){
Config config = ConfigManager.getInstance().loadPlayer(player);
if (config == null) return null;
return config.getSection("land").getKeys(false);
}
public boolean validateLand(List<Block> blocks){
return validateLand(blocks, null);
}
public boolean validateLand(List<Block> blocks, Player player){
if (blocks == null || blocks.isEmpty()) return false;
if (blocks.size() < 2){
if (player != null){
player.sendMessage(configFile.getString("landSetPos"));
}
return false;
}
int landSize = configFile.getInt("landsLimitSize");
if (player != null && player.hasPermission(PERM_VIP)){
landSize = configFile.getInt("landsLimitSizeVip");
}
if (player != null && player.isOp()) return true;
if ((Math.max(blocks.get(0).x, blocks.get(1).x) - Math.min(blocks.get(0).x, blocks.get(1).x)) > landSize ||
(Math.max(blocks.get(0).y, blocks.get(1).y) - Math.min(blocks.get(0).y, blocks.get(1).y)) > landSize ||
(Math.max(blocks.get(0).z, blocks.get(1).z) - Math.min(blocks.get(0).z, blocks.get(1).z)) > landSize){
if (player != null){
String message = configFile.getString("landTooBig");
message = message.replace("{player}", player.getName());
message = message.replace("{limit}", String.valueOf(landSize));
player.sendMessage(message);
}
return false;
}
return true;
}
public void loadLand(SuperConfig config){
String owner = config.getName().substring(0, config.getName().lastIndexOf("."));
for (String land : config.getSection("land").getKeys(false)){
LandRegion region = new LandRegion(owner, land);
List<Integer> data = config.getIntegerList("land."+land+".pos0");
region.pos1 = new Vector3f(data.get(0), data.get(1), data.get(2));
data = config.getIntegerList("land."+land+".pos1");
region.pos2 = new Vector3f(data.get(0), data.get(1), data.get(2));
region.whitelist = config.getStringList("land."+land+".whitelist");
this.lands.put(owner.toLowerCase()+"-"+land, region);
}
}
public void createLand(Player player, String land){
if (player == null || !player.isConnected()) return;
Config config = ConfigManager.getInstance().loadPlayer(player);
if (config == null) return;
int limit = configFile.getInt("landsLimit");
Set<String> lands = config.getSection("land").getKeys();
if (lands != null && lands.size() >= limit && !player.isOp()){
String message = configFile.getString("landLimitWarn");
message = message.replace("{land}", land);
message = message.replace("{player}", player.getName());
player.sendMessage(message);
return;
}
if (lands != null && lands.contains(land.toLowerCase())){
String message = configFile.getString("landWithNameExists");
message = message.replace("{land}", land);
message = message.replace("{player}", player.getName());
player.sendMessage(message);
return;
}
if (!this.selectors.containsKey(player.getName().toLowerCase())){
player.sendMessage(configFile.getString("landSetPos"));
return;
}
List<Block> blocks = this.selectors.get(player.getName().toLowerCase());
if (!validateLand(blocks, player)){
selectors.remove(player.getName().toLowerCase());
return;
}
for (int i = 0; i < blocks.size(); i++){
Block block = blocks.get(i);
Double[] pos = {block.getX(), block.getY(), block.getZ()};
config.set("land."+land.toLowerCase()+".pos"+i, pos);
}
config.set("land."+land.toLowerCase()+".whitelist", new String[0]);
String message = configFile.getString("landCreate");
message = message.replace("{land}", land);
message = message.replace("{player}", player.getName());
player.sendMessage(message);
this.selectors.remove(player.getName().toLowerCase());
config.save();
LandRegion region = new LandRegion(player.getName().toLowerCase(), land.toLowerCase());
region.pos1 = blocks.get(0).asVector3f();
region.pos2 = blocks.get(1).asVector3f();
this.lands.put(player.getName().toLowerCase()+"-"+land.toLowerCase(), region);
}
public void removeLand(Player player, String land){
if (player == null || !player.isConnected()) return;
Config config = ConfigManager.getInstance().loadPlayer(player);
if (config == null) return;
if (!config.exists("land."+land.toLowerCase())){
String message = configFile.getString("landNotExists");
message = message.replace("{land}", land);
message = message.replace("{player}", player.getName());
player.sendMessage(message);
return;
}
((Map) config.get("land")).remove(land.toLowerCase());
config.save();
this.lands.remove(player.getName().toLowerCase()+"-"+land);
String message = configFile.getString("landRemove");
message = message.replace("{player}", player.getName());
message = message.replace("{land}", land);
player.sendMessage(message);
}
public void findLand(Player player){
Block block = player.getLevel().getBlock(player.add(0, -1));
LandRegion land = null;
if (block != null && (land = getLandByBlock(block)) != null){
String message = configFile.getString("landHere");
message = message.replace("{owner}", land.owner);
message = message.replace("{land}", land.land);
player.sendMessage(message);
return;
}
String message = configFile.getString("landHereNotFound");
message = message.replace("{player}", player.getName());
player.sendMessage(message);
}
public void whitelist(Player owner, String player, String land, String action){
LandRegion region = this.lands.get(owner.getName().toLowerCase()+"-"+land.toLowerCase());
if (region == null){
String message = configFile.getString("landNotExists");
message = message.replace("{land}", land);
message = message.replace("{player}", owner.getName());
owner.sendMessage(message);
return;
}
if (!region.owner.equals(owner.getName().toLowerCase())){
String message = configFile.getString("landWarn");
message = message.replace("{land}", region.land);
message = message.replace("{player}", owner.getName());
message = message.replace("{owner}", region.owner);
owner.sendMessage(message);
return;
}
switch (action){
case LandRegion.WHITELIST_ADD:
region.addWhitelist(player);
break;
case LandRegion.WHITELIST_REMOVE:
region.whitelistRemove(player);
break;
case LandRegion.WHITELIST_LIST:
String players = String.join(", ", region.whitelist);
String message = configFile.getString("landWhitelistList");
message = message.replace("{land}", region.land);
message = message.replace("{player}", owner.getName());
message = message.replace("{players}", players);
owner.sendMessage(message);
return; //exit
}
String message = configFile.getString("landWhitelist");
message = message.replace("{land}", region.land);
message = message.replace("{player}", owner.getName());
owner.sendMessage(message);
}
public void listLands(Player player){
Set<String> lands = this.getLands(player);
String message = configFile.getString("landList");
message = message.replace("{lands}", String.join(", ", lands));
message = message.replace("{player}", player.getName());
player.sendMessage(message);
}
}
|
3e09ee9f795a4cd4e24a813fb3f7b732b66c2d96 | 694 | java | Java | java-gateway/src/main/java/com/revianlabs/ju/config/YamlConfig.java | SCBbestof/rest-multiple-languages-demo | 75f7f1fbcaa69439345d66dc901e8f3765a1d438 | [
"MIT"
] | null | null | null | java-gateway/src/main/java/com/revianlabs/ju/config/YamlConfig.java | SCBbestof/rest-multiple-languages-demo | 75f7f1fbcaa69439345d66dc901e8f3765a1d438 | [
"MIT"
] | 1 | 2019-01-09T16:35:49.000Z | 2019-01-09T16:35:56.000Z | java-gateway/src/main/java/com/revianlabs/ju/config/YamlConfig.java | SCBbestof/rest-multiple-languages-demo | 75f7f1fbcaa69439345d66dc901e8f3765a1d438 | [
"MIT"
] | null | null | null | 26.692308 | 81 | 0.776657 | 4,208 | package com.revianlabs.ju.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YamlConfig {
private Map<String, String> services = new HashMap<>();
public Map<String, String> getServices() {
return services;
}
public void setServices(Map<String, String> services) {
this.services = services;
}
}
|
3e09eead656749c7eb85e7855b3a6b0bac78660b | 3,985 | java | Java | modules/transport-netty4/src/test/java/org/elasticsearch/transport/netty4/ESLoggingHandlerIT.java | a137872798/elasticsearch | 293ff2f60eb1fce9af59d23692d783ad040e0654 | [
"Apache-2.0"
] | 3 | 2020-07-09T19:00:34.000Z | 2020-07-09T19:01:20.000Z | modules/transport-netty4/src/test/java/org/elasticsearch/transport/netty4/ESLoggingHandlerIT.java | paulbaudrier/elasticsearch | 16bfdcacc0172264db9b32aa6edfa8b5c327f3b4 | [
"Apache-2.0"
] | 2 | 2019-12-05T10:21:58.000Z | 2020-01-10T09:17:26.000Z | modules/transport-netty4/src/test/java/org/elasticsearch/transport/netty4/ESLoggingHandlerIT.java | paulbaudrier/elasticsearch | 16bfdcacc0172264db9b32aa6edfa8b5c327f3b4 | [
"Apache-2.0"
] | 2 | 2020-02-03T07:05:44.000Z | 2020-02-05T01:51:57.000Z | 44.277778 | 133 | 0.678545 | 4,209 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.netty4;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.elasticsearch.ESNetty4IntegTestCase;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsRequest;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.MockLogAppender;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.transport.TransportLogger;
@ESIntegTestCase.ClusterScope(numDataNodes = 2)
@TestLogging(
value = "org.elasticsearch.transport.netty4.ESLoggingHandler:trace,org.elasticsearch.transport.TransportLogger:trace",
reason = "to ensure we log network events on TRACE level")
public class ESLoggingHandlerIT extends ESNetty4IntegTestCase {
private MockLogAppender appender;
public void setUp() throws Exception {
super.setUp();
appender = new MockLogAppender();
Loggers.addAppender(LogManager.getLogger(ESLoggingHandler.class), appender);
Loggers.addAppender(LogManager.getLogger(TransportLogger.class), appender);
appender.start();
}
public void tearDown() throws Exception {
Loggers.removeAppender(LogManager.getLogger(ESLoggingHandler.class), appender);
Loggers.removeAppender(LogManager.getLogger(TransportLogger.class), appender);
appender.stop();
super.tearDown();
}
public void testLoggingHandler() throws IllegalAccessException {
final String writePattern =
".*\\[length: \\d+" +
", request id: \\d+" +
", type: request" +
", version: .*" +
", action: cluster:monitor/nodes/hot_threads\\[n\\]\\]" +
" WRITE: \\d+B";
final MockLogAppender.LoggingExpectation writeExpectation =
new MockLogAppender.PatternSeenEventExpectation(
"hot threads request", TransportLogger.class.getCanonicalName(), Level.TRACE, writePattern);
final MockLogAppender.LoggingExpectation flushExpectation =
new MockLogAppender.SeenEventExpectation("flush", ESLoggingHandler.class.getCanonicalName(), Level.TRACE, "*FLUSH*");
final String readPattern =
".*\\[length: \\d+" +
", request id: \\d+" +
", type: request" +
", version: .*" +
", action: cluster:monitor/nodes/hot_threads\\[n\\]\\]" +
" READ: \\d+B";
final MockLogAppender.LoggingExpectation readExpectation =
new MockLogAppender.PatternSeenEventExpectation(
"hot threads request", TransportLogger.class.getCanonicalName(), Level.TRACE, readPattern);
appender.addExpectation(writeExpectation);
appender.addExpectation(flushExpectation);
appender.addExpectation(readExpectation);
client().admin().cluster().nodesHotThreads(new NodesHotThreadsRequest()).actionGet();
appender.assertAllExpectationsMatched();
}
}
|
3e09ef5922b4baeda055f4f42d60b2b1873e562b | 26,841 | java | Java | src/com/kcsl/x86/short_circuit/ShortCircuitChecking.java | rgoluch/binary_analyzer | b59d7229b655126d87c718def130b1ea71db3677 | [
"MIT"
] | null | null | null | src/com/kcsl/x86/short_circuit/ShortCircuitChecking.java | rgoluch/binary_analyzer | b59d7229b655126d87c718def130b1ea71db3677 | [
"MIT"
] | 26 | 2020-02-06T16:56:19.000Z | 2021-02-01T05:32:27.000Z | src/com/kcsl/x86/short_circuit/ShortCircuitChecking.java | rgoluch/x86_analyzer | b59d7229b655126d87c718def130b1ea71db3677 | [
"MIT"
] | null | null | null | 32.029833 | 139 | 0.645468 | 4,210 | package com.kcsl.x86.short_circuit;
import static com.kcsl.x86.Importer.my_cfg;
import static com.kcsl.x86.Importer.my_function;
import static com.kcsl.x86.support.SupportMethods.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.ensoftcorp.atlas.core.db.graph.Edge;
import com.ensoftcorp.atlas.core.db.graph.Graph;
import com.ensoftcorp.atlas.core.db.graph.Node;
import com.ensoftcorp.atlas.core.db.set.AtlasHashSet;
import com.ensoftcorp.atlas.core.db.set.AtlasSet;
import com.ensoftcorp.atlas.core.query.Q;
import com.ensoftcorp.atlas.core.query.Query;
import com.ensoftcorp.atlas.core.script.Common;
import com.ensoftcorp.atlas.core.xcsg.XCSG;
import com.se421.paths.algorithms.PathCounter.CountingResult;
import com.se421.paths.algorithms.counting.MultiplicitiesPathCounter;
import com.kcsl.paths.counting.TopDownDFPathCounter;
public class ShortCircuitChecking {
protected static final String OR = "||";
protected static final String AND = "&&";
protected static final String LAST = "sc_end";
protected static String[] scNodeTags = {"sc_node"};
/**
*
* @param cfg
* @return
*/
public static scInfo scChecker(Q cfg) {
AtlasSet<Node> conditions = cfg.eval().nodes().tagged(XCSG.ControlFlowCondition);
ArrayList<String> ordering = new ArrayList<String>();
scInfo scCount = null;
for (Node n : conditions) {
AtlasSet<Node> toCheck = Common.toQ(n).contained().nodes(XCSG.LogicalOr, XCSG.LogicalAnd).eval().nodes();
if (toCheck.size() > 0) {
long and = Common.toQ(n).contained().nodes(XCSG.LogicalAnd).eval().nodes().size();
long or = Common.toQ(n).contained().nodes(XCSG.LogicalOr).eval().nodes().size();
scCount = new scInfo(toCheck.size(), and, or);
}
for (Node x : toCheck) {
ordering.add(x.getAttr(XCSG.name).toString());
}
}
return scCount;
}
/**
*
* @param name
* @return
*/
public static Q scTransform(Q c, String name) {
//Get the original source CFG
// Q f = my_function(name);
// Q c = my_cfg(f);
//Set up for new function node for returned CFG
Node functionNode = Graph.U.createNode();
functionNode.putAttr(XCSG.name, "sc_transform_"+name);
functionNode.tag(XCSG.Function);
functionNode.tag("sc_graph");
//Variables to hold nodes that potentially have complex conditions, the nodes with complex conditions,
//and the ordering of those complex conditions
AtlasSet<Node> conditionNodes = c.eval().nodes().tagged(XCSG.ControlFlowCondition);
ArrayList<Node> scNodes = new ArrayList<Node>();
//Finding the complex conditions
for (Node n : conditionNodes) {
AtlasSet<Node> toCheck = Common.toQ(n).contained().nodes(XCSG.LogicalOr, XCSG.LogicalAnd).eval().nodes();
if (toCheck.size() > 0) {
scNodes.add(n);
n.tag("sc_node");
}
}
Node trueDest = null;
Node falseDest = null;
//Tagging all non-complex condition nodes for creation in the final CFG
for (Node n : c.eval().nodes()) {
if(!scNodes.contains(n)) {
n.tag("sc_graph");
}
}
//Tagging all edges for creation in the final CFG
for (Edge e : c.eval().edges().tagged(XCSG.ControlFlow_Edge)) {
e.tag("sc_edge");
}
Map<Node,Node> addedToGraph = new HashMap<Node,Node>();
ArrayList<Node> scPredecessors = new ArrayList<Node>();
Map<predecessorNode,Node> predMap = new HashMap<predecessorNode,Node>();
ArrayList<predecessorNode> loopBackTails = new ArrayList<predecessorNode>();
Map<Node,Node> loopBackHeaderMap = new HashMap<Node,Node>();
ArrayList<predecessorNode> edgeCreated = new ArrayList<predecessorNode>();
ArrayList<Node> scHeaders = new ArrayList<Node>();
//Create nodes for the new graph that will be returned
for (Edge e : c.eval().edges().tagged(XCSG.ControlFlow_Edge)) {
//Handling the case of the complex condition predecessor that needs to point to the new
//simple condition
if (scNodes.contains(e.to()) && !e.from().taggedWith("sc_node")) {
Node tempSCPred = createNode(e.from(), scNodeTags);
// if (!e.taggedWith(XCSG.ControlFlowBackEdge)) {
// tempSCPred.tag("sc_pred");
//
// }
// e.from().tag("sc_pred");
//Check to make sure the from node hasn't already been created.
//If it has, handle the special case of the edge being a loopback edge since that node is not a predecessor node
Node checkingPred = addedToGraph.get(e.from());
//If predecessor node is a conditional, then we want to add the condition value on the edge
String edgeValue = null;
if (e.hasAttr(XCSG.conditionValue)) {
if (e.getAttr(XCSG.conditionValue).toString().contains("true")) {
edgeValue = "true";
}else {
edgeValue = "false";
}
}
//Case where node was created and is the predecessor
if (checkingPred != null && !e.taggedWith(XCSG.ControlFlowBackEdge)) {
scPredecessors.add(checkingPred);
predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), checkingPred, edgeValue);
predMap.put(p, e.to());
// checkingPred.addressBits()
edgeCreated.add(p);
}
//Case where node was created and edge is a loopback edge
else if (checkingPred != null && e.taggedWith(XCSG.ControlFlowBackEdge)) {
predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), checkingPred, edgeValue);
loopBackTails.add(p);
loopBackHeaderMap.put(checkingPred, e.to());
}
//Case where node hasn't been created yet, still need to handle loopback edge and predecessor checks
else if (checkingPred == null) {
Edge eToPred = Graph.U.createEdge(functionNode, tempSCPred);
eToPred.tag(XCSG.Contains);
addedToGraph.put(e.from(), tempSCPred);
if (e.taggedWith(XCSG.ControlFlowBackEdge)) {
predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), tempSCPred, edgeValue);
loopBackTails.add(p);
loopBackHeaderMap.put(tempSCPred, e.to());
}else {
scPredecessors.add(tempSCPred);
predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), tempSCPred, edgeValue);
predMap.put(p, e.to()); //tempSCPred.addressBits()
edgeCreated.add(p);
}
}
}
else if (scNodes.contains(e.from()) && e.to().taggedWith("sc_graph")) {
Node tempSingle = createNode(e.to(), scNodeTags);
//If predecessor node is a conditional, then we want to add the condition value on the edge
String edgeValue = null;
if (e.hasAttr(XCSG.conditionValue)) {
if (e.getAttr(XCSG.conditionValue).toString().contains("true")) {
edgeValue = "true";
}else {
edgeValue = "false";
}
}
//Check to make sure the node hasn't already been created so we don't make duplicated nodes
Node checkingSuccessor = addedToGraph.get(e.to());
if (checkingSuccessor == null) {
Edge eToSingle = Graph.U.createEdge(functionNode, tempSingle);
eToSingle.tag(XCSG.Contains);
addedToGraph.put(e.to(), tempSingle);
if (e.taggedWith(XCSG.ControlFlowBackEdge)) {
predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), tempSingle, edgeValue);
loopBackTails.add(p);
loopBackHeaderMap.put(tempSingle, e.from());
}
// else {
// scPredecessors.add(tempSingle);
// predMap.put(tempSingle.addressBits(), e.to());
// predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), tempSCPred, edgeValue);
// edgeCreated.add(p);
// }
}
// if (checkingPred != null && !e.taggedWith(XCSG.ControlFlowBackEdge)) {
// scPredecessors.add(checkingPred);
// predMap.put(checkingPred.addressBits(), e.to());
// predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), checkingPred, edgeValue);
// edgeCreated.add(p);
// }
//Case where node was created and edge is a loopback edge
// else
if (checkingSuccessor != null && e.taggedWith(XCSG.ControlFlowBackEdge)) {
predecessorNode p = new predecessorNode(e.from().addressBits(), e.to().addressBits(), checkingSuccessor, edgeValue);
loopBackTails.add(p);
loopBackHeaderMap.put(checkingSuccessor, e.from());
}
}
//Handling all other control flow nodes
else if (e.from().taggedWith("sc_graph") && e.to().taggedWith("sc_graph")) {
Node tempFrom = createNode(e.from(), scNodeTags);
Node tempTo = createNode(e.to(), scNodeTags);
//Check to make sure the node hasn't already been created so we don't make duplicated nodes
Node checkingResultFrom = addedToGraph.get(e.from());
Node checkingResultTo = addedToGraph.get(e.to());
Edge tempEdge = null;
if (checkingResultFrom == null && checkingResultTo == null) {
Edge eFrom = Graph.U.createEdge(functionNode, tempFrom);
eFrom.tag(XCSG.Contains);
Edge eTo = Graph.U.createEdge(functionNode, tempTo);
eTo.tag(XCSG.Contains);
tempEdge = Graph.U.createEdge(tempFrom, tempTo);
tempEdge.tag("sc_edge");
tempEdge.tag(XCSG.ControlFlow_Edge);
addedToGraph.put(e.from(), tempFrom);
addedToGraph.put(e.to(), tempTo);
}
else if (checkingResultFrom != null && checkingResultTo == null) {
Edge eTo = Graph.U.createEdge(functionNode, tempTo);
eTo.tag(XCSG.Contains);
tempEdge = Graph.U.createEdge(checkingResultFrom, tempTo);
tempEdge.tag("sc_edge");
tempEdge.tag(XCSG.ControlFlow_Edge);
addedToGraph.put(e.to(), tempTo);
}
else if (checkingResultFrom == null && checkingResultTo != null) {
Edge eFrom = Graph.U.createEdge(functionNode, tempFrom);
eFrom.tag(XCSG.Contains);
tempEdge = Graph.U.createEdge(tempFrom, checkingResultTo);
tempEdge.tag("sc_edge");
tempEdge.tag(XCSG.ControlFlow_Edge);
addedToGraph.put(e.from(), tempFrom);
}
else if (checkingResultFrom != null && checkingResultTo != null) {
tempEdge = Graph.U.createEdge(checkingResultFrom, checkingResultTo);
tempEdge.tag("sc_edge");
tempEdge.tag(XCSG.ControlFlow_Edge);
}
if (e.taggedWith(XCSG.ControlFlowBackEdge)) {
tempEdge.tag(XCSG.ControlFlowBackEdge);
}
if (e.hasAttr(XCSG.conditionValue)) {
if (e.getAttr(XCSG.conditionValue).toString().contains("true")) {
tempEdge.putAttr(XCSG.conditionValue, true);
tempEdge.putAttr(XCSG.name, "true");
}else {
tempEdge.putAttr(XCSG.conditionValue, false);
tempEdge.putAttr(XCSG.name, "false");
}
}
}
if (e.from().taggedWith("sc_node") && e.to().taggedWith("sc_node")) {
e.to().tag("nested_sc");
}
}
//Move nested SC nodes to the beginning of the array to be processed first
//in order to have initial true and false destinations
for (int r = scNodes.size() - 1; r >=0; r--) {
// Node current = scNodes.get(r);
for (int s = r - 1; s >= 0; s--) {
Node next = scNodes.get(s);
Node current = scNodes.get(r);
long currentLine = getCSourceLineNumber(current);
long nextLine = getCSourceLineNumber(next);
if (currentLine > nextLine) {
Node temp = current;
scNodes.set(r, next);
scNodes.set(s, temp);
current = scNodes.get(r);
}
// if(!current.taggedWith("nested_sc") && next.taggedWith("nested_sc")) {
// Node temp = current;
// scNodes.set(r, next);
// scNodes.set(s, temp);
// current = scNodes.get(r);
// }
// else if (current.taggedWith("nested_sc") && next.taggedWith("nested_sc")) {
// //If you have multiple nested sc nodes, you want to move the "lowest" one to the front
// if (nextLine > currentLine) {
// Node temp = current;
// scNodes.set(r, next);
// scNodes.set(s, temp);
// current = scNodes.get(r);
// }
// }
// else if (currentLine > nextLine) {
// Node temp = current;
// scNodes.set(r, next);
// scNodes.set(s, temp);
// current = scNodes.get(r);
// }
}
}
//Processing each node that could cause short circuiting
for (Node x : scNodes) {
AtlasSet<Edge> outEdges = x.out().tagged(XCSG.ControlFlow_Edge);
Edge o1 = null;
Edge o2 = null;
for (Edge e : outEdges) {
if (o1 == null) {
o1 = e;
}else {
o2 = e;
}
}
//Finding the true and false edge destinations depending on if there are
//nested or non-nested complex conditionals
if (o1.getAttr(XCSG.conditionValue).toString().contains("true")) {
if (o1.to().taggedWith("nested_sc") && !o2.to().taggedWith("nested_sc")) {
for (Node t : scHeaders) {
if (o1.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
trueDest = t;
}
}
falseDest = addedToGraph.get(o2.to());
}else if (o2.to().taggedWith("nested_sc") && !o1.to().taggedWith("nested_sc")) {
for (Node t : scHeaders) {
if (o2.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
falseDest = t;
}
}
trueDest = addedToGraph.get(o1.to());
}else if (o1.to().taggedWith("nested_sc") && o2.to().taggedWith("nested_sc")) {
for (Node t : scHeaders) {
if (o1.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
trueDest = t;
}
if (o2.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
falseDest = t;
}
}
}
else {
trueDest = addedToGraph.get(o1.to());
falseDest = addedToGraph.get(o2.to());
}
}else {
if (o1.to().taggedWith("nested_sc") && !o2.to().taggedWith("nested_sc")) {
for (Node t : scHeaders) {
if (o1.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
falseDest = t;
}
}
trueDest = addedToGraph.get(o2.to());
}else if (o2.to().taggedWith("nested_sc") && !o1.to().taggedWith("nested_sc")) {
for (Node t : scHeaders) {
if (o2.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
trueDest = t;
}
}
falseDest = addedToGraph.get(o1.to());
}else if (o1.to().taggedWith("nested_sc") && o2.to().taggedWith("nested_sc")) {
for (Node t : scHeaders) {
if (o1.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
falseDest = t;
}
if (o2.to().getAttr(XCSG.name).toString().contains(t.getAttr(XCSG.name).toString())) {
trueDest = t;
}
}
}
else {
falseDest = addedToGraph.get(o1.to());
trueDest = addedToGraph.get(o2.to());
}
}
//Getting the order of the conditions in the original node
AtlasSet<Node> toCheck = Common.toQ(x).contained().nodes(XCSG.LogicalOr, XCSG.LogicalAnd).eval().nodes();
ArrayList<String> ordering = new ArrayList<String>();
for (Node q : toCheck) {
ordering.add(q.getAttr(XCSG.name).toString());
}
//Getting all information from original node for new nodes in final graph
scNode[] nodes = createScNodes(ordering, x);
ArrayList<Node> scNodesInGraph = new ArrayList<Node>();
boolean nullFlag = false;
for(int j = 0; j < nodes.length; j++) {
if (nodes[j] == null) {
System.out.println("Macro Condition: " + name);
nullFlag = true;
continue;
}
if (trueDest == null || falseDest == null) {
System.out.println("null destination issue: " + name);
return null;
}
//Creation of new branch nodes for final graph
Node temp1 = Graph.U.createNode();
temp1.putAttr(XCSG.name, nodes[j].getCondition());
temp1.tag(XCSG.ControlFlowCondition);
temp1.tag("sc_graph");
temp1.tag(nodes[j].operator);
temp1.putAttr(XCSG.sourceCorrespondence, x.getAttr(XCSG.sourceCorrespondence));
scNodesInGraph.add(temp1);
if (x.taggedWith(XCSG.ControlFlowIfCondition)) {
temp1.tag(XCSG.ControlFlowIfCondition);
}
if (nodes[j].originalNode.taggedWith(XCSG.ControlFlowLoopCondition)) {
temp1.tag("sc_loop_node");
}
//If this is the first node, being created it needs to have all predecessor nodes pointing to it
//and have any loopback edges coming to it for loops with complex conditions
if (j == 0 || nullFlag) {
temp1.tag("sc_header");
scHeaders.add(temp1);
if (x.taggedWith(XCSG.ControlFlowLoopCondition)) {
temp1.tag(XCSG.ControlFlowLoopCondition);
}
for(predecessorNode p : edgeCreated) {
Node predSCNode = predMap.get(p); //.getAddedNode().addressBits()
if (predSCNode.getAttr(XCSG.name).toString().contains(nodes[j].getCondition()) && p.getToAddr() == x.addressBits() && !p.getEdge()) {
Edge predEdge = Graph.U.createEdge(p.getAddedNode(), temp1);
predEdge.tag(XCSG.ControlFlow_Edge);
predEdge.tag("sc_edge");
predEdge.tag("sc_pred_edge");
p.toggleEdge();
if (p.conditionValue != null) {
predEdge.putAttr(XCSG.conditionValue, p.conditionValue);
predEdge.putAttr(XCSG.name, p.conditionValue.toString());
}
}
}
for (predecessorNode b : loopBackTails) {
Node l = loopBackHeaderMap.get(b.getAddedNode());
if (l.getAttr(XCSG.name).toString().contains(nodes[j].getCondition()) && b.getToAddr() == x.addressBits() && !b.getEdge()) {
Edge backEdge = Graph.U.createEdge(b.getAddedNode(), temp1);
backEdge.tag(XCSG.ControlFlowBackEdge);
backEdge.tag("sc_back_edge");
backEdge.tag("sc_edge");
b.toggleEdge();
if (b.conditionValue != null) {
backEdge.putAttr(XCSG.conditionValue, b.conditionValue);
}
}
}
if (nullFlag) {
temp1.tag("macro_conditional");
scNode tempSC = nodes[j];
nodes = new scNode[1];
nodes[0] = tempSC;
nullFlag = false;
}
}
Edge e1 = Graph.U.createEdge(functionNode, temp1);
e1.tag(XCSG.Contains);
}
//Setting the destination nodes for the true and false edges of the nodes created
scNode lastNode = null;
for (int m = 0; m < scNodesInGraph.size(); m++) {
if (nodes[m] == null) {
continue;
}
scNode checking = nodes[m];
Node checkingNode = scNodesInGraph.get(m);
if(checking.getOperator().contains(LAST)) {
checking.setTrueDest(checkingNode, trueDest);
checking.setFalseDest(checkingNode, falseDest);
checking.trueSCNode = checking;
checking.falseSCNode = checking;
lastNode = checking;
}
}
for (int m = scNodesInGraph.size()-1; m >= 0; m--) {
if (nodes[m] == null) {
continue;
}
scNode checking = nodes[m];
Node checkingNode = scNodesInGraph.get(m);
if(checking.getOperator().contains(AND)) {
checking.setTrueDest(checkingNode, scNodesInGraph.get(m+1));
checking.setSCTrue(nodes[m+1]);
//
if (nodes[m+1].falseSCNode.getOperator().contains(LAST)) {
if (m >=1 && nodes[m-1].getOperator().contains(OR)) {
checking.setFalseDest(checkingNode, falseDest);
checking.setSCFalse(nodes[m+1]);
} else if (nodes[m+1].getOperator().contains(OR)) {
checking.setFalseDest(checkingNode, falseDest);
checking.setSCFalse(nodes[m+1]);
}
else {
checking.setFalseDest(checkingNode, nodes[m+1].getFalseDest());
checking.setSCFalse(nodes[m+1]);
}
}else if (m >=1 && nodes[m-1].getOperator().contains(OR)) {
checking.setFalseDest(checkingNode, lastNode.getFalseDest());
checking.setSCFalse(lastNode);
}
else {
checking.setFalseDest(checkingNode, nodes[m+1].getFalseDest());
checking.setSCFalse(nodes[m+1]);
}
// falseDest
}
if(checking.getOperator().contains(OR)) {
checking.setFalseDest(checkingNode, scNodesInGraph.get(m+1));
checking.setSCFalse(nodes[m+1]);
if (nodes[m+1].trueSCNode.getOperator().contains(LAST)) {
checking.setTrueDest(checkingNode, trueDest);
checking.setSCTrue(nodes[m+1]);
}else if (m >= 1 && nodes[m-1].getOperator().contains(AND)) {
checking.setTrueDest(checkingNode, lastNode.getTrueDest());
checking.setSCFalse(lastNode);
}
else {
checking.setTrueDest(checkingNode, nodes[m+1].getTrueDest());
checking.setSCTrue(nodes[m+1]);
}
// }else {
// checking.setTrueDest(checkingNode, trueDest);
// }
// checking.setTrueDest(checkingNode, nodes[m+1].getTrueDest());
}
}
}
Q x = my_function(functionNode.getAttr(XCSG.name).toString());
Q sc_cfg = my_cfg(x);
return sc_cfg.nodes("sc_graph").induce(Query.universe().edges("sc_edge"));
}
/**
*
* @param ordering
* @param x
* @return
*/
public static scNode[] createScNodes(ArrayList<String> ordering, Node x) {
scNode[] conditions = new scNode[ordering.size()+1];
int j = 0;
int k = 0;
String name = x.attr().get(XCSG.name).toString();
// x.getAttr(XCSG.name).toString();
String[] parts = name.split(" ");
String updatedName[] = x.getAttr(XCSG.name).toString().split("&&|\\|\\|");
for (int p = 0; p < parts.length - 1; p++) {
String toCheck = parts[p];
// if (updatedName[k].contains("<=") && parts[p+1].contains(AND)) {
// scNode tempSCNode = new scNode(updatedName[k], AND, x.addressBits());
// conditions[j] = tempSCNode;
// j++;
// k++;
// }
// else if (updatedName[k].contains("<=") && parts[p+1].contains(OR)) {
// scNode tempSCNode = new scNode(updatedName[k], OR, x.addressBits());
// conditions[j] = tempSCNode;
// j++;
// k++;
// }
if (updatedName[k].contains(toCheck) && parts[p+1].contains(AND)) {
scNode tempSCNode = new scNode(updatedName[k], AND, x.addressBits(), x);
conditions[j] = tempSCNode;
j++;
k++;
}
else if (updatedName[k].contains(toCheck) && parts[p+1].contains(OR)) {
scNode tempSCNode = new scNode(updatedName[k], OR, x.addressBits(), x);
conditions[j] = tempSCNode;
j++;
k++;
}
}
scNode temp = new scNode(updatedName[k], LAST, x.addressBits(), x);
conditions[conditions.length-1] = temp;
return conditions;
}
private static class scNode{
private String condition;
private String operator;
private Node truDest;
private Node falsDest;
private int address;
private scNode trueSCNode;
private scNode falseSCNode;
private Node originalNode;
public scNode(String c, String o, int i, Node n) {
this.condition = c;
this.operator = o;
this.address = i;
this.originalNode = n;
}
public void setSCTrue(scNode s) {
this.trueSCNode = s;
}
public void setSCFalse(scNode s) {
this.falseSCNode = s;
}
public String getCondition() {
return this.condition;
}
public String getOperator() {
return this.operator;
}
public void setTrueDest(Node temp1, Node temp2) {
this.truDest = temp2;
Edge tempTrue = Graph.U.createEdge(temp1, temp2);
tempTrue.tag(XCSG.ControlFlow_Edge);
tempTrue.putAttr(XCSG.conditionValue, true);
tempTrue.putAttr(XCSG.name, "true");
tempTrue.tag("sc_edge");
tempTrue.tag("sc_edge_testing");
if (temp2.taggedWith(XCSG.ControlFlowLoopCondition)) {
tempTrue.tag(XCSG.ControlFlowBackEdge);
}
}
public Node getTrueDest() {
return this.truDest;
}
public void setFalseDest(Node temp1, Node temp2) {
this.falsDest = temp2;
Edge tempTrue = Graph.U.createEdge(temp1, temp2);
tempTrue.tag(XCSG.ControlFlow_Edge);
tempTrue.putAttr(XCSG.conditionValue, false);
tempTrue.putAttr(XCSG.name, "false");
tempTrue.tag("sc_edge");
tempTrue.tag("sc_edge_testing");
if (temp2.taggedWith(XCSG.ControlFlowLoopCondition)) {
tempTrue.tag(XCSG.ControlFlowBackEdge);
}
}
public Node getFalseDest() {
return this.falsDest;
}
}
private static class scInfo{
private long conditions;
private long ands;
private long ors;
public scInfo(long c, long a, long o) {
this.conditions = c;
this.ands = a;
this.ors = o;
}
public long getConditions() {
return this.conditions;
}
public long getAnds() {
return this.ands;
}
public long getOrs() {
return this.ors;
}
}
private static class predecessorNode{
private int fromAddr;
private int toAddr;
private Node addedNode;
private boolean edgeAdded;
private String conditionValue;
public predecessorNode(int f, int t, Node n, String value) {
this.fromAddr = f;
this.toAddr = t;
this.addedNode = n;
this.edgeAdded = false;
this.conditionValue = value;
}
public int getFromAddr() {
return this.fromAddr;
}
public int getToAddr() {
return this.toAddr;
}
public Node getAddedNode() {
return this.addedNode;
}
public void toggleEdge() {
this.edgeAdded = true;
}
public boolean getEdge() {
return this.edgeAdded;
}
}
public static void scCounts() throws IOException {
String scPath = "/Users/RyanGoluch/Desktop/Masters_Work/isomorphism_checking/sc_checking.csv";
File scFile = new File(scPath);
BufferedWriter scWriter = new BufferedWriter(new FileWriter(scFile));
scWriter.write("Function Name, Conditions, Ands, Ors, Original Path Count, Transform Path Count\n");
Q functions = Query.universe().nodesTaggedWithAll(XCSG.Function, "binary_function");
int result = 0;
for (Node f : functions.eval().nodes()) {
String functionName = f.getAttr(XCSG.name).toString();
String srcName = functionName.substring(4);
if (functionName.contains("test") || functionName.contains("_doscan")) {
continue;
}
System.out.println(srcName);
Q function = my_function(srcName);
Q c = my_cfg(function);
scInfo x = scChecker(c);
Q transformedGraph = scTransform(c, srcName);
if (transformedGraph != null) {
TopDownDFPathCounter transformCounter = new TopDownDFPathCounter(true);
TopDownDFPathCounter srcCounter = new TopDownDFPathCounter(true);
com.kcsl.paths.algorithms.PathCounter.CountingResult t = srcCounter.countPaths(c);
com.kcsl.paths.algorithms.PathCounter.CountingResult r = transformCounter.countPaths(transformedGraph);
if (x != null) {
result++;
scWriter.write(srcName + "," + x.getConditions() + "," + x.getAnds() + "," + x.getOrs() + "," +
t.getPaths() + "," + r.getPaths()+ "\n");
scWriter.flush();
}
}
}
scWriter.close();
System.out.println("Number of Source Functions w/ SC: " + result);
}
}
|
3e09efa9b34142a880422c36a9b05b717b8c8367 | 2,976 | java | Java | ec_pdm/src/main/java/com/gohuinuo/web/sys/model/SysMain.java | gto5516172/test | cb9883a42363945d7aa0fd4ef7aca87b0e6faf4d | [
"Apache-2.0"
] | null | null | null | ec_pdm/src/main/java/com/gohuinuo/web/sys/model/SysMain.java | gto5516172/test | cb9883a42363945d7aa0fd4ef7aca87b0e6faf4d | [
"Apache-2.0"
] | null | null | null | ec_pdm/src/main/java/com/gohuinuo/web/sys/model/SysMain.java | gto5516172/test | cb9883a42363945d7aa0fd4ef7aca87b0e6faf4d | [
"Apache-2.0"
] | null | null | null | 19.973154 | 52 | 0.728495 | 4,211 | //Powered By if, Since 2014 - 2020
package com.gohuinuo.web.sys.model;
import java.util.Date;
import java.util.List;
import com.gohuinuo.common.base.BaseEntity;
import com.gohuinuo.common.constant.Constant;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author
*/
@SuppressWarnings({ "unused"})
@Table(name="")
public class SysMain extends BaseEntity {
private static final long serialVersionUID = 1L;
private Integer spuCount; // 新增spu
private Integer skuCount; // 新增sku
private Integer supCount; // 新增供应商
private Integer faqCount; // 新增faq
private Integer fileCount; // 新增文件
private Integer taskCount; // 新增任务
private Integer userCount; // 用户总数
private Integer loginCount; // 今日登录数
private Integer upLoadCount; // 上传文件数
private Integer taskSYCount; // 所有任务
private Integer taskWWCCount; // 未完成任务
private Integer taskYWCCount; // 已完成任务
public Integer getTaskSYCount() {
return getInteger("taskSYCount");
}
public void setTaskSYCount(Integer taskSYCount) {
this.set("taskSYCount", taskSYCount);
}
public Integer getTaskWWCCount() {
return getInteger("taskWWCCount");
}
public void setTaskWWCCount(Integer taskWWCCount) {
this.set("taskWWCCount", taskWWCCount);
}
public Integer getTaskYWCCount() {
return getInteger("taskYWCCount");
}
public void setTaskYWCCount(Integer taskYWCCount) {
this.set("taskYWCCount", taskYWCCount);
}
public Integer getUserCount() {
return getInteger("userCount");
}
public void setUserCount(Integer userCount) {
this.set("userCount", userCount);
}
public Integer getLoginCount() {
return getInteger("loginCount");
}
public void setLoginCount(Integer loginCount) {
this.set("loginCount", loginCount);
}
public Integer getUpLoadCount() {
return getInteger("upLoadCount");
}
public void setUpLoadCount(Integer upLoadCount) {
this.set("upLoadCount", upLoadCount);
}
public Integer getSpuCount() {
return getInteger("spuCount");
}
public void setSpuCount(Integer spuCount) {
this.set("spuCount", spuCount);
}
public Integer getSkuCount() {
return getInteger("skuCount");
}
public void setSkuCount(Integer skuCount) {
this.set("skuCount", skuCount);
}
public Integer getSupCount() {
return getInteger("supCount");
}
public void setSupCount(Integer supCount) {
this.set("supCount", supCount);
}
public Integer getFaqCount() {
return getInteger("faqCount");
}
public void setFaqCount(Integer faqCount) {
this.set("faqCount", faqCount);
}
public Integer getFileCount() {
return getInteger("fileCount");
}
public void setFileCount(Integer fileCount) {
this.set("fileCount", fileCount);
}
public Integer getTaskCount() {
return getInteger("taskCount");
}
public void setTaskCount(Integer taskCount) {
this.set("taskCount", taskCount);
}
}
|
3e09f032ec8248d60f4fce2ef8e8a6be31e98d3d | 935 | java | Java | src/test/java/Command/AddListCommandTest.java | chosti34/TODOList | da6df20af6cd6de0cdc03402b3b077fc6594cd17 | [
"MIT"
] | null | null | null | src/test/java/Command/AddListCommandTest.java | chosti34/TODOList | da6df20af6cd6de0cdc03402b3b077fc6594cd17 | [
"MIT"
] | null | null | null | src/test/java/Command/AddListCommandTest.java | chosti34/TODOList | da6df20af6cd6de0cdc03402b3b077fc6594cd17 | [
"MIT"
] | 1 | 2018-01-07T12:37:01.000Z | 2018-01-07T12:37:01.000Z | 23.974359 | 100 | 0.704813 | 4,212 | package Command;
import Command.AddListCommand;
import Command.InputCommandType;
import Task.TODOListManager;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class AddListCommandTest {
private AddListCommand command = new AddListCommand(new ArrayList<String>() {{ add("name"); }});
@Test
public void getMinRequiredArgsCount() throws Exception {
assertEquals(1, command.getMinRequiredArgsCount());
}
@Test
public void getMaxOptionalArgsCount() throws Exception {
assertEquals(1, command.getMaxOptionalArgsCount());
}
@Test
public void execute() throws Exception {
command.execute(new TODOListManager().getController());
}
@Test
public void getType() throws Exception {
assertEquals(InputCommandType.ADD_LIST, command.getType());
}
@Test
public void setArguments() throws Exception {
}
}
|
3e09f0493d5213a1684f4c0a99f6f174882ee59a | 715 | java | Java | Flashlight Application/src/RedFlashlightActivity.java | neilpelow/workspace | 09fb7fd428526321ea5b52370414407a705bd04a | [
"MIT"
] | null | null | null | Flashlight Application/src/RedFlashlightActivity.java | neilpelow/workspace | 09fb7fd428526321ea5b52370414407a705bd04a | [
"MIT"
] | null | null | null | Flashlight Application/src/RedFlashlightActivity.java | neilpelow/workspace | 09fb7fd428526321ea5b52370414407a705bd04a | [
"MIT"
] | null | null | null | 29.791667 | 90 | 0.735664 | 4,213 | package com.oreilly.android.simpleflashlight;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class RedFlashlightActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button greenButton = (Button)findViewById(R.id.green_button);
greenButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(RedFlashlightActivity.this, GreenFlashlightActivity.class);
startActivity(intent);
}
});
}
} |
3e09f07e96ede6be2fd248781abdabd67bee1dae | 3,740 | java | Java | app/src/main/java/com/rcc/tamagosan/rubikscubecontroller/RankingActivity.java | tamagosan/Rubiks-Cube | 6e9fcfb9006fb29c8f8df58e805dd3fc3f6daf55 | [
"Unlicense"
] | 3 | 2016-09-24T05:52:24.000Z | 2017-12-08T11:58:14.000Z | app/src/main/java/com/rcc/tamagosan/rubikscubecontroller/RankingActivity.java | tamagosan/Rubiks-Cube | 6e9fcfb9006fb29c8f8df58e805dd3fc3f6daf55 | [
"Unlicense"
] | null | null | null | app/src/main/java/com/rcc/tamagosan/rubikscubecontroller/RankingActivity.java | tamagosan/Rubiks-Cube | 6e9fcfb9006fb29c8f8df58e805dd3fc3f6daf55 | [
"Unlicense"
] | null | null | null | 42.988506 | 140 | 0.585561 | 4,214 | package com.rcc.tamagosan.rubikscubecontroller;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class RankingActivity extends AppCompatActivity {
public static long score[][]=new long[4][5];
public static TextView[][] rank=new TextView[4][5];
public static boolean clearf=false;
private int i,j;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ranking);
rank[0][0]=(TextView)this.findViewById(R.id.time_time_1);
rank[0][1]=(TextView)this.findViewById(R.id.time_time_2);
rank[0][2]=(TextView)this.findViewById(R.id.time_time_3);
rank[0][3]=(TextView)this.findViewById(R.id.time_time_4);
rank[0][4]=(TextView)this.findViewById(R.id.time_time_5);
rank[1][0]=(TextView)this.findViewById(R.id.time_tesuu_1);
rank[1][1]=(TextView)this.findViewById(R.id.time_tesuu_2);
rank[1][2]=(TextView)this.findViewById(R.id.time_tesuu_3);
rank[1][3]=(TextView)this.findViewById(R.id.time_tesuu_4);
rank[1][4]=(TextView)this.findViewById(R.id.time_tesuu_5);
rank[2][0]=(TextView)this.findViewById(R.id.tesuu_time_1);
rank[2][1]=(TextView)this.findViewById(R.id.tesuu_time_2);
rank[2][2]=(TextView)this.findViewById(R.id.tesuu_time_3);
rank[2][3]=(TextView)this.findViewById(R.id.tesuu_time_4);
rank[2][4]=(TextView)this.findViewById(R.id.tesuu_time_5);
rank[3][0]=(TextView)this.findViewById(R.id.tesuu_tesuu_1);
rank[3][1]=(TextView)this.findViewById(R.id.tesuu_tesuu_2);
rank[3][2]=(TextView)this.findViewById(R.id.tesuu_tesuu_3);
rank[3][3]=(TextView)this.findViewById(R.id.tesuu_tesuu_4);
rank[3][4]=(TextView)this.findViewById(R.id.tesuu_tesuu_5);
MainActivity mact = new MainActivity();
for(i=0;i<5;i++) {
for (j = 0; j < 4; j++) {
SharedPreferences pref = getSharedPreferences(String.format("rank%d_%d", j, i), MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
if (j % 2 == 0) {
long tcount = pref.getLong("tamagosan", 600000);
long mm = tcount * 10 / 1000 / 60;
long ss = tcount * 10 / 1000 % 60;
long ms = (tcount * 10 - ss * 1000 - mm * 1000 * 60) / 10;
rank[j][i].setText(String.format("%1$02d:%2$02d.%3$02d", mm, ss, ms));
score[j][i] = tcount;
} else {
long tesuu = pref.getLong("tamagosan", 1000);
rank[j][i].setText(String.format("%d手", tesuu));
score[j][i] = tesuu;
}
rank[j][i].setTextColor(Color.BLACK);
}
if (clearf) {
if (mact.cc1 == i) {
rank[0][i].setTextColor(Color.RED);
rank[1][i].setTextColor(Color.RED);
}
if (mact.cc2 == i){
rank[2][i].setTextColor(Color.RED);
rank[3][i].setTextColor(Color.RED);
}
}
}
clearf=false;
Button rtnbutton=(Button)this.findViewById(R.id.rtn);
rtnbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
3e09f10c6dde0991a6371b6998f7d07efc8b6822 | 439 | java | Java | octopus-core/src/main/java/com/github/linkeer8802/octopus/core/cache/Cache.java | linkeer8802/octopus | 1f2cb2af21a5c5380500d83769f5fc7cdef029cb | [
"Apache-2.0"
] | 2 | 2020-01-07T08:44:49.000Z | 2020-01-07T09:07:15.000Z | octopus-core/src/main/java/com/github/linkeer8802/octopus/core/cache/Cache.java | linkeer8802/octopus | 1f2cb2af21a5c5380500d83769f5fc7cdef029cb | [
"Apache-2.0"
] | null | null | null | octopus-core/src/main/java/com/github/linkeer8802/octopus/core/cache/Cache.java | linkeer8802/octopus | 1f2cb2af21a5c5380500d83769f5fc7cdef029cb | [
"Apache-2.0"
] | 2 | 2020-01-07T09:07:19.000Z | 2022-03-20T02:11:21.000Z | 15.137931 | 50 | 0.53303 | 4,215 | package com.github.linkeer8802.octopus.core.cache;
/**
* 缓存抽象接口
* @author wrd
* @param <K> key类型
* @param <V> value类型
*/
public interface Cache<K, V> {
/**
* 从缓存中获取指定key的value
* @param key key
* @return value
*/
V get(K key);
/**
* 设置指定key的对象到缓存中
* @param key key
* @param value value
*/
void put(K key, V value);
/**
* 清除ThreadLocal中的对象
*/
void clear();
}
|
3e09f15bef0993451c784ced8dcf7f002495e218 | 661 | java | Java | design-patterns/HeadFirst Design Patterns/src/day19/copy/CopyTest.java | nnoco/playground | 7149f49eedc5f72454296c40667231d43b54087f | [
"Apache-2.0"
] | null | null | null | design-patterns/HeadFirst Design Patterns/src/day19/copy/CopyTest.java | nnoco/playground | 7149f49eedc5f72454296c40667231d43b54087f | [
"Apache-2.0"
] | null | null | null | design-patterns/HeadFirst Design Patterns/src/day19/copy/CopyTest.java | nnoco/playground | 7149f49eedc5f72454296c40667231d43b54087f | [
"Apache-2.0"
] | null | null | null | 15.738095 | 59 | 0.644478 | 4,216 | package day19.copy;
import java.util.Arrays;
public class CopyTest {
public static void main(String[] args) {
Value[] values = {new Value(1), new Value(5)};
Value[] newValues = Arrays.copyOf(values, values.length);
values[0].i = 113;
System.out.println(newValues[0].i);
}
}
class Reference {
Value v;
public static Reference shallowCopy(Reference r) {
Reference newR = new Reference();
newR.v = r.v;
return newR;
}
public static Reference deepCopy(Reference r) {
Reference newR = new Reference();
newR.v = new Value(r.v.i);
return null;
}
}
class Value {
int i = 0;
public Value(int i) {
this.i = i;
}
}
|
3e09f186eeceb64163177a347c22d47f9bb34818 | 1,173 | java | Java | jogl/src/com/jogl/unpack/ZeroTerminatedStringPacker.java | Otaka/mydifferentprojects | 28489042fb574d1178a6d814b6accc29cdc3aeed | [
"Apache-2.0"
] | null | null | null | jogl/src/com/jogl/unpack/ZeroTerminatedStringPacker.java | Otaka/mydifferentprojects | 28489042fb574d1178a6d814b6accc29cdc3aeed | [
"Apache-2.0"
] | null | null | null | jogl/src/com/jogl/unpack/ZeroTerminatedStringPacker.java | Otaka/mydifferentprojects | 28489042fb574d1178a6d814b6accc29cdc3aeed | [
"Apache-2.0"
] | null | null | null | 24.4375 | 78 | 0.508099 | 4,217 | package com.jogl.unpack;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author Dmitry
*/
class ZeroTerminatedStringPacker extends BasePacker {
private int maxSize;
public ZeroTerminatedStringPacker(int maxSize) {
super(null);
this.maxSize = maxSize;
}
@Override
void process(InputStream stream, List<Object> result) throws IOException {
StringBuilder sb = new StringBuilder();
if (maxSize == -1) {
char c = (char) stream.read();
while (c != -1 && c != 0) {
sb.append(c);
c = (char) stream.read();
}
} else {
boolean isStringFinished = false;
for (int i = 0; i < maxSize; i++) {
char c = (char) stream.read();
if (c == 0) {
isStringFinished = true;
}
if (!isStringFinished) {
sb.append(c);
}
}
}
result.add(sb.toString());
}
@Override
protected void innerProcess(InputStream stream, List<Object> result) {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.