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
sequence | 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
sequence | 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
sequence | 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e01342c659ee2c0da3e9697a370fe930c82d2bf | 283 | java | Java | business/src/main/java/no/nav/sbl/dialogarena/soknadinnsending/business/service/BolkService.java | navikt/sendsoknad | 72eb83954166d861f8e265d09c32e0c18c60a3ee | [
"MIT"
] | null | null | null | business/src/main/java/no/nav/sbl/dialogarena/soknadinnsending/business/service/BolkService.java | navikt/sendsoknad | 72eb83954166d861f8e265d09c32e0c18c60a3ee | [
"MIT"
] | 4 | 2020-03-09T09:34:37.000Z | 2021-05-06T14:16:02.000Z | business/src/main/java/no/nav/sbl/dialogarena/soknadinnsending/business/service/BolkService.java | navikt/sendsoknad | 72eb83954166d861f8e265d09c32e0c18c60a3ee | [
"MIT"
] | null | null | null | 20.214286 | 73 | 0.787986 | 501 | package no.nav.sbl.dialogarena.soknadinnsending.business.service;
import no.nav.sbl.dialogarena.sendsoknad.domain.Faktum;
import java.util.List;
public interface BolkService {
String tilbyrBolk();
List<Faktum> genererSystemFakta(String fodselsnummer, Long soknadId);
}
|
3e01345185fd759b712ea835574e5eef4e3b3739 | 2,690 | java | Java | src/main/java/com/softib/loanmanager/controllers/DocumentRestAPI.java | soft-ib/softib-loanManager | 9a0478265c0989a051690232c2eee6713e57384a | [
"MIT"
] | null | null | null | src/main/java/com/softib/loanmanager/controllers/DocumentRestAPI.java | soft-ib/softib-loanManager | 9a0478265c0989a051690232c2eee6713e57384a | [
"MIT"
] | null | null | null | src/main/java/com/softib/loanmanager/controllers/DocumentRestAPI.java | soft-ib/softib-loanManager | 9a0478265c0989a051690232c2eee6713e57384a | [
"MIT"
] | null | null | null | 40.757576 | 124 | 0.824535 | 502 | package com.softib.loanmanager.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.softib.loanmanager.entity.Document;
import com.softib.loanmanager.entity.Loan;
import com.softib.loanmanager.repository.DocumentRepository;
import com.softib.loanmanager.repository.LoanRepository;
import com.softib.loanmanager.services.DocumentService;
@RestController
@RequestMapping(value = "/documents")
public class DocumentRestAPI {
@Autowired
DocumentService documentService;
@Autowired
LoanRepository loanRepository;
@Autowired
DocumentRepository documentRepository;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Document> addDocument(@RequestBody Document document, @RequestParam(name = "idLoan") Long idLoan) {
Optional<Loan> loan = loanRepository.findById(idLoan);
Loan loanObject = loan.get();
document.setLoan(loanObject);
return new ResponseEntity<>(documentService.addDocuments(document), HttpStatus.OK);
}
@GetMapping(value="/checkIfWeCanValidate")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<String> checkIfWeCanValidate( @RequestParam(name = "idLoan") Long idLoan) {
List<Document> documentList=documentRepository.allDocumentsByLoanId(idLoan);
return new ResponseEntity<>(documentService.checkWeightedDocument(documentList), HttpStatus.OK);
}
@GetMapping(value="/DisplayAllDocuments")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<List<Document>> DisplayDocument( @RequestParam(name = "idLoan") Long idLoan) {
List<Document> documentList=documentRepository.allDocumentsByLoanId(idLoan);
return new ResponseEntity<>(documentList, HttpStatus.OK);
}
@PutMapping(value="/updateOneDoc")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Document> updateOneDocument(@RequestParam(name = "idDoc") Long idDoc, @RequestBody Document newDoc) {
Document documentToupdate=documentRepository.OneDocumentByID(idDoc);
return new ResponseEntity<>(documentService.updateOneDocument(documentToupdate, newDoc), HttpStatus.OK);
}
}
|
3e013475d2d098ef63e64ff8d917125e23ddc0d3 | 3,295 | java | Java | src/cz/zcu/kiv/mobile/logger/eegbase/upload/helpers/WSManufacturerSpecificDataDbUploadHelper.java | NEUROINFORMATICS-GROUP-FAV-KIV-ZCU/elfyz-data-mobile-logger | 8362299d6cb091c57a678c5a7b635851e3cb5d17 | [
"CC-BY-3.0",
"Apache-2.0"
] | 1 | 2017-10-11T12:11:36.000Z | 2017-10-11T12:11:36.000Z | src/cz/zcu/kiv/mobile/logger/eegbase/upload/helpers/WSManufacturerSpecificDataDbUploadHelper.java | NEUROINFORMATICS-GROUP-FAV-KIV-ZCU/elfyz-data-mobile-logger | 8362299d6cb091c57a678c5a7b635851e3cb5d17 | [
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null | src/cz/zcu/kiv/mobile/logger/eegbase/upload/helpers/WSManufacturerSpecificDataDbUploadHelper.java | NEUROINFORMATICS-GROUP-FAV-KIV-ZCU/elfyz-data-mobile-logger | 8362299d6cb091c57a678c5a7b635851e3cb5d17 | [
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null | 31.682692 | 150 | 0.742944 | 503 | package cz.zcu.kiv.mobile.logger.eegbase.upload.helpers;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import cz.zcu.kiv.mobile.logger.Application;
import cz.zcu.kiv.mobile.logger.data.database.WeightScaleManufacturerSpecificDataTable;
import cz.zcu.kiv.mobile.logger.data.database.exceptions.DatabaseException;
import cz.zcu.kiv.mobile.logger.eegbase.exceptions.UploadHelperException;
import cz.zcu.kiv.mobile.logger.utils.CloseUtils;
public class WSManufacturerSpecificDataDbUploadHelper extends ADbUploadHelper {
private WeightScaleManufacturerSpecificDataTable db;
protected int iTime;
protected int iManufSpecific;
protected int iUploaded;
public WSManufacturerSpecificDataDbUploadHelper() { }
public WSManufacturerSpecificDataDbUploadHelper(String parameterName, String valueString, long[] ids, boolean append) {
super(parameterName, valueString, ids, append);
}
public WSManufacturerSpecificDataDbUploadHelper(String parameterName, Double valueInteger, long[] ids, boolean append) {
super(parameterName, valueInteger, ids, append);
}
public WSManufacturerSpecificDataDbUploadHelper(Parcel source) {
super(source);
}
@Override
protected Cursor init() throws UploadHelperException {
db = Application.getInstance().getDatabase().getWeightScaleManufacturerSpecificDataTable();
Cursor c = null;
try {
c = db.getMeasurements(ids);
iTime = c.getColumnIndexOrThrow(WeightScaleManufacturerSpecificDataTable.COLUMN_TIME);
iManufSpecific = c.getColumnIndexOrThrow(WeightScaleManufacturerSpecificDataTable.COLUMN_DATA);
iUploaded = c.getColumnIndexOrThrow(WeightScaleManufacturerSpecificDataTable.COLUMN_UPLOADED);
return c;
}
catch (DatabaseException e) {
CloseUtils.close(c);
throw new UploadHelperException("Failed to load data from database.", e);
}
}
@Override
protected String getID(Cursor data) {
return data.getString(iTime);
}
@Override
protected String toJSON(Cursor c) throws JSONException {
byte[] data = c.getBlob(iManufSpecific);
JSONArray array = new JSONArray();
for (int i = 0; i < data.length; i++) {
array.put(data[i]);
}
JSONObject value = new JSONObject();
value.put("time", c.getLong(iTime));
value.put("length", data.length);
value.put("data", array);
return value.toString();
}
@Override
public void markUploaded() throws UploadHelperException {
try {
db.setUploaded(ids);
}
catch (DatabaseException e) {
throw new UploadHelperException("Failed to mark records as uploaded.", e);
}
}
public static final Parcelable.Creator<WSManufacturerSpecificDataDbUploadHelper> CREATOR = new Creator<WSManufacturerSpecificDataDbUploadHelper>() {
@Override
public WSManufacturerSpecificDataDbUploadHelper[] newArray(int size) {
return new WSManufacturerSpecificDataDbUploadHelper[size];
}
@Override
public WSManufacturerSpecificDataDbUploadHelper createFromParcel(Parcel source) {
return new WSManufacturerSpecificDataDbUploadHelper(source);
}
};
}
|
3e01356c4175ded6861fa391a448df9683baff2a | 1,064 | java | Java | json-interface-generator-core/src/test/java/com/bluecirclesoft/open/jigen/Jee7Processor.java | mrami4/bluecircle-json-interface-generator | 4cec77df21bdace1868efb8fe2041fd3753db7cb | [
"Apache-2.0"
] | 1 | 2021-06-13T16:16:20.000Z | 2021-06-13T16:16:20.000Z | json-interface-generator-core/src/test/java/com/bluecirclesoft/open/jigen/Jee7Processor.java | mrami4/bluecircle-json-interface-generator | 4cec77df21bdace1868efb8fe2041fd3753db7cb | [
"Apache-2.0"
] | 2 | 2022-02-12T02:46:09.000Z | 2022-02-12T03:10:22.000Z | json-interface-generator-core/src/test/java/com/bluecirclesoft/open/jigen/Jee7Processor.java | mrami4/bluecircle-json-interface-generator | 4cec77df21bdace1868efb8fe2041fd3753db7cb | [
"Apache-2.0"
] | null | null | null | 24.744186 | 75 | 0.741541 | 504 | /*
* Copyright 2018 Blue Circle Software, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.bluecirclesoft.open.jigen;
import java.util.List;
/**
* TODO document me
*/
public class Jee7Processor implements ConfigurableProcessor<Jee7Options> {
Jee7Options options;
@Override
public Class<Jee7Options> getOptionsClass() {
return Jee7Options.class;
}
@Override
public void acceptOptions(Jee7Options options, List<String> errors) {
this.options = options;
}
public Jee7Options getOptions() {
return options;
}
}
|
3e0135d6ec3419387cf080399e32d7e2ce516bf6 | 1,551 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomous/AutonomousRedRoute1.java | Ninjseal/ftc_app2.4 | b96fabb0e09e21981ac48d1dff011199b7ef0d67 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomous/AutonomousRedRoute1.java | Ninjseal/ftc_app2.4 | b96fabb0e09e21981ac48d1dff011199b7ef0d67 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomous/AutonomousRedRoute1.java | Ninjseal/ftc_app2.4 | b96fabb0e09e21981ac48d1dff011199b7ef0d67 | [
"MIT"
] | null | null | null | 30.411765 | 121 | 0.684075 | 505 | package org.firstinspires.ftc.teamcode.autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.hardware.DcMotor;
import org.firstinspires.ftc.teamcode.opmodes.AutonomousMode;
/**
* Created by Marius on 3/19/2017.
*/
@Autonomous(name = "AutonomousRedRoute1", group = "Autonomous")
//@Disabled
public class AutonomousRedRoute1 extends AutonomousMode {
@Override
protected void initOpMode() throws InterruptedException {
initHardware();
}
protected void runOp() throws InterruptedException {
while (!isStopRequested() && gyroSensor.isCalibrating()) {
sleep(50);
idle();
}
// Init wheels motors
leftMotorF.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
leftMotorB.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightMotorF.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightMotorB.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
/*
Capture 1 beacon, throw 2 balls in the center vortex, remove the big ball from center and park the robot = 70 pts
Move forward 10 CM
Turn left 45 degrees
Move forward until ods detects the line
Follow the line until the distance between robot and wall is <= 17 CM
Detect the color of beacon and capture it
Move backwards 15 CM
Throw 2 balls in the center vortex
Move backwards 100 CM
*/
}
protected void exitOpMode() throws InterruptedException {
stopMotors();
}
}
|
3e01367d61a9f4be60143896c1dc0ecc05142535 | 317 | java | Java | jpaw-xml/src/main/java/de/jpaw/xml/jaxb/scaledFp/ScaledIntegerAdapter7Round.java | jpaw/jpaw | 68bc06c379851d093f89fbf2c45f8b64e02b2108 | [
"Apache-2.0"
] | null | null | null | jpaw-xml/src/main/java/de/jpaw/xml/jaxb/scaledFp/ScaledIntegerAdapter7Round.java | jpaw/jpaw | 68bc06c379851d093f89fbf2c45f8b64e02b2108 | [
"Apache-2.0"
] | null | null | null | jpaw-xml/src/main/java/de/jpaw/xml/jaxb/scaledFp/ScaledIntegerAdapter7Round.java | jpaw/jpaw | 68bc06c379851d093f89fbf2c45f8b64e02b2108 | [
"Apache-2.0"
] | 1 | 2015-10-25T20:54:44.000Z | 2015-10-25T20:54:44.000Z | 26.416667 | 78 | 0.769716 | 506 | package de.jpaw.xml.jaxb.scaledFp;
import de.jpaw.xml.jaxb.AbstractScaledIntegerAdapter;
/** XmlAdapter for fixed-point arithmetic using 7 fractional digits. */
public class ScaledIntegerAdapter7Round extends AbstractScaledIntegerAdapter {
public ScaledIntegerAdapter7Round() {
super(7, true);
}
}
|
3e01376862bc651c7664567f9c233ed69d00d25b | 7,293 | java | Java | src/test/java/org/nem/deploy/DeserializableEntityMessageConverterTest.java | segfaultxavi/nem.deploy | 7adcead53f7a109abb1cd5932a9b331a4934e629 | [
"MIT"
] | 23 | 2016-08-07T17:20:00.000Z | 2019-03-05T11:47:07.000Z | src/test/java/org/nem/deploy/DeserializableEntityMessageConverterTest.java | segfaultxavi/nem.deploy | 7adcead53f7a109abb1cd5932a9b331a4934e629 | [
"MIT"
] | 3 | 2018-02-14T09:58:54.000Z | 2021-10-30T14:55:29.000Z | src/test/java/org/nem/deploy/DeserializableEntityMessageConverterTest.java | segfaultxavi/nem.deploy | 7adcead53f7a109abb1cd5932a9b331a4934e629 | [
"MIT"
] | 27 | 2016-07-13T09:34:03.000Z | 2021-11-02T08:03:56.000Z | 34.239437 | 113 | 0.787742 | 507 | package org.nem.deploy;
import net.minidev.json.JSONObject;
import org.hamcrest.MatcherAssert;
import org.hamcrest.core.IsEqual;
import org.junit.*;
import org.mockito.Mockito;
import org.nem.core.serialization.*;
import org.nem.core.test.*;
import org.nem.deploy.test.*;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.util.List;
public class DeserializableEntityMessageConverterTest {
// region supports / canRead / canWrite
@Test
public void converterSupportsPolicyMediaType() {
// Arrange:
final MediaType mediaType = new MediaType("application");
final SerializationPolicy policy = Mockito.mock(SerializationPolicy.class);
Mockito.when(policy.getMediaType()).thenReturn(mediaType);
final DeserializableEntityMessageConverter mc = createMessageConverter(policy);
// Act:
final List<MediaType> mediaTypes = mc.getSupportedMediaTypes();
// Assert:
MatcherAssert.assertThat(mediaTypes.size(), IsEqual.equalTo(1));
MatcherAssert.assertThat(mediaTypes.get(0), IsEqual.equalTo(mediaType));
Mockito.verify(policy, Mockito.times(2)).getMediaType();
}
@Test
public void canReadCompatibleTypesWithDeserializerConstructor() {
// Arrange:
final MediaType supportedType = new MediaType("application", "json");
final DeserializableEntityMessageConverter mc = createMessageConverter();
final Class<?>[] types = new Class<?>[]{
MockSerializableEntity.class, ObjectWithConstructorThatThrowsCheckedException.class,
ObjectWithConstructorThatThrowsUncheckedException.class
};
// Assert:
for (final Class<?> type : types) {
MatcherAssert.assertThat(mc.canRead(type, supportedType), IsEqual.equalTo(true));
}
}
@Test
public void cannotReadTypesWithoutDeserializerConstructor() {
// Arrange:
final MediaType supportedType = new MediaType("application", "json");
final DeserializableEntityMessageConverter mc = createMessageConverter();
final Class<?>[] types = new Class<?>[]{
SerializableEntity.class, ObjectWithoutDeserializerConstructor.class, MediaType.class, Object.class
};
// Assert:
for (final Class<?> type : types) {
MatcherAssert.assertThat(mc.canRead(type, supportedType), IsEqual.equalTo(false));
}
}
@Test
public void cannotReadIncompatibleMediaTypes() {
// Arrange:
final MediaType supportedType = new MediaType("application", "binary");
final DeserializableEntityMessageConverter mc = createMessageConverter();
final Class<?>[] types = new Class<?>[]{
MockSerializableEntity.class, ObjectWithConstructorThatThrowsCheckedException.class,
ObjectWithConstructorThatThrowsUncheckedException.class
};
// Assert:
for (final Class<?> type : types) {
MatcherAssert.assertThat(mc.canRead(type, supportedType), IsEqual.equalTo(false));
}
}
@Test
public void cannotWriteCompatibleTypes() {
// Arrange:
final MediaType supportedType = new MediaType("application", "json");
final DeserializableEntityMessageConverter mc = createMessageConverter();
// Assert:
MatcherAssert.assertThat(mc.canWrite(MockSerializableEntity.class, supportedType), IsEqual.equalTo(false));
}
// endregion
// region read
@Test
public void readIsSupportedForCompatibleTypeWithDeserializerConstructor() throws Exception {
// Arrange:
final MockSerializableEntity originalEntity = new MockSerializableEntity(7, "foo", 3);
final DeserializableEntityMessageConverter mc = createMessageConverter();
// Act:
final MockSerializableEntity entity = (MockSerializableEntity) mc.read(MockSerializableEntity.class,
new MockHttpInputMessage(JsonSerializer.serializeToJson(originalEntity)));
// Assert:
MatcherAssert.assertThat(entity, IsEqual.equalTo(originalEntity));
}
@Test
public void readDelegatesToPolicy() throws Exception {
// Arrange:
final MediaType mediaType = new MediaType("application", "json");
final SerializationPolicy policy = Mockito.mock(SerializationPolicy.class);
Mockito.when(policy.getMediaType()).thenReturn(mediaType);
// Arrange:
final MockSerializableEntity originalEntity = new MockSerializableEntity(7, "foo", 3);
final Deserializer deserializer = Utils.roundtripSerializableEntity(originalEntity, null);
Mockito.when(policy.fromStream(Mockito.any())).thenReturn(deserializer);
final DeserializableEntityMessageConverter mc = createMessageConverter(policy);
// Act:
final MockHttpInputMessage message = new MockHttpInputMessage(JsonSerializer.serializeToJson(originalEntity));
mc.read(MockSerializableEntity.class, message);
// Assert:
Mockito.verify(policy, Mockito.times(1)).fromStream(message.getBody());
}
@Test(expected = UnsupportedOperationException.class)
public void readIsUnsupportedForCompatibleTypeWithConstructorThatThrowsCheckedException() throws Exception {
// Arrange:
final DeserializableEntityMessageConverter mc = createMessageConverter();
// Act:
mc.read(ObjectWithConstructorThatThrowsCheckedException.class, new MockHttpInputMessage(new JSONObject()));
}
@Test(expected = IllegalArgumentException.class)
public void readIsUnsupportedForCompatibleTypeWithConstructorThatThrowsUncheckedException() throws Exception {
// Arrange:
final DeserializableEntityMessageConverter mc = createMessageConverter();
// Act:
mc.read(ObjectWithConstructorThatThrowsUncheckedException.class, new MockHttpInputMessage(new JSONObject()));
}
@Test(expected = UnsupportedOperationException.class)
public void readIsUnsupportedForTypeWithoutDeserializerConstructor() throws Exception {
// Arrange:
final DeserializableEntityMessageConverter mc = createMessageConverter();
// Act:
mc.read(ObjectWithoutDeserializerConstructor.class, new MockHttpInputMessage(new JSONObject()));
}
// endregion
// region write
@Test(expected = UnsupportedOperationException.class)
public void writeIsUnsupported() throws Exception {
// Arrange:
final MediaType supportedType = new MediaType("application", "json");
final DeserializableEntityMessageConverter mc = createMessageConverter();
final JsonDeserializer deserializer = new JsonDeserializer(new JSONObject(), new DeserializationContext(null));
// Act:
mc.write(deserializer, supportedType, new MockHttpOutputMessage());
}
// endregion
// region test classes
private static class ObjectWithoutDeserializerConstructor {
public ObjectWithoutDeserializerConstructor() {
}
}
private static class ObjectWithConstructorThatThrowsUncheckedException {
public ObjectWithConstructorThatThrowsUncheckedException(final Deserializer deserializer) {
throw new IllegalArgumentException("constructor failed: " + deserializer.toString());
}
}
private static class ObjectWithConstructorThatThrowsCheckedException {
public ObjectWithConstructorThatThrowsCheckedException(final Deserializer deserializer) throws IOException {
throw new IOException("constructor failed: " + deserializer.toString());
}
}
// endregion
private static DeserializableEntityMessageConverter createMessageConverter() {
return new DeserializableEntityMessageConverter(new JsonSerializationPolicy(null));
}
private static DeserializableEntityMessageConverter createMessageConverter(final SerializationPolicy policy) {
return new DeserializableEntityMessageConverter(policy);
}
}
|
3e01376ce1bdb3f24a8134ccb6c2c50f1cf770f7 | 7,617 | java | Java | jts2geojson-geoserver/src/main/java/org/geoserver/wms/vector/VectorTileMapOutputFormat.java | SaberW/mapbox-vector-tile-ext | aceae0bda962787f63b86f2fb20c95f5671bb477 | [
"Apache-2.0"
] | 9 | 2019-06-28T02:08:24.000Z | 2021-07-05T07:22:42.000Z | jts2geojson-geoserver/src/main/java/org/geoserver/wms/vector/VectorTileMapOutputFormat.java | SaberW/mapbox-vector-tile-ext | aceae0bda962787f63b86f2fb20c95f5671bb477 | [
"Apache-2.0"
] | null | null | null | jts2geojson-geoserver/src/main/java/org/geoserver/wms/vector/VectorTileMapOutputFormat.java | SaberW/mapbox-vector-tile-ext | aceae0bda962787f63b86f2fb20c95f5671bb477 | [
"Apache-2.0"
] | 5 | 2019-11-29T08:59:57.000Z | 2021-01-12T09:22:36.000Z | 40.089474 | 233 | 0.673362 | 508 | /* (c) 2015 Open Source Geospatial Foundation - all rights reserved
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.wms.vector;
import com.google.common.base.Stopwatch;
import org.geoserver.platform.ServiceException;
import org.geoserver.wms.MapProducerCapabilities;
import org.geoserver.wms.WMSMapContent;
import org.geoserver.wms.map.AbstractMapOutputFormat;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.factory.Hints;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.Layer;
import org.geotools.renderer.lite.VectorMapRenderUtils;
import org.geotools.util.logging.Logging;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.*;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import java.awt.*;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.geotools.renderer.lite.VectorMapRenderUtils.getStyleQuery;
public class VectorTileMapOutputFormat extends AbstractMapOutputFormat {
/**
* A logger for this class.
*/
private static final Logger LOGGER = Logging.getLogger(VectorTileMapOutputFormat.class);
private final VectorTileBuilderFactory tileBuilderFactory;
private boolean clipToMapBounds;
private double overSamplingFactor = 2.0; // 1=no oversampling, 4=four time oversample (generialization will be 1/4 pixel)
private boolean transformToScreenCoordinates;
public VectorTileMapOutputFormat(VectorTileBuilderFactory tileBuilderFactory) {
super(tileBuilderFactory.getMimeType(), tileBuilderFactory.getOutputFormats());
this.tileBuilderFactory = tileBuilderFactory;
}
/**
* Multiplies density of simplification from its base value.
*
* @param factor
*/
public void setOverSamplingFactor(double factor) {
this.overSamplingFactor = factor;
}
/**
* Does this format use features clipped to the extent of the tile instead of whole features
*
* @param clip
*/
public void setClipToMapBounds(boolean clip) {
this.clipToMapBounds = clip;
}
/**
* Does this format use screen coordinates
*/
public void setTransformToScreenCoordinates(boolean useScreenCoords) {
this.transformToScreenCoordinates = useScreenCoords;
}
@Override
public byte[] produceMap(final WMSMapContent mapContent, CoordinateReferenceSystem coordinateReferenceSystem) throws ServiceException, IOException {
final ReferencedEnvelope renderingArea = mapContent.getRenderingArea();
final Rectangle paintArea = new Rectangle(mapContent.getMapWidth(), mapContent.getMapHeight());
VectorTileBuilder vectorTileBuilder;
vectorTileBuilder = this.tileBuilderFactory.newBuilder(paintArea, renderingArea);
CoordinateReferenceSystem sourceCrs;
for (Layer layer : mapContent.layers()) {
FeatureSource<?, ?> featureSource = layer.getFeatureSource();
GeometryDescriptor geometryDescriptor = featureSource.getSchema().getGeometryDescriptor();
if (null == geometryDescriptor) {
continue;
}
sourceCrs = geometryDescriptor.getType().getCoordinateReferenceSystem();
int buffer = VectorMapRenderUtils.getComputedBuffer(mapContent.getBuffer(), VectorMapRenderUtils.getFeatureStyles(layer, paintArea, VectorMapRenderUtils.getMapScale(mapContent, renderingArea), featureSource.getSchema()));
Pipeline pipeline = getPipeline(mapContent, renderingArea, paintArea, sourceCrs, buffer);
Query query = getStyleQuery(layer, mapContent);
query.getHints().remove(Hints.SCREENMAP);
FeatureCollection<?, ?> features = featureSource.getFeatures(query);
run(layer.getFeatureSource().getFeatures(), pipeline, geometryDescriptor, vectorTileBuilder, layer);
}
return vectorTileBuilder.build();
}
protected Pipeline getPipeline(final WMSMapContent mapContent, final ReferencedEnvelope renderingArea, final Rectangle paintArea, CoordinateReferenceSystem sourceCrs, int buffer) {
Pipeline pipeline;
try {
final PipelineBuilder builder = PipelineBuilder.newBuilder(renderingArea, paintArea, sourceCrs, overSamplingFactor, buffer);
pipeline = builder.preprocess().transform(transformToScreenCoordinates).simplify(transformToScreenCoordinates).clip(clipToMapBounds, transformToScreenCoordinates).collapseCollections().build();
} catch (FactoryException e) {
throw new ServiceException(e);
}
return pipeline;
}
private Map<String, Object> getProperties(ComplexAttribute feature) {
Map<String, Object> props = new TreeMap<>();
for (Property p : feature.getProperties()) {
if (!(p instanceof Attribute) || (p instanceof GeometryAttribute)) {
continue;
}
String name = p.getName().getLocalPart();
Object value;
if (p instanceof ComplexAttribute) {
value = getProperties((ComplexAttribute) p);
} else {
value = p.getValue();
}
if (value != null) {
props.put(name, value);
}
}
return props;
}
void run(FeatureCollection<?, ?> features, Pipeline pipeline, GeometryDescriptor geometryDescriptor, VectorTileBuilder vectorTileBuilder, Layer layer) {
Stopwatch sw = Stopwatch.createStarted();
int count = 0;
int total = 0;
Feature feature;
try (FeatureIterator<?> it = features.features()) {
while (it.hasNext()) {
feature = it.next();
total++;
Geometry originalGeom;
Geometry finalGeom;
originalGeom = (Geometry) feature.getDefaultGeometryProperty().getValue();
try {
finalGeom = pipeline.execute(originalGeom);
} catch (Exception processingException) {
processingException.printStackTrace();
continue;
}
if (finalGeom.isEmpty()) {
continue;
}
final String layerName = feature.getName().getLocalPart();
final String featureId = feature.getIdentifier().toString();
final String geometryName = geometryDescriptor.getName().getLocalPart();
final Map<String, Object> properties = getProperties(feature);
properties.put("shape", null);
vectorTileBuilder.addFeature(layerName, featureId, geometryName, finalGeom, properties);
count++;
}
}
sw.stop();
if (LOGGER.isLoggable(Level.FINE)) {
String msg = String.format("Added %,d out of %,d features of '%s' in %s", count, total, layer.getTitle(), sw);
// System.err.println(msg);
LOGGER.fine(msg);
}
}
/**
* @return {@code null}, not a raster format.
*/
@Override
public MapProducerCapabilities getCapabilities(String format) {
return null;
}
}
|
3e01376f4e40f79e5f211872e728d902d21b6847 | 975 | java | Java | core/src/main/java/org/apache/oozie/command/wf/StartXCommand.java | sunmeng007/oozie | 8ab5e8d1db3a9594cd569035c7d34006b2191483 | [
"Apache-2.0"
] | 34 | 2017-06-16T11:41:11.000Z | 2022-03-10T09:39:11.000Z | core/src/main/java/org/apache/oozie/command/wf/StartXCommand.java | sunmeng007/oozie | 8ab5e8d1db3a9594cd569035c7d34006b2191483 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/org/apache/oozie/command/wf/StartXCommand.java | sunmeng007/oozie | 8ab5e8d1db3a9594cd569035c7d34006b2191483 | [
"Apache-2.0"
] | 23 | 2017-07-19T01:18:22.000Z | 2022-02-28T07:34:34.000Z | 34.821429 | 76 | 0.726154 | 509 | /**
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package org.apache.oozie.command.wf;
import org.apache.oozie.util.InstrumentUtils;
/**
* Starting the command.
*/
public class StartXCommand extends SignalXCommand {
public StartXCommand(String id) {
super("start", 1, id);
InstrumentUtils.incrJobCounter(getName(), 1, getInstrumentation());
}
} |
3e0138c62a8cfcc16962380c19f007607613ffd1 | 3,762 | java | Java | src/main/java/idv/fd/etl/DbDataLoader.java | Yenchu/food-delivery-r2dbc | 048af9290cfdf974c03ae32a693d14381933abaa | [
"Apache-2.0"
] | null | null | null | src/main/java/idv/fd/etl/DbDataLoader.java | Yenchu/food-delivery-r2dbc | 048af9290cfdf974c03ae32a693d14381933abaa | [
"Apache-2.0"
] | null | null | null | src/main/java/idv/fd/etl/DbDataLoader.java | Yenchu/food-delivery-r2dbc | 048af9290cfdf974c03ae32a693d14381933abaa | [
"Apache-2.0"
] | null | null | null | 34.833333 | 224 | 0.69697 | 510 | package idv.fd.etl;
import idv.fd.etl.dto.RestaurantMenus;
import idv.fd.purchase.repository.PurchaseHistoryRepository;
import idv.fd.purchase.model.PurchaseHistory;
import idv.fd.restaurant.repository.MenuRepository;
import idv.fd.restaurant.repository.OpenHoursRepository;
import idv.fd.restaurant.repository.RestaurantRepository;
import idv.fd.restaurant.model.Menu;
import idv.fd.restaurant.model.OpenHours;
import idv.fd.restaurant.model.Restaurant;
import idv.fd.user.repository.UserRepository;
import idv.fd.user.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuple3;
import reactor.util.function.Tuples;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class DbDataLoader {
private RestaurantRepository restaurantRepository;
private MenuRepository menuRepository;
private OpenHoursRepository openHoursRepository;
private UserRepository userRepository;
private PurchaseHistoryRepository purchaseHistoryRepository;
public DbDataLoader(RestaurantRepository restaurantRepository, MenuRepository menuRepository, OpenHoursRepository openHoursRepository, UserRepository userRepository, PurchaseHistoryRepository purchaseHistoryRepository) {
this.restaurantRepository = restaurantRepository;
this.menuRepository = menuRepository;
this.openHoursRepository = openHoursRepository;
this.userRepository = userRepository;
this.purchaseHistoryRepository = purchaseHistoryRepository;
}
@Transactional
public Mono<Tuple3<Restaurant, List<Menu>, List<OpenHours>>> loadRestaurantData(Tuple3<Restaurant, List<Menu>, List<OpenHours>> tuple) {
Restaurant restaurant = tuple.getT1();
List<Menu> menus = tuple.getT2();
List<OpenHours> ohs = tuple.getT3();
return restaurantRepository.save(restaurant).zipWhen(r -> {
Long restaurantId = r.getId();
for (Menu m : menus) {
m.setRestaurantId(restaurantId);
}
for (OpenHours oh : ohs) {
oh.setRestaurantId(restaurantId);
}
return Mono.zip(menuRepository.saveAll(menus).collectList(), openHoursRepository.saveAll(ohs).collectList());
}).map(t -> Tuples.of(t.getT1(), t.getT2().getT1(), t.getT2().getT2()));
}
@Transactional
public Mono<Tuple2<User, List<PurchaseHistory>>> loadUserData(Tuple2<User, List<PurchaseHistory>> tuple, Map<String, RestaurantMenus> restMenusMap) {
User user = tuple.getT1();
List<PurchaseHistory> phs = tuple.getT2();
return userRepository.save(user).zipWhen(u -> {
updatePurchaseHistory(restMenusMap, user, phs);
return purchaseHistoryRepository.saveAll(phs).collectList();
});
}
protected void updatePurchaseHistory(Map<String, RestaurantMenus> restMenusMap, User user, List<PurchaseHistory> phs) {
for (PurchaseHistory ph : phs) {
ph.setUserId(user.getId());
RestaurantMenus restMenus = restMenusMap.get(ph.getRestaurantName());
if (restMenus == null) {
log.error("can not find restaurant for purchase history: {}", ph);
continue;
}
ph.setRestaurantId(restMenus.getId());
Long menuId = restMenus.getMenus().get(ph.getDishName());
if (menuId == null) {
log.error("can not find menu for purchase history: {}", ph);
continue;
}
ph.setMenuId(menuId);
}
}
}
|
3e013924d8f6429e61d7be8f1d081cd41c96433e | 8,606 | java | Java | src/main/java/com/datasonnet/xml/BadgerFishXMLStreamWriter.java | artnaseef/datasonnet-mapper | 911b1f466ee65f5f731416cbfe89382b93fbf684 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/datasonnet/xml/BadgerFishXMLStreamWriter.java | artnaseef/datasonnet-mapper | 911b1f466ee65f5f731416cbfe89382b93fbf684 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/datasonnet/xml/BadgerFishXMLStreamWriter.java | artnaseef/datasonnet-mapper | 911b1f466ee65f5f731416cbfe89382b93fbf684 | [
"Apache-2.0"
] | null | null | null | 32.11194 | 147 | 0.606554 | 511 | package com.datasonnet.xml;
import org.codehaus.jettison.AbstractXMLStreamWriter;
import org.codehaus.jettison.Node;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.util.FastStack;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
public class BadgerFishXMLStreamWriter extends AbstractXMLStreamWriter {
private JSONObject root;
private JSONObject currentNode;
private Writer writer;
private FastStack nodes;
private String currentKey;
private BadgerFishConfiguration configuration;
public BadgerFishXMLStreamWriter(Writer writer) {
this(writer, new BadgerFishConfiguration());
}
public BadgerFishXMLStreamWriter(Writer writer, BadgerFishConfiguration configuration) {
super();
this.root = new JSONObject();
this.currentNode = this.root;
this.writer = writer;
this.nodes = new FastStack(); //TODO - do we need it?
this.configuration = configuration;
}
public void close() throws XMLStreamException {
}
public void flush() throws XMLStreamException {
}
public NamespaceContext getNamespaceContext() {
return configuration.getNamespaceContext();
}
public String getPrefix(String ns) throws XMLStreamException {
return getNamespaceContext().getPrefix(ns);
}
public Object getProperty(String arg0) throws IllegalArgumentException {
return null;
}
public void setDefaultNamespace(String arg0) throws XMLStreamException {
}
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
this.configuration.setNamespaceContext(context);
}
public void setPrefix(String prefix, String ns) throws XMLStreamException {
SimpleNamespaceContext ctx = (SimpleNamespaceContext)configuration.getNamespaceContext();
String existingNS = ctx.getNamespaceURI(prefix);
if (existingNS == null || "".equals(existingNS)) {
ctx.bindNamespaceUri(prefix, ns);
} else {
int cnt = 1;
while (ctx.getNamespaceURI(prefix + cnt) != "") {
cnt++;
}
ctx.bindNamespaceUri(prefix + cnt, ns);
}
}
public void writeAttribute(String p, String ns, String local, String value) throws XMLStreamException {
String key = createAttributeKey(p, ns, local);
try {
getCurrentNode().put(key, value);
} catch (JSONException e) {
throw new XMLStreamException(e);
}
}
private String createAttributeKey(String p, String ns, String local) {
return configuration.getAttributeCharacter() + createKey(p, ns, local);
}
private String createKey(String p, String ns, String local) {
if (p == null) {
return local;
}
String pp = getNamespaceContext().getPrefix(ns);
if (pp == null) {
pp = p;
}
return (pp.equals("") ? pp : pp + configuration.getNamespaceSeparator()) + local;
}
public void writeAttribute(String ns, String local, String value) throws XMLStreamException {
writeAttribute(null, ns, local, value);
}
public void writeAttribute(String local, String value) throws XMLStreamException {
writeAttribute(null, local, value);
}
public void writeCData(String text) throws XMLStreamException {
writeCharacters(text, true);
}
public void writeCharacters(String text) throws XMLStreamException {
writeCharacters(text, false);
}
private void writeCharacters(String text, boolean isCDATA) throws XMLStreamException {
text = text.trim();
if (text.length() == 0) {
return;
}
String keyPrefix = (isCDATA ? configuration.getCdataValueKey() : configuration.getTextValueKey());
try {
int counter = 0;
Iterator keys = getCurrentNode().keys();
while (keys.hasNext()) {
String nextKey = (String)keys.next();
if (!isCDATA && nextKey.equalsIgnoreCase(keyPrefix)) { //Adding second text attribute requires removing the old one and renaming it
Object oldText = getCurrentNode().remove(nextKey);
getCurrentNode().put(keyPrefix + "1", text);
return;
}
if (nextKey.startsWith(keyPrefix)) {
counter++;
}
}
if (counter == 0) {
if (isCDATA) { //CDATA fragments all have numbers
counter = 1;
}
} else {
counter++;
}
getCurrentNode().put(keyPrefix + (counter == 0 ? "" : counter), text);
} catch (JSONException e) {
throw new XMLStreamException(e);
}
}
public void writeDefaultNamespace(String ns) throws XMLStreamException {
writeNamespace("", ns);
}
public void writeEndElement() throws XMLStreamException {
if (getNodes().size() > 1) {
getNodes().pop();
currentNode = ((Node) getNodes().peek()).getObject();
}
}
public void writeEntityRef(String arg0) throws XMLStreamException {
// TODO Auto-generated method stub
}
public void writeNamespace(String prefix, String ns) throws XMLStreamException {
SimpleNamespaceContext ctx = (SimpleNamespaceContext)configuration.getNamespaceContext();
String _prefix = prefix;
String configuredPrefix = ctx.getPrefix(ns);
if (configuredPrefix != null) {
_prefix = configuredPrefix;
}
((Node) getNodes().peek()).setNamespace(_prefix, ns);
JSONObject currentNode = getCurrentNode();
try {
JSONObject nsObj = currentNode.optJSONObject(configuration.getAttributeCharacter() + "xmlns");
if (nsObj == null) {
nsObj = new JSONObject();
currentNode.put(configuration.getAttributeCharacter() + "xmlns", nsObj);
}
if (_prefix.equals("")) {
_prefix = "$";
}
nsObj.put(_prefix, ns);
} catch (JSONException e) {
throw new XMLStreamException(e);
}
}
public void writeProcessingInstruction(String arg0, String arg1) throws XMLStreamException {
// TODO Auto-generated method stub
}
public void writeProcessingInstruction(String arg0) throws XMLStreamException {
// TODO Auto-generated method stub
}
public void writeStartDocument() throws XMLStreamException {
}
public void writeEndDocument() throws XMLStreamException {
try {
root.write(writer);
writer.flush();
} catch (JSONException e) {
throw new XMLStreamException(e);
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeStartElement(String prefix, String local, String ns) throws XMLStreamException {
try {
currentKey = createKey(prefix, ns, local);
Object existing = getCurrentNode().opt(currentKey);
if (existing instanceof JSONObject) {
JSONArray array = new JSONArray();
array.put(existing);
JSONObject newCurrent = new JSONObject();
array.put(newCurrent);
getCurrentNode().put(currentKey, array);
currentNode = newCurrent;
Node node = new Node(currentNode);
getNodes().push(node);
} else {
JSONObject newCurrent = new JSONObject();
if (existing instanceof JSONArray) {
((JSONArray) existing).put(newCurrent);
} else {
getCurrentNode().put(currentKey, newCurrent);
}
currentNode = newCurrent;
Node node = new Node(currentNode);
getNodes().push(node);
}
} catch (JSONException e) {
throw new XMLStreamException("Could not write start element!", e);
}
}
protected JSONObject getCurrentNode() {
return currentNode;
}
protected FastStack getNodes() {
return nodes;
}
} |
3e01398ce0e12656540bd0ad4766fce540db7e39 | 822 | java | Java | com/intkr/saas/domain/dbo/user/SecureQuestionDO.java | Beiden/Intkr_SAAS_BEIDEN | fb2b68f2e04a891523e3589dd3abebd2fcd5828d | [
"Apache-2.0"
] | null | null | null | com/intkr/saas/domain/dbo/user/SecureQuestionDO.java | Beiden/Intkr_SAAS_BEIDEN | fb2b68f2e04a891523e3589dd3abebd2fcd5828d | [
"Apache-2.0"
] | null | null | null | com/intkr/saas/domain/dbo/user/SecureQuestionDO.java | Beiden/Intkr_SAAS_BEIDEN | fb2b68f2e04a891523e3589dd3abebd2fcd5828d | [
"Apache-2.0"
] | 1 | 2022-03-16T15:04:17.000Z | 2022-03-16T15:04:17.000Z | 14.678571 | 49 | 0.695864 | 512 | package com.intkr.saas.domain.dbo.user;
import com.intkr.saas.domain.BaseDO;
/**
*
* @author Beiden
* @date 2016-5-28 下午10:51:14
* @version 1.0
*/
public class SecureQuestionDO extends BaseDO {
private static final long serialVersionUID = 1L;
private Long userId;
private String code;
private String question;
private String answer;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
|
3e013bc98d1d3c6ae379537ff1c6816d6d7acb10 | 11,398 | java | Java | src/org/cordovastudio/editors/designer/propertyTable/properties/IdProperty.java | chrimm/cordovastudio | 199233198db410a9f2d7c8d8c103b85220912dae | [
"Apache-2.0"
] | 2 | 2017-07-02T13:39:06.000Z | 2021-12-22T08:09:27.000Z | src/org/cordovastudio/editors/designer/propertyTable/properties/IdProperty.java | chrimm/cordovastudio | 199233198db410a9f2d7c8d8c103b85220912dae | [
"Apache-2.0"
] | null | null | null | src/org/cordovastudio/editors/designer/propertyTable/properties/IdProperty.java | chrimm/cordovastudio | 199233198db410a9f2d7c8d8c103b85220912dae | [
"Apache-2.0"
] | null | null | null | 42.214815 | 138 | 0.576154 | 513 | /*
* Copyright 2000-2012 JetBrains s.r.o.
* (Orignial as of com.intellij.android.designer.propertyTable.IdProperty)
*
* Copyright (C) 2014 Christoffer T. Timm
* Changes:
* – Adopted for Cordova projects
*
* 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.cordovastudio.editors.designer.propertyTable.properties;
import com.intellij.designer.model.PropertiesContainer;
import com.intellij.designer.model.Property;
import com.intellij.designer.model.PropertyContext;
import com.intellij.designer.propertyTable.InplaceContext;
import com.intellij.designer.propertyTable.PropertyEditor;
import com.intellij.designer.propertyTable.PropertyRenderer;
import com.intellij.designer.propertyTable.renderers.LabelPropertyRenderer;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.usageView.UsageInfo;
import org.cordovastudio.dom.AttributeDefinition;
import org.cordovastudio.dom.AttributeFormat;
import org.cordovastudio.editors.designer.model.IdManager;
import org.cordovastudio.editors.designer.model.RadModelBuilder;
import org.cordovastudio.editors.designer.model.RadViewComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import static org.cordovastudio.GlobalConstants.ATTR_ID;
import static org.cordovastudio.GlobalConstants.CORDOVASTUDIO_URI;
/**
* Customized renderer and property editors for the ID property
*/
public class IdProperty extends AttributeProperty {
private static final int REFACTOR_ASK = 0;
private static final int REFACTOR_NO = 1;
private static final int REFACTOR_YES = 2;
private static int ourRefactoringChoice = REFACTOR_ASK;
public static final Property INSTANCE = new IdProperty();
private IdProperty() {
this(ATTR_ID, new AttributeDefinition(ATTR_ID, Arrays.asList(AttributeFormat.Reference)));
setImportant(true);
}
public IdProperty(@NotNull String name, @NotNull AttributeDefinition definition) {
super(name, definition);
}
public IdProperty(@Nullable Property parent, @NotNull String name, @NotNull AttributeDefinition definition) {
super(parent, name, definition);
}
@Override
public Property<RadViewComponent> createForNewPresentation(@Nullable Property parent, @NotNull String name) {
return new IdProperty(parent, name, myDefinition);
}
@Override
public void setValue(@NotNull final RadViewComponent component, final Object value) throws Exception {
final String newId = value != null ? value.toString() : "";
IdManager idManager = IdManager.get(component);
final String oldId = component.getId();
if (ourRefactoringChoice != REFACTOR_NO
&& oldId != null
&& !oldId.isEmpty()
&& !newId.isEmpty()
&& !oldId.equals(newId)
&& component.getTag().isValid()) {
// Offer rename refactoring?
XmlTag tag = component.getTag();
XmlAttribute attribute = tag.getAttribute(ATTR_ID, CORDOVASTUDIO_URI);
if (attribute != null) {
Module module = RadModelBuilder.getModule(component);
if (module != null) {
XmlAttributeValue valueElement = attribute.getValueElement();
if (valueElement != null && valueElement.isValid()) {
final Project project = module.getProject();
// Exact replace only, no comment/text occurrence changes since it is non-interactive
RenameProcessor processor = new RenameProcessor(project, valueElement, newId, false /*comments*/, false /*text*/);
processor.setPreviewUsages(false);
// Do a quick usage search to see if we need to ask about renaming
UsageInfo[] usages = processor.findUsages();
if (usages.length > 0) {
int choice = ourRefactoringChoice;
if (choice == REFACTOR_ASK) {
DialogBuilder builder = new DialogBuilder(project);
builder.setTitle("Update Usages?");
JPanel panel = new JPanel(new BorderLayout()); // UGH!
JLabel label = new JLabel("<html>" +
"Update usages as well?<br>" +
"This will update all XML references and Java R field references.<br>" +
"<br>" +
"</html>");
panel.add(label, BorderLayout.CENTER);
JBCheckBox checkBox = new JBCheckBox("Don't ask again during this session");
panel.add(checkBox, BorderLayout.SOUTH);
builder.setCenterPanel(panel);
builder.setDimensionServiceKey("idPropertyDimension");
builder.removeAllActions();
DialogBuilder.CustomizableAction yesAction = builder.addOkAction();
yesAction.setText(Messages.YES_BUTTON);
builder.addActionDescriptor(new DialogBuilder.ActionDescriptor() {
@Override
public Action getAction(final DialogWrapper dialogWrapper) {
return new AbstractAction(Messages.NO_BUTTON) {
@Override
public void actionPerformed(ActionEvent actionEvent) {
dialogWrapper.close(DialogWrapper.NEXT_USER_EXIT_CODE);
}
};
}
});
builder.addCancelAction();
int exitCode = builder.show();
choice = exitCode == DialogWrapper.OK_EXIT_CODE ? REFACTOR_YES :
exitCode == DialogWrapper.NEXT_USER_EXIT_CODE ? REFACTOR_NO : ourRefactoringChoice;
if (!checkBox.isSelected()) {
ourRefactoringChoice = REFACTOR_ASK;
} else {
ourRefactoringChoice = choice;
}
if (exitCode == DialogWrapper.CANCEL_EXIT_CODE) {
return;
}
}
if (choice == REFACTOR_YES) {
processor.run();
// Fall through to also set the value in the layout editor property; otherwise we'll be out of sync
}
}
}
}
}
}
if (idManager != null) {
idManager.removeComponent(component, false);
}
//noinspection ConstantConditions
super.setValue(component, value);
if (idManager != null) {
idManager.addComponent(component);
}
}
@Override
public boolean availableFor(List<PropertiesContainer> components) {
return false;
}
private final PropertyRenderer myRenderer = new IdPropertyRenderer();
private final IdPropertyEditor myEditor = new IdPropertyEditor();
@NotNull
@Override
public PropertyRenderer getRenderer() {
return myRenderer;
}
@Override
public PropertyEditor getEditor() {
return myEditor;
}
/**
* Customized such that we can filter out the @+id/@id prefixes
* <p/>
* Also, no need to include a "..." button; you pretty much never want to link your declaration to an existing id
*/
private static class IdPropertyRenderer extends LabelPropertyRenderer {
public IdPropertyRenderer() {
super(null);
}
// Strip the @id/@+id/ prefix
@Override
@NotNull
public JComponent getComponent(@Nullable PropertiesContainer container,
PropertyContext context,
@Nullable Object value,
boolean selected,
boolean hasFocus) {
value = (value != null) ? value.toString() : "";
return super.getComponent(container, context, value, selected, hasFocus);
}
}
/**
* Customized such that we can filter out (and on edit, put back) the @+id/@id prefixes
* <p/>
* Also, no need to include a "..." button; you pretty much never want to link your declaration to an existing id
*/
private static class IdPropertyEditor extends PropertyEditor {
private final JTextField myEditor = new JTextField();
private IdPropertyEditor() {
JTextField textField = myEditor;
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fireValueCommitted(true, true);
}
});
}
@NotNull
@Override
public JComponent getComponent(@Nullable PropertiesContainer container,
@Nullable PropertyContext context,
Object value,
@Nullable InplaceContext inplaceContext) {
myEditor.setText((value != null) ? value.toString() : "");
preferredSizeChanged();
return myEditor;
}
@Nullable
@Override
public Object getValue() throws Exception {
return myEditor.getText().trim();
}
@Override
public void updateUI() {
SwingUtilities.updateComponentTreeUI(myEditor);
}
}
} |
3e013d3b614081a57e253dbd7fb0491d6636a9d3 | 3,462 | java | Java | Cosmos-Android/app/src/main/java/wannabit/io/cosmostaion/widget/WalletBandHolder.java | Manny27nyc/cosmostation-mobile | ca0b8be2354746ff984453f12aabb5d04d01fde4 | [
"MIT"
] | null | null | null | Cosmos-Android/app/src/main/java/wannabit/io/cosmostaion/widget/WalletBandHolder.java | Manny27nyc/cosmostation-mobile | ca0b8be2354746ff984453f12aabb5d04d01fde4 | [
"MIT"
] | null | null | null | Cosmos-Android/app/src/main/java/wannabit/io/cosmostaion/widget/WalletBandHolder.java | Manny27nyc/cosmostation-mobile | ca0b8be2354746ff984453f12aabb5d04d01fde4 | [
"MIT"
] | null | null | null | 48.760563 | 146 | 0.73368 | 514 | package wannabit.io.cosmostaion.widget;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import java.math.BigDecimal;
import wannabit.io.cosmostaion.R;
import wannabit.io.cosmostaion.activities.MainActivity;
import wannabit.io.cosmostaion.activities.ValidatorListActivity;
import wannabit.io.cosmostaion.activities.VoteListActivity;
import wannabit.io.cosmostaion.utils.WDp;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_BAND;
public class WalletBandHolder extends WalletHolder {
public TextView mTvBandTotal, mTvBandValue, mTvBandAvailable, mTvBandDelegated, mTvBandUnBonding, mTvBandRewards;
public RelativeLayout mBtnStake, mBtnVote;
public WalletBandHolder(@NonNull View itemView) {
super(itemView);
mTvBandTotal = itemView.findViewById(R.id.band_total_amount);
mTvBandValue = itemView.findViewById(R.id.band_total_value);
mTvBandAvailable = itemView.findViewById(R.id.band_available);
mTvBandDelegated = itemView.findViewById(R.id.band_delegate);
mTvBandUnBonding = itemView.findViewById(R.id.band_unbonding);
mTvBandRewards = itemView.findViewById(R.id.band_reward);
mBtnStake = itemView.findViewById(R.id.btn_band_delegate);
mBtnVote = itemView.findViewById(R.id.btn_band_vote);
}
public void onBindHolder(@NotNull MainActivity mainActivity) {
final BigDecimal availableAmount = WDp.getAvailableCoin(mainActivity.mBalances, TOKEN_BAND);
final BigDecimal delegateAmount = WDp.getAllDelegatedAmount(mainActivity.mBondings, mainActivity.mAllValidators, mainActivity.mBaseChain);
final BigDecimal unbondingAmount = WDp.getUnbondingAmount(mainActivity.mUnbondings);
final BigDecimal rewardAmount = WDp.getAllRewardAmount(mainActivity.mRewards, TOKEN_BAND);
final BigDecimal totalAmount = availableAmount.add(delegateAmount).add(unbondingAmount).add(rewardAmount);
mTvBandTotal.setText(WDp.getDpAmount2(mainActivity, totalAmount, 6, 6));
mTvBandAvailable.setText(WDp.getDpAmount2(mainActivity, availableAmount, 6, 6));
mTvBandDelegated.setText(WDp.getDpAmount2(mainActivity, delegateAmount, 6, 6));
mTvBandUnBonding.setText(WDp.getDpAmount2(mainActivity, unbondingAmount, 6, 6));
mTvBandRewards.setText(WDp.getDpAmount2(mainActivity, rewardAmount, 6, 6));
mTvBandValue.setText(WDp.getValueOfBand(mainActivity, mainActivity.getBaseDao(), totalAmount));
mainActivity.getBaseDao().onUpdateLastTotalAccount(mainActivity.mAccount, totalAmount.toPlainString());
mBtnStake.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent validators = new Intent(mainActivity, ValidatorListActivity.class);
validators.putExtra("rewards", mainActivity.mRewards);
mainActivity.startActivity(validators);
}
});
mBtnVote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent proposals = new Intent(mainActivity, VoteListActivity.class);
mainActivity.startActivity(proposals);
}
});
}
}
|
3e013dd2abd8b859bcc2ca7fac1bdb11801aea45 | 1,163 | java | Java | samples/easymock/src/org/easymock/samples/TaxCalculator.java | theyelllowdart/jmockit | 08eb1269cf7a0d3fc60743a488d655d0cb6e08e8 | [
"MIT"
] | null | null | null | samples/easymock/src/org/easymock/samples/TaxCalculator.java | theyelllowdart/jmockit | 08eb1269cf7a0d3fc60743a488d655d0cb6e08e8 | [
"MIT"
] | 1 | 2015-05-28T16:05:06.000Z | 2015-05-28T16:08:24.000Z | samples/easymock/src/org/easymock/samples/TaxCalculator.java | theyelllowdart/jmockit | 08eb1269cf7a0d3fc60743a488d655d0cb6e08e8 | [
"MIT"
] | null | null | null | 25.844444 | 76 | 0.66724 | 515 | /*
* Copyright 2003-2009 OFFIS, Henri Tremblay
*
* 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.easymock.samples;
import java.math.*;
/**
* Class to test and partially mock.
*/
public abstract class TaxCalculator
{
private final BigDecimal[] values;
protected TaxCalculator(BigDecimal... values)
{
this.values = values;
}
protected abstract BigDecimal rate();
public final BigDecimal tax()
{
BigDecimal result = BigDecimal.ZERO;
for (BigDecimal d : values) {
result = result.add(d);
}
return result.multiply(rate());
}
}
|
3e013dfc9b1f0a457b06c3261b3a01da6913367d | 477 | java | Java | mall-member/src/main/java/com/touch/air/mall/member/service/MemberCollectSpuService.java | dongdong1018645785/touch-air-mall | cc75e5e75690bda9d20d23c192c0576cbafe17f0 | [
"Apache-2.0"
] | 1 | 2021-07-16T02:15:44.000Z | 2021-07-16T02:15:44.000Z | mall-member/src/main/java/com/touch/air/mall/member/service/MemberCollectSpuService.java | dongdong1018645785/touch-air-mall | cc75e5e75690bda9d20d23c192c0576cbafe17f0 | [
"Apache-2.0"
] | null | null | null | mall-member/src/main/java/com/touch/air/mall/member/service/MemberCollectSpuService.java | dongdong1018645785/touch-air-mall | cc75e5e75690bda9d20d23c192c0576cbafe17f0 | [
"Apache-2.0"
] | null | null | null | 22.714286 | 83 | 0.771488 | 516 | package com.touch.air.mall.member.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.touch.air.common.utils.PageUtils;
import com.touch.air.mall.member.entity.MemberCollectSpuEntity;
import java.util.Map;
/**
* 会员收藏的商品
*
* @author bin.wang
* @email hzdkv@example.com
* @date 2020-12-04 14:18:41
*/
public interface MemberCollectSpuService extends IService<MemberCollectSpuEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
3e013ea2130cb717a17e1e0165734199a71690e5 | 883 | java | Java | documentsmanager/src/main/java/com/documentsmanager/service/RedisService.java | KaanArdar/DocumentsManager | 956d8ca0656f36223f29d21cad73014ea1f991a8 | [
"Apache-2.0"
] | null | null | null | documentsmanager/src/main/java/com/documentsmanager/service/RedisService.java | KaanArdar/DocumentsManager | 956d8ca0656f36223f29d21cad73014ea1f991a8 | [
"Apache-2.0"
] | null | null | null | documentsmanager/src/main/java/com/documentsmanager/service/RedisService.java | KaanArdar/DocumentsManager | 956d8ca0656f36223f29d21cad73014ea1f991a8 | [
"Apache-2.0"
] | 1 | 2020-03-24T08:45:23.000Z | 2020-03-24T08:45:23.000Z | 25.970588 | 90 | 0.783692 | 517 | package com.documentsmanager.service;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.documentsmanager.model.DocumentBody;
@Service
public class RedisService{
@Autowired
private RedisTemplate<String, DocumentBody> template;
public void setValue(final String key, final DocumentBody value) {
template.opsForValue().set(key, value);
}
public void setValue(final String key, final DocumentBody value, final long expireTime) {
template.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
}
public DocumentBody getValue(final String key) {
return template.opsForValue().get(key);
}
public void remKey(final String key) {
template.opsForValue().getOperations().delete(key);
}
}
|
3e013f571475ba9a9c82c7fe069bd9dcc5972a95 | 562 | java | Java | src/main/java/io/bigdogz/expiringaccounts/command/Transaction.java | bigdogz-io/expiring-accounts | bf784791d23b03c2e3e5e9c71a4b85297cc9e9fa | [
"Apache-2.0"
] | null | null | null | src/main/java/io/bigdogz/expiringaccounts/command/Transaction.java | bigdogz-io/expiring-accounts | bf784791d23b03c2e3e5e9c71a4b85297cc9e9fa | [
"Apache-2.0"
] | null | null | null | src/main/java/io/bigdogz/expiringaccounts/command/Transaction.java | bigdogz-io/expiring-accounts | bf784791d23b03c2e3e5e9c71a4b85297cc9e9fa | [
"Apache-2.0"
] | null | null | null | 24.434783 | 97 | 0.736655 | 518 | package io.bigdogz.expiringaccounts.command;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
public class Transaction {
private String transactionId;
private Long timestamp;
private String description;
private Double amount;
public Transaction(String transactionId, Long timestamp, String description, Double amount) {
this.transactionId = transactionId;
this.timestamp = timestamp;
this.description = description;
this.amount = amount;
}
}
|
3e013f7cf4440eba006e99c143ccdde769117e73 | 19,348 | java | Java | src/co/eightyfourthousand/readingroom/client/Lobby.java | 84000/readingroom | 67ead39fd7984315a2b1023a2cc26c50d07d1878 | [
"Apache-2.0"
] | 1 | 2017-11-11T09:29:10.000Z | 2017-11-11T09:29:10.000Z | src/co/eightyfourthousand/readingroom/client/Lobby.java | 84000/readingroom | 67ead39fd7984315a2b1023a2cc26c50d07d1878 | [
"Apache-2.0"
] | 1 | 2017-01-10T04:43:12.000Z | 2017-01-10T04:43:12.000Z | src/co/eightyfourthousand/readingroom/client/Lobby.java | 84000/readingroom | 67ead39fd7984315a2b1023a2cc26c50d07d1878 | [
"Apache-2.0"
] | null | null | null | 36.300188 | 103 | 0.748036 | 519 | package co.eightyfourthousand.readingroom.client;
import java.util.ArrayList;
import co.eightyfourthousand.readingroom.shared.Global;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
*
* The main "lobby" view (cards/tomb-stones)
*
* @author curtis
*
*/
public class Lobby extends Composite {
private static LobbyUiBinder uiBinder = GWT.create(LobbyUiBinder.class);
interface LobbyUiBinder extends UiBinder<Widget, Lobby> {}
@UiField HTMLPanel lobbyPage;
@UiField VerticalPanel titleBlockPanel;
@UiField Label titleEnLabel;
@UiField Label titleTiLabel;
@UiField Label titleWyLabel;
@UiField Label titleSaLabel;
@UiField HTML desc;
@UiField Grid titleTiWyGrid;
@UiField Grid kangyurGrid;
@UiField Grid kangyurCatGrid;
@UiField VerticalPanel kangyurTitleBar;
@UiField HorizontalPanel kangyurTitleInner;
@UiField Button kLearnMoreButton;
@UiField HTML kLearnMoreDisclosure;
@UiField HTMLPanel kangyurTitlePanel;
@UiField VerticalPanel kangyurContentPanel;
@UiField VerticalPanel kangyurLearnMorePanel;
@UiField Label kangyurTitleEn;
@UiField Label kangyurTitleTi;
@UiField HTML kangyurDesc;
@UiField Grid tengyurGrid;
@UiField Grid tengyurCatGrid;
@UiField VerticalPanel tengyurTitleBar;
@UiField HorizontalPanel tengyurTitleInner;
@UiField Button tLearnMoreButton;
@UiField HTML tLearnMoreDisclosure;
@UiField HTMLPanel tengyurTitlePanel;
@UiField VerticalPanel tengyurContentPanel;
@UiField VerticalPanel tengyurLearnMorePanel;
@UiField Label tengyurTitleEn;
@UiField Label tengyurTitleTi;
@UiField HTML tengyurDesc;
@UiField FocusPanel kangyurCatPanel;
@UiField FocusPanel tengyurCatPanel;
@UiField Label kCatTitleEnLabel;
@UiField Label kCatTitleWyLabel;
@UiField Label kCatDescLabel;
@UiField VerticalPanel kCatBottomPanel;
@UiField VerticalPanel kCatSidePanel;
@UiField Label tCatTitleEnLabel;
@UiField Label tCatTitleWyLabel;
@UiField Label tCatDescLabel;
@UiField VerticalPanel tCatBottomPanel;
@UiField VerticalPanel tCatSidePanel;
private int kGridRows = 0, tGridRows = 0;
private int gridCols = 0;
private String colWidth = "25%";
private int lastPortWidth = 0;
private boolean isLobbyLevel = true;
private boolean isKLearnMoreDiscVisible = false;
private boolean isTLearnMoreDiscVisible = false;
private ArrayList<DataItem> kangyurItems = new ArrayList<DataItem>();
private ArrayList<DataItem> tengyurItems = new ArrayList<DataItem>();
public Lobby(boolean isLobbyLevel)
{
initWidget(uiBinder.createAndBindUi(this));
// Establish whether this is our top-level lobby view or not
this.isLobbyLevel = isLobbyLevel;
if (isLobbyLevel)
titleBlockPanel.setVisible(false);
else
{
// Move Tengyur title bar so it is above title block
tengyurTitlePanel.remove(tengyurTitleBar);
kangyurTitlePanel.add(tengyurTitleBar);
// Catalogues are not used except for the main lobby view
kangyurCatGrid.setVisible(false);
tengyurCatGrid.setVisible(false);
}
// Establish initial rows & cols based on viewport size
int width = Window.getClientWidth();
if (width >= Global.LARGE_VIEWPORT_MIN_WIDTH)
{
gridCols = 4;
colWidth = "25%";
}
else if (width >= Global.MEDIUM_VIEWPORT_MIN_WIDTH)
{
gridCols = 2;
colWidth = "50%";
}
else // width < med min
{
gridCols = 1;
colWidth = "100%";
}
}
@UiHandler("kLearnMoreButton")
void onMoreKClick(ClickEvent e) {
//Window.alert("child count: " + kLearnMoreDisclosure.getElement().getChildCount());
isKLearnMoreDiscVisible = !isKLearnMoreDiscVisible;
kLearnMoreDisclosure.setVisible(isKLearnMoreDiscVisible);
if (isKLearnMoreDiscVisible)
kLearnMoreButton.addStyleName("infoButtonActivated");
else
{
kLearnMoreButton.setStyleName("infoButton");
kLearnMoreButton.addStyleName("ss-info");
}
}
// @UiHandler("kCatTitleEnLabel")
// void onkCatTitleEnClick(ClickEvent e) {
// Readingroom.main.newPage(kangyurItems.get(kangyurItems.size()-1), kCatTitleEnLabel);
// }
@UiHandler("kangyurCatPanel")
void onKangyurCatPanelClick(ClickEvent e) {
Readingroom.main.newPage(kangyurItems.get(kangyurItems.size()-1), kangyurCatPanel);
}
@UiHandler("tLearnMoreButton")
void onMoreTClick(ClickEvent e) {
isTLearnMoreDiscVisible = !isTLearnMoreDiscVisible;
tLearnMoreDisclosure.setVisible(isTLearnMoreDiscVisible);
if (isTLearnMoreDiscVisible)
tLearnMoreButton.addStyleName("infoButtonActivated");
else
{
tLearnMoreButton.setStyleName("infoButton");
tLearnMoreButton.addStyleName("ss-info");
}
}
// @UiHandler("tCatTitleEnLabel")
// void ontCatTitleEnClick(ClickEvent e) {
// Readingroom.main.newPage(tengyurItems.get(tengyurItems.size()-1), tCatTitleEnLabel);
// }
@UiHandler("tengyurCatPanel")
void onTengyurCatPanelClick(ClickEvent e) {
Readingroom.main.newPage(tengyurItems.get(tengyurItems.size()-1), tengyurCatPanel);
}
public void initialize(DataItem data)
{
// NOTE: This is only called for non-top-level instances
titleEnLabel.setText(data.getNameEn());
titleTiLabel.setText(data.getNameTi());
titleWyLabel.setText(Utils.removeTrailingChar(data.getNameWy(), "/"));
titleSaLabel.setText(data.getNameSa());
//desc.setText(data.getDesc());
desc.setHTML(data.getDesc());
//kLearnMoreDisclosure.getElement().setPropertyBoolean("normalize", true);
kLearnMoreDisclosure.setHTML(data.getLearnMore() + data.getNote());
if (kLearnMoreDisclosure.getHTML() == "")
kLearnMoreDisclosure.setHTML("[More information will be made available soon]");
tLearnMoreDisclosure.setHTML(kLearnMoreDisclosure.getHTML());
// Crazy required chapuza!
titleTiWyGrid.getColumnFormatter().setWidth(0, "50%");
titleTiWyGrid.getColumnFormatter().setWidth(1, "50%");
}
public void onViewportSizeChange(int newWidth)
{
// Only invoke changes if we cross a viewport-change width
if (Utils.viewPortChanged(newWidth, lastPortWidth))
{
if (newWidth >= Global.LARGE_VIEWPORT_MIN_WIDTH)
{
gridCols = 4;
colWidth = "25%";
titleEnLabel.setStyleName("sectionTitleEn"); titleEnLabel.addStyleName("sectionTitleEnLarge");
titleTiLabel.setStyleName("sectionTitleTi"); titleTiLabel.addStyleName("sectionTitleLarge");
titleWyLabel.setStyleName("sectionTitleWy"); titleWyLabel.addStyleName("sectionTitleLarge");
titleSaLabel.setStyleName("sectionTitleSa"); titleSaLabel.addStyleName("sectionTitleLarge");
desc.setStyleName("sectionTitleDesc"); desc.addStyleName("sectionTitleDescLarge");
titleBlockPanel.setWidth("60%");
kangyurLearnMorePanel.setWidth("60%");
tengyurLearnMorePanel.setWidth("60%");
if (isLobbyLevel)
{
kangyurTitlePanel.setStyleName("titleLarge");
kangyurTitleEn.setStyleName("bigTitleFont"); kangyurTitleEn.addStyleName("titleFontLarge");
kangyurTitleTi.setStyleName("bigTitleTFont"); kangyurTitleTi.addStyleName("titleFontLarge");
tengyurTitlePanel.setStyleName("titleLarge");
tengyurTitleEn.setStyleName("bigTitleFont"); tengyurTitleEn.addStyleName("titleFontLarge");
tengyurTitleTi.setStyleName("bigTitleTFont"); tengyurTitleTi.addStyleName("titleFontLarge");
kLearnMoreButton.setText(" LEARN MORE ABOUT THE KANGYUR");
tLearnMoreButton.setText(" LEARN MORE ABOUT THE TENGYUR");
}
else
{
kangyurTitlePanel.setStyleName("titleSmall");
kangyurTitleEn.setStyleName("bigTitleFont"); kangyurTitleEn.addStyleName("titleFontSmall");
kangyurTitleTi.setStyleName("bigTitleTFont"); kangyurTitleTi.addStyleName("titleFontSmall");
tengyurTitlePanel.setStyleName("titleSmall");
tengyurTitleEn.setStyleName("bigTitleFont"); tengyurTitleEn.addStyleName("titleFontSmall");
tengyurTitleTi.setStyleName("bigTitleTFont"); tengyurTitleTi.addStyleName("titleFontSmall");
kLearnMoreButton.setText(" LEARN MORE ABOUT " + titleEnLabel.getText().toUpperCase());
tLearnMoreButton.setText(" LEARN MORE ABOUT " + titleEnLabel.getText().toUpperCase());
}
kangyurTitleBar.setCellHorizontalAlignment(kangyurTitleInner, HasHorizontalAlignment.ALIGN_LEFT);
tengyurTitleBar.setCellHorizontalAlignment(tengyurTitleInner, HasHorizontalAlignment.ALIGN_LEFT);
//tengyurTitleEn.setStyleName("bigTitleFont"); tengyurTitleEn.addStyleName("titleFontLarge");
//tengyurTitleTi.setStyleName("bigTitleTFont"); tengyurTitleTi.addStyleName("titleFontLarge");
lobbyPage.setWidth("94%");
kangyurCatGrid.setWidth("48%");
tengyurCatGrid.setWidth("48%");
}
else if (newWidth >= Global.MEDIUM_VIEWPORT_MIN_WIDTH)
{
gridCols = 2;
colWidth = "50%";
titleEnLabel.setStyleName("sectionTitleEn"); titleEnLabel.addStyleName("sectionTitleEnMedium");
titleTiLabel.setStyleName("sectionTitleTi"); titleTiLabel.addStyleName("sectionTitleMedium");
titleWyLabel.setStyleName("sectionTitleWy"); titleWyLabel.addStyleName("sectionTitleMedium");
titleSaLabel.setStyleName("sectionTitleSa"); titleSaLabel.addStyleName("sectionTitleMedium");
desc.setStyleName("sectionTitleDesc"); desc.addStyleName("sectionTitleDescMedium");
titleBlockPanel.setWidth("60%");
kangyurLearnMorePanel.setWidth("60%");
tengyurLearnMorePanel.setWidth("60%");
kLearnMoreButton.setText(" LEARN MORE");
tLearnMoreButton.setText(" LEARN MORE");
if (isLobbyLevel)
{
kangyurTitlePanel.setStyleName("titleMedium");
kangyurTitleEn.setStyleName("bigTitleFont"); kangyurTitleEn.addStyleName("titleFontMedium");
kangyurTitleTi.setStyleName("bigTitleTFont"); kangyurTitleTi.addStyleName("titleFontMedium");
tengyurTitlePanel.setStyleName("titleMedium");
tengyurTitleEn.setStyleName("bigTitleFont"); tengyurTitleEn.addStyleName("titleFontMedium");
tengyurTitleTi.setStyleName("bigTitleTFont"); tengyurTitleTi.addStyleName("titleFontMedium");
}
else
{
kangyurTitlePanel.setStyleName("titleSmall");
kangyurTitleEn.setStyleName("bigTitleFont"); kangyurTitleEn.addStyleName("titleFontSmall");
kangyurTitleTi.setStyleName("bigTitleTFont"); kangyurTitleTi.addStyleName("titleFontSmall");
tengyurTitlePanel.setStyleName("titleSmall");
tengyurTitleEn.setStyleName("bigTitleFont"); tengyurTitleEn.addStyleName("titleFontSmall");
tengyurTitleTi.setStyleName("bigTitleTFont"); tengyurTitleTi.addStyleName("titleFontSmall");
}
kangyurTitleBar.setCellHorizontalAlignment(kangyurTitleInner, HasHorizontalAlignment.ALIGN_CENTER);
tengyurTitleBar.setCellHorizontalAlignment(tengyurTitleInner, HasHorizontalAlignment.ALIGN_CENTER);
kCatBottomPanel.remove(kCatDescLabel);
kCatSidePanel.add(kCatDescLabel);
//kCatBottomPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
kangyurCatGrid.getColumnFormatter().setWidth(0, "50%");
kangyurCatGrid.getColumnFormatter().setWidth(1, "50%");
tCatBottomPanel.remove(tCatDescLabel);
tCatSidePanel.add(tCatDescLabel);
//tCatBottomPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
tengyurCatGrid.getColumnFormatter().setWidth(0, "50%");
tengyurCatGrid.getColumnFormatter().setWidth(1, "50%");
lobbyPage.setWidth("94%");
kangyurCatGrid.setWidth("94%");
tengyurCatGrid.setWidth("94%");
}
else // newWith < med min
{
gridCols = 1;
colWidth = "100%";
titleEnLabel.setStyleName("sectionTitleEn"); titleEnLabel.addStyleName("sectionTitleEnSmall");
titleTiLabel.setStyleName("sectionTitleTi"); titleTiLabel.addStyleName("sectionTitleSmall");
titleWyLabel.setStyleName("sectionTitleWy"); titleWyLabel.addStyleName("sectionTitleSmall");
titleSaLabel.setStyleName("sectionTitleSa"); titleSaLabel.addStyleName("sectionTitleSmall");
desc.setStyleName("sectionTitleDesc"); desc.addStyleName("sectionTitleDescSmall");
titleBlockPanel.setWidth("90%");
kangyurLearnMorePanel.setWidth("90%");
tengyurLearnMorePanel.setWidth("90%");
kLearnMoreButton.setText(" LEARN MORE");
tLearnMoreButton.setText(" LEARN MORE");
kangyurTitlePanel.setStyleName("titleSmall");
kangyurTitleBar.setCellHorizontalAlignment(kangyurTitleInner, HasHorizontalAlignment.ALIGN_CENTER);
kangyurTitleEn.setStyleName("bigTitleFont"); kangyurTitleEn.addStyleName("titleFontSmall");
kangyurTitleTi.setStyleName("bigTitleTFont"); kangyurTitleTi.addStyleName("titleFontSmall");
tengyurTitlePanel.setStyleName("titleSmall");
tengyurTitleBar.setCellHorizontalAlignment(tengyurTitleInner, HasHorizontalAlignment.ALIGN_CENTER);
tengyurTitleEn.setStyleName("bigTitleFont"); tengyurTitleEn.addStyleName("titleFontSmall");
tengyurTitleTi.setStyleName("bigTitleTFont"); tengyurTitleTi.addStyleName("titleFontSmall");
kCatSidePanel.remove(kCatDescLabel);
kCatBottomPanel.add(kCatDescLabel);
//kCatBottomPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
kangyurCatGrid.getColumnFormatter().setWidth(0, "100%");
kangyurCatGrid.getColumnFormatter().setWidth(1, "0%");
tCatSidePanel.remove(tCatDescLabel);
tCatBottomPanel.add(tCatDescLabel);
//tCatBottomPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
tengyurCatGrid.getColumnFormatter().setWidth(0, "100%");
tengyurCatGrid.getColumnFormatter().setWidth(1, "0%");
lobbyPage.setWidth("100%");
kangyurCatGrid.setWidth("92%");
tengyurCatGrid.setWidth("92%");
}
resetGrids();
}
lastPortWidth = newWidth;
}
public void populatePage(String kDesc, String kLearnMore, ArrayList<DataItem> kItems,
String tDesc, String tLearnMore, ArrayList<DataItem> tItems)
{
kangyurItems = kItems;
tengyurItems = tItems;
if (kangyurItems.size() == 0)
{
//kangyurTitleBar.setVisible(false);
//kLearnMoreButton.setVisible(false);
// kangyurTitlePanel.removeFromParent();
kangyurTitleBar.removeFromParent();
kangyurContentPanel.removeFromParent();
}
if (tengyurItems.size() == 0)
{
//tengyurTitleBar.setVisible(false);
//tLearnMoreButton.setVisible(false);
// tengyurTitlePanel.removeFromParent();
tengyurTitleBar.removeFromParent();
tengyurContentPanel.removeFromParent();
}
resetGrids();
// Place top-level description
//kangyurDesc.setText(kDesc);
kangyurDesc.setHTML(kDesc);
if (kLearnMore.length() > 0)
kLearnMoreDisclosure.setHTML(kLearnMore);
// Handle last kanjur item ("Kangyur Catalogue")
if (isLobbyLevel)
{
int lastIndex = kangyurItems.size() - 1;
kCatTitleEnLabel.setText(kangyurItems.get(lastIndex).getNameEn());
kCatTitleWyLabel.setText(kangyurItems.get(lastIndex).getNameWy());
kCatDescLabel.setText(kangyurItems.get(lastIndex).getDesc());
}
// Place top-level description
//tengyurDesc.setText(tDesc);
tengyurDesc.setHTML(tDesc);
if (tLearnMore.length() > 0)
tLearnMoreDisclosure.setHTML(tLearnMore);
// Handle last tenjur item ("Tengyur Catalogue")
if (isLobbyLevel)
{
int lastIndex = tengyurItems.size() - 1;
tCatTitleEnLabel.setText(tengyurItems.get(lastIndex).getNameEn());
tCatTitleWyLabel.setText(tengyurItems.get(lastIndex).getNameWy());
tCatDescLabel.setText(tengyurItems.get(lastIndex).getDesc());
}
}
private void resetGrids()
{
kGridRows = kangyurItems.size() / gridCols;
int count = kGridRows * gridCols;
if (isLobbyLevel)
count++;
if (count < kangyurItems.size())
kGridRows++;
count = tGridRows * gridCols;
if (isLobbyLevel)
count++;
tGridRows = tengyurItems.size() / gridCols;
if (count < tengyurItems.size())
tGridRows++;
if (kGridRows > 0)
{
kangyurGrid.clear();
kangyurGrid.resize(kGridRows, gridCols);
placeKangyurItems();
}
if (tGridRows > 0)
{
tengyurGrid.clear();
tengyurGrid.resize(tGridRows, gridCols);
placeTengyurItems();
}
}
private void placeKangyurItems()
{
// Make sure rows are top-aligned
for (int i = 0; i < kGridRows; i++)
kangyurGrid.getRowFormatter().setVerticalAlign(i, HasVerticalAlignment.ALIGN_TOP);
// Make sure we have even-width columns
for (int i = 0; i < gridCols; i++)
kangyurGrid.getColumnFormatter().setWidth(i, colWidth);
// Put lobby sections in appropriate grid cells
int count = kangyurItems.size();
if (isLobbyLevel)
count -= 1;
for (int i = 0; i < count; i++)
{
final LobbySection lobbySection = new LobbySection();
kangyurGrid.setWidget((i/gridCols), (i%gridCols), lobbySection);
DataItem item = kangyurItems.get(i);
item.setCategory("kangyur");
lobbySection.setData(item);
}
// Make sure catalogue has correct category
kangyurItems.get(kangyurItems.size()-1).setCategory("kangyur");
// If 2 remain in last row, center them (only for wide viewport)
if (gridCols == 4)
{
if (((kGridRows * gridCols) - count) == 2)
{
int row = kGridRows-1;
LobbySection ls;
kangyurGrid.clearCell(row, 3);
ls = (LobbySection)kangyurGrid.getWidget(row, 1);
kangyurGrid.setWidget(row, 2, ls);
ls = (LobbySection)kangyurGrid.getWidget(row, 0);
kangyurGrid.setWidget(row, 1, ls);
kangyurGrid.clearCell(row, 0);
}
}
}
private void placeTengyurItems()
{
// Make sure rows are top-aligned
for (int i = 0; i < tGridRows; i++)
tengyurGrid.getRowFormatter().setVerticalAlign(i, HasVerticalAlignment.ALIGN_TOP);
// Make sure we have even-width columns
for (int i = 0; i < gridCols; i++)
tengyurGrid.getColumnFormatter().setWidth(i, colWidth);
// Put lobby sections in appropriate grid cells
int count = tengyurItems.size();
if (isLobbyLevel)
count -= 1;
for (int i = 0; i < count; i++)
{
LobbySection lobbySection = new LobbySection();
tengyurGrid.setWidget((i/gridCols), (i%gridCols), lobbySection);
DataItem item = tengyurItems.get(i);
item.setCategory("tengyur");
lobbySection.setData(item);
}
// Make sure catalogue has correct category
tengyurItems.get(tengyurItems.size()-1).setCategory("tengyur");
// If 2 remain in last row, center them (only for wide viewport)
if (gridCols == 4)
{
if (((tGridRows * gridCols) - count) == 2)
{
int row = tGridRows-1;
LobbySection ls;
tengyurGrid.clearCell(row, 3);
ls = (LobbySection)tengyurGrid.getWidget(row, 1);
tengyurGrid.setWidget(row, 2, ls);
ls = (LobbySection)tengyurGrid.getWidget(row, 0);
tengyurGrid.setWidget(row, 1, ls);
tengyurGrid.clearCell(row, 0);
}
}
}
public ArrayList<DataItem> getKangyurItems() { return kangyurItems; }
public ArrayList<DataItem> getTengyurItems() { return tengyurItems; }
}
|
3e013f8e531b22f0835b7087ddd47efd23837c8b | 1,382 | java | Java | src/main/java/com/abcl/libmgmt/repository/BookRepository.java | TusharGirase/LibraryMgmtSystem | e1a0bba62de722f517658d91bb9dc3959dfad63d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/abcl/libmgmt/repository/BookRepository.java | TusharGirase/LibraryMgmtSystem | e1a0bba62de722f517658d91bb9dc3959dfad63d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/abcl/libmgmt/repository/BookRepository.java | TusharGirase/LibraryMgmtSystem | e1a0bba62de722f517658d91bb9dc3959dfad63d | [
"Apache-2.0"
] | 2 | 2020-11-04T04:46:14.000Z | 2021-06-20T21:45:31.000Z | 30.043478 | 76 | 0.757598 | 520 | /* bcabcl
*
* Copyright (c) 2018 Tushar Girase 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.
*
* ecabcl
*/
package com.abcl.libmgmt.repository;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.abcl.libmgmt.models.Book;
/**
*
*/
@Repository
@Transactional
public interface BookRepository extends CrudRepository<Book, Long> {
@Query("select o from Book o where isbin = :isbinNo")
public Book findByIsbin(@Param("isbinNo") String isbinNo);
@Query("select o from Book o where book_title like %:bookTitle%")
public List<Book> findByBookTitle(@Param("bookTitle") String bookTitle);
}
|
3e01400d17dbe9fe04afab51f5ef1d8d01a13578 | 6,494 | java | Java | spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java | moyutech/spring-cloud-netflix | 40ec6066c1e82a447314ebe0b45ca34e9e7034ce | [
"Apache-2.0"
] | 3 | 2019-10-13T05:09:22.000Z | 2019-11-05T01:43:17.000Z | spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java | moyutech/spring-cloud-netflix | 40ec6066c1e82a447314ebe0b45ca34e9e7034ce | [
"Apache-2.0"
] | null | null | null | spring-cloud-netflix-zuul/src/test/java/org/springframework/cloud/netflix/zuul/filters/post/SendErrorFilterIntegrationTests.java | moyutech/spring-cloud-netflix | 40ec6066c1e82a447314ebe0b45ca34e9e7034ce | [
"Apache-2.0"
] | null | null | null | 30.471698 | 96 | 0.768731 | 521 | /*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.netflix.zuul.filters.post;
import javax.servlet.http.HttpServletRequest;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.StaticServerList;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "zuul.routes.filtertest:/filtertest/**",
webEnvironment = RANDOM_PORT)
@DirtiesContext
public class SendErrorFilterIntegrationTests {
@Autowired
private MeterRegistry meterRegistry;
@LocalServerPort
private int port;
@Before
public void setTestRequestcontext() {
RequestContext context = new RequestContext();
RequestContext.testSetCurrentContext(context);
}
@After
public void clear() {
RequestContext.getCurrentContext().clear();
}
@Test
public void testPreFails() {
String url = "http://localhost:" + port + "/filtertest/get?failpre=true";
ResponseEntity<String> response = new TestRestTemplate().getForEntity(url,
String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertMetrics("pre");
}
private void assertMetrics(String filterType) {
Double count = meterRegistry.counter("ZUUL::EXCEPTION:" + filterType + "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b")
.count();
assertThat(count.longValue()).isEqualTo(1L);
count = meterRegistry.counter("ZUUL::EXCEPTION:null:500").count();
assertThat(count.longValue()).isEqualTo(0L);
}
@Test
public void testRouteFails() {
String url = "http://localhost:" + port + "/filtertest/get?failroute=true";
ResponseEntity<String> response = new TestRestTemplate().getForEntity(url,
String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertMetrics("route");
}
@Test
public void testPostFails() {
String url = "http://localhost:" + port + "/filtertest/get?failpost=true";
ResponseEntity<String> response = new TestRestTemplate().getForEntity(url,
String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
// FIXME: 2.1.0 assertMetrics("post");
}
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableZuulProxy
@RestController
@RibbonClient(name = "filtertest", configuration = RibbonConfig.class)
@Import(NoSecurityConfiguration.class)
protected static class Config {
@RequestMapping("/get")
public String get() {
return "Hello";
}
@Bean
public ZuulFilter testPreFilter() {
return new FailureFilter() {
@Override
public String filterType() {
return PRE_TYPE;
}
};
}
@Bean
public ZuulFilter testRouteFilter() {
return new FailureFilter() {
@Override
public String filterType() {
return ROUTE_TYPE;
}
};
}
@Bean
public ZuulFilter testPostFilter() {
return new FailureFilter() {
@Override
public String filterType() {
return POST_TYPE;
}
};
}
@Bean
public MeterRegistry meterRegistry() {
return new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());
}
}
@Configuration
private static class RibbonConfig {
@LocalServerPort
private int port;
@Bean
public ServerList<Server> ribbonServerList() {
return new StaticServerList<>(new Server("localhost", this.port));
}
}
private abstract static class FailureFilter extends ZuulFilter {
@Override
public int filterOrder() {
return Integer.MIN_VALUE;
}
@Override
public boolean shouldFilter() {
HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
return request.getParameter("fail" + filterType()) != null;
}
@Override
public Object run() {
HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
if (request.getParameter("fail" + filterType()) != null) {
throw new RuntimeException("failing on purpose in " + filterType());
}
return null;
}
}
}
|
3e01404a4222bd4bdc8ca35b91783a5e5dc70ff3 | 3,637 | java | Java | 3rdPartyServices/EnterpriseServices/CollaborationTools/CollabTools-Server/src/main/java/org/societies/collabtools/api/ICollabApps.java | societies/SOCIETIES-SCE-Services | ea2ed1f6a96e253e297dd64fd5db643a0268f193 | [
"BSD-2-Clause"
] | null | null | null | 3rdPartyServices/EnterpriseServices/CollaborationTools/CollabTools-Server/src/main/java/org/societies/collabtools/api/ICollabApps.java | societies/SOCIETIES-SCE-Services | ea2ed1f6a96e253e297dd64fd5db643a0268f193 | [
"BSD-2-Clause"
] | null | null | null | 3rdPartyServices/EnterpriseServices/CollaborationTools/CollabTools-Server/src/main/java/org/societies/collabtools/api/ICollabApps.java | societies/SOCIETIES-SCE-Services | ea2ed1f6a96e253e297dd64fd5db643a0268f193 | [
"BSD-2-Clause"
] | null | null | null | 46.628205 | 131 | 0.749519 | 522 | /**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.collabtools.api;
import java.util.Observer;
/**
* Interface for Collaborative Applications Manager
*
* @author Chris Lima
*
*/
public interface ICollabApps {
/**
* @return Collaborative applications integrated
*/
public abstract AbstractCollabAppConnector[] getCollabAppConnectors();
/**
* Send invitation to members of a session
* @param member Individual to invite
* @param collabApps Collaborative applications to send the action
* @param sessionName Collaborative session name
* @param string
*/
public abstract void sendInvite(String member, String[] collabApps, String sessionName, String string);
/**
* Remove member from a session
* @param member Individual to kick
* @param collabApps Collaborative applications to send the action
* @param sessionName Collaborative session name
*/
public abstract void sendKick(String member, String[] collabApps, String sessionName);
/**
* Join event to trigger some action
*
* @param member Participant
* @param collabApps Collaborative applications to send the action
* @param sessionName Collaborative session name
*/
public abstract void joinEvent(String member, String collabApp, String sessionName);
/**
* Leave event to trigger some action
*
* @param member Participant
* @param collabApps Collaborative applications to send the action
* @param sessionName Collaborative session name
*/
public abstract void leaveEvent(String member, String collabApps, String sessionName);
}
|
3e0140b5bc1d552c42b973c1f4fdc10d8aa31ebd | 1,738 | java | Java | src/test/java/com/faforever/client/builders/MapVersionReviewBeanBuilder.java | micheljung/faf-client-2.0 | 470c019169f5b2e4321d342032a6cfd30d1f3e13 | [
"MIT"
] | 161 | 2016-06-06T16:00:33.000Z | 2022-03-19T20:11:05.000Z | src/test/java/com/faforever/client/builders/MapVersionReviewBeanBuilder.java | micheljung/faf-client-2.0 | 470c019169f5b2e4321d342032a6cfd30d1f3e13 | [
"MIT"
] | 2,217 | 2016-05-27T18:21:49.000Z | 2022-03-31T12:08:14.000Z | src/test/java/com/faforever/client/builders/MapVersionReviewBeanBuilder.java | micheljung/faf-client-2.0 | 470c019169f5b2e4321d342032a6cfd30d1f3e13 | [
"MIT"
] | 127 | 2016-06-13T22:52:19.000Z | 2022-03-02T17:47:25.000Z | 25.940299 | 87 | 0.7687 | 523 | package com.faforever.client.builders;
import com.faforever.client.domain.MapVersionBean;
import com.faforever.client.domain.MapVersionReviewBean;
import com.faforever.client.domain.PlayerBean;
import java.time.OffsetDateTime;
public class MapVersionReviewBeanBuilder {
public static MapVersionReviewBeanBuilder create() {
return new MapVersionReviewBeanBuilder();
}
private final MapVersionReviewBean mapVersionReviewBean = new MapVersionReviewBean();
public MapVersionReviewBeanBuilder defaultValues() {
mapVersion(MapVersionBeanBuilder.create().defaultValues().get());
text("test");
player(PlayerBeanBuilder.create().defaultValues().get());
score(0);
id(null);
return this;
}
public MapVersionReviewBeanBuilder mapVersion(MapVersionBean mapVersion) {
mapVersionReviewBean.setMapVersion(mapVersion);
return this;
}
public MapVersionReviewBeanBuilder text(String text) {
mapVersionReviewBean.setText(text);
return this;
}
public MapVersionReviewBeanBuilder player(PlayerBean player) {
mapVersionReviewBean.setPlayer(player);
return this;
}
public MapVersionReviewBeanBuilder score(int score) {
mapVersionReviewBean.setScore(score);
return this;
}
public MapVersionReviewBeanBuilder id(Integer id) {
mapVersionReviewBean.setId(id);
return this;
}
public MapVersionReviewBeanBuilder createTime(OffsetDateTime createTime) {
mapVersionReviewBean.setCreateTime(createTime);
return this;
}
public MapVersionReviewBeanBuilder updateTime(OffsetDateTime updateTime) {
mapVersionReviewBean.setUpdateTime(updateTime);
return this;
}
public MapVersionReviewBean get() {
return mapVersionReviewBean;
}
}
|
3e01411028b06b0c1842f373511e7ef513b0bae0 | 2,371 | java | Java | src/main/java/com/yanxin/common/controller/UserAdminController.java | ndsc-iot/jcbase | a1e98274a220029e135d934054079e099195663a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/yanxin/common/controller/UserAdminController.java | ndsc-iot/jcbase | a1e98274a220029e135d934054079e099195663a | [
"Apache-2.0"
] | 1 | 2019-04-11T16:16:40.000Z | 2019-04-11T16:16:40.000Z | src/main/java/com/yanxin/common/controller/UserAdminController.java | howdypl/jcbase | e1d1d07ac751fc6e3c56070469ba21cfef14c189 | [
"Apache-2.0"
] | null | null | null | 26.943182 | 224 | 0.682834 | 524 | /**
*
*/
package com.yanxin.common.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yanxin.common.model.User;
/**
* @author Cheng Guozhen
*
*/
public class UserAdminController extends Controller {
public void index() {
String sqlString = "SELECT `user`.id, user_name, `password`,phone, actor, last_login,`user`.create_time, valid,op_name FROM `user`,operation_class WHERE `user`.actor = 2 AND `user`.operation_class_id = operation_class.id "
+ " UNION ALL "
+ "SELECT `user`.id, user_name, `password`,phone,actor, last_login,`user`.create_time,valid,NULL op_name FROM `user` WHERE `user`.actor <> 2";
List<Record> userInfoList = new ArrayList<Record>();
userInfoList = Db.find(sqlString);
//List<Record> sensorDataList = Db.paginate(1, 10, select, sqlExcepionString).getList();
setAttr("userInfoList", userInfoList);
render("userdata.jsp");
}
public void update() {
User user = getBean(User.class, "user");
if(null != user){
Record targetUser = Db.findById("user", user.getId());
if(null != targetUser){
targetUser.set("user_name", user.getUserName());
targetUser.set("phone", user.getPhone());
Db.save("user", targetUser);
}
}
}
public void updateWithAjax() {
boolean result = true;
int id = getParaToInt("userId");
String userName = getPara("userName");
String phoneString = getPara("phone");
result = User.dao.findById(id).set("user_name", userName).set("phone", phoneString).update();
//System.out.println("result="+result);
setAttr("result", result);
renderJson();
}
public void deleteUser(){
boolean result;
int id = getParaToInt("userid");
System.out.println("userid="+id);
result = Db.deleteById("user", id);
setAttr("result", result);
renderJson();
}
public void checkUser(){
String usernameString = getPara("username");
System.out.println("usernameString="+usernameString);
if(null != usernameString){
Record tempRecord = Db.findFirst("select * from user where user_name=?", usernameString);
if (null != tempRecord) {
setAttr("hasExisting",1);
}else {
setAttr("hasExisting",0);
}
renderJson();
}
}
}
|
3e0141136bdfdd2f7c720898fe5070b10f42e277 | 5,250 | java | Java | code/java/SecuritizedDerivativesAPIforDigitalPortals/v2/src/main/java/com/factset/sdk/SecuritizedDerivativesAPIforDigitalPortals/models/InlineResponse2007DataBarrierTypeConditions.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 6 | 2022-02-07T16:34:18.000Z | 2022-03-30T08:04:57.000Z | code/java/SecuritizedDerivativesAPIforDigitalPortals/v2/src/main/java/com/factset/sdk/SecuritizedDerivativesAPIforDigitalPortals/models/InlineResponse2007DataBarrierTypeConditions.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 2 | 2022-02-07T05:25:57.000Z | 2022-03-07T14:18:04.000Z | code/java/SecuritizedDerivativesAPIforDigitalPortals/v2/src/main/java/com/factset/sdk/SecuritizedDerivativesAPIforDigitalPortals/models/InlineResponse2007DataBarrierTypeConditions.java | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | null | null | null | 33.227848 | 142 | 0.773905 | 525 | /*
* Prime Developer Trial
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.factset.sdk.SecuritizedDerivativesAPIforDigitalPortals.models;
import java.util.Objects;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import com.factset.sdk.SecuritizedDerivativesAPIforDigitalPortals.models.InlineResponse2007DataBarrierType;
import com.factset.sdk.SecuritizedDerivativesAPIforDigitalPortals.models.InlineResponse2007DataConditions;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.factset.sdk.SecuritizedDerivativesAPIforDigitalPortals.JSON;
/**
* InlineResponse2007DataBarrierTypeConditions
*/
@JsonPropertyOrder({
InlineResponse2007DataBarrierTypeConditions.JSON_PROPERTY_BARRIER_TYPE,
InlineResponse2007DataBarrierTypeConditions.JSON_PROPERTY_CONDITIONS
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class InlineResponse2007DataBarrierTypeConditions implements Serializable {
private static final long serialVersionUID = 1L;
public static final String JSON_PROPERTY_BARRIER_TYPE = "barrierType";
private InlineResponse2007DataBarrierType barrierType;
public static final String JSON_PROPERTY_CONDITIONS = "conditions";
private java.util.List<InlineResponse2007DataConditions> conditions = null;
public InlineResponse2007DataBarrierTypeConditions() {
}
public InlineResponse2007DataBarrierTypeConditions barrierType(InlineResponse2007DataBarrierType barrierType) {
this.barrierType = barrierType;
return this;
}
/**
* Get barrierType
* @return barrierType
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_BARRIER_TYPE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public InlineResponse2007DataBarrierType getBarrierType() {
return barrierType;
}
@JsonProperty(JSON_PROPERTY_BARRIER_TYPE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setBarrierType(InlineResponse2007DataBarrierType barrierType) {
this.barrierType = barrierType;
}
public InlineResponse2007DataBarrierTypeConditions conditions(java.util.List<InlineResponse2007DataConditions> conditions) {
this.conditions = conditions;
return this;
}
public InlineResponse2007DataBarrierTypeConditions addConditionsItem(InlineResponse2007DataConditions conditionsItem) {
if (this.conditions == null) {
this.conditions = new java.util.ArrayList<>();
}
this.conditions.add(conditionsItem);
return this;
}
/**
* Set of conditions associated with the given barrier type.
* @return conditions
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Set of conditions associated with the given barrier type.")
@JsonProperty(JSON_PROPERTY_CONDITIONS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public java.util.List<InlineResponse2007DataConditions> getConditions() {
return conditions;
}
@JsonProperty(JSON_PROPERTY_CONDITIONS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setConditions(java.util.List<InlineResponse2007DataConditions> conditions) {
this.conditions = conditions;
}
/**
* Return true if this inline_response_200_7_data_barrierTypeConditions object is equal to o.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InlineResponse2007DataBarrierTypeConditions inlineResponse2007DataBarrierTypeConditions = (InlineResponse2007DataBarrierTypeConditions) o;
return Objects.equals(this.barrierType, inlineResponse2007DataBarrierTypeConditions.barrierType) &&
Objects.equals(this.conditions, inlineResponse2007DataBarrierTypeConditions.conditions);
}
@Override
public int hashCode() {
return Objects.hash(barrierType, conditions);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InlineResponse2007DataBarrierTypeConditions {\n");
sb.append(" barrierType: ").append(toIndentedString(barrierType)).append("\n");
sb.append(" conditions: ").append(toIndentedString(conditions)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e0141f21c2d56fe80de5c277cec8bb12630ae82 | 659 | java | Java | src/back_end/model/command/SetPenSizeCommand.java | matthewfaw/slogo_team15 | df29555a06362bc54772e0baec52a1fbbb562035 | [
"MIT"
] | null | null | null | src/back_end/model/command/SetPenSizeCommand.java | matthewfaw/slogo_team15 | df29555a06362bc54772e0baec52a1fbbb562035 | [
"MIT"
] | null | null | null | src/back_end/model/command/SetPenSizeCommand.java | matthewfaw/slogo_team15 | df29555a06362bc54772e0baec52a1fbbb562035 | [
"MIT"
] | null | null | null | 28.652174 | 105 | 0.810319 | 526 | package back_end.model.command;
import back_end.model.exception.InvalidNodeUsageException;
import back_end.model.node.IReadableInput;
import back_end.model.robot.IRobot;
import back_end.model.states.IModifiableEnvironmentState;
public class SetPenSizeCommand implements ICommand, ICommandTurtle {
private IRobot myRobot;
public SetPenSizeCommand(IRobot aRobot, IModifiableEnvironmentState aEnvironment, String aCommandName) {
myRobot = aRobot;
}
@Override
public double eval(IReadableInput... aList) throws InvalidNodeUsageException {
myRobot.getPenInformation().setPenThickness((int) aList[0].getValue());
return aList[0].getValue();
}
}
|
3e01436c7e4fd4d2c41de628f676cd018a617485 | 400 | java | Java | src/main/java/com/wbz/wbzapi/entity/Item.java | prestigeprog/wbz-api | 6ed6b57d21d2f9766bb0e95d54f169381533aa4f | [
"MIT"
] | 1 | 2021-01-11T17:36:52.000Z | 2021-01-11T17:36:52.000Z | src/main/java/com/wbz/wbzapi/entity/Item.java | prestigeprog/wbz-api | 6ed6b57d21d2f9766bb0e95d54f169381533aa4f | [
"MIT"
] | 22 | 2021-02-15T17:33:15.000Z | 2021-05-20T18:30:42.000Z | src/main/java/com/wbz/wbzapi/entity/Item.java | prestigeprog/wbz-api | 6ed6b57d21d2f9766bb0e95d54f169381533aa4f | [
"MIT"
] | 5 | 2021-02-17T08:13:31.000Z | 2021-02-20T15:34:32.000Z | 14.285714 | 54 | 0.6925 | 527 | package com.wbz.wbzapi.entity;
import lombok.*;
import javax.persistence.*;
@Getter
@Setter
@Entity
@ToString
@AllArgsConstructor
@Table(name = "item")
public class Item {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private long id;
private String name;
private String description;
private double price;
private String image;
public Item() {
}
}
|
3e0143a9c5b3c4168ee10f74aeaf9b2cb1663516 | 12,489 | java | Java | src/frames/RegisterFrame.java | Heideo/Examination-System-With-Score-Mailing | f70b9f5e06409a8accaa934e9f12a36a835a4eda | [
"MIT"
] | null | null | null | src/frames/RegisterFrame.java | Heideo/Examination-System-With-Score-Mailing | f70b9f5e06409a8accaa934e9f12a36a835a4eda | [
"MIT"
] | null | null | null | src/frames/RegisterFrame.java | Heideo/Examination-System-With-Score-Mailing | f70b9f5e06409a8accaa934e9f12a36a835a4eda | [
"MIT"
] | null | null | null | 51.395062 | 147 | 0.65874 | 528 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package frames;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
*
* @author maxyspark
*/
public class RegisterFrame extends javax.swing.JFrame {
javax.swing.JFrame F;
/**
* Creates new form loginFrame
*/
public RegisterFrame() {
initComponents();
customInit();
}
// custom constructor
public RegisterFrame(javax.swing.JFrame F) {
this.F = F;
initComponents();
customInit();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
firstName = new javax.swing.JTextField();
lastName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
emailReg = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
submitReg = new javax.swing.JButton();
passReg = new javax.swing.JPasswordField();
cancelBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridBagLayout());
jLabel1.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
jLabel1.setText("First Name");
jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
firstName.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
firstName.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
firstName.setMinimumSize(new java.awt.Dimension(28, 38));
firstName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
firstNameActionPerformed(evt);
}
});
lastName.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
lastName.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
jLabel2.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
jLabel2.setText("Last Name");
jLabel2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
emailReg.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
emailReg.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
jLabel3.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
jLabel3.setText("Email");
jLabel3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
jLabel4.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
jLabel4.setText("Password");
jLabel4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
submitReg.setFont(new java.awt.Font("Comic Sans MS", 1, 18)); // NOI18N
submitReg.setText("Submit");
submitReg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitRegActionPerformed(evt);
}
});
passReg.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
passReg.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 3, true));
cancelBtn.setFont(new java.awt.Font("Comic Sans MS", 1, 18)); // NOI18N
cancelBtn.setText("Cancel");
cancelBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(70, 70, 70)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lastName, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(131, 131, 131)
.addComponent(firstName, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(131, 131, 131)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(emailReg, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addComponent(passReg))))
.addContainerGap(65, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(cancelBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(submitReg, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(311, 311, 311))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(108, 108, 108)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(firstName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lastName, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE)
.addComponent(emailReg))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(passReg, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addComponent(submitReg, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(cancelBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(108, 108, 108))
);
getContentPane().add(jPanel1, new java.awt.GridBagConstraints());
pack();
}// </editor-fold>//GEN-END:initComponents
private void firstNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_firstNameActionPerformed
}//GEN-LAST:event_firstNameActionPerformed
private void submitRegActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitRegActionPerformed
String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
String FN,LN,email,pass;
FN = firstName.getText();
LN = lastName.getText();
email = emailReg.getText();
pass = passReg.getText();
Connection c = null;
Statement s;
if(email.matches(EMAIL_REGEX) && !FN.equals("") && !LN.equals("") && !pass.equals("")) {
try {
setVisible(false);
F.setVisible(true);
Class.forName("com.mysql.jdbc.Driver");
c=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ExamManagement","root","");
s=c.createStatement();
s.executeUpdate("insert into STUDENT(FIRSTNAME,LASTNAME,EMAIL,PASSWORD) values('"+FN+"','"+LN+"','"+email+"','"+pass+"')");
JOptionPane.showMessageDialog(this, "Registration Successful","Message",JOptionPane.INFORMATION_MESSAGE);
} catch(Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(),"Exception",JOptionPane.ERROR_MESSAGE);
} finally {
try{c.close();}catch(Exception e){}
}
} else {
JOptionPane.showMessageDialog(this, "Please Check The Entered Details Again","Registration Error",JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_submitRegActionPerformed
private void cancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtnActionPerformed
setVisible(false);
F.setVisible(true);
}//GEN-LAST:event_cancelBtnActionPerformed
//custom
final public void customInit() {
jLabel1.setHorizontalAlignment(JLabel.CENTER);
jLabel2.setHorizontalAlignment(JLabel.CENTER);
jLabel3.setHorizontalAlignment(JLabel.CENTER);
jLabel4.setHorizontalAlignment(JLabel.CENTER);
firstName.setHorizontalAlignment(JLabel.CENTER);
lastName.setHorizontalAlignment(JLabel.CENTER);
emailReg.setHorizontalAlignment(JLabel.CENTER);
passReg.setHorizontalAlignment(JLabel.CENTER);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelBtn;
private javax.swing.JTextField emailReg;
private javax.swing.JTextField firstName;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField lastName;
private javax.swing.JPasswordField passReg;
private javax.swing.JButton submitReg;
// End of variables declaration//GEN-END:variables
}
|
3e01448966b231731e65c7b427467dedfc9925e5 | 5,111 | java | Java | #633 - Client/src/Class251_Sub2.java | CSS-Lletya/open633 | e512f3a8af1581427539bde4c535e6c117851dac | [
"Apache-2.0"
] | null | null | null | #633 - Client/src/Class251_Sub2.java | CSS-Lletya/open633 | e512f3a8af1581427539bde4c535e6c117851dac | [
"Apache-2.0"
] | null | null | null | #633 - Client/src/Class251_Sub2.java | CSS-Lletya/open633 | e512f3a8af1581427539bde4c535e6c117851dac | [
"Apache-2.0"
] | null | null | null | 28.237569 | 99 | 0.644492 | 529 | /* Class251_Sub2 - Decompiled by JODE
* Visit http://jode.sourceforge.net/
*/
import jaclib.memory.Buffer;
import jaclib.memory.Source;
final class Class251_Sub2 extends Class251 implements Interface3 {
static int anInt5427;
static int anInt5428;
static Class240 aClass240_5429;
static int anInt5430;
static int anInt5431;
static int anInt5432 = 0;
static boolean aBool5433 = false;
static int anInt5434;
static int anInt5435;
static int anInt5436;
private byte aByte5437;
static int anInt5438;
static boolean aBool5439;
static int anInt5440;
public final int method48(boolean bool) {
try {
anInt5440++;
if (bool != true)
aBool5433 = false;
return super.method48(true);
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "dea.A(" + bool + ')');
}
}
Class251_Sub2(Class163_Sub2_Sub1 class163_sub2_sub1, boolean bool) {
super(class163_sub2_sub1, 34962, bool);
}
public final boolean method9(int i) {
try {
if (i != -17151)
method2382(false, null);
anInt5428++;
return super
.method1601(
(byte) 100,
(((Class163_Sub2_Sub1) (((Class251) this).aClass163_Sub2_Sub1_3465)).aMapBuffer8671));
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "dea.D(" + i + ')');
}
}
static final void method2379(int i,
Actor class376_sub7_sub5_sub5, int i_0_) {
try {
if ((((Actor) class376_sub7_sub5_sub5).anIntArray10272) != null) {
int i_1_ = (((Actor) class376_sub7_sub5_sub5).anIntArray10272[1 + i]);
if ((((Actor) class376_sub7_sub5_sub5).anInt10352) != i_1_) {
((Actor) class376_sub7_sub5_sub5).anInt10305 = 0;
((Actor) class376_sub7_sub5_sub5).anInt10282 = 0;
((Actor) class376_sub7_sub5_sub5).anInt10326 = 0;
((Actor) class376_sub7_sub5_sub5).anInt10283 = 1;
((Actor) class376_sub7_sub5_sub5).anInt10368 = (((Actor) class376_sub7_sub5_sub5).anInt10375);
((Actor) class376_sub7_sub5_sub5).anInt10352 = i_1_;
if ((((Actor) class376_sub7_sub5_sub5).anInt10352) != -1)
Class268.method1690(
-701644944,
(((Actor) class376_sub7_sub5_sub5).anInt10326),
class376_sub7_sub5_sub5,
(Class108_Sub23.aClass198_7760
.method1284(
(((Actor) class376_sub7_sub5_sub5).anInt10352),
(byte) -43)));
}
}
if (i_0_ != -1)
method2379(121, null, -48);
anInt5427++;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("dea.Q(" + i + ','
+ (class376_sub7_sub5_sub5 != null ? "{...}" : "null")
+ ',' + i_0_ + ')'));
}
}
public static void method2380(int i) {
try {
if (i != 30386)
anInt5432 = -48;
aClass240_5429 = null;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "dea.P(" + i + ')');
}
}
public final void method8(int i) {
try {
if (i != 5342)
aByte5437 = (byte) 62;
super.method8(i);
anInt5435++;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "dea.E(" + i + ')');
}
}
public final boolean method10(int i, int i_2_, int i_3_) {
try {
anInt5430++;
aByte5437 = (byte) i_2_;
int i_4_ = 88 / ((-67 - i) / 56);
super.method17(i_3_, (byte) 55);
return true;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("dea.B(" + i + ','
+ i_2_ + ',' + i_3_ + ')'));
}
}
public final boolean method11(Source source, byte i, int i_5_, int i_6_) {
try {
int i_7_ = 110 % ((i - 22) / 49);
aByte5437 = (byte) i_6_;
anInt5438++;
super.method1604(source, i_5_, 2);
return true;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("dea.C("
+ (source != null ? "{...}" : "null") + ',' + i + ','
+ i_5_ + ',' + i_6_ + ')'));
}
}
final int method2381(int i) {
try {
if (i != -1611)
method2381(117);
anInt5436++;
return aByte5437;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "dea.G(" + i + ')');
}
}
static final String method2382(boolean bool, String string) {
try {
if (bool != false)
aClass240_5429 = null;
anInt5431++;
String string_8_ = Class42.method385(45,
Class11_Sub30.method2728(57, string));
if (string_8_ == null)
string_8_ = "";
return string_8_;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("dea.H(" + bool + ','
+ (string != null ? "{...}" : "null") + ')'));
}
}
public final Buffer method12(int i, boolean bool) {
try {
if (i != -5419)
return null;
anInt5434++;
return super
.method1603(
bool,
(((Class163_Sub2_Sub1) (((Class251) this).aClass163_Sub2_Sub1_3465)).aMapBuffer8671),
(byte) -24);
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "dea.F(" + i + ','
+ bool + ')');
}
}
static {
aClass240_5429 = new Class240();
aBool5439 = true;
}
}
|
3e0144e53ef7920e98c14695c27c344a28260b4d | 1,785 | java | Java | src/main/java/slimeknights/mantle/recipe/helper/FluidTagEmptyCondition.java | ProjectET/Mantle | 8682dd5f90ad8f599cddba2209522b5edd333735 | [
"MIT"
] | 1 | 2022-03-03T02:12:54.000Z | 2022-03-03T02:12:54.000Z | src/main/java/slimeknights/mantle/recipe/helper/FluidTagEmptyCondition.java | ProjectET/Mantle | 8682dd5f90ad8f599cddba2209522b5edd333735 | [
"MIT"
] | null | null | null | src/main/java/slimeknights/mantle/recipe/helper/FluidTagEmptyCondition.java | ProjectET/Mantle | 8682dd5f90ad8f599cddba2209522b5edd333735 | [
"MIT"
] | 2 | 2022-02-25T16:41:21.000Z | 2022-03-18T23:37:03.000Z | 36.428571 | 169 | 0.744538 | 530 | //package slimeknights.mantle.recipe.helper;
//
//import com.google.gson.JsonObject;
//import lombok.RequiredArgsConstructor;
//import net.fabricmc.fabric.api.resource.conditions.v1.ConditionJsonProvider;
//import net.fabricmc.fabric.api.resource.conditions.v1.ResourceConditions;
//import net.minecraft.core.Registry;
//import net.minecraft.resources.ResourceLocation;
//import net.minecraft.tags.SerializationTags;
//import net.minecraft.tags.Tag;
//import net.minecraft.world.level.material.Fluid;
//import net.minecraftforge.common.crafting.conditions.ICondition;
//import net.minecraftforge.common.crafting.conditions.IConditionSerializer;
//import slimeknights.mantle.Mantle;
//import slimeknights.mantle.util.JsonHelper;
//
///** Condition that checks when a fluid tag is empty. Same as {@link net.minecraftforge.common.crafting.conditions.TagEmptyCondition} but for fluids instead of items */
//@RequiredArgsConstructor
//public class FluidTagEmptyCondition implements ConditionJsonProvider {
// private static final ResourceLocation NAME = Mantle.getResource("fluid_tag_empty");
// private final ResourceLocation name;
//
// public FluidTagEmptyCondition(String domain, String name) {
// this(new ResourceLocation(domain, name));
// }
//
// @Override
// public ResourceLocation getConditionId() {
// return NAME;
// }
//
// @Override
// public boolean test() {
// Tag<Fluid> tag = SerializationTags.getInstance().getOrEmpty(Registry.FLUID_REGISTRY).getTag(name);
// return tag == null || tag.getValues().isEmpty();
// }
//
// @Override
// public void writeParameters(JsonObject json) {
// json.addProperty("tag", name.toString());
// }
//
// @Override
// public String toString()
// {
// return "fluid_tag_empty(\"" + name + "\")";
// }
//}
|
3e0145c3d8f0aad1d88c31558b1c5e5286894035 | 906 | java | Java | runtime/src/main/java/org/corfudb/protocols/wireprotocol/HandshakeMsg.java | xcchang/CorfuDB | 325613b140f23150c7f00ad8f9da4702dcdd4a5f | [
"Apache-2.0"
] | 1 | 2018-07-11T18:43:16.000Z | 2018-07-11T18:43:16.000Z | runtime/src/main/java/org/corfudb/protocols/wireprotocol/HandshakeMsg.java | xcchang/CorfuDB | 325613b140f23150c7f00ad8f9da4702dcdd4a5f | [
"Apache-2.0"
] | 5 | 2018-07-11T17:59:06.000Z | 2021-06-30T22:54:21.000Z | runtime/src/main/java/org/corfudb/protocols/wireprotocol/HandshakeMsg.java | xcchang/CorfuDB | 325613b140f23150c7f00ad8f9da4702dcdd4a5f | [
"Apache-2.0"
] | null | null | null | 23.842105 | 71 | 0.710817 | 531 | package org.corfudb.protocols.wireprotocol;
import io.netty.buffer.ByteBuf;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* Message sent to initiate handshake between client and server.
*
* Created by amartinezman on 12/11/17.
*/
@CorfuPayload
@Data
@AllArgsConstructor
public class HandshakeMsg implements ICorfuPayload<HandshakeMsg> {
private UUID clientId;
private UUID serverId;
/**
* Constructor to generate an initiating Handshake Message Payload.
*
* @param buf The buffer to deserialize.
*/
public HandshakeMsg(ByteBuf buf) {
clientId = ICorfuPayload.fromBuffer(buf, UUID.class);
serverId = ICorfuPayload.fromBuffer(buf, UUID.class);
}
@Override
public void doSerialize(ByteBuf buf) {
ICorfuPayload.serialize(buf, clientId);
ICorfuPayload.serialize(buf, serverId);
}
}
|
3e0145d009696418e4a082f1a6eb79ac1499a836 | 411 | java | Java | app/src/test/java/com/timelesssoftware/popularmovies/ExampleUnitTest.java | sickterror/PopularMovies | 64fffbca8fa5e2b1905f7a4f987277dbd82eced2 | [
"Apache-2.0"
] | null | null | null | app/src/test/java/com/timelesssoftware/popularmovies/ExampleUnitTest.java | sickterror/PopularMovies | 64fffbca8fa5e2b1905f7a4f987277dbd82eced2 | [
"Apache-2.0"
] | null | null | null | app/src/test/java/com/timelesssoftware/popularmovies/ExampleUnitTest.java | sickterror/PopularMovies | 64fffbca8fa5e2b1905f7a4f987277dbd82eced2 | [
"Apache-2.0"
] | null | null | null | 24.176471 | 80 | 0.703163 | 532 | package com.timelesssoftware.popularmovies;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit get, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} |
3e014634fa1a2f02d001ebc4e22977a5efce24cc | 1,157 | java | Java | code/design-patterns/constructor-patterns/5-prototype/src/Clone/Prototype.java | Laishuxin/blog_cs | 7bcbcbc053fc8cdf7ae3bb60787b2b1c62ab4f65 | [
"MIT"
] | null | null | null | code/design-patterns/constructor-patterns/5-prototype/src/Clone/Prototype.java | Laishuxin/blog_cs | 7bcbcbc053fc8cdf7ae3bb60787b2b1c62ab4f65 | [
"MIT"
] | null | null | null | code/design-patterns/constructor-patterns/5-prototype/src/Clone/Prototype.java | Laishuxin/blog_cs | 7bcbcbc053fc8cdf7ae3bb60787b2b1c62ab4f65 | [
"MIT"
] | null | null | null | 19.610169 | 58 | 0.501296 | 533 | package Clone;
/**
* Project 1-singleton
* File null.java
*
* @author LaiShuXin
* @time 2021-07-05 21:31
*/
public class Prototype implements Cloneable {
private String name;
private int id;
Prototype p;
public Prototype(String name, int id) {
this.name = name;
this.id = id;
}
public Prototype(String name, int id, Prototype p) {
this.name = name;
this.id = id;
this.p = p;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
protected Prototype clone() {
Prototype prototype = null;
try {
Object obj = super.clone();
prototype = (Prototype)obj;
} catch (Exception e) {
e.printStackTrace();
}
return prototype;
}
@Override
public String toString() {
return "name: " + this.name + ", id: " + this.id;
}
}
|
3e01469356296baabf023b766d21876d6d492fda | 2,567 | java | Java | mockito-study/src/main/java/com/edgar/core/init/AppInitializer.java | edgar615/javase-study | 06b0d7fa58e1611ce27267b3efb30ebfe2e43c35 | [
"Apache-2.0"
] | 3 | 2016-05-12T21:42:56.000Z | 2020-05-27T07:52:14.000Z | mockito-study/src/main/java/com/edgar/core/init/AppInitializer.java | edgar615/javase-study | 06b0d7fa58e1611ce27267b3efb30ebfe2e43c35 | [
"Apache-2.0"
] | null | null | null | mockito-study/src/main/java/com/edgar/core/init/AppInitializer.java | edgar615/javase-study | 06b0d7fa58e1611ce27267b3efb30ebfe2e43c35 | [
"Apache-2.0"
] | 2 | 2019-12-25T14:14:35.000Z | 2020-05-27T07:52:15.000Z | 34.689189 | 95 | 0.632645 | 534 | package com.edgar.core.init;
import com.edgar.core.util.ExceptionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 系统初始化类,在Spring的bean加载完毕后执行.
*
* @author Edgar
* @version 1.0
*/
@Service
public class AppInitializer implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(AppInitializer.class);
private static final ExecutorService EXEC = Executors.newCachedThreadPool();
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
LOGGER.info("{} resource initializing", context);
Map<String, Initialization> map = context.getBeansOfType(Initialization.class);
Collection<Initialization> initializations = Collections.unmodifiableCollection(map
.values());
final CountDownLatch LATCH = new CountDownLatch(initializations.size());
init(initializations, LATCH);
try {
LATCH.await();
} catch (InterruptedException e) {
throw ExceptionFactory.appError();
}
LOGGER.info("{}resource initialized", context);
}
/**
* 使用线程调用初始化类
*
* @param initializations 初始化类的集合
* @param latch 闭锁
*/
private void init(Collection<Initialization> initializations, final CountDownLatch latch) {
for (final Initialization INITIAL : initializations) {
EXEC.submit(new Runnable() {
@Override
public void run() {
try {
INITIAL.init();
// 如果初始化启动失败,则不允许系统继续运行
latch.countDown();
} catch (Exception e) {
LOGGER.error("System start failed, stop initialize! class:{} reson:{}",
INITIAL.getClass().getSimpleName(),
e.getMessage(), e);
Thread.currentThread().interrupt();
}
}
});
}
}
}
|
3e01472d6f6450188a0971d4c88ef29f107e6dc1 | 1,809 | java | Java | aws-publisher/src/main/java/com/coderstower/socialmediapubisher/springpublisher/main/aws/repository/post/PostAWSRepository.java | estigma88/social-media-publisher | c665e64b870efad8fdc1fd88812163f9cb7d2724 | [
"MIT"
] | 2 | 2020-10-05T09:37:17.000Z | 2021-06-06T03:24:33.000Z | aws-publisher/src/main/java/com/coderstower/socialmediapubisher/springpublisher/main/aws/repository/post/PostAWSRepository.java | estigma88/social-media-publisher | c665e64b870efad8fdc1fd88812163f9cb7d2724 | [
"MIT"
] | null | null | null | aws-publisher/src/main/java/com/coderstower/socialmediapubisher/springpublisher/main/aws/repository/post/PostAWSRepository.java | estigma88/social-media-publisher | c665e64b870efad8fdc1fd88812163f9cb7d2724 | [
"MIT"
] | 1 | 2020-11-12T15:40:21.000Z | 2020-11-12T15:40:21.000Z | 35.470588 | 102 | 0.664456 | 535 | package com.coderstower.socialmediapubisher.springpublisher.main.aws.repository.post;
import com.coderstower.socialmediapubisher.springpublisher.abstraction.post.repository.Post;
import com.coderstower.socialmediapubisher.springpublisher.abstraction.post.repository.PostRepository;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.StreamSupport;
public class PostAWSRepository implements PostRepository {
private final PostDynamoRepository postDynamoRepository;
public PostAWSRepository(PostDynamoRepository postDynamoRepository) {
this.postDynamoRepository = postDynamoRepository;
}
@Override
public Optional<Post> getNextToPublish() {
return StreamSupport.stream(postDynamoRepository.findAll().spliterator(), false)
.min(Comparator.comparing(PostDynamo::getPublishedDate))
.map(this::convert);
}
@Override
public Post update(Post post) {
return convert(postDynamoRepository.save(convert(post)));
}
private PostDynamo convert(Post post) {
return PostDynamo.builder()
.id(post.getId())
.description(post.getDescription())
.publishedDate(post.getPublishedDate())
.name(post.getName())
.tags(post.getTags())
.url(post.getUrl())
.build();
}
private Post convert(PostDynamo postDynamo) {
return Post.builder()
.id(postDynamo.getId())
.description(postDynamo.getDescription())
.publishedDate(postDynamo.getPublishedDate())
.name(postDynamo.getName())
.tags(postDynamo.getTags())
.url(postDynamo.getUrl()).build();
}
}
|
3e014774db63f2d7689df5659f647095a5655480 | 1,506 | java | Java | core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/SdkStructuredCborFactory.java | kellertk/aws-sdk-java-v2 | 94e7bab182d3e125f723ac4c520046b72b1148ca | [
"Apache-2.0"
] | 2 | 2022-03-02T16:51:16.000Z | 2022-03-03T08:27:21.000Z | core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/SdkStructuredCborFactory.java | kellertk/aws-sdk-java-v2 | 94e7bab182d3e125f723ac4c520046b72b1148ca | [
"Apache-2.0"
] | 33 | 2021-04-15T23:54:55.000Z | 2022-03-14T06:15:34.000Z | core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/SdkStructuredCborFactory.java | kellertk/aws-sdk-java-v2 | 94e7bab182d3e125f723ac4c520046b72b1148ca | [
"Apache-2.0"
] | 1 | 2020-09-17T13:37:43.000Z | 2020-09-17T13:37:43.000Z | 35.023256 | 112 | 0.775564 | 536 | /*
* Copyright 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 software.amazon.awssdk.protocols.cbor.internal;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import java.util.function.BiFunction;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
/**
* Creates generators and protocol handlers for CBOR wire format.
*/
@SdkInternalApi
public abstract class SdkStructuredCborFactory {
protected static final JsonFactory CBOR_FACTORY = new CBORFactory();
protected static final CborGeneratorSupplier CBOR_GENERATOR_SUPPLIER = SdkCborGenerator::new;
SdkStructuredCborFactory() {
}
@FunctionalInterface
protected interface CborGeneratorSupplier extends BiFunction<JsonFactory, String, StructuredJsonGenerator> {
@Override
StructuredJsonGenerator apply(JsonFactory jsonFactory, String contentType);
}
}
|
3e0147b2a3e742b7eaf99324d1273594c7293ad7 | 12,418 | java | Java | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/main/java/org/kie/workbench/common/stunner/core/graph/command/impl/SafeDeleteNodeCommand.java | Bonuseto/kie-wb-common | 421c7793ff4745d22b9af21763d8ff766f43db9b | [
"Apache-2.0"
] | null | null | null | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/main/java/org/kie/workbench/common/stunner/core/graph/command/impl/SafeDeleteNodeCommand.java | Bonuseto/kie-wb-common | 421c7793ff4745d22b9af21763d8ff766f43db9b | [
"Apache-2.0"
] | 4 | 2018-09-12T14:18:13.000Z | 2018-10-30T20:33:29.000Z | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/main/java/org/kie/workbench/common/stunner/core/graph/command/impl/SafeDeleteNodeCommand.java | Bonuseto/kie-wb-common | 421c7793ff4745d22b9af21763d8ff766f43db9b | [
"Apache-2.0"
] | null | null | null | 43.268293 | 129 | 0.558464 | 537 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.graph.command.impl;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.jboss.errai.common.client.api.annotations.MapsTo;
import org.jboss.errai.common.client.api.annotations.NonPortable;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.kie.soup.commons.validation.PortablePreconditions;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.Graph;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.graph.content.definition.Definition;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector;
import org.kie.workbench.common.stunner.core.graph.processing.traverse.content.ChildrenTraverseProcessorImpl;
import org.kie.workbench.common.stunner.core.graph.processing.traverse.tree.TreeWalkTraverseProcessorImpl;
import org.kie.workbench.common.stunner.core.graph.util.SafeDeleteNodeProcessor;
/**
* Deletes a node taking into account its ingoing / outgoing edges and safe remove all node's children as well, if any.
*/
@Portable
public class SafeDeleteNodeCommand extends AbstractGraphCompositeCommand {
@Portable
public static final class Options {
private final boolean shortcutCandidateConnectors;
private final Set<String> exclusions;
public static Options defaults() {
return new Options(true, new HashSet<>());
}
public static Options doNotShortcutConnectors() {
return new Options(false, new HashSet<>());
}
public static Options exclude(final Set<String> ids) {
return new Options(false, ids);
}
public Options(final @MapsTo("shortcutCandidateConnectors") boolean shortcutCandidateConnectors,
final @MapsTo("exclusions") Set<String> exclusions) {
this.shortcutCandidateConnectors = shortcutCandidateConnectors;
this.exclusions = exclusions;
}
public boolean isShortcutCandidateConnectors() {
return shortcutCandidateConnectors;
}
public Set<String> getExclusions() {
return exclusions;
}
}
@NonPortable
public interface SafeDeleteNodeCommandCallback extends SafeDeleteNodeProcessor.Callback {
void setEdgeTargetNode(final Node<? extends View<?>, Edge> targetNode,
final Edge<? extends ViewConnector<?>, Node> candidate);
}
private final String candidateUUID;
private final Options options;
private transient Node<?, Edge> node;
private transient Optional<SafeDeleteNodeCommandCallback> safeDeleteCallback;
public SafeDeleteNodeCommand(final @MapsTo("candidateUUID") String candidateUUID,
final @MapsTo("options") Options options) {
this.candidateUUID = PortablePreconditions.checkNotNull("candidateUUID",
candidateUUID);
this.options = PortablePreconditions.checkNotNull("options",
options);
this.safeDeleteCallback = Optional.empty();
}
public SafeDeleteNodeCommand(final Node<?, Edge> node) {
this(node,
Options.defaults());
this.node = node;
}
public SafeDeleteNodeCommand(final Node<?, Edge> node,
final Options options) {
this(node.getUUID(),
options);
this.node = node;
}
public SafeDeleteNodeCommand(final Node<?, Edge> node,
final SafeDeleteNodeCommandCallback safeDeleteCallback,
final Options options) {
this(node,
options);
this.safeDeleteCallback = Optional.ofNullable(safeDeleteCallback);
}
@Override
@SuppressWarnings("unchecked")
protected SafeDeleteNodeCommand initialize(final GraphCommandExecutionContext context) {
super.initialize(context);
final Graph<?, Node> graph = getGraph(context);
final Node<Definition<?>, Edge> candidate = (Node<Definition<?>, Edge>) getCandidate(context);
new SafeDeleteNodeProcessor(new ChildrenTraverseProcessorImpl(new TreeWalkTraverseProcessorImpl()),
graph,
candidate)
.run(new SafeDeleteNodeProcessor.Callback() {
private final Set<String> processedConnectors = new HashSet<String>();
@Override
public void deleteCandidateConnector(final Edge<? extends View<?>, Node> edge) {
if (!processedConnectors.contains(edge.getUUID())) {
processCandidateConnectors();
}
}
@Override
public boolean deleteConnector(final Edge<? extends View<?>, Node> edge) {
return doDeleteConnector(edge);
}
@Override
public void removeChild(final Element<?> parent,
final Node<?, Edge> candidate) {
addCommand(createRemoveChildCommand(parent, candidate));
safeDeleteCallback.ifPresent(c -> c.removeChild(parent,
candidate));
}
@Override
public void removeDock(final Node<?, Edge> parent,
final Node<?, Edge> candidate) {
addCommand(new UnDockNodeCommand(parent,
candidate));
safeDeleteCallback.ifPresent(c -> c.removeDock(parent,
candidate));
}
@Override
public void deleteCandidateNode(final Node<?, Edge> node) {
deleteNode(node);
}
@Override
public boolean deleteNode(final Node<?, Edge> node) {
if (!isElementExcluded(node)) {
addCommand(new DeregisterNodeCommand(node));
safeDeleteCallback.ifPresent(c -> c.deleteNode(node));
return true;
}
return false;
}
private void processCandidateConnectors() {
if (options.isShortcutCandidateConnectors() &&
hasSingleIncomingEdge()
.and(hasSingleOutgoingEdge())
.test(candidate)) {
final Edge<? extends ViewConnector<?>, Node> in = getViewConnector().apply(candidate.getInEdges());
final Edge<? extends ViewConnector<?>, Node> out = getViewConnector().apply(candidate.getOutEdges());
shortcut(in,
out);
} else {
Stream.concat(candidate.getInEdges().stream(),
candidate.getOutEdges().stream())
.filter(e -> e.getContent() instanceof ViewConnector)
.forEach(this::deleteConnector);
}
}
private void shortcut(final Edge<? extends ViewConnector<?>, Node> in,
final Edge<? extends ViewConnector<?>, Node> out) {
final ViewConnector<?> outContent = out.getContent();
final Node targetNode = out.getTargetNode();
addCommand(new DeleteConnectorCommand(out));
safeDeleteCallback.ifPresent(c -> c.deleteCandidateConnector(out));
addCommand(new SetConnectionTargetNodeCommand(targetNode,
in,
outContent.getTargetConnection().orElse(null)));
safeDeleteCallback.ifPresent(c -> c.setEdgeTargetNode(targetNode,
in));
processedConnectors.add(in.getUUID());
processedConnectors.add(out.getUUID());
}
private boolean doDeleteConnector(final Edge<? extends View<?>, Node> edge) {
if (!isElementExcluded(edge) && !processedConnectors.contains(edge.getUUID())) {
addCommand(new DeleteConnectorCommand(edge));
safeDeleteCallback.ifPresent(c -> c.deleteConnector(edge));
processedConnectors.add(edge.getUUID());
return true;
}
return false;
}
});
return this;
}
protected AbstractGraphCommand createRemoveChildCommand(final Element<?> parent,
final Node<?, Edge> candidate) {
return new RemoveChildrenCommand((Node<?, Edge>) parent,
candidate);
}
private boolean isElementExcluded(final Element<?> e) {
return !options.getExclusions().isEmpty() && options.getExclusions().contains(e.getUUID());
}
@Override
protected boolean delegateRulesContextToChildren() {
return true;
}
@SuppressWarnings("unchecked")
private Node<? extends Definition<?>, Edge> getCandidate(final GraphCommandExecutionContext context) {
if (null == node) {
node = checkNodeNotNull(context,
candidateUUID);
}
return (Node<View<?>, Edge>) node;
}
public Node<?, Edge> getNode() {
return node;
}
public Options getOptions() {
return options;
}
private static Predicate<Node<Definition<?>, Edge>> hasSingleIncomingEdge() {
return node -> 1 == countViewConnectors().apply(node.getInEdges());
}
private static Predicate<Node<Definition<?>, Edge>> hasSingleOutgoingEdge() {
return node -> 1 == countViewConnectors().apply(node.getOutEdges());
}
private static Function<List<Edge>, Long> countViewConnectors() {
return edges -> edges
.stream()
.filter(e -> e.getContent() instanceof ViewConnector)
.count();
}
private static Function<List<Edge>, Edge> getViewConnector() {
return edges -> edges
.stream()
.filter(e -> e.getContent() instanceof ViewConnector)
.findAny()
.get();
}
@Override
public String toString() {
return "SafeDeleteNodeCommand [candidate=" + candidateUUID + "]";
}
}
|
3e014882830cc18298fd0f0990be68356922d0f7 | 3,017 | java | Java | src/main/java/com/vadrin/primeart/services/prime/AlpertronPrimalityServiceImpl.java | gv-prashanth/prime-art | ed8840b350274bae756ecfeef86e202ace6b2d19 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/vadrin/primeart/services/prime/AlpertronPrimalityServiceImpl.java | gv-prashanth/prime-art | ed8840b350274bae756ecfeef86e202ace6b2d19 | [
"Apache-2.0"
] | 1 | 2021-03-31T19:36:38.000Z | 2021-03-31T19:36:38.000Z | src/main/java/com/vadrin/primeart/services/prime/AlpertronPrimalityServiceImpl.java | gv-prashanth/prime-art | ed8840b350274bae756ecfeef86e202ace6b2d19 | [
"Apache-2.0"
] | null | null | null | 29.578431 | 102 | 0.729201 | 538 | package com.vadrin.primeart.services.prime;
import java.math.BigInteger;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class AlpertronPrimalityServiceImpl implements PrimalityService {
private WebDriver driver;
private static final String PRIME = "PRIME";
private static final String COMPOSITE = "COMPOSITE";
private static final String UNDETERMINED = "UNDETERMINED";
@Value("${prime-art.alpertron.url}")
private String alpertronUrl;
@Value("${prime-art.drivers.chrome}")
private String chromeDriverLocation;
public void loadDriver() {
System.setProperty("webdriver.chrome.driver", chromeDriverLocation);
driver = new ChromeDriver();
driver.get(alpertronUrl);
}
public void destroyDriver() {
driver.close();
driver.quit();
}
private boolean isPrime(String input) {
try {
WebElement stop = driver.findElement(By.xpath("//*[@id=\"stop\"]"));
stop.click();
} catch (ElementNotVisibleException ex) {
}
WebElement inputBox = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"value\"]")));
inputBox.clear();
((JavascriptExecutor) driver).executeScript("arguments[0].value = arguments[1];", inputBox, input);
WebElement factor = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"factor\"]")));
factor.click();
try {
WebElement compositeResult = (new WebDriverWait(driver, 10)).until(
ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"result\"]/p[@class=\"blue\"]")));
if (compositeResult.getText().toLowerCase().contains("digits) =")) {
//return COMPOSITE;
return false;
}
} catch (TimeoutException ex) {
} catch (StaleElementReferenceException ex) {
}
try {
WebElement primeResult = (new WebDriverWait(driver, 20))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"result\"]/ul/li")));
if (primeResult.getText().toLowerCase().contains("prime")) {
//return PRIME;
return true;
} else {
//return COMPOSITE;
return false;
}
} catch (TimeoutException ex) {
//return UNDETERMINED;
return false;
}
}
@Override
public String nextPrime(String input) {
loadDriver();
BigInteger b = new BigInteger(input);
while(!isPrime(b.toString())){
b = b.add(new BigInteger("1"));
}
destroyDriver();
return b.toString();
}
}
|
3e0149a205c285429689b243fc13ed4fed4dffc6 | 32,461 | java | Java | platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java | pwielgolaski/intellij-community | fe455792c18fc0e2ee81401f3a55710521b503b3 | [
"Apache-2.0"
] | 1 | 2019-08-28T13:18:50.000Z | 2019-08-28T13:18:50.000Z | platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java | pwielgolaski/intellij-community | fe455792c18fc0e2ee81401f3a55710521b503b3 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java | pwielgolaski/intellij-community | fe455792c18fc0e2ee81401f3a55710521b503b3 | [
"Apache-2.0"
] | null | null | null | 42.157143 | 158 | 0.67099 | 539 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testFramework;
import com.intellij.CommonBundle;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.SeveritiesProvider;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.LineColumn;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.rt.execution.junit.FileComparisonFailure;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ThreeState;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TObjectHashingStrategy;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.text.ParsePosition;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.intellij.openapi.util.Pair.pair;
import static org.junit.Assert.*;
/**
* @author cdr
*/
public class ExpectedHighlightingData {
public static final String EXPECTED_DUPLICATION_MESSAGE =
"Expected duplication problem. Please remove this wrapper, if there is no such problem any more";
private static final String ERROR_MARKER = CodeInsightTestFixture.ERROR_MARKER;
private static final String WARNING_MARKER = CodeInsightTestFixture.WARNING_MARKER;
private static final String WEAK_WARNING_MARKER = CodeInsightTestFixture.WEAK_WARNING_MARKER;
private static final String INFO_MARKER = CodeInsightTestFixture.INFO_MARKER;
private static final String END_LINE_HIGHLIGHT_MARKER = CodeInsightTestFixture.END_LINE_HIGHLIGHT_MARKER;
private static final String END_LINE_WARNING_MARKER = CodeInsightTestFixture.END_LINE_WARNING_MARKER;
private static final String INJECT_MARKER = "inject";
private static final String SYMBOL_NAME_MARKER = "symbolName";
private static final String LINE_MARKER = "lineMarker";
private static final String ANY_TEXT = "*";
private static final HighlightInfoType WHATEVER =
new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, HighlighterColors.TEXT);
private static boolean isDuplicatedCheckDisabled = false;
private static int failedDuplicationChecks = 0;
public static class ExpectedHighlightingSet {
private final HighlightSeverity severity;
private final boolean endOfLine;
private final boolean enabled;
private final Set<HighlightInfo> infos;
public ExpectedHighlightingSet(@NotNull HighlightSeverity severity, boolean endOfLine, boolean enabled) {
this.severity = severity;
this.endOfLine = endOfLine;
this.enabled = enabled;
this.infos = new THashSet<>();
}
}
private final Map<String, ExpectedHighlightingSet> myHighlightingTypes = new LinkedHashMap<>();
private final Map<RangeMarker, LineMarkerInfo> myLineMarkerInfos = new THashMap<>();
private final Document myDocument;
private final PsiFile myFile;
private final String myText;
private boolean myIgnoreExtraHighlighting;
private final ResourceBundle[] myMessageBundles;
public ExpectedHighlightingData(@NotNull Document document, boolean checkWarnings, boolean checkInfos) {
this(document, checkWarnings, false, checkInfos);
}
public ExpectedHighlightingData(@NotNull Document document, boolean checkWarnings, boolean checkWeakWarnings, boolean checkInfos) {
this(document, checkWarnings, checkWeakWarnings, checkInfos, null);
}
public ExpectedHighlightingData(@NotNull Document document,
boolean checkWarnings,
boolean checkWeakWarnings,
boolean checkInfos,
@Nullable PsiFile file) {
this(document, checkWarnings, checkWeakWarnings, checkInfos, false, file);
}
public ExpectedHighlightingData(@NotNull Document document,
boolean checkWarnings,
boolean checkWeakWarnings,
boolean checkInfos,
boolean ignoreExtraHighlighting,
@Nullable PsiFile file,
ResourceBundle... messageBundles) {
this(document, file, messageBundles);
myIgnoreExtraHighlighting = ignoreExtraHighlighting;
if (checkWarnings) checkWarnings();
if (checkWeakWarnings) checkWeakWarnings();
if (checkInfos) checkInfos();
}
public ExpectedHighlightingData(@NotNull Document document, @Nullable PsiFile file, ResourceBundle... messageBundles) {
myDocument = document;
myFile = file;
myMessageBundles = messageBundles;
myText = document.getText();
registerHighlightingType(ERROR_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, false, true));
registerHighlightingType(WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, false, false));
registerHighlightingType(WEAK_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WEAK_WARNING, false, false));
registerHighlightingType(INJECT_MARKER, new ExpectedHighlightingSet(HighlightInfoType.INJECTED_FRAGMENT_SEVERITY, false, false));
registerHighlightingType(INFO_MARKER, new ExpectedHighlightingSet(HighlightSeverity.INFORMATION, false, false));
registerHighlightingType(SYMBOL_NAME_MARKER, new ExpectedHighlightingSet(HighlightInfoType.SYMBOL_TYPE_SEVERITY, false, false));
for (SeveritiesProvider provider : SeveritiesProvider.EP_NAME.getExtensionList()) {
for (HighlightInfoType type : provider.getSeveritiesHighlightInfoTypes()) {
HighlightSeverity severity = type.getSeverity(null);
registerHighlightingType(severity.getName(), new ExpectedHighlightingSet(severity, false, true));
}
}
registerHighlightingType(END_LINE_HIGHLIGHT_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, true, true));
registerHighlightingType(END_LINE_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, true, false));
}
public boolean hasLineMarkers() {
return !myLineMarkerInfos.isEmpty();
}
public void init() {
WriteCommandAction.runWriteCommandAction(null, () -> {
extractExpectedLineMarkerSet(myDocument);
extractExpectedHighlightsSet(myDocument);
refreshLineMarkers();
});
}
public void checkWarnings() {
registerHighlightingType(WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, false, true));
registerHighlightingType(END_LINE_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, true, true));
}
public void checkWeakWarnings() {
registerHighlightingType(WEAK_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WEAK_WARNING, false, true));
}
public void checkInfos() {
registerHighlightingType(INFO_MARKER, new ExpectedHighlightingSet(HighlightSeverity.INFORMATION, false, true));
registerHighlightingType(INJECT_MARKER, new ExpectedHighlightingSet(HighlightInfoType.INJECTED_FRAGMENT_SEVERITY, false, true));
}
public void checkSymbolNames() {
registerHighlightingType(SYMBOL_NAME_MARKER, new ExpectedHighlightingSet(HighlightInfoType.SYMBOL_TYPE_SEVERITY, false, true));
}
public void registerHighlightingType(@NotNull String key, @NotNull ExpectedHighlightingSet highlightingSet) {
myHighlightingTypes.put(key, highlightingSet);
}
private void refreshLineMarkers() {
for (Map.Entry<RangeMarker, LineMarkerInfo> entry : myLineMarkerInfos.entrySet()) {
RangeMarker rangeMarker = entry.getKey();
int startOffset = rangeMarker.getStartOffset();
int endOffset = rangeMarker.getEndOffset();
LineMarkerInfo value = entry.getValue();
PsiElement element = value.getElement();
assert element != null : value;
TextRange range = new TextRange(startOffset, endOffset);
String tooltip = value.getLineMarkerTooltip();
MyLineMarkerInfo markerInfo =
new MyLineMarkerInfo(element, range, value.updatePass, GutterIconRenderer.Alignment.RIGHT, tooltip);
entry.setValue(markerInfo);
}
}
private void extractExpectedLineMarkerSet(Document document) {
String text = document.getText();
String pat = ".*?((<" + LINE_MARKER + ")(?: descr=\"((?:[^\"\\\\]|\\\\\")*)\")?>)(.*)";
Pattern openingTagRx = Pattern.compile(pat, Pattern.DOTALL);
Pattern closingTagRx = Pattern.compile("(.*?)(</" + LINE_MARKER + ">)(.*)", Pattern.DOTALL);
while (true) {
Matcher opening = openingTagRx.matcher(text);
if (!opening.matches()) break;
int startOffset = opening.start(1);
String descr = opening.group(3) != null ? opening.group(3) : ANY_TEXT;
String rest = opening.group(4);
Matcher closing = closingTagRx.matcher(rest);
if (!closing.matches()) {
fail("Cannot find closing </" + LINE_MARKER + ">");
}
document.replaceString(startOffset, opening.end(1), "");
String content = closing.group(1);
int endOffset = startOffset + closing.start(3);
String endTag = closing.group(2);
document.replaceString(startOffset, endOffset, content);
endOffset -= endTag.length();
PsiElement leaf = Objects.requireNonNull(myFile.findElementAt(startOffset));
TextRange range = new TextRange(startOffset, endOffset);
String tooltip = StringUtil.unescapeStringCharacters(descr);
LineMarkerInfo<PsiElement> markerInfo =
new MyLineMarkerInfo(leaf, range, Pass.LINE_MARKERS, GutterIconRenderer.Alignment.RIGHT, tooltip);
myLineMarkerInfos.put(document.createRangeMarker(startOffset, endOffset), markerInfo);
text = document.getText();
}
}
/**
* Removes highlights (bounded with <marker>...</marker>) from test case file.
*/
private void extractExpectedHighlightsSet(Document document) {
String text = document.getText();
Set<String> markers = myHighlightingTypes.keySet();
String typesRx = "(?:" + StringUtil.join(markers, ")|(?:") + ")";
String openingTagRx = "<(" + typesRx + ")" +
"(?:\\s+descr=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\])*)\")?" +
"(?:\\s+type=\"([0-9A-Z_]+)\")?" +
"(?:\\s+foreground=\"([0-9xa-f]+)\")?" +
"(?:\\s+background=\"([0-9xa-f]+)\")?" +
"(?:\\s+effectcolor=\"([0-9xa-f]+)\")?" +
"(?:\\s+effecttype=\"([A-Z]+)\")?" +
"(?:\\s+fonttype=\"([0-9]+)\")?" +
"(?:\\s+textAttributesKey=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\])*)\")?" +
"(?:\\s+bundleMsg=\"((?:[^\"]|\\\\\"|\\\\\\\\\")*)\")?" +
"(/)?>";
Matcher matcher = Pattern.compile(openingTagRx).matcher(text);
int pos = 0;
Ref<Integer> textOffset = Ref.create(0);
while (matcher.find(pos)) {
textOffset.set(textOffset.get() + matcher.start() - pos);
pos = extractExpectedHighlight(matcher, text, document, textOffset);
}
}
private int extractExpectedHighlight(Matcher matcher, String text, Document document, Ref<Integer> textOffset) {
document.deleteString(textOffset.get(), textOffset.get() + matcher.end() - matcher.start());
int groupIdx = 1;
String marker = matcher.group(groupIdx++);
String descr = matcher.group(groupIdx++);
String typeString = matcher.group(groupIdx++);
String foregroundColor = matcher.group(groupIdx++);
String backgroundColor = matcher.group(groupIdx++);
String effectColor = matcher.group(groupIdx++);
String effectType = matcher.group(groupIdx++);
String fontType = matcher.group(groupIdx++);
String attrKey = matcher.group(groupIdx++);
String bundleMessage = matcher.group(groupIdx++);
boolean closed = matcher.group(groupIdx) != null;
if (descr == null) {
descr = ANY_TEXT; // no descr means any string by default
}
else if (descr.equals("null")) {
descr = null; // explicit "null" descr
}
if (descr != null) {
descr = descr.replaceAll("\\\\\\\\\"", "\""); // replace: \\" to ", doesn't check symbol before sequence \\"
descr = descr.replaceAll("\\\\\"", "\"");
}
HighlightInfoType type = WHATEVER;
if (typeString != null) {
try {
type = getTypeByName(typeString);
}
catch (Exception e) {
throw new RuntimeException(e);
}
if (type == null) {
fail("Wrong highlight type: " + typeString);
}
}
TextAttributes forcedAttributes = null;
if (foregroundColor != null) {
@JdkConstants.FontStyle int ft = Integer.parseInt(fontType);
forcedAttributes = new TextAttributes(
Color.decode(foregroundColor), Color.decode(backgroundColor), Color.decode(effectColor), EffectType.valueOf(effectType), ft);
}
int rangeStart = textOffset.get();
int toContinueFrom;
if (closed) {
toContinueFrom = matcher.end();
}
else {
int pos = matcher.end();
Matcher closingTagMatcher = Pattern.compile("</" + marker + ">").matcher(text);
while (true) {
if (!closingTagMatcher.find(pos)) {
toContinueFrom = pos;
break;
}
int nextTagStart = matcher.find(pos) ? matcher.start() : text.length();
if (closingTagMatcher.start() < nextTagStart) {
textOffset.set(textOffset.get() + closingTagMatcher.start() - pos);
document.deleteString(textOffset.get(), textOffset.get() + closingTagMatcher.end() - closingTagMatcher.start());
toContinueFrom = closingTagMatcher.end();
break;
}
textOffset.set(textOffset.get() + nextTagStart - pos);
pos = extractExpectedHighlight(matcher, text, document, textOffset);
}
}
ExpectedHighlightingSet expectedHighlightingSet = myHighlightingTypes.get(marker);
if (expectedHighlightingSet.enabled) {
TextAttributesKey forcedTextAttributesKey = attrKey == null ? null : TextAttributesKey.createTextAttributesKey(attrKey);
HighlightInfo.Builder builder =
HighlightInfo.newHighlightInfo(type).range(rangeStart, textOffset.get()).severity(expectedHighlightingSet.severity);
if (forcedAttributes != null) builder.textAttributes(forcedAttributes);
if (forcedTextAttributesKey != null) builder.textAttributes(forcedTextAttributesKey);
if (bundleMessage != null) {
descr = extractDescrFromBundleMessage(bundleMessage);
}
if (descr != null) {
builder.description(descr);
builder.unescapedToolTip(descr);
}
if (expectedHighlightingSet.endOfLine) builder.endOfLine();
HighlightInfo highlightInfo = builder.createUnconditionally();
expectedHighlightingSet.infos.add(highlightInfo);
}
return toContinueFrom;
}
@NotNull
private String extractDescrFromBundleMessage(String bundleMessage) {
String descr = null;
List<String> split = StringUtil.split(bundleMessage, "|");
String key = split.get(0);
List<String> keySplit = StringUtil.split(key, "#");
ResourceBundle[] bundles = myMessageBundles;
if (keySplit.size() == 2) {
key = keySplit.get(1);
bundles = new ResourceBundle[]{ResourceBundle.getBundle(keySplit.get(0))};
}
else {
assertEquals("Format for bundleMsg attribute is: [bundleName#] bundleKey [|argument]... ", 1, keySplit.size());
}
assertTrue("messageBundles must be provided for bundleMsg tags in test data", bundles.length > 0);
Object[] params = split.stream().skip(1).toArray();
for (ResourceBundle bundle : bundles) {
String message = CommonBundle.messageOrDefault(bundle, key, null, params);
if (message != null) {
if (descr != null) fail("Key " + key + " is not unique in bundles for expected highlighting data");
descr = message;
}
}
if (descr == null) fail("Can't find bundle message " + bundleMessage);
return descr;
}
protected HighlightInfoType getTypeByName(String typeString) throws Exception {
Field field = HighlightInfoType.class.getField(typeString);
return (HighlightInfoType)field.get(null);
}
public void checkLineMarkers(@NotNull Collection<? extends LineMarkerInfo> markerInfos, @NotNull String text) {
String fileName = myFile == null ? "" : myFile.getName() + ": ";
StringBuilder failMessage = new StringBuilder();
for (LineMarkerInfo info : markerInfos) {
if (!containsLineMarker(info, myLineMarkerInfos.values())) {
if (failMessage.length() > 0) failMessage.append('\n');
failMessage.append(fileName).append("extra ")
.append(rangeString(text, info.startOffset, info.endOffset))
.append(": '").append(info.getLineMarkerTooltip()).append('\'');
}
}
for (LineMarkerInfo expectedLineMarker : myLineMarkerInfos.values()) {
if (markerInfos.isEmpty() || !containsLineMarker(expectedLineMarker, markerInfos)) {
if (failMessage.length() > 0) failMessage.append('\n');
failMessage.append(fileName).append("missing ")
.append(rangeString(text, expectedLineMarker.startOffset, expectedLineMarker.endOffset))
.append(": '").append(expectedLineMarker.getLineMarkerTooltip()).append('\'');
}
}
if (failMessage.length() > 0) {
fail(failMessage.toString());
}
}
private static boolean containsLineMarker(LineMarkerInfo info, Collection<? extends LineMarkerInfo> where) {
String infoTooltip = info.getLineMarkerTooltip();
for (LineMarkerInfo markerInfo : where) {
String markerInfoTooltip;
if (markerInfo.startOffset == info.startOffset &&
markerInfo.endOffset == info.endOffset &&
(Comparing.equal(infoTooltip, markerInfoTooltip = markerInfo.getLineMarkerTooltip()) ||
ANY_TEXT.equals(markerInfoTooltip) ||
ANY_TEXT.equals(infoTooltip))) {
return true;
}
}
return false;
}
public void checkResult(Collection<HighlightInfo> infos, String text) {
checkResult(infos, text, null);
}
public void checkResult(Collection<HighlightInfo> infos, String text, @Nullable String filePath) {
StringBuilder failMessage = new StringBuilder();
Set<HighlightInfo> expectedFound = new THashSet<>(new TObjectHashingStrategy<HighlightInfo>() {
@Override
public int computeHashCode(HighlightInfo object) {
return object.hashCode();
}
@Override
public boolean equals(HighlightInfo o1, HighlightInfo o2) {
return haveSamePresentation(o1, o2, true);
}
});
if (!myIgnoreExtraHighlighting) {
for (HighlightInfo info : reverseCollection(infos)) {
ThreeState state = expectedInfosContainsInfo(info);
if (state == ThreeState.NO) {
reportProblem(failMessage, text, info, "extra ");
failMessage.append(" [").append(info.type).append(']');
}
else if (state == ThreeState.YES) {
if (expectedFound.contains(info)) {
if (isDuplicatedCheckDisabled) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
failedDuplicationChecks++;
}
else {
reportProblem(failMessage, text, info, "duplicated ");
}
}
expectedFound.add(info);
}
}
}
Collection<ExpectedHighlightingSet> expectedHighlights = myHighlightingTypes.values();
for (ExpectedHighlightingSet highlightingSet : reverseCollection(expectedHighlights)) {
Set<HighlightInfo> expInfos = highlightingSet.infos;
for (HighlightInfo expectedInfo : expInfos) {
if (!infosContainsExpectedInfo(infos, expectedInfo) && highlightingSet.enabled) {
reportProblem(failMessage, text, expectedInfo, "missing ");
}
}
}
if (failMessage.length() > 0) {
if (filePath == null && myFile != null) {
VirtualFile file = myFile.getVirtualFile();
if (file != null) {
filePath = file.getUserData(VfsTestUtil.TEST_DATA_FILE_PATH);
}
}
failMessage.append('\n');
compareTexts(infos, text, failMessage.toString(), filePath);
}
}
private void reportProblem(@NotNull StringBuilder failMessage,
@NotNull String text,
@NotNull HighlightInfo info,
@NotNull String messageType) {
String fileName = myFile == null ? "" : myFile.getName() + ": ";
int startOffset = info.startOffset;
int endOffset = info.endOffset;
String s = text.substring(startOffset, endOffset);
String desc = info.getDescription();
if (failMessage.length() > 0) {
failMessage.append('\n');
}
failMessage.append(fileName).append(messageType)
.append(rangeString(text, startOffset, endOffset))
.append(": '").append(s).append('\'');
if (desc != null) {
failMessage.append(" (").append(desc).append(')');
}
}
private static <T> List<T> reverseCollection(Collection<T> infos) {
return ContainerUtil.reverse(infos instanceof List ? (List<T>)infos : new ArrayList<>(infos));
}
private void compareTexts(Collection<HighlightInfo> infos, String text, String failMessage, @Nullable String filePath) {
String actual = composeText(myHighlightingTypes, infos, text, myMessageBundles);
if (filePath != null && !myText.equals(actual)) {
// uncomment to overwrite, don't forget to revert on commit!
//VfsTestUtil.overwriteTestData(filePath, actual);
//return;
throw new FileComparisonFailure(failMessage, myText, actual, filePath);
}
assertEquals(failMessage + "\n", myText, actual);
fail(failMessage);
}
private static String findTag(Map<String, ExpectedHighlightingSet> types, HighlightInfo info) {
Map.Entry<String, ExpectedHighlightingSet> entry = ContainerUtil.find(
types.entrySet(),
e -> e.getValue().enabled && e.getValue().severity == info.getSeverity() && e.getValue().endOfLine == info.isAfterEndOfLine());
return entry != null ? entry.getKey() : null;
}
@NotNull
public static String composeText(@NotNull Map<String, ExpectedHighlightingSet> types,
@NotNull Collection<HighlightInfo> infos,
@NotNull String text,
@NotNull ResourceBundle... messageBundles) {
// filter highlighting data and map each highlighting to a tag name
List<Pair<String, HighlightInfo>> list = infos.stream()
.map(info -> pair(findTag(types, info), info))
.filter(p -> p.first != null)
.collect(Collectors.toList());
boolean showAttributesKeys =
types.values().stream().flatMap(set -> set.infos.stream()).anyMatch(i -> i.forcedTextAttributesKey != null);
// sort filtered highlighting data by end offset in descending order
Collections.sort(list, (o1, o2) -> {
HighlightInfo i1 = o1.second;
HighlightInfo i2 = o2.second;
int byEnds = i2.endOffset - i1.endOffset;
if (byEnds != 0) return byEnds;
if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) {
int byStarts = i1.startOffset - i2.startOffset;
if (byStarts != 0) return byStarts;
}
else {
int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine());
if (byEOL != 0) return byEOL;
}
int bySeverity = i2.getSeverity().compareTo(i1.getSeverity());
if (bySeverity != 0) return bySeverity;
return Comparing.compare(i1.getDescription(), i2.getDescription());
});
// combine highlighting data with original text
StringBuilder sb = new StringBuilder();
int[] offsets = composeText(sb, list, 0, text, text.length(), -1, showAttributesKeys, messageBundles);
sb.insert(0, text.substring(0, offsets[1]));
return sb.toString();
}
/** This is temporary wrapper to provide a time to fix failing tests */
@Deprecated
public static void expectedDuplicatedHighlighting(@NotNull Runnable check) {
try {
isDuplicatedCheckDisabled = true;
failedDuplicationChecks = 0;
check.run();
}
finally {
isDuplicatedCheckDisabled = false;
}
if (failedDuplicationChecks == 0) {
throw new IllegalStateException(EXPECTED_DUPLICATION_MESSAGE);
}
}
private static int[] composeText(StringBuilder sb,
List<? extends Pair<String, HighlightInfo>> list, int index,
String text, int endPos, int startPos,
boolean showAttributesKeys,
ResourceBundle... messageBundles) {
int i = index;
while (i < list.size()) {
Pair<String, HighlightInfo> pair = list.get(i);
HighlightInfo info = pair.second;
if (info.endOffset <= startPos) {
break;
}
String severity = pair.first;
HighlightInfo prev = i < list.size() - 1 ? list.get(i + 1).second : null;
sb.insert(0, text.substring(info.endOffset, endPos));
sb.insert(0, "</" + severity + '>');
endPos = info.endOffset;
if (prev != null && prev.endOffset > info.startOffset) {
int[] offsets = composeText(sb, list, i + 1, text, endPos, info.startOffset, showAttributesKeys, messageBundles);
i = offsets[0] - 1;
endPos = offsets[1];
}
sb.insert(0, text.substring(info.startOffset, endPos));
String str = '<' + severity + " ";
String bundleMsg = composeBundleMsg(info, messageBundles);
if (bundleMsg != null) {
str += "bundleMsg=\"" + StringUtil.escapeQuotes(bundleMsg) + '"';
}
else {
str += "descr=\"" + StringUtil.escapeQuotes(String.valueOf(info.getDescription())) + '"';
}
if (showAttributesKeys) {
str += " textAttributesKey=\"" + info.forcedTextAttributesKey + '"';
}
str += '>';
sb.insert(0, str);
endPos = info.startOffset;
i++;
}
return new int[]{i, endPos};
}
private static String composeBundleMsg(HighlightInfo info, ResourceBundle... messageBundles) {
String bundleKey = null;
Object[] bundleMsgParams = null;
for (ResourceBundle bundle : messageBundles) {
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
ParsePosition position = new ParsePosition(0);
String value = bundle.getString(key);
Object[] parse;
boolean matched;
if (value.contains("{0")) {
parse = new MessageFormat(value).parse(info.getDescription(), position);
matched = parse != null && info.getDescription() != null && position.getIndex() == info.getDescription().length() && position.getErrorIndex() == -1;
}
else {
parse = ArrayUtil.EMPTY_OBJECT_ARRAY;
matched = value.equals(info.getDescription());
}
if (matched) {
if (bundleKey != null) {
bundleKey = null;
break; // several keys matched, don't suggest bundle key
}
bundleKey = key;
bundleMsgParams = parse;
}
}
}
if (bundleKey == null) return null;
String bundleMsg = bundleKey;
if (bundleMsgParams.length > 0) {
bundleMsg += '|' + StringUtil.join(ContainerUtil.map(bundleMsgParams, Objects::toString), "|");
}
return bundleMsg;
}
private static boolean infosContainsExpectedInfo(Collection<? extends HighlightInfo> infos, HighlightInfo expectedInfo) {
for (HighlightInfo info : infos) {
if (matchesPattern(expectedInfo, info, false)) {
return true;
}
}
return false;
}
private ThreeState expectedInfosContainsInfo(HighlightInfo info) {
if (info.getTextAttributes(null, null) == TextAttributes.ERASE_MARKER) return ThreeState.UNSURE;
Collection<ExpectedHighlightingSet> expectedHighlights = myHighlightingTypes.values();
for (ExpectedHighlightingSet highlightingSet : expectedHighlights) {
if (highlightingSet.severity != info.getSeverity()) continue;
if (!highlightingSet.enabled) return ThreeState.UNSURE;
Set<HighlightInfo> infos = highlightingSet.infos;
for (HighlightInfo expectedInfo : infos) {
if (matchesPattern(expectedInfo, info, false)) {
return ThreeState.YES;
}
}
}
return ThreeState.NO;
}
private static boolean matchesPattern(@NotNull HighlightInfo expectedInfo, @NotNull HighlightInfo info, boolean strictMatch) {
if (expectedInfo == info) return true;
boolean typeMatches = expectedInfo.type.equals(info.type) || !strictMatch && expectedInfo.type == WHATEVER;
boolean textAttributesMatches = Comparing.equal(expectedInfo.getTextAttributes(null, null), info.getTextAttributes(null, null)) ||
!strictMatch && expectedInfo.forcedTextAttributes == null;
boolean attributesKeyMatches = !strictMatch && expectedInfo.forcedTextAttributesKey == null ||
Objects.equals(expectedInfo.forcedTextAttributesKey, info.forcedTextAttributesKey);
return
haveSamePresentation(info, expectedInfo, strictMatch) &&
info.getSeverity() == expectedInfo.getSeverity() &&
typeMatches &&
textAttributesMatches &&
attributesKeyMatches;
}
private static boolean haveSamePresentation(@NotNull HighlightInfo info1, @NotNull HighlightInfo info2, boolean strictMatch) {
return info1.startOffset == info2.startOffset &&
info1.endOffset == info2.endOffset &&
info1.isAfterEndOfLine() == info2.isAfterEndOfLine() &&
(Comparing.strEqual(info1.getDescription(), info2.getDescription()) ||
!strictMatch && Comparing.strEqual(ANY_TEXT, info2.getDescription()));
}
private static String rangeString(String text, int startOffset, int endOffset) {
LineColumn start = StringUtil.offsetToLineColumn(text, startOffset);
assert start != null: "textLength = " + text.length() + ", startOffset = " + startOffset;
LineColumn end = StringUtil.offsetToLineColumn(text, endOffset);
assert end != null : "textLength = " + text.length() + ", endOffset = " + endOffset;
if (start.line == end.line) {
return String.format("(%d:%d/%d)", start.line + 1, start.column + 1, end.column - start.column);
}
else {
return String.format("(%d:%d..%d:%d)", start.line + 1, end.line + 1, start.column + 1, end.column + 1);
}
}
private static class MyLineMarkerInfo extends LineMarkerInfo<PsiElement> {
private final String myTooltip;
MyLineMarkerInfo(PsiElement element, TextRange range, int updatePass, GutterIconRenderer.Alignment alignment, String tooltip) {
super(element, range, null, updatePass, null, null, alignment);
myTooltip = tooltip;
}
@Override
public String getLineMarkerTooltip() {
return myTooltip;
}
}
} |
3e014b2b444ed02c95ec97f26b7bc3b7cbc3678d | 1,761 | java | Java | modules/core/src/test/java/org/apache/ignite/internal/client/thin/TestExceptionalTask.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 4,339 | 2015-08-21T21:13:25.000Z | 2022-03-30T09:56:44.000Z | modules/core/src/test/java/org/apache/ignite/internal/client/thin/TestExceptionalTask.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 1,933 | 2015-08-24T11:37:40.000Z | 2022-03-31T08:37:08.000Z | modules/core/src/test/java/org/apache/ignite/internal/client/thin/TestExceptionalTask.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 2,140 | 2015-08-21T22:09:00.000Z | 2022-03-25T07:57:34.000Z | 37.468085 | 101 | 0.748438 | 540 | /*
* 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.ignite.internal.client.thin;
import java.util.List;
import java.util.Map;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.compute.ComputeJob;
import org.apache.ignite.compute.ComputeJobResult;
import org.apache.ignite.compute.ComputeTaskAdapter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Test compute task that throws an exception.
*/
public class TestExceptionalTask extends ComputeTaskAdapter<String, String> {
/** {@inheritDoc} */
@Override public @NotNull Map<? extends ComputeJob, ClusterNode> map(
List<ClusterNode> subgrid,
@Nullable String arg) throws IgniteException {
throw new ArithmeticException("Foo");
}
/** {@inheritDoc} */
@Nullable @Override public String reduce(List<ComputeJobResult> results) throws IgniteException {
return null;
}
}
|
3e014c9df0a6c4360032cfe02851fa9e0625dcfc | 2,100 | java | Java | DailyProjectLibrary/src/main/java/com/xfhy/androidbasiclibs/util/DevicesUtils.java | xfhy/Daily | 72b021ffd301440ba9a28d63546ba4388981dbd3 | [
"Apache-2.0"
] | 15 | 2017-08-24T15:46:46.000Z | 2020-05-07T13:00:30.000Z | DailyProjectLibrary/src/main/java/com/xfhy/androidbasiclibs/util/DevicesUtils.java | xfhy/Daily | 72b021ffd301440ba9a28d63546ba4388981dbd3 | [
"Apache-2.0"
] | null | null | null | DailyProjectLibrary/src/main/java/com/xfhy/androidbasiclibs/util/DevicesUtils.java | xfhy/Daily | 72b021ffd301440ba9a28d63546ba4388981dbd3 | [
"Apache-2.0"
] | 3 | 2017-09-21T00:54:55.000Z | 2018-03-05T05:52:04.000Z | 29.166667 | 110 | 0.663333 | 541 | package com.xfhy.androidbasiclibs.util;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import com.xfhy.androidbasiclibs.BaseApplication;
/**
* Created by xfhy on 2017/9/24 21:57.
* Description: 设备的工具类
* 用来存放诸如:设备屏幕宽度 设置连接网络状态...
*/
public class DevicesUtils {
/**
* 判断网络连接是否正常
*
* @return 返回网络连接是否正常 true:正常 false:无网络连接
*/
public static boolean hasNetworkConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) BaseApplication.getApplication()
.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
return activeNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 获取屏幕的大小(宽高)
*
* @return DisplayMetrics实例
* <p>
* displayMetrics.heightPixels是高度(单位是像素)
* displayMetrics.heightPixels是宽度(单位是像素)
*/
public static DisplayMetrics getDevicesSize() {
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) BaseApplication.getApplication().getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
Display defaultDisplay = windowManager.getDefaultDisplay();
defaultDisplay.getMetrics(displayMetrics);
return displayMetrics;
}
return new DisplayMetrics();
}
/**
* 跳转到设置界面
*
* @param context Context
*/
public static void goSetting(Context context) {
if (context != null) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
context.startActivity(intent);
}
}
}
|
3e014cd801018e599808717ce3eaeb9f4d528c3c | 1,315 | java | Java | felles/integrasjon/inntekt-klient/src/main/java/no/nav/vedtak/felles/integrasjon/inntekt/InntektConsumerImpl.java | navikt/spsak | ede4770de33bd896d62225a9617b713878d1efa5 | [
"MIT"
] | 1 | 2019-11-15T10:37:38.000Z | 2019-11-15T10:37:38.000Z | felles/integrasjon/inntekt-klient/src/main/java/no/nav/vedtak/felles/integrasjon/inntekt/InntektConsumerImpl.java | navikt/spsak | ede4770de33bd896d62225a9617b713878d1efa5 | [
"MIT"
] | null | null | null | felles/integrasjon/inntekt-klient/src/main/java/no/nav/vedtak/felles/integrasjon/inntekt/InntektConsumerImpl.java | navikt/spsak | ede4770de33bd896d62225a9617b713878d1efa5 | [
"MIT"
] | 1 | 2019-11-15T10:37:41.000Z | 2019-11-15T10:37:41.000Z | 42.419355 | 114 | 0.796198 | 542 | package no.nav.vedtak.felles.integrasjon.inntekt;
import javax.xml.ws.soap.SOAPFaultException;
import no.nav.tjeneste.virksomhet.inntekt.v3.binding.HentInntektListeBolkHarIkkeTilgangTilOensketAInntektsfilter;
import no.nav.tjeneste.virksomhet.inntekt.v3.binding.HentInntektListeBolkUgyldigInput;
import no.nav.tjeneste.virksomhet.inntekt.v3.binding.InntektV3;
import no.nav.tjeneste.virksomhet.inntekt.v3.meldinger.HentInntektListeBolkRequest;
import no.nav.tjeneste.virksomhet.inntekt.v3.meldinger.HentInntektListeBolkResponse;
import no.nav.vedtak.felles.integrasjon.felles.ws.SoapWebServiceFeil;
public class InntektConsumerImpl implements InntektConsumer {
public static final String SERVICE_IDENTIFIER = "InntektV3";
private InntektV3 port;
public InntektConsumerImpl(InntektV3 port) {
this.port = port;
}
@Override
public HentInntektListeBolkResponse hentInntektListeBolk(HentInntektListeBolkRequest request)
throws HentInntektListeBolkHarIkkeTilgangTilOensketAInntektsfilter, HentInntektListeBolkUgyldigInput {
try {
return port.hentInntektListeBolk(request);
} catch (SOAPFaultException e) { // NOSONAR
throw SoapWebServiceFeil.FACTORY.soapFaultIwebserviceKall(SERVICE_IDENTIFIER, e).toException();
}
}
}
|
3e014ce28c4242eb4b5aa5e4a084600b82a53563 | 1,052 | java | Java | learn-micro-services-with-spring-boot/src/main/java/com/KSTech/learnmicroserviceswithspringboot/LocalizationViewController.java | kamarshad/LearnMSUsingSpringBoot | 4ee1fceac500c594c7e3df5fac245d577198144b | [
"MIT"
] | null | null | null | learn-micro-services-with-spring-boot/src/main/java/com/KSTech/learnmicroserviceswithspringboot/LocalizationViewController.java | kamarshad/LearnMSUsingSpringBoot | 4ee1fceac500c594c7e3df5fac245d577198144b | [
"MIT"
] | null | null | null | learn-micro-services-with-spring-boot/src/main/java/com/KSTech/learnmicroserviceswithspringboot/LocalizationViewController.java | kamarshad/LearnMSUsingSpringBoot | 4ee1fceac500c594c7e3df5fac245d577198144b | [
"MIT"
] | null | null | null | 38.962963 | 103 | 0.79943 | 543 | package com.KSTech.learnmicroserviceswithspringboot;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
@RestController
public class LocalizationViewController {
@Autowired
private MessageSource messageSource;
@GetMapping ("/hello-world/internationalization")
//@RequestHeader(value = "Accept-Language", required = false) Locale locale
// Instead of putting the locale and accessing it from request header is quite redundant work.
// Instead of that we can access it from LocaleContxtHolder as mentioned below
public String helloWorld() {
return messageSource.getMessage("good.morning.message", null, LocaleContextHolder.getLocale());
}
}
|
3e014d19dc41fe5bdacad8a6455cec628d93ca37 | 1,008 | java | Java | xill-api/src/main/java/nl/xillio/xill/api/components/MetaExpressionSerializer.java | xillio/xill-platform | 1da3697f39b4c3997b6b40dda82977b293234b36 | [
"Apache-2.0"
] | 4 | 2018-05-03T15:39:10.000Z | 2021-12-14T15:19:50.000Z | xill-api/src/main/java/nl/xillio/xill/api/components/MetaExpressionSerializer.java | RobAaldijk/xill-platform | 1da3697f39b4c3997b6b40dda82977b293234b36 | [
"Apache-2.0"
] | 46 | 2018-04-13T10:04:43.000Z | 2022-01-21T23:20:29.000Z | xill-api/src/main/java/nl/xillio/xill/api/components/MetaExpressionSerializer.java | RobAaldijk/xill-platform | 1da3697f39b4c3997b6b40dda82977b293234b36 | [
"Apache-2.0"
] | 3 | 2018-03-29T18:52:13.000Z | 2021-12-15T09:38:10.000Z | 30.575758 | 86 | 0.72448 | 544 | /**
* Copyright (C) 2014 Xillio (anpch@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.xillio.xill.api.components;
/**
* This interface represents an object that can convert a MetaExpression to an Object.
*
* @author Thomas Biesaart
* @author Titus Nachbauer
*/
public interface MetaExpressionSerializer {
Object extractValue(MetaExpression metaExpression);
/**
* A null implementation.
*/
MetaExpressionSerializer NULL = a -> null;
}
|
3e014d554c8cfc04c692dc2141efa177cb719990 | 11,523 | java | Java | providers/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java | storgashov/jclouds | f46b38dd89626bc3d32d8260dd816d44255a8420 | [
"Apache-1.1"
] | 324 | 2015-01-07T00:53:52.000Z | 2022-02-15T10:46:41.000Z | providers/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java | storgashov/jclouds | f46b38dd89626bc3d32d8260dd816d44255a8420 | [
"Apache-1.1"
] | 608 | 2015-01-01T00:35:57.000Z | 2020-07-25T13:30:31.000Z | providers/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java | storgashov/jclouds | f46b38dd89626bc3d32d8260dd816d44255a8420 | [
"Apache-1.1"
] | 427 | 2015-01-05T08:13:49.000Z | 2022-01-02T04:40:30.000Z | 42.836431 | 121 | 0.702074 | 545 | /*
* 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.jclouds.glesys.compute;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.contains;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.find;
import static com.google.common.io.BaseEncoding.base16;
import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.glesys.GleSYSApi;
import org.jclouds.glesys.compute.options.GleSYSTemplateOptions;
import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;
import org.jclouds.glesys.domain.OSTemplate;
import org.jclouds.glesys.domain.Server;
import org.jclouds.glesys.domain.ServerDetails;
import org.jclouds.glesys.domain.ServerSpec;
import org.jclouds.glesys.options.CreateServerOptions;
import org.jclouds.glesys.options.DestroyServerOptions;
import org.jclouds.location.predicates.LocationPredicates;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListeningExecutorService;
/**
* defines the connection between the {@link GleSYSApi} implementation and
* the jclouds {@link ComputeService}
*/
@Singleton
public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter<ServerDetails, Hardware, OSTemplate, String> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final GleSYSApi api;
private final ListeningExecutorService userExecutor;
private final Timeouts timeouts;
private final Supplier<Set<? extends Location>> locations;
@Inject
public GleSYSComputeServiceAdapter(GleSYSApi api,
@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, Timeouts timeouts,
@Memoized Supplier<Set<? extends Location>> locations) {
this.api = checkNotNull(api, "api");
this.userExecutor = checkNotNull(userExecutor, "userExecutor");
this.timeouts = checkNotNull(timeouts, "timeouts");
this.locations = checkNotNull(locations, "locations");
}
@Override
public NodeAndInitialCredentials<ServerDetails> createNodeWithGroupEncodedIntoName(String group, String name,
Template template) {
checkNotNull(template, "template was null");
checkNotNull(template.getOptions(), "template options was null");
checkArgument(template.getOptions().getClass().isAssignableFrom(GleSYSTemplateOptions.class),
"options class %s should have been assignable from GleSYSTemplateOptions", template.getOptions().getClass());
GleSYSTemplateOptions templateOptions = template.getOptions().as(GleSYSTemplateOptions.class);
CreateServerOptions createServerOptions = new CreateServerOptions();
createServerOptions.ip(templateOptions.getIp());
template.getOptions().userMetadata(ComputeServiceConstants.NODE_GROUP_KEY, group);
Map<String, String> md = metadataAndTagsAsCommaDelimitedValue(template.getOptions());
if (!md.isEmpty()) {
String description = Joiner.on('\n').withKeyValueSeparator("=").join(md);
// TODO: get glesys to stop stripping out equals and commas!
createServerOptions.description(base16().lowerCase().encode(description.getBytes(UTF_8)));
}
ServerSpec.Builder<?> builder = ServerSpec.builder();
builder.datacenter(template.getLocation().getId());
builder.templateName(template.getImage().getId());
builder.platform(template.getHardware().getHypervisor());
builder.memorySizeMB(template.getHardware().getRam());
builder.diskSizeGB(Math.round(template.getHardware().getVolumes().get(0).getSize()));
builder.cpuCores((int) template.getHardware().getProcessors().get(0).getCores());
builder.transferGB(templateOptions.getTransferGB());
ServerSpec spec = builder.build();
// use random root password unless one was provided via template options
String password = templateOptions.hasRootPassword() ? templateOptions.getRootPassword() : getRandomPassword();
logger.debug(">> creating new Server spec(%s) name(%s) options(%s)", spec, name, createServerOptions);
ServerDetails result = api.getServerApi().createWithHostnameAndRootPassword(spec, name, password,
createServerOptions);
logger.trace("<< server(%s)", result.getId());
return new NodeAndInitialCredentials<ServerDetails>(result, result.getId() + "", LoginCredentials.builder()
.password(password).build());
}
/**
* @return a generated random password string
*/
private String getRandomPassword() {
return UUID.randomUUID().toString().replace("-", "");
}
@Override
public Iterable<Hardware> listHardwareProfiles() {
Set<? extends Location> locationsSet = locations.get();
ImmutableSet.Builder<Hardware> hardwareToReturn = ImmutableSet.builder();
// do this loop after dupes are filtered, else OOM
Set<OSTemplate> images = listImages();
for (Entry<String, AllowedArgumentsForCreateServer> platformToArgs : api.getServerApi()
.getAllowedArgumentsForCreateByPlatform().entrySet())
for (String datacenter : platformToArgs.getValue().getDataCenters())
for (int diskSizeGB : platformToArgs.getValue().getDiskSizesInGB().getAllowedUnits())
for (int cpuCores : platformToArgs.getValue().getCpuCoreOptions().getAllowedUnits())
for (int memorySizeMB : platformToArgs.getValue().getMemorySizesInMB().getAllowedUnits()) {
ImmutableSet.Builder<String> templatesSupportedBuilder = ImmutableSet.builder();
for (OSTemplate template : images) {
if (template.getPlatform().equals(platformToArgs.getKey())
&& diskSizeGB >= template.getMinDiskSize() && memorySizeMB >= template.getMinMemSize())
templatesSupportedBuilder.add(template.getName());
}
ImmutableSet<String> templatesSupported = templatesSupportedBuilder.build();
if (!templatesSupported.isEmpty())
hardwareToReturn.add(new HardwareBuilder()
.ids(String.format(
"datacenter(%s)platform(%s)cpuCores(%d)memorySizeMB(%d)diskSizeGB(%d)", datacenter,
platformToArgs.getKey(), cpuCores, memorySizeMB, diskSizeGB)).ram(memorySizeMB)
.processors(ImmutableList.of(new Processor(cpuCores, 1.0)))
.volumes(ImmutableList.<Volume> of(new VolumeImpl((float) diskSizeGB, true, true)))
.hypervisor(platformToArgs.getKey())
.location(find(locationsSet, LocationPredicates.idEquals(datacenter)))
.supportsImage(ImagePredicates.idIn(templatesSupported)).build());
}
return hardwareToReturn.build();
}
@Override
public Set<OSTemplate> listImages() {
return api.getServerApi().listTemplates().toSet();
}
// cheat until we have a getTemplate command
@Override
public OSTemplate getImage(final String id) {
return find(listImages(), new Predicate<OSTemplate>() {
@Override
public boolean apply(OSTemplate input) {
return input.getName().equals(id);
}
}, null);
}
@Override
public Iterable<ServerDetails> listNodes() {
return api.getServerApi().list().transform(new Function<Server, ServerDetails>() {
public ServerDetails apply(Server from) {
return api.getServerApi().get(from.getId());
}
});
}
@Override
public Iterable<ServerDetails> listNodesByIds(final Iterable<String> ids) {
return filter(listNodes(), new Predicate<ServerDetails>() {
@Override
public boolean apply(ServerDetails server) {
return contains(ids, server.getId());
}
});
}
@Override
public Set<String> listLocations() {
return FluentIterable.from(api.getServerApi().getAllowedArgumentsForCreateByPlatform().values())
.transformAndConcat(new Function<AllowedArgumentsForCreateServer, Set<String>>() {
@Override
public Set<String> apply(AllowedArgumentsForCreateServer arg0) {
return arg0.getDataCenters();
}
}).toSet();
}
@Override
public ServerDetails getNode(String id) {
return api.getServerApi().get(id);
}
@Override
public void destroyNode(String id) {
retry(new Predicate<String>() {
public boolean apply(String arg0) {
try {
api.getServerApi().destroy(arg0, DestroyServerOptions.Builder.discardIp());
return true;
} catch (IllegalStateException e) {
return false;
}
}
}, timeouts.nodeTerminated).apply(id);
}
@Override
public void rebootNode(String id) {
api.getServerApi().reboot(id);
}
@Override
public void resumeNode(String id) {
api.getServerApi().start(id);
}
@Override
public void suspendNode(String id) {
api.getServerApi().stop(id);
}
}
|
3e014d6e1aaf4df3a595d73fcc6b99aab5f2403a | 2,609 | java | Java | src/main/java/eu/midnightdust/midnightcontrols/client/mixin/MouseMixin.java | Motschen/LambdaControls | bca73c93ccee13a5a566ed2611d9a88434c3713e | [
"MIT"
] | 4 | 2022-03-13T13:58:41.000Z | 2022-03-27T16:49:11.000Z | src/main/java/eu/midnightdust/midnightcontrols/client/mixin/MouseMixin.java | Motschen/LambdaControls | bca73c93ccee13a5a566ed2611d9a88434c3713e | [
"MIT"
] | 4 | 2022-03-13T14:15:35.000Z | 2022-03-26T18:56:46.000Z | src/main/java/eu/midnightdust/midnightcontrols/client/mixin/MouseMixin.java | Motschen/LambdaControls | bca73c93ccee13a5a566ed2611d9a88434c3713e | [
"MIT"
] | null | null | null | 39.044776 | 125 | 0.724006 | 546 | /*
* Copyright © 2021 LambdAurora <nnheo@example.com>
*
* This file is part of midnightcontrols.
*
* Licensed under the MIT license. For more information,
* see the LICENSE file.
*/
package eu.midnightdust.midnightcontrols.client.mixin;
import eu.midnightdust.midnightcontrols.ControlsMode;
import eu.midnightdust.midnightcontrols.client.MidnightControlsClient;
import eu.midnightdust.midnightcontrols.client.MidnightControlsConfig;
import eu.midnightdust.midnightcontrols.client.util.MouseAccessor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.Mouse;
import net.minecraft.client.gui.screen.Screen;
import org.lwjgl.glfw.GLFW;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/**
* Adds extra access to the mouse.
*/
@Mixin(Mouse.class)
public abstract class MouseMixin implements MouseAccessor {
@Shadow
@Final
private MinecraftClient client;
@Invoker("onCursorPos")
public abstract void midnightcontrols$onCursorPos(long window, double x, double y);
@Inject(method = "onMouseButton", at = @At(value = "TAIL"))
private void onMouseBackButton(long window, int button, int action, int mods, CallbackInfo ci) {
if (action == 1 && button == GLFW.GLFW_MOUSE_BUTTON_4 && MinecraftClient.getInstance().currentScreen != null) {
if (MidnightControlsClient.get().input.tryGoBack(MinecraftClient.getInstance().currentScreen)) {
action = 0;
}
}
}
@Inject(method = "isCursorLocked", at = @At("HEAD"), cancellable = true)
private void isCursorLocked(CallbackInfoReturnable<Boolean> ci) {
if (this.client.currentScreen == null) {
if (MidnightControlsConfig.controlsMode == ControlsMode.CONTROLLER && MidnightControlsConfig.virtualMouse) {
ci.setReturnValue(true);
ci.cancel();
}
}
}
@Inject(method = "lockCursor", at = @At("HEAD"), cancellable = true)
private void onCursorLocked(CallbackInfo ci) {
if (/*config.getControlsMode() == ControlsMode.TOUCHSCREEN
||*/ (MidnightControlsConfig.controlsMode == ControlsMode.CONTROLLER && MidnightControlsConfig.virtualMouse))
ci.cancel();
}
}
|
3e014d7f884d3631075568608a247ec2a8079adb | 14,662 | java | Java | netreflected/src/netcoreapp3.1/system.security.cryptography.algorithms_version_4.3.2.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/security/cryptography/RSAOAEPKeyExchangeFormatter.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 35 | 2020-08-30T03:19:42.000Z | 2022-03-12T09:22:23.000Z | netreflected/src/netcoreapp3.1/system.security.cryptography.algorithms_version_4.3.2.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/security/cryptography/RSAOAEPKeyExchangeFormatter.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 50 | 2020-06-22T17:03:18.000Z | 2022-03-30T21:19:05.000Z | netreflected/src/netcoreapp3.1/system.security.cryptography.algorithms_version_4.3.2.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/security/cryptography/RSAOAEPKeyExchangeFormatter.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 12 | 2020-08-30T03:19:45.000Z | 2022-03-05T02:22:37.000Z | 46.694268 | 392 | 0.685309 | 547 | /*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.security.cryptography;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.security.cryptography.AsymmetricKeyExchangeFormatter;
import system.security.cryptography.AsymmetricAlgorithm;
import system.security.cryptography.RandomNumberGenerator;
/**
* The base .NET class managing System.Security.Cryptography.RSAOAEPKeyExchangeFormatter, System.Security.Cryptography.Algorithms, Version=4.3.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Security.Cryptography.RSAOAEPKeyExchangeFormatter" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Security.Cryptography.RSAOAEPKeyExchangeFormatter</a>
*/
public class RSAOAEPKeyExchangeFormatter extends AsymmetricKeyExchangeFormatter {
/**
* Fully assembly qualified name: System.Security.Cryptography.Algorithms, Version=4.3.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
*/
public static final String assemblyFullName = "System.Security.Cryptography.Algorithms, Version=4.3.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
/**
* Assembly name: System.Security.Cryptography.Algorithms
*/
public static final String assemblyShortName = "System.Security.Cryptography.Algorithms";
/**
* Qualified class name: System.Security.Cryptography.RSAOAEPKeyExchangeFormatter
*/
public static final String className = "System.Security.Cryptography.RSAOAEPKeyExchangeFormatter";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public RSAOAEPKeyExchangeFormatter(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link RSAOAEPKeyExchangeFormatter}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link RSAOAEPKeyExchangeFormatter} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static RSAOAEPKeyExchangeFormatter cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new RSAOAEPKeyExchangeFormatter(from.getJCOInstance());
}
// Constructors section
public RSAOAEPKeyExchangeFormatter() throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(key == null ? null : key.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
public byte[] CreateKeyExchange(byte[] rgbData) throws Throwable, system.ArgumentException, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.PlatformNotSupportedException, system.globalization.CultureNotFoundException, system.security.cryptography.CryptographicUnexpectedOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
ArrayList<java.lang.Object> resultingArrayList = new ArrayList<java.lang.Object>();
JCObject resultingObjects = (JCObject)classInstance.Invoke("CreateKeyExchange", (java.lang.Object)rgbData);
for (java.lang.Object resultingObject : resultingObjects) {
resultingArrayList.add(resultingObject);
}
byte[] resultingArray = new byte[resultingArrayList.size()];
for(int indexCreateKeyExchange = 0; indexCreateKeyExchange < resultingArrayList.size(); indexCreateKeyExchange++ ) {
resultingArray[indexCreateKeyExchange] = (byte)resultingArrayList.get(indexCreateKeyExchange);
}
return resultingArray;
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public byte[] CreateKeyExchange(JCORefOut dupParam0) throws Throwable, system.ArgumentException, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.PlatformNotSupportedException, system.globalization.CultureNotFoundException, system.security.cryptography.CryptographicUnexpectedOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
ArrayList<java.lang.Object> resultingArrayList = new ArrayList<java.lang.Object>();
JCObject resultingObjects = (JCObject)classInstance.Invoke("CreateKeyExchange", (java.lang.Object)dupParam0.getJCRefOut());
for (java.lang.Object resultingObject : resultingObjects) {
resultingArrayList.add(resultingObject);
}
byte[] resultingArray = new byte[resultingArrayList.size()];
for(int indexCreateKeyExchange = 0; indexCreateKeyExchange < resultingArrayList.size(); indexCreateKeyExchange++ ) {
resultingArray[indexCreateKeyExchange] = (byte)resultingArrayList.get(indexCreateKeyExchange);
}
return resultingArray;
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public byte[] CreateKeyExchange(byte[] rgbData, NetType symAlgType) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
ArrayList<java.lang.Object> resultingArrayList = new ArrayList<java.lang.Object>();
JCObject resultingObjects = (JCObject)classInstance.Invoke("CreateKeyExchange", rgbData, symAlgType == null ? null : symAlgType.getJCOInstance());
for (java.lang.Object resultingObject : resultingObjects) {
resultingArrayList.add(resultingObject);
}
byte[] resultingArray = new byte[resultingArrayList.size()];
for(int indexCreateKeyExchange = 0; indexCreateKeyExchange < resultingArrayList.size(); indexCreateKeyExchange++ ) {
resultingArray[indexCreateKeyExchange] = (byte)resultingArrayList.get(indexCreateKeyExchange);
}
return resultingArray;
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public byte[] CreateKeyExchange(JCORefOut dupParam0, NetType dupParam1) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
ArrayList<java.lang.Object> resultingArrayList = new ArrayList<java.lang.Object>();
JCObject resultingObjects = (JCObject)classInstance.Invoke("CreateKeyExchange", dupParam0.getJCRefOut(), dupParam1 == null ? null : dupParam1.getJCOInstance());
for (java.lang.Object resultingObject : resultingObjects) {
resultingArrayList.add(resultingObject);
}
byte[] resultingArray = new byte[resultingArrayList.size()];
for(int indexCreateKeyExchange = 0; indexCreateKeyExchange < resultingArrayList.size(); indexCreateKeyExchange++ ) {
resultingArray[indexCreateKeyExchange] = (byte)resultingArrayList.get(indexCreateKeyExchange);
}
return resultingArray;
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void SetKey(AsymmetricAlgorithm key) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("SetKey", key == null ? null : key.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Properties section
public byte[] getParameter() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
ArrayList<java.lang.Object> resultingArrayList = new ArrayList<java.lang.Object>();
JCObject resultingObjects = (JCObject)classInstance.Get("Parameter");
for (java.lang.Object resultingObject : resultingObjects) {
resultingArrayList.add(resultingObject);
}
byte[] resultingArray = new byte[resultingArrayList.size()];
for(int indexParameter = 0; indexParameter < resultingArrayList.size(); indexParameter++ ) {
resultingArray[indexParameter] = (byte)resultingArrayList.get(indexParameter);
}
return resultingArray;
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setParameter(byte[] Parameter) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("Parameter", Parameter);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public RandomNumberGenerator getRng() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("Rng");
return new RandomNumberGenerator(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setRng(RandomNumberGenerator Rng) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("Rng", Rng == null ? null : Rng.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
} |
3e014de615be5e3861d5d338053abe7e9179fa96 | 6,776 | java | Java | src/main/java/org/apache/jetspeed/portlets/spaces/SpacesList.java | Konque/J2-Admin | 3381e284e2816e9cec2d7bf429dc7549aa32c733 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/jetspeed/portlets/spaces/SpacesList.java | Konque/J2-Admin | 3381e284e2816e9cec2d7bf429dc7549aa32c733 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/jetspeed/portlets/spaces/SpacesList.java | Konque/J2-Admin | 3381e284e2816e9cec2d7bf429dc7549aa32c733 | [
"Apache-2.0"
] | null | null | null | 40.094675 | 163 | 0.704841 | 548 | /*
* 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.jetspeed.portlets.spaces;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.jetspeed.CommonPortletServices;
import org.apache.jetspeed.portlet.HeaderPhaseSupportConstants;
import org.apache.jetspeed.portlets.toolbox.ThemeBean;
import org.apache.jetspeed.request.RequestContext;
import org.apache.jetspeed.spaces.Space;
import org.apache.jetspeed.spaces.Spaces;
import org.apache.jetspeed.spaces.SpacesException;
import org.apache.portals.bridges.common.GenericServletPortlet;
import org.apache.portals.messaging.PortletMessaging;
import org.w3c.dom.Element;
/**
* Spaces List
*
* @author <a href="mailto:lyhxr@example.com">David Sean Taylor</a>
* @version $Id: $
*/
public class SpacesList extends GenericServletPortlet
{
private Spaces spacesService;
protected String yuiScriptPath = "/javascript/yui/build/yui/yui-min.js";
public void init(PortletConfig config) throws PortletException
{
super.init(config);
PortletContext context = getPortletContext();
spacesService = (Spaces) context.getAttribute(CommonPortletServices.CPS_SPACES_SERVICE);
if (spacesService == null)
{
throw new PortletException(
"Could not get instance of portal spaces service component");
}
String param = config.getInitParameter("yuiScriptPath");
if (param != null)
{
yuiScriptPath = param;
}
}
@Override
protected void doHeaders(RenderRequest request, RenderResponse response)
{
super.doHeaders(request, response);
RequestContext rc = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV);
Element headElem = response.createElement("script");
headElem.setAttribute("language", "javascript");
String scriptPath = rc.getRequest().getContextPath() + yuiScriptPath;
headElem.setAttribute("id", HeaderPhaseSupportConstants.HEAD_ELEMENT_CONTRIBUTION_ELEMENT_ID_YUI_LIBRARY_INCLUDE);
headElem.setAttribute("src", scriptPath);
headElem.setAttribute("type", "text/javascript");
response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, headElem);
}
@SuppressWarnings("unchecked")
public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException
{
String userName = (request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null);
UserSpaceBeanList spaces = (UserSpaceBeanList) request.getPortletSession().getAttribute(SpaceNavigator.ATTRIBUTE_SPACES, PortletSession.APPLICATION_SCOPE);
// Validating the spaces cache in session if it was for the same user
if (spaces != null && !StringUtils.equals(spaces.getUserName(), userName))
{
request.getPortletSession().removeAttribute(SpaceNavigator.ATTRIBUTE_SPACES, PortletSession.APPLICATION_SCOPE);
spaces = null;
}
if (spaces == null)
{
// TODO: use environment
spaces = SpaceNavigator.createSpaceBeanList(spacesService, userName, null);
request.getPortletSession().setAttribute(SpaceNavigator.ATTRIBUTE_SPACES, spaces);
}
request.setAttribute(SpaceNavigator.ATTRIBUTE_SPACES, spaces);
SpaceBean space = (SpaceBean) request.getPortletSession().getAttribute(SpaceNavigator.ATTRIBUTE_SPACE, PortletSession.APPLICATION_SCOPE);
request.setAttribute(SpaceNavigator.ATTRIBUTE_SPACE, space);
try
{
super.doView(request, response);
}
catch (Throwable t)
{
t.printStackTrace();
}
}
@Override
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException
{
String spaceName = request.getParameter("edit");
if (spaceName != null)
{
PortletMessaging.publish(request, SpacesManager.MSG_TOPIC_SPACE_LIST, SpacesManager.MSG_SPACE_CHANGE, spaceName);
ThemeBean.clearThemesSession(request);
}
else
{
spaceName = request.getParameter("delete");
if (spaceName != null)
{
Space space = spacesService.lookupSpace(spaceName);
if (space != null)
{
try
{
spacesService.deleteSpace(space);
request.getPortletSession().removeAttribute(SpaceNavigator.ATTRIBUTE_SPACES, PortletSession.APPLICATION_SCOPE);
PortletMessaging.cancel(request, SpacesManager.MSG_TOPIC_SPACE_LIST, SpacesManager.MSG_SPACE_CHANGE);
PortletMessaging.cancel(request, SpacesManager.MSG_TOPIC_SPACE_NAV, SpacesManager.MSG_SPACE_CHANGE);
PortletMessaging.cancel(request, SpacesManager.MSG_TOPIC_PAGE_NAV, SpacesManager.MSG_SPACE_CHANGE);
request.getPortletSession().removeAttribute(SpaceNavigator.ATTRIBUTE_SPACES, PortletSession.APPLICATION_SCOPE);
request.getPortletSession().removeAttribute(SpaceNavigator.ATTRIBUTE_SPACE, PortletSession.APPLICATION_SCOPE);
ThemeBean.clearThemesSession(request);
}
catch (SpacesException e)
{
throw new PortletException(e);
}
}
}
else
{
String add = request.getParameter("addspace");
if (add != null)
{
PortletMessaging.cancel(request, SpacesManager.MSG_TOPIC_SPACE_LIST, SpacesManager.MSG_SPACE_CHANGE);
ThemeBean.clearThemesSession(request);
}
}
}
}
} |
3e014e19b82663b9640f5e0ad4539849b5fe2688 | 1,303 | java | Java | drive-core-base/src/main/java/com/drive/cool/init/InitFrame.java | kevin82008/KCool-BASE | d3afffe1c60cc7fce01f3c45cf315d2028c13514 | [
"Apache-2.0"
] | null | null | null | drive-core-base/src/main/java/com/drive/cool/init/InitFrame.java | kevin82008/KCool-BASE | d3afffe1c60cc7fce01f3c45cf315d2028c13514 | [
"Apache-2.0"
] | null | null | null | drive-core-base/src/main/java/com/drive/cool/init/InitFrame.java | kevin82008/KCool-BASE | d3afffe1c60cc7fce01f3c45cf315d2028c13514 | [
"Apache-2.0"
] | null | null | null | 29.613636 | 124 | 0.735994 | 549 | package com.drive.cool.init;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 初始化框架
* @author kevin
*
*/
public class InitFrame{
private final static String CONTEXT_PATH = "classpath*:spring/application-base-beans.xml";
private static ApplicationContext ctx = null;
public static void init(){
ctx = new ClassPathXmlApplicationContext(CONTEXT_PATH);
Map<String, FrameInitedListener> beans = ctx.getBeansOfType(FrameInitedListener.class);
List<Map.Entry<String,FrameInitedListener>> list = new ArrayList<Map.Entry<String,FrameInitedListener>>(beans.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String,FrameInitedListener>>() {
@Override
public int compare(Entry<String, FrameInitedListener> o1,
Entry<String, FrameInitedListener> o2) {
return o1.getValue().getOrder() - o2.getValue().getOrder();
}
});
for(Map.Entry<String,FrameInitedListener> mapping:list){
beans.get(mapping.getKey()).init();
}
}
public static void main(String[] args) {
init();
}
}
|
3e014e625660989a2d4914a734311d1479f3cd9c | 496 | java | Java | rw-web-gis-rural/src/rw/wasac/pdf/PdfBeginText.java | JinIgarashi/rwasom_webgis_trial_secondphase | 46517df22d3f0e0127796e3e92ced4b1e5e5038a | [
"Apache-2.0"
] | null | null | null | rw-web-gis-rural/src/rw/wasac/pdf/PdfBeginText.java | JinIgarashi/rwasom_webgis_trial_secondphase | 46517df22d3f0e0127796e3e92ced4b1e5e5038a | [
"Apache-2.0"
] | null | null | null | rw-web-gis-rural/src/rw/wasac/pdf/PdfBeginText.java | JinIgarashi/rwasom_webgis_trial_secondphase | 46517df22d3f0e0127796e3e92ced4b1e5e5038a | [
"Apache-2.0"
] | null | null | null | 14.588235 | 58 | 0.616935 | 550 | /**
*
*/
package rw.wasac.pdf;
import com.itextpdf.text.pdf.PdfContentByte;
/**
* PdfBeginText class
* @version 1.00
* @author Igarashi
*
*/
public class PdfBeginText extends PdfCmdBase {
/**
* Constructor
*/
public PdfBeginText() {
super("beginText");
}
/**
* To start drawing text
* the parameters are as follows
* <br>method:beginText
*/
@Override
public void execute(PdfContentByte cb) throws Exception{
cb.beginText();
}
}
|
3e015031a3a79c0005c68867d1528356976708d9 | 33,951 | java | Java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/ModifyVolumeRequest.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/ModifyVolumeRequest.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/ModifyVolumeRequest.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 35.037152 | 146 | 0.553327 | 551 | /*
* 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.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.ModifyVolumeRequestMarshaller;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ModifyVolumeRequest extends AmazonWebServiceRequest implements Serializable, Cloneable, DryRunSupportedRequest<ModifyVolumeRequest> {
/**
* <p>
* The ID of the volume.
* </p>
*/
private String volumeId;
/**
* <p>
* The target size of the volume, in GiB. The target volume size must be greater than or equal to the existing size
* of the volume.
* </p>
* <p>
* The following are the supported volumes sizes for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp2</code> and <code>gp3</code>: 1-16,384
* </p>
* </li>
* <li>
* <p>
* <code>io1</code> and <code>io2</code>: 4-16,384
* </p>
* </li>
* <li>
* <p>
* <code>st1</code> and <code>sc1</code>: 125-16,384
* </p>
* </li>
* <li>
* <p>
* <code>standard</code>: 1-1,024
* </p>
* </li>
* </ul>
* <p>
* Default: The existing size is retained.
* </p>
*/
private Integer size;
/**
* <p>
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a> in the
* <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
* <p>
* Default: The existing type is retained.
* </p>
*/
private String volumeType;
/**
* <p>
* The target IOPS rate of the volume. This parameter is valid only for <code>gp3</code>, <code>io1</code>, and
* <code>io2</code> volumes.
* </p>
* <p>
* The following are the supported values for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp3</code>: 3,000-16,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io1</code>: 100-64,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io2</code>: 100-64,000 IOPS
* </p>
* </li>
* </ul>
* <p>
* Default: The existing value is retained if you keep the same volume type. If you change the volume type to
* <code>io1</code>, <code>io2</code>, or <code>gp3</code>, the default is 3,000.
* </p>
*/
private Integer iops;
/**
* <p>
* The target throughput of the volume, in MiB/s. This parameter is valid only for <code>gp3</code> volumes. The
* maximum value is 1,000.
* </p>
* <p>
* Default: The existing value is retained if the source and target volume type is <code>gp3</code>. Otherwise, the
* default value is 125.
* </p>
* <p>
* Valid Range: Minimum value of 125. Maximum value of 1000.
* </p>
*/
private Integer throughput;
/**
* <p>
* Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up
* to 16 <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with <code>io1</code> and
* <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS Multi-Attach</a> in
* the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
private Boolean multiAttachEnabled;
/**
* <p>
* The ID of the volume.
* </p>
*
* @param volumeId
* The ID of the volume.
*/
public void setVolumeId(String volumeId) {
this.volumeId = volumeId;
}
/**
* <p>
* The ID of the volume.
* </p>
*
* @return The ID of the volume.
*/
public String getVolumeId() {
return this.volumeId;
}
/**
* <p>
* The ID of the volume.
* </p>
*
* @param volumeId
* The ID of the volume.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyVolumeRequest withVolumeId(String volumeId) {
setVolumeId(volumeId);
return this;
}
/**
* <p>
* The target size of the volume, in GiB. The target volume size must be greater than or equal to the existing size
* of the volume.
* </p>
* <p>
* The following are the supported volumes sizes for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp2</code> and <code>gp3</code>: 1-16,384
* </p>
* </li>
* <li>
* <p>
* <code>io1</code> and <code>io2</code>: 4-16,384
* </p>
* </li>
* <li>
* <p>
* <code>st1</code> and <code>sc1</code>: 125-16,384
* </p>
* </li>
* <li>
* <p>
* <code>standard</code>: 1-1,024
* </p>
* </li>
* </ul>
* <p>
* Default: The existing size is retained.
* </p>
*
* @param size
* The target size of the volume, in GiB. The target volume size must be greater than or equal to the
* existing size of the volume.</p>
* <p>
* The following are the supported volumes sizes for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp2</code> and <code>gp3</code>: 1-16,384
* </p>
* </li>
* <li>
* <p>
* <code>io1</code> and <code>io2</code>: 4-16,384
* </p>
* </li>
* <li>
* <p>
* <code>st1</code> and <code>sc1</code>: 125-16,384
* </p>
* </li>
* <li>
* <p>
* <code>standard</code>: 1-1,024
* </p>
* </li>
* </ul>
* <p>
* Default: The existing size is retained.
*/
public void setSize(Integer size) {
this.size = size;
}
/**
* <p>
* The target size of the volume, in GiB. The target volume size must be greater than or equal to the existing size
* of the volume.
* </p>
* <p>
* The following are the supported volumes sizes for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp2</code> and <code>gp3</code>: 1-16,384
* </p>
* </li>
* <li>
* <p>
* <code>io1</code> and <code>io2</code>: 4-16,384
* </p>
* </li>
* <li>
* <p>
* <code>st1</code> and <code>sc1</code>: 125-16,384
* </p>
* </li>
* <li>
* <p>
* <code>standard</code>: 1-1,024
* </p>
* </li>
* </ul>
* <p>
* Default: The existing size is retained.
* </p>
*
* @return The target size of the volume, in GiB. The target volume size must be greater than or equal to the
* existing size of the volume.</p>
* <p>
* The following are the supported volumes sizes for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp2</code> and <code>gp3</code>: 1-16,384
* </p>
* </li>
* <li>
* <p>
* <code>io1</code> and <code>io2</code>: 4-16,384
* </p>
* </li>
* <li>
* <p>
* <code>st1</code> and <code>sc1</code>: 125-16,384
* </p>
* </li>
* <li>
* <p>
* <code>standard</code>: 1-1,024
* </p>
* </li>
* </ul>
* <p>
* Default: The existing size is retained.
*/
public Integer getSize() {
return this.size;
}
/**
* <p>
* The target size of the volume, in GiB. The target volume size must be greater than or equal to the existing size
* of the volume.
* </p>
* <p>
* The following are the supported volumes sizes for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp2</code> and <code>gp3</code>: 1-16,384
* </p>
* </li>
* <li>
* <p>
* <code>io1</code> and <code>io2</code>: 4-16,384
* </p>
* </li>
* <li>
* <p>
* <code>st1</code> and <code>sc1</code>: 125-16,384
* </p>
* </li>
* <li>
* <p>
* <code>standard</code>: 1-1,024
* </p>
* </li>
* </ul>
* <p>
* Default: The existing size is retained.
* </p>
*
* @param size
* The target size of the volume, in GiB. The target volume size must be greater than or equal to the
* existing size of the volume.</p>
* <p>
* The following are the supported volumes sizes for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp2</code> and <code>gp3</code>: 1-16,384
* </p>
* </li>
* <li>
* <p>
* <code>io1</code> and <code>io2</code>: 4-16,384
* </p>
* </li>
* <li>
* <p>
* <code>st1</code> and <code>sc1</code>: 125-16,384
* </p>
* </li>
* <li>
* <p>
* <code>standard</code>: 1-1,024
* </p>
* </li>
* </ul>
* <p>
* Default: The existing size is retained.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyVolumeRequest withSize(Integer size) {
setSize(size);
return this;
}
/**
* <p>
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a> in the
* <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
* <p>
* Default: The existing type is retained.
* </p>
*
* @param volumeType
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a>
* in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p>
* <p>
* Default: The existing type is retained.
* @see VolumeType
*/
public void setVolumeType(String volumeType) {
this.volumeType = volumeType;
}
/**
* <p>
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a> in the
* <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
* <p>
* Default: The existing type is retained.
* </p>
*
* @return The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume
* types</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p>
* <p>
* Default: The existing type is retained.
* @see VolumeType
*/
public String getVolumeType() {
return this.volumeType;
}
/**
* <p>
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a> in the
* <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
* <p>
* Default: The existing type is retained.
* </p>
*
* @param volumeType
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a>
* in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p>
* <p>
* Default: The existing type is retained.
* @return Returns a reference to this object so that method calls can be chained together.
* @see VolumeType
*/
public ModifyVolumeRequest withVolumeType(String volumeType) {
setVolumeType(volumeType);
return this;
}
/**
* <p>
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a> in the
* <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
* <p>
* Default: The existing type is retained.
* </p>
*
* @param volumeType
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a>
* in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p>
* <p>
* Default: The existing type is retained.
* @see VolumeType
*/
public void setVolumeType(VolumeType volumeType) {
withVolumeType(volumeType);
}
/**
* <p>
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a> in the
* <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
* <p>
* Default: The existing type is retained.
* </p>
*
* @param volumeType
* The target EBS volume type of the volume. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon EBS volume types</a>
* in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p>
* <p>
* Default: The existing type is retained.
* @return Returns a reference to this object so that method calls can be chained together.
* @see VolumeType
*/
public ModifyVolumeRequest withVolumeType(VolumeType volumeType) {
this.volumeType = volumeType.toString();
return this;
}
/**
* <p>
* The target IOPS rate of the volume. This parameter is valid only for <code>gp3</code>, <code>io1</code>, and
* <code>io2</code> volumes.
* </p>
* <p>
* The following are the supported values for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp3</code>: 3,000-16,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io1</code>: 100-64,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io2</code>: 100-64,000 IOPS
* </p>
* </li>
* </ul>
* <p>
* Default: The existing value is retained if you keep the same volume type. If you change the volume type to
* <code>io1</code>, <code>io2</code>, or <code>gp3</code>, the default is 3,000.
* </p>
*
* @param iops
* The target IOPS rate of the volume. This parameter is valid only for <code>gp3</code>, <code>io1</code>,
* and <code>io2</code> volumes.</p>
* <p>
* The following are the supported values for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp3</code>: 3,000-16,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io1</code>: 100-64,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io2</code>: 100-64,000 IOPS
* </p>
* </li>
* </ul>
* <p>
* Default: The existing value is retained if you keep the same volume type. If you change the volume type to
* <code>io1</code>, <code>io2</code>, or <code>gp3</code>, the default is 3,000.
*/
public void setIops(Integer iops) {
this.iops = iops;
}
/**
* <p>
* The target IOPS rate of the volume. This parameter is valid only for <code>gp3</code>, <code>io1</code>, and
* <code>io2</code> volumes.
* </p>
* <p>
* The following are the supported values for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp3</code>: 3,000-16,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io1</code>: 100-64,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io2</code>: 100-64,000 IOPS
* </p>
* </li>
* </ul>
* <p>
* Default: The existing value is retained if you keep the same volume type. If you change the volume type to
* <code>io1</code>, <code>io2</code>, or <code>gp3</code>, the default is 3,000.
* </p>
*
* @return The target IOPS rate of the volume. This parameter is valid only for <code>gp3</code>, <code>io1</code>,
* and <code>io2</code> volumes.</p>
* <p>
* The following are the supported values for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp3</code>: 3,000-16,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io1</code>: 100-64,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io2</code>: 100-64,000 IOPS
* </p>
* </li>
* </ul>
* <p>
* Default: The existing value is retained if you keep the same volume type. If you change the volume type
* to <code>io1</code>, <code>io2</code>, or <code>gp3</code>, the default is 3,000.
*/
public Integer getIops() {
return this.iops;
}
/**
* <p>
* The target IOPS rate of the volume. This parameter is valid only for <code>gp3</code>, <code>io1</code>, and
* <code>io2</code> volumes.
* </p>
* <p>
* The following are the supported values for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp3</code>: 3,000-16,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io1</code>: 100-64,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io2</code>: 100-64,000 IOPS
* </p>
* </li>
* </ul>
* <p>
* Default: The existing value is retained if you keep the same volume type. If you change the volume type to
* <code>io1</code>, <code>io2</code>, or <code>gp3</code>, the default is 3,000.
* </p>
*
* @param iops
* The target IOPS rate of the volume. This parameter is valid only for <code>gp3</code>, <code>io1</code>,
* and <code>io2</code> volumes.</p>
* <p>
* The following are the supported values for each volume type:
* </p>
* <ul>
* <li>
* <p>
* <code>gp3</code>: 3,000-16,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io1</code>: 100-64,000 IOPS
* </p>
* </li>
* <li>
* <p>
* <code>io2</code>: 100-64,000 IOPS
* </p>
* </li>
* </ul>
* <p>
* Default: The existing value is retained if you keep the same volume type. If you change the volume type to
* <code>io1</code>, <code>io2</code>, or <code>gp3</code>, the default is 3,000.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyVolumeRequest withIops(Integer iops) {
setIops(iops);
return this;
}
/**
* <p>
* The target throughput of the volume, in MiB/s. This parameter is valid only for <code>gp3</code> volumes. The
* maximum value is 1,000.
* </p>
* <p>
* Default: The existing value is retained if the source and target volume type is <code>gp3</code>. Otherwise, the
* default value is 125.
* </p>
* <p>
* Valid Range: Minimum value of 125. Maximum value of 1000.
* </p>
*
* @param throughput
* The target throughput of the volume, in MiB/s. This parameter is valid only for <code>gp3</code> volumes.
* The maximum value is 1,000.</p>
* <p>
* Default: The existing value is retained if the source and target volume type is <code>gp3</code>.
* Otherwise, the default value is 125.
* </p>
* <p>
* Valid Range: Minimum value of 125. Maximum value of 1000.
*/
public void setThroughput(Integer throughput) {
this.throughput = throughput;
}
/**
* <p>
* The target throughput of the volume, in MiB/s. This parameter is valid only for <code>gp3</code> volumes. The
* maximum value is 1,000.
* </p>
* <p>
* Default: The existing value is retained if the source and target volume type is <code>gp3</code>. Otherwise, the
* default value is 125.
* </p>
* <p>
* Valid Range: Minimum value of 125. Maximum value of 1000.
* </p>
*
* @return The target throughput of the volume, in MiB/s. This parameter is valid only for <code>gp3</code> volumes.
* The maximum value is 1,000.</p>
* <p>
* Default: The existing value is retained if the source and target volume type is <code>gp3</code>.
* Otherwise, the default value is 125.
* </p>
* <p>
* Valid Range: Minimum value of 125. Maximum value of 1000.
*/
public Integer getThroughput() {
return this.throughput;
}
/**
* <p>
* The target throughput of the volume, in MiB/s. This parameter is valid only for <code>gp3</code> volumes. The
* maximum value is 1,000.
* </p>
* <p>
* Default: The existing value is retained if the source and target volume type is <code>gp3</code>. Otherwise, the
* default value is 125.
* </p>
* <p>
* Valid Range: Minimum value of 125. Maximum value of 1000.
* </p>
*
* @param throughput
* The target throughput of the volume, in MiB/s. This parameter is valid only for <code>gp3</code> volumes.
* The maximum value is 1,000.</p>
* <p>
* Default: The existing value is retained if the source and target volume type is <code>gp3</code>.
* Otherwise, the default value is 125.
* </p>
* <p>
* Valid Range: Minimum value of 125. Maximum value of 1000.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyVolumeRequest withThroughput(Integer throughput) {
setThroughput(throughput);
return this;
}
/**
* <p>
* Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up
* to 16 <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with <code>io1</code> and
* <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS Multi-Attach</a> in
* the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*
* @param multiAttachEnabled
* Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume
* to up to 16 <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with <code>io1</code>
* and <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS
* Multi-Attach</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
*/
public void setMultiAttachEnabled(Boolean multiAttachEnabled) {
this.multiAttachEnabled = multiAttachEnabled;
}
/**
* <p>
* Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up
* to 16 <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with <code>io1</code> and
* <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS Multi-Attach</a> in
* the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*
* @return Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the
* volume to up to 16 <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with
* <code>io1</code> and <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS
* Multi-Attach</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
*/
public Boolean getMultiAttachEnabled() {
return this.multiAttachEnabled;
}
/**
* <p>
* Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up
* to 16 <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with <code>io1</code> and
* <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS Multi-Attach</a> in
* the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*
* @param multiAttachEnabled
* Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume
* to up to 16 <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with <code>io1</code>
* and <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS
* Multi-Attach</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyVolumeRequest withMultiAttachEnabled(Boolean multiAttachEnabled) {
setMultiAttachEnabled(multiAttachEnabled);
return this;
}
/**
* <p>
* Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up
* to 16 <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with <code>io1</code> and
* <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS Multi-Attach</a> in
* the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*
* @return Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the
* volume to up to 16 <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances">
* Nitro-based instances</a> in the same Availability Zone. This parameter is supported with
* <code>io1</code> and <code>io2</code> volumes only. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html"> Amazon EBS
* Multi-Attach</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
*/
public Boolean isMultiAttachEnabled() {
return this.multiAttachEnabled;
}
/**
* This method is intended for internal use only. Returns the marshaled request configured with additional
* parameters to enable operation dry-run.
*/
@Override
public Request<ModifyVolumeRequest> getDryRunRequest() {
Request<ModifyVolumeRequest> request = new ModifyVolumeRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getVolumeId() != null)
sb.append("VolumeId: ").append(getVolumeId()).append(",");
if (getSize() != null)
sb.append("Size: ").append(getSize()).append(",");
if (getVolumeType() != null)
sb.append("VolumeType: ").append(getVolumeType()).append(",");
if (getIops() != null)
sb.append("Iops: ").append(getIops()).append(",");
if (getThroughput() != null)
sb.append("Throughput: ").append(getThroughput()).append(",");
if (getMultiAttachEnabled() != null)
sb.append("MultiAttachEnabled: ").append(getMultiAttachEnabled());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ModifyVolumeRequest == false)
return false;
ModifyVolumeRequest other = (ModifyVolumeRequest) obj;
if (other.getVolumeId() == null ^ this.getVolumeId() == null)
return false;
if (other.getVolumeId() != null && other.getVolumeId().equals(this.getVolumeId()) == false)
return false;
if (other.getSize() == null ^ this.getSize() == null)
return false;
if (other.getSize() != null && other.getSize().equals(this.getSize()) == false)
return false;
if (other.getVolumeType() == null ^ this.getVolumeType() == null)
return false;
if (other.getVolumeType() != null && other.getVolumeType().equals(this.getVolumeType()) == false)
return false;
if (other.getIops() == null ^ this.getIops() == null)
return false;
if (other.getIops() != null && other.getIops().equals(this.getIops()) == false)
return false;
if (other.getThroughput() == null ^ this.getThroughput() == null)
return false;
if (other.getThroughput() != null && other.getThroughput().equals(this.getThroughput()) == false)
return false;
if (other.getMultiAttachEnabled() == null ^ this.getMultiAttachEnabled() == null)
return false;
if (other.getMultiAttachEnabled() != null && other.getMultiAttachEnabled().equals(this.getMultiAttachEnabled()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getVolumeId() == null) ? 0 : getVolumeId().hashCode());
hashCode = prime * hashCode + ((getSize() == null) ? 0 : getSize().hashCode());
hashCode = prime * hashCode + ((getVolumeType() == null) ? 0 : getVolumeType().hashCode());
hashCode = prime * hashCode + ((getIops() == null) ? 0 : getIops().hashCode());
hashCode = prime * hashCode + ((getThroughput() == null) ? 0 : getThroughput().hashCode());
hashCode = prime * hashCode + ((getMultiAttachEnabled() == null) ? 0 : getMultiAttachEnabled().hashCode());
return hashCode;
}
@Override
public ModifyVolumeRequest clone() {
return (ModifyVolumeRequest) super.clone();
}
}
|
3e0150dbc770e54d652ed13370977f2708f9bb05 | 4,753 | java | Java | src/main/java/adris/altoclef/util/ItemTarget.java | Toyota-Supra/altoclef | dc7de3817a59292a8a35dea183812b94218726c1 | [
"MIT"
] | 2 | 2021-10-05T15:16:51.000Z | 2021-10-05T15:24:07.000Z | src/main/java/adris/altoclef/util/ItemTarget.java | Toyota-Supra/altoclef | dc7de3817a59292a8a35dea183812b94218726c1 | [
"MIT"
] | null | null | null | src/main/java/adris/altoclef/util/ItemTarget.java | Toyota-Supra/altoclef | dc7de3817a59292a8a35dea183812b94218726c1 | [
"MIT"
] | null | null | null | 30.273885 | 121 | 0.574795 | 552 | package adris.altoclef.util;
import adris.altoclef.Debug;
import adris.altoclef.TaskCatalogue;
import adris.altoclef.util.helpers.ItemHelper;
import net.minecraft.item.Item;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ItemTarget {
// Want to avoid int max to prevent overflow or something
private static final int BASICALLY_INFINITY = 99999999;
public static ItemTarget EMPTY = new ItemTarget(new Item[0], 0);
private Item[] _itemMatches;
private int _targetCount;
private String _catalogueName = null;
private boolean _infinite = false;
public ItemTarget(Item[] items, int targetCount) {
_itemMatches = items;
_targetCount = targetCount;
}
public ItemTarget(String catalogueName, int targetCount) {
if (catalogueName == null) return;
_catalogueName = catalogueName;
_itemMatches = TaskCatalogue.getItemMatches(catalogueName);
_targetCount = targetCount;
if (_itemMatches == null) {
Debug.logError("Invalid catalogue name for item target: \"" + catalogueName + "\". Something isn't robust!");
}
}
public ItemTarget(String catalogueName) {
this(catalogueName, BASICALLY_INFINITY);
_infinite = true;
}
public ItemTarget(Item item, int targetCount) {
this(new Item[]{item}, targetCount);
}
public ItemTarget(Item[] items) {
this(items, BASICALLY_INFINITY);
_infinite = true;
}
public ItemTarget(Item item) {
this(item, BASICALLY_INFINITY);
_infinite = true;
}
public ItemTarget(ItemTarget toCopy, int newCount) {
_itemMatches = new Item[toCopy._itemMatches.length];
System.arraycopy(toCopy._itemMatches, 0, _itemMatches, 0, toCopy._itemMatches.length);
_catalogueName = toCopy._catalogueName;
_targetCount = newCount;
_infinite = toCopy._infinite;
}
public static Item[] getMatches(ItemTarget... targets) {
Set<Item> result = new HashSet<>();
for (ItemTarget target : targets) {
result.addAll(Arrays.asList(target.getMatches()));
}
return result.toArray(Item[]::new);
}
public Item[] getMatches() {
return _itemMatches;
}
public int getTargetCount() {
return _targetCount;
}
public boolean matches(Item item) {
for (Item match : _itemMatches) {
if (match == null) continue;
if (match.equals(item)) return true;
}
return false;
}
public boolean isCatalogueItem() {
return _catalogueName != null;
}
public String getCatalogueName() {
return _catalogueName;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ItemTarget other) {
if (_infinite) {
if (!other._infinite) return false;
} else {
// Neither are infinite
if (_targetCount != other._targetCount) return false;
}
if ((other._itemMatches == null) != (_itemMatches == null)) return false;
boolean isNull = (other._itemMatches == null);
if (isNull) return true;
if (_itemMatches.length != other._itemMatches.length) return false;
for (int i = 0; i < _itemMatches.length; ++i) {
if (other._itemMatches[i] == null) {
if ((other._itemMatches[i] == null) != (_itemMatches[i] == null)) return false;
} else {
if (!other._itemMatches[i].equals(_itemMatches[i])) return false;
}
}
return true;
}
return false;
}
public boolean isEmpty() {
return _itemMatches == null || _itemMatches.length == 0;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
if (isEmpty()) {
result.append("(empty)");
} else if (isCatalogueItem()) {
result.append(_catalogueName);
} else {
result.append("[");
int counter = 0;
for (Item item : _itemMatches) {
if (item == null) {
result.append("(null??)");
} else {
result.append(ItemHelper.trimItemName(item.getTranslationKey()));
}
if (++counter != _itemMatches.length) {
result.append(",");
}
}
result.append("]");
}
if (!_infinite && !isEmpty()) {
result.append(" x ").append(_targetCount);
}
return result.toString();
}
}
|
3e0151b977a381ce4761e620bcad14f4ea0662bb | 1,186 | java | Java | concurrent-series/src/com/luren/day13/ConditionDemo04.java | mutolee/luren-java | f780b8468246aff185f1ef6396f727f2e45e5344 | [
"Apache-2.0"
] | null | null | null | concurrent-series/src/com/luren/day13/ConditionDemo04.java | mutolee/luren-java | f780b8468246aff185f1ef6396f727f2e45e5344 | [
"Apache-2.0"
] | null | null | null | concurrent-series/src/com/luren/day13/ConditionDemo04.java | mutolee/luren-java | f780b8468246aff185f1ef6396f727f2e45e5344 | [
"Apache-2.0"
] | null | null | null | 31.210526 | 97 | 0.571669 | 553 | package com.luren.day13;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Condition await() 超时自动返回 例子
*/
public class ConditionDemo04 {
static ReentrantLock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
public static void main(String[] args) throws InterruptedException {
Thrd t1 = new Thrd();
t1.start();
}
static class Thrd extends Thread {
@Override
public void run() {
lock.lock();
try {
System.out.println(System.currentTimeMillis() + ":" + this.getName() + ",start");
// 等待被唤醒,2 秒后,自动唤醒
boolean await = condition.await(2, TimeUnit.SECONDS);
System.out.println("等待状态:" + await);
System.out.println(System.currentTimeMillis() + ":" + this.getName() + ",end");
} catch (InterruptedException e) {
System.out.println("中断标识:" + this.isInterrupted());
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
|
3e0151bee253b1f706fe984b7144f34ba3a4736b | 1,224 | java | Java | src/leetcode/problems/_136SingleNumber.java | alparslansari/algorithm | 4fad99704f894fd33e0e01ab0ef2f6705b0d4638 | [
"MIT"
] | null | null | null | src/leetcode/problems/_136SingleNumber.java | alparslansari/algorithm | 4fad99704f894fd33e0e01ab0ef2f6705b0d4638 | [
"MIT"
] | null | null | null | src/leetcode/problems/_136SingleNumber.java | alparslansari/algorithm | 4fad99704f894fd33e0e01ab0ef2f6705b0d4638 | [
"MIT"
] | null | null | null | 26.608696 | 110 | 0.586601 | 554 | package leetcode.problems;
import java.util.HashMap;
/** 136. Single Number
* Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
* You must implement a solution with a linear runtime complexity and use only constant extra space.
*
* Example 1:
* Input: nums = [2,2,1]
* Output: 1
*
* Example 2:
* Input: nums = [4,1,2,1,2]
* Output: 4
*
* Example 3:
* Input: nums = [1]
* Output: 1
*/
public class _136SingleNumber {
public int singleNumber(int[] nums) {
HashMap<Integer, Integer> hashTable = new HashMap<>();
for(int num:nums)
hashTable.put(num,hashTable.getOrDefault(num,0)+1);
for(int num:nums)
if(hashTable.get(num)==1) return num;
return 0;
}
public int singleNumberV2(int[] nums) {
HashMap<Integer, Integer> hashTable = new HashMap<>();
for(int i=0;i<nums.length;i++)
if(!hashTable.containsKey(nums[i]))
hashTable.put(nums[i],1);
else
hashTable.put(nums[i],2);
for(int i=0;i<nums.length;i++)
if(hashTable.get(nums[i])!=2)
return nums[i];
return -1;
}
}
|
3e0151fd1000f0db81efde9dc25b61c19dc4a134 | 1,882 | java | Java | thelibrary-core/src/main/java/com/benfante/javacourse/thelibrary/application/model/Customer.java | Malex/thelibrary | 5c56b4748c2f3ad907e6efa12b10b11d45931269 | [
"Apache-2.0"
] | null | null | null | thelibrary-core/src/main/java/com/benfante/javacourse/thelibrary/application/model/Customer.java | Malex/thelibrary | 5c56b4748c2f3ad907e6efa12b10b11d45931269 | [
"Apache-2.0"
] | null | null | null | thelibrary-core/src/main/java/com/benfante/javacourse/thelibrary/application/model/Customer.java | Malex/thelibrary | 5c56b4748c2f3ad907e6efa12b10b11d45931269 | [
"Apache-2.0"
] | null | null | null | 21.386364 | 80 | 0.734857 | 555 | package com.benfante.javacourse.thelibrary.application.model;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import com.benfante.javacourse.thelibrary.core.model.Address;
import com.benfante.javacourse.thelibrary.core.model.FullName;
@Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@OneToOne(cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinColumn(unique=true)
@Column(nullable=false)
private FullName name;
private Byte age;
@Column(length=16, nullable=false)
private String taxCode;
@Embedded
private Address address;
private List<Address> additionalAddresses = new LinkedList<>();
public FullName getName() {
return name;
}
public void setName(FullName name) {
this.name = name;
}
public byte getAge() {
return age;
}
public void setAge(byte age) {
this.age = age;
}
public String getTaxCode() {
return taxCode;
}
public void setTaxCode(String taxCode) {
this.taxCode = taxCode;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Address> getAdditionalAddresses() {
return additionalAddresses;
}
public void setAdditionalAddresses(List<Address> additionalAddresses) {
this.additionalAddresses = additionalAddresses;
}
}
|
3e015367d71dd5efc04fecda8e8e1cfadb4eea8e | 797 | java | Java | wk-app/wk-nb-service-sys/src/main/java/cn/wizzer/app/sys/modules/services/impl/SysConfigServiceImpl.java | dingmike/nutwxProject | 0a8004054ac3e992c5130a44a654293e41bc1e74 | [
"Apache-2.0"
] | 2 | 2020-04-18T06:10:46.000Z | 2020-05-09T13:52:36.000Z | wk-app/wk-nb-service-sys/src/main/java/cn/wizzer/app/sys/modules/services/impl/SysConfigServiceImpl.java | dingmike/nutwxProject | 0a8004054ac3e992c5130a44a654293e41bc1e74 | [
"Apache-2.0"
] | 9 | 2020-03-04T23:19:03.000Z | 2022-02-16T00:59:37.000Z | wk-app/wk-nb-service-sys/src/main/java/cn/wizzer/app/sys/modules/services/impl/SysConfigServiceImpl.java | dingmike/nutwxProject | 0a8004054ac3e992c5130a44a654293e41bc1e74 | [
"Apache-2.0"
] | 1 | 2017-12-27T10:57:39.000Z | 2017-12-27T10:57:39.000Z | 30.653846 | 99 | 0.755332 | 556 | package cn.wizzer.app.sys.modules.services.impl;
import cn.wizzer.app.sys.modules.models.Sys_config;
import cn.wizzer.app.sys.modules.services.SysConfigService;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import com.alibaba.dubbo.config.annotation.Service;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import java.util.List;
/**
* Created by wizzer on 2016/12/23.
*/
@IocBean(args = {"refer:dao"})
@Service(interfaceClass=SysConfigService.class)
public class SysConfigServiceImpl extends BaseServiceImpl<Sys_config> implements SysConfigService {
public SysConfigServiceImpl(Dao dao) {
super(dao);
}
public List<Sys_config> getAllList() {
return this.query(Cnd.where("delFlag", "=", false));
}
} |
3e015434e051a031a1376cd74ffbfdeafe20cedd | 267 | java | Java | src/com/reason/lang/core/psi/PsiFunctionCallParams.java | samdfonseca/reasonml-idea-plugin | a3cb65f2b60aaeacb307b458d1838dad185458d3 | [
"MIT"
] | null | null | null | src/com/reason/lang/core/psi/PsiFunctionCallParams.java | samdfonseca/reasonml-idea-plugin | a3cb65f2b60aaeacb307b458d1838dad185458d3 | [
"MIT"
] | null | null | null | src/com/reason/lang/core/psi/PsiFunctionCallParams.java | samdfonseca/reasonml-idea-plugin | a3cb65f2b60aaeacb307b458d1838dad185458d3 | [
"MIT"
] | null | null | null | 22.25 | 59 | 0.801498 | 557 | package com.reason.lang.core.psi;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public interface PsiFunctionCallParams extends PsiElement {
@NotNull
Collection<PsiElement> getParametersList();
}
|
3e015640d6c81689c10e63b194f043b8f27a231f | 2,087 | java | Java | src/net/minecraft/world/gen/layer/IntCache.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 5 | 2022-02-04T12:57:17.000Z | 2022-03-26T16:12:16.000Z | src/net/minecraft/world/gen/layer/IntCache.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 2 | 2022-02-25T20:10:14.000Z | 2022-03-03T14:25:03.000Z | src/net/minecraft/world/gen/layer/IntCache.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 1 | 2021-11-28T09:59:55.000Z | 2021-11-28T09:59:55.000Z | 34.213115 | 177 | 0.626258 | 558 | package net.minecraft.world.gen.layer;
import com.google.common.collect.Lists;
import java.util.List;
public class IntCache {
private static int intCacheSize = 256;
private static List freeSmallArrays = Lists.newArrayList();
private static List inUseSmallArrays = Lists.newArrayList();
private static List freeLargeArrays = Lists.newArrayList();
private static List inUseLargeArrays = Lists.newArrayList();
public static synchronized int[] getIntCache(int var0) {
if(var0 <= 256) {
if(freeSmallArrays.isEmpty()) {
int[] var5 = new int[256];
inUseSmallArrays.add(var5);
return var5;
} else {
int[] var4 = (int[])((int[])freeSmallArrays.remove(freeSmallArrays.size() - 1));
inUseSmallArrays.add(var4);
return var4;
}
} else if(var0 > intCacheSize) {
intCacheSize = var0;
freeLargeArrays.clear();
inUseLargeArrays.clear();
int[] var3 = new int[intCacheSize];
inUseLargeArrays.add(var3);
return var3;
} else if(freeLargeArrays.isEmpty()) {
int[] var2 = new int[intCacheSize];
inUseLargeArrays.add(var2);
return var2;
} else {
int[] var1 = (int[])((int[])freeLargeArrays.remove(freeLargeArrays.size() - 1));
inUseLargeArrays.add(var1);
return var1;
}
}
public static synchronized void resetIntCache() {
if(!freeLargeArrays.isEmpty()) {
freeLargeArrays.remove(freeLargeArrays.size() - 1);
}
if(!freeSmallArrays.isEmpty()) {
freeSmallArrays.remove(freeSmallArrays.size() - 1);
}
freeLargeArrays.addAll(inUseLargeArrays);
freeSmallArrays.addAll(inUseSmallArrays);
inUseLargeArrays.clear();
inUseSmallArrays.clear();
}
public static synchronized String getCacheSizes() {
return "cache: " + freeLargeArrays.size() + ", tcache: " + freeSmallArrays.size() + ", allocated: " + inUseLargeArrays.size() + ", tallocated: " + inUseSmallArrays.size();
}
}
|
3e015780f091e57ab44ef1d21a62b42179a5abbb | 489 | java | Java | Contacts_component/src/main/java/com/it/yk/contacts_component/di/component/AddFriendsComponent.java | yangkun19921001/FWX_Component_Project | 856505ae45ef8e78602c13bcf1c4a6f4abc04730 | [
"Apache-2.0"
] | 4 | 2018-10-29T03:38:36.000Z | 2020-03-23T03:09:31.000Z | Contacts_component/src/main/java/com/it/yk/contacts_component/di/component/AddFriendsComponent.java | yangkun19921001/FWX_Component_Project | 856505ae45ef8e78602c13bcf1c4a6f4abc04730 | [
"Apache-2.0"
] | 1 | 2020-12-11T15:38:05.000Z | 2020-12-11T15:38:05.000Z | Contacts_component/src/main/java/com/it/yk/contacts_component/di/component/AddFriendsComponent.java | yangkun19921001/FWX_Component_Project | 856505ae45ef8e78602c13bcf1c4a6f4abc04730 | [
"Apache-2.0"
] | 3 | 2020-03-13T01:00:29.000Z | 2022-02-25T09:57:55.000Z | 34.928571 | 79 | 0.832311 | 559 | package com.it.yk.contacts_component.di.component;
import com.it.yk.contacts_component.di.module.AddFriendsModule;
import com.it.yk.contacts_component.mvp.ui.activity.AddFriendsActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.di.scope.ActivityScope;
import dagger.Component;
@ActivityScope
@Component(modules = AddFriendsModule.class, dependencies = AppComponent.class)
public interface AddFriendsComponent {
void inject(AddFriendsActivity activity);
} |
3e0157863f5f09cfcbc8910e8d15889fdf608e0c | 470 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/NavigationHelper.java | tsipurinda-s/swt_java_course | 5d01f36bca97be03960ed7f63620350c8e5852d9 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/NavigationHelper.java | tsipurinda-s/swt_java_course | 5d01f36bca97be03960ed7f63620350c8e5852d9 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/NavigationHelper.java | tsipurinda-s/swt_java_course | 5d01f36bca97be03960ed7f63620350c8e5852d9 | [
"Apache-2.0"
] | 1 | 2021-12-02T16:35:02.000Z | 2021-12-02T16:35:02.000Z | 16.785714 | 49 | 0.638298 | 560 | package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class NavigationHelper extends HelperBase{
public NavigationHelper(WebDriver wd) {
super(wd);
}
public void groupPage() {
click(By.linkText("groups"));
}
public void contactPage() {
click(By.linkText("add new"));
}
public void homePage() {
click(By.cssSelector("#logo"));
}
}
|
3e0158109ef17868602b82bfdc565de30107f44d | 92 | java | Java | backend/src/main/java/com/purini/common/Views.java | univermal/webflux-mongodb-react-starter | 09bff716af0d8d82432db3c12891547dbdbc45df | [
"Apache-2.0"
] | null | null | null | backend/src/main/java/com/purini/common/Views.java | univermal/webflux-mongodb-react-starter | 09bff716af0d8d82432db3c12891547dbdbc45df | [
"Apache-2.0"
] | null | null | null | backend/src/main/java/com/purini/common/Views.java | univermal/webflux-mongodb-react-starter | 09bff716af0d8d82432db3c12891547dbdbc45df | [
"Apache-2.0"
] | null | null | null | 10.222222 | 32 | 0.663043 | 561 | package com.purini.common;
public class Views {
public static class Public {
}
}
|
3e0158bf54d264ef11c0d381bcc3f378fd88a33d | 294 | java | Java | mobile_app1/module1022/src/main/java/module1022packageJava0/Foo97.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 70 | 2021-01-22T16:48:06.000Z | 2022-02-16T10:37:33.000Z | mobile_app1/module1022/src/main/java/module1022packageJava0/Foo97.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 16 | 2021-01-22T20:52:52.000Z | 2021-08-09T17:51:24.000Z | mobile_app1/module1022/src/main/java/module1022packageJava0/Foo97.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 5 | 2021-01-26T13:53:49.000Z | 2021-08-11T20:10:57.000Z | 12.25 | 46 | 0.608844 | 562 | package module1022packageJava0;
import java.lang.Integer;
public class Foo97 {
Integer int0;
public void foo0() {
new module1022packageJava0.Foo96().foo3();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
}
|
3e015b8fe2b0fa8a8ec70fbbdd1e4165f510a6a4 | 688 | java | Java | src/main/java/com/flat/view/settings/scene/pane/children/selection/apperance/appearancepane/previewpane/colorpane/bordercolorpane/children/BorderColorLabel.java | JoshuaCrotts/Formal-Logic-Aiding-Tool | 089c426686d57df652e2dcb698f5765a306c8d63 | [
"MIT"
] | null | null | null | src/main/java/com/flat/view/settings/scene/pane/children/selection/apperance/appearancepane/previewpane/colorpane/bordercolorpane/children/BorderColorLabel.java | JoshuaCrotts/Formal-Logic-Aiding-Tool | 089c426686d57df652e2dcb698f5765a306c8d63 | [
"MIT"
] | null | null | null | src/main/java/com/flat/view/settings/scene/pane/children/selection/apperance/appearancepane/previewpane/colorpane/bordercolorpane/children/BorderColorLabel.java | JoshuaCrotts/Formal-Logic-Aiding-Tool | 089c426686d57df652e2dcb698f5765a306c8d63 | [
"MIT"
] | 1 | 2021-11-18T19:32:19.000Z | 2021-11-18T19:32:19.000Z | 38.222222 | 133 | 0.790698 | 563 | package com.flat.view.settings.scene.pane.children.selection.apperance.appearancepane.previewpane.colorpane.bordercolorpane.children;
import com.flat.controller.Controller;
import com.flat.models.data.settings.tabs.appearance.content.ColorPane;
import javafx.scene.control.Label;
/**
* @author Christopher Brantley <anpch@example.com>
*/
public class BorderColorLabel extends Label {
public BorderColorLabel() {
super.textProperty().bind(Controller.MAPPED_TEXT.getValue(ColorPane.class, ColorPane.Keys.BORDER_COLOR).textProperty());
super.fontProperty().bind(Controller.MAPPED_TEXT.getValue(ColorPane.class, ColorPane.Keys.BORDER_COLOR).fontProperty());
}
} |
3e015c03890ddfa31a3faa3534456342952ef1ec | 210 | java | Java | src/main/java/net/chanrich/eachother/enums/UploadFileTypeEnum.java | ccczg/Eachother | b7e3989414700d9c3b8abaf2cf9f12fd2bf60252 | [
"MIT"
] | null | null | null | src/main/java/net/chanrich/eachother/enums/UploadFileTypeEnum.java | ccczg/Eachother | b7e3989414700d9c3b8abaf2cf9f12fd2bf60252 | [
"MIT"
] | 1 | 2022-01-28T09:22:09.000Z | 2022-01-28T09:22:09.000Z | src/main/java/net/chanrich/eachother/enums/UploadFileTypeEnum.java | ccczg/Eachother | b7e3989414700d9c3b8abaf2cf9f12fd2bf60252 | [
"MIT"
] | null | null | null | 17.5 | 37 | 0.704762 | 564 | package net.chanrich.eachother.enums;
/**
* @ClassName: UploadFileTypeEnum
* @Description: 上传文件类型
* @Author: Chanrich
* @CreateDate: 2021/12/9 14:32
* @Version: 1.0
*/
public enum UploadFileTypeEnum {
}
|
3e015c04eb2ad840acc882b94c3f61d974a4b901 | 5,607 | java | Java | build-scripts/net.osmand.translator/test/resources/net_osmand_osm/MapRoutingTypes.java | brownsys/android-app-modes-osmand | 3e971bd4b919122e12600d3f96de514eadf532fd | [
"MIT"
] | null | null | null | build-scripts/net.osmand.translator/test/resources/net_osmand_osm/MapRoutingTypes.java | brownsys/android-app-modes-osmand | 3e971bd4b919122e12600d3f96de514eadf532fd | [
"MIT"
] | null | null | null | build-scripts/net.osmand.translator/test/resources/net_osmand_osm/MapRoutingTypes.java | brownsys/android-app-modes-osmand | 3e971bd4b919122e12600d3f96de514eadf532fd | [
"MIT"
] | null | null | null | 25.256757 | 114 | 0.676119 | 565 | package net.osmand.osm;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TLongObjectHashMap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapRoutingTypes {
private static Set<String> TAGS_TO_SAVE = new HashSet<String>();
private static Set<String> TAGS_TO_ACCEPT = new HashSet<String>();
private static Set<String> TAGS_TEXT = new HashSet<String>();
private static char TAG_DELIMETER = '/'; //$NON-NLS-1$
static {
TAGS_TO_ACCEPT.add("highway");
TAGS_TO_ACCEPT.add("junction");
TAGS_TO_ACCEPT.add("cycleway");
TAGS_TO_ACCEPT.add("route");
// TEXT tags
TAGS_TEXT.add("int_ref");
TAGS_TEXT.add("ref");
TAGS_TEXT.add("name");
TAGS_TEXT.add("direction");
TAGS_TEXT.add("destination");
TAGS_TEXT.add("destination:lanes");
TAGS_TEXT.add("duration");
TAGS_TO_SAVE.add("agricultural");
TAGS_TO_SAVE.add("barrier");
TAGS_TO_SAVE.add("bicycle");
TAGS_TO_SAVE.add("boat");
TAGS_TO_SAVE.add("bridge");
TAGS_TO_SAVE.add("bus");
TAGS_TO_SAVE.add("construction");
TAGS_TO_SAVE.add("direction");
TAGS_TO_SAVE.add("ferry");
TAGS_TO_SAVE.add("foot");
TAGS_TO_SAVE.add("goods");
TAGS_TO_SAVE.add("hgv");
TAGS_TO_SAVE.add("horse");
TAGS_TO_SAVE.add("lanes");
TAGS_TO_SAVE.add("maxspeed");
TAGS_TO_SAVE.add("maxweight");
TAGS_TO_SAVE.add("minspeed");
TAGS_TO_SAVE.add("moped");
TAGS_TO_SAVE.add("motorboat");
TAGS_TO_SAVE.add("motorcar");
TAGS_TO_SAVE.add("motorcycle");
TAGS_TO_SAVE.add("motor_vehicle");
TAGS_TO_SAVE.add("oneway");
TAGS_TO_SAVE.add("roundabout");
TAGS_TO_SAVE.add("route");
TAGS_TO_SAVE.add("service");
TAGS_TO_SAVE.add("ship");
TAGS_TO_SAVE.add("toll");
TAGS_TO_SAVE.add("toll_booth");
TAGS_TO_SAVE.add("train");
TAGS_TO_SAVE.add("tracktype");
TAGS_TO_SAVE.add("traffic_calming");
TAGS_TO_SAVE.add("turn:lanes");
TAGS_TO_SAVE.add("turn");
TAGS_TO_SAVE.add("tunnel");
TAGS_TO_SAVE.add("railway");
}
private Map<String, MapRouteType> types = new LinkedHashMap<String, MapRoutingTypes.MapRouteType>();
private List<MapRouteType> listTypes = new ArrayList<MapRoutingTypes.MapRouteType>();
public static String constructRuleKey(String tag, String val) {
if(val == null || val.length() == 0){
return tag;
}
return tag + TAG_DELIMETER + val;
}
protected static String getTagKey(String tagValue) {
int i = tagValue.indexOf(TAG_DELIMETER);
if(i >= 0){
return tagValue.substring(0, i);
}
return tagValue;
}
protected static String getValueKey(String tagValue) {
int i = tagValue.indexOf(TAG_DELIMETER);
if(i >= 0){
return tagValue.substring(i + 1);
}
return null;
}
private boolean contains(Set<String> s, String tag, String value) {
if(s.contains(tag) || s.contains(tag + TAG_DELIMETER + value)){
return true;
}
return false;
}
public boolean encodeEntity(Way et, TIntArrayList outTypes, Map<MapRouteType, String> names){
Way e = (Way) et;
boolean init = false;
for(Entry<String, String> es : e.getTags().entrySet()) {
String tag = es.getKey();
String value = es.getValue();
if (contains(TAGS_TO_ACCEPT, tag, value)) {
init = true;
break;
}
}
if(!init) {
return false;
}
outTypes.clear();
names.clear();
for(Entry<String, String> es : e.getTags().entrySet()) {
String tag = es.getKey();
String value = converBooleanValue(es.getValue());
if(contains(TAGS_TO_ACCEPT, tag, value) || contains(TAGS_TO_SAVE, tag, value) || tag.startsWith("access")) {
outTypes.add(registerRule(tag, value).id);
}
if(TAGS_TEXT.contains(tag)) {
names.put(registerRule(tag, null), value);
}
}
return true;
}
private String converBooleanValue(String value){
if(value.equals("true")) {
return "yes";
} else if(value.equals("false")) {
return "no";
}
return value;
}
public void encodePointTypes(Way e, TLongObjectHashMap<TIntArrayList> pointTypes){
pointTypes.clear();
for(Node nd : e.getNodes() ) {
if (nd != null) {
for (Entry<String, String> es : nd.getTags().entrySet()) {
String tag = es.getKey();
String value = converBooleanValue(es.getValue());
if (contains(TAGS_TO_ACCEPT, tag, value) || contains(TAGS_TO_SAVE, tag, value) || tag.startsWith("access")) {
if (!pointTypes.containsKey(nd.getId())) {
pointTypes.put(nd.getId(), new TIntArrayList());
}
pointTypes.get(nd.getId()).add(registerRule(tag, value).id);
}
}
}
}
}
public MapRouteType getTypeByInternalId(int id) {
return listTypes.get(id - 1);
}
private MapRouteType registerRule(String tag, String val) {
String id = constructRuleKey(tag, val);
if(!types.containsKey(id)) {
MapRouteType rt = new MapRouteType();
// first one is always 1
rt.id = types.size() + 1;
rt.tag = tag;
rt.value = val;
types.put(id, rt);
listTypes.add(rt);
}
MapRouteType type = types.get(id);
type.freq ++;
return type;
}
public static class MapRouteType {
int freq = 0;
int id;
int targetId;
String tag;
String value;
public int getInternalId() {
return id;
}
public int getFreq() {
return freq;
}
public int getTargetId() {
return targetId;
}
public String getTag() {
return tag;
}
public String getValue() {
return value;
}
public void setTargetId(int targetId) {
this.targetId = targetId;
}
}
public List<MapRouteType> getEncodingRuleTypes() {
return listTypes;
}
}
|
3e015c4ec4cb58d669402e6d442af605edbe4015 | 13,271 | java | Java | src/main/java/org/spigotmc/builder/Utils.java | SpraxDev/Spigot-BuildTools | 27ce530b9abe168ac2e17618abfdae2bac5d83f4 | [
"BSD-3-Clause"
] | 2 | 2021-03-18T09:05:27.000Z | 2021-12-15T22:32:13.000Z | src/main/java/org/spigotmc/builder/Utils.java | SpraxDev/Spigot-BuildTools | 27ce530b9abe168ac2e17618abfdae2bac5d83f4 | [
"BSD-3-Clause"
] | 10 | 2020-10-20T20:28:54.000Z | 2021-06-14T05:48:43.000Z | src/main/java/org/spigotmc/builder/Utils.java | SpraxDev/Spigot-BuildTools | 27ce530b9abe168ac2e17618abfdae2bac5d83f4 | [
"BSD-3-Clause"
] | null | null | null | 40.215152 | 153 | 0.626479 | 566 | package org.spigotmc.builder;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.IOUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.transport.FetchResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Utils {
private static final byte[] HEX_ARRAY = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII);
public static String httpGet(@NotNull String url) throws IOException {
URLConnection con = new URL(url).openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
try (InputStream in = con.getInputStream()) {
return IOUtils.toString(in, StandardCharsets.UTF_8);
}
}
public static void downloadFile(@NotNull String url, @NotNull File dest, @Nullable HashAlgo hashAlgo, @Nullable String goodHash) throws IOException {
if (hashAlgo != null && goodHash == null) {
hashAlgo = null;
}
System.out.println("Downloading '" + url + "' to '" + dest.toString() + "'...");
byte[] data = IOUtils.toByteArray(new URL(url));
String dataHash = hashAlgo != null ? hashAlgo.getHash(data) : null;
if (dataHash != null && !dataHash.equalsIgnoreCase(goodHash)) {
throw new IllegalStateException("File at '" + url + "' did not match the expected " + hashAlgo.getAlgorithm()
+ " (Expected: " + goodHash + ")");
}
System.out.println("Successfully downloaded '" + url + "'" +
(hashAlgo != null ? " (" + hashAlgo.getAlgorithm() + ": " + dataHash + ")" : ""));
Files.createDirectories(dest.getParentFile().toPath());
try (FileOutputStream out = new FileOutputStream(dest)) {
IOUtils.write(data, out);
}
}
public static void extractZip(@NotNull File zipFile, @NotNull File targetFolder, @Nullable Predicate<String> filter) throws IOException {
System.out.println("Extracting '" + zipFile.getAbsolutePath() + "' to '" + targetFolder.getAbsolutePath() + "'...");
Path targetPath = targetFolder.getAbsoluteFile().toPath().normalize();
Files.createDirectories(targetPath);
try (ZipFile zip = new ZipFile(zipFile)) {
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = entries.nextElement();
if (filter != null && !filter.test(entry.getName())) {
continue;
}
File outFile = targetPath.resolve(entry.getName()).toFile();
if (!outFile.toPath().normalize().startsWith(targetPath))
throw new IllegalStateException("Bad zip entry(=" + entry.getName() + ") - malicious archive?"); // e.g. containing '..'
if (entry.isDirectory()) {
Files.createDirectories(outFile.toPath());
continue;
}
if (outFile.getParentFile() != null) {
Files.createDirectories(outFile.getParentFile().toPath());
}
try (InputStream is = zip.getInputStream(entry);
OutputStream os = new FileOutputStream(outFile)) {
IOUtils.copy(is, os);
}
System.out.println("Extracted " + targetPath.relativize(outFile.toPath()).toString());
}
}
}
public static boolean doesCommandFail(@NotNull File workingDir, @NotNull String cmd, @Nullable String... args) {
try {
return runCommand(workingDir, cmd, args) != 0;
} catch (IOException ignore) {
}
return true;
}
public static int runCommand(@NotNull File workingDir, @NotNull String cmd, @Nullable String... args) throws IOException {
CommandLine cmdLine = new CommandLine(cmd);
for (String arg : args) {
if (arg != null && !arg.isEmpty()) {
cmdLine.addArgument(arg);
}
}
DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(workingDir);
executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
Map<String, String> env = new HashMap<>(System.getenv());
env.put("JAVA_HOME", System.getProperty("java.home"));
if (!env.containsKey("MAVEN_OPTS")) {
env.put("MAVEN_OPTS", "-Xmx1G");
}
if (!env.containsKey("_JAVA_OPTIONS")) {
StringBuilder javaOptions = new StringBuilder("-Djdk.net.URLClassPath.disableClassPathURLCheck=true");
for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
if (arg.startsWith("-Xmx")) {
javaOptions.append(" ")
.append(arg);
}
}
env.put("_JAVA_OPTIONS", javaOptions.toString());
}
return executor.execute(cmdLine, env);
}
/**
* This is an alias for:
* <p>
* {@code runTasksMultiThreaded(Math.max(2, Runtime.getRuntime().availableProcessors()), tasks)}
*
* @see #runTasksMultiThreaded(int, MultiThreadedTask...)
*/
public static int runTasksMultiThreaded(MultiThreadedTask... tasks) throws Exception {
return runTasksMultiThreaded(Math.max(2, Runtime.getRuntime().availableProcessors()), tasks);
}
/**
* Runs the given tasks in multiple threads and blocks the calling
* thread until all the tasks have been executed or aborts
* <p>
* If a task throws an {@link Exception}, this method will throw it
* after all the other tasks finished (only from the last task throwing one!).
*
* @param threadCount The amount of threads to use for this task (uses {@code Math.min(threadCount, tasks.length)})
* @param tasks The tasks to be executed
*
* @return {@code 0} if all tasks ran successfully, else the status code of the last failed task
*
* @throws Exception The Exception thrown by the last last task throwing one
* @throws IllegalStateException If {@code tasks.length == 0}
*/
public static int runTasksMultiThreaded(int threadCount, MultiThreadedTask... tasks) throws Exception {
if (threadCount <= 0) throw new IllegalArgumentException("threadCount needs to be larger than 0");
if (tasks.length == 0) throw new IllegalArgumentException("You have to provide tasks to execute");
ExecutorService pool = Executors.newFixedThreadPool(Math.min(threadCount, tasks.length));
AtomicInteger statusCode = new AtomicInteger();
AtomicReference<Exception> exception = new AtomicReference<>();
for (MultiThreadedTask task : tasks) {
pool.execute(() -> {
try {
int result = task.runTask();
if (result != 0) {
statusCode.set(result);
}
} catch (Exception ex) {
exception.set(ex);
}
});
}
pool.shutdown();
pool.awaitTermination(60, TimeUnit.MINUTES); // This *should* not be exceeded and Long.MAX_VALUE seems overkill
// Making sure there won't be any buggy/unwanted threads left
if (!pool.shutdownNow().isEmpty()) {
throw new IllegalStateException("There are still tasks in the queue after 1 hour of execution... This doesn't look right");
}
if (exception.get() != null) {
throw exception.get();
}
return statusCode.get();
}
public static void gitClone(@NotNull String url, @NotNull File target, boolean autoCRLF) throws GitAPIException, IOException {
System.out.println("Cloning git repository '" + url + "' to '" + target.toString() + "'");
try (Git result = Git.cloneRepository().setURI(url).setDirectory(target).call()) {
StoredConfig config = result.getRepository().getConfig();
config.setBoolean("core", null, "autocrlf", autoCRLF);
config.save();
System.out.println("Successfully cloned '" + url + "' (HEAD: " + getCurrGitHeadHash(result) + ")");
}
}
public static boolean gitPull(@NotNull Git repo, @NotNull String ref) throws GitAPIException {
System.out.println("Pulling updates for '" + repo.getRepository().getDirectory().toString() + "'");
try {
repo.reset().setRef("origin/master").setMode(ResetCommand.ResetType.HARD).call();
} catch (JGitInternalException ex) {
System.err.println("*** Warning, could not find origin/master ref, but continuing anyway.");
System.err.println("*** If further errors occur, delete '" + repo.getRepository().getDirectory().getParent() + "' and retry.");
}
FetchResult result = repo.fetch().call();
System.out.println("Successfully fetched updates for '" + repo.getRepository().getDirectory().toString() + "'");
repo.reset().setRef(ref).setMode(ResetCommand.ResetType.HARD).call();
if (ref.equals("master")) {
repo.reset().setRef("origin/master").setMode(ResetCommand.ResetType.HARD).call();
}
System.out.println("Checked out '" + ref + "' for '" + repo.getRepository().getDirectory().toString() + "'");
// Return true if fetch changed any tracking refs.
return !result.getTrackingRefUpdates().isEmpty();
}
public static String getCurrGitHeadHash(Git repo) throws GitAPIException {
return repo.log().setMaxCount(1).call().iterator().next().getName();
}
public static String toHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; ++j) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
/**
* This globally disables certificate checking
* https://stackoverflow.com/a/26448998/9346616
*
* @throws NoSuchAlgorithmException Thrown by {@link SSLContext#getInstance(String)} with {@code protocol = "SSL"}
* @throws KeyManagementException Thrown by {@link SSLContext#init(KeyManager[], TrustManager[], SecureRandom)}
*/
public static void disableHttpsCertificateChecks() throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Trust SSL certs
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Trust host names
HostnameVerifier allHostsValid = (hostname, session) -> true;
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
public interface MultiThreadedTask {
/**
* @return A numeric status code (e.g. exit code)
*
* @throws Exception An exception that may be thrown by the task
*/
int runTask() throws Exception;
}
} |
3e015c79c4d3d3b4081e60955e5c6c52521b2c9a | 857 | java | Java | src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetReducer.java | DataBiosphere/consent | 9a0e2daa6dc35c2cc344e40aa8a76e164151bad5 | [
"BSD-3-Clause"
] | 4 | 2018-06-28T05:49:42.000Z | 2021-07-26T17:24:13.000Z | src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetReducer.java | DataBiosphere/consent | 9a0e2daa6dc35c2cc344e40aa8a76e164151bad5 | [
"BSD-3-Clause"
] | 415 | 2018-01-17T20:04:59.000Z | 2022-03-31T10:04:40.000Z | src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetReducer.java | DataBiosphere/consent | 9a0e2daa6dc35c2cc344e40aa8a76e164151bad5 | [
"BSD-3-Clause"
] | 3 | 2018-04-23T16:40:24.000Z | 2019-09-30T14:46:50.000Z | 30.607143 | 82 | 0.71762 | 567 | package org.broadinstitute.consent.http.db.mapper;
import org.broadinstitute.consent.http.models.DataSet;
import org.broadinstitute.consent.http.models.DataUse;
import org.jdbi.v3.core.result.LinkedHashMapRowReducer;
import org.jdbi.v3.core.result.RowView;
import java.util.Objects;
import java.util.Map;
public class DatasetReducer implements LinkedHashMapRowReducer<Integer, DataSet> {
@Override
public void accumulate(Map<Integer, DataSet> map, RowView rowView) {
DataSet dataset = map.computeIfAbsent(
rowView.getColumn("datasetid", Integer.class),
id -> rowView.getRow(DataSet.class));
if(Objects.nonNull(rowView.getColumn("datause", String.class))) {
dataset.setDataUse(
DataUse.parseDataUse(
rowView.getColumn("datause", String.class)
).orElse(null)
);
}
}
}
|
3e015d57975c587b66564f0de570392441166525 | 15,439 | java | Java | app/src/main/java/com/kcrason/highperformancefriendscircle/widgets/HorizontalEmojiIndicators.java | zhinengjiqishidai/wechat | d1cd9b1963e98fc47cc963afdf3d6f9fc3bd1094 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/kcrason/highperformancefriendscircle/widgets/HorizontalEmojiIndicators.java | zhinengjiqishidai/wechat | d1cd9b1963e98fc47cc963afdf3d6f9fc3bd1094 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/kcrason/highperformancefriendscircle/widgets/HorizontalEmojiIndicators.java | zhinengjiqishidai/wechat | d1cd9b1963e98fc47cc963afdf3d6f9fc3bd1094 | [
"Apache-2.0"
] | null | null | null | 34.616592 | 169 | 0.631647 | 568 | package com.kcrason.highperformancefriendscircle.widgets;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.kcrason.highperformancefriendscircle.R;
import com.kcrason.highperformancefriendscircle.beans.emoji.EmojiIndicatorInfo;
import com.kcrason.highperformancefriendscircle.beans.emoji.EmojiPanelBean;
import com.kcrason.highperformancefriendscircle.utils.Utils;
import java.util.List;
public class HorizontalEmojiIndicators extends LinearLayout implements ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
/**
* 表情的总页数
*/
private List<EmojiPanelBean> mEmojiPanelBeans;
/**
* 表情面板View
*/
private EmojiPanelView mEmojiPanelView;
/**
* 显示表情的adapter
*/
private PagerAdapter mPagerAdapter;
/**
* 内部指示器
*/
private LinearLayout mInnerIndicatorParentView;
/**
* 外部指示器
*/
private LinearLayout mOutIndicatorParentView;
/**
* 用于保存外部指示器的ViewPager position和外部指示器index的对应关系。
*/
private SparseArray<EmojiIndicatorInfo> mOutInfoSparseArray = new SparseArray<>();
/**
* 用于保存内部指示器的ViewPager position和外部指示器index的对应关系。
*/
private SparseArray<EmojiIndicatorInfo> mInnerInfoSparseArray = new SparseArray<>();
/**
* 用于保存内部指示器的位置。使得点击切换时可以定位到响应的位置
* key:emojiType(emoji的类型)
* value:当前这一类型下的索引
*/
private SparseIntArray mOutIndicatorLastPosition = new SparseIntArray();
public HorizontalEmojiIndicators(Context context) {
super(context);
init();
}
public HorizontalEmojiIndicators(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public HorizontalEmojiIndicators(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOrientation(VERTICAL);
addView(mInnerIndicatorParentView = createIndicatorParentView(true));
addView(mOutIndicatorParentView = createIndicatorParentView(false));
}
public HorizontalEmojiIndicators setViewPager(ViewPager viewPager) {
if (viewPager == null) {
throw new NullPointerException("viewpager my be null");
}
mViewPager = viewPager;
mPagerAdapter = viewPager.getAdapter();
if (mPagerAdapter == null) {
throw new NullPointerException("pageradapter my be null");
}
viewPager.addOnPageChangeListener(this);
return this;
}
public HorizontalEmojiIndicators setEmojiPanelView(EmojiPanelView emojiPanelView) {
mEmojiPanelView = emojiPanelView;
return this;
}
public HorizontalEmojiIndicators setEmojiPanelBeans(List<EmojiPanelBean> emojiPanelBeans) {
if (emojiPanelBeans != null && emojiPanelBeans.size() > 0) {
mEmojiPanelBeans = emojiPanelBeans;
}
return this;
}
public void build() {
if (mEmojiPanelBeans != null && mEmojiPanelBeans.size() > 0) {
createInnerIndicator(mEmojiPanelBeans.get(0).getMaxPage(), mEmojiPanelBeans.get(0).getEmojiType());
generateInnerPositinInfo();
generateOutPositionInfo();
}
createOutIndicator(mEmojiPanelView.getEmojiTypeSize());
}
private LinearLayout createIndicatorParentView(boolean isInnerIndicator) {
LinearLayout indicatorParentView = new LinearLayout(getContext());
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dp2px(44f));
if (isInnerIndicator) {
indicatorParentView.setGravity(Gravity.CENTER);
indicatorParentView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.base_F2F2F2));
} else {
indicatorParentView.setGravity(Gravity.CENTER_VERTICAL);
indicatorParentView.setBackgroundColor(Color.WHITE);
}
indicatorParentView.setLayoutParams(params);
return indicatorParentView;
}
private void createInnerIndicator(int itemCount, int emojiType) {
if (mInnerIndicatorParentView == null) {
mInnerIndicatorParentView = createIndicatorParentView(true);
mInnerIndicatorParentView.removeAllViews();
addInnerIndicatorItemView(mInnerIndicatorParentView, itemCount, emojiType);
addView(mInnerIndicatorParentView);
} else {
mInnerIndicatorParentView.removeAllViews();
addInnerIndicatorItemView(mInnerIndicatorParentView, itemCount, emojiType);
}
}
private void createOutIndicator(int newViewCount) {
if (mOutIndicatorParentView == null) {
mOutIndicatorParentView = createIndicatorParentView(false);
mOutIndicatorParentView.removeAllViews();
addOutIndcatorItemView(mOutIndicatorParentView, newViewCount);
addView(mOutIndicatorParentView);
} else {
mOutIndicatorParentView.removeAllViews();
addOutIndcatorItemView(mOutIndicatorParentView, newViewCount);
}
}
/**
* 移除多余的View
*
* @param parentView
* @param oldViewCount
* @param newViewCount
*/
private void removeSurplusViews(LinearLayout parentView, int oldViewCount, int newViewCount) {
if (oldViewCount > newViewCount) {
parentView.removeViews(newViewCount, oldViewCount - newViewCount);
}
}
/**
* 创建并加入外部指示器的itemView
*
* @param parentView
* @param newViewCount
*/
private void addOutIndcatorItemView(LinearLayout parentView, int newViewCount) {
int oldViewCount = parentView.getChildCount();
removeSurplusViews(parentView, oldViewCount, newViewCount);
for (int i = 0; i < newViewCount; i++) {
boolean hasChild = i < oldViewCount;
View childView = hasChild ? parentView.getChildAt(i) : null;
if (childView == null) {
final int index = i;
ImageView itemView = createOutImageView(i);
itemView.setOnClickListener(v -> switchOutIndicatorToTargetPosition(index));
mOutIndicatorParentView.addView(itemView);
}
}
}
/**
* 创建并加入内部指示器的itemView
*
* @param parentView
* @param newViewCount
* @param emjiType
*/
private void addInnerIndicatorItemView(LinearLayout parentView, int newViewCount, int emjiType) {
int oldViewCount = parentView.getChildCount();
removeSurplusViews(parentView, oldViewCount, newViewCount);
for (int i = 0; i < newViewCount; i++) {
boolean hasChild = i < oldViewCount;
View childView = hasChild ? parentView.getChildAt(i) : null;
if (childView == null) {
final int index = i;
ImageView itemView = createInnerImageView(i);
itemView.setOnClickListener(v -> switchInnerIndicatorToTargetPosition(index, emjiType));
mInnerIndicatorParentView.addView(itemView);
}
}
}
/**
* 点击内部指示器时切换到指定页面
*
* @param index
* @param emojiType
*/
private void switchInnerIndicatorToTargetPosition(int index, int emojiType) {
for (int i = 0; i < mInnerInfoSparseArray.size(); i++) {
EmojiIndicatorInfo innerInfo = mInnerInfoSparseArray.get(i);
if (innerInfo.getIndicatorIndex() == index && innerInfo.getEmojiType() == emojiType) {
int keyValue = mInnerInfoSparseArray.keyAt(i);
mViewPager.setCurrentItem(keyValue);
break;
}
}
}
/**
* 点击外部指示器时切换到指定页面
*
* @param index
*/
private void switchOutIndicatorToTargetPosition(int index) {
for (int i = 0; i < mOutInfoSparseArray.size(); i++) {
EmojiIndicatorInfo emojiIndicatorInfo = mOutInfoSparseArray.get(i);
if (emojiIndicatorInfo.getIndicatorIndex() == index) {
int keyValue = mOutInfoSparseArray.keyAt(i);
EmojiIndicatorInfo innerInfo = mInnerInfoSparseArray.get(keyValue);
int lastPosition = mOutIndicatorLastPosition.get(emojiIndicatorInfo.getEmojiType());
if (innerInfo.getIndicatorIndex() == lastPosition) {
mViewPager.setCurrentItem(keyValue);
break;
}
}
}
}
/**
* 将ViewPager的position去生成内部指示器的index,形成对应关系,便于后面指示器的显示状态的切换。
*/
private void generateInnerPositinInfo() {
int innerIndex = 0;
for (int i = 0; i < mEmojiPanelBeans.size(); i++) {
int type = mEmojiPanelBeans.get(i).getEmojiType();
if (isExistEmojiTypeInSparse(true, type)) {
mInnerInfoSparseArray.put(i, new EmojiIndicatorInfo(type, ++innerIndex));
} else {
//不存在
innerIndex = 0;
mInnerInfoSparseArray.put(i, new EmojiIndicatorInfo(type, innerIndex));
}
}
}
/**
* 将ViewPager的position去生成外部指示器的index,形成对应关系,便于后面指示器的显示状态的切换。
*/
private void generateOutPositionInfo() {
int outIndex = -1;
for (int i = 0; i < mEmojiPanelBeans.size(); i++) {
int type = mEmojiPanelBeans.get(i).getEmojiType();
if (isExistEmojiTypeInSparse(false, type)) {
mOutInfoSparseArray.put(i, new EmojiIndicatorInfo(type, outIndex));
} else {
mOutInfoSparseArray.put(i, new EmojiIndicatorInfo(type, ++outIndex));
}
}
}
/**
* 检查是否已经在SparseArray中存在相应emoji类型的所对应的索引,用于构建内外指示器SpareArray数据调用
*
* @param isInnerIndicator
* @param emojiType
* @return
*/
private boolean isExistEmojiTypeInSparse(boolean isInnerIndicator, int emojiType) {
int size = isInnerIndicator ? mInnerInfoSparseArray.size() : mOutInfoSparseArray.size();
for (int j = 0; j < size; j++) {
EmojiIndicatorInfo emojiIndicatorInfo = isInnerIndicator ? mInnerInfoSparseArray.get(j) : mOutInfoSparseArray.get(j);
if (emojiIndicatorInfo != null && emojiIndicatorInfo.getEmojiType() == emojiType) {
return true;
}
}
return false;
}
/**
* 创建内部指示器的ItemView(ImageView)
*
* @param index
* @return
*/
private ImageView createInnerImageView(int index) {
ImageView imageView = new ImageView(getContext());
LayoutParams layoutParams = new LayoutParams(Utils.dp2px(6f), Utils.dp2px(6f));
layoutParams.leftMargin = Utils.dp2px(4f);
layoutParams.rightMargin = Utils.dp2px(4f);
imageView.setLayoutParams(layoutParams);
imageView.setImageDrawable(index == 0 ? ContextCompat.getDrawable(getContext(), R.drawable.indicator_selected) :
ContextCompat.getDrawable(getContext(), R.drawable.indicator_normal));
return imageView;
}
/**
* 创建外部指示器的itemView(ImageView)
*
* @param index
* @return
*/
private ImageView createOutImageView(int index) {
ImageView imageView = new ImageView(getContext());
LayoutParams layoutParams = new LayoutParams(Utils.dp2px(60), Utils.dp2px(48f));
imageView.setLayoutParams(layoutParams);
imageView.setBackgroundColor(index == 0 ? ContextCompat.getColor(getContext(), R.color.base_DCDCDC) : ContextCompat.getColor(getContext(), R.color.base_FFFFFF));
int padding = Utils.dp2px(8f);
imageView.setPadding(padding, padding, padding, padding);
if (mPagerAdapter instanceof EmojiPanelView.EmojiPanelPagerAdapter) {
imageView.setImageDrawable(((EmojiPanelView.EmojiPanelPagerAdapter) mPagerAdapter).getDrawable(index));
}
return imageView;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
/**
* 滑动切换ViewPager时,更新外部指示器的状态。
*
* @param count
* @param position
* @param emojiType
*/
private void updateInnerIndicatorState(int count, int position, int emojiType) {
for (int k = 0; k < count; k++) {
ImageView imageView = (ImageView) mInnerIndicatorParentView.getChildAt(k);
if (mInnerInfoSparseArray.get(position).getIndicatorIndex() == k) {
mOutIndicatorLastPosition.put(emojiType, k);
imageView.setImageResource(R.drawable.indicator_selected);
} else {
imageView.setImageResource(R.drawable.indicator_normal);
}
}
}
/**
* 滑动切换ViewPager时,更新内部部指示器的状态。
*
* @param position
*/
private void updateOutIndicatorState(int position) {
int outCount = mOutIndicatorParentView.getChildCount();
for (int j = 0; j < outCount; j++) {
ImageView imageView = (ImageView) mOutIndicatorParentView.getChildAt(j);
if (mOutInfoSparseArray.get(position).getIndicatorIndex() == j) {
imageView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.base_DCDCDC));
} else {
imageView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.base_FFFFFF));
}
}
}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < getChildCount(); i++) {
View childView = getChildAt(i);
if (childView instanceof LinearLayout) {
if (i == 0) {
//内部指示器
if (mInnerIndicatorParentView != null) {
int maxCount = mEmojiPanelBeans.get(position).getMaxPage();
int innerCount = mInnerIndicatorParentView.getChildCount();
int emojitType = positionToEmojiType(position);
if (innerCount != maxCount) {
createInnerIndicator(maxCount, emojitType);
updateInnerIndicatorState(maxCount, position, emojitType);
} else {
updateInnerIndicatorState(innerCount, position, emojitType);
}
}
} else {
//外部指示器
if (mOutIndicatorParentView != null) {
updateOutIndicatorState(position);
}
}
}
}
}
/**
* 通过当前position获取该position的emoji的类型
*
* @param position
* @return
*/
public int positionToEmojiType(int position) {
if (mEmojiPanelBeans != null && position < mEmojiPanelBeans.size()) {
return mEmojiPanelBeans.get(position).getEmojiType();
}
return -1;
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
|
3e015d71a1c0960eb8dce06d618841a5895730f1 | 344 | java | Java | jdbc/resource-server/src/main/java/br/eti/esabreu/oauth2/resourceserver/ResourceServerApplication.java | nosered/spring-oauth2 | b9f051b6b19209f160b999f89324258dbc9d28e3 | [
"MIT"
] | null | null | null | jdbc/resource-server/src/main/java/br/eti/esabreu/oauth2/resourceserver/ResourceServerApplication.java | nosered/spring-oauth2 | b9f051b6b19209f160b999f89324258dbc9d28e3 | [
"MIT"
] | null | null | null | jdbc/resource-server/src/main/java/br/eti/esabreu/oauth2/resourceserver/ResourceServerApplication.java | nosered/spring-oauth2 | b9f051b6b19209f160b999f89324258dbc9d28e3 | [
"MIT"
] | null | null | null | 26.461538 | 68 | 0.834302 | 569 | package br.eti.esabreu.oauth2.resourceserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceServerApplication.class, args);
}
}
|
3e015dfbe6f21e3b570452aabcf99503f3ca7230 | 16,645 | java | Java | src/Program5.0/src/soars/application/visualshell/object/role/base/object/legacy/command/MapCommand.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | null | null | null | src/Program5.0/src/soars/application/visualshell/object/role/base/object/legacy/command/MapCommand.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | null | null | null | src/Program5.0/src/soars/application/visualshell/object/role/base/object/legacy/command/MapCommand.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | 1 | 2019-03-18T06:22:49.000Z | 2019-03-18T06:22:49.000Z | 30.374088 | 207 | 0.663683 | 570 | /**
*
*/
package soars.application.visualshell.object.role.base.object.legacy.command;
import java.util.Vector;
import soars.application.visualshell.layer.Layer;
import soars.application.visualshell.layer.LayerManager;
import soars.application.visualshell.object.role.base.Role;
import soars.application.visualshell.object.role.base.object.base.Rule;
import soars.application.visualshell.object.role.base.object.common.CommonRuleManipulator;
/**
* @author kurata
*
*/
public class MapCommand extends Rule {
/**
* Reserved words
*/
public static String[] _reservedWords = {
"getMap ",
"putMap "
};
/**
* @param value
* @return
*/
public static int get_kind(String value) {
String reservedWord = CommonRuleManipulator.get_reserved_word( value);
for ( int i = 0; i < _reservedWords.length; ++i) {
if ( _reservedWords[ i].equals( reservedWord))
return i;
}
return -1;
}
/**
* @param kind
* @param type
* @param value
*/
public MapCommand(String kind, String type, String value) {
super(kind, type, value);
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#get_used_spot_names()
*/
@Override
protected String[] get_used_spot_names() {
return new String[] { CommonRuleManipulator.extract_spot_name1( _value)};
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#get_used_spot_variable_names(soars.application.visualshell.object.role.base.Role)
*/
@Override
protected String[] get_used_spot_variable_names(Role role) {
return new String[] { CommonRuleManipulator.get_spot_variable_name2( _value)};
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#get_used_probability_names()
*/
@Override
protected String[] get_used_probability_names() {
return new String[] { get_used_probability_name()};
}
/**
* @return
*/
private String get_used_probability_name() {
String usedProbabilityName = get_used_object_name( _value, 0, 2);
if ( null == usedProbabilityName)
return null;
if ( !CommonRuleManipulator.is_object( "probability", usedProbabilityName, LayerManager.get_instance()))
return null;
return usedProbabilityName;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#get_used_map_names()
*/
@Override
protected String[] get_used_map_names() {
return new String[] { get_used_map_name()};
}
/**
* @return
*/
private String get_used_map_name() {
String usedMapName = get_used_object_name( _value, 1, 0);
if ( null == usedMapName)
return null;
if ( !CommonRuleManipulator.is_object( "map", usedMapName, LayerManager.get_instance()))
return null;
return usedMapName;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#get_used_keyword_names()
*/
@Override
protected String[] get_used_keyword_names() {
String[] usedKeywordNames = new String[] { null, null};
usedKeywordNames[ 0] = get_used_object_name( _value, 2, 1);
if ( null == usedKeywordNames[ 0])
return null;
usedKeywordNames[ 1] = get_used_object_name( _value, 0, 2);
if ( null == usedKeywordNames[ 1])
return null;
if ( usedKeywordNames[ 0].startsWith( "\"") && usedKeywordNames[ 0].endsWith( "\""))
usedKeywordNames[ 0] = null;
else
usedKeywordNames[ 0] = ( ( !CommonRuleManipulator.is_object( "keyword", usedKeywordNames[ 0], LayerManager.get_instance())) ? null : usedKeywordNames[ 0]);
usedKeywordNames[ 1] = ( ( !CommonRuleManipulator.is_object( "keyword", usedKeywordNames[ 1], LayerManager.get_instance())) ? null : usedKeywordNames[ 1]);
return usedKeywordNames;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#get_used_number_object_names()
*/
@Override
protected String[] get_used_number_object_names() {
return new String[] { get_used_number_object_name()};
}
/**
* @return
*/
private String get_used_number_object_name() {
String usedNumberObjectName = get_used_object_name( _value, 0, 2);
if ( null == usedNumberObjectName)
return null;
if ( !CommonRuleManipulator.is_object( "number object", usedNumberObjectName, LayerManager.get_instance()))
return null;
return usedNumberObjectName;
}
/**
* @param value
* @param index0
* @param index1
* @return
*/
private String get_used_object_name(String value, int index0, int index1) {
int kind = get_kind( value);
if ( 0 > kind)
return null;
String prefix = CommonRuleManipulator.get_full_prefix( value);
if ( null == prefix)
return null;
String usedObjectName = get_used_object_name( kind, value, index0, index1);
if ( null == usedObjectName)
return null;
if ( usedObjectName.startsWith( "\"") && usedObjectName.endsWith( "\""))
return usedObjectName;
return ( prefix + usedObjectName);
}
/**
* @param kind
* @param value
* @param index1
* @param index0
* @return
*/
private String get_used_object_name(int kind, String value, int index0, int index1) {
String[] elements = CommonRuleManipulator.get_elements( value, 3);
if ( null == elements)
return null;
switch ( kind) {
case 0:
return elements[ index0];
case 1:
return elements[ index1];
}
return null;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#update_spot_name_and_number(java.lang.String, java.lang.String, java.lang.String, java.util.Vector, java.lang.String, java.util.Vector)
*/
@Override
public boolean update_spot_name_and_number(String newName, String originalName, String headName, Vector<String[]> ranges, String newHeadName, Vector<String[]> newRanges) {
String value = CommonRuleManipulator.update_spot_name2( _value, newName, originalName, headName, ranges, newHeadName, newRanges);
if ( null == value)
return false;
_value = value;
return true;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#update_spot_variable_name(java.lang.String, java.lang.String, java.lang.String, soars.application.visualshell.object.role.base.Role)
*/
@Override
protected boolean update_spot_variable_name(String name, String newName, String type, Role role) {
String value = CommonRuleManipulator.update_spot_variable_name2( _value, name, newName, type);
if ( null == value)
return false;
_value = value;
return true;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#update_probability_name(java.lang.String, java.lang.String, java.lang.String, soars.application.visualshell.object.role.base.Role)
*/
@Override
protected boolean update_probability_name(String name, String newName, String type, Role role) {
return update_object_name( name, newName, type);
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#update_map_name(java.lang.String, java.lang.String, java.lang.String, soars.application.visualshell.object.role.base.Role)
*/
@Override
protected boolean update_map_name(String name, String newName, String type, Role role) {
int kind = get_kind( _value);
if ( 0 > kind)
return false;
String prefix = CommonRuleManipulator.get_full_prefix( _value);
if ( null== prefix)
return false;
String[] elements = CommonRuleManipulator.get_elements( _value, 3);
if ( null == elements)
return false;
switch ( kind) {
case 0:
if ( !CommonRuleManipulator.correspond( prefix, elements[ 1], name, type))
return false;
elements[ 1] = newName;
break;
case 1:
if ( !CommonRuleManipulator.correspond( prefix, elements[ 0], name, type))
return false;
elements[ 0] = newName;
break;
default:
return false;
}
_value = ( prefix + _reservedWords[ kind]);
for ( int i = 0; i < elements.length; ++i)
_value += ( ( ( 0 == i) ? "" : "=") + elements[ i]);
return true;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#update_keyword_name(java.lang.String, java.lang.String, java.lang.String, soars.application.visualshell.object.role.base.Role)
*/
@Override
protected boolean update_keyword_name(String name, String newName, String type, Role role) {
int kind = get_kind( _value);
if ( 0 > kind)
return false;
String prefix = CommonRuleManipulator.get_full_prefix( _value);
if ( null== prefix)
return false;
String[] elements = CommonRuleManipulator.get_elements( _value, 3);
if ( null == elements)
return false;
boolean result1 = false;
switch ( kind) {
case 0:
result1 = CommonRuleManipulator.correspond( prefix, elements[ 0], name, type);
if ( result1)
elements[ 0] = newName;
break;
case 1:
result1 = CommonRuleManipulator.correspond( prefix, elements[ 1], name, type);
if ( result1)
elements[ 1] = newName;
break;
default:
return false;
}
boolean result2 = CommonRuleManipulator.correspond( prefix, elements[ 2], name, type);
if ( result2)
elements[ 2] = newName;
if ( !result1 && !result2)
return false;
_value = ( prefix + _reservedWords[ kind]);
for ( int i = 0; i < elements.length; ++i)
_value += ( ( ( 0 == i) ? "" : "=") + elements[ i]);
return true;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#update_number_object_name(java.lang.String, java.lang.String, java.lang.String, soars.application.visualshell.object.role.base.Role)
*/
@Override
protected boolean update_number_object_name(String name, String newName, String type, Role role) {
return update_object_name( name, newName, type);
}
/**
* @param name
* @param newName
* @param type
* @param rule
* @return
*/
private boolean update_object_name(String name, String newName, String type) {
int kind = get_kind( _value);
if ( 0 > kind)
return false;
String prefix = CommonRuleManipulator.get_full_prefix( _value);
if ( null== prefix)
return false;
String[] elements = CommonRuleManipulator.get_elements( _value, 3);
if ( null == elements)
return false;
switch ( kind) {
case 0:
if ( !CommonRuleManipulator.correspond( prefix, elements[ 0], name, type))
return false;
elements[ 0] = newName;
break;
case 1:
if ( !CommonRuleManipulator.correspond( prefix, elements[ 2], name, type))
return false;
elements[ 2] = newName;
break;
default:
return false;
}
_value = ( prefix + _reservedWords[ kind]);
for ( int i = 0; i < elements.length; ++i)
_value += ( ( ( 0 == i) ? "" : "=") + elements[ i]);
return true;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#can_paste(soars.application.visualshell.object.role.base.Role, soars.application.visualshell.layer.Layer)
*/
@Override
protected boolean can_paste(Role role, Layer drawObjects) {
int kind = get_kind( _value);
if ( 0 > kind)
return false;
if ( !CommonRuleManipulator.can_paste_spot_and_spot_variable_name1( _value, drawObjects))
return false;
if ( !can_paste_map_name( kind, drawObjects))
return false;
if ( !can_paste_key( kind, drawObjects))
return false;
if ( !can_paste_value( kind, drawObjects))
return false;
return true;
}
/**
* @param kind
* @param drawObjects
* @return
*/
private boolean can_paste_map_name(int kind, Layer drawObjects) {
String prefix = CommonRuleManipulator.get_full_prefix( _value);
if ( null == prefix)
return false;
String map = get_used_object_name( kind, _value, 1, 0);
if ( null == map)
return false;
return CommonRuleManipulator.can_paste_object( "map", prefix + map, drawObjects);
}
/**
* @param kind
* @param drawObjects
* @return
*/
private boolean can_paste_key(int kind, Layer drawObjects) {
String prefix = CommonRuleManipulator.get_full_prefix( _value);
if ( null == prefix)
return false;
String key = get_used_object_name( kind, _value, 2, 1);
if ( null == key)
return false;
if ( key.startsWith( "\"") && key.endsWith( "\""))
return true;
return CommonRuleManipulator.can_paste_object( "keyword", prefix + key, drawObjects);
}
/**
* @param kind
* @param drawObjects
* @return
*/
private boolean can_paste_value(int kind, Layer drawObjects) {
String prefix = CommonRuleManipulator.get_full_prefix( _value);
if ( null == prefix)
return false;
String val = get_used_object_name( kind, _value, 0, 2);
if ( null == val)
return false;
return ( CommonRuleManipulator.can_paste_object( "probability", prefix + val, drawObjects)
|| CommonRuleManipulator.can_paste_object( "keyword", prefix + val, drawObjects)
|| CommonRuleManipulator.can_paste_object( "number object", prefix + val, drawObjects));
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.base.Rule#get_script(java.lang.String, soars.application.visualshell.object.role.base.Role)
*/
@Override
protected String get_script(String value, Role role) {
int kind = get_kind( value);
if ( 0 > kind)
return "";
String spot = CommonRuleManipulator.get_full_prefix( value);
if ( null == spot)
return "";
String key = get_used_object_name( kind, value, 2, 1);
if ( null == key)
return "";
boolean key_is_keyword = ( key.startsWith( "\"") && key.endsWith( "\"")) ? false : true;
String script = ( !key_is_keyword ? "" : ( spot + "equip " + key + " ; "));
String val = get_used_object_name( kind, value, 0, 2);
if ( null == val)
return "";
// TODO 今後対応が必要になりそう
// if ( ( null != LayerManager.get_instance().get_agent_has_this_name( val))
// || ( null != LayerManager.get_instance().get_spot_has_this_name( _name_textField.getText()))) {
// TODO 修正済
if ( CommonRuleManipulator.is_object( "keyword", spot + val, LayerManager.get_instance())
|| CommonRuleManipulator.is_object( "file", spot + val, LayerManager.get_instance())) {
switch ( kind) {
case 0:
return ( script + value + " ; " + spot + "printEquip " + val);
case 1:
return ( script + spot + "equip " + val + " ; " + value);
default:
return "";
}
} else if ( CommonRuleManipulator.is_object( "time variable", spot + val, LayerManager.get_instance()))
return ( script + value + " ; " + spot + "cloneEquip $Time." + val);
else if ( ( null != LayerManager.get_instance().get_agent_has_this_name( val))
|| ( null != LayerManager.get_instance().get_spot_has_this_name( val))
|| CommonRuleManipulator.is_object( "role variable", spot + val, LayerManager.get_instance())
|| CommonRuleManipulator.is_object( "spot variable", spot + val, LayerManager.get_instance()))
return ( script + value);
else
return ( script + value + " ; " + spot + "cloneEquip " + val);
// boolean val_is_keyword = CommonRuleManipulator.is_object( "keyword", spot + val, LayerManager.get_instance());
//
// boolean val_is_role_variable = CommonRuleManipulator.is_object( "role variable", spot + val, LayerManager.get_instance());
// boolean val_is_time_variable = CommonRuleManipulator.is_object( "time variable", spot + val, LayerManager.get_instance());
// boolean val_is_spot_variable = CommonRuleManipulator.is_object( "spot variable", spot + val, LayerManager.get_instance());
//
// if ( !val_is_keyword) {
// if ( val_is_role_variable)
// script += ( value + " ; " + spot + "cloneEquip $Role." + val);
// else if ( val_is_time_variable)
// script += ( value + " ; " + spot + "cloneEquip $Time." + val);
// else if ( val_is_spot_variable)
// script += value;
// else
// script += ( value + " ; " + spot + "cloneEquip " + val);
// } else {
// if ( !val_is_keyword)
// script += ( value + " ; " + spot + "cloneEquip " + val);
// else {
// switch ( kind) {
// case 0:
// script += ( value + " ; " + spot + "printEquip " + val);
// break;
// case 1:
// script += ( spot + "equip " + val + " ; " + value);
// break;
// default:
// return "";
// }
// }
//
// return script;
}
}
|
3e015e98854940dcb2c6cee0599a9d1e4e82007a | 97 | java | Java | src/main/java/com/noetic/server/enums/QueueStatus.java | Sakerini/UO-Server | 1c342d5589997b107ca5440ce9deb2a108209d15 | [
"MIT"
] | null | null | null | src/main/java/com/noetic/server/enums/QueueStatus.java | Sakerini/UO-Server | 1c342d5589997b107ca5440ce9deb2a108209d15 | [
"MIT"
] | null | null | null | src/main/java/com/noetic/server/enums/QueueStatus.java | Sakerini/UO-Server | 1c342d5589997b107ca5440ce9deb2a108209d15 | [
"MIT"
] | null | null | null | 12.125 | 32 | 0.680412 | 571 | package com.noetic.server.enums;
public enum QueueStatus {
Error,
Failed,
Success
}
|
3e015eabd3e2a4835bc3de0a998ca0ae89ecde15 | 1,007 | java | Java | src/main/java/org/obfuscatedmc/servergl/api/RGBColor.java | PizzaCrust/ServerGL | 894941bc651a0a69629c08e62a5570ebb2f5faf1 | [
"MIT"
] | 1 | 2016-10-25T15:06:37.000Z | 2016-10-25T15:06:37.000Z | src/main/java/org/obfuscatedmc/servergl/api/RGBColor.java | PizzaCrust/ServerGL | 894941bc651a0a69629c08e62a5570ebb2f5faf1 | [
"MIT"
] | null | null | null | src/main/java/org/obfuscatedmc/servergl/api/RGBColor.java | PizzaCrust/ServerGL | 894941bc651a0a69629c08e62a5570ebb2f5faf1 | [
"MIT"
] | 1 | 2019-11-21T21:01:13.000Z | 2019-11-21T21:01:13.000Z | 23.418605 | 82 | 0.495531 | 572 | package org.obfuscatedmc.servergl.api;
/**
* Represents a RGB color set.
* (immutable)
*
* @author PizzaCrust
* @since 1.0-SNAPSHOT
*/
public class RGBColor
{
public final int red;
public final int blue;
public final int green;
private RGBColor(int red,
int blue,
int green) {
this.red = red;
this.blue = blue;
this.green = green;
}
public static RGBColor of(int red,
int blue,
int green) {
return new RGBColor(red, blue, green);
}
public RGBColor add(int red,
int blue,
int green) {
return new RGBColor(this.red + red, this.blue + blue, this.green + green);
}
public RGBColor subtract(int red,
int blue,
int green) {
return new RGBColor(this.red - red, this.blue - blue, this.green - green);
}
}
|
3e015eb345f9253ff17b9fa0bfe43002464f7556 | 1,649 | java | Java | aliyun-java-sdk-datalake/src/main/java/com/aliyuncs/datalake/transform/v20200710/ExportQueryResultResponseUnmarshaller.java | carldea/aliyun-openapi-java-sdk | 2d7c54d31cfb41af85a3f110c85f1b28ea1edf47 | [
"Apache-2.0"
] | 1 | 2022-02-12T06:01:36.000Z | 2022-02-12T06:01:36.000Z | aliyun-java-sdk-datalake/src/main/java/com/aliyuncs/datalake/transform/v20200710/ExportQueryResultResponseUnmarshaller.java | carldea/aliyun-openapi-java-sdk | 2d7c54d31cfb41af85a3f110c85f1b28ea1edf47 | [
"Apache-2.0"
] | 27 | 2021-06-11T21:08:40.000Z | 2022-03-11T21:25:09.000Z | aliyun-java-sdk-datalake/src/main/java/com/aliyuncs/datalake/transform/v20200710/ExportQueryResultResponseUnmarshaller.java | carldea/aliyun-openapi-java-sdk | 2d7c54d31cfb41af85a3f110c85f1b28ea1edf47 | [
"Apache-2.0"
] | 1 | 2020-03-05T07:30:16.000Z | 2020-03-05T07:30:16.000Z | 41.225 | 132 | 0.792602 | 573 | /*
* 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.datalake.transform.v20200710;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.datalake.model.v20200710.ExportQueryResultResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class ExportQueryResultResponseUnmarshaller {
public static ExportQueryResultResponse unmarshall(ExportQueryResultResponse exportQueryResultResponse, UnmarshallerContext _ctx) {
exportQueryResultResponse.setRequestId(_ctx.stringValue("ExportQueryResultResponse.RequestId"));
exportQueryResultResponse.setSuccess(_ctx.booleanValue("ExportQueryResultResponse.Success"));
exportQueryResultResponse.setIsReady(_ctx.booleanValue("ExportQueryResultResponse.IsReady"));
List<String> downloadUrlList = new ArrayList<String>();
for (int i = 0; i < _ctx.lengthValue("ExportQueryResultResponse.DownloadUrlList.Length"); i++) {
downloadUrlList.add(_ctx.stringValue("ExportQueryResultResponse.DownloadUrlList["+ i +"]"));
}
exportQueryResultResponse.setDownloadUrlList(downloadUrlList);
return exportQueryResultResponse;
}
} |
3e015f95c12f9abfaba1ae8781257b2ca3ebc4d5 | 767 | java | Java | src/test/java/com/thinkgem/jeesite/test/Test.java | 544852009/jeesite | e7a6a23bf5ae6811d2f3173531bde09c3a7033cb | [
"Apache-2.0"
] | null | null | null | src/test/java/com/thinkgem/jeesite/test/Test.java | 544852009/jeesite | e7a6a23bf5ae6811d2f3173531bde09c3a7033cb | [
"Apache-2.0"
] | null | null | null | src/test/java/com/thinkgem/jeesite/test/Test.java | 544852009/jeesite | e7a6a23bf5ae6811d2f3173531bde09c3a7033cb | [
"Apache-2.0"
] | null | null | null | 22.558824 | 79 | 0.698827 | 574 | package com.thinkgem.jeesite.test;
import com.thinkgem.jeesite.TheadYinHang.Bank;
import com.thinkgem.jeesite.TheadYinHang.PersonOne;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
// Station station = new Station("ONE");
// Station station1 = new Station("TWO");
// Station station2 = new Station("THREE");
//
//
// station.start();
// station1.start();
// station2.start();
List<Object> objects = Collections.synchronizedList(new ArrayList<Object>());
Bank bank1 = new Bank(new PersonOne("小王",12));
Bank bank2 = new Bank(new PersonOne("小李",13));
Thread one = new Thread(bank1);
Thread two = new Thread(bank2);
one.start();
two.start();
}
}
|
3e0161229bbab7f1162d34010f60810842eb002a | 2,436 | java | Java | BattleTanks/src/main/java/com/almasb/fxgl/entity/action/ActionComponent.java | HermiloOrtega/FXGLGames | 143c57de7ee54e64a7738f9575dece057bd26fa0 | [
"MIT"
] | 1 | 2020-04-07T04:36:44.000Z | 2020-04-07T04:36:44.000Z | BattleTanks/src/main/java/com/almasb/fxgl/entity/action/ActionComponent.java | HermiloOrtega/FXGLGames | 143c57de7ee54e64a7738f9575dece057bd26fa0 | [
"MIT"
] | null | null | null | BattleTanks/src/main/java/com/almasb/fxgl/entity/action/ActionComponent.java | HermiloOrtega/FXGLGames | 143c57de7ee54e64a7738f9575dece057bd26fa0 | [
"MIT"
] | null | null | null | 23.901961 | 83 | 0.623462 | 575 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (ychag@example.com).
* See LICENSE for details.
*/
package com.almasb.fxgl.entity.action;
import com.almasb.fxgl.entity.component.Component;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
* @author Almas Baimagambetov (ychag@example.com)
*/
public final class ActionComponent extends Component {
private final Action IDLE = new IdleAction();
private ObservableList<Action> actions = FXCollections.observableArrayList();
private Action currentAction = IDLE;
@Override
public void onUpdate(double tpf) {
if (currentAction.isCancelled()) {
clearActions();
}
if (currentAction.isComplete()) {
removeCurrentAction();
} else {
currentAction.onUpdate(tpf);
}
}
@Override
public void onRemoved() {
clearActions();
}
public ObservableList<Action> actionsProperty() {
return FXCollections.unmodifiableObservableList(actions);
}
public Action getCurrentAction() {
return currentAction;
}
/**
* @return true when not performing any actions
*/
public boolean isIdle() {
return currentAction == IDLE;
}
/**
* @return true if there are more actions (apart from Idle) in the queue
*/
public boolean hasNextActions() {
return !actions.isEmpty();
}
/**
* Clears all running and pending actions.
*/
public void clearActions() {
actions.forEach(Action::reset);
actions.clear();
removeCurrentAction();
}
/**
* Add an action for this entity to execute.
* If an entity is already executing an action,
* this action will be queued.
*
* @param action next action to execute
*/
public void pushAction(Action action) {
action.setEntity(entity);
actions.add(action);
}
/**
* Remove current executing action.
* If there are more actions pending, the first pending action becomes current.
*/
public void removeCurrentAction() {
currentAction.reset();
if (!isIdle() && !actions.isEmpty())
actions.remove(0);
currentAction = getNextAction();
}
public Action getNextAction() {
return hasNextActions() ? actions.get(0) : IDLE;
}
}
|
3e0161a9707a50f8b2a1f026028129fdff089671 | 3,329 | java | Java | src/main/java/io/github/frogastudios/facecavity/ui/FaceCavityScreenHandler.java | A5TR0spud/face-cavity | 537750970ea5b4bd3c4d8722b7cef509ccc38bb8 | [
"MIT"
] | null | null | null | src/main/java/io/github/frogastudios/facecavity/ui/FaceCavityScreenHandler.java | A5TR0spud/face-cavity | 537750970ea5b4bd3c4d8722b7cef509ccc38bb8 | [
"MIT"
] | null | null | null | src/main/java/io/github/frogastudios/facecavity/ui/FaceCavityScreenHandler.java | A5TR0spud/face-cavity | 537750970ea5b4bd3c4d8722b7cef509ccc38bb8 | [
"MIT"
] | 2 | 2021-06-07T20:36:33.000Z | 2022-03-13T18:20:39.000Z | 35.795699 | 112 | 0.605287 | 576 | package io.github.frogastudios.facecavity.ui;
import io.github.frogastudios.facecavity.FaceCavity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.slot.Slot;
import io.github.frogastudios.facecavity.facecavities.FaceCavityInventory;
public class FaceCavityScreenHandler extends ScreenHandler {
private final FaceCavityInventory inventory;
private final int size;
private final int rows;
private static FaceCavityInventory getOrCreateChestCavityInventory(PlayerInventory playerInventory){/*
FaceCavityInstance playerCC = ((FaceCavityEntity)playerInventory.player).getChestCavityInstance();
FaceCavityInstance targetCCI = playerCC.ccBeingOpened;
if(targetCCI != null){
FaceCavity.LOGGER.info("Found CCI");
return targetCCI.inventory;
}
FaceCavity.LOGGER.info("Missed CCI");*/
return new FaceCavityInventory();
}
public FaceCavityScreenHandler(int syncId, PlayerInventory playerInventory) {
this(syncId, playerInventory, getOrCreateChestCavityInventory(playerInventory));
}
public FaceCavityScreenHandler(int syncId, PlayerInventory playerInventory, FaceCavityInventory inventory) {
super(FaceCavity.FACE_CAVITY_SCREEN_HANDLER, syncId);
this.size = inventory.size();
this.inventory = inventory;
this.rows = (size-1)/9 + 1;
inventory.onOpen(playerInventory.player);
int i = (rows - 4) * 18;
int n;
int m;
for(n = 0; n < this.rows; ++n) {
for(m = 0; m < 9 && (n*9)+m < size; ++m) {
this.addSlot(new Slot(inventory, m + n * 9, 8 + m * 18, 18 + n * 18));
}
}
for(n = 0; n < 3; ++n) {
for(m = 0; m < 9; ++m) {
this.addSlot(new Slot(playerInventory, m + n * 9 + 9, 8 + m * 18, 103 + n * 18 + i));
}
}
for(n = 0; n < 9; ++n) {
this.addSlot(new Slot(playerInventory, n, 8 + n * 18, 161 + i));
}
}
@Override
public ItemStack transferSlot(PlayerEntity player, int invSlot) {
ItemStack newStack = ItemStack.EMPTY;
Slot slot = this.slots.get(invSlot);
if (slot != null && slot.hasStack()) {
ItemStack originalStack = slot.getStack();
newStack = originalStack.copy();
if (invSlot < this.inventory.size()) {
/*if(inventory.getInstance().type.isSlotForbidden(invSlot)){
return ItemStack.EMPTY;
}*/
if (!this.insertItem(originalStack, this.inventory.size(), this.slots.size(), true)) {
return ItemStack.EMPTY;
}
} else if (!this.insertItem(originalStack, 0, this.inventory.size(), false)) {
return ItemStack.EMPTY;
}
if (originalStack.isEmpty()) {
slot.setStack(ItemStack.EMPTY);
} else {
slot.markDirty();
}
}
return newStack;
}
@Override
public boolean canUse(PlayerEntity player) {
return this.inventory.canPlayerUse(player);
}
}
|
3e0162437094362fd9ea06229a78120546023d93 | 1,894 | java | Java | modules/core/src/main/java/org/gridgain/grid/util/nio/GridNioException.java | gridgentoo/gridgain | 735b7859d9f87e74a06172bd7847b7db418fcb83 | [
"Apache-2.0"
] | 1 | 2019-04-22T08:48:55.000Z | 2019-04-22T08:48:55.000Z | modules/core/src/main/java/org/gridgain/grid/util/nio/GridNioException.java | cybernetics/gridgain | 39f3819c9769b04caca62b263581c0458f21c4d6 | [
"Apache-2.0"
] | null | null | null | modules/core/src/main/java/org/gridgain/grid/util/nio/GridNioException.java | cybernetics/gridgain | 39f3819c9769b04caca62b263581c0458f21c4d6 | [
"Apache-2.0"
] | null | null | null | 29.138462 | 84 | 0.634636 | 577 | /*
Copyright (C) GridGain Systems. 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 org.gridgain.grid.util.nio;
import org.gridgain.grid.*;
import org.jetbrains.annotations.*;
/**
* Nio specific exception.
*/
public class GridNioException extends GridException {
/** */
private static final long serialVersionUID = 0L;
/**
* Creates new exception with given error message.
*
* @param msg Error message.
*/
public GridNioException(String msg) {
super(msg);
}
/**
* Creates new exception with given error message and optional nested exception.
*
* @param msg Error message.
* @param cause Nested exception.
*/
public GridNioException(String msg, @Nullable Throwable cause) {
super(msg, cause);
}
/**
* Creates new grid exception given throwable as a cause and
* source of error message.
*
* @param cause Non-null throwable cause.
*/
public GridNioException(Throwable cause) {
super(cause);
}
}
|
3e01627f92ca76c604fab38f3d75ee34804f540f | 5,930 | java | Java | model/src/main/java/io/github/cloudiator/rest/model/FaasInterface.java | IMU-ICCS/rest-server | 5dd7d0347f1aef535faa9f82417d7ea220f72ff0 | [
"Apache-2.0"
] | null | null | null | model/src/main/java/io/github/cloudiator/rest/model/FaasInterface.java | IMU-ICCS/rest-server | 5dd7d0347f1aef535faa9f82417d7ea220f72ff0 | [
"Apache-2.0"
] | 6 | 2017-12-04T12:41:23.000Z | 2022-01-21T23:22:29.000Z | model/src/main/java/io/github/cloudiator/rest/model/FaasInterface.java | IMU-ICCS/rest-server | 5dd7d0347f1aef535faa9f82417d7ea220f72ff0 | [
"Apache-2.0"
] | 1 | 2019-02-02T17:59:22.000Z | 2019-02-02T17:59:22.000Z | 26.473214 | 120 | 0.696627 | 578 | package io.github.cloudiator.rest.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.github.cloudiator.rest.model.TaskInterface;
import io.github.cloudiator.rest.model.Trigger;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* Part of a Task. Represents one function.
*/
@ApiModel(description = "Part of a Task. Represents one function. ")
@Validated
public class FaasInterface extends TaskInterface {
@JsonProperty("functionName")
private String functionName = null;
@JsonProperty("sourceCodeUrl")
private String sourceCodeUrl = null;
@JsonProperty("handler")
private String handler = null;
@JsonProperty("triggers")
@Valid
private List<Trigger> triggers = null;
@JsonProperty("timeout")
private Integer timeout = 6;
@JsonProperty("functionEnvironment")
private java.util.Map functionEnvironment = null;
public FaasInterface functionName(String functionName) {
this.functionName = functionName;
return this;
}
/**
* Unique name of the function.
* @return functionName
**/
@ApiModelProperty(value = "Unique name of the function. ")
public String getFunctionName() {
return functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
public FaasInterface sourceCodeUrl(String sourceCodeUrl) {
this.sourceCodeUrl = sourceCodeUrl;
return this;
}
/**
* URL path to ZIP artifact.
* @return sourceCodeUrl
**/
@ApiModelProperty(value = "URL path to ZIP artifact. ")
public String getSourceCodeUrl() {
return sourceCodeUrl;
}
public void setSourceCodeUrl(String sourceCodeUrl) {
this.sourceCodeUrl = sourceCodeUrl;
}
public FaasInterface handler(String handler) {
this.handler = handler;
return this;
}
/**
* function in the code to be invoked.
* @return handler
**/
@ApiModelProperty(value = "function in the code to be invoked. ")
public String getHandler() {
return handler;
}
public void setHandler(String handler) {
this.handler = handler;
}
public FaasInterface triggers(List<Trigger> triggers) {
this.triggers = triggers;
return this;
}
public FaasInterface addTriggersItem(Trigger triggersItem) {
if (this.triggers == null) {
this.triggers = new ArrayList<Trigger>();
}
this.triggers.add(triggersItem);
return this;
}
/**
* Events on which function will be invoked.
* @return triggers
**/
@ApiModelProperty(value = "Events on which function will be invoked. ")
@Valid
public List<Trigger> getTriggers() {
return triggers;
}
public void setTriggers(List<Trigger> triggers) {
this.triggers = triggers;
}
public FaasInterface timeout(Integer timeout) {
this.timeout = timeout;
return this;
}
/**
* Allowed time in seconds for function to finish its task.
* minimum: 1
* @return timeout
**/
@ApiModelProperty(value = "Allowed time in seconds for function to finish its task. ")
@Min(1)
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public FaasInterface functionEnvironment(java.util.Map functionEnvironment) {
this.functionEnvironment = functionEnvironment;
return this;
}
/**
* Environment variables passed to function.
* @return functionEnvironment
**/
@ApiModelProperty(value = "Environment variables passed to function. ")
@Valid
public java.util.Map getFunctionEnvironment() {
return functionEnvironment;
}
public void setFunctionEnvironment(java.util.Map functionEnvironment) {
this.functionEnvironment = functionEnvironment;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FaasInterface faasInterface = (FaasInterface) o;
return Objects.equals(this.functionName, faasInterface.functionName) &&
Objects.equals(this.sourceCodeUrl, faasInterface.sourceCodeUrl) &&
Objects.equals(this.handler, faasInterface.handler) &&
Objects.equals(this.triggers, faasInterface.triggers) &&
Objects.equals(this.timeout, faasInterface.timeout) &&
Objects.equals(this.functionEnvironment, faasInterface.functionEnvironment) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(functionName, sourceCodeUrl, handler, triggers, timeout, functionEnvironment, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class FaasInterface {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" functionName: ").append(toIndentedString(functionName)).append("\n");
sb.append(" sourceCodeUrl: ").append(toIndentedString(sourceCodeUrl)).append("\n");
sb.append(" handler: ").append(toIndentedString(handler)).append("\n");
sb.append(" triggers: ").append(toIndentedString(triggers)).append("\n");
sb.append(" timeout: ").append(toIndentedString(timeout)).append("\n");
sb.append(" functionEnvironment: ").append(toIndentedString(functionEnvironment)).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 ");
}
}
|
3e016302f932f7e46322e0b9f83dda551f8edc5f | 91 | java | Java | math/src/main/java/net/sf/javagimmicks/math/package-info.java | m34434/JavaGimmicks | 2cb9bc1f063bceddeb51621231a908a2dbc836cf | [
"Apache-2.0"
] | null | null | null | math/src/main/java/net/sf/javagimmicks/math/package-info.java | m34434/JavaGimmicks | 2cb9bc1f063bceddeb51621231a908a2dbc836cf | [
"Apache-2.0"
] | 1 | 2022-01-21T23:20:04.000Z | 2022-01-21T23:20:04.000Z | math/src/main/java/net/sf/javagimmicks/math/package-info.java | m34434/JavaGimmicks | 2cb9bc1f063bceddeb51621231a908a2dbc836cf | [
"Apache-2.0"
] | 2 | 2017-09-14T10:27:43.000Z | 2020-02-05T16:20:30.000Z | 15.166667 | 47 | 0.736264 | 579 | /**
* Provides some useful mathematical utilities.
*/
package net.sf.javagimmicks.math;
|
3e016377de76850547f70d1362b63607a644fdf0 | 1,556 | java | Java | org.ektorp/src/main/java/org/ektorp/impl/StdObjectMapperFactory.java | femangl/Ektorp | b822c0d656aefb90a5e0cb5ec2de3daa969e3eaa | [
"Apache-2.0"
] | 142 | 2015-01-07T09:12:01.000Z | 2022-02-19T04:13:23.000Z | org.ektorp/src/main/java/org/ektorp/impl/StdObjectMapperFactory.java | femangl/Ektorp | b822c0d656aefb90a5e0cb5ec2de3daa969e3eaa | [
"Apache-2.0"
] | 82 | 2015-01-05T09:10:39.000Z | 2022-03-29T12:53:57.000Z | org.ektorp/src/main/java/org/ektorp/impl/StdObjectMapperFactory.java | femangl/Ektorp | b822c0d656aefb90a5e0cb5ec2de3daa969e3eaa | [
"Apache-2.0"
] | 103 | 2015-01-09T16:08:54.000Z | 2022-03-30T11:03:32.000Z | 26.827586 | 92 | 0.789846 | 580 | package org.ektorp.impl;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.ektorp.CouchDbConnector;
import org.ektorp.impl.jackson.EktorpJacksonModule;
import org.ektorp.util.Assert;
/**
*
* @author henrik lundgren
*
*/
public class StdObjectMapperFactory implements ObjectMapperFactory {
private ObjectMapper instance;
private boolean writeDatesAsTimestamps = false;
public synchronized ObjectMapper createObjectMapper() {
ObjectMapper result = instance;
if (result == null) {
result = new ObjectMapper();
applyDefaultConfiguration(result);
instance = result;
}
return result;
}
public ObjectMapper createObjectMapper(CouchDbConnector connector) {
ObjectMapper objectMapper = new ObjectMapper();
applyDefaultConfiguration(objectMapper);
objectMapper.registerModule(new EktorpJacksonModule(connector, objectMapper));
return objectMapper;
}
public synchronized void setObjectMapper(ObjectMapper om) {
Assert.notNull(om, "ObjectMapper may not be null");
this.instance = om;
}
public void setWriteDatesAsTimestamps(boolean b) {
this.writeDatesAsTimestamps = b;
}
/**
* This protected method can be overridden in order to change the configuration.
*/
protected void applyDefaultConfiguration(ObjectMapper om) {
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, this.writeDatesAsTimestamps);
om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
|
3e0166404149b5a95a000062834e36841edf2235 | 182 | java | Java | src/main/java/io/datakitchen/ide/service/ContainerServiceException.java | Carlos-Descalzi/dkide | cc767ddb90b658ff82badb2d2c26c3ebe76c857d | [
"Apache-2.0"
] | null | null | null | src/main/java/io/datakitchen/ide/service/ContainerServiceException.java | Carlos-Descalzi/dkide | cc767ddb90b658ff82badb2d2c26c3ebe76c857d | [
"Apache-2.0"
] | null | null | null | src/main/java/io/datakitchen/ide/service/ContainerServiceException.java | Carlos-Descalzi/dkide | cc767ddb90b658ff82badb2d2c26c3ebe76c857d | [
"Apache-2.0"
] | null | null | null | 22.75 | 57 | 0.758242 | 581 | package io.datakitchen.ide.service;
public class ContainerServiceException extends Exception{
public ContainerServiceException(String message) {
super(message);
}
}
|
3e016679bd762d6eccde8888cb674a594436ecde | 7,273 | java | Java | S-Query-examples/query-state-job/src/main/java/org/example/MainQuery.java | delftdata/s-query | a8197e64b9630263d5a7a29cfa47e8a5f8c75e54 | [
"Apache-2.0"
] | null | null | null | S-Query-examples/query-state-job/src/main/java/org/example/MainQuery.java | delftdata/s-query | a8197e64b9630263d5a7a29cfa47e8a5f8c75e54 | [
"Apache-2.0"
] | null | null | null | S-Query-examples/query-state-job/src/main/java/org/example/MainQuery.java | delftdata/s-query | a8197e64b9630263d5a7a29cfa47e8a5f8c75e54 | [
"Apache-2.0"
] | null | null | null | 46.922581 | 364 | 0.558779 | 582 | package org.example;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.datamodel.TimestampedItem;
import com.hazelcast.jet.impl.processor.IMapStateHelper;
import com.hazelcast.jet.impl.processor.TransformStatefulP;
import com.hazelcast.map.IMap;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.PredicateBuilder;
import com.hazelcast.query.Predicates;
import com.hazelcast.sql.SqlResult;
import com.hazelcast.sql.SqlRow;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public class MainQuery {
public static void main(String[] args) {
JetInstance jet = Jet.bootstrappedInstance();
HazelcastInstance hz = jet.getHazelcastInstance();
final AtomicBoolean stop = new AtomicBoolean(false);
Runtime.getRuntime().addShutdownHook(new Thread(() -> stop.set(true)));
if (args.length == 1) {
String queryString = String.format("SELECT * FROM \"%1$s\"", args[0]);
try (SqlResult result = hz.getSql().execute(queryString)) {
for (SqlRow row : result) {
System.out.println(row.getObject(0).toString());
}
}
return;
}
if (args.length == 2) {
String queryString = String.format("SELECT * FROM \"%1$s\"", args[0]);
int sleepTime = Integer.parseInt(args[1]);
while (!stop.get()) {
try (SqlResult result = hz.getSql().execute(queryString)) {
// for (SqlRow row : result) {
// System.out.println(row.getObject(0).toString());
// }
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
stop.set(true);
e.printStackTrace();
}
}
return;
}
String ssMap1 = IMapStateHelper.getSnapshotMapName("id1-map");
String ssMap2 = IMapStateHelper.getSnapshotMapName("id2-map");
System.out.println(ssMap1);
System.out.println(ssMap2);
String queryString = String.format("SELECT \"%1$s\".partitionKey AS key1, \"%1$s\".counter AS counter1, \"%2$s\".partitionKey AS key2, \"%2$s\".counter AS counter2, (\"%1$s\".counter + \"%2$s\".counter) AS combined, \"%1$s\".snapshotId AS ss1, \"%2$s\".snapshotId AS ss2 FROM \"%1$s\" INNER JOIN \"%2$s\" USING (partitionKey, snapshotId)", ssMap1, ssMap2);
System.out.println(queryString);
try (SqlResult result = hz.getSql().execute(queryString)) {
System.out.println("Key1, Key2, Counter1, Counter2, Countertotal, Snapshot 1, Snapshot 2");
for (SqlRow row : result) {
long key1 = row.getObject(0);
long counter1 = row.getObject(1);
long key2 = row.getObject(2);
long counter2 = row.getObject(3);
long countertotal = row.getObject(4);
long ss1 = row.getObject(5);
long ss2 = row.getObject(6);
System.out.printf("%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d%n", key1, key2, counter1, counter2, countertotal, ss1, ss2);
}
}
// String[] imapsArray = stateMapNames.toArray(new String[0]);
// String[] ssArray = snapshotMapNames.toArray(new String[0]);
// System.out.println("State IMaps:");
// for (String s : imapsArray) {
// System.out.println("\t" + s);
// }
// System.out.println("Snapshot IMaps:");
// for (String s : ssArray) {
// System.out.println("\t" + s);
// }
// for (String stateIMap : imapsArray) {
// System.out.println("\nResults for state IMap: " + stateIMap);
// System.out.println("\tSQL Query results:");
// try (SqlResult result = hz.getSql().execute(String.format("SELECT * FROM \"%s\"", stateIMap))) {
// for (SqlRow row : result) {
// Object metadata = row.getMetadata();
// System.out.println("\t\t" + metadata);
// Long ts = row.getObject("timestamp");
// Long[] stateObj = row.getObject("item");
// System.out.println(String.format("\t\tts: %d, state: %d", ts, stateObj[0]));
// }
// } catch (Exception e) {
//
// }
//
// IMap state = hz.getMap(imapsArray[0]);
//
// PredicateBuilder.EntryObject e = Predicates.newPredicateBuilder().getEntryObject();
// Predicate predicate = e.get("longarr[0]").greaterEqual(1);
// Collection<TimestampedItem<Long[]>> greaterOne = state.values(predicate);
// System.out.println("\tPredicate result:");
// greaterOne.forEach(ts -> System.out.println(
// String.format("\t\tts: %d, state: %d", ts.timestamp(), ts.item()[0])));
//
// String queryGreaterOne = "longarr[0] >= 1";
// Collection<TimestampedItem<Long[]>> greaterOneSQL = state.values(Predicates.sql(queryGreaterOne));
// System.out.println(String.format("\tPredicate result using SQL string: '%s'", queryGreaterOne));
// greaterOneSQL.forEach(ts -> System.out.println(
// String.format("\t\tts: %d, state: %d", ts.timestamp(), ts.item()[0])));
// }
//
// for (String ssIMap : ssArray) {
// System.out.println("\nResults for state IMap: " + ssIMap);
// System.out.println("\tSQL Query results:");
// try (SqlResult result = hz.getSql().execute(String.format("SELECT * FROM \"%s\"", ssIMap))) {
// for (SqlRow row : result) {
// Object metadata = row.getMetadata();
// System.out.println("\t\t" + metadata);
// Long ts = row.getObject("timestamp");
// Long[] stateObj = row.getObject("item");
// System.out.println(String.format("\t\tts: %d, state: %d", ts, stateObj[0]));
// }
// } catch (Exception e) {
//
// }
//
// IMap state = hz.getMap(imapsArray[0]);
//
// PredicateBuilder.EntryObject e = Predicates.newPredicateBuilder().getEntryObject();
// Predicate predicate = e.get("longarr[0]").greaterEqual(1);
// Collection<TimestampedItem<Long[]>> greaterOne = state.values(predicate);
// System.out.println("\tPredicate result:");
// greaterOne.forEach(ts -> System.out.println(
// String.format("\t\tts: %d, state: %d", ts.timestamp(), ts.item()[0])));
//
// String queryGreaterOne = "longarr[0] >= 1";
// Collection<TimestampedItem<Long[]>> greaterOneSQL = state.values(Predicates.sql(queryGreaterOne));
// System.out.println(String.format("\tPredicate result using SQL string: '%s'", queryGreaterOne));
// greaterOneSQL.forEach(ts -> System.out.println(
// String.format("\t\tts: %d, state: %d", ts.timestamp(), ts.item()[0])));
// }
}
}
|
3e016720dde9f18a54de4c3f07f870e029d38cc4 | 1,364 | java | Java | Finales/final-2018-12-11/final-alumno/tests/Pruebas.java | brunograssano/7507-Algo3 | 21e262179dc2e9df8bfa691c9ee9878a3c38c226 | [
"MIT"
] | 37 | 2018-11-14T13:56:26.000Z | 2022-03-17T19:46:04.000Z | Finales/final-2018-12-11/final-alumno/tests/Pruebas.java | brunograssano/7507-Algo3 | 21e262179dc2e9df8bfa691c9ee9878a3c38c226 | [
"MIT"
] | 8 | 2019-03-01T22:23:13.000Z | 2021-09-14T22:19:52.000Z | Finales/final-2018-12-11/final-alumno/tests/Pruebas.java | brunograssano/7507-Algo3 | 21e262179dc2e9df8bfa691c9ee9878a3c38c226 | [
"MIT"
] | 48 | 2018-09-18T18:13:29.000Z | 2022-02-03T15:21:03.000Z | 31 | 107 | 0.68695 | 583 | package fiuba.algo3.tiendaonline;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class Pruebas {
private static final double DELTA = 1e-15;
@Test
public void testCompraGrande() {
Map<String, Double> preciosProductos = new HashMap<String, Double>();
preciosProductos.put("Raspberry Pi 3", 3500.00);
preciosProductos.put("Arduino kit", 2000.00);
preciosProductos.put("Arduino super kit", 4000.00);
Map<String, Integer> stockProductos = new HashMap<String, Integer>();
stockProductos.put("Raspberry Pi 3", 5);
stockProductos.put("Arduino kit", 6);
stockProductos.put("Arduino super kit", 2);
TiendaOnline tienda = new TiendaOnline();
tienda.setPreciosProductos(preciosProductos);
tienda.setStockProductos(stockProductos);
Pedido pedido = new Pedido();
tienda.agregarProductoAlPedido(pedido, "Arduino kit", 3);
tienda.agregarProductoAlPedido(pedido, "Arduino super kit", 1);
tienda.agregarEnvio(pedido, new EnvioInternacional()); // se le aplica un recargo del 20%
tienda.agregarCuponDeDescuento(Cupon.CYBER_MONDAY_50, pedido); // se le aplica un descuento del 50%
assertEquals(6000, tienda.cobrarPedido(pedido), DELTA);
}
}
|
3e0167f7d98748bef8df9d0cbc5dd2552bfd05e9 | 1,224 | java | Java | src/main/java/com/microsoft/store/partnercenter/servicerequests/IServiceRequest.java | Serik0/Partner-Center-Java | 9e10bb1c62b3d36c131795950b5553c36a0a3c4f | [
"MIT"
] | 17 | 2019-05-17T08:19:27.000Z | 2021-12-09T19:07:56.000Z | src/main/java/com/microsoft/store/partnercenter/servicerequests/IServiceRequest.java | Serik0/Partner-Center-Java | 9e10bb1c62b3d36c131795950b5553c36a0a3c4f | [
"MIT"
] | 48 | 2019-05-09T23:11:24.000Z | 2022-02-24T03:24:08.000Z | src/main/java/com/microsoft/store/partnercenter/servicerequests/IServiceRequest.java | Serik0/Partner-Center-Java | 9e10bb1c62b3d36c131795950b5553c36a0a3c4f | [
"MIT"
] | 25 | 2019-08-30T02:45:09.000Z | 2022-02-07T11:59:37.000Z | 34.971429 | 105 | 0.776961 | 584 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See the LICENSE file in the project root for full license information.
package com.microsoft.store.partnercenter.servicerequests;
import com.microsoft.store.partnercenter.IPartnerComponent;
import com.microsoft.store.partnercenter.genericoperations.IEntityGetOperations;
import com.microsoft.store.partnercenter.genericoperations.IEntityPatchOperations;
import com.microsoft.store.partnercenter.models.servicerequests.ServiceRequest;
import com.microsoft.store.partnercenter.models.utils.Tuple;
/**
* Groups operations that can be performed on a single service request.
*/
public interface IServiceRequest
extends IPartnerComponent<Tuple<String, String>>, IEntityGetOperations<ServiceRequest>,
IEntityPatchOperations<ServiceRequest>
{
/**
* Retrieves the service request.
*
* @return The service request information.
*/
ServiceRequest get();
/**
* Patches a service request.
*
* @param serviceRequest The service request that has the properties to be patched set.
* @return The updated service request.
*/
ServiceRequest patch(ServiceRequest serviceRequest);
}
|
3e0168d0e361d121a124ea4d947db6044ed937af | 13,112 | java | Java | webside-dtgrid/src/main/java/com/webside/user/controller/UserController.java | njyefeihu/webside | 81bbc9f822054b94b13fcb30e22671c6c646f8b8 | [
"Apache-2.0"
] | 1 | 2016-08-08T03:57:37.000Z | 2016-08-08T03:57:37.000Z | platform-web/src/main/java/com/webside/user/controller/UserController.java | fglovezzr123/platform-web | 618519272cd0f9c87fee012627d725594b6c9800 | [
"Apache-2.0"
] | null | null | null | platform-web/src/main/java/com/webside/user/controller/UserController.java | fglovezzr123/platform-web | 618519272cd0f9c87fee012627d725594b6c9800 | [
"Apache-2.0"
] | null | null | null | 27.604211 | 107 | 0.666107 | 585 | package com.webside.user.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.webside.base.basecontroller.BaseController;
import com.webside.common.Common;
import com.webside.dtgrid.model.Pager;
import com.webside.dtgrid.util.ExportUtils;
import com.webside.exception.AjaxException;
import com.webside.exception.ServiceException;
import com.webside.role.model.RoleEntity;
import com.webside.role.service.RoleService;
import com.webside.shiro.ShiroAuthenticationManager;
import com.webside.user.model.UserEntity;
import com.webside.user.model.UserInfoEntity;
import com.webside.user.service.UserService;
import com.webside.util.EndecryptUtils;
import com.webside.util.PageUtil;
import com.webside.util.RandomUtil;
@Controller
@Scope("prototype")
@RequestMapping("/user/")
public class UserController extends BaseController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@RequestMapping("listUI.html")
public String listUI(Model model, HttpServletRequest request) {
try
{
PageUtil page = new PageUtil();
if(request.getParameterMap().containsKey("page")){
page.setPageNum(Integer.valueOf(request.getParameter("page")));
page.setPageSize(Integer.valueOf(request.getParameter("rows")));
page.setOrderByColumn(request.getParameter("sidx"));
page.setOrderByType(request.getParameter("sord"));
}
model.addAttribute("page", page);
return Common.BACKGROUND_PATH + "/user/list";
}catch(Exception e)
{
throw new AjaxException(e);
}
}
/**
* ajax分页动态加载模式
* @param dtGridPager Pager对象
* @throws Exception
*/
@RequestMapping(value = "/list.html", method = RequestMethod.POST)
@ResponseBody
public Object list(String gridPager, HttpServletResponse response) throws Exception{
Map<String, Object> parameters = null;
//1、映射Pager对象
Pager pager = JSON.parseObject(gridPager, Pager.class);
//2、设置查询参数
parameters = pager.getParameters();
parameters.put("creatorName", ShiroAuthenticationManager.getUserAccountName());
if (parameters.size() < 0) {
parameters.put("userName", null);
}
//3、判断是否是导出操作
if(pager.getIsExport())
{
if(pager.getExportAllData())
{
//3.1、导出全部数据
List<UserEntity> list = userService.queryListByPage(parameters);
ExportUtils.exportAll(response, pager, list);
return null;
}else
{
//3.2、导出当前页数据
ExportUtils.export(response, pager);
return null;
}
}else
{
//设置分页,page里面包含了分页信息
Page<Object> page = PageHelper.startPage(pager.getNowPage(),pager.getPageSize(), "u_id DESC");
List<UserEntity> list = userService.queryListByPage(parameters);
parameters.clear();
parameters.put("isSuccess", Boolean.TRUE);
parameters.put("nowPage", pager.getNowPage());
parameters.put("pageSize", pager.getPageSize());
parameters.put("pageCount", page.getPages());
parameters.put("recordCount", page.getTotal());
parameters.put("startRecord", page.getStartRow());
//列表展示数据
parameters.put("exhibitDatas", list);
return parameters;
}
}
@RequestMapping("addUI.html")
public String addUI(Model model) {
try
{
List<RoleEntity> list = roleService.queryListByPage(new HashMap<String, Object>());
model.addAttribute("roleList", list);
return Common.BACKGROUND_PATH + "/user/form";
}catch(Exception e)
{
throw new AjaxException(e);
}
}
@RequestMapping("add.html")
@ResponseBody
public Object add(UserEntity userEntity) throws AjaxException
{
Map<String, Object> map = new HashMap<String, Object>();
try
{
String password = userEntity.getPassword();
// 加密用户输入的密码,得到密码和加密盐,保存到数据库
UserEntity user = EndecryptUtils.md5Password(userEntity.getAccountName(), userEntity.getPassword(), 2);
//设置添加用户的密码和加密盐
userEntity.setPassword(user.getPassword());
userEntity.setCredentialsSalt(user.getCredentialsSalt());
//设置创建者姓名
userEntity.setCreatorName(ShiroAuthenticationManager.getUserAccountName());
userEntity.setCreateTime(new Date(System.currentTimeMillis()));
//设置锁定状态:未锁定;删除状态:未删除
userEntity.setLocked(0);
userEntity.setDeleteStatus(0);
UserInfoEntity userInfo = new UserInfoEntity();
userEntity.setUserInfo(userInfo);
int result = userService.insert(userEntity, password);
if(result == 1)
{
map.put("success", Boolean.TRUE);
map.put("data", null);
map.put("message", "添加成功");
}else
{
map.put("success", Boolean.FALSE);
map.put("data", null);
map.put("message", "添加失败");
}
}catch(ServiceException e)
{
throw new AjaxException(e);
}
return map;
}
@RequestMapping("editUI.html")
public String editUI(Model model, HttpServletRequest request, Long id) {
try
{
UserEntity userEntity = userService.findById(id);
PageUtil page = new PageUtil();
page.setPageNum(Integer.valueOf(request.getParameter("page")));
page.setPageSize(Integer.valueOf(request.getParameter("rows")));
page.setOrderByColumn(request.getParameter("sidx"));
page.setOrderByType(request.getParameter("sord"));
List<RoleEntity> list = roleService.queryListByPage(new HashMap<String, Object>());
model.addAttribute("page", page);
model.addAttribute("userEntity", userEntity);
model.addAttribute("roleList", list);
return Common.BACKGROUND_PATH + "/user/form";
}catch(Exception e)
{
throw new AjaxException(e);
}
}
@RequestMapping("edit.html")
@ResponseBody
public Object update(UserEntity userEntity) throws AjaxException
{
Map<String, Object> map = new HashMap<String, Object>();
try
{
//设置创建者姓名
userEntity.setCreatorName(ShiroAuthenticationManager.getUserAccountName());
int result = userService.update(userEntity);
if(result == 1)
{
map.put("success", Boolean.TRUE);
map.put("data", null);
map.put("message", "编辑成功");
}else
{
map.put("success", Boolean.FALSE);
map.put("data", null);
map.put("message", "编辑失败");
}
}catch(Exception e)
{
throw new AjaxException(e);
}
return map;
}
@RequestMapping("deleteBatch.html")
@ResponseBody
public Object deleteBatch(String ids){
Map<String, Object> result = new HashMap<String, Object>();
try
{
String[] userIds = ids.split(",");
List<Long> list = new ArrayList<Long>();
for (String string : userIds) {
list.add(Long.valueOf(string));
}
int cnt = userService.deleteBatchById(list);
if(cnt == list.size())
{
result.put("success", true);
result.put("data", null);
result.put("message", "删除成功");
}else
{
result.put("success", false);
result.put("data", null);
result.put("message", "删除失败");
}
}catch(Exception e)
{
throw new AjaxException(e);
}
return result;
}
@RequestMapping("resetPassword.html")
@ResponseBody
public Object resetPassword(UserEntity userEntity){
Map<String, Object> result = new HashMap<String, Object>();
try
{
//生成随机密码
String password = RandomUtil.generateString(6);
//加密用户输入的密码,得到密码和加密盐,保存到数据库
UserEntity user = EndecryptUtils.md5Password(userEntity.getAccountName(), password, 2);
//设置添加用户的密码和加密盐
userEntity.setPassword(user.getPassword());
userEntity.setCredentialsSalt(user.getCredentialsSalt());
if(userEntity.getId() == null)
{
user = null;
user = userService.findByName(userEntity.getAccountName());
if(user != null)
{
userEntity.setId(user.getId());
userEntity.setUserName(user.getUserName());
int cnt = userService.updateOnly(userEntity, password);
if(cnt > 0)
{
result.put("success", true);
result.put("data", null);
result.put("message", "密码重置成功");
}else
{
result.put("success", false);
result.put("data", null);
result.put("message", "密码重置失败");
}
}else
{
result.put("success", false);
result.put("data", null);
result.put("message", "账户不存在");
}
}else
{
int cnt = userService.updateOnly(userEntity, password);
if(cnt > 0)
{
result.put("success", true);
result.put("data", null);
result.put("message", "密码重置成功");
}else
{
result.put("success", false);
result.put("data", null);
result.put("message", "密码重置失败");
}
}
}catch(Exception e)
{
throw new AjaxException(e);
}
return result;
}
@RequestMapping("withoutAuth/resetPassWithoutAuthc.html")
@ResponseBody
public Object resetPassWithoutAuthc(UserEntity userEntity){
Map<String, Object> result = new HashMap<String, Object>();
try
{
//生成随机密码
String password = RandomUtil.generateString(6);
//加密用户输入的密码,得到密码和加密盐,保存到数据库
UserEntity user = EndecryptUtils.md5Password(userEntity.getAccountName(), password, 2);
//设置添加用户的密码和加密盐
userEntity.setPassword(user.getPassword());
userEntity.setCredentialsSalt(user.getCredentialsSalt());
user = null;
user = userService.findByName(userEntity.getAccountName());
if(user != null)
{
userEntity.setId(user.getId());
userEntity.setUserName(user.getUserName());
int cnt = userService.updateOnly(userEntity, password);
if(cnt > 0)
{
result.put("success", true);
result.put("data", null);
result.put("message", "密码重置成功");
}else
{
result.put("success", false);
result.put("data", null);
result.put("message", "密码重置失败");
}
}else
{
result.put("success", false);
result.put("data", null);
result.put("message", "账户不存在");
}
}catch(Exception e)
{
throw new AjaxException(e);
}
return result;
}
@RequestMapping("infoUI.html")
public String infoUI(Model model, Long id) {
try
{
UserEntity userEntity = userService.findById(id);
model.addAttribute("userEntity", userEntity);
return Common.BACKGROUND_PATH + "/user/info";
}catch(Exception e)
{
throw new AjaxException(e);
}
}
@RequestMapping("info.html")
@ResponseBody
public Object info(UserEntity userEntity)
{
Map<String, Object> map = new HashMap<String, Object>();
try
{
int result = userService.update(userEntity);
if(result == 1)
{
map.put("success", Boolean.TRUE);
map.put("data", null);
map.put("message", "编辑成功");
}else
{
map.put("success", Boolean.FALSE);
map.put("data", null);
map.put("message", "编辑失败");
}
}catch(Exception e)
{
throw new AjaxException(e);
}
return map;
}
@RequestMapping("passwordUI.html")
public String passwordUI(Model model, UserEntity userEntity) {
try
{
model.addAttribute("userEntity", userEntity);
return Common.BACKGROUND_PATH + "/user/password";
}catch(Exception e)
{
throw new AjaxException(e);
}
}
@RequestMapping("password.html")
@ResponseBody
public Object password(UserEntity userEntity){
Map<String, Object> result = new HashMap<String, Object>();
try
{
String password = userEntity.getPassword();
userEntity.setUserName(new String(userEntity.getUserName().getBytes("iso-8859-1"),"utf-8"));
//加密用户输入的密码,得到密码和加密盐,保存到数据库
UserEntity user = EndecryptUtils.md5Password(userEntity.getAccountName(), userEntity.getPassword(), 2);
//设置添加用户的密码和加密盐
userEntity.setPassword(user.getPassword());
userEntity.setCredentialsSalt(user.getCredentialsSalt());
int cnt = userService.updateOnly(userEntity, password);
if(cnt > 0)
{
result.put("success", true);
result.put("data", null);
result.put("message", "密码修改成功");
}else
{
result.put("success", false);
result.put("data", null);
result.put("message", "密码修改失败");
}
}catch(Exception e)
{
throw new AjaxException(e);
}
return result;
}
@RequestMapping("withoutAuth/validateAccountName.html")
@ResponseBody
public Object validateAccount(String accountName){
try
{
UserEntity userEntity = userService.findByName(accountName);
if(userEntity == null)
{
return true;
}else
{
return false;
}
}catch(Exception e)
{
throw new AjaxException(e);
}
}
}
|
3e016ad597e35f1fd230a185acd3dd3cd15f8db2 | 5,157 | java | Java | src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalTerms.java | navyliu/elasticsearch | c1e67a0d7730d884b3921b691c80d9fb8bef2ef0 | [
"Apache-2.0"
] | 1 | 2019-01-10T00:10:11.000Z | 2019-01-10T00:10:11.000Z | src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalTerms.java | navyliu/elasticsearch | c1e67a0d7730d884b3921b691c80d9fb8bef2ef0 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalTerms.java | navyliu/elasticsearch | c1e67a0d7730d884b3921b691c80d9fb8bef2ef0 | [
"Apache-2.0"
] | null | null | null | 36.574468 | 127 | 0.678301 | 586 | /*
* 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.search.aggregations.bucket.terms;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.bucket.terms.support.BucketPriorityQueue;
import java.util.*;
/**
*
*/
public abstract class InternalTerms extends InternalAggregation implements Terms, ToXContent, Streamable {
public static abstract class Bucket extends Terms.Bucket {
long bucketOrd;
protected long docCount;
protected InternalAggregations aggregations;
protected Bucket(long docCount, InternalAggregations aggregations) {
this.docCount = docCount;
this.aggregations = aggregations;
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
abstract Object getKeyAsObject();
abstract Bucket newBucket(long docCount, InternalAggregations aggs);
public Bucket reduce(List<? extends Bucket> buckets, BigArrays bigArrays) {
long docCount = 0;
List<InternalAggregations> aggregationsList = new ArrayList<>(buckets.size());
for (Bucket bucket : buckets) {
docCount += bucket.docCount;
aggregationsList.add(bucket.aggregations);
}
InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, bigArrays);
return newBucket(docCount, aggs);
}
}
protected InternalOrder order;
protected int requiredSize;
protected long minDocCount;
protected Collection<Bucket> buckets;
protected Map<String, Bucket> bucketMap;
protected InternalTerms() {} // for serialization
protected InternalTerms(String name, InternalOrder order, int requiredSize, long minDocCount, Collection<Bucket> buckets) {
super(name);
this.order = order;
this.requiredSize = requiredSize;
this.minDocCount = minDocCount;
this.buckets = buckets;
}
@Override
public Collection<Terms.Bucket> getBuckets() {
Object o = buckets;
return (Collection<Terms.Bucket>) o;
}
@Override
public Terms.Bucket getBucketByKey(String term) {
if (bucketMap == null) {
bucketMap = Maps.newHashMapWithExpectedSize(buckets.size());
for (Bucket bucket : buckets) {
bucketMap.put(bucket.getKey(), bucket);
}
}
return bucketMap.get(term);
}
@Override
public InternalAggregation reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
Multimap<Object, InternalTerms.Bucket> buckets = ArrayListMultimap.create();
for (InternalAggregation aggregation : aggregations) {
InternalTerms terms = (InternalTerms) aggregation;
for (Bucket bucket : terms.buckets) {
buckets.put(bucket.getKeyAsObject(), bucket);
}
}
final int size = Math.min(requiredSize, buckets.size());
BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null));
for (Collection<Bucket> l : buckets.asMap().values()) {
List<Bucket> sameTermBuckets = (List<Bucket>) l; // cast is ok according to javadocs
final Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext.bigArrays());
if (b.docCount >= minDocCount) {
ordered.insertWithOverflow(b);
}
}
Bucket[] list = new Bucket[ordered.size()];
for (int i = ordered.size() - 1; i >= 0; i--) {
list[i] = (Bucket) ordered.pop();
}
return newAggregation(name, Arrays.asList(list));
}
protected abstract InternalTerms newAggregation(String name, List<Bucket> buckets);
}
|
3e016b5eba3305e3f7b00e4ebbe7dce142b20bb5 | 572 | java | Java | src/main/java/com/emc/rpsp/fal/commons/ConsistencyGroupCopyPolicyParams.java | delirium-software/RPSP | ed34b8c07a97ac99a984b3508c20fba50a0b31d7 | [
"Unlicense",
"MIT"
] | 4 | 2015-05-12T10:10:37.000Z | 2017-06-19T18:58:55.000Z | src/main/java/com/emc/rpsp/fal/commons/ConsistencyGroupCopyPolicyParams.java | emccode/RPSP | ed34b8c07a97ac99a984b3508c20fba50a0b31d7 | [
"Unlicense",
"MIT"
] | 92 | 2016-03-31T15:47:27.000Z | 2016-06-08T07:44:33.000Z | src/main/java/com/emc/rpsp/fal/commons/ConsistencyGroupCopyPolicyParams.java | emccode/RPSP | ed34b8c07a97ac99a984b3508c20fba50a0b31d7 | [
"Unlicense",
"MIT"
] | 1 | 2016-12-27T08:38:31.000Z | 2016-12-27T08:38:31.000Z | 24.869565 | 71 | 0.814685 | 587 | package com.emc.rpsp.fal.commons;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.xml.bind.annotation.*;
@SuppressWarnings("serial")
@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType(name = "ConsistencyGroupCopyPolicyParams")
public class ConsistencyGroupCopyPolicyParams implements Validateable {
@XmlElement(required = true)
private ConsistencyGroupCopyUID copyUid;
@XmlElement(required = true)
private ConsistencyGroupCopyPolicy policy;
}
|
3e016c325b9d5aed682cf38307eccf6f9cbe9005 | 3,381 | java | Java | core/src/test/java/com/sequenceiq/cloudbreak/service/cluster/ClusterCommonServiceTest.java | jgolieb/cloudbreak | 2a374876af1c042961f7342c1c33d25782018d78 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/com/sequenceiq/cloudbreak/service/cluster/ClusterCommonServiceTest.java | jgolieb/cloudbreak | 2a374876af1c042961f7342c1c33d25782018d78 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/com/sequenceiq/cloudbreak/service/cluster/ClusterCommonServiceTest.java | jgolieb/cloudbreak | 2a374876af1c042961f7342c1c33d25782018d78 | [
"Apache-2.0"
] | null | null | null | 33.81 | 83 | 0.707483 | 588 | package com.sequenceiq.cloudbreak.service.cluster;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.InstanceStatus;
import com.sequenceiq.cloudbreak.domain.stack.Stack;
import com.sequenceiq.cloudbreak.domain.stack.cluster.Cluster;
import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceGroup;
import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData;
import com.sequenceiq.cloudbreak.exception.NotFoundException;
import com.sequenceiq.cloudbreak.service.ClusterCommonService;
@RunWith(MockitoJUnitRunner.class)
public class ClusterCommonServiceTest {
@InjectMocks
private ClusterCommonService underTest;
@Before
public void setUp() {
}
@Test
public void testIniFileGeneration() {
// GIVEN
Stack stack = new Stack();
Cluster cluster = new Cluster();
cluster.setId(1L);
cluster.setName("cl1");
cluster.setClusterManagerIp("gatewayIP");
stack.setCluster(cluster);
stack.setInstanceGroups(generateInstanceMetadata());
// WHEN
String result = underTest.getHostNamesAsIniString(stack, "cloudbreak");
// THEN
assertTrue(result.contains("[server]\ngatewayIP\n\n"));
assertTrue(result.contains("[cluster]\nname=cl1\n\n"));
assertTrue(result.contains("[master]\nh1\n"));
assertTrue(result.contains("[agent]\n"));
assertTrue(result.contains("[all:vars]\nansible_ssh_user=cloudbreak\n"));
}
@Test(expected = NotFoundException.class)
public void testIniFileGenerationWithoutAgents() {
Stack stack = new Stack();
Cluster cluster = new Cluster();
cluster.setId(1L);
cluster.setName("cl1");
cluster.setClusterManagerIp(null);
stack.setCluster(cluster);
// WHEN
underTest.getHostNamesAsIniString(stack, "cloudbreak");
}
private Set<InstanceGroup> generateInstanceMetadata() {
Set<InstanceGroup> instanceGroups = new HashSet<>();
InstanceGroup master = new InstanceGroup();
master.setGroupName("master");
InstanceGroup worker = new InstanceGroup();
worker.setGroupName("worker");
InstanceMetaData master1 = new InstanceMetaData();
master1.setDiscoveryFQDN("h1");
master1.setInstanceGroup(master);
master1.setInstanceStatus(InstanceStatus.SERVICES_HEALTHY);
master.setInstanceMetaData(new HashSet<>(Arrays.asList(master1)));
InstanceMetaData worker1 = new InstanceMetaData();
worker1.setDiscoveryFQDN("worker-1");
worker1.setInstanceGroup(worker);
worker1.setInstanceStatus(InstanceStatus.SERVICES_HEALTHY);
InstanceMetaData worker2 = new InstanceMetaData();
worker2.setDiscoveryFQDN("worker-2");
worker2.setInstanceGroup(worker);
worker2.setInstanceStatus(InstanceStatus.SERVICES_HEALTHY);
worker.setInstanceMetaData(new HashSet<>(Arrays.asList(worker1, worker2)));
instanceGroups.add(master);
instanceGroups.add(worker);
return instanceGroups;
}
}
|
3e016c374c96127a8287a4be6c12d0946d11e516 | 1,593 | java | Java | src/main/java/com/datadog/api/v2/client/model/SecurityMonitoringRuleNewValueOptionsLearningDuration.java | nikhilunni/datadog-api-client-java | 4bd5e59917ab3d13784719068faa517a75fdccdd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/datadog/api/v2/client/model/SecurityMonitoringRuleNewValueOptionsLearningDuration.java | nikhilunni/datadog-api-client-java | 4bd5e59917ab3d13784719068faa517a75fdccdd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/datadog/api/v2/client/model/SecurityMonitoringRuleNewValueOptionsLearningDuration.java | nikhilunni/datadog-api-client-java | 4bd5e59917ab3d13784719068faa517a75fdccdd | [
"Apache-2.0"
] | null | null | null | 28.446429 | 109 | 0.741368 | 589 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-Present Datadog, Inc.
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.datadog.api.v2.client.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* The duration in days during which values are learned, and after which signals will be generated
* for values that weren't learned. If set to 0, a signal will be generated for all new values
* after the first value is learned.
*/
public enum SecurityMonitoringRuleNewValueOptionsLearningDuration {
ZERO_DAYS(0),
ONE_DAY(1),
SEVEN_DAYS(7);
private Integer value;
SecurityMonitoringRuleNewValueOptionsLearningDuration(Integer value) {
this.value = value;
}
@JsonValue
public Integer getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static SecurityMonitoringRuleNewValueOptionsLearningDuration fromValue(Integer value) {
for (SecurityMonitoringRuleNewValueOptionsLearningDuration b :
SecurityMonitoringRuleNewValueOptionsLearningDuration.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
}
|
3e016ce52a550376b14803368121a8ea2b2d936d | 2,998 | java | Java | src/main/java/net/haesleinhuepf/clij2/plugins/DistanceMatrixToMesh.java | mmongy/clij2 | c035f061fcf539a8c48b53e943e68700c97697d3 | [
"BSD-3-Clause"
] | 24 | 2020-05-16T20:31:16.000Z | 2022-03-23T11:43:44.000Z | src/main/java/net/haesleinhuepf/clij2/plugins/DistanceMatrixToMesh.java | mmongy/clij2 | c035f061fcf539a8c48b53e943e68700c97697d3 | [
"BSD-3-Clause"
] | 38 | 2020-03-24T11:14:52.000Z | 2022-03-07T15:42:49.000Z | src/main/java/net/haesleinhuepf/clij2/plugins/DistanceMatrixToMesh.java | mmongy/clij2 | c035f061fcf539a8c48b53e943e68700c97697d3 | [
"BSD-3-Clause"
] | 10 | 2020-03-24T11:07:48.000Z | 2022-03-04T08:52:05.000Z | 38.435897 | 173 | 0.724817 | 590 | package net.haesleinhuepf.clij2.plugins;
import net.haesleinhuepf.clij.clearcl.ClearCLBuffer;
import net.haesleinhuepf.clij.macro.CLIJMacroPlugin;
import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor;
import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation;
import net.haesleinhuepf.clij2.AbstractCLIJ2Plugin;
import net.haesleinhuepf.clij2.CLIJ2;
import net.haesleinhuepf.clij2.utilities.HasClassifiedInputOutput;
import net.haesleinhuepf.clij2.utilities.IsCategorized;
import org.scijava.plugin.Plugin;
import java.util.HashMap;
/**
* Author: @haesleinhuepf
* December 2019
*/
@Plugin(type = CLIJMacroPlugin.class, name = "CLIJ2_distanceMatrixToMesh")
public class DistanceMatrixToMesh extends AbstractCLIJ2Plugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation, IsCategorized, HasClassifiedInputOutput {
@Override
public String getInputType() {
return "Matrix";
}
@Override
public String getOutputType() {
return "Image";
}
@Override
public String getParameterHelpText() {
return "Image pointlist, Image distance_matrix, ByRef Image mesh_destination, Number maximum_distance";
}
@Override
public boolean executeCL() {
ClearCLBuffer pointlist = (ClearCLBuffer) args[0];
ClearCLBuffer touch_matrix = (ClearCLBuffer) args[1];
ClearCLBuffer mesh = (ClearCLBuffer) args[2];
Float distanceThreshold = asFloat(args[3]);
return getCLIJ2().distanceMatrixToMesh(pointlist, touch_matrix, mesh, distanceThreshold);
}
public static boolean distanceMatrixToMesh(CLIJ2 clij2, ClearCLBuffer pointlist, ClearCLBuffer distance_matrix, ClearCLBuffer mesh, Float distanceThreshold) {
HashMap<String, Object> parameters = new HashMap<String, Object>();
parameters.put("src_pointlist", pointlist);
parameters.put("src_distance_matrix", distance_matrix);
parameters.put("dst_mesh", mesh);
parameters.put("distance_threshold", distanceThreshold);
long[] dimensions = {distance_matrix.getDimensions()[0], 1, 1};
clij2.activateSizeIndependentKernelCompilation();
clij2.execute(DistanceMatrixToMesh.class, "distance_matrix_to_mesh_x.cl", "distance_matrix_to_mesh", dimensions, dimensions, parameters);
return true;
}
@Override
public String getDescription() {
return "Generates a mesh from a distance matric and a list of point coordinates.\n\n" +
"Takes a pointlist with dimensions n*d with n point coordinates in d dimensions and a distance matrix of " +
"size n*n to draw lines from all points to points if the corresponding pixel in the distance matrix is " +
"smaller than a given distance threshold.";
}
@Override
public String getAvailableForDimensions() {
return "2D, 3D";
}
@Override
public String getCategories() {
return "Visualisation, Graph";
}
}
|
3e016d9520466410543fc5a4c3a1a140bec13b4c | 3,837 | java | Java | modules/activiti-rest/src/main/java/org/activiti/rest/service/api/repository/DeploymentResourceResource.java | wjlc/rd-bpm | dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5 | [
"Apache-1.1"
] | 15 | 2018-09-06T07:57:49.000Z | 2021-02-28T07:40:39.000Z | modules/activiti-rest/src/main/java/org/activiti/rest/service/api/repository/DeploymentResourceResource.java | wjlc/rd-bpm | dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5 | [
"Apache-1.1"
] | 8 | 2019-11-13T08:32:36.000Z | 2022-01-27T16:19:19.000Z | modules/activiti-rest/src/main/java/org/activiti/rest/service/api/repository/DeploymentResourceResource.java | wjlc/rd-bpm | dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5 | [
"Apache-1.1"
] | 16 | 2018-09-07T07:56:35.000Z | 2021-11-12T03:09:18.000Z | 45.678571 | 242 | 0.776388 | 591 | /* 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.activiti.rest.service.api.repository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.rest.common.application.ContentTypeResolver;
import org.activiti.rest.service.api.RestResponseFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Frederik Heremans
*/
@RestController
@Api(tags = { "Deployment" }, description = "Manage Deployment", authorizations = { @Authorization(value = "basicAuth") })
public class DeploymentResourceResource {
@Autowired
protected RestResponseFactory restResponseFactory;
@Autowired
protected ContentTypeResolver contentTypeResolver;
@Autowired
protected RepositoryService repositoryService;
@ApiOperation(value = "Get a deployment resource", tags = {"Deployment"}, notes="Replace ** by ResourceId")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates both deployment and resource have been found and the resource has been returned."),
@ApiResponse(code = 404, message = "Indicates the requested deployment was not found or there is no resource with the given id present in the deployment. The status-description contains additional information.")
})
@RequestMapping(value = "/repository/deployments/{deploymentId}/resources/**", method = RequestMethod.GET, produces = "application/json")
public DeploymentResourceResponse getDeploymentResource(@ApiParam(name = "deploymentId", value = "The id of the deployment the requested resource is part of.") @PathVariable("deploymentId") String deploymentId, HttpServletRequest request) {
Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
if (deployment == null) {
throw new ActivitiObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.");
}
String pathInfo = request.getPathInfo();
String resourceName = pathInfo.replace("/repository/deployments/" + deploymentId + "/resources/", "");
List<String> resourceList = repositoryService.getDeploymentResourceNames(deploymentId);
if (resourceList.contains(resourceName)) {
// Build resource representation
DeploymentResourceResponse response = restResponseFactory.createDeploymentResourceResponse(deploymentId, resourceName, contentTypeResolver.resolveContentType(resourceName));
return response;
} else {
// Resource not found in deployment
throw new ActivitiObjectNotFoundException("Could not find a resource with id '" + resourceName + "' in deployment '" + deploymentId + "'.");
}
}
}
|
3e016e2a699400c415de2d4165f557ecb9ed0fb0 | 4,036 | java | Java | plug-ins/helios/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Reference.java | TheRakeshPurohit/CodingSpectator | badd6efaaa8d187983d11c94012da747dda0c85a | [
"NCSA"
] | 5 | 2015-01-20T10:33:20.000Z | 2021-05-11T06:56:51.000Z | plug-ins/helios/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Reference.java | TheRakeshPurohit/CodingSpectator | badd6efaaa8d187983d11c94012da747dda0c85a | [
"NCSA"
] | null | null | null | plug-ins/helios/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/Reference.java | TheRakeshPurohit/CodingSpectator | badd6efaaa8d187983d11c94012da747dda0c85a | [
"NCSA"
] | 7 | 2015-02-13T10:21:04.000Z | 2019-05-08T06:04:40.000Z | 43.397849 | 192 | 0.726462 | 592 | /*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.ast;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.Opcodes;
import org.eclipse.jdt.internal.compiler.flow.FlowContext;
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
public abstract class Reference extends Expression {
/**
* BaseLevelReference constructor comment.
*/
public Reference() {
super();
}
public abstract FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound);
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
return flowInfo;
}
public FieldBinding fieldBinding() {
//this method should be sent one FIELD-tagged references
// (ref.bits & BindingIds.FIELD != 0)()
return null;
}
public void fieldStore(Scope currentScope, CodeStream codeStream, FieldBinding fieldBinding, MethodBinding syntheticWriteAccessor, TypeBinding receiverType, boolean isImplicitThisReceiver,
boolean valueRequired) {
int pc= codeStream.position;
if (fieldBinding.isStatic()) {
if (valueRequired) {
switch (fieldBinding.type.id) {
case TypeIds.T_long:
case TypeIds.T_double:
codeStream.dup2();
break;
default:
codeStream.dup();
break;
}
}
if (syntheticWriteAccessor == null) {
TypeBinding constantPoolDeclaringClass= CodeStream.getConstantPoolDeclaringClass(currentScope, fieldBinding, receiverType, isImplicitThisReceiver);
codeStream.fieldAccess(Opcodes.OPC_putstatic, fieldBinding, constantPoolDeclaringClass);
} else {
codeStream.invoke(Opcodes.OPC_invokestatic, syntheticWriteAccessor, null /* default declaringClass */);
}
} else { // Stack: [owner][new field value] ---> [new field value][owner][new field value]
if (valueRequired) {
switch (fieldBinding.type.id) {
case TypeIds.T_long:
case TypeIds.T_double:
codeStream.dup2_x1();
break;
default:
codeStream.dup_x1();
break;
}
}
if (syntheticWriteAccessor == null) {
TypeBinding constantPoolDeclaringClass= CodeStream.getConstantPoolDeclaringClass(currentScope, fieldBinding, receiverType, isImplicitThisReceiver);
codeStream.fieldAccess(Opcodes.OPC_putfield, fieldBinding, constantPoolDeclaringClass);
} else {
codeStream.invoke(Opcodes.OPC_invokestatic, syntheticWriteAccessor, null /* default declaringClass */);
}
}
codeStream.recordPositionsFrom(pc, this.sourceStart);
}
public abstract void generateAssignment(BlockScope currentScope, CodeStream codeStream, Assignment assignment, boolean valueRequired);
public abstract void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired);
public abstract void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired);
}
|
3e016edb787d6a8bcfb17fe4ef3ce3496d26785e | 10,795 | java | Java | clients/google-api-services-content/v2.1/1.31.0/com/google/api/services/content/model/OrderTrackingSignal.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 372 | 2018-09-05T21:06:51.000Z | 2022-03-31T09:22:03.000Z | clients/google-api-services-content/v2.1/1.31.0/com/google/api/services/content/model/OrderTrackingSignal.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 1,351 | 2018-10-12T23:07:12.000Z | 2022-03-05T09:25:29.000Z | clients/google-api-services-content/v2.1/1.31.0/com/google/api/services/content/model/OrderTrackingSignal.java | yoshi-code-bot/google-api-java-client-services | 9f5e3b6073c822db4078d638c980b11a0effc686 | [
"Apache-2.0"
] | 307 | 2018-09-04T20:15:31.000Z | 2022-03-31T09:42:39.000Z | 35.048701 | 182 | 0.723205 | 593 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.content.model;
/**
* Represents a merchant trade from which signals are extracted, e.g. shipping.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class OrderTrackingSignal extends com.google.api.client.json.GenericJson {
/**
* The shipping fee of the order; this value should be set to zero in the case of free shipping.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PriceAmount customerShippingFee;
/**
* Required. The delivery postal code, as a continuous string without spaces or dashes, e.g.
* "95016". This field will be anonymized in returned OrderTrackingSignal creation response.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String deliveryPostalCode;
/**
* Required. The [CLDR territory code]
* (http://www.unicode.org/repos/cldr/tags/latest/common/main/en.xml) for the shipping
* destination.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String deliveryRegionCode;
/**
* Information about line items in the order.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<OrderTrackingSignalLineItemDetails> lineItems;
/**
* The Google merchant ID of this order tracking signal. This value is optional. If left unset,
* the caller's merchant ID is used. You must request access in order to provide data on behalf of
* another merchant. For more information, see [Submitting Order Tracking Signals](/shopping-
* content/guides/order-tracking-signals).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long merchantId;
/**
* Required. The time when the order was created on the merchant side. Include the year and
* timezone string, if available.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DateTime orderCreatedTime;
/**
* Required. The ID of the order on the merchant side. This field will be hashed in returned
* OrderTrackingSignal creation response.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String orderId;
/**
* Output only. The ID that uniquely identifies this order tracking signal.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long orderTrackingSignalId;
/**
* The mapping of the line items to the shipment information.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<OrderTrackingSignalShipmentLineItemMapping> shipmentLineItemMapping;
/**
* The shipping information for the order.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<OrderTrackingSignalShippingInfo> shippingInfo;
/**
* The shipping fee of the order; this value should be set to zero in the case of free shipping.
* @return value or {@code null} for none
*/
public PriceAmount getCustomerShippingFee() {
return customerShippingFee;
}
/**
* The shipping fee of the order; this value should be set to zero in the case of free shipping.
* @param customerShippingFee customerShippingFee or {@code null} for none
*/
public OrderTrackingSignal setCustomerShippingFee(PriceAmount customerShippingFee) {
this.customerShippingFee = customerShippingFee;
return this;
}
/**
* Required. The delivery postal code, as a continuous string without spaces or dashes, e.g.
* "95016". This field will be anonymized in returned OrderTrackingSignal creation response.
* @return value or {@code null} for none
*/
public java.lang.String getDeliveryPostalCode() {
return deliveryPostalCode;
}
/**
* Required. The delivery postal code, as a continuous string without spaces or dashes, e.g.
* "95016". This field will be anonymized in returned OrderTrackingSignal creation response.
* @param deliveryPostalCode deliveryPostalCode or {@code null} for none
*/
public OrderTrackingSignal setDeliveryPostalCode(java.lang.String deliveryPostalCode) {
this.deliveryPostalCode = deliveryPostalCode;
return this;
}
/**
* Required. The [CLDR territory code]
* (http://www.unicode.org/repos/cldr/tags/latest/common/main/en.xml) for the shipping
* destination.
* @return value or {@code null} for none
*/
public java.lang.String getDeliveryRegionCode() {
return deliveryRegionCode;
}
/**
* Required. The [CLDR territory code]
* (http://www.unicode.org/repos/cldr/tags/latest/common/main/en.xml) for the shipping
* destination.
* @param deliveryRegionCode deliveryRegionCode or {@code null} for none
*/
public OrderTrackingSignal setDeliveryRegionCode(java.lang.String deliveryRegionCode) {
this.deliveryRegionCode = deliveryRegionCode;
return this;
}
/**
* Information about line items in the order.
* @return value or {@code null} for none
*/
public java.util.List<OrderTrackingSignalLineItemDetails> getLineItems() {
return lineItems;
}
/**
* Information about line items in the order.
* @param lineItems lineItems or {@code null} for none
*/
public OrderTrackingSignal setLineItems(java.util.List<OrderTrackingSignalLineItemDetails> lineItems) {
this.lineItems = lineItems;
return this;
}
/**
* The Google merchant ID of this order tracking signal. This value is optional. If left unset,
* the caller's merchant ID is used. You must request access in order to provide data on behalf of
* another merchant. For more information, see [Submitting Order Tracking Signals](/shopping-
* content/guides/order-tracking-signals).
* @return value or {@code null} for none
*/
public java.lang.Long getMerchantId() {
return merchantId;
}
/**
* The Google merchant ID of this order tracking signal. This value is optional. If left unset,
* the caller's merchant ID is used. You must request access in order to provide data on behalf of
* another merchant. For more information, see [Submitting Order Tracking Signals](/shopping-
* content/guides/order-tracking-signals).
* @param merchantId merchantId or {@code null} for none
*/
public OrderTrackingSignal setMerchantId(java.lang.Long merchantId) {
this.merchantId = merchantId;
return this;
}
/**
* Required. The time when the order was created on the merchant side. Include the year and
* timezone string, if available.
* @return value or {@code null} for none
*/
public DateTime getOrderCreatedTime() {
return orderCreatedTime;
}
/**
* Required. The time when the order was created on the merchant side. Include the year and
* timezone string, if available.
* @param orderCreatedTime orderCreatedTime or {@code null} for none
*/
public OrderTrackingSignal setOrderCreatedTime(DateTime orderCreatedTime) {
this.orderCreatedTime = orderCreatedTime;
return this;
}
/**
* Required. The ID of the order on the merchant side. This field will be hashed in returned
* OrderTrackingSignal creation response.
* @return value or {@code null} for none
*/
public java.lang.String getOrderId() {
return orderId;
}
/**
* Required. The ID of the order on the merchant side. This field will be hashed in returned
* OrderTrackingSignal creation response.
* @param orderId orderId or {@code null} for none
*/
public OrderTrackingSignal setOrderId(java.lang.String orderId) {
this.orderId = orderId;
return this;
}
/**
* Output only. The ID that uniquely identifies this order tracking signal.
* @return value or {@code null} for none
*/
public java.lang.Long getOrderTrackingSignalId() {
return orderTrackingSignalId;
}
/**
* Output only. The ID that uniquely identifies this order tracking signal.
* @param orderTrackingSignalId orderTrackingSignalId or {@code null} for none
*/
public OrderTrackingSignal setOrderTrackingSignalId(java.lang.Long orderTrackingSignalId) {
this.orderTrackingSignalId = orderTrackingSignalId;
return this;
}
/**
* The mapping of the line items to the shipment information.
* @return value or {@code null} for none
*/
public java.util.List<OrderTrackingSignalShipmentLineItemMapping> getShipmentLineItemMapping() {
return shipmentLineItemMapping;
}
/**
* The mapping of the line items to the shipment information.
* @param shipmentLineItemMapping shipmentLineItemMapping or {@code null} for none
*/
public OrderTrackingSignal setShipmentLineItemMapping(java.util.List<OrderTrackingSignalShipmentLineItemMapping> shipmentLineItemMapping) {
this.shipmentLineItemMapping = shipmentLineItemMapping;
return this;
}
/**
* The shipping information for the order.
* @return value or {@code null} for none
*/
public java.util.List<OrderTrackingSignalShippingInfo> getShippingInfo() {
return shippingInfo;
}
/**
* The shipping information for the order.
* @param shippingInfo shippingInfo or {@code null} for none
*/
public OrderTrackingSignal setShippingInfo(java.util.List<OrderTrackingSignalShippingInfo> shippingInfo) {
this.shippingInfo = shippingInfo;
return this;
}
@Override
public OrderTrackingSignal set(String fieldName, Object value) {
return (OrderTrackingSignal) super.set(fieldName, value);
}
@Override
public OrderTrackingSignal clone() {
return (OrderTrackingSignal) super.clone();
}
}
|
3e016f5055ef4e2f08485b0ab04934b31de4779b | 975 | java | Java | mall-coupon/src/main/java/org/june/coupon/entity/SeckillSkuRelationEntity.java | Robert-byte-s/mall-project | 419933c892035bc7ee599e69d626545ed60f19c0 | [
"Apache-2.0"
] | null | null | null | mall-coupon/src/main/java/org/june/coupon/entity/SeckillSkuRelationEntity.java | Robert-byte-s/mall-project | 419933c892035bc7ee599e69d626545ed60f19c0 | [
"Apache-2.0"
] | null | null | null | mall-coupon/src/main/java/org/june/coupon/entity/SeckillSkuRelationEntity.java | Robert-byte-s/mall-project | 419933c892035bc7ee599e69d626545ed60f19c0 | [
"Apache-2.0"
] | null | null | null | 17.105263 | 63 | 0.619487 | 594 | package org.june.coupon.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 秒杀活动商品关联
*
* @author lishaobo
* @email hzdkv@example.com
* @date 2022-02-06 19:55:01
*/
@Data
@TableName("sms_seckill_sku_relation")
public class SeckillSkuRelationEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 活动id
*/
private Long promotionId;
/**
* 活动场次id
*/
private Long promotionSessionId;
/**
* 商品id
*/
private Long skuId;
/**
* 秒杀价格
*/
private BigDecimal seckillPrice;
/**
* 秒杀总量
*/
private BigDecimal seckillCount;
/**
* 每人限购数量
*/
private Integer seckillLimit;
/**
* 排序
*/
private Integer seckillSort;
}
|
3e017002bd408b8749f913d455507b2acd1eef22 | 981 | java | Java | src/test/java/com/comcast/pantry/io/ByteArrayCreator.java | Comcast/pantry | e2924184d9114dcbdc1b31924cb4445553e4f03a | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-02-02T05:20:00.000Z | 2019-02-02T05:20:00.000Z | src/test/java/com/comcast/pantry/io/ByteArrayCreator.java | DalavanCloud/pantry | e2924184d9114dcbdc1b31924cb4445553e4f03a | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2018-07-26T18:02:40.000Z | 2018-07-26T18:03:02.000Z | src/test/java/com/comcast/pantry/io/ByteArrayCreator.java | DalavanCloud/pantry | e2924184d9114dcbdc1b31924cb4445553e4f03a | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-07-23T22:58:53.000Z | 2019-02-02T05:19:50.000Z | 28.028571 | 75 | 0.708461 | 595 | /**
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.comcast.pantry.io;
import java.util.Random;
public class ByteArrayCreator {
private Random rand;
public ByteArrayCreator(long seed) {
this.rand = new Random(seed);
}
public byte[] getBytes(int length) {
byte[] contents = new byte[length];
rand.nextBytes(contents);
return contents;
}
}
|
3e0171b2ed30b03b99353d51776defd5b81db0ff | 1,754 | java | Java | src/main/java/dev/negativekb/kitpvpframework/core/structure/region/DataPoint.java | NegativeKB/KitPvP-Framework | e9f8f840edaa3f579823890a3655b10f69742725 | [
"MIT"
] | 3 | 2021-11-04T09:38:19.000Z | 2022-01-26T12:28:04.000Z | src/main/java/dev/negativekb/kitpvpframework/core/structure/region/DataPoint.java | xtoples/KitPvP-Framework | 36f4bd139e6eb542662ca7c99f049ffe438e33fb | [
"MIT"
] | 9 | 2021-10-29T18:26:54.000Z | 2021-11-04T06:38:48.000Z | src/main/java/dev/negativekb/kitpvpframework/core/structure/region/DataPoint.java | xtoples/KitPvP-Framework | 36f4bd139e6eb542662ca7c99f049ffe438e33fb | [
"MIT"
] | 3 | 2021-11-06T17:52:02.000Z | 2022-01-26T12:28:07.000Z | 33.730769 | 81 | 0.72691 | 596 | /*
* MIT License
*
* Copyright (c) 2021 Negative
*
* 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 dev.negativekb.kitpvpframework.core.structure.region;
import lombok.Data;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import java.util.Objects;
@Data
public class DataPoint {
private String world;
private double x;
private double y;
private double z;
public DataPoint(Location location) {
this.world = Objects.requireNonNull(location.getWorld()).getName();
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
}
public Location toLocation() {
return new Location(Bukkit.getWorld(world), x, y, z);
}
}
|
3e017261da86b80775c5ac4900c1105bf46522cb | 2,481 | java | Java | test/Datagrams.java | tarotanaka0/avian | 56253e31237e42acefbaa93d473ce62a861e8126 | [
"0BSD"
] | 1 | 2022-02-02T23:44:49.000Z | 2022-02-02T23:44:49.000Z | test/Datagrams.java | geeksville/avian | dfdd1f6e6c55ada96172f40d1256dc219637c492 | [
"0BSD"
] | null | null | null | test/Datagrams.java | geeksville/avian | dfdd1f6e6c55ada96172f40d1256dc219637c492 | [
"0BSD"
] | null | null | null | 27.876404 | 76 | 0.528416 | 597 | import java.net.SocketAddress;
import java.net.InetSocketAddress;
import java.net.ProtocolFamily;
import java.net.StandardProtocolFamily;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
public class Datagrams {
private static void expect(boolean v) {
if (! v) throw new RuntimeException();
}
private static boolean equal(byte[] a, int aOffset, byte[] b, int bOffset,
int length)
{
for (int i = 0; i < length; ++i) {
if (a[aOffset + i] != b[bOffset + i]) return false;
}
return true;
}
public static void main(String[] args) throws Exception {
final String Hostname = "localhost";
final int Port = 22043;
final SocketAddress Address = new InetSocketAddress(Hostname, Port);
final byte[] Message = "hello, world!".getBytes();
DatagramChannel out = DatagramChannel.open();
try {
out.configureBlocking(false);
out.connect(Address);
DatagramChannel in = DatagramChannel.open();
try {
in.configureBlocking(false);
in.socket().bind(Address);
Selector selector = Selector.open();
try {
SelectionKey outKey = out.register
(selector, SelectionKey.OP_WRITE, null);
SelectionKey inKey = in.register
(selector, SelectionKey.OP_READ, null);
int state = 0;
ByteBuffer inBuffer = ByteBuffer.allocate(Message.length);
loop: while (true) {
selector.select();
switch (state) {
case 0: {
if (outKey.isWritable()) {
out.write(ByteBuffer.wrap(Message));
state = 1;
}
} break;
case 1: {
if (inKey.isReadable()) {
in.receive(inBuffer);
if (! inBuffer.hasRemaining()) {
expect(equal(inBuffer.array(),
inBuffer.arrayOffset(),
Message,
0,
Message.length));
break loop;
}
}
} break;
default: throw new RuntimeException();
}
}
} finally {
selector.close();
}
} finally {
in.close();
}
} finally {
out.close();
}
}
}
|
3e01737b80775bd0abbf7581b5ae5ff4a60a7b4a | 10,417 | java | Java | src/test/java/com/grayfox/server/ws/rest/UserWebServiceTest.java | dan-zx/gray-fox-server | 804e3381ce94c7825ca334bce2bd56f86f5634e0 | [
"Apache-2.0"
] | 3 | 2015-06-12T01:19:32.000Z | 2016-08-07T15:33:39.000Z | src/test/java/com/grayfox/server/ws/rest/UserWebServiceTest.java | dan-zx/gray-fox-server | 804e3381ce94c7825ca334bce2bd56f86f5634e0 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/grayfox/server/ws/rest/UserWebServiceTest.java | dan-zx/gray-fox-server | 804e3381ce94c7825ca334bce2bd56f86f5634e0 | [
"Apache-2.0"
] | 7 | 2015-06-12T01:29:34.000Z | 2020-11-01T11:00:32.000Z | 54.826316 | 188 | 0.722185 | 598 | /*
* Copyright 2014-2015 Daniel Pedraza-Arcega
*
* 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.grayfox.server.ws.rest;
import static org.assertj.core.api.Assertions.assertThat;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.grayfox.server.test.BaseWebServiceTest;
import com.grayfox.server.ws.rest.response.AccessTokenResponse;
import com.grayfox.server.ws.rest.response.ApiResponse;
import com.grayfox.server.ws.rest.response.ErrorResponse;
import org.junit.Test;
public class UserWebServiceTest extends BaseWebServiceTest {
@Test
public void testService() {
Response response = target("users/register/foursquare").queryParam("authorization_code", "fakeCode").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
ApiResponse<AccessTokenResponse> accesTokenResponse = new Gson().fromJson(response.readEntity(String.class), new TypeToken<ApiResponse<AccessTokenResponse>>() {}.getType());
assertThat(accesTokenResponse).isNotNull();
assertThat(accesTokenResponse.getResponse()).isNotNull();
assertThat(accesTokenResponse.getResponse().getAccessToken()).isNotNull().isNotEmpty();
}
@Test
public void testAuthenticationError() {
Response response = target("users/register/foursquare").queryParam("authorization_code", "invalidCode").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("foursquare.authentication.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testMissingParamsWhenRegistering() {
Response response = target("users/register/foursquare").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("param.validation.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testMissingParamsWhenRequestingSelf() {
Response response = target("users/self").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("param.validation.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testAuthenticationErrorWhenRequestingSelf() {
Response response = target("users/self").queryParam("access_token", "invalidToken").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.UNAUTHORIZED.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("user.invalid.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testMissingParamsWhenRequestingSelfFriends() {
Response response = target("users/self/friends").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("param.validation.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testAuthenticationErrorWhenRequestingSelfFriends() {
Response response = target("users/self/friends").queryParam("access_token", "invalidToken").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.UNAUTHORIZED.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("user.invalid.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testMissingParamsWhenRequestingSelfLikes() {
Response response = target("users/self/likes").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("param.validation.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testAuthenticationErrorWhenRequestingSelfLikes() {
Response response = target("users/self/likes").queryParam("access_token", "invalidToken").request().get();
assertThat(response.getStatus()).isEqualTo(Response.Status.UNAUTHORIZED.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("user.invalid.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testMissingParamsWhenAddingLike() {
Response response = target("users/self/update/addlike").request().put(Entity.text(""));
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("param.validation.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testAuthenticationErrorWhenAddingLike() {
Response response = target("users/self/update/addlike").queryParam("access_token", "invalidToken").queryParam("category_foursquare_id", "invalidId").request().put(Entity.text(""));
assertThat(response.getStatus()).isEqualTo(Response.Status.UNAUTHORIZED.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("user.invalid.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testMissingParamsWhenRemovingLike() {
Response response = target("users/self/update/removelike").request().delete();
assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("param.validation.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
@Test
public void testAuthenticationErrorWhenRemovingLike() {
Response response = target("users/self/update/removelike").queryParam("access_token", "invalidToken").queryParam("category_foursquare_id", "anyId").request().delete();
assertThat(response.getStatus()).isEqualTo(Response.Status.UNAUTHORIZED.getStatusCode());
Gson gson = new Gson();
ErrorResponse errorResponse = gson.fromJson(gson.fromJson(response.readEntity(String.class), JsonObject.class).get("error"), ErrorResponse.class);
assertThat(errorResponse).isNotNull();
assertThat(errorResponse.getErrorCode()).isNotNull().isNotEmpty().isEqualTo("user.invalid.error");
assertThat(errorResponse.getErrorMessage()).isNotNull().isNotEmpty();
}
} |
3e0174c2a6c1131f3c06d44c45a1b4f81fbaa123 | 5,621 | java | Java | src/test/java/nom/bdezonia/zorbage/type/helper/TestMatrixDiagonalRModuleBridge.java | bdezonia/zorbage | 853eb95ad358d7797740cba5ce04d4dbeaa71027 | [
"BSD-3-Clause"
] | 8 | 2019-04-16T11:03:55.000Z | 2021-06-06T06:41:06.000Z | src/test/java/nom/bdezonia/zorbage/type/helper/TestMatrixDiagonalRModuleBridge.java | bdezonia/zorbage | 853eb95ad358d7797740cba5ce04d4dbeaa71027 | [
"BSD-3-Clause"
] | 37 | 2019-05-07T19:14:40.000Z | 2021-06-28T11:30:28.000Z | src/test/java/nom/bdezonia/zorbage/type/helper/TestMatrixDiagonalRModuleBridge.java | bdezonia/zorbage | 853eb95ad358d7797740cba5ce04d4dbeaa71027 | [
"BSD-3-Clause"
] | null | null | null | 36.5 | 113 | 0.732254 | 599 | /*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package nom.bdezonia.zorbage.type.helper;
import static org.junit.Assert.assertEquals;
import org.junit.Test; import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.algorithm.RampFill;
import nom.bdezonia.zorbage.type.helper.MatrixDiagonalRModuleBridge.Origin;
import nom.bdezonia.zorbage.type.real.float64.Float64MatrixMember;
import nom.bdezonia.zorbage.type.real.float64.Float64Member;
/**
*
* @author Barry DeZonia
*
*/
public class TestMatrixDiagonalRModuleBridge {
@Test
public void testDiags() {
Float64MatrixMember matrix = new Float64MatrixMember(5,5,new double[25]);
Float64Member value = new Float64Member();
RampFill.compute(G.DBL, matrix.rawData());
MatrixDiagonalRModuleBridge<Float64Member> diag = new MatrixDiagonalRModuleBridge<Float64Member>(G.DBL,matrix);
assertEquals(5, diag.length());
for (long i = 0; i < diag.length(); i++) {
diag.getV(i, value);
assertEquals(i*6,value.v(),0);
}
diag.setDiagonal(Origin.UpperLeft, 1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.UpperLeft, 2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.UpperLeft, 3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.UpperLeft, 4);
assertEquals(1, diag.length());
assertEquals(0, diag.row(0));
assertEquals(4, diag.col(0));
diag.setDiagonal(Origin.UpperLeft, -1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.UpperLeft, -2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.UpperLeft, -3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.UpperLeft, -4);
assertEquals(1, diag.length());
assertEquals(4, diag.row(0));
assertEquals(0, diag.col(0));
diag.setDiagonal(Origin.LowerLeft, 1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.LowerLeft, 2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.LowerLeft, 3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.LowerLeft, 4);
assertEquals(1, diag.length());
assertEquals(0, diag.row(0));
assertEquals(0, diag.col(0));
diag.setDiagonal(Origin.LowerLeft, -1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.LowerLeft, -2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.LowerLeft, -3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.LowerLeft, -4);
assertEquals(1, diag.length());
assertEquals(4, diag.row(0));
assertEquals(4, diag.col(0));
diag.setDiagonal(Origin.LowerRight, 1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.LowerRight, 2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.LowerRight, 3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.LowerRight, 4);
assertEquals(1, diag.length());
assertEquals(4, diag.row(0));
assertEquals(0, diag.col(0));
diag.setDiagonal(Origin.LowerRight, -1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.LowerRight, -2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.LowerRight, -3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.LowerRight, -4);
assertEquals(1, diag.length());
assertEquals(0, diag.row(0));
assertEquals(4, diag.col(0));
diag.setDiagonal(Origin.UpperRight, 1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.UpperRight, 2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.UpperRight, 3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.UpperRight, 4);
assertEquals(1, diag.length());
assertEquals(4, diag.row(0));
assertEquals(4, diag.col(0));
diag.setDiagonal(Origin.UpperRight, -1);
assertEquals(4, diag.length());
diag.setDiagonal(Origin.UpperRight, -2);
assertEquals(3, diag.length());
diag.setDiagonal(Origin.UpperRight, -3);
assertEquals(2, diag.length());
diag.setDiagonal(Origin.UpperRight, -4);
assertEquals(1, diag.length());
assertEquals(0, diag.row(0));
assertEquals(0, diag.col(0));
// TODO: test non-square matrices
// TODO: test illegal arg edge conditions
}
}
|
3e0175800edfb7c0b2752c966a7183b2dc4fb17a | 6,726 | java | Java | spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/AbstractShellIntegrationTest.java | dsyer/spring-cloud-dataflow | 7a9da33139cd29d2929d2c3d76c32389d3c808c0 | [
"Apache-2.0"
] | null | null | null | spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/AbstractShellIntegrationTest.java | dsyer/spring-cloud-dataflow | 7a9da33139cd29d2929d2c3d76c32389d3c808c0 | [
"Apache-2.0"
] | null | null | null | spring-cloud-dataflow-shell/src/test/java/org/springframework/cloud/dataflow/shell/AbstractShellIntegrationTest.java | dsyer/spring-cloud-dataflow | 7a9da33139cd29d2929d2c3d76c32389d3c808c0 | [
"Apache-2.0"
] | 1 | 2020-05-29T09:08:11.000Z | 2020-05-29T09:08:11.000Z | 31.429907 | 98 | 0.752453 | 600 | /*
* Copyright 2015-2016 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.cloud.dataflow.shell;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.dataflow.admin.AdminApplication;
import org.springframework.cloud.dataflow.admin.config.AdminConfiguration;
import org.springframework.cloud.dataflow.artifact.registry.InMemoryArtifactRegistry;
import org.springframework.cloud.dataflow.artifact.registry.ArtifactRegistry;
import org.springframework.cloud.dataflow.shell.command.StreamCommandTemplate;
import org.springframework.cloud.dataflow.shell.command.TaskCommandTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.shell.Bootstrap;
import org.springframework.shell.core.CommandResult;
import org.springframework.shell.core.JLineShellComponent;
import org.springframework.util.AlternativeJdkIdGenerator;
import org.springframework.util.Assert;
import org.springframework.util.IdGenerator;
import org.springframework.util.SocketUtils;
/**
* Base class for shell integration tests. This class sets up and tears down
* the infrastructure required for executing shell tests - in particular, the
* {@link AdminApplication} server.
* <p>
* Extensions of this class may obtain instances of command templates.
* For example, call {@link #stream} to obtain a {@link StreamCommandTemplate}
* in order to perform stream operations.
*
* @author Ilayaperumal Gopinathan
* @author Patrick Peralta
* @author Glenn Renfro
*/
public abstract class AbstractShellIntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(AbstractShellIntegrationTest.class);
/**
* Generator used to create random stream names.
*/
private final IdGenerator idGenerator = new AlternativeJdkIdGenerator();
/**
* System property indicating whether the test infrastructure should
* be shut down after all tests are executed. If running in a test
* suite, this system property should be set to {@code false} to allow
* multiple tests to execute with the same admin server.
*/
public static final String SHUTDOWN_AFTER_RUN = "shutdown.after.run";
/**
* Indicates whether the test infrastructure should be shut down
* after all tests are executed.
*
* @see #SHUTDOWN_AFTER_RUN
*/
private static boolean shutdownAfterRun = false;
/**
* Application context for admin application.
*/
protected static ApplicationContext applicationContext;
/**
* Instance of shell to execute commands for testing.
*/
private static DataFlowShell dataFlowShell;
/**
* TCP port for the admin server.
*/
private static final int adminPort = SocketUtils.findAvailableTcpPort();
/**
* Used to capture currently executing test method.
*/
@Rule
public TestName name = new TestName();
@BeforeClass
public static void startUp() throws InterruptedException, IOException {
if (applicationContext == null) {
if (System.getProperty(SHUTDOWN_AFTER_RUN) != null) {
shutdownAfterRun = Boolean.getBoolean(SHUTDOWN_AFTER_RUN);
}
SpringApplication application = new SpringApplicationBuilder(AdminApplication.class,
AdminConfiguration.class, TestConfig.class).build();
applicationContext = application.run(
String.format("--server.port=%s", adminPort), "--security.basic.enabled=false",
"--spring.main.show_banner=false", "--spring.cloud.config.enabled=false",
"--deployer.local.out-of-process=false");
}
JLineShellComponent shell = new Bootstrap(new String[] {"--port", String.valueOf(adminPort)})
.getJLineShellComponent();
if (!shell.isRunning()) {
shell.start();
}
dataFlowShell = new DataFlowShell(shell);
}
@AfterClass
public static void shutdown() {
if (shutdownAfterRun) {
logger.info("Stopping Data Flow Shell");
if (dataFlowShell != null) {
dataFlowShell.stop();
}
if (applicationContext != null) {
logger.info("Stopping Data Flow Admin Server");
SpringApplication.exit(applicationContext);
applicationContext = null;
}
}
}
/**
* Return a {@link StreamCommandTemplate} for issuing shell based stream commands.
*
* @return template for issuing stream commands
*/
protected StreamCommandTemplate stream() {
return new StreamCommandTemplate(dataFlowShell);
}
/**
* Return a {@link TaskCommandTemplate} for issuing shell based task commands.
*
* @return template for issuing task commands
*/
protected TaskCommandTemplate task() {
return new TaskCommandTemplate(dataFlowShell);
}
// Util methods
/**
* Return a unique random name for stream/task testing.
*
* @param name name to use as part of stream/task name
* @return unique random stream/task name
*/
protected String generateUniqueName(String name) {
return name + "-" + idGenerator.generateId();
}
/**
* Return a unique random name for stream/task testing.
*
* @return unique random stream/task name
*/
protected String generateUniqueName() {
return generateUniqueName(name.getMethodName().replace('[', '-').replaceAll("]", ""));
}
private static class DataFlowShell extends JLineShellComponent {
private final JLineShellComponent shell;
public DataFlowShell(JLineShellComponent shell) {
this.shell = shell;
}
public CommandResult executeCommand(String command) {
CommandResult cr = this.shell.executeCommand(command);
if (cr.getException() != null) {
cr.getException().printStackTrace();
}
Assert.isTrue(cr.isSuccess(), "Failure. CommandResult = " + cr.toString());
return cr;
}
}
/**
* Configuration for admin server that is specific to shell tests.
*/
@Configuration
public static class TestConfig {
@Bean
public ArtifactRegistry artifactRegistry() {
return new InMemoryArtifactRegistry();
}
}
}
|
Subsets and Splits