hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923ad7e34d9dd22772ea0c538fe3476d7a230a21 | 10,631 | java | Java | src/main/java/io/connectedhealth_idaas/eventbuilder/builders/hl7/RAS_O17.java | jayfray12/iDAAS-EventBuilder | 769248c81f3e7e594dc637fd1b21b2b558fa4fd8 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/connectedhealth_idaas/eventbuilder/builders/hl7/RAS_O17.java | jayfray12/iDAAS-EventBuilder | 769248c81f3e7e594dc637fd1b21b2b558fa4fd8 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/connectedhealth_idaas/eventbuilder/builders/hl7/RAS_O17.java | jayfray12/iDAAS-EventBuilder | 769248c81f3e7e594dc637fd1b21b2b558fa4fd8 | [
"Apache-2.0"
] | 1 | 2021-06-17T14:44:01.000Z | 2021-06-17T14:44:01.000Z | 30.031073 | 97 | 0.74358 | 999,363 | package io.connectedhealth_idaas.eventbuilder.builders.hl7;
import io.connectedhealth_idaas.eventbuilder.pojos.clinical.hl7.*;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class RAS_O17 {
private MSH messageHeader;
private SFT softwareSegment;
private UAC userAuthenticationCredentialSegment;
private NTE notesandComments;
private PID patientIdentification;
private PD1 patientAdditionalDemographic;
private PRT participationInformation;
private NTE notesandComments1;
private ARV accessRestriction;
private AL1 patientAllergyInformation;
private PV1 patientVisit;
private PV2 patientVisitAdditionalInformation;
private PRT participationInformation1;
private ARV accessRestriction1;
private ORC commonOrder;
private PRT participationInformation2;
private TQ1 timingQuantity;
private TQ2 timingQuantityRelationship;
private RXO pharmacyTreatmentOrder;
private NTE notesandComments2;
private RXR pharmacyTreatmentRoute;
private RXC pharmacyTreatmentComponentOrder;
private NTE notesandComments3;
private RXE pharmacyTreatmentEncodedOrder;
private PRT participationInformation3;
private NTE notesandComments4;
private TQ1 timingQuantity1;
private TQ2 timingQuantityRelationship1;
private RXR pharmacyTreatmentRoute1;
private RXC pharmacyTreatmentComponentOrder1;
private CDO cumulativeDosage;
private RXA pharmacyTreatmentAdministration;
private PRT participationInformation4;
private RXR pharmacyTreatmentRoute2;
private OBX observationResult;
private PRT participationInformation5;
private NTE notesandComments5;
private CTI clinicalTrialIdentification;
public MSH getMessageHeader() {
return messageHeader;
}
public void setMessageHeader(MSH messageHeader) {
this.messageHeader = messageHeader;
}
public SFT getSoftwareSegment() {
return softwareSegment;
}
public void setSoftwareSegment(SFT softwareSegment) {
this.softwareSegment = softwareSegment;
}
public UAC getUserAuthenticationCredentialSegment() {
return userAuthenticationCredentialSegment;
}
public void setUserAuthenticationCredentialSegment(UAC userAuthenticationCredentialSegment) {
this.userAuthenticationCredentialSegment = userAuthenticationCredentialSegment;
}
public NTE getNotesandComments() {
return notesandComments;
}
public void setNotesandComments(NTE notesandComments) {
this.notesandComments = notesandComments;
}
public PID getPatientIdentification() {
return patientIdentification;
}
public void setPatientIdentification(PID patientIdentification) {
this.patientIdentification = patientIdentification;
}
public PD1 getPatientAdditionalDemographic() {
return patientAdditionalDemographic;
}
public void setPatientAdditionalDemographic(PD1 patientAdditionalDemographic) {
this.patientAdditionalDemographic = patientAdditionalDemographic;
}
public PRT getParticipationInformation() {
return participationInformation;
}
public void setParticipationInformation(PRT participationInformation) {
this.participationInformation = participationInformation;
}
public NTE getNotesandComments1() {
return notesandComments1;
}
public void setNotesandComments1(NTE notesandComments1) {
this.notesandComments1 = notesandComments1;
}
public ARV getAccessRestriction() {
return accessRestriction;
}
public void setAccessRestriction(ARV accessRestriction) {
this.accessRestriction = accessRestriction;
}
public AL1 getPatientAllergyInformation() {
return patientAllergyInformation;
}
public void setPatientAllergyInformation(AL1 patientAllergyInformation) {
this.patientAllergyInformation = patientAllergyInformation;
}
public PV1 getPatientVisit() {
return patientVisit;
}
public void setPatientVisit(PV1 patientVisit) {
this.patientVisit = patientVisit;
}
public PV2 getPatientVisitAdditionalInformation() {
return patientVisitAdditionalInformation;
}
public void setPatientVisitAdditionalInformation(PV2 patientVisitAdditionalInformation) {
this.patientVisitAdditionalInformation = patientVisitAdditionalInformation;
}
public PRT getParticipationInformation1() {
return participationInformation1;
}
public void setParticipationInformation1(PRT participationInformation1) {
this.participationInformation1 = participationInformation1;
}
public ARV getAccessRestriction1() {
return accessRestriction1;
}
public void setAccessRestriction1(ARV accessRestriction1) {
this.accessRestriction1 = accessRestriction1;
}
public ORC getCommonOrder() {
return commonOrder;
}
public void setCommonOrder(ORC commonOrder) {
this.commonOrder = commonOrder;
}
public PRT getParticipationInformation2() {
return participationInformation2;
}
public void setParticipationInformation2(PRT participationInformation2) {
this.participationInformation2 = participationInformation2;
}
public TQ1 getTimingQuantity() {
return timingQuantity;
}
public void setTimingQuantity(TQ1 timingQuantity) {
this.timingQuantity = timingQuantity;
}
public TQ2 getTimingQuantityRelationship() {
return timingQuantityRelationship;
}
public void setTimingQuantityRelationship(TQ2 timingQuantityRelationship) {
this.timingQuantityRelationship = timingQuantityRelationship;
}
public RXO getPharmacyTreatmentOrder() {
return pharmacyTreatmentOrder;
}
public void setPharmacyTreatmentOrder(RXO pharmacyTreatmentOrder) {
this.pharmacyTreatmentOrder = pharmacyTreatmentOrder;
}
public NTE getNotesandComments2() {
return notesandComments2;
}
public void setNotesandComments2(NTE notesandComments2) {
this.notesandComments2 = notesandComments2;
}
public RXR getPharmacyTreatmentRoute() {
return pharmacyTreatmentRoute;
}
public void setPharmacyTreatmentRoute(RXR pharmacyTreatmentRoute) {
this.pharmacyTreatmentRoute = pharmacyTreatmentRoute;
}
public RXC getPharmacyTreatmentComponentOrder() {
return pharmacyTreatmentComponentOrder;
}
public void setPharmacyTreatmentComponentOrder(RXC pharmacyTreatmentComponentOrder) {
this.pharmacyTreatmentComponentOrder = pharmacyTreatmentComponentOrder;
}
public NTE getNotesandComments3() {
return notesandComments3;
}
public void setNotesandComments3(NTE notesandComments3) {
this.notesandComments3 = notesandComments3;
}
public RXE getPharmacyTreatmentEncodedOrder() {
return pharmacyTreatmentEncodedOrder;
}
public void setPharmacyTreatmentEncodedOrder(RXE pharmacyTreatmentEncodedOrder) {
this.pharmacyTreatmentEncodedOrder = pharmacyTreatmentEncodedOrder;
}
public PRT getParticipationInformation3() {
return participationInformation3;
}
public void setParticipationInformation3(PRT participationInformation3) {
this.participationInformation3 = participationInformation3;
}
public NTE getNotesandComments4() {
return notesandComments4;
}
public void setNotesandComments4(NTE notesandComments4) {
this.notesandComments4 = notesandComments4;
}
public TQ1 getTimingQuantity1() {
return timingQuantity1;
}
public void setTimingQuantity1(TQ1 timingQuantity1) {
this.timingQuantity1 = timingQuantity1;
}
public TQ2 getTimingQuantityRelationship1() {
return timingQuantityRelationship1;
}
public void setTimingQuantityRelationship1(TQ2 timingQuantityRelationship1) {
this.timingQuantityRelationship1 = timingQuantityRelationship1;
}
public RXR getPharmacyTreatmentRoute1() {
return pharmacyTreatmentRoute1;
}
public void setPharmacyTreatmentRoute1(RXR pharmacyTreatmentRoute1) {
this.pharmacyTreatmentRoute1 = pharmacyTreatmentRoute1;
}
public RXC getPharmacyTreatmentComponentOrder1() {
return pharmacyTreatmentComponentOrder1;
}
public void setPharmacyTreatmentComponentOrder1(RXC pharmacyTreatmentComponentOrder1) {
this.pharmacyTreatmentComponentOrder1 = pharmacyTreatmentComponentOrder1;
}
public CDO getCumulativeDosage() {
return cumulativeDosage;
}
public void setCumulativeDosage(CDO cumulativeDosage) {
this.cumulativeDosage = cumulativeDosage;
}
public RXA getPharmacyTreatmentAdministration() {
return pharmacyTreatmentAdministration;
}
public void setPharmacyTreatmentAdministration(RXA pharmacyTreatmentAdministration) {
this.pharmacyTreatmentAdministration = pharmacyTreatmentAdministration;
}
public PRT getParticipationInformation4() {
return participationInformation4;
}
public void setParticipationInformation4(PRT participationInformation4) {
this.participationInformation4 = participationInformation4;
}
public RXR getPharmacyTreatmentRoute2() {
return pharmacyTreatmentRoute2;
}
public void setPharmacyTreatmentRoute2(RXR pharmacyTreatmentRoute2) {
this.pharmacyTreatmentRoute2 = pharmacyTreatmentRoute2;
}
public OBX getObservationResult() {
return observationResult;
}
public void setObservationResult(OBX observationResult) {
this.observationResult = observationResult;
}
public PRT getParticipationInformation5() {
return participationInformation5;
}
public void setParticipationInformation5(PRT participationInformation5) {
this.participationInformation5 = participationInformation5;
}
public NTE getNotesandComments5() {
return notesandComments5;
}
public void setNotesandComments5(NTE notesandComments5) {
this.notesandComments5 = notesandComments5;
}
public CTI getClinicalTrialIdentification() {
return clinicalTrialIdentification;
}
public void setClinicalTrialIdentification(CTI clinicalTrialIdentification) {
this.clinicalTrialIdentification = clinicalTrialIdentification;
}
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
|
923ad8cda66d5dd5b1f5ddb6579014f6b9b361ba | 1,228 | java | Java | src/main/java/me/hwiggy/whmjava/payload/g/GetEmailsPayload.java | Hwiggy/WHM-Java | 938142faa1bece192b4243d6d788ef5c1134e9fc | [
"Apache-2.0"
] | 2 | 2020-01-08T22:32:36.000Z | 2020-11-05T07:15:28.000Z | src/main/java/me/hwiggy/whmjava/payload/g/GetEmailsPayload.java | Hwiggy/WHM-Java | 938142faa1bece192b4243d6d788ef5c1134e9fc | [
"Apache-2.0"
] | null | null | null | src/main/java/me/hwiggy/whmjava/payload/g/GetEmailsPayload.java | Hwiggy/WHM-Java | 938142faa1bece192b4243d6d788ef5c1134e9fc | [
"Apache-2.0"
] | 1 | 2021-02-14T16:17:25.000Z | 2021-02-14T16:17:25.000Z | 25.061224 | 104 | 0.619707 | 999,364 | package me.hwiggy.whmjava.payload.g;
import me.hwiggy.whmjava.payload.Payload;
public class GetEmailsPayload extends Payload {
/***
*
* @param clientID The Client ID to retrieve the emails for
*/
public GetEmailsPayload(int clientID) {
super("GetEmails");
append("clientid", clientID);
}
/***
* @param limitStart The offset for the returned log data (default: 0) Optional
*/
public GetEmailsPayload withLimitStart(int limitStart) {
append("limitstart", limitStart);
return this;
}
/***
* @param limitNum The number of records to return (default: 25) Optional
*/
public GetEmailsPayload withLimitNum(int limitNum) {
append("limitnum", limitNum);
return this;
}
/***
* @param date The date to retrieve emails for. Optional
*/
public GetEmailsPayload withDate(String date) {
append("date", date);
return this;
}
/***
* @param subject The subject to retrieve emails for - uses approximate string matching. Optional
*/
public GetEmailsPayload withSubject(String subject) {
append("subject", subject);
return this;
}
}
|
923ad8d865e032bce965797a08a806fb53d29c1e | 610 | java | Java | src/main/java/in.togetu.tablestore/repository/bean/TableStorePageResult.java | togetu/spring-data-tablestore | 8e3e48ae48093792ab97b2a21a4715e1a5e0f805 | [
"Apache-2.0"
] | 13 | 2018-12-24T06:16:48.000Z | 2021-04-23T06:19:35.000Z | src/main/java/in.togetu.tablestore/repository/bean/TableStorePageResult.java | togetu/spring-data-tablestore | 8e3e48ae48093792ab97b2a21a4715e1a5e0f805 | [
"Apache-2.0"
] | null | null | null | src/main/java/in.togetu.tablestore/repository/bean/TableStorePageResult.java | togetu/spring-data-tablestore | 8e3e48ae48093792ab97b2a21a4715e1a5e0f805 | [
"Apache-2.0"
] | null | null | null | 22.592593 | 81 | 0.695082 | 999,365 | package in.togetu.tablestore.repository.bean;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import java.util.List;
public class TableStorePageResult<T> extends PageImpl<T> {
private Key nextKey;
public TableStorePageResult(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public TableStorePageResult(List<T> content) {
super(content);
}
public Key getNextKey() {
return nextKey;
}
public void setNextKey(Key nextKey) {
this.nextKey = nextKey;
}
}
|
923ad9326ef6b2b5caddabbd8f22d1834225f281 | 13,068 | java | Java | src/scripts/Figure_Generation/TwoColorHeatMap.java | seqcode/scriptmanager | 9b97a7aaea2c3c918ae31ca52aa3ed0f79cf1062 | [
"MIT"
] | 10 | 2018-04-05T14:08:57.000Z | 2021-08-09T11:56:13.000Z | src/scripts/Figure_Generation/TwoColorHeatMap.java | seqcode/scriptmanager | 9b97a7aaea2c3c918ae31ca52aa3ed0f79cf1062 | [
"MIT"
] | 53 | 2018-03-08T16:00:22.000Z | 2022-03-22T19:45:24.000Z | src/scripts/Figure_Generation/TwoColorHeatMap.java | seqcode/scriptmanager | 9b97a7aaea2c3c918ae31ca52aa3ed0f79cf1062 | [
"MIT"
] | 1 | 2019-12-09T16:07:21.000Z | 2019-12-09T16:07:21.000Z | 31.338129 | 116 | 0.63843 | 999,366 | package scripts.Figure_Generation;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class TwoColorHeatMap {
protected static File SAMPLE = null;
protected static int startROW = 1;
protected static int startCOL = 2;
protected static int pixelHeight = 600;
protected static int pixelWidth = 200;
protected static String scaleType = "treeview";
protected static double quantile = 0.9;
protected static double absolute = -999;
public static Color MINCOLOR = new Color(255, 255, 255);
public static Color MAXCOLOR = new Color(255, 0, 0);
protected static boolean OUTPUTSTATUS = false;
protected static File OUTFILE = null;
protected static String FILEID = null;
private static ArrayList<double[]> MATRIX = null;
public static double COLOR_RATIO = 1;
private JLabel picLabel = null;
public TwoColorHeatMap(File in, Color c, int startR, int startC, int pHeight, int pWidth, String scale, double abs,
double quant, File output, boolean outstatus) {
SAMPLE = in;
MAXCOLOR = c;
startROW = startR;
startCOL = startC;
pixelHeight = pHeight;
pixelWidth = pWidth;
scaleType = scale;
absolute = abs;
quantile = quant;
OUTFILE = output;
OUTPUTSTATUS = outstatus;
}
public void run() throws IOException {
System.out.println("Loading Matrix file: " + OUTFILE.getName());
MATRIX = loadMatrix(SAMPLE);
System.out.println("Matrix file loaded.");
System.out.println("Rows detected: " + MATRIX.size());
System.out.println("Columns detected: " + MATRIX.get(0).length);
if (scaleType.equalsIgnoreCase("treeview")) {
ArrayList<double[]> newMatrix = rebinMatrix(MATRIX);
if (absolute != -999) {
COLOR_RATIO = absolute;
} else {
COLOR_RATIO = getQuantile(newMatrix, quantile);
}
System.out.println("Contrast threshold: " + COLOR_RATIO);
BufferedImage treeMap = generateHeatMap(newMatrix);
picLabel = new JLabel(new ImageIcon(treeMap));
// Don't output PNG if OUTPUTSTATUS is false, which is the flag for not
// outputing figures
if (OUTPUTSTATUS) {
ImageIO.write(treeMap, "png", OUTFILE);
}
} else if (!scaleType.equalsIgnoreCase("treeview")) {
// COLOR_RATIO = 2 * getNonZeroAvg(MATRIX);
if (absolute != -999) {
COLOR_RATIO = absolute;
} else {
COLOR_RATIO = getQuantile(MATRIX, quantile);
}
System.out.println("Contrast threshold: " + COLOR_RATIO);
BufferedImage rawMap = generateHeatMap(MATRIX);
BufferedImage compressedMap = resize(rawMap, pixelWidth, pixelHeight);
picLabel = new JLabel(new ImageIcon(compressedMap));
// Don't output PNG if OUTPUTSTATUS is false, which is the flag for not
// outputing figures
if (OUTPUTSTATUS) {
ImageIO.write(compressedMap, "png", OUTFILE);
}
}
}
public static BufferedImage generateHeatMap(ArrayList<double[]> matrix) throws FileNotFoundException {
int width = 1;
int height = 1;
int pixwidth = matrix.get(0).length * width;
int pixheight = matrix.size() * height;
System.setProperty("java.awt.headless", "true");
BufferedImage im = new BufferedImage(pixwidth, pixheight, BufferedImage.TYPE_INT_ARGB);
Graphics g = im.getGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.setColor(new Color(255, 255, 255));
g2.fillRect(0, 0, pixwidth, pixheight);
int count = 0;
for (int x = 0; x < matrix.size(); x++) {
double[] ID = matrix.get(x);
for (int j = 0; j < ID.length; j++) {
if (ID[j] > 0) {
double v = ID[j] / COLOR_RATIO;
double sVal = v > 1 ? 1 : (v < 0 ? 0 : v);
int red = (int) (MAXCOLOR.getRed() * sVal + MINCOLOR.getRed() * (1 - sVal));
int green = (int) (MAXCOLOR.getGreen() * sVal + MINCOLOR.getGreen() * (1 - sVal));
int blue = (int) (MAXCOLOR.getBlue() * sVal + MINCOLOR.getBlue() * (1 - sVal));
g.setColor(new Color(red, green, blue));
} else {
g.setColor(Color.WHITE);
}
g.fillRect(j * width, count * height, width, height);
}
count++;
}
return im;
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
BufferedImage resized_image = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D) resized_image.createGraphics();
if (scaleType.equalsIgnoreCase("bicubic")) {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
} else if (scaleType.equalsIgnoreCase("bilinear")) {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
} else if (scaleType.equalsIgnoreCase("neighbor")) {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
g2.drawImage(img, 0, 0, newW, newH, null);
g2.dispose();
return resized_image;
}
public static ArrayList<double[]> rebinMatrix(ArrayList<double[]> oldmatrix) {
ArrayList<double[]> newmatrix = new ArrayList<double[]>();
int R = oldmatrix.size();
int C = oldmatrix.get(0).length;
int r = pixelHeight;
int c = pixelWidth;
// expand the original array to be larger is expanding beyond pixel size
if (r > R) {
int rowAdd = (r / R) + 1;
// System.out.println("Row duplication events: " + rowAdd);
ArrayList<double[]> temp = new ArrayList<double[]>();
for (int x = 0; x < R; x++) {
for (int y = 0; y <= rowAdd; y++) {
temp.add(oldmatrix.get(x).clone());
}
}
// Set pointers to new row values
oldmatrix = temp;
R = oldmatrix.size();
}
if (c > C) {
int colAdd = (c / C) + 1;
// System.out.println("Column duplication events: " + colAdd);
ArrayList<double[]> temp = new ArrayList<double[]>();
for (int x = 0; x < R; x++) {
double[] oldarray = oldmatrix.get(x);
double[] newarray = new double[oldarray.length * colAdd];
for (int y = 0; y < newarray.length; y++) {
// System.out.print(y + "\t");
// System.out.println(y / colAdd);
newarray[y] = oldarray[y / colAdd];
}
temp.add(newarray);
}
// Set pointers to new row values
oldmatrix = temp;
C = oldmatrix.get(0).length;
}
int rowDelete = R % r;
int colDelete = C % c;
// if(rowDelete != 0) { System.out.println("Rows to delete: " + rowDelete); }
// if(colDelete != 0) { System.out.println("Cols to delete: " + colDelete); }
// Matrix resize requires perfect division % == 0; So remove and average in
// rows/columns to make it happen
if (rowDelete > 0) {
// Get indexes of matrix rows evenly spread across the matrix
// [0 ... 100] down to 20 rows produces [0,5,10,15,20]
int[] row_delete = linspace(0, R - 1, rowDelete);
// Correction to remove the last row if linspace output results in out of bounds
for (int x = 0; x < row_delete.length; x++) {
if (row_delete[x] == oldmatrix.size() - 1) {
row_delete[x]--;
}
}
// Get the indexes of matrix rows +1
int[] row_delete_plus1 = frameshift(row_delete);
if (row_delete.length != row_delete_plus1.length) {
System.err.println("Row delete frameshift/merge failure!!!");
System.exit(1);
}
// Merge rows to be deleted into adjacent row by averaging
for (int x = 0; x < row_delete.length; x++) {
double[] oldrow = oldmatrix.get(row_delete[x]);
double[] updatedrow = oldmatrix.get(row_delete_plus1[x]);
for (int y = 0; y < oldrow.length; y++) {
updatedrow[y] = (oldrow[y] + updatedrow[y]) / 2.0;
}
}
// Delete redundant rows - go in reverse order to maintain index order
for (int x = row_delete.length - 1; x >= 0; x--) {
oldmatrix.remove(row_delete[x]);
}
// Set R to new value
R = oldmatrix.size();
}
if (colDelete > 0) {
int[] col_delete = linspace(0, C - 1, colDelete);
// Correction to remove the last column if linspace output results in out of
// bounds
for (int x = 0; x < col_delete.length; x++) {
if (col_delete[x] == oldmatrix.get(0).length - 1) {
col_delete[x]--;
}
}
int[] col_delete_plus1 = frameshift(col_delete);
if (col_delete.length != col_delete_plus1.length) {
System.err.println("Column delete frameshift/merge failure!!!");
System.exit(1);
}
// Merge cols to be deleted into adjacent col by averaging
for (int x = 0; x < oldmatrix.size(); x++) {
double[] oldcol = oldmatrix.get(x);
double[] avgcol = oldcol.clone();
for (int y = 0; y < col_delete.length; y++) {
avgcol[col_delete_plus1[y]] = (oldcol[col_delete[y]] + oldcol[col_delete_plus1[y]]) / 2.0;
}
double[] updatedcol = new double[oldcol.length - col_delete.length];
int currentIndex = 0;
for (int y = 0; y < oldcol.length; y++) {
boolean remove = false;
for (int z = 0; z < col_delete.length; z++) {
if (col_delete[z] == y) {
remove = true;
}
}
if (!remove) {
updatedcol[currentIndex] = avgcol[y];
currentIndex++;
}
}
oldmatrix.set(x, updatedcol);
}
// Set C to new value
C = oldmatrix.get(0).length;
}
if (R % r != 0) {
System.err.println("Failure to remove rows modularly!!!");
System.exit(1);
}
if (C % c != 0) {
System.err.println("Failure to remove columns modularly!!!");
System.exit(1);
}
// Resize original matrix into new matrix size; average values to make new
// values
for (int i = 0; i < R; i += (R / r)) {
double[] newRow = new double[c];
for (int j = 0; j < C; j += (C / c)) {
double AVG = 0, count = 0;
for (int x = i; x < i + (R / r); x++) {
for (int y = j; y < j + (C / c); y++) {
AVG += oldmatrix.get(x)[y];
count++;
}
}
newRow[j / (C / c)] = AVG / count;
}
newmatrix.add(newRow);
}
return newmatrix;
}
public static int[] linspace(int min, int max, int points) {
int[] d = new int[points];
if (points < 0) {
System.err.println("Invalid number of points to parse!!!\n" + points);
System.exit(1);
}
for (int i = 1; i < points; i++) {
d[i] = min + i * (max - min) / (points - 1);
}
return d;
}
public static int[] frameshift(int[] orig) {
int[] newarray = new int[orig.length];
for (int x = 0; x < orig.length; x++) {
newarray[x] = orig[x] + 1;
}
return newarray;
}
public static double getNonZeroAvg(ArrayList<double[]> matrix) {
double average = 0;
int count = 0;
for (int x = 0; x < matrix.size(); x++) {
for (int y = 0; y < matrix.get(x).length; y++) {
if (matrix.get(x)[y] != 0) {
average += matrix.get(x)[y];
count++;
}
}
}
if (count != 0) {
average /= count;
}
return average;
}
public static double getQuantile(ArrayList<double[]> matrix, double percent) {
ArrayList<Double> nonZero = new ArrayList<Double>();
for (int x = 0; x < matrix.size(); x++) {
for (int y = 0; y < matrix.get(x).length; y++) {
if (matrix.get(x)[y] != 0) {
nonZero.add(Double.valueOf(matrix.get(x)[y]));
}
}
}
Collections.sort(nonZero);
// Collections.reverse(nonZero);
int index = (int) (percent * (double) (nonZero.size() - 1));
return nonZero.get(index);
}
public static ArrayList<double[]> loadMatrix(File input) throws UnsupportedEncodingException, IOException {
ArrayList<double[]> matrix = new ArrayList<double[]>();
int currentRow = 0;
if (input.getAbsoluteFile().toString().endsWith(".gz")) {
BufferedReader scan = new BufferedReader(
new InputStreamReader(new GZIPInputStream(new FileInputStream(input)), "UTF-8"));
String line = scan.readLine();
while (line != null) {
String[] temp = line.split("\t");
if (!temp[0].contains("YORF") && currentRow >= startROW) {
double[] ARRAY = new double[temp.length - startCOL];
for (int x = startCOL; x < temp.length; x++) {
try {
ARRAY[x - startCOL] = Double.parseDouble(temp[x]);
} catch (NumberFormatException nfe) {
ARRAY[x - startCOL] = Double.NaN;
}
}
matrix.add(ARRAY);
}
currentRow++;
line = scan.readLine();
}
scan.close();
} else {
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
String[] temp = scan.nextLine().split("\t");
if (!temp[0].contains("YORF") && currentRow >= startROW) {
double[] ARRAY = new double[temp.length - startCOL];
for (int x = startCOL; x < temp.length; x++) {
try {
ARRAY[x - startCOL] = Double.parseDouble(temp[x]);
} catch (NumberFormatException nfe) {
ARRAY[x - startCOL] = Double.NaN;
}
}
matrix.add(ARRAY);
}
currentRow++;
}
scan.close();
}
return matrix;
}
public JLabel getImg() {
return (picLabel);
}
}
|
923adeb530ee5bed99172ab1a0ac9c98ba9aa5ec | 3,545 | java | Java | core/camel-core/src/test/java/org/apache/camel/processor/RollbackCustomMessageTest.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | core/camel-core/src/test/java/org/apache/camel/processor/RollbackCustomMessageTest.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | 23 | 2021-03-23T00:01:38.000Z | 2022-01-04T16:47:34.000Z | core/camel-core/src/test/java/org/apache/camel/processor/RollbackCustomMessageTest.java | dmgerman/camel | cab53c57b3e58871df1f96d54b2a2ad5a73ce220 | [
"Apache-2.0"
] | null | null | null | 17.725 | 810 | 0.802821 | 999,367 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.processor
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|processor
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|CamelExecutionException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|ContextTestSupport
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|RollbackExchangeException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_class
DECL|class|RollbackCustomMessageTest
specifier|public
class|class
name|RollbackCustomMessageTest
extends|extends
name|ContextTestSupport
block|{
annotation|@
name|Test
DECL|method|testRollbackCustomMessage ()
specifier|public
name|void
name|testRollbackCustomMessage
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|template
operator|.
name|sendBody
argument_list|(
literal|"direct:start"
argument_list|,
literal|"Hello World"
argument_list|)
expr_stmt|;
name|fail
argument_list|(
literal|"Should have thrown an exception"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|CamelExecutionException
name|e
parameter_list|)
block|{
name|assertIsInstanceOf
argument_list|(
name|RollbackExchangeException
operator|.
name|class
argument_list|,
name|e
operator|.
name|getCause
argument_list|()
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|e
operator|.
name|getCause
argument_list|()
operator|.
name|getMessage
argument_list|()
operator|.
name|startsWith
argument_list|(
literal|"boo"
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|createRouteBuilder ()
specifier|protected
name|RouteBuilder
name|createRouteBuilder
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|RouteBuilder
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|configure
parameter_list|()
throws|throws
name|Exception
block|{
name|context
operator|.
name|setTracing
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|from
argument_list|(
literal|"direct:start"
argument_list|)
operator|.
name|rollback
argument_list|(
literal|"boo"
argument_list|)
expr_stmt|;
block|}
block|}
return|;
block|}
block|}
end_class
end_unit
|
923adeca835a963538ce81a062dda2b0cfbcd2b6 | 1,424 | java | Java | src/com/ticktac/utils/LogInRequestHandler.java | vnegi5555/tick-tac | 7faa77588b255408d0a32eabeedb99cde2c9a180 | [
"MIT"
] | null | null | null | src/com/ticktac/utils/LogInRequestHandler.java | vnegi5555/tick-tac | 7faa77588b255408d0a32eabeedb99cde2c9a180 | [
"MIT"
] | null | null | null | src/com/ticktac/utils/LogInRequestHandler.java | vnegi5555/tick-tac | 7faa77588b255408d0a32eabeedb99cde2c9a180 | [
"MIT"
] | 1 | 2020-10-01T16:17:40.000Z | 2020-10-01T16:17:40.000Z | 27.921569 | 104 | 0.726124 | 999,368 | package com.ticktac.utils;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import com.ticktac.business.User;
import com.ticktac.data.UserDAO;
public class LogInRequestHandler implements RequestHandler {
UserDAO userDAO;
public LogInRequestHandler() {
userDAO = new UserDAO();
}
public String handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
return null;
}
@Override
public String handleRequest(HttpServletRequest request, HttpServletResponse response, EntityManager em,
UserTransaction tr) throws ServletException, IOException {
String view = "";
String email = (String)request.getParameter("email");
String password = (String)request.getParameter("password");
if(email == null || password == null)
view = "login.jsp";
else {
User userBean = userDAO.searchUser(email, password, em); // Doesn't need UserTransaction
if(userBean == null) {
request.setAttribute("accountFound", 0);
view = "login.jsp";
}
else {
request.setAttribute("accountFound", 1);
request.getSession().setAttribute("userBean", userBean);
view = "index.jsp";
}
}
return view;
}
}
|
923adfba9c4ade6e00f7b91f4c4fec9754280f22 | 8,904 | java | Java | app/src/main/java/com/codepath/simplydo/activities/MainActivity.java | omersalar/ToDo-app-demo | 198bd1e3f92fdd5abdc92ad02b5e99c77df5ba9f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/codepath/simplydo/activities/MainActivity.java | omersalar/ToDo-app-demo | 198bd1e3f92fdd5abdc92ad02b5e99c77df5ba9f | [
"Apache-2.0"
] | 1 | 2017-08-24T09:01:55.000Z | 2017-08-29T08:48:38.000Z | app/src/main/java/com/codepath/simplydo/activities/MainActivity.java | omersalar/ToDo-app-demo | 198bd1e3f92fdd5abdc92ad02b5e99c77df5ba9f | [
"Apache-2.0"
] | null | null | null | 33.855513 | 148 | 0.65712 | 999,369 | package com.codepath.simplydo.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.codepath.simplydo.BuildConfig;
import com.codepath.simplydo.Constants;
import com.codepath.simplydo.R;
import com.codepath.simplydo.adapters.CustomAdapter;
import com.codepath.simplydo.model.Item;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
int currentVersion = BuildConfig.VERSION_CODE;
public static final String EXTRA_MESSAGE_ACTION = "com.codepath.todo.MESSAGE.ACTION";
public static final String EXTRA_MESSAGE_POS = "com.codepath.todo.MESSAGE.POS";
public static final int REQUEST_CODE_CREATE = 20;
public static final int REQUEST_CODE_EDIT = 30;
ArrayList<Item> itemsArrayList;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
CustomAdapter customAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (BuildConfig.DEBUG) Log.e(Constants.LOG, "MainActivity::onCreate called.");
setUpActivity();
itemsArrayList = (ArrayList<Item>) readItemsFromDB();
if (isFirstRun()) {
if (BuildConfig.DEBUG) Log.e(Constants.LOG, "First run of the app.");
runFirstTime();
}
setUpRecyclerView();
}
/**
* This method is called when the add fab button is pressed.
* Thie method calls card_view new Activity where new tasks can be added.
*
* @param view
*/
public void createItem(View view) {
if (BuildConfig.DEBUG) Log.e(Constants.LOG, "Clicked fab button.");
Intent intent = new Intent(this, CreateItemActivity.class);
startActivityForResult(intent, REQUEST_CODE_CREATE);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds itemsArrayList to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify card_view parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (BuildConfig.DEBUG)
Log.e(Constants.LOG, "onActivityResult called. resultCode: " + resultCode + "; requestCode: " + requestCode);
if (resultCode == RESULT_OK) {
String action = data.getExtras().getString(EXTRA_MESSAGE_ACTION);
if (requestCode == REQUEST_CODE_CREATE) {
Item item = (Item) data.getExtras().getSerializable("item");
itemsArrayList.add(item);
customAdapter.notifyDataSetChanged();
if (BuildConfig.DEBUG)
Log.e(Constants.LOG, "Created item: " + item);
} else if (requestCode == REQUEST_CODE_EDIT) {
if (BuildConfig.DEBUG) Log.e(Constants.LOG, "action: " + action);
if (action.equalsIgnoreCase("EDIT_SAVE")) {
Item item = ((Item) data.getExtras().getSerializable("item"));
int pos = data.getExtras().getInt(EXTRA_MESSAGE_POS);
itemsArrayList.remove(pos);
itemsArrayList.add(pos, item);
customAdapter.notifyDataSetChanged();
if (BuildConfig.DEBUG) Log.e(Constants.LOG, "Edited item: " + item);
} else if (action.equalsIgnoreCase("EDIT_DELETE")) {
int pos = data.getExtras().getInt(EXTRA_MESSAGE_POS);
itemsArrayList.remove(pos);
customAdapter.notifyDataSetChanged();
if (BuildConfig.DEBUG) Log.e(Constants.LOG, "Deleted item at position: " + pos);
}
}
}
}
/**
* This is card_view convenience method to read all items from database
*
* @return A list of Item objects stored in database.
*/
private List<Item> readItemsFromDB() {
return SQLite.select().
from(Item.class).queryList();
}
/**
* This method checks if the app is running for the first time or not.
*
* @return True if this app is running first time. Running first time after card_view version upgrade also return true. Other wise return false.
*/
private boolean isFirstRun() {
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREFS_NAME, MODE_PRIVATE);
int lastVersion = sharedPreferences.getInt(Constants.SHARED_PREFS_VERSION, -1);
sharedPreferences.edit().putInt(Constants.SHARED_PREFS_VERSION, currentVersion).apply();
if (lastVersion == -1) {
// This is the first run ever.
return true;
} else if (lastVersion < currentVersion) {
// This is the first run for this version.
return true;
}
// Not first run.
return false;
}
/**
* This method add items to ArrayList for the first time run.
*/
private void runFirstTime() {
newItem("Welcome to SimplyDo!", "High");
newItem("You can create new tasks by pressing on add button.", "Medium");
newItem("You can edit a task by pressing on it.", "Low");
newItem("You can also delete tasks. Just press on a task and press delete.", "Medium");
}
/**
* This is card_view convenience method to create card_view new item and dislplay on the UI
*/
private void newItem(String desc, String priority) {
Item item = new Item();
item.setDesc(desc);
item.setPriority(priority);
item.setDueDate(new Date());
item.save();
itemsArrayList.add(item);
}
/**
* This method initializes and sets up the Activity.
*/
private void setUpActivity() {
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Your to do list");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
/**
* This method initializes and sets up the Recycler View for to-do items.
*/
private void setUpRecyclerView() {
recyclerView = ((RecyclerView) findViewById(R.id.rvItems));
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
customAdapter = new CustomAdapter(itemsArrayList, this);
recyclerView.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
}
|
923ae14929d84567eee6220ca6f5e87f6078bc23 | 5,599 | java | Java | src/main/java/com/squareup/square/models/ListCashDrawerShiftsResponse.java | square/square-java-sdk | dc02d72da08b13468f6230cc339380dc2cdab8cc | [
"Apache-2.0"
] | 51 | 2019-12-18T20:17:14.000Z | 2022-03-13T22:48:24.000Z | src/main/java/com/squareup/square/models/ListCashDrawerShiftsResponse.java | square/square-java-sdk | dc02d72da08b13468f6230cc339380dc2cdab8cc | [
"Apache-2.0"
] | 13 | 2020-02-20T22:40:38.000Z | 2022-03-28T15:42:34.000Z | src/main/java/com/squareup/square/models/ListCashDrawerShiftsResponse.java | square/square-java-sdk | dc02d72da08b13468f6230cc339380dc2cdab8cc | [
"Apache-2.0"
] | 24 | 2019-12-23T18:08:02.000Z | 2022-01-06T07:15:43.000Z | 30.763736 | 99 | 0.595106 | 999,370 |
package com.squareup.square.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.squareup.square.http.client.HttpContext;
import java.util.List;
import java.util.Objects;
/**
* This is a model class for ListCashDrawerShiftsResponse type.
*/
public class ListCashDrawerShiftsResponse {
private HttpContext httpContext;
@JsonInclude(JsonInclude.Include.NON_NULL)
private final List<CashDrawerShiftSummary> items;
@JsonInclude(JsonInclude.Include.NON_NULL)
private final String cursor;
@JsonInclude(JsonInclude.Include.NON_NULL)
private final List<Error> errors;
/**
* Initialization constructor.
* @param items List of CashDrawerShiftSummary value for items.
* @param cursor String value for cursor.
* @param errors List of Error value for errors.
*/
@JsonCreator
public ListCashDrawerShiftsResponse(
@JsonProperty("items") List<CashDrawerShiftSummary> items,
@JsonProperty("cursor") String cursor,
@JsonProperty("errors") List<Error> errors) {
this.items = items;
this.cursor = cursor;
this.errors = errors;
}
@JsonIgnore
public HttpContext getContext() {
return httpContext;
}
/**
* Getter for Items.
* A collection of CashDrawerShiftSummary objects for shifts that match the query.
* @return Returns the List of CashDrawerShiftSummary
*/
@JsonGetter("items")
public List<CashDrawerShiftSummary> getItems() {
return items;
}
/**
* Getter for Cursor.
* Opaque cursor for fetching the next page of results. Cursor is not present in the last page
* of results.
* @return Returns the String
*/
@JsonGetter("cursor")
public String getCursor() {
return cursor;
}
/**
* Getter for Errors.
* Any errors that occurred during the request.
* @return Returns the List of Error
*/
@JsonGetter("errors")
public List<Error> getErrors() {
return errors;
}
@Override
public int hashCode() {
return Objects.hash(items, cursor, errors);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ListCashDrawerShiftsResponse)) {
return false;
}
ListCashDrawerShiftsResponse other = (ListCashDrawerShiftsResponse) obj;
return Objects.equals(items, other.items)
&& Objects.equals(cursor, other.cursor)
&& Objects.equals(errors, other.errors);
}
/**
* Converts this ListCashDrawerShiftsResponse into string format.
* @return String representation of this class
*/
@Override
public String toString() {
return "ListCashDrawerShiftsResponse [" + "items=" + items + ", cursor=" + cursor
+ ", errors=" + errors + "]";
}
/**
* Builds a new {@link ListCashDrawerShiftsResponse.Builder} object.
* Creates the instance with the state of the current model.
* @return a new {@link ListCashDrawerShiftsResponse.Builder} object
*/
public Builder toBuilder() {
Builder builder = new Builder()
.items(getItems())
.cursor(getCursor())
.errors(getErrors());
return builder;
}
/**
* Class to build instances of {@link ListCashDrawerShiftsResponse}.
*/
public static class Builder {
private HttpContext httpContext;
private List<CashDrawerShiftSummary> items;
private String cursor;
private List<Error> errors;
/**
* Setter for httpContext.
* @param httpContext HttpContext value for httpContext.
* @return Builder
*/
public Builder httpContext(HttpContext httpContext) {
this.httpContext = httpContext;
return this;
}
/**
* Setter for items.
* @param items List of CashDrawerShiftSummary value for items.
* @return Builder
*/
public Builder items(List<CashDrawerShiftSummary> items) {
this.items = items;
return this;
}
/**
* Setter for cursor.
* @param cursor String value for cursor.
* @return Builder
*/
public Builder cursor(String cursor) {
this.cursor = cursor;
return this;
}
/**
* Setter for errors.
* @param errors List of Error value for errors.
* @return Builder
*/
public Builder errors(List<Error> errors) {
this.errors = errors;
return this;
}
/**
* Builds a new {@link ListCashDrawerShiftsResponse} object using the set fields.
* @return {@link ListCashDrawerShiftsResponse}
*/
public ListCashDrawerShiftsResponse build() {
ListCashDrawerShiftsResponse model =
new ListCashDrawerShiftsResponse(items, cursor, errors);
model.httpContext = httpContext;
return model;
}
}
}
|
923ae1b039aedcefab34c2c1251a3616f5e4494e | 1,469 | java | Java | vertx-spring-boot-starter-kafka/src/main/java/dev/snowdrop/vertx/kafka/SnowdropHeader.java | szbalx/vertx-spring-boot | aca3fd1cbeb1ab6e782487fffd4eefb967ffd00a | [
"Apache-2.0"
] | 1 | 2022-01-16T08:49:17.000Z | 2022-01-16T08:49:17.000Z | vertx-spring-boot-starter-kafka/src/main/java/dev/snowdrop/vertx/kafka/SnowdropHeader.java | szbalx/vertx-spring-boot | aca3fd1cbeb1ab6e782487fffd4eefb967ffd00a | [
"Apache-2.0"
] | null | null | null | vertx-spring-boot-starter-kafka/src/main/java/dev/snowdrop/vertx/kafka/SnowdropHeader.java | szbalx/vertx-spring-boot | aca3fd1cbeb1ab6e782487fffd4eefb967ffd00a | [
"Apache-2.0"
] | null | null | null | 23.31746 | 82 | 0.643295 | 999,371 | package dev.snowdrop.vertx.kafka;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import io.vertx.axle.kafka.client.producer.KafkaHeader;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
final class SnowdropHeader implements Header {
private final String key;
private final DataBuffer value;
SnowdropHeader(String key, DataBuffer value) {
this.key = key;
this.value = value;
}
SnowdropHeader(String key, String value) {
this(key, toDataBuffer(value.getBytes(StandardCharsets.UTF_8)));
}
SnowdropHeader(KafkaHeader axelHeader) {
this(axelHeader.key(), toDataBuffer(axelHeader.value().getBytes()));
}
@Override
public String key() {
return key;
}
@Override
public DataBuffer value() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SnowdropHeader that = (SnowdropHeader) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
private static DataBuffer toDataBuffer(byte[] bytes) {
return new DefaultDataBufferFactory().wrap(bytes);
}
}
|
923ae1c518bb2661cd0d2b6cf16f87d2e4666073 | 2,179 | java | Java | src/main/java/net/silentchaos512/gear/client/material/CompoundMaterialDisplay.java | TexBlock/Silent-Gear | 92f8d7081bacb10594e19d5447ad16bca34002ed | [
"MIT"
] | 50 | 2018-06-24T02:49:52.000Z | 2022-02-13T22:12:03.000Z | src/main/java/net/silentchaos512/gear/client/material/CompoundMaterialDisplay.java | TexBlock/Silent-Gear | 92f8d7081bacb10594e19d5447ad16bca34002ed | [
"MIT"
] | 473 | 2018-07-02T08:21:56.000Z | 2022-03-16T10:49:02.000Z | src/main/java/net/silentchaos512/gear/client/material/CompoundMaterialDisplay.java | TexBlock/Silent-Gear | 92f8d7081bacb10594e19d5447ad16bca34002ed | [
"MIT"
] | 53 | 2019-06-18T17:46:33.000Z | 2022-03-25T00:20:12.000Z | 38.910714 | 116 | 0.7095 | 999,372 | package net.silentchaos512.gear.client.material;
import net.minecraft.world.item.ItemStack;
import net.minecraft.resources.ResourceLocation;
import net.silentchaos512.gear.api.item.GearType;
import net.silentchaos512.gear.api.material.*;
import net.silentchaos512.gear.api.part.IPartData;
import net.silentchaos512.gear.client.util.ColorUtils;
import net.silentchaos512.gear.item.CompoundMaterialItem;
import net.silentchaos512.gear.item.IColoredMaterialItem;
import net.silentchaos512.gear.util.Const;
import net.silentchaos512.utils.Color;
import java.util.List;
public class CompoundMaterialDisplay implements IMaterialDisplay {
public static final CompoundMaterialDisplay INSTANCE = new CompoundMaterialDisplay();
@Override
public ResourceLocation getMaterialId() {
return Const.NULL_ID;
}
@Override
public IMaterialLayerList getLayerList(GearType gearType, IPartData part, IMaterialInstance material) {
ItemStack stack = material.getItem();
if (!material.isSimple() && stack.getItem() instanceof IColoredMaterialItem) {
IMaterialInstance primary = ((IColoredMaterialItem) stack.getItem()).getPrimarySubMaterial(stack);
if (primary != null) {
IMaterialDisplay model = primary.getDisplayProperties();
return model.getLayerList(gearType, part, material);
}
}
return MaterialLayerList.DEFAULT;
}
@Override
public int getLayerColor(GearType gearType, IPartData part, IMaterialInstance materialIn, int layer) {
List<MaterialLayer> layers = getLayerList(gearType, part, materialIn).getLayers();
if (layer < layers.size()) {
ItemStack stack = materialIn.getItem();
if (stack.getItem() instanceof CompoundMaterialItem) {
List<IMaterialInstance> subMaterials = CompoundMaterialItem.getSubMaterials(stack);
int color = ColorUtils.getBlendedColor((CompoundMaterialItem) stack.getItem(), subMaterials, layer);
// return layers.get(layer).getColor();
return color;
}
}
return Color.VALUE_WHITE;
}
}
|
923ae249144815fb22aff36e6b605beadc5e518c | 296 | java | Java | src/main/java/de/hswhameln/beverages/projections/CustomerAddress.java | CapOfCave/sa2-beverage-shop | f5465506463e99789184d80d6dbb6b95e2d9b678 | [
"MIT"
] | 1 | 2022-02-28T09:39:56.000Z | 2022-02-28T09:39:56.000Z | src/main/java/de/hswhameln/beverages/projections/CustomerAddress.java | CapOfCave/sa2-beverage-shop | f5465506463e99789184d80d6dbb6b95e2d9b678 | [
"MIT"
] | null | null | null | src/main/java/de/hswhameln/beverages/projections/CustomerAddress.java | CapOfCave/sa2-beverage-shop | f5465506463e99789184d80d6dbb6b95e2d9b678 | [
"MIT"
] | null | null | null | 21.142857 | 43 | 0.679054 | 999,373 | package de.hswhameln.beverages.projections;
public interface CustomerAddress {
long getId();
String getPrename();
String getSurname();
boolean isActive();
String getStreet();
String getStreetno();
String getZipcode();
String getCity();
String getCountry();
}
|
923ae2589f834f26ecccea49b362f06be5b4c91f | 2,498 | java | Java | src/core/src/com/ru/tgra/objects/GameObject.java | Indexu/Labyrinth | f750f4494e78e812e0dac07f306291bcda2a94c6 | [
"MIT"
] | 1 | 2020-11-07T00:12:54.000Z | 2020-11-07T00:12:54.000Z | src/core/src/com/ru/tgra/objects/GameObject.java | Indexu/Labyrinth | f750f4494e78e812e0dac07f306291bcda2a94c6 | [
"MIT"
] | null | null | null | src/core/src/com/ru/tgra/objects/GameObject.java | Indexu/Labyrinth | f750f4494e78e812e0dac07f306291bcda2a94c6 | [
"MIT"
] | 2 | 2020-01-01T07:29:32.000Z | 2020-11-07T00:10:55.000Z | 19.825397 | 126 | 0.614492 | 999,374 | package com.ru.tgra.objects;
import com.ru.tgra.models.Material;
import com.ru.tgra.models.Point3D;
import com.ru.tgra.models.Vector3D;
public abstract class GameObject
{
protected Point3D position;
protected Vector3D direction;
protected float speed;
protected Vector3D rotation;
protected Vector3D scale;
protected Material material;
protected Material minimapMaterial;
protected boolean destroyed;
public GameObject()
{
position = new Point3D();
direction = new Vector3D();
speed = 0;
rotation = new Vector3D();
scale = new Vector3D();
material = new Material();
minimapMaterial = new Material();
destroyed = false;
}
public GameObject(Point3D position, Vector3D direction, float speed, Vector3D rotation, Vector3D scale, Material material)
{
this.position = position;
this.direction = direction;
this.speed = speed;
this.rotation = rotation;
this.scale = scale;
this.material = material;
destroyed = false;
}
public abstract void draw(int viewportID);
public abstract void update(float deltaTime);
public void destroy()
{
destroyed = true;
}
public boolean isDestroyed()
{
return destroyed;
}
public Point3D getPosition()
{
return position;
}
public void setPosition(Point3D position)
{
this.position = position;
}
public Vector3D getDirection()
{
return direction;
}
public void setDirection(Vector3D direction)
{
this.direction = direction;
}
public float getSpeed()
{
return speed;
}
public void setSpeed(float speed)
{
this.speed = speed;
}
public Vector3D getRotation()
{
return rotation;
}
public void setRotation(Vector3D rotation)
{
this.rotation = rotation;
}
public Vector3D getScale()
{
return scale;
}
public void setScale(Vector3D scale)
{
this.scale = scale;
}
public Material getMaterial()
{
return material;
}
public void setMaterial(Material material)
{
this.material = material;
}
public Material getMinimapMaterial()
{
return minimapMaterial;
}
public void setMinimapMaterial(Material minimapMaterial)
{
this.minimapMaterial = minimapMaterial;
}
}
|
923ae3c2579ca93755cc4e375260b3043c3dd8c4 | 1,647 | java | Java | create-reactor-core/src/test/java/com/internetitem/reactorBuilder/CommandLineRunnerTest.java | internetitem/ReactorBuilder | 67a3b98e9f00304ae09523f9098707034ac15b82 | [
"Apache-2.0"
] | 1 | 2015-11-20T14:43:39.000Z | 2015-11-20T14:43:39.000Z | create-reactor-core/src/test/java/com/internetitem/reactorBuilder/CommandLineRunnerTest.java | internetitem/ReactorBuilder | 67a3b98e9f00304ae09523f9098707034ac15b82 | [
"Apache-2.0"
] | null | null | null | create-reactor-core/src/test/java/com/internetitem/reactorBuilder/CommandLineRunnerTest.java | internetitem/ReactorBuilder | 67a3b98e9f00304ae09523f9098707034ac15b82 | [
"Apache-2.0"
] | null | null | null | 43.342105 | 142 | 0.803886 | 999,375 | package com.internetitem.reactorBuilder;
import com.internetitem.reactorBuilder.config.Configuration;
import com.internetitem.reactorBuilder.config.mocks.MockPropertiesLoader;
import org.junit.Test;
import static org.junit.Assert.*;
public class CommandLineRunnerTest {
@Test
public void testEmptyBuildConfiguration() throws Exception {
MockPropertiesLoader mockPropertiesLoader = new MockPropertiesLoader();
CommandLineRunner runner = new CommandLineRunner(mockPropertiesLoader);
runner.buildConfiguration(new String[0]);
}
@Test
public void testBuildConfigurationWithProperty() throws Exception {
MockPropertiesLoader mockPropertiesLoader = new MockPropertiesLoader();
mockPropertiesLoader.addProperty("file1.properties", "version", "v1.0.0");
CommandLineRunner runner = new CommandLineRunner(mockPropertiesLoader);
Configuration configuration = runner.buildConfiguration(new String[]{"--propertyFile=file1.properties"});
assertEquals("v1.0.0", configuration.getVersion());
}
@Test
public void testBuildConfigurationWithMultiplePropertyFiles() throws Exception {
MockPropertiesLoader mockPropertiesLoader = new MockPropertiesLoader();
mockPropertiesLoader.addProperty("file1.properties", "version", "v1.0.0");
mockPropertiesLoader.addProperty("file2.properties", "groupId", "gid");
CommandLineRunner runner = new CommandLineRunner(mockPropertiesLoader);
Configuration configuration = runner.buildConfiguration(new String[]{"--propertyFile=file1.properties", "--propertyFile=file2.properties"});
assertEquals("v1.0.0", configuration.getVersion());
assertEquals("gid", configuration.getGroupId());
}
}
|
923ae416aa64482d8a8727644f07b6b2747bc8ca | 21,248 | java | Java | taverna-workflowmodel-impl/src/main/java/org/apache/taverna/facade/impl/WorkflowInstanceFacadeImpl.java | apache/incubator-taverna-engine | 7318b4319c5e63709c3ea3a3a918f02d3f299130 | [
"Apache-2.0"
] | 19 | 2015-07-22T10:31:28.000Z | 2021-11-10T19:40:24.000Z | taverna-workflowmodel-impl/src/main/java/org/apache/taverna/facade/impl/WorkflowInstanceFacadeImpl.java | apache/incubator-taverna-engine | 7318b4319c5e63709c3ea3a3a918f02d3f299130 | [
"Apache-2.0"
] | 1 | 2018-01-05T13:42:33.000Z | 2018-01-05T13:42:33.000Z | taverna-workflowmodel-impl/src/main/java/org/apache/taverna/facade/impl/WorkflowInstanceFacadeImpl.java | apache/incubator-taverna-engine | 7318b4319c5e63709c3ea3a3a918f02d3f299130 | [
"Apache-2.0"
] | 17 | 2015-12-11T18:02:53.000Z | 2022-03-06T10:51:17.000Z | 33.673534 | 100 | 0.743929 | 999,377 | /*
* 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.taverna.facade.impl;
import static java.lang.System.currentTimeMillis;
import static java.util.Collections.synchronizedList;
import static java.util.UUID.randomUUID;
import java.lang.ref.WeakReference;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.taverna.facade.FacadeListener;
import org.apache.taverna.facade.ResultListener;
import org.apache.taverna.facade.WorkflowInstanceFacade;
import org.apache.taverna.facade.WorkflowRunCancellation;
import org.apache.taverna.invocation.InvocationContext;
import org.apache.taverna.invocation.TokenOrderException;
import org.apache.taverna.invocation.WorkflowDataToken;
import org.apache.taverna.lang.observer.Observable;
import org.apache.taverna.lang.observer.Observer;
import org.apache.taverna.monitor.MonitorManager;
import org.apache.taverna.monitor.MonitorNode;
import org.apache.taverna.monitor.MonitorableProperty;
import org.apache.taverna.monitor.NoSuchPropertyException;
import org.apache.taverna.provenance.item.DataflowRunComplete;
import org.apache.taverna.provenance.item.WorkflowDataProvenanceItem;
import org.apache.taverna.provenance.item.WorkflowProvenanceItem;
import org.apache.taverna.reference.T2Reference;
import org.apache.taverna.reference.WorkflowRunIdEntity;
import org.apache.taverna.utility.TypedTreeModel;
import org.apache.taverna.workflowmodel.Dataflow;
import org.apache.taverna.workflowmodel.DataflowInputPort;
import org.apache.taverna.workflowmodel.DataflowOutputPort;
import org.apache.taverna.workflowmodel.DataflowValidationReport;
import org.apache.taverna.workflowmodel.EditException;
import org.apache.taverna.workflowmodel.Edits;
import org.apache.taverna.workflowmodel.InvalidDataflowException;
import org.apache.taverna.workflowmodel.Processor;
import org.apache.taverna.workflowmodel.ProcessorFinishedEvent;
import org.apache.taverna.workflowmodel.impl.EditsImpl;
import org.apache.taverna.workflowmodel.impl.ProcessorImpl;
import org.apache.taverna.workflowmodel.processor.dispatch.DispatchLayer;
import org.apache.taverna.workflowmodel.processor.dispatch.DispatchStack;
import org.apache.taverna.workflowmodel.processor.dispatch.layers.ErrorBounce;
import org.apache.taverna.workflowmodel.processor.dispatch.layers.IntermediateProvenance;
import org.apache.taverna.workflowmodel.processor.dispatch.layers.Parallelize;
import org.apache.taverna.workflowmodel.processor.dispatch.layers.Stop;
import org.apache.log4j.Logger;
/**
* Implementation of {@link WorkflowInstanceFacade}
*
* @author Tom Oinn
* @author Stian Soiland-Reyes
* @author Ian Dunlop
* @author Alex Nenadic
*/
public class WorkflowInstanceFacadeImpl implements WorkflowInstanceFacade {
private static Logger logger = Logger
.getLogger(WorkflowInstanceFacadeImpl.class);
protected static AtomicLong owningProcessId = new AtomicLong(0);
private InvocationContext context;
private State state = State.prepared;
public Date stateLastModified = new Date();
@Override
public InvocationContext getContext() {
return context;
}
private Dataflow dataflow;
private FacadeResultListener facadeResultListener;
/** How many processors have finished so far */
private int processorsToComplete;
private String instanceOwningProcessId;
private String localName;
private MonitorManager monitorManager = MonitorManager.getInstance();
protected List<FacadeListener> facadeListeners = synchronizedList(new ArrayList<FacadeListener>());
protected List<ResultListener> resultListeners = synchronizedList(new ArrayList<ResultListener>());
private boolean provEnabled = false;
private WeakHashMap<String, T2Reference> pushedDataMap = new WeakHashMap<>();
/** Id of this run */
private String workflowRunId;
private Timestamp workflowStarted;
private WorkflowProvenanceItem workflowItem = null;
private int portsToComplete;
private enum WorkflowInstanceFacadeChange {
CANCELLATION, PORT_DECREMENT, PROCESSOR_DECREMENT
};
public WorkflowInstanceFacadeImpl(Dataflow dataflow,
InvocationContext context, String parentProcess)
throws InvalidDataflowException {
if (dataflow == null) {
logger.error("Dataflow is null");
throw new IllegalArgumentException("Dataflow is null");
}
DataflowValidationReport report = dataflow.checkValidity();
if (!report.isValid())
throw new InvalidDataflowException(dataflow, report);
this.dataflow = dataflow;
this.context = context;
this.portsToComplete = dataflow.getOutputPorts().size();
this.processorsToComplete = dataflow.getProcessors().size();
this.localName = "facade" + owningProcessId.getAndIncrement();
// Set the wf run id
workflowRunId = UUID.randomUUID().toString();
if (parentProcess.isEmpty()) {
// Top-level workflow
/*
* add top level workflow run so that reference service can generate
* identifiers linked to our run
*/
context.addEntity(new WorkflowRunIdEntity(workflowRunId));
this.instanceOwningProcessId = localName;
/*
* Add this WorkflowInstanceFacade to the map of all workflow run
* IDs against the corresponding WorkflowInstanceFacadeS/ - to be
* used by DependencyActivity's such as API consumer and Beanshell
*/
workflowRunFacades.put(localName, new WeakReference<WorkflowInstanceFacade>(this));
/*
* Note that we do not put the IDs for nested workflows, just for
* the main ones!
*/
} else {
// Nested workflow
this.instanceOwningProcessId = parentProcess + ":" + localName;
}
if (context.getProvenanceReporter() != null) {
provEnabled = true;
workflowItem = new WorkflowProvenanceItem();
workflowItem.setDataflow(dataflow);
workflowItem.setProcessId(instanceOwningProcessId);
workflowItem.setIdentifier(workflowRunId);
workflowItem.setParentId(dataflow.getIdentifier());
workflowItem.setWorkflowId(dataflow.getIdentifier());
/*
* FIXME: workflowItem is local to each instanceOwningProcessId, but
* might be added to the Processor within different concurrent runs.
* (T3-930)
*/
addProvenanceLayerToProcessors(workflowItem);
context.getProvenanceReporter().setSessionID(workflowRunId);
}
facadeResultListener = new FacadeResultListener(dataflow, workflowItem);
// Register an observer with each of the processors
for (Processor processor : dataflow.getProcessors()) {
String expectedProcessId = instanceOwningProcessId + ":"
+ dataflow.getLocalName() + ":" + processor.getLocalName();
ProcessorFinishedObserver observer = new ProcessorFinishedObserver(
workflowItem, expectedProcessId);
((ProcessorImpl) processor).addObserver(observer);
}
}
private void addProvenanceLayerToProcessors(WorkflowProvenanceItem workflowItem) {
// TODO Shouldn't we use a bean for this?
Edits edits = new EditsImpl();
for (Processor processor : dataflow.getProcessors())
/*
* Synchronized per processor as we might be modifying its dispatch
* stack (fixes T3-929)
*/
synchronized (processor) {
DispatchStack dispatchStack = processor.getDispatchStack();
List<DispatchLayer<?>> layers = dispatchStack.getLayers();
if (isProvenanceAlreadyAdded(layers))
continue;
IntermediateProvenance provenance = new IntermediateProvenance();
provenance.setWorkflow(workflowItem);
provenance.setReporter(context.getProvenanceReporter());
try {
edits.getAddDispatchLayerEdit(dispatchStack, provenance,
provenancePosition(layers)).doEdit();
break;
} catch (EditException e) {
logger.warn("adding provenance layer to dispatch stack failed "
+ e.toString());
}
}
}
private boolean isProvenanceAlreadyAdded(List<DispatchLayer<?>> layers) {
for (DispatchLayer<?> layer : layers)
if (layer instanceof IntermediateProvenance)
return true;
return false;
}
private int provenancePosition(List<DispatchLayer<?>> layers) {
int position=0; // fallback - beginning of list
for (int i = 0; i < layers.size(); i++) {
DispatchLayer<?> layer = layers.get(i);
if (layer instanceof Parallelize)
// Below Parallelize (should be there!)
position = i+1;
else if (layer instanceof ErrorBounce)
// and inserted just above ErrorBounce (if it's there)
position = i;
}
return position;
}
@Override
public void addFacadeListener(FacadeListener listener) {
facadeListeners.add(listener);
}
@Override
public void addResultListener(ResultListener listener) {
synchronized (resultListeners) {
if (resultListeners.isEmpty())
for (DataflowOutputPort port : dataflow.getOutputPorts())
port.addResultListener(facadeResultListener);
resultListeners.add(listener);
}
}
@Override
public synchronized void fire() throws IllegalStateException {
if (getState().equals(State.running))
throw new IllegalStateException("Workflow is already running!");
workflowStarted = new Timestamp(currentTimeMillis());
setState(State.running);
if (provEnabled) {
workflowItem.setInvocationStarted(workflowStarted);
context.getProvenanceReporter().addProvenanceItem(workflowItem);
}
HashSet<MonitorableProperty<?>> properties = new HashSet<>();
properties.add(new StateProperty());
monitorManager.registerNode(this, instanceOwningProcessId.split(":"),
properties);
dataflow.fire(instanceOwningProcessId, context);
}
public final class StateProperty implements MonitorableProperty<State> {
@Override
public Date getLastModified() {
return stateLastModified;
}
@Override
public String[] getName() {
return new String[] { "facade", "state" };
}
@Override
public State getValue() throws NoSuchPropertyException {
return getState();
}
}
@Override
public Dataflow getDataflow() {
return dataflow;
}
@Override
public TypedTreeModel<MonitorNode> getStateModel() {
// TODO WorkflowInstanceFacade.getStateModel not yet implemented
return null;
}
@Override
public void pushData(WorkflowDataToken token, String portName)
throws TokenOrderException {
State currentState = getState();
if (! currentState.equals(State.running))
throw new IllegalStateException(
"Can't push data, current state is not running, but "
+ currentState);
/*
* TODO: throw TokenOrderException when token stream is violates order
* constraints.
*/
for (DataflowInputPort port : dataflow.getInputPorts()) {
if (!portName.equals(port.getName()))
continue;
if (token.getIndex().length == 0) {
if (pushedDataMap.containsKey(portName))
throw new IllegalStateException("Already pushed for port " + portName);
pushedDataMap.put(portName, token.getData());
}
if (provEnabled) {
WorkflowDataProvenanceItem provItem = new WorkflowDataProvenanceItem();
provItem.setPortName(portName);
provItem.setInputPort(true);
provItem.setData(token.getData());
provItem.setReferenceService(context.getReferenceService());
provItem.setParentId(workflowItem.getIdentifier());
provItem.setWorkflowId(workflowItem.getParentId());
provItem.setIdentifier(randomUUID().toString());
provItem.setParentId(instanceOwningProcessId);
provItem.setProcessId(instanceOwningProcessId);
provItem.setIndex(token.getIndex());
provItem.setFinal(token.isFinal());
context.getProvenanceReporter().addProvenanceItem(provItem);
}
port.receiveEvent(token.pushOwningProcess(localName));
}
}
@Override
public void removeFacadeListener(FacadeListener listener) {
facadeListeners.remove(listener);
}
private <T> ArrayList<T> copyList(List<T> listenerList) {
synchronized (listenerList) {
return new ArrayList<>(listenerList);
}
}
@Override
public void removeResultListener(ResultListener listener) {
synchronized (resultListeners) {
resultListeners.remove(listener);
if (resultListeners.isEmpty())
for (DataflowOutputPort port : dataflow.getOutputPorts())
port.removeResultListener(facadeResultListener);
}
}
protected class FacadeResultListener implements ResultListener {
private final WorkflowProvenanceItem workflowItem;
public FacadeResultListener(Dataflow dataflow,
WorkflowProvenanceItem workflowItem) {
this.workflowItem = workflowItem;
}
@Override
public void resultTokenProduced(WorkflowDataToken token, String portName) {
if (!instanceOwningProcessId.equals(token.getOwningProcess()))
return;
if (getState().equals(State.cancelled))
// Throw the token away
return;
if (provEnabled) {
WorkflowDataProvenanceItem provItem = new WorkflowDataProvenanceItem();
provItem.setPortName(portName);
provItem.setInputPort(false);
provItem.setData(token.getData());
provItem.setReferenceService(context.getReferenceService());
provItem.setParentId(workflowItem.getIdentifier());
provItem.setWorkflowId(workflowItem.getParentId());
provItem.setIdentifier(randomUUID().toString());
provItem.setParentId(instanceOwningProcessId);
provItem.setProcessId(instanceOwningProcessId);
provItem.setIndex(token.getIndex());
provItem.setFinal(token.isFinal());
context.getProvenanceReporter().addProvenanceItem(provItem);
}
for (ResultListener resultListener : copyList(resultListeners))
try {
resultListener.resultTokenProduced(
token.popOwningProcess(), portName);
} catch (RuntimeException ex) {
logger.warn("Could not notify result listener "
+ resultListener, ex);
}
if (token.getIndex().length == 0)
checkWorkflowFinished(WorkflowInstanceFacadeChange.PORT_DECREMENT);
}
}
/**
* An observer of events that occur when a processor finishes with execution.
*
*/
private class ProcessorFinishedObserver implements Observer<ProcessorFinishedEvent>{
private final String expectedProcessId;
public ProcessorFinishedObserver(WorkflowProvenanceItem workflowItem, String expectedProcessId) {
this.expectedProcessId = expectedProcessId;
}
@Override
public void notify(Observable<ProcessorFinishedEvent> sender,
ProcessorFinishedEvent message) throws Exception {
if (! message.getOwningProcess().equals(expectedProcessId))
return;
// De-register the processor node from the monitor as it has finished
monitorManager.deregisterNode(message.getOwningProcess());
// De-register this observer from the processor
message.getProcessor().removeObserver(this);
// All processors have finished => the workflow run has finished
checkWorkflowFinished(WorkflowInstanceFacadeChange.PROCESSOR_DECREMENT);
}
}
private void applyChange(WorkflowInstanceFacadeChange change) {
switch (change) {
case CANCELLATION:
processorsToComplete = 0;
portsToComplete = 0;
break;
case PORT_DECREMENT:
portsToComplete--;
break;
case PROCESSOR_DECREMENT:
processorsToComplete--;
break;
}
}
protected void checkWorkflowFinished(WorkflowInstanceFacadeChange change) {
synchronized (this) {
applyChange(change);
if (getState().equals(State.cancelled) && processorsToComplete < 0) {
logger.error("Already cancelled workflow run "
+ instanceOwningProcessId);
return;
}
if (getState().equals(State.completed)) {
logger.error("Already finished workflow run "
+ instanceOwningProcessId, new IllegalStateException());
return;
}
if (processorsToComplete > 0 || portsToComplete > 0)
// Not yet finished
return;
if (processorsToComplete < 0 || portsToComplete < 0) {
logger.error("Already finished workflow run "
+ instanceOwningProcessId, new IllegalStateException());
return;
}
if (!getState().equals(State.cancelled))
setState(State.completed);
processorsToComplete = -1;
portsToComplete = -1;
}
// De-register the workflow node from the monitor
monitorManager.deregisterNode(instanceOwningProcessId + ":" + dataflow.getLocalName());
/*
* De-register this facade node from the monitor - this will effectively
* tell the monitor that the workflow run has finished
*/
monitorManager.deregisterNode(instanceOwningProcessId);
if (provEnabled) {
DataflowRunComplete provItem = new DataflowRunComplete();
provItem.setInvocationEnded(new Timestamp(currentTimeMillis()));
provItem.setParentId(workflowItem.getIdentifier());
provItem.setWorkflowId(workflowItem.getParentId());
provItem.setProcessId(instanceOwningProcessId);
provItem.setIdentifier(randomUUID().toString());
provItem.setState(getState());
context.getProvenanceReporter().addProvenanceItem(provItem);
}
}
@Override
public WeakHashMap<String, T2Reference> getPushedDataMap() {
return pushedDataMap;
}
public void setWorkflowRunId(String workflowRunId) {
this.workflowRunId = workflowRunId;
}
@Override
public String getWorkflowRunId() {
return workflowRunId;
}
@Override
public synchronized State getState() {
return state;
}
public synchronized void setState(State newState) throws IllegalStateException {
State oldState = state;
if (newState.equals(state))
return;
switch (newState) {
case running:
switch (state) {
case prepared:
case paused:
stateLastModified = new Date();
state = newState;
notifyFacadeListeners(oldState, newState);
return;
default:
throw new IllegalStateException("Can't change state from "
+ state + " to " + newState);
}
case paused:
switch (state) {
case running:
stateLastModified = new Date();
state = newState;
notifyFacadeListeners(oldState, newState);
return;
default:
throw new IllegalStateException("Can't change state from "
+ state + " to " + newState);
}
case completed:
switch (state) {
case running:
stateLastModified = new Date();
state = newState;
notifyFacadeListeners(oldState, newState);
return;
case cancelled:
// Keep as cancelled
return;
default:
throw new IllegalStateException("Can't change state from "
+ state + " to " + newState);
}
case cancelled:
switch (state) {
case completed:
throw new IllegalStateException("Can't change state from "
+ state + " to " + newState);
default:
stateLastModified = new Date();
state = newState;
notifyFacadeListeners(oldState, newState);
return;
}
default:
throw new IllegalStateException("Can't change state from " + state + " to " + newState);
}
}
private void notifyFacadeListeners(State oldState, State newState) {
for (FacadeListener facadeListener : copyList(facadeListeners))
try {
facadeListener.stateChange(this, oldState, newState);
} catch (RuntimeException ex) {
logger.warn("Could not notify facade listener "
+ facadeListener, ex);
}
}
@Override
public synchronized boolean cancelWorkflowRun() {
if (getState().equals(State.completed))
return false;
boolean result = Stop.cancelWorkflow(getWorkflowRunId());
if (result) {
setState(State.cancelled);
logger.info("Cancelled workflow runId=" + getWorkflowRunId()
+ " processId=" + instanceOwningProcessId);
for (FacadeListener facadeListener : copyList(facadeListeners))
try {
facadeListener.workflowFailed(this, "Workflow was cancelled",
new WorkflowRunCancellation(getWorkflowRunId()));
} catch (RuntimeException ex) {
logger.warn("Could not notify failure listener "
+ facadeListener, ex);
}
checkWorkflowFinished(WorkflowInstanceFacadeChange.CANCELLATION);
}
return result;
}
@Override
public boolean pauseWorkflowRun() {
setState(State.paused);
if (Stop.pauseWorkflow(getWorkflowRunId())) {
logger.info("Paused workflow runId=" + getWorkflowRunId()
+ " processId=" + instanceOwningProcessId);
return true;
}
return false;
}
@Override
public boolean resumeWorkflowRun() {
setState(State.running);
if (Stop.resumeWorkflow(getWorkflowRunId())) {
logger.info("Resumed paused workflow runId=" + getWorkflowRunId()
+ " processId=" + instanceOwningProcessId);
return true;
}
return false;
}
@Override
public String getIdentifier() {
return localName;
}
}
|
923ae4233052a3c34768760adf17bb5fdb4e0bc3 | 357 | java | Java | customer-management/src/main/java/com/neu/customermanagement/management/controller/EmployeeController.java | xsb1999/npms-backend | 126f4e1771cce98d86e170d3797c2d66dd63891f | [
"MIT"
] | null | null | null | customer-management/src/main/java/com/neu/customermanagement/management/controller/EmployeeController.java | xsb1999/npms-backend | 126f4e1771cce98d86e170d3797c2d66dd63891f | [
"MIT"
] | null | null | null | customer-management/src/main/java/com/neu/customermanagement/management/controller/EmployeeController.java | xsb1999/npms-backend | 126f4e1771cce98d86e170d3797c2d66dd63891f | [
"MIT"
] | null | null | null | 16.227273 | 62 | 0.7507 | 999,378 | package com.neu.customermanagement.management.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author xsb
* @since 2021-07-08
*/
@RestController
@RequestMapping("/cusManagement/employee")
public class EmployeeController {
}
|
923ae42df961c15961bb6bd8d9a9c322135e8fe0 | 1,854 | java | Java | org/apache/batik/util/gui/LocationBar.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | 1 | 2022-02-24T01:32:41.000Z | 2022-02-24T01:32:41.000Z | org/apache/batik/util/gui/LocationBar.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | org/apache/batik/util/gui/LocationBar.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | 30.393443 | 141 | 0.707659 | 999,379 | package org.apache.batik.util.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.batik.util.resources.ResourceManager;
public class LocationBar extends JPanel {
protected static final String RESOURCES = "org.apache.batik.util.gui.resources.LocationBar";
protected static ResourceBundle bundle = ResourceBundle.getBundle("org.apache.batik.util.gui.resources.LocationBar", Locale.getDefault());
protected static ResourceManager rManager;
protected JComboBox comboBox;
public LocationBar() {
super(new BorderLayout(5, 5));
JLabel var1 = new JLabel(rManager.getString("Panel.label"));
this.add("West", var1);
try {
String var2 = rManager.getString("Panel.icon");
URL var3 = this.getClass().getResource(var2);
if (var3 != null) {
var1.setIcon(new ImageIcon(var3));
}
} catch (MissingResourceException var4) {
}
this.add("Center", this.comboBox = new JComboBox());
this.comboBox.setEditable(true);
}
public void addActionListener(ActionListener var1) {
this.comboBox.addActionListener(var1);
}
public String getText() {
return (String)this.comboBox.getEditor().getItem();
}
public void setText(String var1) {
this.comboBox.getEditor().setItem(var1);
}
public void addToHistory(String var1) {
this.comboBox.addItem(var1);
this.comboBox.setPreferredSize(new Dimension(0, this.comboBox.getPreferredSize().height));
}
static {
rManager = new ResourceManager(bundle);
}
}
|
923ae42e8257976359216f5f9baafbb33edd8379 | 877 | java | Java | src/main/java/pathfinder/benchmark/package-info.java | mriekkin/pathfinder | f45c279ad8088d569a2d993b6e19aab432f676f1 | [
"MIT"
] | null | null | null | src/main/java/pathfinder/benchmark/package-info.java | mriekkin/pathfinder | f45c279ad8088d569a2d993b6e19aab432f676f1 | [
"MIT"
] | 1 | 2018-08-29T12:34:18.000Z | 2018-08-29T12:34:18.000Z | src/main/java/pathfinder/benchmark/package-info.java | mriekkin/pathfinder | f45c279ad8088d569a2d993b6e19aab432f676f1 | [
"MIT"
] | null | null | null | 48.722222 | 80 | 0.769669 | 999,380 | /**
* The benchmark mode.
* <p>
* Algorithms can be compared by running the same set of problems for a number
* of algorithms. Hence, the basic idea of the benchmark mode is to run a large
* number of problems for the same set of algorithms. This means running
* multiple problems on any single map with different source and destination
* nodes. This set of source and destination nodes is called a scenario. It also
* means running the same set of algorithms on a variety of different maps. This
* means running multiple scenarios and averaging the results.
* <p>
* Each problem represents a small experiment. Each experiment should also be
* replicated a specified number of times to obtain reliable results. This means
* running the same shortest path problem for multiple times and taking the
* average of the running times.
*/
package pathfinder.benchmark;
|
923ae5a022f715becf4bdfee62153e3de0566619 | 2,673 | java | Java | zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/MiniZeppelin.java | panthdeepak/zeppelin | 50cfabdf9b4a55e1bb964376eb5eca22f6046913 | [
"MIT"
] | 15 | 2015-05-25T10:08:00.000Z | 2018-09-05T05:02:29.000Z | zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/MiniZeppelin.java | panthdeepak/zeppelin | 50cfabdf9b4a55e1bb964376eb5eca22f6046913 | [
"MIT"
] | 4 | 2016-06-24T16:41:29.000Z | 2017-03-18T05:45:26.000Z | zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/MiniZeppelin.java | panthdeepak/zeppelin | 50cfabdf9b4a55e1bb964376eb5eca22f6046913 | [
"MIT"
] | 4 | 2016-11-29T13:49:52.000Z | 2019-06-25T14:29:13.000Z | 38.73913 | 137 | 0.789001 | 999,381 | package org.apache.zeppelin.interpreter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.display.AngularObjectRegistryListener;
import org.apache.zeppelin.helium.ApplicationEventListener;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcessListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import static org.mockito.Mockito.mock;
public class MiniZeppelin {
protected static final Logger LOGGER = LoggerFactory.getLogger(MiniZeppelin.class);
protected InterpreterSettingManager interpreterSettingManager;
protected InterpreterFactory interpreterFactory;
protected File zeppelinHome;
private File confDir;
private File notebookDir;
protected ZeppelinConfiguration conf;
public void start() throws IOException {
zeppelinHome = new File("..");
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_HOME.getVarName(),
zeppelinHome.getAbsolutePath());
confDir = new File(zeppelinHome, "conf_" + getClass().getSimpleName());
notebookDir = new File(zeppelinHome, "notebook_" + getClass().getSimpleName());
confDir.mkdirs();
notebookDir.mkdirs();
LOGGER.info("ZEPPELIN_HOME: " + zeppelinHome.getAbsolutePath());
FileUtils.copyFile(new File(zeppelinHome, "conf/log4j.properties"), new File(confDir, "log4j.properties"));
FileUtils.copyFile(new File(zeppelinHome, "conf/log4j_yarn_cluster.properties"), new File(confDir, "log4j_yarn_cluster.properties"));
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_CONF_DIR.getVarName(), confDir.getAbsolutePath());
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_DIR.getVarName(), notebookDir.getAbsolutePath());
conf = new ZeppelinConfiguration();
interpreterSettingManager = new InterpreterSettingManager(conf,
mock(AngularObjectRegistryListener.class), mock(RemoteInterpreterProcessListener.class), mock(ApplicationEventListener.class));
interpreterFactory = new InterpreterFactory(interpreterSettingManager);
}
public void stop() throws IOException {
interpreterSettingManager.close();
FileUtils.deleteDirectory(confDir);
FileUtils.deleteDirectory(notebookDir);
}
public File getZeppelinHome() {
return zeppelinHome;
}
public File getZeppelinConfDir() {
return confDir;
}
public InterpreterFactory getInterpreterFactory() {
return interpreterFactory;
}
public InterpreterSettingManager getInterpreterSettingManager() {
return interpreterSettingManager;
}
}
|
923ae74255c59a2e93e4e02302a6b48ab24add74 | 4,539 | java | Java | manager-master/src/main/java/pt/unl/fct/miei/usmanagement/manager/management/monitoring/metrics/simulated/AppSimulatedMetricsController.java | usmanager/manager | b30e1738072f7445666bfd9365104b200cb7699a | [
"MIT"
] | null | null | null | manager-master/src/main/java/pt/unl/fct/miei/usmanagement/manager/management/monitoring/metrics/simulated/AppSimulatedMetricsController.java | usmanager/manager | b30e1738072f7445666bfd9365104b200cb7699a | [
"MIT"
] | null | null | null | manager-master/src/main/java/pt/unl/fct/miei/usmanagement/manager/management/monitoring/metrics/simulated/AppSimulatedMetricsController.java | usmanager/manager | b30e1738072f7445666bfd9365104b200cb7699a | [
"MIT"
] | null | null | null | 44.940594 | 117 | 0.820886 | 999,382 | /* * MIT License
*
* Copyright (c) 2020 manager
*
* 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 pt.unl.fct.miei.usmanagement.manager.management.monitoring.metrics.simulated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import pt.unl.fct.miei.usmanagement.manager.apps.App;
import pt.unl.fct.miei.usmanagement.manager.metrics.simulated.AppSimulatedMetric;
import pt.unl.fct.miei.usmanagement.manager.services.monitoring.metrics.simulated.AppSimulatedMetricsService;
import pt.unl.fct.miei.usmanagement.manager.util.validate.Validation;
import java.util.List;
@RestController
@RequestMapping("/simulated-metrics/apps")
public class AppSimulatedMetricsController {
private final AppSimulatedMetricsService appSimulatedMetricsService;
public AppSimulatedMetricsController(AppSimulatedMetricsService appSimulatedMetricsService) {
this.appSimulatedMetricsService = appSimulatedMetricsService;
}
@GetMapping
public List<AppSimulatedMetric> getAppSimulatedMetrics() {
return appSimulatedMetricsService.getAppSimulatedMetrics();
}
@GetMapping("/{simulatedMetricName}")
public AppSimulatedMetric getAppSimulatedMetric(@PathVariable String simulatedMetricName) {
return appSimulatedMetricsService.getAppSimulatedMetric(simulatedMetricName);
}
@PostMapping
public AppSimulatedMetric addAppSimulatedMetric(@RequestBody AppSimulatedMetric appSimulatedMetric) {
Validation.validatePostRequest(appSimulatedMetric.getId());
return appSimulatedMetricsService.addAppSimulatedMetric(appSimulatedMetric);
}
@PutMapping("/{simulatedMetricName}")
public AppSimulatedMetric updateAppSimulatedMetric(@PathVariable String simulatedMetricName,
@RequestBody AppSimulatedMetric simulatedMetric) {
Validation.validatePutRequest(simulatedMetric.getId());
return appSimulatedMetricsService.updateAppSimulatedMetric(simulatedMetricName, simulatedMetric);
}
@DeleteMapping("/{simulatedMetricName}")
public void deleteAppSimulatedMetric(@PathVariable String simulatedMetricName) {
appSimulatedMetricsService.deleteAppSimulatedMetric(simulatedMetricName);
}
@GetMapping("/{simulatedMetricName}/apps")
public List<App> getAppSimulatedMetricApps(@PathVariable String simulatedMetricName) {
return appSimulatedMetricsService.getApps(simulatedMetricName);
}
@PostMapping("/{simulatedMetricName}/apps")
public void addAppSimulatedMetricApps(@PathVariable String simulatedMetricName, @RequestBody List<String> apps) {
appSimulatedMetricsService.addApps(simulatedMetricName, apps);
}
@DeleteMapping("/{simulatedMetricName}/apps")
public void removeAppSimulatedMetricApps(@PathVariable String simulatedMetricName, @RequestBody List<String> apps) {
appSimulatedMetricsService.removeApps(simulatedMetricName, apps);
}
@DeleteMapping("/{simulatedMetricName}/apps/{appId}")
public void removeAppSimulatedMetricApp(@PathVariable String simulatedMetricName, @PathVariable String appId) {
appSimulatedMetricsService.removeApp(simulatedMetricName, appId);
}
}
|
923ae75838219a119f8edddc0bbefb7238012bf1 | 612 | java | Java | src/elementary_programming/Exercises/Exercise2.java | mandy8055/javaBookCaseStudies | 8dcda5b73520f4a9194d39d8659d4134dea1d96d | [
"MIT"
] | null | null | null | src/elementary_programming/Exercises/Exercise2.java | mandy8055/javaBookCaseStudies | 8dcda5b73520f4a9194d39d8659d4134dea1d96d | [
"MIT"
] | null | null | null | src/elementary_programming/Exercises/Exercise2.java | mandy8055/javaBookCaseStudies | 8dcda5b73520f4a9194d39d8659d4134dea1d96d | [
"MIT"
] | null | null | null | 38.25 | 74 | 0.648693 | 999,383 | package elementary_programming.Exercises;
import java.util.Scanner;
public class Exercise2 {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.print("Enter the radius and length of the cylinder: ");
double radius = sc.nextDouble();
double length = sc.nextDouble();
double area = Math.PI * radius * radius;
double volume = area * length;
System.out.println("The area of the cylinder is: " + area);
System.out.println("The volume of the cylinder is: " + volume);
sc.close();
}
}
|
923ae7b75ac1337efb08d895c3f56cb3a12b572a | 10,482 | java | Java | src/main/java/com/autotune/analyzer/services/ListAppTunables.java | agarwalrounak/autotune | cbb55e7eebd2362164e8115629ce398f95e5b160 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/autotune/analyzer/services/ListAppTunables.java | agarwalrounak/autotune | cbb55e7eebd2362164e8115629ce398f95e5b160 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/autotune/analyzer/services/ListAppTunables.java | agarwalrounak/autotune | cbb55e7eebd2362164e8115629ce398f95e5b160 | [
"Apache-2.0"
] | null | null | null | 48.527778 | 169 | 0.716657 | 999,384 | /*******************************************************************************
* Copyright (c) 2020, 2021 Red Hat, IBM Corporation and others.
*
* 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.autotune.analyzer.services;
import com.autotune.analyzer.application.Tunable;
import com.autotune.analyzer.datasource.DataSource;
import com.autotune.analyzer.datasource.DataSourceFactory;
import com.autotune.analyzer.deployment.AutotuneDeployment;
import com.autotune.analyzer.deployment.DeploymentInfo;
import com.autotune.analyzer.exceptions.MonitoringAgentNotFoundException;
import com.autotune.analyzer.k8sObjects.AutotuneConfig;
import com.autotune.analyzer.k8sObjects.AutotuneObject;
import com.autotune.analyzer.k8sObjects.FunctionVariable;
import com.autotune.analyzer.utils.DAConstants;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
public class ListAppTunables extends HttpServlet
{
/**
* Returns the list of applications monitored by autotune along with their tunables
*
* Request:
* `GET /listAppTunables` gives the tunables and layer information for all the applications monitored by autotune.
*
* `GET /listAppTunables?application_name=<APPLICATION_NAME>` for getting the tunables information of a specific application.
*
* `GET /listAppTunables?application_name=<APPLICATION_NAME>&layer_name='<LAYER>' for getting tunables of a specific layer for the application.
*
* Example JSON:
* {
* "application_name": "app1",
* “objective_function”: “transaction_response_time”,
* "sla_class": "response_time",
* “direction”: “minimize”
* "layers": [
* {
* "layer_level": 0,
* "layer_name": "container",
* "layer_details": "generic container tunables"
* "tunables": [
* {
* "name": "memoryRequest",
* "upper_bound": "300M",
* "lower_bound": "150M",
* "value_type": "double",
* "query_url": "http://prometheus:9090/container_memory_working_set_bytes{container=\"\", pod_name=\"petclinic-deployment-6d4c8678d4-jmz8x\"}"
* },
* {
* "name": "cpuRequest",
* "upper_bound": "3.0",
* "lower_bound": "1.0",
* "value_type": "double",
* "query_url": "http://prometheus:9090/(container_cpu_usage_seconds_total{container!=\"POD\", pod_name=\"petclinic-deployment-6d4c8678d4-jmz8x\"}[1m])"
* }
* ]
* },
* {
* "layer_level": 1,
* "layer_name": "openj9",
* "layer_details": "java openj9 tunables",
* "tunables": [
* {
* "name": "javaHeap",
* "upper_bound": "250M",
* "lower_bound": "100M",
* "value_type": "double",
* "query_url": "http://prometheus:9090/jvm_memory_used_bytes{area=\"heap\",id=\"nursery-allocate\", pod=petclinic-deployment-6d4c8678d4-jmz8x}"
* }
* ]
* }
* ]
* }
* ]
* @param req
* @param resp
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
JSONArray outputJsonArray = new JSONArray();
resp.setContentType("application/json");
String applicationName = req.getParameter(DAConstants.ServiceConstants.APPLICATION_NAME);
String layerName = req.getParameter(DAConstants.AutotuneConfigConstants.LAYER_NAME);
// If no autotuneobjects in the cluster
if (AutotuneDeployment.autotuneObjectMap.isEmpty()) {
outputJsonArray.put("Error: No objects of kind Autotune found!");
} else {
//If no application_name was passed in the request, print all apps in all autotune obects in response
if (applicationName == null) {
for (String autotuneObjectKey : AutotuneDeployment.applicationServiceStackMap.keySet()) {
AutotuneObject autotuneObject = AutotuneDeployment.autotuneObjectMap.get(autotuneObjectKey);
for (String application : AutotuneDeployment.applicationServiceStackMap.get(autotuneObjectKey).keySet()) {
addAppTunablesToResponse(outputJsonArray, autotuneObjectKey, autotuneObject, application, layerName);
}
}
} else {
boolean doesApplicationExist = false;
for (String autotuneObjectKey : AutotuneDeployment.applicationServiceStackMap.keySet()) {
if (AutotuneDeployment.applicationServiceStackMap.get(autotuneObjectKey).containsKey(applicationName)) {
AutotuneObject autotuneObject = AutotuneDeployment.autotuneObjectMap.get(autotuneObjectKey);
addAppTunablesToResponse(outputJsonArray, autotuneObjectKey, autotuneObject, applicationName, layerName);
doesApplicationExist = true;
}
}
//If no such application is monitored by autotune
if (!doesApplicationExist) {
outputJsonArray.put("Error: Application " + applicationName + " not found!");
}
}
}
resp.getWriter().println(outputJsonArray.toString(4));
}
private void addAppTunablesToResponse(JSONArray outputJsonArray, String autotuneObjectKey, AutotuneObject autotuneObject, String application, String layerName) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(DAConstants.ServiceConstants.APPLICATION_NAME, application);
jsonObject.put(DAConstants.AutotuneObjectConstants.DIRECTION, autotuneObject.getSlaInfo().getDirection());
jsonObject.put(DAConstants.AutotuneObjectConstants.OBJECTIVE_FUNCTION, autotuneObject.getSlaInfo().getObjectiveFunction());
jsonObject.put(DAConstants.AutotuneObjectConstants.SLA_CLASS, autotuneObject.getSlaInfo().getSlaClass());
jsonObject.put(DAConstants.AutotuneObjectConstants.ID, autotuneObject.getId());
jsonObject.put(DAConstants.AutotuneObjectConstants.HPO_ALGO_IMPL, autotuneObject.getSlaInfo().getHpoAlgoImpl());
// Add function_variables info
JSONArray functionVariablesArray = new JSONArray();
for (FunctionVariable functionVariable : autotuneObject.getSlaInfo().getFunctionVariables()) {
JSONObject functionVariableJson = new JSONObject();
functionVariableJson.put(DAConstants.AutotuneObjectConstants.NAME, functionVariable.getName());
functionVariableJson.put(DAConstants.AutotuneObjectConstants.VALUE_TYPE, functionVariable.getValueType());
try {
final DataSource dataSource = DataSourceFactory.getDataSource(DeploymentInfo.getMonitoringAgent());
functionVariableJson.put(DAConstants.ServiceConstants.QUERY_URL, Objects.requireNonNull(dataSource).getDataSourceURL() +
dataSource.getQueryEndpoint() + functionVariable.getQuery());
} catch (MonitoringAgentNotFoundException e) {
functionVariableJson.put(DAConstants.ServiceConstants.QUERY_URL, functionVariable.getQuery());
}
functionVariablesArray.put(functionVariableJson);
}
jsonObject.put(DAConstants.AutotuneObjectConstants.FUNCTION_VARIABLES, functionVariablesArray);
JSONArray layersArray = new JSONArray();
for (String autotuneConfigName : AutotuneDeployment.applicationServiceStackMap.get(autotuneObjectKey)
.get(application).getStackLayers().keySet()) {
AutotuneConfig autotuneConfig = AutotuneDeployment.applicationServiceStackMap.get(autotuneObjectKey)
.get(application).getStackLayers().get(autotuneConfigName);
if (layerName == null || autotuneConfigName.equals(layerName)) {
JSONObject layerJson = new JSONObject();
layerJson.put(DAConstants.AutotuneConfigConstants.ID, autotuneConfig.getId());
layerJson.put(DAConstants.AutotuneConfigConstants.LAYER_NAME, autotuneConfig.getLayerName());
layerJson.put(DAConstants.ServiceConstants.LAYER_DETAILS, autotuneConfig.getDetails());
layerJson.put(DAConstants.AutotuneConfigConstants.LAYER_LEVEL, autotuneConfig.getLevel());
JSONArray tunablesArray = new JSONArray();
for (Tunable tunable : autotuneConfig.getTunables()) {
JSONObject tunableJson = new JSONObject();
String tunableQuery = tunable.getQueries().get(DeploymentInfo.getMonitoringAgent());
tunableJson.put(DAConstants.AutotuneConfigConstants.NAME, tunable.getName());
tunableJson.put(DAConstants.AutotuneConfigConstants.UPPER_BOUND, tunable.getUpperBound());
tunableJson.put(DAConstants.AutotuneConfigConstants.LOWER_BOUND, tunable.getLowerBound());
tunableJson.put(DAConstants.AutotuneConfigConstants.VALUE_TYPE, tunable.getValueType());
tunableJson.put(DAConstants.AutotuneConfigConstants.STEP, tunable.getStep());
try {
String query = DAConstants.NONE;
final DataSource dataSource = DataSourceFactory.getDataSource(DeploymentInfo.getMonitoringAgent());
// If tunable has a query specified
if (tunableQuery != null && !tunableQuery.isEmpty()) {
query = Objects.requireNonNull(dataSource).getDataSourceURL() +
dataSource.getQueryEndpoint() + tunableQuery;
}
tunableJson.put(DAConstants.ServiceConstants.QUERY_URL, query);
} catch (MonitoringAgentNotFoundException e) {
tunableJson.put(DAConstants.ServiceConstants.QUERY_URL, tunableQuery);
}
tunablesArray.put(tunableJson);
}
layerJson.put(DAConstants.AutotuneConfigConstants.TUNABLES, tunablesArray);
layersArray.put(layerJson);
}
}
if (layersArray.isEmpty()) {
// No autotuneconfig objects currently being monitored.
if (layerName == null)
outputJsonArray.put("Error: No AutotuneConfig objects found!");
else
outputJsonArray.put("Error: AutotuneConfig " + layerName + " not found!");
return;
}
jsonObject.put(DAConstants.ServiceConstants.LAYERS, layersArray);
outputJsonArray.put(jsonObject);
}
}
|
923ae85c8532dc24a709d474ec6b0a9b1f4a5f70 | 4,875 | java | Java | src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateTableTest20.java | gdyjlqh/druid | d8805ae98c0973b9e684fadb394df2d24f12b335 | [
"Apache-2.0"
] | 9 | 2018-12-29T08:44:08.000Z | 2018-12-29T08:44:34.000Z | src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateTableTest20.java | gdyjlqh/druid | d8805ae98c0973b9e684fadb394df2d24f12b335 | [
"Apache-2.0"
] | 5 | 2021-12-10T01:35:55.000Z | 2022-02-16T01:07:37.000Z | src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateTableTest20.java | gdyjlqh/druid | d8805ae98c0973b9e684fadb394df2d24f12b335 | [
"Apache-2.0"
] | 2 | 2019-04-18T08:22:12.000Z | 2019-04-18T08:22:18.000Z | 44.724771 | 91 | 0.523692 | 999,385 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.bvt.sql.oracle.create;
import java.util.List;
import org.junit.Assert;
import com.alibaba.druid.sql.OracleTest;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.util.JdbcConstants;
public class OracleCreateTableTest20 extends OracleTest {
public void test_types() throws Exception {
String sql = //
" CREATE TABLE \"SONAR\".\"ACTIVE_RULE_NOTES\" " //
+ " ( \"ID\" NUMBER(38,0) NOT NULL ENABLE, " //
+ " \"CREATED_AT\" TIMESTAMP (6), " //
+ " \"UPDATED_AT\" TIMESTAMP (6), " //
+ " \"ACTIVE_RULE_ID\" NUMBER(38,0), " //
+ " \"USER_LOGIN\" VARCHAR2(40 BYTE), " //
+ " \"DATA\" BLOB, " //
+ " PRIMARY KEY (\"ID\")" //
+ " USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS " //
+ " TABLESPACE \"USERS\" ENABLE" //
+ " ) SEGMENT CREATION DEFERRED " //
+ " PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 " //
+ " NOCOMPRESS LOGGING" //
+ " TABLESPACE \"USERS\" " //
+ " LOB (\"DATA\") STORE AS SECUREFILE (" //
+ " TABLESPACE \"USERS\" ENABLE STORAGE IN ROW CHUNK 8192" //
+ " NOCACHE LOGGING NOCOMPRESS KEEP_DUPLICATES ) ;";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement statement = statementList.get(0);
print(statementList);
Assert.assertEquals(1, statementList.size());
Assert.assertEquals("CREATE TABLE \"SONAR\".\"ACTIVE_RULE_NOTES\" (\n" +
"\t\"ID\" NUMBER(38, 0) NOT NULL ENABLE,\n" +
"\t\"CREATED_AT\" TIMESTAMP(6),\n" +
"\t\"UPDATED_AT\" TIMESTAMP(6),\n" +
"\t\"ACTIVE_RULE_ID\" NUMBER(38, 0),\n" +
"\t\"USER_LOGIN\" VARCHAR2(40 BYTE),\n" +
"\t\"DATA\" BLOB,\n" +
"\tPRIMARY KEY (\"ID\")\n" +
"\t\tUSING INDEX\n" +
"\t\tPCTFREE 10\n" +
"\t\tINITRANS 2\n" +
"\t\tMAXTRANS 255\n" +
"\t\tTABLESPACE \"USERS\"\n" +
"\t\tCOMPUTE STATISTICS\n" +
"\t\tENABLE\n" +
")\n" +
"PCTFREE 10\n" +
"PCTUSED 40\n" +
"INITRANS 1\n" +
"MAXTRANS 255\n" +
"NOCOMPRESS\n" +
"LOGGING\n" +
"TABLESPACE \"USERS\"\n" +
"LOB (\"DATA\") STORE AS SECUREFILE (\n" +
"\tNOCOMPRESS\n" +
"\tLOGGING\n" +
"\tTABLESPACE \"USERS\"\n" +
"\tENABLE STORAGE IN ROW\n" +
"\tCHUNK 8192\n" +
"\tNOCACHE\n" +
"\tKEEP_DUPLICATES\n" +
");",//
SQLUtils.toSQLString(statement, JdbcConstants.ORACLE));
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
statement.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
Assert.assertEquals(1, visitor.getTables().size());
Assert.assertEquals(6, visitor.getColumns().size());
Assert.assertTrue(visitor.containsColumn("SONAR.ACTIVE_RULE_NOTES", "ID"));
}
}
|
923ae8d3ae512e789629d0640b6ba07830659376 | 417 | java | Java | app/src/main/java/com/android/smartlink/ui/model/UISetting.java | devin1014/Smartlink-ELEC | 74e9ddf7712672b1ce526b68810dc4d5a10d69bf | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/smartlink/ui/model/UISetting.java | devin1014/Smartlink-ELEC | 74e9ddf7712672b1ce526b68810dc4d5a10d69bf | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/smartlink/ui/model/UISetting.java | devin1014/Smartlink-ELEC | 74e9ddf7712672b1ce526b68810dc4d5a10d69bf | [
"Apache-2.0"
] | null | null | null | 13.451613 | 47 | 0.570743 | 999,386 | package com.android.smartlink.ui.model;
/**
* User: LIUWEI
* Date: 2017-10-17
* Time: 16:38
*/
public class UISetting
{
private String mName;
private String mImage;
public UISetting(String name, String image)
{
mName = name;
mImage = image;
}
public String getName()
{
return mName;
}
public String getImage()
{
return mImage;
}
}
|
923ae91bbe8f99f75434cddd256fc8ec7743d76e | 10,752 | java | Java | CustomListView/src/main/java/com/thomaskioko/customlistview/adapter/ListAdapter.java | mikespux/CustomListView | 9edbcadf0b344ae387b8de3f8ded9c65b3d1f08e | [
"Apache-2.0"
] | null | null | null | CustomListView/src/main/java/com/thomaskioko/customlistview/adapter/ListAdapter.java | mikespux/CustomListView | 9edbcadf0b344ae387b8de3f8ded9c65b3d1f08e | [
"Apache-2.0"
] | null | null | null | CustomListView/src/main/java/com/thomaskioko/customlistview/adapter/ListAdapter.java | mikespux/CustomListView | 9edbcadf0b344ae387b8de3f8ded9c65b3d1f08e | [
"Apache-2.0"
] | null | null | null | 40.432331 | 108 | 0.564389 | 999,387 | /*
* Copyright (c) 2015. Thomas Kioko.
*
* 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.thomaskioko.customlistview.adapter;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.thomaskioko.customlistview.R;
import com.thomaskioko.customlistview.model.Movie;
import java.util.LinkedList;
import java.util.List;
/**
* This class provides data to the list.
*
* @author <a href="kenaa@example.com">Thomas Kioko</a>
* @version Version 1.0
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.MovieViewHolder> {
private List<Movie> mMovieList;
/**
* This LinkedList is used to map the position of the item and the image
*/
protected LinkedList<Integer> drawableLinkedList;
private Context mContext;
/**
* Default Constructor
*
* @param context Application context
* @param followerList Follower List objects
* @param drawableLinkedList Drawable item .
*/
public ListAdapter(Context context, List<Movie> followerList, LinkedList<Integer> drawableLinkedList) {
this.mContext = context;
this.mMovieList = followerList;
this.drawableLinkedList = drawableLinkedList;
}
@Override
public void onBindViewHolder(MovieViewHolder holder, final int position) {
Movie movie = mMovieList.get(position);
final int actionDrawableId = this.drawableLinkedList.get(position);
holder.title.setText(movie.getTitle());
holder.rating.setText("Rating: " + String.valueOf(movie.getRating()));
//Use Glide to load the Image
Glide.with(mContext).load(movie.getThumbnailUrl()).centerCrop().into(holder.thumbNail);
// genre
String genreStr = "";
for (String str : movie.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,
genreStr.length() - 2) : genreStr;
holder.genre.setText(genreStr);
holder.year.setText(String.valueOf(movie.getYear()));
/**
* Set OnClickListener on the Button.
* We pass in 3 parameters:
* @param position :Position of the object on the List
* @param mMovieList Movie Object
* @param actionDrawableId Drawable ID
*/
holder.imageViewAddMovie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onMemberClick(position, mMovieList, actionDrawableId);
}
});
//Set the Image Resource
holder.imageViewAddMovie.setImageResource(actionDrawableId);
}
@Override
public int getItemCount() {
return mMovieList.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.movie_item_layout, viewGroup, false);
return new MovieViewHolder(itemView);
}
/**
* This class uses A ViewHolder object stores to each of the component views inside the tag field
* of the Layout, so you can immediately access them without the need to look them up repeatedly.
* <p/>
* {@see <a href="http://developer.android.com/training/improving-layouts/smooth-scrolling.html</a>}
*/
public static class MovieViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
ImageView imageViewAddMovie;
TextView title;
TextView rating;
TextView genre;
TextView year;
public MovieViewHolder(View itemView) {
super(itemView);
thumbNail = (ImageView) itemView.findViewById(R.id.thumbnail);
title = (TextView) itemView.findViewById(R.id.title);
rating = (TextView) itemView.findViewById(R.id.rating);
genre = (TextView) itemView.findViewById(R.id.genre);
year = (TextView) itemView.findViewById(R.id.releaseYear);
imageViewAddMovie = (ImageView) itemView.findViewById(R.id.btnAddMovie);
}
}
/**
* This method handles onclick behaviour when a user clicks on the add movie button.
* We get the Drawable Id on the clicked item and perform the related action. We use an AsyncTask
* to simulate a long process.
*
* Once the AsyncTask is complete {@see onPostExecute}, we remove the drawable/image on the list
* and add the another image mapping it to the position of the object.
*
* Use Case:
* When a user clicks on add button, make a HTTP request and store the selected movie in the
* watchlist table then get the response from the server and update the icon based on the response
* from the server.
*
* We Use a Switch case to get the Drawable ID which will determine what action to perform.
*
* R.drawable.movie_add_touch: Add the selected movie to the DB
* R.drawable.movie_added_touch: Remove the Movie from the DB
* R.drawable.movie_error_touch: An error occurred performing your request. Retry.
*
*
* @param position clicked object position
* @param followerList Object List
* @param actionDrawableId Drawable Id
*/
protected void onMemberClick(final int position, final List<Movie> followerList,int actionDrawableId) {
final Movie follower = followerList.get(position);
switch (actionDrawableId) {
case R.drawable.movie_add_touch:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 1; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Complete";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equals("Complete")) {
Toast.makeText(mContext, follower.getTitle(), Toast.LENGTH_SHORT).show();
drawableLinkedList.remove(position);
drawableLinkedList.add(position, R.drawable.movie_added_touch);
notifyDataSetChanged();
} else {
drawableLinkedList.remove(position);
drawableLinkedList.add(position, R.drawable.movie_error_touch);
Toast.makeText(mContext, mContext.getString(R.string.text_something_went_wrong),
Toast.LENGTH_SHORT).show();
}
}
}.execute();
break;
case R.drawable.movie_added_touch:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 1; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Complete";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equals("Complete")) {
drawableLinkedList.remove(position);
drawableLinkedList.add(position, R.drawable.movie_add_touch);
notifyDataSetChanged();
} else {
drawableLinkedList.remove(position);
drawableLinkedList.add(position, R.drawable.movie_error_touch);
Toast.makeText(mContext, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
}.execute();
break;
case R.drawable.movie_error_touch:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 1; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Complete";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equals("Complete")) {
drawableLinkedList.remove(position);
drawableLinkedList.add(position, R.drawable.movie_added_touch);
notifyDataSetChanged();
} else {
drawableLinkedList.remove(position);
drawableLinkedList.add(position, R.drawable.movie_error_touch);
Toast.makeText(mContext, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
}.execute();
break;
}
}
}
|
923ae9c13cdc345ad4e10eb32ae1e66e7ad0f486 | 1,552 | java | Java | app/src/main/java/com/linkb/jstx/model/intent/SearchUserParam.java | hongchun166/jtxt | 5ceac15b4a6bf510eb82bf5dd496c80b2d08a25d | [
"Apache-2.0"
] | 1 | 2020-07-27T10:36:28.000Z | 2020-07-27T10:36:28.000Z | app/src/main/java/com/linkb/jstx/model/intent/SearchUserParam.java | hongchun166/jtxt | 5ceac15b4a6bf510eb82bf5dd496c80b2d08a25d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/linkb/jstx/model/intent/SearchUserParam.java | hongchun166/jtxt | 5ceac15b4a6bf510eb82bf5dd496c80b2d08a25d | [
"Apache-2.0"
] | null | null | null | 19.4 | 54 | 0.623067 | 999,388 | package com.linkb.jstx.model.intent;
import java.io.Serializable;
public class SearchUserParam implements Serializable {
private int searchType;
private String inputStr;
private String region;
private String industry;
private String label;
String gender;
private String otherKey;
String marriedStr;//单身|非单身
public String getInputStr() {
return inputStr;
}
public void setInputStr(String inputStr) {
this.inputStr = inputStr;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getIndustry() {
return industry;
}
public void setIndustry(String industry) {
this.industry = industry;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getSearchType() {
return searchType;
}
public void setSearchType(int searchType) {
this.searchType = searchType;
}
public String getOtherKey() {
return otherKey;
}
public void setOtherKey(String otherKey) {
this.otherKey = otherKey;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMarriedStr() {
return marriedStr;
}
public void setMarriedStr(String marriedStr) {
this.marriedStr = marriedStr;
}
}
|
923aeabc67bbdab30a229089cc7a0d6c5802056f | 3,844 | java | Java | app/src/main/java/com/example/android/news/NewsActivity.java | duracellpower/android-news | e5b880b8913c65a8b2a0dff48a31af205265725a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/news/NewsActivity.java | duracellpower/android-news | e5b880b8913c65a8b2a0dff48a31af205265725a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/news/NewsActivity.java | duracellpower/android-news | e5b880b8913c65a8b2a0dff48a31af205265725a | [
"Apache-2.0"
] | null | null | null | 36.264151 | 99 | 0.705775 | 999,389 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.news;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class NewsActivity extends AppCompatActivity
implements LoaderCallbacks<List<News>> {
private static final String LOG_TAG = NewsActivity.class.getName();
private static final String USGS_REQUEST_URL =
"https://content.guardianapis.com/search?api-key=ee342bf0-b6de-496b-b577-1452f42de113";
private static final int NEWS_LOADER_ID = 1;
private NewsAdapter mAdapter;
private TextView mEmptyStateTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_activity);
ListView newsListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
newsListView.setEmptyView(mEmptyStateTextView);
mAdapter = new NewsAdapter(this, new ArrayList<News>());
newsListView.setAdapter(mAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
News currentNews = mAdapter.getItem(position);
Uri newsUri = Uri.parse(currentNews.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
startActivity(websiteIntent);
}
});
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
@Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, USGS_REQUEST_URL);
}
@Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
@Override
public void onLoaderReset(Loader<List<News>> loader) {
mAdapter.clear();
}
}
|
923aeb7234f343cbdf3fc0766828b1b9d3812b94 | 3,042 | java | Java | fs_web_common/src/main/java/py/com/sodep/mobileforms/web/json/JsonResponse.java | jokoframework/captura-formserver-community | 004f979d5116ef24eb1ed43aca2566d48fc13ee4 | [
"Apache-2.0"
] | null | null | null | fs_web_common/src/main/java/py/com/sodep/mobileforms/web/json/JsonResponse.java | jokoframework/captura-formserver-community | 004f979d5116ef24eb1ed43aca2566d48fc13ee4 | [
"Apache-2.0"
] | 1 | 2021-03-08T18:28:30.000Z | 2021-03-08T18:28:30.000Z | fs_web_common/src/main/java/py/com/sodep/mobileforms/web/json/JsonResponse.java | jokoframework/captura-formserver-community | 004f979d5116ef24eb1ed43aca2566d48fc13ee4 | [
"Apache-2.0"
] | null | null | null | 22.701493 | 80 | 0.735371 | 999,390 | package py.com.sodep.mobileforms.web.json;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
@JsonInclude(Include.NON_NULL)
public class JsonResponse<T> {
private boolean success;
private String title;
private String unescapedTitle;
private String message;
private String unescapedMessage;
private Map<String, Object> content;
private T obj;
public boolean getSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Map<String, Object> getContent() {
return content;
}
public void setContent(Map<String, Object> content) {
this.content = content;
}
/**
* Message is meant to be an explanation of the action that took place. It
* could be a more elaborated description than caption
*
* If only one message is needed, this is the preferred property to put it.
*
* @param message
*/
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getObj() {
return obj;
}
public void setObj(T obj) {
this.obj = obj;
}
/**
* Title is meant to be used as a short message or title for a response to
* the user
*
* @return
*/
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
/**
* If the title has some html content use this field
*
* @return unescaped String. No html content is escaped
*/
@JsonSerialize(using = StringSerializer.class, include = Inclusion.NON_NULL)
public String getUnescapedTitle() {
return unescapedTitle;
}
public void setUnescapedTitle(String unescapedTitle) {
this.unescapedTitle = unescapedTitle;
}
/**
* If the message has some html content that needs to be renderer on the
* browser use this
*
* @return unescaped String. No html content is escaped
*/
@JsonSerialize(using = StringSerializer.class, include = Inclusion.NON_NULL)
public String getUnescapedMessage() {
return unescapedMessage;
}
public void setUnescapedMessage(String unescapedMessage) {
this.unescapedMessage = unescapedMessage;
}
public void addContent(String key, Object val) {
if (content == null) {
content = new HashMap<String, Object>();
}
content.put(key, val);
}
public static JsonResponse<String> buildSimpleSuccessResponse(String message) {
JsonResponse<String> response = new JsonResponse<String>();
response.setMessage(message);
response.setSuccess(true);
return response;
}
public static JsonResponse<String> buildSimpleFailureResponse(String message) {
JsonResponse<String> response = new JsonResponse<String>();
response.setMessage(message);
response.setSuccess(false);
return response;
}
}
|
923aebdfc11d7bf322100dfb10ab911a0185adf1 | 8,879 | java | Java | app/src/main/java/com/smart/cloud/fire/GetLocationActivity.java | bingo1118/kaipingMS | 76da24fbdebcbd7d1ff4bfa79335ca67f374c773 | [
"Apache-2.0"
] | 1 | 2019-09-27T05:37:29.000Z | 2019-09-27T05:37:29.000Z | app/src/main/java/com/smart/cloud/fire/GetLocationActivity.java | bingo1118/SmartCloudFire | 7795912c0d38457a92be8ba24fa28467232c68ff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/smart/cloud/fire/GetLocationActivity.java | bingo1118/SmartCloudFire | 7795912c0d38457a92be8ba24fa28467232c68ff | [
"Apache-2.0"
] | null | null | null | 33.889313 | 137 | 0.622367 | 999,391 | package com.smart.cloud.fire;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.smart.cloud.fire.global.MyApp;
import fire.cloud.smart.com.smartcloudfire.R;
public class GetLocationActivity extends Activity implements View.OnClickListener{
Context mContext;
MapView mMapView;
private LatLng selectedLatlng;
private String location_address="";
private BaiduMap mBaiduMap;
private LocationClient mLocationClient;
/**
* 定位的监听器
*/
public MyLocationListener mMyLocationListener;
/**
* 当前定位的模式
*/
private MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
/***
* 是否是第一次定位
*/
private volatile boolean isFristLocation = true;
Button btn_confirm;
ImageView image_location;
GeoCoder geoCoder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_location);
mContext=getApplicationContext();
btn_confirm=(Button)findViewById(R.id.confirm_btn);
image_location=(ImageView)findViewById(R.id.location_image);
btn_confirm.setOnClickListener(this);
image_location.setOnClickListener(this);
mMapView=(MapView)findViewById(R.id.bmapView) ;
mBaiduMap = mMapView.getMap();// 获得MapView
initMyLocation();
geoCoder = GeoCoder.newInstance();
mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
//获取经纬度
final double latitude = latLng.latitude;
final double longitude = latLng.longitude;
System.out.println("latitude=" + latitude + ",longitude=" + longitude);
//先清除图层
mBaiduMap.clear();
mBaiduMap.setMyLocationEnabled(false);//@@6.20关闭定位图层
// 定义Maker坐标点
LatLng point = new LatLng(latitude, longitude);
// 构建MarkerOption,用于在地图上添加Marker
View viewA = LayoutInflater.from(MyApp.app).inflate(
R.layout.image_mark, null);
BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
.fromView(viewA);
MarkerOptions options = new MarkerOptions().position(point)
.icon(mCurrentMarker);
// 在地图上添加Marker,并显示
mBaiduMap.addOverlay(options);
findAddress(point);
}
@Override
public boolean onMapPoiClick(MapPoi mapPoi) {
return false;
}
});
}
private void findAddress(final LatLng latLng) {
this.selectedLatlng=latLng;
//实例化一个地理编码查询对象
// GeoCoder geoCoder = GeoCoder.newInstance();
//设置反地理编码位置坐标
ReverseGeoCodeOption op = new ReverseGeoCodeOption();
op.location(latLng);
//发起反地理编码请求(经纬度->地址信息)
geoCoder.reverseGeoCode(op);
geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
//获取点击的坐标地址
String address = arg0.getAddress();
location_address=address;
Toast.makeText(MyApp.app,"地址:"+address+"\n"+"纬度:"+latLng.latitude+"\n"+"经度:"+latLng.longitude,Toast.LENGTH_LONG).show();
System.out.println("address="+address);
}
@Override
public void onGetGeoCodeResult(GeoCodeResult arg0) {
}
});
}
private void initMyLocation()
{
// 定位初始化
mLocationClient = new LocationClient(getApplicationContext());
mMyLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(mMyLocationListener);
// 设置定位的相关配置
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);// 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
mLocationClient.setLocOption(option);
}
@Override
protected void onStart()
{
// 开启图层定位
mBaiduMap.setMyLocationEnabled(true);
if (!mLocationClient.isStarted())
{
mLocationClient.start();
}
super.onStart();
}
@Override
protected void onStop()
{
// 关闭图层定位
mBaiduMap.setMyLocationEnabled(false);
mLocationClient.stop();
super.onStop();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.confirm_btn:
Intent intent = new Intent();
//把返回数据存入Intent
Bundle bundle=new Bundle();
bundle.putString("address", location_address);
if(selectedLatlng!=null){
bundle.putDouble("lat",selectedLatlng.latitude);
bundle.putDouble("lon",selectedLatlng.longitude);
}
intent.putExtra("data",bundle);
this.setResult(this.RESULT_OK,intent);
finish();
break;
case R.id.location_image:
mBaiduMap.clear();
mBaiduMap.setMyLocationEnabled(true);
isFristLocation=true;
initMyLocation();
break;
}
}
public class MyLocationListener implements BDLocationListener
{
@Override
public void onReceiveLocation(BDLocation location)
{
// map view 销毁后不在处理新接收的位置
if (location == null || mMapView == null)
return;
// 构造定位数据
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius()).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
// 设置定位数据
mBaiduMap.setMyLocationData(locData);
// 设置自定义图标
View viewA = LayoutInflater.from(getApplicationContext()).inflate(
R.layout.image_mark, null);
BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
.fromView(viewA);
mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
// 第一次定位时,将地图位置移动到当前位置
if (isFristLocation)
{
isFristLocation = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
// mBaiduMap.animateMapStatus(u);
mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(ll).zoom(18).build()));//@@6.28
findAddress(new LatLng(location.getLatitude(),
location.getLongitude()));//@@6.20
}
}
}
@Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
@Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
@Override
protected void onDestroy() {
mMapView.onDestroy();
if(mLocationClient!=null){
mLocationClient.stop();
mLocationClient.unRegisterLocationListener(mMyLocationListener);
}
geoCoder.destroy();
super.onDestroy();
}
}
|
923aece179a057ac696d2901e3c8d36c2589665a | 1,566 | java | Java | src/main/java/net/datenstrudel/bulbs/core/application/services/ActuatorServiceImpl.java | datenstrudel/bulbs-core | bc87aa2a815b56fc21de2fca902176ed6d8ea5d1 | [
"Apache-2.0"
] | 2 | 2015-11-10T17:50:51.000Z | 2016-10-30T11:19:08.000Z | src/main/java/net/datenstrudel/bulbs/core/application/services/ActuatorServiceImpl.java | datenstrudel/bulbs-core | bc87aa2a815b56fc21de2fca902176ed6d8ea5d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/datenstrudel/bulbs/core/application/services/ActuatorServiceImpl.java | datenstrudel/bulbs-core | bc87aa2a815b56fc21de2fca902176ed6d8ea5d1 | [
"Apache-2.0"
] | 2 | 2018-02-12T15:48:59.000Z | 2022-02-10T05:25:46.000Z | 34.8 | 94 | 0.639208 | 999,392 | package net.datenstrudel.bulbs.core.application.services;
import net.datenstrudel.bulbs.core.domain.model.bulb.AbstractActuatorCmd;
import net.datenstrudel.bulbs.core.domain.model.bulb.ActuatorDomainService;
import net.datenstrudel.bulbs.shared.domain.model.bulb.BulbBridgeHwException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* @author Thomas Wendzinski
*/
@Service(value = "bulbActuatorServiceImpl")
public class ActuatorServiceImpl implements ActuatorService {
//~ Member(s) //////////////////////////////////////////////////////////////
@Autowired
private ActuatorDomainService actuatorDomainService;
//~ Construction ///////////////////////////////////////////////////////////
//~ Method(s) //////////////////////////////////////////////////////////////
@Override
public void executeDeferred(
AbstractActuatorCmd command) throws BulbBridgeHwException {
actuatorDomainService.executeDeferred(command);
}
@Override
public void execute(
AbstractActuatorCmd command) throws BulbBridgeHwException {
actuatorDomainService.execute(command);
}
@Override
public void execute(
Collection<? extends AbstractActuatorCmd> commands) throws BulbBridgeHwException {
actuatorDomainService.execute(commands);
}
//~ Private Artifact(s) ////////////////////////////////////////////////////
}
|
923aed285e5776d17aae059dd85e96034fe1764f | 185 | java | Java | src/main/java/com/appsom/tkach/spring/core/loggers/EventLogger.java | olegmikheyev/tkach-spring-basics | 35fb4df57aa9cd58c5a8598594ea815361be3ffe | [
"MIT"
] | null | null | null | src/main/java/com/appsom/tkach/spring/core/loggers/EventLogger.java | olegmikheyev/tkach-spring-basics | 35fb4df57aa9cd58c5a8598594ea815361be3ffe | [
"MIT"
] | null | null | null | src/main/java/com/appsom/tkach/spring/core/loggers/EventLogger.java | olegmikheyev/tkach-spring-basics | 35fb4df57aa9cd58c5a8598594ea815361be3ffe | [
"MIT"
] | null | null | null | 20.555556 | 49 | 0.756757 | 999,393 | package com.appsom.tkach.spring.core.loggers;
import com.appsom.tkach.spring.core.events.Event;
public interface EventLogger {
void logEvent(Event event);
String getName();
}
|
923aef3d5fe7247fb868d7c6fc63a1b9e33b8ee9 | 235 | java | Java | src/main/java/silverchain/parser/TypeParameterList.java | gitter-badger/silverchain | 93ce14899ace3652840452d28724a1c889e89a0c | [
"MIT"
] | 35 | 2017-10-26T06:43:44.000Z | 2022-03-26T13:03:58.000Z | src/main/java/silverchain/parser/TypeParameterList.java | gitter-badger/silverchain | 93ce14899ace3652840452d28724a1c889e89a0c | [
"MIT"
] | 42 | 2021-06-20T10:13:50.000Z | 2022-03-30T20:11:04.000Z | src/main/java/silverchain/parser/TypeParameterList.java | gitter-badger/silverchain | 93ce14899ace3652840452d28724a1c889e89a0c | [
"MIT"
] | 5 | 2018-05-10T08:36:11.000Z | 2021-11-06T13:19:13.000Z | 26.111111 | 89 | 0.787234 | 999,394 | package silverchain.parser;
public final class TypeParameterList extends ASTNodeN<TypeParameter, TypeParameterList> {
TypeParameterList(Range range, TypeParameter head, TypeParameterList tail) {
super(range, head, tail);
}
}
|
923aefe3543696d422022f1d79086ef6bab8269b | 557 | java | Java | chapter_001/src/test/java/ru/job4j/calculate/CalculateTest.java | AnnWhite007/job4j | 4df2dc7c83ec28e43cf1d5cac557bec20cceed9b | [
"Apache-2.0"
] | null | null | null | chapter_001/src/test/java/ru/job4j/calculate/CalculateTest.java | AnnWhite007/job4j | 4df2dc7c83ec28e43cf1d5cac557bec20cceed9b | [
"Apache-2.0"
] | null | null | null | chapter_001/src/test/java/ru/job4j/calculate/CalculateTest.java | AnnWhite007/job4j | 4df2dc7c83ec28e43cf1d5cac557bec20cceed9b | [
"Apache-2.0"
] | null | null | null | 20.107143 | 58 | 0.683837 | 999,395 | package ru.job4j.calculate;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Anna Babintseva (lyhxr@example.com)
* @version $Id$
* @since 0.1
*/
public class CalculateTest {
/**
* Test echo.
*/
@Test
public void whenTakeNameThenThreeEchoPlusName() {
String input = "Anna Babintseva";
String expect = "Echo, echo, echo : Anna Babintseva";
Calculate calc = new Calculate();
String result = calc.echo(input);
assertThat(result, is(expect));
}
} |
923af011dad3845479689174c3950d1945e53132 | 4,984 | java | Java | app/src/main/java/com/example/android/miwok/ColorsActivity.java | Nkonyane/ud839_Miwok-lesson-one | d9bc5700490d71ac6064fbbda1091d64fdb510c4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/miwok/ColorsActivity.java | Nkonyane/ud839_Miwok-lesson-one | d9bc5700490d71ac6064fbbda1091d64fdb510c4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/miwok/ColorsActivity.java | Nkonyane/ud839_Miwok-lesson-one | d9bc5700490d71ac6064fbbda1091d64fdb510c4 | [
"Apache-2.0"
] | null | null | null | 36.918519 | 116 | 0.65931 | 999,396 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.miwok;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RemoteController;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import static android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT;
public class ColorsActivity extends AppCompatActivity {
private MediaPlayer mMediaPlayer;
private AudioManager mAudiomanager;
private RemoteController RemoteControlReceiver;
AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener=
new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange==AUDIOFOCUS_LOSS_TRANSIENT||
focusChange== AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
mMediaPlayer.pause();
mMediaPlayer.seekTo(0);
}else if(focusChange==AudioManager.AUDIOFOCUS_GAIN) {
mMediaPlayer.start();
//resume play back
}else if (focusChange==AudioManager.AUDIOFOCUS_LOSS){
releaseMediaPlayer();
}
}
};
private MediaPlayer.OnCompletionListener mCompletionListener=new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
releaseMediaPlayer();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
//create and setup the audi manager to request audio focus
mAudiomanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
//creating a list of words
final ArrayList<word> words=new ArrayList<word>();
//creating an arrayn list of words
words.add(new word("red","wetetti",R.drawable.color_red,R.raw.color_red));
words.add(new word("mustard yellow","chiwiita",R.drawable.color_mustard_yellow,R.raw.color_mustard_yellow));
words.add(new word("dusty yellow","topiisa",R.drawable.color_dusty_yellow,R.raw.color_dusty_yellow));
words.add(new word("green","chkokki",R.drawable.color_green,R.raw.color_green));
words.add(new word("brown","takaakki,",R.drawable.color_brown,R.raw.color_brown));
words.add(new word("gray","topoppi",R.drawable.color_gray,R.raw.color_gray));
words.add(new word("black","kululli",R.drawable.color_black,R.raw.color_black));
words.add(new word("white","kelelli",R.drawable.color_white,R.raw.color_white));
WordAdapter adapter=
new WordAdapter(this, words,R.color.category_colors);
ListView listView=(ListView)findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
word Word=words.get(position);
releaseMediaPlayer();
//Request audio focus for playback
int result = mAudiomanager.requestAudioFocus(mOnAudioFocusChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mMediaPlayer = MediaPlayer.create(ColorsActivity.this, Word.getmAudioresourceId());
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
}
protected void onStop(){
super.onStop();
releaseMediaPlayer();
}
//clean the media player by releasing its resources
private void releaseMediaPlayer(){
//
if (mMediaPlayer!=null){
mMediaPlayer.release();
mMediaPlayer=null;
mAudiomanager.abandonAudioFocus(mOnAudioFocusChangeListener);
}
}
}
|
923af0890dfd8ca7e120c49b534aeb69d8b405fd | 3,157 | java | Java | src/test/java/seedu/plannermd/model/appointment/AppointmentIsBeforePredicateTest.java | pualixue/tp | 137d2c7effacedae8ec8a251a3ee9d3061d15ba7 | [
"MIT"
] | null | null | null | src/test/java/seedu/plannermd/model/appointment/AppointmentIsBeforePredicateTest.java | pualixue/tp | 137d2c7effacedae8ec8a251a3ee9d3061d15ba7 | [
"MIT"
] | 195 | 2021-09-19T03:53:26.000Z | 2021-11-08T08:25:43.000Z | src/test/java/seedu/plannermd/model/appointment/AppointmentIsBeforePredicateTest.java | pualixue/tp | 137d2c7effacedae8ec8a251a3ee9d3061d15ba7 | [
"MIT"
] | 5 | 2021-09-12T05:52:16.000Z | 2021-09-21T06:24:50.000Z | 39.4625 | 106 | 0.712385 | 999,397 | package seedu.plannermd.model.appointment;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import seedu.plannermd.testutil.appointment.AppointmentBuilder;
public class AppointmentIsBeforePredicateTest {
@Test
public void equals() {
LocalDate firstDate = LocalDate.now();
LocalDate secondDate = LocalDate.now().minusDays(1);
AppointmentIsBeforePredicate firstPredicate =
new AppointmentIsBeforePredicate(firstDate);
AppointmentIsBeforePredicate secondPredicate =
new AppointmentIsBeforePredicate(secondDate);
// same object -> equals
assertEquals(firstPredicate, firstPredicate);
// Same values -> equals
AppointmentIsBeforePredicate firstPredicateCopy =
new AppointmentIsBeforePredicate(firstDate);
assertEquals(firstPredicate, firstPredicateCopy);
// Different values -> not equals
assertNotEquals(firstPredicate, secondPredicate);
// Different types -> not equals
assertNotEquals(firstPredicate, firstDate);
assertNotEquals(firstPredicate, new AppointmentIsAfterPredicate(firstDate));
// Null -> not equals
assertNotEquals(firstDate, null);
}
@Test
public void test_nullKeywords_throwsException() {
assertThrows(NullPointerException.class, () -> new AppointmentIsBeforePredicate(null));
}
@Test
public void test_appointmentIsBefore_returnsTrue() {
LocalDate sampleDate = LocalDate.of(2021, 10, 20);
AppointmentIsBeforePredicate datePredicate = new AppointmentIsBeforePredicate(sampleDate);
// Appointment is on the same date as the filter end date -> returns true
assertTrue(datePredicate.test(new AppointmentBuilder().withDate("20/10/2021").build()));
// Appointment is on the same date as the filter end date and has start time 23:59 -> returns true
assertTrue(datePredicate.test(new AppointmentBuilder().withDate("20/10/2021")
.withSession("23:59", 16).build()));
// Appointment is on the previous day as compared to the filter end date -> returns true
assertTrue(datePredicate.test(new AppointmentBuilder().withDate("19/10/2021").build()));
}
@Test
public void test_appointmentIsNotBefore_returnsFalse() {
LocalDate sampleDate = LocalDate.of(2021, 10, 20);
AppointmentIsBeforePredicate datePredicate = new AppointmentIsBeforePredicate(sampleDate);
// Appointment is on the next day as compared to the filter end date -> returns true
assertFalse(datePredicate.test(new AppointmentBuilder().withDate("21/10/2021").build()));
assertFalse(datePredicate.test(new AppointmentBuilder().withDate("21/10/2021")
.withSession("00:00", 5).build()));
}
}
|
923af154daeef6b90c213fdf132ea3cf74b49c03 | 770 | java | Java | dmd-mall/src/main/java/com/dmd/mall/web/pms/PmsProductAttributeController.java | qhl0505/dmd | e9b3ca850d3f53cc56f0efba30ff3dde5c65138a | [
"Apache-2.0"
] | 2 | 2019-11-18T10:16:45.000Z | 2019-11-18T10:16:47.000Z | dmd-mall/src/main/java/com/dmd/mall/web/pms/PmsProductAttributeController.java | qhl0505/dmd | e9b3ca850d3f53cc56f0efba30ff3dde5c65138a | [
"Apache-2.0"
] | 1 | 2020-12-09T22:15:16.000Z | 2020-12-09T22:15:16.000Z | dmd-mall/src/main/java/com/dmd/mall/web/pms/PmsProductAttributeController.java | qhl0505/dmd | e9b3ca850d3f53cc56f0efba30ff3dde5c65138a | [
"Apache-2.0"
] | null | null | null | 24.83871 | 70 | 0.8 | 999,398 | package com.dmd.mall.web.pms;
import com.dmd.core.support.BaseController;
import com.dmd.mall.service.PmsProductAttributeService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 商品属性参数表 前端控制器
* </p>
*
* @author YangAnsheng
* @since 2019-10-10
*/
@RestController
@RequestMapping("/pmsProductAttribute")
@Api(value = "XXXX", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class PmsProductAttributeController extends BaseController {
@Autowired
private PmsProductAttributeService pmsProductAttributeService;
}
|
923af1c6d3c8b6e5732d2dd4a498b0ca19ca9a44 | 3,903 | java | Java | services/src/main/java/cz/nkp/urnnbn/services/impl/UrnNbnReservationServiceImpl.java | NLCR/CZIDLO | c830b6d4d5cfdf75c91f0937eea3470f2d23f5c9 | [
"PostgreSQL"
] | 3 | 2017-03-21T10:12:48.000Z | 2020-07-18T11:47:15.000Z | services/src/main/java/cz/nkp/urnnbn/services/impl/UrnNbnReservationServiceImpl.java | NLCR/CZIDLO | c830b6d4d5cfdf75c91f0937eea3470f2d23f5c9 | [
"PostgreSQL"
] | 117 | 2015-06-16T13:20:34.000Z | 2021-06-17T14:31:57.000Z | services/src/main/java/cz/nkp/urnnbn/services/impl/UrnNbnReservationServiceImpl.java | NLCR/CZIDLO | c830b6d4d5cfdf75c91f0937eea3470f2d23f5c9 | [
"PostgreSQL"
] | null | null | null | 36.476636 | 139 | 0.667948 | 999,399 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.nkp.urnnbn.services.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import cz.nkp.urnnbn.core.dto.Registrar;
import cz.nkp.urnnbn.core.dto.UrnNbn;
import cz.nkp.urnnbn.core.persistence.DatabaseConnector;
import cz.nkp.urnnbn.core.persistence.exceptions.AlreadyPresentException;
import cz.nkp.urnnbn.core.persistence.exceptions.DatabaseException;
import cz.nkp.urnnbn.core.persistence.exceptions.RecordNotFoundException;
import cz.nkp.urnnbn.services.UrnNbnReservationService;
import cz.nkp.urnnbn.services.exceptions.AccessException;
import cz.nkp.urnnbn.services.exceptions.UnknownRegistrarException;
import cz.nkp.urnnbn.services.exceptions.UnknownUserException;
/**
*
* @author Martin Řehánek
*/
public class UrnNbnReservationServiceImpl extends BusinessServiceImpl implements UrnNbnReservationService {
private static final Logger logger = Logger.getLogger(UrnNbnReservationService.class.getName());
private final int maxBatchSize;
public UrnNbnReservationServiceImpl(DatabaseConnector conn, int maxBatchSize) {
super(conn);
if (maxBatchSize <= 0) {
throw new IllegalArgumentException("maxBatchSize must be positive number");
}
this.maxBatchSize = maxBatchSize;
}
@Override
public List<UrnNbn> reserveUrnNbnBatch(int batchSize, Registrar registrar, String login) throws UnknownUserException, AccessException {
try {
authorization.checkAccessRights(registrar.getId(), login);
List<UrnNbn> result = new ArrayList<UrnNbn>(batchSize);
for (int i = 0; i < batchSize; i++) {
UrnNbn found = findAndSaveNewUrnNbn(registrar);
if (found != null) {
result.add(found);
}
}
return result;
} catch (DatabaseException ex) {
throw new RuntimeException(ex);
}
}
@Override
public List<UrnNbn> getReservedUrnNbnList(long registrarId) throws UnknownRegistrarException {
try {
return factory.urnReservedDao().getUrnNbnList(registrarId);
} catch (RecordNotFoundException ex) {
throw new UnknownRegistrarException(registrarId);
} catch (DatabaseException ex) {
throw new RuntimeException(ex);
}
}
@Override
public int getMaxBatchSize() {
return maxBatchSize;
}
@Override
public boolean isReserved(UrnNbn urn) {
try {
System.err.println("isReserved: " + urn);
factory.urnReservedDao().getUrn(urn.getRegistrarCode(), urn.getDocumentCode());
// when RecordNotFound is not thrown the urn:nbn is reserved
return true;
} catch (DatabaseException ex) {
throw new RuntimeException(ex);
} catch (RecordNotFoundException ex) {
System.err.println("NOT FOUND in RESERVED_URN_TABLE");
return false;
}
}
// POZOR: nekdy vraci null. jeste rozmyslet, jak se tady zachovat
// nejspis nakonec budou orm vyjimky nehlidane
private UrnNbn findAndSaveNewUrnNbn(Registrar registrar) throws DatabaseException {
UrnNbnFinder finder = new UrnNbnFinder(factory, registrar);
UrnNbn found = finder.findNewUrnNbn();
try {
factory.urnReservedDao().insertUrnNbn(found, registrar.getId());
return found;
} catch (AlreadyPresentException ex) {
// should never happend
logger.log(Level.SEVERE, null, ex);
return null;
} catch (RecordNotFoundException ex) {
// should never happen
logger.log(Level.SEVERE, null, ex);
return null;
}
}
}
|
923af24a9ef6e4dee466bb6627ee096c19945b26 | 9,907 | java | Java | pds/java/src/main/java/com/aliyun/pds/client/models/UpdateDomainRequest.java | baokeyu/alibabacloud-pds-sdk | 31b448754304043f300febb79e05d35e20014bd0 | [
"Apache-2.0"
] | null | null | null | pds/java/src/main/java/com/aliyun/pds/client/models/UpdateDomainRequest.java | baokeyu/alibabacloud-pds-sdk | 31b448754304043f300febb79e05d35e20014bd0 | [
"Apache-2.0"
] | null | null | null | pds/java/src/main/java/com/aliyun/pds/client/models/UpdateDomainRequest.java | baokeyu/alibabacloud-pds-sdk | 31b448754304043f300febb79e05d35e20014bd0 | [
"Apache-2.0"
] | null | null | null | 27.443213 | 108 | 0.6882 | 999,400 | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.pds.client.models;
import com.aliyun.tea.*;
/**
* update domain request
*/
public class UpdateDomainRequest extends TeaModel {
@NameInMap("auth_config")
public java.util.Map<String, ?> authConfig;
// 钉钉 App Id
@NameInMap("auth_dingding_app_id")
public String authDingdingAppId;
// 钉钉 App Secret
@NameInMap("auth_dingding_app_secret")
public String authDingdingAppSecret;
// 启用钉钉认证
@NameInMap("auth_dingding_enable")
public Boolean authDingdingEnable;
// RAM App Id
@NameInMap("auth_ram_app_id")
public String authRamAppId;
// RAM App Secret
@NameInMap("auth_ram_app_secret")
public String authRamAppSecret;
// 启用 RAM 认证
@NameInMap("auth_ram_enable")
public Boolean authRamEnable;
@NameInMap("custom_benefits")
public java.util.Map<String, ?> customBenefits;
// 数据 Hash 算法
@NameInMap("data_hash_name")
public String dataHashName;
// Domain 描述
@NameInMap("description")
public String description;
// Domain ID
@NameInMap("domain_id")
@Validation(required = true)
public String domainId;
// Domain 名称
@NameInMap("domain_name")
public String domainName;
// 事件通知 MNS 匹配文件名
@NameInMap("event_filename_matches")
public String eventFilenameMatches;
// 事件通知 MNS Endpoint
@NameInMap("event_mns_endpoint")
public String eventMnsEndpoint;
// 事件通知 MNS Topic
@NameInMap("event_mns_topic")
public String eventMnsTopic;
// 事件名列表
@NameInMap("event_names")
public java.util.List<String> eventNames;
// 事件通知 Role Arn
@NameInMap("event_role_arn")
public String eventRoleArn;
@NameInMap("get_benefit")
public Boolean getBenefit;
// 单团队单drive
@NameInMap("group_single_drive_enabled")
public Boolean groupSingleDriveEnabled;
// 开启自动初始化 Drive
@NameInMap("init_drive_enable")
public Boolean initDriveEnable;
// 自动初始化 Drive 大小
@NameInMap("init_drive_size")
public Long initDriveSize;
// 自动初始化 Drive 使用 Store ID
@NameInMap("init_drive_store_id")
public String initDriveStoreId;
@NameInMap("published_app_access_strategy")
public AppAccessStrategy publishedAppAccessStrategy;
// 开启分享
@NameInMap("sharable")
public Boolean sharable;
// 逻辑空间quota,默认为-1,无限制,单位为字节
@NameInMap("size_quota")
public Long sizeQuota;
// 状态
@NameInMap("status")
public Long status;
// 逻辑空间刷新周期,单位:秒
@NameInMap("used_size_refresh_interval")
public Long usedSizeRefreshInterval;
// 用户数quota,默认为-1,无限制
@NameInMap("user_count_quota")
public Long userCountQuota;
// 单用户单drive
@NameInMap("user_single_drive_enabled")
public Boolean userSingleDriveEnabled;
public static UpdateDomainRequest build(java.util.Map<String, ?> map) throws Exception {
UpdateDomainRequest self = new UpdateDomainRequest();
return TeaModel.build(map, self);
}
public UpdateDomainRequest setAuthConfig(java.util.Map<String, ?> authConfig) {
this.authConfig = authConfig;
return this;
}
public java.util.Map<String, ?> getAuthConfig() {
return this.authConfig;
}
public UpdateDomainRequest setAuthDingdingAppId(String authDingdingAppId) {
this.authDingdingAppId = authDingdingAppId;
return this;
}
public String getAuthDingdingAppId() {
return this.authDingdingAppId;
}
public UpdateDomainRequest setAuthDingdingAppSecret(String authDingdingAppSecret) {
this.authDingdingAppSecret = authDingdingAppSecret;
return this;
}
public String getAuthDingdingAppSecret() {
return this.authDingdingAppSecret;
}
public UpdateDomainRequest setAuthDingdingEnable(Boolean authDingdingEnable) {
this.authDingdingEnable = authDingdingEnable;
return this;
}
public Boolean getAuthDingdingEnable() {
return this.authDingdingEnable;
}
public UpdateDomainRequest setAuthRamAppId(String authRamAppId) {
this.authRamAppId = authRamAppId;
return this;
}
public String getAuthRamAppId() {
return this.authRamAppId;
}
public UpdateDomainRequest setAuthRamAppSecret(String authRamAppSecret) {
this.authRamAppSecret = authRamAppSecret;
return this;
}
public String getAuthRamAppSecret() {
return this.authRamAppSecret;
}
public UpdateDomainRequest setAuthRamEnable(Boolean authRamEnable) {
this.authRamEnable = authRamEnable;
return this;
}
public Boolean getAuthRamEnable() {
return this.authRamEnable;
}
public UpdateDomainRequest setCustomBenefits(java.util.Map<String, ?> customBenefits) {
this.customBenefits = customBenefits;
return this;
}
public java.util.Map<String, ?> getCustomBenefits() {
return this.customBenefits;
}
public UpdateDomainRequest setDataHashName(String dataHashName) {
this.dataHashName = dataHashName;
return this;
}
public String getDataHashName() {
return this.dataHashName;
}
public UpdateDomainRequest setDescription(String description) {
this.description = description;
return this;
}
public String getDescription() {
return this.description;
}
public UpdateDomainRequest setDomainId(String domainId) {
this.domainId = domainId;
return this;
}
public String getDomainId() {
return this.domainId;
}
public UpdateDomainRequest setDomainName(String domainName) {
this.domainName = domainName;
return this;
}
public String getDomainName() {
return this.domainName;
}
public UpdateDomainRequest setEventFilenameMatches(String eventFilenameMatches) {
this.eventFilenameMatches = eventFilenameMatches;
return this;
}
public String getEventFilenameMatches() {
return this.eventFilenameMatches;
}
public UpdateDomainRequest setEventMnsEndpoint(String eventMnsEndpoint) {
this.eventMnsEndpoint = eventMnsEndpoint;
return this;
}
public String getEventMnsEndpoint() {
return this.eventMnsEndpoint;
}
public UpdateDomainRequest setEventMnsTopic(String eventMnsTopic) {
this.eventMnsTopic = eventMnsTopic;
return this;
}
public String getEventMnsTopic() {
return this.eventMnsTopic;
}
public UpdateDomainRequest setEventNames(java.util.List<String> eventNames) {
this.eventNames = eventNames;
return this;
}
public java.util.List<String> getEventNames() {
return this.eventNames;
}
public UpdateDomainRequest setEventRoleArn(String eventRoleArn) {
this.eventRoleArn = eventRoleArn;
return this;
}
public String getEventRoleArn() {
return this.eventRoleArn;
}
public UpdateDomainRequest setGetBenefit(Boolean getBenefit) {
this.getBenefit = getBenefit;
return this;
}
public Boolean getGetBenefit() {
return this.getBenefit;
}
public UpdateDomainRequest setGroupSingleDriveEnabled(Boolean groupSingleDriveEnabled) {
this.groupSingleDriveEnabled = groupSingleDriveEnabled;
return this;
}
public Boolean getGroupSingleDriveEnabled() {
return this.groupSingleDriveEnabled;
}
public UpdateDomainRequest setInitDriveEnable(Boolean initDriveEnable) {
this.initDriveEnable = initDriveEnable;
return this;
}
public Boolean getInitDriveEnable() {
return this.initDriveEnable;
}
public UpdateDomainRequest setInitDriveSize(Long initDriveSize) {
this.initDriveSize = initDriveSize;
return this;
}
public Long getInitDriveSize() {
return this.initDriveSize;
}
public UpdateDomainRequest setInitDriveStoreId(String initDriveStoreId) {
this.initDriveStoreId = initDriveStoreId;
return this;
}
public String getInitDriveStoreId() {
return this.initDriveStoreId;
}
public UpdateDomainRequest setPublishedAppAccessStrategy(AppAccessStrategy publishedAppAccessStrategy) {
this.publishedAppAccessStrategy = publishedAppAccessStrategy;
return this;
}
public AppAccessStrategy getPublishedAppAccessStrategy() {
return this.publishedAppAccessStrategy;
}
public UpdateDomainRequest setSharable(Boolean sharable) {
this.sharable = sharable;
return this;
}
public Boolean getSharable() {
return this.sharable;
}
public UpdateDomainRequest setSizeQuota(Long sizeQuota) {
this.sizeQuota = sizeQuota;
return this;
}
public Long getSizeQuota() {
return this.sizeQuota;
}
public UpdateDomainRequest setStatus(Long status) {
this.status = status;
return this;
}
public Long getStatus() {
return this.status;
}
public UpdateDomainRequest setUsedSizeRefreshInterval(Long usedSizeRefreshInterval) {
this.usedSizeRefreshInterval = usedSizeRefreshInterval;
return this;
}
public Long getUsedSizeRefreshInterval() {
return this.usedSizeRefreshInterval;
}
public UpdateDomainRequest setUserCountQuota(Long userCountQuota) {
this.userCountQuota = userCountQuota;
return this;
}
public Long getUserCountQuota() {
return this.userCountQuota;
}
public UpdateDomainRequest setUserSingleDriveEnabled(Boolean userSingleDriveEnabled) {
this.userSingleDriveEnabled = userSingleDriveEnabled;
return this;
}
public Boolean getUserSingleDriveEnabled() {
return this.userSingleDriveEnabled;
}
}
|
923af29236ec49375f606945cc7b5bcf8e063ed6 | 6,120 | java | Java | src/main/java/org/grouplens/grapht/solver/BindRuleBuilder.java | AutoscanForJava/org.grouplens.grapht-grapht | f6a5d21014ed05413ec811621fdd815feb053d7a | [
"MIT"
] | 21 | 2015-03-17T21:01:57.000Z | 2022-03-13T06:02:29.000Z | src/main/java/org/grouplens/grapht/solver/BindRuleBuilder.java | AutoscanForJava/org.grouplens.grapht-grapht | f6a5d21014ed05413ec811621fdd815feb053d7a | [
"MIT"
] | 39 | 2015-02-04T16:12:16.000Z | 2021-06-07T23:02:47.000Z | src/main/java/org/grouplens/grapht/solver/BindRuleBuilder.java | AutoscanForJava/org.grouplens.grapht-grapht | f6a5d21014ed05413ec811621fdd815feb053d7a | [
"MIT"
] | 13 | 2015-02-05T06:27:06.000Z | 2022-02-11T18:04:54.000Z | 30.753769 | 137 | 0.662255 | 999,401 | /*
* Grapht, an open source dependency injector.
* Copyright 2014-2017 various contributors (see CONTRIBUTORS.txt)
* Copyright 2010-2014 Regents of the University of Minnesota
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.grouplens.grapht.solver;
import com.google.common.base.Preconditions;
import org.grouplens.grapht.CachePolicy;
import org.grouplens.grapht.reflect.QualifierMatcher;
import org.grouplens.grapht.reflect.Qualifiers;
import org.grouplens.grapht.reflect.Satisfaction;
import java.util.EnumSet;
/**
* Builder for bind rules.
*
* @since 0.7
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class BindRuleBuilder {
private Class<?> dependencyType;
private QualifierMatcher qualifierMatcher = Qualifiers.matchAny();
private Satisfaction satisfaction;
private Class<?> implementation;
private CachePolicy cachePolicy = CachePolicy.NO_PREFERENCE;
private EnumSet<BindingFlag> flags = BindingFlag.emptySet();
public static BindRuleBuilder create() {
return new BindRuleBuilder();
}
/**
* Get the dependency type to match.
* @return The dependency type to match.
*/
public Class<?> getDependencyType() {
return dependencyType;
}
/**
* Set the dependency type to match.
* @param type The dependency type to match.
*/
public BindRuleBuilder setDependencyType(Class<?> type) {
dependencyType = type;
return this;
}
/**
* Get the configured qualifer matcher. The initial qualifier matcher is {@link org.grouplens.grapht.reflect.Qualifiers#matchAny()}.
* @return The qualifier matcher.
*/
public QualifierMatcher getQualifierMatcher() {
return qualifierMatcher;
}
/**
* Set the qualifier matcher.
* @param qm The qualifier matcher.
*/
public BindRuleBuilder setQualifierMatcher(QualifierMatcher qm) {
qualifierMatcher = qm;
return this;
}
/**
* Get the target satisfaction.
* @return The configured satisfaction, or {@code null} if none is configured.
*/
public Satisfaction getSatisfaction() {
return satisfaction;
}
/**
* Set the satisfaction to bind to. This will unset the implementation class and result in
* a satisfaction binding.
*
* @param sat The satisfaction.
*/
public BindRuleBuilder setSatisfaction(Satisfaction sat) {
satisfaction = sat;
return this;
}
/**
* Get the target implementation.
* @return The target implementation, or {@code null} if none is configured.
*/
public Class<?> getImplementation() {
return implementation;
}
/**
* Set the target implementation. This will unset the satisfaction and result in an implementation
* class binding.
*
* @param type The implementation class.
*/
public BindRuleBuilder setImplementation(Class<?> type) {
implementation = type;
return this;
}
/**
* Query whether the binding will be terminal.
* @return {@code true} if the binding will be terminal.
*/
public boolean isTerminal() {
return flags.contains(BindingFlag.TERMINAL);
}
/**
* Set whether the binding will be terminal.
*
* @param term {@code true} to create a terminal binding.
* @see BindingFlag#TERMINAL
*/
public BindRuleBuilder setTerminal(boolean term) {
if (term) {
flags.add(BindingFlag.TERMINAL);
} else {
flags.remove(BindingFlag.TERMINAL);
}
return this;
}
/**
* Set the flags on this bind rule.
* @param fs The flags.
* @return The builder (for chaining).
*/
public BindRuleBuilder setFlags(EnumSet<BindingFlag> fs) {
flags = fs.clone();
return this;
}
/**
* Add a flag to the constructed bind rule.
* @param flag The flag to add.
* @return The builder (for chaining).
*/
public BindRuleBuilder addFlag(BindingFlag flag) {
flags.add(flag);
return this;
}
/**
* Get the cache policy.
* @return The cache policy.
*/
public CachePolicy getCachePolicy() {
return cachePolicy;
}
/**
* Set the cache policy.
* @param policy The cache policy.
*/
public BindRuleBuilder setCachePolicy(CachePolicy policy) {
cachePolicy = policy;
return this;
}
public BindRule build() {
Preconditions.checkState(dependencyType != null, "no dependency type specified");
if (implementation != null) {
assert satisfaction == null;
return new BindRuleImpl(dependencyType, implementation, cachePolicy, qualifierMatcher, flags);
} else if (satisfaction != null) {
return new BindRuleImpl(dependencyType, satisfaction, cachePolicy, qualifierMatcher, flags);
} else {
throw new IllegalStateException("no binding target specified");
}
}
}
|
923af2de2aeed37e42214a707135adf9d548e33e | 4,382 | java | Java | providers/softlayer/src/test/java/org/jclouds/softlayer/features/DatacenterApiLiveTest.java | mhurne/jclouds | a2ee7341e3b3569d6ba1f0bdb7b3517fff7bb2f6 | [
"Apache-1.1"
] | null | null | null | providers/softlayer/src/test/java/org/jclouds/softlayer/features/DatacenterApiLiveTest.java | mhurne/jclouds | a2ee7341e3b3569d6ba1f0bdb7b3517fff7bb2f6 | [
"Apache-1.1"
] | 1 | 2021-06-23T21:11:21.000Z | 2021-06-23T21:11:21.000Z | providers/softlayer/src/test/java/org/jclouds/softlayer/features/DatacenterApiLiveTest.java | mhurne/jclouds | a2ee7341e3b3569d6ba1f0bdb7b3517fff7bb2f6 | [
"Apache-1.1"
] | 1 | 2015-10-19T11:26:42.000Z | 2015-10-19T11:26:42.000Z | 42.960784 | 101 | 0.701734 | 999,402 | /*
* 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.softlayer.features;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
import org.jclouds.softlayer.domain.Address;
import org.jclouds.softlayer.domain.Datacenter;
import org.jclouds.softlayer.domain.Region;
import org.testng.annotations.Test;
import java.util.Set;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
/**
* Tests behavior of {@code DatacenterApi}
*/
@Test(groups = "live")
public class DatacenterApiLiveTest extends BaseSoftLayerApiLiveTest {
@Test
public void testListDatacenters() {
Set<Datacenter> response = api().listDatacenters();
assertNotNull(response);
assertTrue(response.size() >= 0);
for (Datacenter vg : response) {
Datacenter newDetails = api().getDatacenter(vg.getId());
assertEquals(vg.getId(), newDetails.getId());
checkDatacenter(newDetails);
}
}
@Test
public void testListDatacentersContent() {
Builder<Datacenter> builder = ImmutableSet.builder();
builder.add(Datacenter.builder().id(265592).name("ams01").longName("Amsterdam 1").build());
builder.add(Datacenter.builder().id(358698).name("wdc03").longName("Ashburn, VA 3").build());
builder.add(Datacenter.builder().id(3).name("dal01").longName("Dallas").build());
builder.add(Datacenter.builder().id(154770).name("dal02").longName("Dallas 2").build());
builder.add(Datacenter.builder().id(167092).name("dal04").longName("Dallas 4").build());
builder.add(Datacenter.builder().id(138124).name("dal05").longName("Dallas 5").build());
builder.add(Datacenter.builder().id(154820).name("dal06").longName("Dallas 6").build());
builder.add(Datacenter.builder().id(142776).name("dal07").longName("Dallas 7").build());
builder.add(Datacenter.builder().id(352494).name("hkg02").longName("Hong Kong 2").build());
builder.add(Datacenter.builder().id(142775).name("hou02").longName("Houston 2").build());
builder.add(Datacenter.builder().id(358694).name("lon02").longName("London 2").build());
builder.add(Datacenter.builder().id(18171).name("sea01").longName("Seattle").build());
builder.add(Datacenter.builder().id(168642).name("sjc01").longName("San Jose 1").build());
builder.add(Datacenter.builder().id(224092).name("sng01").longName("Singapore 1").build());
builder.add(Datacenter.builder().id(448994).name("tor01").longName("Toronto 1").build());
builder.add(Datacenter.builder().id(37473).name("wdc01").longName("Washington, DC 1").build());
Set<Datacenter> response = api().listDatacenters();
Set<Datacenter> expected = builder.build();
assertEquals(response.size(), expected.size());
for (Datacenter datacenter : response) {
Address address = datacenter.getLocationAddress();
if (address != null) checkAddress(address);
}
}
private DatacenterApi api() {
return api.getDatacenterApi();
}
private void checkDatacenter(Datacenter dc) {
assertNotNull(dc.getId());
assertNotNull(dc.getName());
assertNotNull(dc.getLongName());
for (Region region : dc.getRegions()) checkRegion(region);
}
private void checkRegion(Region region) {
assertNotNull(region.getDescription());
assertNotNull(region.getKeyname());
}
private void checkAddress(Address address) {
assertNotNull(address.getId());
assertNotNull(address.getCountry());
}
}
|
923af4909bb5042293bb68d97e3156a52b72a852 | 452 | java | Java | src/main/java/com/rjh/web/RepeatReadStreamDemoApplication.java | spring-based-solutions/repeat-read-stream-demo | 516930b2e3560aed381178d500a3d6a1a72c4ff1 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/rjh/web/RepeatReadStreamDemoApplication.java | spring-based-solutions/repeat-read-stream-demo | 516930b2e3560aed381178d500a3d6a1a72c4ff1 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/rjh/web/RepeatReadStreamDemoApplication.java | spring-based-solutions/repeat-read-stream-demo | 516930b2e3560aed381178d500a3d6a1a72c4ff1 | [
"BSD-3-Clause"
] | null | null | null | 28.25 | 75 | 0.818584 | 999,403 | package com.rjh.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan // 开启Servlet原生的组件扫描
@SpringBootApplication
public class RepeatReadStreamDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RepeatReadStreamDemoApplication.class, args);
}
}
|
923af4f3635864708c315bc9c9f13718f7479b17 | 4,349 | java | Java | blazingcache-jcache/src/test/java/blazingcache/jcache/StoreByReferenceSimpleTest.java | aluccaroni/blazingcache | b73f4e5ffbd3cafad2d35b70257c93fd2eda5f95 | [
"Apache-2.0"
] | 27 | 2016-05-13T14:53:15.000Z | 2022-02-24T06:43:42.000Z | blazingcache-jcache/src/test/java/blazingcache/jcache/StoreByReferenceSimpleTest.java | aluccaroni/blazingcache | b73f4e5ffbd3cafad2d35b70257c93fd2eda5f95 | [
"Apache-2.0"
] | 96 | 2016-04-12T13:31:38.000Z | 2022-03-15T08:30:19.000Z | blazingcache-jcache/src/test/java/blazingcache/jcache/StoreByReferenceSimpleTest.java | aluccaroni/blazingcache | b73f4e5ffbd3cafad2d35b70257c93fd2eda5f95 | [
"Apache-2.0"
] | 15 | 2016-08-02T16:43:24.000Z | 2022-02-24T06:43:49.000Z | 38.486726 | 152 | 0.66774 | 999,404 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 blazingcache.jcache;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.AccessedExpiryPolicy;
import static javax.cache.expiry.Duration.ONE_HOUR;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.MutableEntry;
import javax.cache.spi.CachingProvider;
import org.junit.Test;
import static org.junit.Assert.assertSame;
/**
* Test storeByReference
*
* @author enrico.olivelli
*/
public class StoreByReferenceSimpleTest {
public static class MyBean implements Serializable {
public String name;
public MyBean(String name) {
this.name = name;
}
}
@Test
public void testStoreByReference() {
CachingProvider cachingProvider = Caching.getCachingProvider();
Properties p = new Properties();
try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
MutableConfiguration<String, MyBean> config
= new MutableConfiguration<String, MyBean>()
.setTypes(String.class, MyBean.class)
.setStoreByValue(false)
.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR))
.setStatisticsEnabled(true);
Cache<String, MyBean> cache = cacheManager.createCache("simpleCache", config);
MyBean bean1 = new MyBean("foo");
cache.put("foo", bean1);
assertSame(bean1, cache.get("foo"));
MyBean bean_one = new MyBean("one");
MyBean bean_two = new MyBean("two");
Map<String, MyBean> all = new HashMap<>();
all.put("one", bean_one);
all.put("two", bean_two);
cache.putAll(all);
Map<String, MyBean> result = cache.getAll(new HashSet<>(Arrays.asList("one", "two")));
assertSame(bean_one, cache.get("one"));
assertSame(bean_two, cache.get("two"));
assertSame(bean_one, result.get("one"));
assertSame(bean_two, result.get("two"));
AtomicReference<MyBean> result_in_invoke = new AtomicReference<>();
cache.invoke("one", new EntryProcessor<String, StoreByReferenceSimpleTest.MyBean, Object>() {
@Override
public Object process(MutableEntry<String, MyBean> entry, Object... arguments) throws EntryProcessorException {
result_in_invoke.set(entry.getValue());
return null;
}
});
assertSame(bean_one, result_in_invoke.get());
AtomicReference<MyBean> result_in_invoke_all = new AtomicReference<>();
cache.invokeAll(new HashSet<>(Arrays.asList("one")), new EntryProcessor<String, StoreByReferenceSimpleTest.MyBean, Object>() {
@Override
public Object process(MutableEntry<String, MyBean> entry, Object... arguments) throws EntryProcessorException {
result_in_invoke_all.set(entry.getValue());
return null;
}
});
assertSame(bean_one, result_in_invoke.get());
}
}
}
|
923af690ec500944fbd22476d29ad44da73e6f29 | 297 | java | Java | FY_Java9_JavaSE/src/day10/interfaceDemo/TestInterface.java | MYHUNBT/JavaSECode | b1884a0e0428b44b7c05f17273db94dfa3197003 | [
"Apache-2.0"
] | 1 | 2020-08-13T00:43:25.000Z | 2020-08-13T00:43:25.000Z | FY_Java9_JavaSE/src/day10/interfaceDemo/TestInterface.java | MYHUNBT/JavaSECode | b1884a0e0428b44b7c05f17273db94dfa3197003 | [
"Apache-2.0"
] | null | null | null | FY_Java9_JavaSE/src/day10/interfaceDemo/TestInterface.java | MYHUNBT/JavaSECode | b1884a0e0428b44b7c05f17273db94dfa3197003 | [
"Apache-2.0"
] | null | null | null | 17.470588 | 44 | 0.572391 | 999,405 | package day10.interfaceDemo;
/**
* @author liuboting
* @date 2020/7/24 14:36
*/
public class TestInterface {
public static void main(String[] args) {
Animal animal = new Animal();
animal.eat();
animal.sleep();
animal.fly();
LiveAble.run();
}
}
|
923af758b1d2e33ab8a99a9eb6930901120d0292 | 4,679 | java | Java | visualization/src/main/java/de/hshannover/f4/trust/metalyzer/gui/characteristics/MacAddressPanel.java | trustathsh/metalyzer | 7bffdba7030e94ebcbe50d8a9c75db2b86af609b | [
"Apache-2.0"
] | null | null | null | visualization/src/main/java/de/hshannover/f4/trust/metalyzer/gui/characteristics/MacAddressPanel.java | trustathsh/metalyzer | 7bffdba7030e94ebcbe50d8a9c75db2b86af609b | [
"Apache-2.0"
] | null | null | null | visualization/src/main/java/de/hshannover/f4/trust/metalyzer/gui/characteristics/MacAddressPanel.java | trustathsh/metalyzer | 7bffdba7030e94ebcbe50d8a9c75db2b86af609b | [
"Apache-2.0"
] | null | null | null | 31.246667 | 75 | 0.662684 | 999,406 | /*
* #%L
* =====================================================
* _____ _ ____ _ _ _ _
* |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | |
* | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| |
* | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ |
* |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_|
* \____/
*
* =====================================================
*
* Hochschule Hannover
* (University of Applied Sciences and Arts, Hannover)
* Faculty IV, Dept. of Computer Science
* Ricklinger Stadtweg 118, 30459 Hannover, Germany
*
* Email: ychag@example.com
* Website: http://trust.f4.hs-hannover.de/
*
* This file is part of metalyzer-visualization, version 0.1.1,
* implemented by the Trust@HsH research group at the Hochschule Hannover.
* %%
* Copyright (C) 2013 - 2016 Trust@HsH
* %%
* 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.
* #L%
*/
package de.hshannover.f4.trust.metalyzer.gui.characteristics;
import java.util.ArrayList;
import de.hshannover.f4.trust.metalyzer.gui.MetalyzerGuiController;
import de.hshannover.f4.trust.metalyzer.gui.labels.CharacteristicLabels;
import de.hshannover.f4.trust.metalyzer.semantic.entities.MacAddress;
/**
* @author Anton Zaiser
*
*/
public class MacAddressPanel extends SemanticPanel {
private static final long serialVersionUID = 1L;
private ArrayList<MacAddress> mMacAddresses;
public MacAddressPanel(MetalyzerGuiController guiController,
String characteristic) {
super(guiController, characteristic);
if (characteristic.equals(CharacteristicLabels.MAC_USER)) {
super.setComboBoxLabel("MacAddresses: ");
mLabelView.addLabel("MacUser", "Count of Users:", 0);
} else if (characteristic.equals(CharacteristicLabels.MAC_IP)) {
super.setComboBoxLabel("MacAddresses: ");
mLabelView.addLabel("MacIp", "Count of IpAddresses:", 0);
} else if (characteristic.equals(CharacteristicLabels.MAC_DEVICES)) {
super.setComboBoxLabel("MacAddresses: ");
mLabelView.addLabel("MacDev", "Count of Devices:", 0);
} else if (characteristic.equals(CharacteristicLabels.MAC_ALL)) {
super.setComboBoxLabel("MacAddresses: ");
mLabelView.addLabel("MacUser", "Count of Users:", 0);
mLabelView.addLabel("MacIp", "Count of IpAddresses:", 0);
mLabelView.addLabel("MacDev", "Count of Devices:", 0);
} else if (characteristic.equals(CharacteristicLabels.MAC_AUTH)) {
super.setComboBoxLabel("Timestamp: ");
this.getTimeSelectionView().hideTimeSelectors();
}
}
/**
* Sets the count of user of a macaddress
*
* @param ipAddressCount
* the count of user of a macaddress
* */
public void setCountOfUsers(int userCount) {
mLabelView.setValueById("MacUser", userCount);
}
/**
* Sets the count of ipaddress of a macaddress
*
* @param ipAddressCount
* the count of ipaddress of a macaddress
* */
public void setCountOfIpAddresses(int ipAddressCount) {
mLabelView.setValueById("MacIp", ipAddressCount);
}
/**
* Sets the count of devices of a macaddress
*
* @param ipAddressCount
* the count of devices of a macaddress
* */
public void setCountOfDevices(int devCount) {
mLabelView.setValueById("MacDev", devCount);
}
/**
* Sets an ArrayList of all macAddresses
*
* @param macAddresses
*/
public void setMacAddresses(ArrayList<MacAddress> macAddresses) {
mMacAddresses = macAddresses;
}
/**
* Fills a {@link ComboBox} with an {@link ArrayList} of macAddresses
*
* @param macAddresses
* ArrayList of macAddresses
*/
public void setMacAddressItems(ArrayList<MacAddress> macAddresses) {
mComboBoxView.clear();
for (MacAddress mac : macAddresses) {
if (!mComboBoxView.containsItem(mac.getAddress())) {
mComboBoxView.addItem(mac.getAddress());
}
}
}
/**
* @return An {@link ArrayList} which contains all macAddresses
*/
public MacAddress getMac(String macAddress) {
if (mMacAddresses == null) {
return null;
}
for (MacAddress mac : mMacAddresses) {
if (mac.getAddress().equals(macAddress)) {
return mac;
}
}
return null;
}
}
|
923af90cdd89b6be908276fa2e9ee216cb964c05 | 2,930 | java | Java | Mage.Sets/src/mage/cards/m/MissDemeanor.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/m/MissDemeanor.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/m/MissDemeanor.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 33.295455 | 149 | 0.691809 | 999,407 |
package mage.cards.m;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.BeginningOfUpkeepTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.keyword.FirstStrikeAbility;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.constants.TargetController;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
/**
*
* @author Ketsuban
*/
public final class MissDemeanor extends CardImpl {
public MissDemeanor(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{W}");
this.subtype.add(SubType.LADYOFPROPERETIQUETTE);
this.power = new MageInt(3);
this.toughness = new MageInt(1);
// Flying
this.addAbility(FlyingAbility.getInstance());
// First strike
this.addAbility(FirstStrikeAbility.getInstance());
// At the beginning of each other player's upkeep, you may compliment that player on their game play. If you don't, sacrifice Miss Demeanour.
this.addAbility(new BeginningOfUpkeepTriggeredAbility(Zone.BATTLEFIELD, new MissDemeanorEffect(), TargetController.NOT_YOU, false, true));
}
private MissDemeanor(final MissDemeanor card) {
super(card);
}
@Override
public MissDemeanor copy() {
return new MissDemeanor(this);
}
}
class MissDemeanorEffect extends OneShotEffect {
public MissDemeanorEffect() {
super(Outcome.Sacrifice);
this.staticText = "you may compliment that player on their game play. If you don't, sacrifice {this}";
}
public MissDemeanorEffect(final MissDemeanorEffect effect) {
super(effect);
}
@Override
public MissDemeanorEffect copy() {
return new MissDemeanorEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
Permanent sourceObject = (Permanent) source.getSourceObjectIfItStillExists(game);
String activePlayerName = game.getPlayer(game.getActivePlayerId()).getName();
if (sourceObject != null) {
if (controller.chooseUse(outcome, "Compliment " + activePlayerName + " on their game play?", source, game)) {
// TODO(Ketsuban): this could probably stand to be randomly chosen from a pool of compliments
game.informPlayers(controller.getLogName() + ": That's a well-built deck and you pilot it well, " + activePlayerName + ".");
} else {
sourceObject.sacrifice(source, game);
}
return true;
}
return false;
}
}
|
923af98062557f5bc34e547a7578d0543c8aa578 | 3,120 | java | Java | app/src/main/java/com/akuwalink/ball/ui/mainview/CircleView.java | akuwalink/3DBall | 4dfb1414b9b90c06a1b73778c9b89c39cfb06fdc | [
"Apache-2.0"
] | 1 | 2021-02-15T02:57:07.000Z | 2021-02-15T02:57:07.000Z | app/src/main/java/com/akuwalink/ball/ui/mainview/CircleView.java | akuwalink/3DBall | 4dfb1414b9b90c06a1b73778c9b89c39cfb06fdc | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/akuwalink/ball/ui/mainview/CircleView.java | akuwalink/3DBall | 4dfb1414b9b90c06a1b73778c9b89c39cfb06fdc | [
"Apache-2.0"
] | null | null | null | 32.5 | 105 | 0.702244 | 999,408 | package com.akuwalink.ball.ui.mainview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import com.akuwalink.ball.R;
public class CircleView extends View {
Paint paint;
Paint edge_paint;
private int resId;
private int edge_color;
private float scale_x;
private float scale_y;
private Matrix matrix;
public CircleView(Context context) {
super(context);
init();
}
public CircleView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
init();
}
public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.CircleView);
resId=array.getResourceId(R.styleable.CircleView_background,R.drawable.main_headimage);
edge_color=array.getColor(R.styleable.CircleView_edge_color,Color.BLACK);
init();
}
public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
public void init(){
paint=new Paint();
edge_paint=new Paint();
edge_paint.setAntiAlias(true);
edge_paint.setColor(edge_color);
edge_paint.setStrokeWidth(20);
edge_paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);
matrix=new Matrix();
}
public void setResId(int res){
resId=res;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int paddingLeft=getPaddingLeft();
int paddingRight=getPaddingRight();
int paddingBottom=getPaddingBottom();
int paddingTop=getPaddingTop();
int width=getWidth()-paddingLeft;
int height=getHeight()-paddingBottom;
float center_w=getWidth();
float center_h=getHeight();
Drawable drawable= getResources().getDrawable(resId,null);
Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();
if(bitmap==null) return;
float min_view=Math.min(width,height);
float radius=min_view/2;
float c_min_view=Math.min(center_w,center_h)/2;
matrix.setScale(center_w/bitmap.getWidth(),center_h/bitmap.getHeight());
BitmapShader shader=new BitmapShader(bitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
shader.setLocalMatrix(matrix);
paint.setShader(shader);
canvas.drawCircle(c_min_view,c_min_view,radius,edge_paint);
canvas.drawCircle(c_min_view,c_min_view,radius,paint);
}
}
|
923af9fafd6d35795cf5b0094ac519c76450bd8b | 661 | java | Java | addressbook-web-tests/src/test/java/ua/stqa/pft/addressbook/AppManager/NavigationHelper.java | ShemiakinYevhen/java_prac | d858894973d5e05fa1fee532292cf133176bd00c | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ua/stqa/pft/addressbook/AppManager/NavigationHelper.java | ShemiakinYevhen/java_prac | d858894973d5e05fa1fee532292cf133176bd00c | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ua/stqa/pft/addressbook/AppManager/NavigationHelper.java | ShemiakinYevhen/java_prac | d858894973d5e05fa1fee532292cf133176bd00c | [
"Apache-2.0"
] | null | null | null | 25.423077 | 149 | 0.585477 | 999,409 | package ua.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 group() {
if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Groups") && isElementPresent(By.name("new"))) {
return;
}
click(By.linkText("groups"));
}
public void home() {
if (isElementPresent(By.id("maintable"))) {
return;
}
click(By.linkText("home"));
}
}
|
923afa41171f40ab46896a05d77d5729efb20c80 | 1,088 | java | Java | linkis-commons/linkis-message-scheduler/src/test/java/org/apache/linkis/message/ImplicitObject.java | poenr/incubator-linkis | d4a92b3f546933b7c6364b52c15daf856cab5f54 | [
"Apache-2.0"
] | 1 | 2022-01-06T03:18:05.000Z | 2022-01-06T03:18:05.000Z | linkis-commons/linkis-message-scheduler/src/test/java/org/apache/linkis/message/ImplicitObject.java | poenr/incubator-linkis | d4a92b3f546933b7c6364b52c15daf856cab5f54 | [
"Apache-2.0"
] | 2 | 2022-03-08T07:25:23.000Z | 2022-03-08T08:18:44.000Z | linkis-commons/linkis-message-scheduler/src/test/java/org/apache/linkis/message/ImplicitObject.java | poenr/incubator-linkis | d4a92b3f546933b7c6364b52c15daf856cab5f54 | [
"Apache-2.0"
] | 2 | 2021-12-29T15:34:03.000Z | 2021-12-30T02:08:32.000Z | 34 | 91 | 0.75 | 999,410 | /*
* 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.linkis.message;
import org.apache.linkis.message.annotation.Implicit;
/**
* @date 2020/7/29
*/
public class ImplicitObject {
@Implicit
public ImplicitInterfaceImpl implicitMethod02(DefaultRequestProtocol requestProtocol) {
return null;
}
}
|
923afabac11bb0b370d4b10226bc3812cd691ffc | 4,018 | java | Java | PopPicture/app/src/main/java/leonardolana/poppicture/about/AboutActivity.java | leonardodlana/pop-picture | 0cafdc6d293a4cc3302aab6a24875a254795b245 | [
"Apache-2.0"
] | 2 | 2018-12-06T19:32:44.000Z | 2018-12-19T09:58:50.000Z | PopPicture/app/src/main/java/leonardolana/poppicture/about/AboutActivity.java | leonardodlana/pop-picture | 0cafdc6d293a4cc3302aab6a24875a254795b245 | [
"Apache-2.0"
] | null | null | null | PopPicture/app/src/main/java/leonardolana/poppicture/about/AboutActivity.java | leonardodlana/pop-picture | 0cafdc6d293a4cc3302aab6a24875a254795b245 | [
"Apache-2.0"
] | 1 | 2018-12-22T07:06:04.000Z | 2018-12-22T07:06:04.000Z | 29.544118 | 113 | 0.703335 | 999,411 | package leonardolana.poppicture.about;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import leonardolana.poppicture.R;
import leonardolana.poppicture.common.BaseActivity;
import leonardolana.poppicture.common.BasePresenter;
import leonardolana.poppicture.helpers.impl.TrackingHelperImpl;
/**
* Created by Leonardo Lana
* Github: https://github.com/leonardodlana
* <p>
* Copyright 2018 Leonardo Lana
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class AboutActivity extends BaseActivity implements AboutActivityView {
private AboutActivityPresenter mPresenter;
@BindView(R.id.text_icons)
TextView mTextIcons;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ButterKnife.bind(this);
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
supportActionBar.setDisplayHomeAsUpEnabled(true);
supportActionBar.setDisplayShowHomeEnabled(true);
supportActionBar.setTitle("About");
}
mTextIcons.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
protected BasePresenter createPresenter() {
mPresenter = new AboutActivityPresenter(this, TrackingHelperImpl.getInstance(getApplicationContext()));
return mPresenter;
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@OnClick(R.id.button_review)
public void onClickReview() {
mPresenter.onClickReview();
}
@OnClick(R.id.button_privacy_policy)
public void onClickPrivacyPolicy() {
mPresenter.onClickPrivacyPolicy();
}
@OnClick(R.id.button_terms_and_conditions)
public void onClickTermsAndConditions() {
mPresenter.onClickTermsAndConditions();
}
@OnClick(R.id.button_github)
public void onClickGitHub() {
mPresenter.onClickGitHub();
}
private void openBrowser(String url) {
if(TextUtils.isEmpty(url))
return;
try {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
} catch (Exception e) {
// Bad Uri or no browser detected
Crashlytics.logException(e);
Toast.makeText(getApplicationContext(), R.string.error_browser_not_found, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
/*
View methods
*/
@Override
public void openMarket() {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName())));
}
@Override
public void openPrivacyPolicy() {
openBrowser(getString(R.string.privacy_policy_url));
}
@Override
public void openTermsAndConditions() {
openBrowser(getString(R.string.terms_and_conditions_url));
}
@Override
public void openGitHub() {
openBrowser(getString(R.string.github_url));
}
}
|
923afcf3acde1b0e994b57f8aae47f6a7ffff47b | 618 | java | Java | src/main/java/vexatos/tgregworks/proxy/ClientProxy.java | Kiwi233/TinkersGregworks | e7eb54f4268c9dd5af3572f3ba55ca8a6d21704c | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 12 | 2015-01-16T15:28:15.000Z | 2020-04-05T16:42:37.000Z | src/main/java/vexatos/tgregworks/proxy/ClientProxy.java | Kiwi233/TinkersGregworks | e7eb54f4268c9dd5af3572f3ba55ca8a6d21704c | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 43 | 2015-02-10T22:13:24.000Z | 2022-01-29T22:02:29.000Z | src/main/java/vexatos/tgregworks/proxy/ClientProxy.java | Kiwi233/TinkersGregworks | e7eb54f4268c9dd5af3572f3ba55ca8a6d21704c | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 11 | 2015-08-14T13:49:20.000Z | 2021-12-21T01:26:32.000Z | 26.869565 | 112 | 0.791262 | 999,412 | package vexatos.tgregworks.proxy;
import gregtech.api.enums.Materials;
import tconstruct.library.client.TConstructClientRegistry;
import vexatos.tgregworks.TGregworks;
/**
* @author Vexatos
*/
public class ClientProxy extends CommonProxy {
@Override
public void addToolRenderMappings() {
for(Materials m : TGregworks.registry.toolMaterials) {
TConstructClientRegistry.addMaterialRenderMapping(TGregworks.registry.matIDs.get(m), "tgregworks", "", true);
}
}
public void registerRenderers() {
//RenderingRegistry.registerEntityRenderingHandler(TGregDaggerEntity.class, new DaggerRenderCustom());
}
}
|
923afdb3af858edef698bddb96200c40ce27d82f | 1,130 | java | Java | PAT_1003.java | cnlyzy/PAT | 89bfdade64c3684615ea84a14ba4020382449f02 | [
"MIT"
] | null | null | null | PAT_1003.java | cnlyzy/PAT | 89bfdade64c3684615ea84a14ba4020382449f02 | [
"MIT"
] | null | null | null | PAT_1003.java | cnlyzy/PAT | 89bfdade64c3684615ea84a14ba4020382449f02 | [
"MIT"
] | null | null | null | 32.285714 | 78 | 0.349558 | 999,413 | import java.util.Scanner;
public class PAT_1003 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
for (int i = 0; i < n; i++) {
String s = in.nextLine();
String str = s;
if (str.contains("P") && str.contains("A") && str.contains("T")) {
str = str.replace("A", "");
str = str.replace("P", "");
str = str.replace("T", "");
if (str.isEmpty()) {
int p = s.indexOf("P");
int t = s.indexOf("T");
int len = s.length();
int b = t - p - 1;
int c = len - t - 1;
if (p * b == c) {
System.out.println("YES");
} else {
System.out.println("NO");
}
} else {
System.out.println("NO");
}
} else {
System.out.println("NO");
}
}
}
}
|
923afdce3f180bd2c89f4400f64acd51dc4adb11 | 1,807 | java | Java | model/src/main/java/org/openo/sdno/model/servicemodel/tepath/TePath.java | openov2/sdno-l3vpn | df7ba25dc152a32fe65035043c8a8d704dccfde2 | [
"CC-BY-4.0"
] | null | null | null | model/src/main/java/org/openo/sdno/model/servicemodel/tepath/TePath.java | openov2/sdno-l3vpn | df7ba25dc152a32fe65035043c8a8d704dccfde2 | [
"CC-BY-4.0"
] | null | null | null | model/src/main/java/org/openo/sdno/model/servicemodel/tepath/TePath.java | openov2/sdno-l3vpn | df7ba25dc152a32fe65035043c8a8d704dccfde2 | [
"CC-BY-4.0"
] | null | null | null | 22.036585 | 75 | 0.674599 | 999,414 | /*
* Copyright 2016 Huawei Technologies Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openo.sdno.model.servicemodel.tepath;
import java.util.List;
/**
*
* TE path class<br>
*
* @author
* @version SDNO 0.5 August 4, 2016
*/
public class TePath {
private String pathRole;
private String pathStatus;
private String ingressNeid;
private String egressNeid;
private List<ServiceTePath> pathList;
public List<ServiceTePath> getPathList() {
return pathList;
}
public void setPathList(List<ServiceTePath> pathList) {
this.pathList = pathList;
}
public String getPathRole() {
return pathRole;
}
public void setPathRole(String pathRole) {
this.pathRole = pathRole;
}
public String getPathStatus() {
return pathStatus;
}
public void setPathStatus(String pathStatus) {
this.pathStatus = pathStatus;
}
public String getIngressNeid() {
return ingressNeid;
}
public void setIngressNeid(String ingressNeid) {
this.ingressNeid = ingressNeid;
}
public String getEgressNeid() {
return egressNeid;
}
public void setEgressNeid(String egressNeid) {
this.egressNeid = egressNeid;
}
}
|
923afe0319cb905c255e1f824e06fddfa76c91be | 3,555 | java | Java | webpageloader/src/main/java/com/nikolaosfragkiadakis/www/webpageloader/utilities/Constants.java | nikolaosfragkiadakis/Web-Explorer | 33ab098b69501a2484841541b6a4ff639986b986 | [
"MIT"
] | null | null | null | webpageloader/src/main/java/com/nikolaosfragkiadakis/www/webpageloader/utilities/Constants.java | nikolaosfragkiadakis/Web-Explorer | 33ab098b69501a2484841541b6a4ff639986b986 | [
"MIT"
] | null | null | null | webpageloader/src/main/java/com/nikolaosfragkiadakis/www/webpageloader/utilities/Constants.java | nikolaosfragkiadakis/Web-Explorer | 33ab098b69501a2484841541b6a4ff639986b986 | [
"MIT"
] | null | null | null | 45.576923 | 119 | 0.696484 | 999,415 | package com.nikolaosfragkiadakis.www.webpageloader.utilities;
/*
* MIT License
*
* Copyright 2019 © Nikolaos Fragkiadakis / www.nikolaosfragkiadakis.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import com.nikolaosfragkiadakis.www.webpageloader.classes.OverlayLayout;
import com.nikolaosfragkiadakis.www.webpageloader.classes.WebPage;
import com.nikolaosfragkiadakis.www.webpageloader.classes.WebPageLoader;
/**
* The {@link Constants} class is a container of all the constant values that are used in the
* "Web Page Loader" SDK.
*/
public class Constants {
////////////////////////////////////////////////////
///////////////////// Classes //////////////////////
////////////////////////////////////////////////////
/**
* The constant values of the {@link OverlayLayout} class.
*/
public class OverlayLayoutConstants {
// The text for the "No internet connection" toast message.
public static final String NO_INTERNET_CONNECTION_MESSAGE = "No internet connection!\nPlease try again later.";
// The text for the "Error" toast message.
public static final String ERROR_MESSAGE =
"Unable to load the requested web page url.\nAn unexpected error has been occurred.";
}
/**
* The constant values of the {@link WebPage} class.
*/
public class WebPageConstants {
// The default web page's description text value.
public static final String DEFAULT_DESCRIPTION_TEXT = "No description provided.";
// The default calling application's user ID text value.
public static final String DEFAULT_USER_ID_TEXT = "000";
// The default calling application's user name text value.
public static final String DEFAULT_USER_NAME_TEXT = "User name";
// The default calling application's user message text value.
public static final String DEFAULT_USER_MESSAGE_TEXT = "User message";
// The invalid url "IllegalStateException" exception message text value.
public static final String INVALID_URL_VALUE_EXCEPTION_MESSAGE =
"Unable to load the requested web page.\nPlease, provide a valid url.";
}
/**
* The constant values of the {@link WebPageLoader} class.
*/
public class WebPageLoaderConstants {
// The initialization error "IllegalStateException" exception message text value.
public static final String INITIALIZATION_ERROR_MESSAGE = "The Web Page Loader has not been initialized yet!";
}
}
|
923afe06a387d4118cd3cfe8912922f49eab70ce | 3,906 | java | Java | ulyp-ui-transport/src/main/java/com/ulyp/agent/transport/GrpcUiTransport.java | fossabot/ulyp | 4bc8b854229a48cb35ae61d10d3040c9e32a0c14 | [
"Apache-2.0"
] | null | null | null | ulyp-ui-transport/src/main/java/com/ulyp/agent/transport/GrpcUiTransport.java | fossabot/ulyp | 4bc8b854229a48cb35ae61d10d3040c9e32a0c14 | [
"Apache-2.0"
] | null | null | null | ulyp-ui-transport/src/main/java/com/ulyp/agent/transport/GrpcUiTransport.java | fossabot/ulyp | 4bc8b854229a48cb35ae61d10d3040c9e32a0c14 | [
"Apache-2.0"
] | null | null | null | 41.553191 | 144 | 0.665387 | 999,416 | package com.ulyp.agent.transport;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.ulyp.core.*;
import com.ulyp.core.printers.TypeInfo;
import com.ulyp.transport.*;
import io.grpc.ManagedChannel;
import io.grpc.internal.DnsNameResolverProvider;
import io.grpc.netty.NettyChannelBuilder;
import java.time.Duration;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.*;
public class GrpcUiTransport implements UiTransport {
public static final GrpcUiAddress DEFAULT_ADDRESS = new GrpcUiAddress("localhost", 13991);
private final ManagedChannel channel;
private final UiTransportGrpc.UiTransportFutureStub uploadingServiceFutureStub;
private final ExecutorService uploadExecutor = Executors.newFixedThreadPool(
5,
new NamedThreadFactory("GRPC-Transport-Senders", true)
);
private final ExecutorService responseProcessingExecutor = Executors.newFixedThreadPool(
3,
new NamedThreadFactory("GRPC-Response-processor", true)
);
private final Set<Long> recordLogsCurrentlyInSending = Collections.newSetFromMap(new ConcurrentHashMap<>());
public GrpcUiTransport(GrpcUiAddress address) {
channel = NettyChannelBuilder.forAddress(address.hostName, address.port)
.nameResolverFactory(new DnsNameResolverProvider())
.usePlaintext()
.build();
uploadingServiceFutureStub = UiTransportGrpc
.newFutureStub(channel)
.withExecutor(Executors.newFixedThreadPool(3, new NamedThreadFactory("GRPC-Connector", true)));
}
public Settings getSettingsBlocking(Duration duration) throws InterruptedException, ExecutionException, TimeoutException {
return uploadingServiceFutureStub.requestSettings(SettingsRequest.newBuilder().build()).get(duration.toMillis(), TimeUnit.MILLISECONDS);
}
public void uploadAsync(CallRecordTreeRequest request) {
CallRecordLog recordLog = request.getRecordLog();
uploadExecutor.submit(
() -> {
TCallRecordLogUploadRequest protoRequest = RequestConverter.convert(request);
long id = recordLog.getId();
ListenableFuture<TCallRecordLogUploadResponse> upload = uploadingServiceFutureStub.uploadCallGraph(protoRequest);
Futures.addCallback(upload, new FutureCallback<TCallRecordLogUploadResponse>() {
@Override
public void onSuccess(TCallRecordLogUploadResponse result) {
recordLogsCurrentlyInSending.remove(id);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
recordLogsCurrentlyInSending.remove(id);
}
}, responseProcessingExecutor);
}
);
long id = recordLog.getId();
recordLogsCurrentlyInSending.add(id);
}
public void shutdownNowAndAwaitForRecordsLogsSending(long time, TimeUnit timeUnit) throws InterruptedException {
long startWaitingAtEpochMillis = System.currentTimeMillis();
long deadline = startWaitingAtEpochMillis + timeUnit.toMillis(time);
while (System.currentTimeMillis() < deadline && !recordLogsCurrentlyInSending.isEmpty()) {
Thread.sleep(100);
}
if (!recordLogsCurrentlyInSending.isEmpty()) {
System.err.println(
"Didn't send " + recordLogsCurrentlyInSending + " record logs, but shutting " +
"down anyway as waited for " + time + " " + timeUnit
);
}
}
}
|
923affeddbe296711dfc0dbcb395e5ee97a37d46 | 1,061 | java | Java | src/main/java/wordhunt/BasicIndexWalkerFactory.java | vpiotr/wordhunt | 3b036eb3f7f7167b75a8c603bb25bcffbbd144f2 | [
"Apache-2.0"
] | null | null | null | src/main/java/wordhunt/BasicIndexWalkerFactory.java | vpiotr/wordhunt | 3b036eb3f7f7167b75a8c603bb25bcffbbd144f2 | [
"Apache-2.0"
] | null | null | null | src/main/java/wordhunt/BasicIndexWalkerFactory.java | vpiotr/wordhunt | 3b036eb3f7f7167b75a8c603bb25bcffbbd144f2 | [
"Apache-2.0"
] | null | null | null | 27.205128 | 72 | 0.734213 | 999,417 | /*
Copyright 2017 Piotr Likus
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 wordhunt;
/**
* Creates default index walker object.
*
* @author piotr
*/
public class BasicIndexWalkerFactory implements IndexWalkerFactory {
private final IndexStorage indexStorage;
public BasicIndexWalkerFactory(IndexStorage is) {
this.indexStorage = is;
}
@Override
public IndexWalker newWalker(String indexFilePath) {
return new BasicIndexWalker(
indexStorage.getReaderForIndexFile(indexFilePath)
);
}
}
|
923b003b443b4a13d69dd6f59e4f081ca35dde97 | 2,409 | java | Java | src/com/maxzxwd/fitsvegetationonly/BlockListeners.java | maxzxwd/FistsVegetationOnly | 3441312044e4b951cee648e16d4ccb9bf0b2bf71 | [
"MIT"
] | null | null | null | src/com/maxzxwd/fitsvegetationonly/BlockListeners.java | maxzxwd/FistsVegetationOnly | 3441312044e4b951cee648e16d4ccb9bf0b2bf71 | [
"MIT"
] | null | null | null | src/com/maxzxwd/fitsvegetationonly/BlockListeners.java | maxzxwd/FistsVegetationOnly | 3441312044e4b951cee648e16d4ccb9bf0b2bf71 | [
"MIT"
] | null | null | null | 38.854839 | 150 | 0.672478 | 999,418 | package com.maxzxwd.fitsvegetationonly;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.material.Directional;
public class BlockListeners implements Listener {
public static final Material[] ONLY_FISTS =
{ Material.CROPS, Material.PUMPKIN, Material.MELON_BLOCK, Material.SOIL, Material.COCOA};
public static final Material[] PISTON_DONT_MOVE =
{ Material.BEDROCK, Material.OBSIDIAN, Material.AIR, Material.CHEST, Material.FURNACE, Material.BURNING_FURNACE, Material.JUKEBOX,
Material.ENCHANTMENT_TABLE, Material.ENDER_PORTAL_FRAME, Material.ENDER_CHEST, Material.SIGN_POST, Material.WALL_SIGN, Material.DISPENSER,
Material.NOTE_BLOCK, Material.BREWING_STAND, Material.MOB_SPAWNER, Material.TRAPPED_CHEST };
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockFlow(BlockFromToEvent event) {
event.setCancelled(Utils.contains(ONLY_FISTS, event.getToBlock().getType()));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block block = event.getBlock();
if (block.getType() == Material.PISTON_BASE || block.getType() == Material.PISTON_STICKY_BASE) {
BlockFace face = ((Directional) block.getState().getData()).getFacing();
List<Block> blocks = new ArrayList<>(12);
Location loc = block.getLocation().clone();
for (int i = 1; i <= 12; i++) {
if (Utils.contains(PISTON_DONT_MOVE, loc.add(face.getModX(), face.getModY(), face.getModZ()).getBlock().getType())) {
break;
}
blocks.add(loc.getBlock());
}
event.setCancelled(onPistonMove(blocks));
}
}
public boolean onPistonMove(List<Block> blocks) {
boolean cancelled = false;
for (Block b : blocks) {
if (Utils.contains(ONLY_FISTS, b.getType())) {
cancelled = true;
break;
}
}
return cancelled;
}
} |
923b00efa60c9ebc8d4aaad3d4bc90bb9d19a370 | 497 | java | Java | zmall-seckill/src/main/java/com/devotion/zmall/seckill/dao/UserDao.java | ZhouBoXiao/ZMall | f994fb61cca11c5190329164100da269d3757499 | [
"Apache-2.0"
] | 1 | 2020-04-25T08:03:15.000Z | 2020-04-25T08:03:15.000Z | zmall-seckill/src/main/java/com/devotion/zmall/seckill/dao/UserDao.java | ZhouBoXiao/ZMall | f994fb61cca11c5190329164100da269d3757499 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:07:40.000Z | 2021-09-20T20:58:13.000Z | zmall-seckill/src/main/java/com/devotion/zmall/seckill/dao/UserDao.java | ZhouBoXiao/ZMall | f994fb61cca11c5190329164100da269d3757499 | [
"Apache-2.0"
] | null | null | null | 23.666667 | 62 | 0.744467 | 999,419 | package com.devotion.zmall.seckill.dao;
import com.devotion.zmall.seckill.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserDao {
@Select("select * from user where id = #{id}")
public User getById(@Param("id") int id);
@Insert("insert into user (id, name) values(#{id}, #{name})")
public int insert(User user);
}
|
923b01008fe20bac1f27094e987c834e7447f5f8 | 29,717 | java | Java | modules/flowable-cmmn-engine/src/test/java/org/flowable/cmmn/test/async/AsyncCmmnHistoryTest.java | rovegaby/flowable-engine | 5c7b90ce61533e67a903ad114c140c56b4ad8a97 | [
"Apache-2.0"
] | 1 | 2019-04-26T02:22:18.000Z | 2019-04-26T02:22:18.000Z | modules/flowable-cmmn-engine/src/test/java/org/flowable/cmmn/test/async/AsyncCmmnHistoryTest.java | rovegaby/flowable-engine | 5c7b90ce61533e67a903ad114c140c56b4ad8a97 | [
"Apache-2.0"
] | null | null | null | modules/flowable-cmmn-engine/src/test/java/org/flowable/cmmn/test/async/AsyncCmmnHistoryTest.java | rovegaby/flowable-engine | 5c7b90ce61533e67a903ad114c140c56b4ad8a97 | [
"Apache-2.0"
] | null | null | null | 59.197211 | 190 | 0.749975 | 999,420 | /* 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.flowable.cmmn.test.async;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.flowable.cmmn.api.history.HistoricCaseInstance;
import org.flowable.cmmn.api.history.HistoricMilestoneInstance;
import org.flowable.cmmn.api.history.HistoricPlanItemInstance;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.api.runtime.CaseInstanceState;
import org.flowable.cmmn.api.runtime.PlanItemDefinitionType;
import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.api.runtime.UserEventListenerInstance;
import org.flowable.cmmn.engine.CmmnEngineConfiguration;
import org.flowable.cmmn.engine.test.CmmnDeployment;
import org.flowable.cmmn.test.impl.CustomCmmnConfigurationFlowableTestCase;
import org.flowable.common.engine.api.scope.ScopeTypes;
import org.flowable.identitylink.api.IdentityLinkType;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskLogEntry;
import org.flowable.task.api.history.HistoricTaskLogEntryBuilder;
import org.flowable.task.api.history.HistoricTaskLogEntryType;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.junit.Test;
/**
* @author Joram Barrez
*/
public class AsyncCmmnHistoryTest extends CustomCmmnConfigurationFlowableTestCase {
@Override
protected String getEngineName() {
return "AsyncCmmnHistoryTest";
}
@Override
protected void configureConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) {
cmmnEngineConfiguration.setAsyncHistoryEnabled(true);
cmmnEngineConfiguration.setAsyncExecutorActivate(false);
cmmnEngineConfiguration.setAsyncHistoryJsonGroupingEnabled(true);
cmmnEngineConfiguration.setAsyncHistoryJsonGroupingThreshold(1);
cmmnEngineConfiguration.setAsyncFailedJobWaitTime(1);
cmmnEngineConfiguration.setDefaultFailedJobWaitTime(1);
cmmnEngineConfiguration.setAsyncHistoryExecutorNumberOfRetries(10);
cmmnEngineConfiguration.setAsyncHistoryExecutorDefaultAsyncJobAcquireWaitTime(1000);
}
@Test
@CmmnDeployment
public void testCaseInstanceStartAndEnd() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
.caseDefinitionKey("oneHumanTaskCase")
.name("someName")
.businessKey("someBusinessKey")
.start();
assertEquals(0, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
HistoricCaseInstance historicCaseInstance = cmmnHistoryService.createHistoricCaseInstanceQuery().singleResult();
assertEquals(caseInstance.getId(), historicCaseInstance.getId());
assertEquals("someName", historicCaseInstance.getName());
assertNull(historicCaseInstance.getParentId());
assertEquals("someBusinessKey", historicCaseInstance.getBusinessKey());
assertEquals(caseInstance.getCaseDefinitionId(), historicCaseInstance.getCaseDefinitionId());
assertEquals(CaseInstanceState.ACTIVE, historicCaseInstance.getState());
assertNotNull(historicCaseInstance.getStartTime());
assertNull(historicCaseInstance.getEndTime());
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnTaskService.complete(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertCaseInstanceEnded(caseInstance);
historicCaseInstance = cmmnHistoryService.createHistoricCaseInstanceQuery().singleResult();
assertEquals(caseInstance.getId(), historicCaseInstance.getId());
assertEquals("someName", historicCaseInstance.getName());
assertNull(historicCaseInstance.getParentId());
assertEquals("someBusinessKey", historicCaseInstance.getBusinessKey());
assertEquals(caseInstance.getCaseDefinitionId(), historicCaseInstance.getCaseDefinitionId());
assertEquals(CaseInstanceState.ACTIVE, historicCaseInstance.getState());
assertNotNull(historicCaseInstance.getStartTime());
assertNotNull(historicCaseInstance.getEndTime());
}
@Test
@CmmnDeployment
public void testHistoricCaseInstanceDeleted() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
.caseDefinitionKey("oneHumanTaskCase")
.name("someName")
.businessKey("someBusinessKey")
.start();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnTaskService.complete(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnRuntimeService.createPlanItemInstanceQuery().count());
assertEquals(1, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
cmmnHistoryService.deleteHistoricCaseInstance(caseInstance.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
}
@Test
@CmmnDeployment
public void testMilestoneReached() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("caseWithOneMilestone").start();
assertEquals(1, cmmnRuntimeService.createMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count());
assertEquals(0, cmmnHistoryService.createHistoricMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.createHistoricMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count());
HistoricMilestoneInstance historicMilestoneInstance = cmmnHistoryService.createHistoricMilestoneInstanceQuery()
.milestoneInstanceCaseInstanceId(caseInstance.getId())
.singleResult();
assertEquals("xyzMilestone", historicMilestoneInstance.getName());
assertEquals("milestonePlanItem1", historicMilestoneInstance.getElementId());
assertEquals(caseInstance.getId(), historicMilestoneInstance.getCaseInstanceId());
assertEquals(caseInstance.getCaseDefinitionId(), historicMilestoneInstance.getCaseDefinitionId());
assertNotNull(historicMilestoneInstance.getTimeStamp());
}
@Test
@CmmnDeployment
public void testIdentityLinks() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("caseWithOneMilestone").start();
cmmnRuntimeService.addUserIdentityLink(caseInstance.getId(), "someUser", IdentityLinkType.PARTICIPANT);
assertEquals(0, cmmnHistoryService.getHistoricIdentityLinksForCaseInstance(caseInstance.getId()).size());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.getHistoricIdentityLinksForCaseInstance(caseInstance.getId()).size());
cmmnRuntimeService.deleteUserIdentityLink(caseInstance.getId(), "someUser", IdentityLinkType.PARTICIPANT);
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnHistoryService.getHistoricIdentityLinksForCaseInstance(caseInstance.getId()).size());
}
@Test
@CmmnDeployment
public void testVariables() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
assertEquals(0, cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).count());
cmmnRuntimeService.setVariable(caseInstance.getId(), "test", "hello world");
cmmnRuntimeService.setVariable(caseInstance.getId(), "test2", 2);
// Create
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(2, cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).count());
HistoricVariableInstance historicVariableInstance = cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test").singleResult();
assertEquals("test", historicVariableInstance.getVariableName());
assertEquals(caseInstance.getId(), historicVariableInstance.getScopeId());
assertEquals(ScopeTypes.CMMN, historicVariableInstance.getScopeType());
assertEquals("hello world", historicVariableInstance.getValue());
assertNotNull(historicVariableInstance.getCreateTime());
assertNotNull(historicVariableInstance.getLastUpdatedTime());
historicVariableInstance = cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test2").singleResult();
assertEquals("test2", historicVariableInstance.getVariableName());
assertEquals(caseInstance.getId(), historicVariableInstance.getScopeId());
assertNull(historicVariableInstance.getSubScopeId());
assertEquals(ScopeTypes.CMMN, historicVariableInstance.getScopeType());
assertEquals(2, historicVariableInstance.getValue());
assertNotNull(historicVariableInstance.getCreateTime());
assertNotNull(historicVariableInstance.getLastUpdatedTime());
// Update
try {
Thread.sleep(16); // wait time for diff in last updated time
} catch (InterruptedException e) {
e.printStackTrace();
}
cmmnRuntimeService.setVariable(caseInstance.getId(), "test", "hello test");
waitForAsyncHistoryExecutorToProcessAllJobs();
HistoricVariableInstance updatedHistoricVariable = cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test").singleResult();
assertEquals("test", updatedHistoricVariable.getVariableName());
assertEquals(caseInstance.getId(), updatedHistoricVariable.getScopeId());
assertNull(updatedHistoricVariable.getSubScopeId());
assertEquals(ScopeTypes.CMMN, updatedHistoricVariable.getScopeType());
assertEquals("hello test", updatedHistoricVariable.getValue());
assertNotNull(updatedHistoricVariable.getCreateTime());
assertNotNull(updatedHistoricVariable.getLastUpdatedTime());
assertNotEquals(updatedHistoricVariable.getLastUpdatedTime(), historicVariableInstance.getLastUpdatedTime());
// Delete
cmmnRuntimeService.removeVariable(caseInstance.getId(), "test");
waitForAsyncHistoryExecutorToProcessAllJobs();
assertNull(cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test").singleResult());
}
@Test
@CmmnDeployment
public void testHumanTask() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
assertEquals(1, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
assertEquals(0, cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).count());
// Create
HistoricTaskInstance historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals("The Task", historicTaskInstance.getName());
assertEquals("johnDoe", historicTaskInstance.getAssignee());
assertEquals(caseInstance.getId(), historicTaskInstance.getScopeId());
assertEquals(caseInstance.getCaseDefinitionId(), historicTaskInstance.getScopeDefinitionId());
assertEquals(ScopeTypes.CMMN, historicTaskInstance.getScopeType());
assertNotNull(historicTaskInstance.getStartTime());
// Update
cmmnTaskService.setAssignee(historicTaskInstance.getId(), "janeDoe");
waitForAsyncHistoryExecutorToProcessAllJobs();
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals("The Task", historicTaskInstance.getName());
assertEquals("janeDoe", historicTaskInstance.getAssignee());
cmmnTaskService.setPriority(historicTaskInstance.getId(), 99);
waitForAsyncHistoryExecutorToProcessAllJobs();
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals(99, historicTaskInstance.getPriority());
assertNull(historicTaskInstance.getEndTime());
// Complete
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnTaskService.complete(task.getId());
assertEquals(0, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertNotNull(historicTaskInstance.getEndTime());
}
@Test
@CmmnDeployment
public void testPlanItemInstances() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testSimpleCaseFlow").start();
List<PlanItemInstance> currentPlanItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).list();
assertEquals(3, currentPlanItemInstances.size());
assertEquals(0, cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceCaseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(3, cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceCaseInstanceId(caseInstance.getId()).count());
List<HistoricPlanItemInstance> historicPlanItemInstances = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceCaseInstanceId(caseInstance.getId()).list();
assertTrue(historicPlanItemInstances.stream().map(HistoricPlanItemInstance::getPlanItemDefinitionType).anyMatch(PlanItemDefinitionType.STAGE::equalsIgnoreCase));
assertTrue(historicPlanItemInstances.stream().map(HistoricPlanItemInstance::getPlanItemDefinitionType).anyMatch(PlanItemDefinitionType.MILESTONE::equalsIgnoreCase));
assertTrue(historicPlanItemInstances.stream().anyMatch(h -> "task".equalsIgnoreCase(h.getPlanItemDefinitionType()) && "planItemTaskA".equalsIgnoreCase(h.getElementId())));
for (HistoricPlanItemInstance historicPlanItemInstance : historicPlanItemInstances) {
assertEquals(caseInstance.getId(), historicPlanItemInstance.getCaseInstanceId());
assertEquals(caseInstance.getCaseDefinitionId(), historicPlanItemInstance.getCaseDefinitionId());
assertNotNull(historicPlanItemInstance.getElementId());
assertNotNull(historicPlanItemInstance.getCreateTime());
assertNotNull(historicPlanItemInstance.getLastAvailableTime());
assertNull(historicPlanItemInstance.getEndedTime());
assertNull(historicPlanItemInstance.getLastDisabledTime());
assertNull(historicPlanItemInstance.getLastSuspendedTime());
assertNull(historicPlanItemInstance.getExitTime());
assertNull(historicPlanItemInstance.getTerminatedTime());
assertNull(historicPlanItemInstance.getEntryCriterionId());
assertNull(historicPlanItemInstance.getExitCriterionId());
if (historicPlanItemInstance.getElementId().equals("planItemTaskA")) {
assertNotNull(historicPlanItemInstance.getLastEnabledTime());
} else {
assertNull(historicPlanItemInstance.getLastEnabledTime());
}
}
// Disable task
PlanItemInstance task = cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceElementId("planItemTaskA").singleResult();
assertNotNull(task);
cmmnRuntimeService.disablePlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnManagementService.createHistoryJobQuery().scopeType(ScopeTypes.CMMN).count());
assertEquals(0, cmmnManagementService.createDeadLetterJobQuery().scopeType(ScopeTypes.CMMN).count());
HistoricPlanItemInstance historicPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertEquals(PlanItemInstanceState.DISABLED, historicPlanItemInstance.getState());
assertNotNull(historicPlanItemInstance.getLastEnabledTime());
assertNotNull(historicPlanItemInstance.getLastDisabledTime());
assertNotNull(historicPlanItemInstance.getLastAvailableTime());
assertNull(historicPlanItemInstance.getLastStartedTime());
assertNull(historicPlanItemInstance.getEndedTime());
assertNull(historicPlanItemInstance.getLastSuspendedTime());
assertNull(historicPlanItemInstance.getExitTime());
assertNull(historicPlanItemInstance.getTerminatedTime());
assertNotNull(historicPlanItemInstance.getLastUpdatedTime());
// Enable task
cmmnRuntimeService.enablePlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
historicPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertEquals(PlanItemInstanceState.ENABLED, historicPlanItemInstance.getState());
assertNotNull(historicPlanItemInstance.getLastEnabledTime());
assertNotNull(historicPlanItemInstance.getLastAvailableTime());
assertNotNull(historicPlanItemInstance.getLastDisabledTime());
assertNull(historicPlanItemInstance.getLastStartedTime());
assertNull(historicPlanItemInstance.getEndedTime());
assertNull(historicPlanItemInstance.getLastSuspendedTime());
assertNull(historicPlanItemInstance.getExitTime());
assertNull(historicPlanItemInstance.getTerminatedTime());
assertNotNull(historicPlanItemInstance.getLastUpdatedTime());
// Manually enable
cmmnRuntimeService.startPlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
historicPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertNotNull(historicPlanItemInstance.getLastStartedTime());
assertNull(historicPlanItemInstance.getEndedTime());
// Complete task
Calendar clockCal = cmmnEngineConfiguration.getClock().getCurrentCalendar();
clockCal.add(Calendar.HOUR, 1);
setClockTo(clockCal.getTime());
cmmnRuntimeService.triggerPlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
HistoricPlanItemInstance completedHistoricPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertNotNull(completedHistoricPlanItemInstance.getEndedTime());
assertNotNull(completedHistoricPlanItemInstance.getLastEnabledTime());
assertNotNull(completedHistoricPlanItemInstance.getLastDisabledTime());
assertNotNull(completedHistoricPlanItemInstance.getLastAvailableTime());
assertNotNull(completedHistoricPlanItemInstance.getLastStartedTime());
assertNull(completedHistoricPlanItemInstance.getLastSuspendedTime());
assertNull(completedHistoricPlanItemInstance.getExitTime());
assertNull(completedHistoricPlanItemInstance.getTerminatedTime());
assertNotNull(completedHistoricPlanItemInstance.getLastUpdatedTime());
assertTrue(historicPlanItemInstance.getLastUpdatedTime().before(completedHistoricPlanItemInstance.getLastUpdatedTime()));
cmmnEngineConfiguration.getClock().reset();
}
@Test
@CmmnDeployment
public void testCriterionStoredOnPlanItemInstance() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testCriterions").start();
// Executing the tasks triggers the entry criterion
Task taskB = cmmnTaskService.createTaskQuery().taskName("B").singleResult();
cmmnTaskService.complete(taskB.getId());
assertEquals(cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceName("C").singleResult().getEntryCriterionId(), "entryA2");
waitForAsyncHistoryExecutorToProcessAllJobs();
HistoricPlanItemInstance planItemInstanceC = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceName("C").singleResult();
assertEquals(planItemInstanceC.getEntryCriterionId(), "entryA2");
assertNull(planItemInstanceC.getExitCriterionId());
// Completing will set the exit criterion
UserEventListenerInstance userEventListenerInstance = cmmnRuntimeService.createUserEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnRuntimeService.completeUserEventListenerInstance(userEventListenerInstance.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
planItemInstanceC = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceName("C").singleResult();
assertEquals(planItemInstanceC.getEntryCriterionId(), "entryA2");
assertEquals(planItemInstanceC.getExitCriterionId(), "stop");
}
@Test
public void createUserTaskLogEntity() {
HistoricTaskLogEntryBuilder historicTaskLogEntryBuilder = cmmnHistoryService.createHistoricTaskLogEntryBuilder();
Date todayDate = new Date();
historicTaskLogEntryBuilder.taskId("1");
historicTaskLogEntryBuilder.type("testType");
historicTaskLogEntryBuilder.userId("testUserId");
historicTaskLogEntryBuilder.data("testData");
historicTaskLogEntryBuilder.scopeId("testScopeId");
historicTaskLogEntryBuilder.scopeType("testScopeType");
historicTaskLogEntryBuilder.scopeDefinitionId("testDefinitionId");
historicTaskLogEntryBuilder.subScopeId("testSubScopeId");
historicTaskLogEntryBuilder.timeStamp(todayDate);
historicTaskLogEntryBuilder.tenantId("testTenant");
historicTaskLogEntryBuilder.create();
HistoricTaskLogEntry historicTaskLogEntry = null;
try {
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId("1").count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId("1").count());
historicTaskLogEntry = cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId("1").singleResult();
assertTrue(historicTaskLogEntry.getLogNumber() > 0);
assertEquals("1", historicTaskLogEntry.getTaskId());
assertEquals("testType", historicTaskLogEntry.getType());
assertEquals("testUserId", historicTaskLogEntry.getUserId());
assertEquals("testScopeId", historicTaskLogEntry.getScopeId());
assertEquals("testScopeType", historicTaskLogEntry.getScopeType());
assertEquals("testDefinitionId", historicTaskLogEntry.getScopeDefinitionId());
assertEquals("testSubScopeId", historicTaskLogEntry.getSubScopeId());
assertEquals("testData", historicTaskLogEntry.getData());
assertTrue(historicTaskLogEntry.getLogNumber() > 0l);
assertNotNull(historicTaskLogEntry.getTimeStamp());
assertEquals("testTenant", historicTaskLogEntry.getTenantId());
} finally {
if (historicTaskLogEntry != null) {
cmmnHistoryService.deleteHistoricTaskLogEntry(historicTaskLogEntry.getLogNumber());
waitForAsyncHistoryExecutorToProcessAllJobs();
}
}
}
@Test
public void createCmmnAsynchUserTaskLogEntries() {
CaseInstance caseInstance = deployAndStartOneHumanTaskCaseModel();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
task.setName("newName");
task.setPriority(0);
cmmnTaskService.saveTask(task);
cmmnTaskService.setAssignee(task.getId(), "newAssignee");
cmmnTaskService.setOwner(task.getId(), "newOwner");
cmmnTaskService.setDueDate(task.getId(), new Date());
cmmnTaskService.addUserIdentityLink(task.getId(), "testUser", IdentityLinkType.PARTICIPANT);
cmmnTaskService.addGroupIdentityLink(task.getId(), "testGroup", IdentityLinkType.PARTICIPANT);
cmmnTaskService.deleteUserIdentityLink(task.getId(), "testUser", IdentityLinkType.PARTICIPANT);
cmmnTaskService.deleteGroupIdentityLink(task.getId(), "testGroup", IdentityLinkType.PARTICIPANT);
cmmnTaskService.complete(task.getId());
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().count());
assertEquals(10l, cmmnManagementService.createHistoryJobQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(11l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).count());
assertEquals(1l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_CREATED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_NAME_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_PRIORITY_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_ASSIGNEE_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_OWNER_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_DUEDATE_CHANGED.name()).count());
assertEquals(2l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_IDENTITY_LINK_ADDED.name()).count());
assertEquals(2l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_IDENTITY_LINK_REMOVED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_COMPLETED.name()).count());
}
@Test
public void deleteAsynchUserTaskLogEntries() {
CaseInstance caseInstance = deployAndStartOneHumanTaskCaseModel();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().count());
assertEquals(1l, cmmnManagementService.createHistoryJobQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
List<HistoricTaskLogEntry> historicTaskLogEntries = cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).list();
assertEquals(1l, historicTaskLogEntries.size());
cmmnHistoryService.deleteHistoricTaskLogEntry(historicTaskLogEntries.get(0).getLogNumber());
assertEquals(1l, cmmnManagementService.createHistoryJobQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).count());
}
}
|
923b023d6d63bea1f256bd85e422f799d136e62c | 3,287 | java | Java | src/main/java/eu/artemisc/stodium/auth/HmacSha512.java | ArteMisc/libstodium | 4c0805d963f447da3eaaaad45790d9371d61347a | [
"Apache-2.0"
] | 11 | 2016-01-02T18:49:09.000Z | 2020-10-09T23:21:23.000Z | src/main/java/eu/artemisc/stodium/auth/HmacSha512.java | ArteMisc/libstodium | 4c0805d963f447da3eaaaad45790d9371d61347a | [
"Apache-2.0"
] | 3 | 2015-12-10T13:54:49.000Z | 2016-02-18T09:46:00.000Z | src/main/java/eu/artemisc/stodium/auth/HmacSha512.java | ArteMisc/libstodium | 4c0805d963f447da3eaaaad45790d9371d61347a | [
"Apache-2.0"
] | 7 | 2016-01-31T19:26:51.000Z | 2020-10-02T21:31:09.000Z | 33.886598 | 76 | 0.658047 | 999,421 | package eu.artemisc.stodium.auth;
import org.jetbrains.annotations.NotNull;
import java.nio.ByteBuffer;
import eu.artemisc.stodium.Multipart;
import eu.artemisc.stodium.Stodium;
import eu.artemisc.stodium.StodiumJNI;
import eu.artemisc.stodium.exceptions.StodiumException;
/**
* @author Jan van de Molengraft [jan@artemisc.eu]
*/
final class HmacSha512
extends Auth
implements Multipart.Spec {
HmacSha512() {
super(StodiumJNI.crypto_auth_hmacsha512_bytes(),
StodiumJNI.crypto_auth_hmacsha512_keybytes(),
StodiumJNI.crypto_auth_hmacsha512_statebytes());
}
@Override
public void mac(final @NotNull ByteBuffer dstMac,
final @NotNull ByteBuffer src,
final @NotNull ByteBuffer key)
throws StodiumException {
Stodium.checkDestinationWritable(dstMac);
Stodium.checkSizeMin(dstMac.remaining(), BYTES);
Stodium.checkSize(key.remaining(), KEYBYTES);
Stodium.checkStatus(StodiumJNI.crypto_auth_hmacsha512(
Stodium.ensureUsableByteBuffer(dstMac),
Stodium.ensureUsableByteBuffer(src),
Stodium.ensureUsableByteBuffer(key)));
}
@Override
public boolean verify(final @NotNull ByteBuffer srcMac,
final @NotNull ByteBuffer src,
final @NotNull ByteBuffer key)
throws StodiumException {
Stodium.checkSizeMin(srcMac.remaining(), BYTES);
Stodium.checkSize(key.remaining(), KEYBYTES);
return StodiumJNI.NOERR == StodiumJNI.crypto_auth_hmacsha512_verify(
Stodium.ensureUsableByteBuffer(srcMac),
Stodium.ensureUsableByteBuffer(src),
Stodium.ensureUsableByteBuffer(key));
}
@NotNull
@Override
public Multipart<Auth> init(final @NotNull ByteBuffer key)
throws StodiumException {
final ByteBuffer state;
Stodium.checkSize(key.remaining(), KEYBYTES);
state = ByteBuffer.allocateDirect(STATEBYTES);
Stodium.checkStatus(StodiumJNI.crypto_auth_hmacsha512_init(
state, Stodium.ensureUsableByteBuffer(key)));
return new Multipart<>(this, state);
}
@Override
public void update(final @NotNull ByteBuffer state,
final @NotNull ByteBuffer in)
throws StodiumException {
Stodium.checkDestinationWritable(state);
Stodium.checkSize(state.remaining(), STATEBYTES);
Stodium.checkStatus(StodiumJNI.crypto_auth_hmacsha512_update(
Stodium.ensureUsableByteBuffer(state),
Stodium.ensureUsableByteBuffer(in)));
}
@Override
public void doFinal(final @NotNull ByteBuffer state,
final @NotNull ByteBuffer dst)
throws StodiumException {
Stodium.checkDestinationWritable(state);
Stodium.checkDestinationWritable(dst);
Stodium.checkSize(state.remaining(), STATEBYTES);
Stodium.checkSizeMin(dst.remaining(), BYTES);
Stodium.checkStatus(StodiumJNI.crypto_auth_hmacsha512_final(
Stodium.ensureUsableByteBuffer(state),
Stodium.ensureUsableByteBuffer(dst)));
}
}
|
923b03a24c4bcd93e00afaf596e3ef5d8d98b2d9 | 900 | java | Java | learning/idtech/Java/PrintingStuff/src/Treasure.java | NaiculS/projects | 69b5e828eb8c37768d68a11e79e111ef18d697b1 | [
"Apache-2.0"
] | null | null | null | learning/idtech/Java/PrintingStuff/src/Treasure.java | NaiculS/projects | 69b5e828eb8c37768d68a11e79e111ef18d697b1 | [
"Apache-2.0"
] | null | null | null | learning/idtech/Java/PrintingStuff/src/Treasure.java | NaiculS/projects | 69b5e828eb8c37768d68a11e79e111ef18d697b1 | [
"Apache-2.0"
] | null | null | null | 29.032258 | 85 | 0.56 | 999,422 | //Importing Random
import java.util.Random;
public class Treasure {
public static void MakeTreasure(){
int gold;
boolean trap;
Random generator=new Random();
gold=generator.nextInt(5);
System.out.println("You open the chest to find " + gold + " gold pieces!");
trap = generator.nextBoolean();
if (trap){
System.out.println("You lost all of the gold due to a trap however...");
}}
public static void main(String[] args) {
int gold;
boolean trap;
Random generator=new Random();
gold=generator.nextInt(5);
System.out.println("You open the chest to find " + gold + " gold pieces!");
trap = generator.nextBoolean();
if (trap){
System.out.println("You lost all of the gold due to a trap however...");
}
}
}
|
923b03e6647ae1e463daa25aa325c9b3339a08bc | 8,958 | java | Java | src/main/java/rsc/publisher/PublisherAmb.java | spring-operator/reactive-streams-commons | 30e366f0f4172205060df81ad09f9f850ba8d539 | [
"Apache-2.0"
] | 364 | 2015-12-27T00:57:55.000Z | 2022-01-12T00:52:25.000Z | src/main/java/rsc/publisher/PublisherAmb.java | spring-operator/reactive-streams-commons | 30e366f0f4172205060df81ad09f9f850ba8d539 | [
"Apache-2.0"
] | 25 | 2016-02-03T09:41:40.000Z | 2019-06-21T13:21:22.000Z | src/main/java/rsc/publisher/PublisherAmb.java | reactor/reactive-stream-extensions | 9db7f7829460ea9678fbc4746e4e1215584fdf23 | [
"Apache-2.0"
] | 49 | 2015-12-26T02:02:59.000Z | 2021-12-02T15:24:43.000Z | 28.258675 | 119 | 0.487162 | 999,423 | package rsc.publisher;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import rsc.flow.MultiReceiver;
import rsc.flow.Trackable;
import rsc.subscriber.DeferredSubscriptionSubscriber;
import rsc.subscriber.SubscriptionHelper;
/**
* Given a set of source Publishers the values of that Publisher is forwarded to the
* subscriber which responds first with any signal.
*
* @param <T> the value type
*/
public final class PublisherAmb<T>
extends Px<T>
implements MultiReceiver {
final Publisher<? extends T>[] array;
final Iterable<? extends Publisher<? extends T>> iterable;
@SafeVarargs
public PublisherAmb(Publisher<? extends T>... array) {
this.array = Objects.requireNonNull(array, "array");
this.iterable = null;
}
public PublisherAmb(Iterable<? extends Publisher<? extends T>> iterable) {
this.array = null;
this.iterable = Objects.requireNonNull(iterable);
}
@Override
public Iterator<?> upstreams() {
return iterable != null ? iterable.iterator() : Arrays.asList(array).iterator();
}
@Override
public long upstreamCount() {
return array != null ? array.length : -1L;
}
@SuppressWarnings("unchecked")
@Override
public void subscribe(Subscriber<? super T> s) {
Publisher<? extends T>[] a = array;
int n;
if (a == null) {
n = 0;
a = new Publisher[8];
Iterator<? extends Publisher<? extends T>> it;
try {
it = iterable.iterator();
} catch (Throwable e) {
SubscriptionHelper.error(s, e);
return;
}
if (it == null) {
SubscriptionHelper.error(s, new NullPointerException("The iterator returned is null"));
return;
}
for (; ; ) {
boolean b;
try {
b = it.hasNext();
} catch (Throwable e) {
SubscriptionHelper.error(s, e);
return;
}
if (!b) {
break;
}
Publisher<? extends T> p;
try {
p = it.next();
} catch (Throwable e) {
SubscriptionHelper.error(s, e);
return;
}
if (p == null) {
SubscriptionHelper.error(s, new NullPointerException("The Publisher returned by the iterator is " +
"null"));
return;
}
if (n == a.length) {
Publisher<? extends T>[] c = new Publisher[n + (n >> 2)];
System.arraycopy(a, 0, c, 0, n);
a = c;
}
a[n++] = p;
}
} else {
n = a.length;
}
if (n == 0) {
SubscriptionHelper.complete(s);
return;
}
if (n == 1) {
Publisher<? extends T> p = a[0];
if (p == null) {
SubscriptionHelper.error(s, new NullPointerException("The single source Publisher is null"));
} else {
p.subscribe(s);
}
return;
}
PublisherAmbCoordinator<T> coordinator = new PublisherAmbCoordinator<>(n);
coordinator.subscribe(a, n, s);
}
/**
* Returns a new instance which has the additional source to be amb'd together with
* the current array of sources.
* <p>
* This operation doesn't change the current PublisherAmb instance.
*
* @param source the new source to merge with the others
* @return the new PublisherAmb instance or null if the Amb runs with an Iterable
*/
public PublisherAmb<T> ambAdditionalSource(Publisher<? extends T> source) {
if (array != null) {
int n = array.length;
@SuppressWarnings("unchecked")
Publisher<? extends T>[] newArray = new Publisher[n + 1];
System.arraycopy(array, 0, newArray, 0, n);
newArray[n] = source;
return new PublisherAmb<>(newArray);
}
return null;
}
static final class PublisherAmbCoordinator<T>
implements Subscription, MultiReceiver, Trackable {
final PublisherAmbSubscriber<T>[] subscribers;
volatile boolean cancelled;
volatile int wip;
@SuppressWarnings("rawtypes")
static final AtomicIntegerFieldUpdater<PublisherAmbCoordinator> WIP =
AtomicIntegerFieldUpdater.newUpdater(PublisherAmbCoordinator.class, "wip");
@SuppressWarnings("unchecked")
public PublisherAmbCoordinator(int n) {
subscribers = new PublisherAmbSubscriber[n];
wip = Integer.MIN_VALUE;
}
void subscribe(Publisher<? extends T>[] sources, int n, Subscriber<? super T> actual) {
PublisherAmbSubscriber<T>[] a = subscribers;
for (int i = 0; i < n; i++) {
a[i] = new PublisherAmbSubscriber<>(actual, this, i);
}
actual.onSubscribe(this);
for (int i = 0; i < n; i++) {
if (cancelled || wip != Integer.MIN_VALUE) {
return;
}
Publisher<? extends T> p = sources[i];
if (p == null) {
if (WIP.compareAndSet(this, Integer.MIN_VALUE, -1)) {
actual.onError(new NullPointerException("The " + i + " th Publisher source is null"));
}
return;
}
p.subscribe(a[i]);
}
}
@Override
public void request(long n) {
if (SubscriptionHelper.validate(n)) {
int w = wip;
if (w >= 0) {
subscribers[w].request(n);
} else {
for (PublisherAmbSubscriber<T> s : subscribers) {
s.request(n);
}
}
}
}
@Override
public void cancel() {
if (cancelled) {
return;
}
cancelled = true;
int w = wip;
if (w >= 0) {
subscribers[w].cancel();
} else {
for (PublisherAmbSubscriber<T> s : subscribers) {
s.cancel();
}
}
}
boolean tryWin(int index) {
if (wip == Integer.MIN_VALUE) {
if (WIP.compareAndSet(this, Integer.MIN_VALUE, index)) {
PublisherAmbSubscriber<T>[] a = subscribers;
int n = a.length;
for (int i = 0; i < n; i++) {
if (i != index) {
a[i].cancel();
}
}
return true;
}
}
return false;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public Iterator<?> upstreams() {
return Arrays.asList(subscribers).iterator();
}
@Override
public long upstreamCount() {
return subscribers.length;
}
}
static final class PublisherAmbSubscriber<T> extends
DeferredSubscriptionSubscriber<T, T> {
final PublisherAmbCoordinator<T> parent;
final int index;
boolean won;
public PublisherAmbSubscriber(Subscriber<? super T> actual, PublisherAmbCoordinator<T> parent, int index) {
super(actual);
this.parent = parent;
this.index = index;
}
@Override
public void onNext(T t) {
if (won) {
subscriber.onNext(t);
} else if (parent.tryWin(index)) {
won = true;
subscriber.onNext(t);
}
}
@Override
public void onError(Throwable t) {
if (won) {
subscriber.onError(t);
} else if (parent.tryWin(index)) {
won = true;
subscriber.onError(t);
}
}
@Override
public void onComplete() {
if (won) {
subscriber.onComplete();
} else if (parent.tryWin(index)) {
won = true;
subscriber.onComplete();
}
}
}
}
|
923b047f05134fa55ac668f1f255830856ec2768 | 965 | java | Java | src/main/java/org/scaffoldeditor/worldexport/vcap/VcapMeta.java | Sam54123/mc-world-export | b82632d76f012121de389276880ddb2eed9e6661 | [
"MIT"
] | 2 | 2021-11-30T20:59:36.000Z | 2022-03-09T18:43:23.000Z | src/main/java/org/scaffoldeditor/worldexport/vcap/VcapMeta.java | Sam54123/mc-world-export | b82632d76f012121de389276880ddb2eed9e6661 | [
"MIT"
] | 2 | 2021-11-04T03:45:42.000Z | 2022-03-27T00:23:16.000Z | src/main/java/org/scaffoldeditor/worldexport/vcap/VcapMeta.java | Sam54123/mc-world-export | b82632d76f012121de389276880ddb2eed9e6661 | [
"MIT"
] | null | null | null | 28.382353 | 82 | 0.67772 | 999,424 | package org.scaffoldeditor.worldexport.vcap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.scaffoldeditor.worldexport.Constants;
/**
* Represents the general metadata for a VCap file.
*/
public class VcapMeta {
public String version = Constants.REPLAY_FORMAT_VERSION;
public String encoder = "Minecraft World Exporter";
public final List<String> faceLayers = new ArrayList<>();
/**
* A mapping of model IDs and the namespaced ids of the blocks they represent.
* Used to infer the block id of any block within the file.
*/
public final Map<String, String> blockTypes = new HashMap<>();
/**
* Create a VCap metadata object.
* @param numLayers The number of face layers in the file.
*/
public VcapMeta(int numLayers) {
for (int i = 0; i < numLayers; i++) {
faceLayers.add(MeshWriter.genGroupName(i));
}
}
}
|
923b04ce5e8a87c0c3a6671c5dae156869ccfccd | 4,419 | java | Java | src/main/java/com/intel/rfid/security/SecurityContext.java | john-belstner/rsp-sw-toolkit-gw | 076821f07777c9f0a59e7bb5b7793b0cd4a1f120 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/main/java/com/intel/rfid/security/SecurityContext.java | john-belstner/rsp-sw-toolkit-gw | 076821f07777c9f0a59e7bb5b7793b0cd4a1f120 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/main/java/com/intel/rfid/security/SecurityContext.java | john-belstner/rsp-sw-toolkit-gw | 076821f07777c9f0a59e7bb5b7793b0cd4a1f120 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 34.523438 | 113 | 0.647658 | 999,425 | /*
* Copyright (C) 2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.intel.rfid.security;
import com.intel.rfid.exception.ConfigException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.Security;
public class SecurityContext {
protected Logger log = LoggerFactory.getLogger(getClass());
private static SecurityContext instance;
public static SecurityContext instance() {
if (instance == null) {
instance = new SecurityContext();
}
return instance;
}
private KeyManager keyMgr;
private BouncyCastleProvider bouncyCastleProvider;
private SecurityContext() {
Security.addProvider(getBouncyCastleProvider());
}
public KeyManager getKeyMgr() {
if (keyMgr == null) { keyMgr = new KeyManager(); }
return keyMgr;
}
public BouncyCastleProvider getBouncyCastleProvider() {
if (bouncyCastleProvider == null) { bouncyCastleProvider = new BouncyCastleProvider(); }
return bouncyCastleProvider;
}
public SSLSocketFactory getSecureSocketFactory() {
SSLSocketFactory factory = null;
try {
// CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", getKeyMgr().getCACertificate());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(caKs);
// create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null, tmf.getTrustManagers(), null);
factory = context.getSocketFactory();
} catch (GeneralSecurityException | IOException _e) {
log.error("error creating secure socket factory: {}", _e.getMessage());
}
return factory;
}
public static final String[] ALLOWED_CIPHERS = {
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
"TLS_RSA_WITH_AES_256_CBC_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
"TLS_RSA_WITH_AES_128_CBC_SHA256"
};
public SslContextFactory getJettySslContextFactory() throws ConfigException {
SslContextFactory factory = new SslContextFactory();
KeyManager km = getKeyMgr();
factory.setKeyStoreType(km.getKeystoreType());
factory.setKeyStorePath(km.getKeystoryPath());
factory.setKeyStorePassword(km.getKeystorePassword());
factory.setIncludeCipherSuites(ALLOWED_CIPHERS);
if (log.isInfoEnabled()) {
StringBuilder sb = new StringBuilder();
for (String s : factory.getExcludeCipherSuites()) {
sb.append(s).append('\n');
}
log.info("excluded cipher suites:\n{}", sb.toString());
sb = new StringBuilder();
for (String s : factory.getIncludeCipherSuites()) {
sb.append(s).append('\n');
}
log.info("included cipher suites:\n{}", sb.toString());
sb = new StringBuilder();
for (String s : factory.getExcludeProtocols()) {
sb.append(s).append('\n');
}
log.info("excluded protocols:\n{}", sb.toString());
sb = new StringBuilder();
for (String s : factory.getIncludeProtocols()) {
sb.append(s).append('\n');
}
log.info("included protocols:\n{}", sb.toString());
}
return factory;
}
}
|
923b05495e77e0f52ad1a06842fe6c7fb7ce574a | 1,109 | java | Java | spring-session-2/src/main/java/com/api/config/SecurityConfig.java | helloworldtang/api-server | 6067ab0ba60159f691dbd920991b8168238e5b87 | [
"Apache-2.0"
] | 1 | 2017-04-06T05:32:06.000Z | 2017-04-06T05:32:06.000Z | spring-session-2/src/main/java/com/api/config/SecurityConfig.java | helloworldtang/api-server | 6067ab0ba60159f691dbd920991b8168238e5b87 | [
"Apache-2.0"
] | null | null | null | spring-session-2/src/main/java/com/api/config/SecurityConfig.java | helloworldtang/api-server | 6067ab0ba60159f691dbd920991b8168238e5b87 | [
"Apache-2.0"
] | null | null | null | 36.966667 | 107 | 0.714157 | 999,426 | package com.api.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* Created by tang.cheng on 2017/3/28.
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.permitAll().and()
.logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
|
923b06a82da1f329b738e3787e4ee37cb5c64cd9 | 3,944 | java | Java | library/src/main/java/quickutils/core/categories/voice.java | cesarferreira/AndroidQuickUtils | 73a91daedbb9f7be7986ea786fbc441c9e5a881c | [
"MIT"
] | 120 | 2015-01-14T05:58:41.000Z | 2021-10-02T02:32:12.000Z | library/src/main/java/quickutils/core/categories/voice.java | cesarferreira/AndroidQuickUtils | 73a91daedbb9f7be7986ea786fbc441c9e5a881c | [
"MIT"
] | 5 | 2015-02-28T01:48:57.000Z | 2016-09-06T10:35:16.000Z | library/src/main/java/quickutils/core/categories/voice.java | cesarferreira/AndroidQuickUtils | 73a91daedbb9f7be7986ea786fbc441c9e5a881c | [
"MIT"
] | 35 | 2015-01-11T09:47:30.000Z | 2019-07-02T10:06:20.000Z | 34 | 135 | 0.67571 | 999,427 | package quickutils.core.categories;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognizerIntent;
import java.util.ArrayList;
import java.util.List;
public class voice {
protected voice() {
}
/**
* Start google activity of speechRecognition (needed on
* onActivityResult(int requestCode, int resultCode, Intent data) to call
* getSpeechRecognitionResults() to get the results)
*
* @param activity
* - activity
* @param maxResults
* - Max number of results that you want to get
* @param text
* - what will ask to user when activity start
*/
public static void speechRecognition(final Activity activity, int maxResults, String text) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, text);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
activity.startActivityForResult(intent, 0);
}
/**
* Get all results from the Google Speech Recognition activity (DO NOT FORGET call this function on
* onActivityResult())
*
* @param requestCode
* - onActivityResult request code
* @param resultCode
* - onActivityResult result code
* @param data
* - onActivityResult Intent data
* @return ArrayList<String> with all results or null if was not possible to
* get any results
*/
public static ArrayList<String> getSpeechRecognitionResults(int requestCode, int resultCode, Intent data) {
ArrayList<String> matches = null;
if (requestCode == 0 && resultCode == -1) {
matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
StringBuilder sb = new StringBuilder();
for (String match : matches) {
sb.append(match + ", ");
}
}
return matches;
}
/**
* Get the first result that matches the Result List from Google Speech
* Recognition activity (DO NOT FORGET call this function on onActivityResult()) and the Dictionary
* given
*
* @param requestCode
* - onActivityResult request code
* @param resultCode
* - onActivityResult result code
* @param data
* - onActivityResult Intent data
* @param array
* - Dictionary with all keywords
*
* @return String with the first result matched or null if was not possible
* to get any result
*/
public static String getSpeechRecognitionResultFromDicionary(int requestCode, int resultCode, Intent data, ArrayList<String> array) {
ArrayList<String> matches = null;
if (requestCode == 0 && resultCode == -1) {
matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
StringBuilder sb = new StringBuilder();
for (String match : matches) {
for (String arrayString : array) {
if (arrayString.equals(match)) {
return match;
}
}
}
}
return null;
}
/**
* Get first result from the Google Speech Recognition activity (DO NOT FORGET call this function on
* onActivityResult())
*
* @param requestCode
* - onActivityResult request code
* @param resultCode
* - onActivityResult result code
* @param data
* - onActivityResult Intent data
* @return string containing the first result of what was recognized
*/
public static String getSpeechRecognitionFirstResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == -1) {
List<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (results != null && results.size() > 0) {
return results.get(0);
}
}
return null;
}
}
|
923b08686d4bb7df32ca77822f16c77cfb676be0 | 2,555 | java | Java | src/pactTest/java/uk/gov/hmcts/probate/services/submit/controllers/v2/consumer/ccd/GetCaseConsumerTest.java | hmcts/probate-submit-service | dd8b43e4c5423988c9ff9629c1615af184d844c8 | [
"MIT"
] | null | null | null | src/pactTest/java/uk/gov/hmcts/probate/services/submit/controllers/v2/consumer/ccd/GetCaseConsumerTest.java | hmcts/probate-submit-service | dd8b43e4c5423988c9ff9629c1615af184d844c8 | [
"MIT"
] | 308 | 2018-06-08T18:11:59.000Z | 2021-08-02T13:48:01.000Z | src/pactTest/java/uk/gov/hmcts/probate/services/submit/controllers/v2/consumer/ccd/GetCaseConsumerTest.java | hmcts/probate-submit-service | dd8b43e4c5423988c9ff9629c1615af184d844c8 | [
"MIT"
] | 1 | 2021-04-10T22:41:03.000Z | 2021-04-10T22:41:03.000Z | 44.051724 | 114 | 0.717025 | 999,428 | package uk.gov.hmcts.probate.services.submit.controllers.v2.consumer.ccd;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.RequestResponsePact;
import au.com.dius.pact.core.model.annotations.Pact;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import uk.gov.hmcts.reform.ccd.client.model.CaseDetails;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static uk.gov.hmcts.probate.services.submit.controllers.v2.consumer.util.AssertionHelper.assertCaseDetails;
import static uk.gov.hmcts.reform.probate.pact.dsl.PactDslBuilderForCaseDetailsList.buildCaseResourcesDsl;
public class GetCaseConsumerTest extends AbstractProbateSubmitServicePact {
private static final String BASECASE_PAYLOAD_PATH = "json/base-case.json";
@Pact(provider = "ccdDataStoreAPI_Cases", consumer = "probate_submitService")
RequestResponsePact getCaseDetails(PactDslWithProvider builder) throws Exception {
// @formatter:off
return builder
.given("A Get Case is requested", setUpStateMapForProviderWithCaseData(createEventId))
.uponReceiving("A Get for a Case is requested")
.path("/cases/" + CASE_ID)
.method("GET")
.headers(HttpHeaders.AUTHORIZATION,
SOME_AUTHORIZATION_TOKEN,
SERVICE_AUTHORIZATION,
SOME_SERVICE_AUTHORIZATION_TOKEN, "experimental",
"true")
.willRespondWith()
.status(200)
.body(buildCaseResourcesDsl(100L, false, false))
.matchHeader(HttpHeaders.CONTENT_TYPE,
"application/vnd\\.uk\\.gov\\.hmcts\\.ccd-data-store-api\\.case\\.v2\\+json;charset=UTF-8",
"application/vnd.uk.gov.hmcts.ccd-data-store-api.case.v2+json;charset=UTF-8")
.toPact();
}
@Test
@PactTestFor(pactMethod = "getCaseDetails")
public void verifyGetCaseDetails() throws Exception {
caseDataContent = getCaseDataContent(EVENT_ID, BASECASE_PAYLOAD_PATH);
final CaseDetails caseDetails = coreCaseDataApi.getCase(SOME_AUTHORIZATION_TOKEN,
SOME_SERVICE_AUTHORIZATION_TOKEN, CASE_ID.toString());
assertThat(caseDetails.getJurisdiction(), is("PROBATE"));
assertThat(caseDetails.getState(), is(notNullValue()));
assertCaseDetails(caseDetails);
}
}
|
923b0b258a6e0b880308db9c5b218211b7a76ddc | 2,476 | java | Java | Debug 1.2.6/cn/kody/debug/mod/mods/WORLD/MurderFinder.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | 3 | 2022-02-28T17:34:51.000Z | 2022-03-06T21:55:16.000Z | Debug 1.2.6/cn/kody/debug/mod/mods/WORLD/MurderFinder.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | 2 | 2022-02-25T20:10:14.000Z | 2022-03-03T14:25:03.000Z | Debug 1.2.6/cn/kody/debug/mod/mods/WORLD/MurderFinder.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | null | null | null | 41.266667 | 114 | 0.580372 | 999,429 | package cn.kody.debug.mod.mods.WORLD;
import com.darkmagician6.eventapi.EventTarget;
import cn.kody.debug.events.EventUpdate;
import cn.kody.debug.mod.Category;
import cn.kody.debug.mod.Mod;
import cn.kody.debug.ui.Notification;
import cn.kody.debug.utils.HBTimer;
import cn.kody.debug.utils.Type;
import net.minecraft.block.Block;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemSword;
import java.util.Iterator;
public class MurderFinder extends Mod
{
HBTimer time;
public MurderFinder() {
super("MurderFinder", "Murder Finder", Category.WORLD);
this.time = new HBTimer();
}
@EventTarget
public void onUpdate(final EventUpdate eventUpdate) {
for (final Entity next : this.mc.theWorld.loadedEntityList) {
if (!(next instanceof EntityPlayer) && next instanceof EntityPlayerSP) {
final EntityPlayer entity = (EntityPlayer) next;
int i = 0;
while (i < 1) {
if (entity != null
&& entity.getName() != this.mc.thePlayer.getName()
&& (((EntityPlayer) entity).getHeldItem().getItem() == Items.iron_shovel
|| entity.getHeldItem().getItem() == Items.stick
|| entity.getHeldItem().getItem() == Items.wooden_axe
|| entity.getHeldItem().getItem() instanceof ItemSword
|| entity.getHeldItem().getItem() == Items.stone_shovel
|| entity.getHeldItem().getItem() == Items.blaze_rod
|| entity.getHeldItem().getItem() == Items.diamond_shovel
|| entity.getHeldItem().getItem() == Items.feather
|| entity.getHeldItem().getItem() == Items.carrot_on_a_stick
|| entity.getHeldItem().getItem() == Items.bone
|| entity.getHeldItem().getItem() == Items.golden_carrot
|| entity.getHeldItem().getItem() == Items.diamond_hoe
|| entity.getHeldItem().getItem() == Items.shears)) {
Notification.tellPlayer("This is Murdurer: " + entity.getName().toUpperCase(), Type.WARN);
}
++i;
}
}
}
}
}
|
923b0bb3ba555b7b0b27780e0951b04236ef545a | 242 | java | Java | Quad.java | sakshampuri/Calculator | 30d9bbba73997baea83f78f2a0c9a4bcc1325b82 | [
"Unlicense"
] | null | null | null | Quad.java | sakshampuri/Calculator | 30d9bbba73997baea83f78f2a0c9a4bcc1325b82 | [
"Unlicense"
] | null | null | null | Quad.java | sakshampuri/Calculator | 30d9bbba73997baea83f78f2a0c9a4bcc1325b82 | [
"Unlicense"
] | null | null | null | 24.2 | 54 | 0.5 | 999,430 | public class Quad
{
public static String solveQuad(int a,int b,int c)
{
double x1=((-b)+(Math.sqrt(b*b-4*a*c)))/(2*a);
double x2=((-b)-(Math.sqrt(b*b-4*a*c)))/(2*a);
return ("Solutions: "+x1+" , "+x2);
}
}
|
923b0be02a62a8e966ecf8d26f15c4e4becafb9f | 10,615 | java | Java | src/main/java/com/dua3/meja/model/Workbook.java | xzel23/meja | 9e68ad180649828adeeffebc6e3097c35f5b6a1a | [
"Apache-2.0"
] | 7 | 2015-05-06T21:53:45.000Z | 2018-05-17T03:50:13.000Z | src/main/java/com/dua3/meja/model/Workbook.java | xzel23/meja | 9e68ad180649828adeeffebc6e3097c35f5b6a1a | [
"Apache-2.0"
] | 16 | 2015-04-08T17:01:59.000Z | 2022-01-02T07:18:04.000Z | src/main/java/com/dua3/meja/model/Workbook.java | xzel23/meja | 9e68ad180649828adeeffebc6e3097c35f5b6a1a | [
"Apache-2.0"
] | null | null | null | 29.231405 | 113 | 0.621336 | 999,431 | /*
* Copyright 2015 Axel Howind (efpyi@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 com.dua3.meja.model;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import com.dua3.meja.io.FileType;
import com.dua3.meja.util.Options;
/**
* Workbook class.
* <p>
* A workbook consists of different sheets which can be accessed by number or
* name. Use one of the concrete implementations of {@link WorkbookFactory} to
* read a workbook from disk.
* </p>
*
* @author axel
*/
public interface Workbook extends AutoCloseable, Iterable<Sheet> {
public final String PROPERTY_ACTIVE_SHEET = "ACTIVE_SHEET";
public final String PROPERTY_SHEET_ADDED = "SHEET_ADDED";
public final String PROPERTY_SHEET_REMOVED = "SHEET_REMOVED";
/**
* Add property change listener.
*
* @see PropertyChangeSupport#addPropertyChangeListener(PropertyChangeListener)
* @param listener the listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener);
/**
* Add property change listener.
*
* @see PropertyChangeSupport#addPropertyChangeListener(String,
* PropertyChangeListener)
* @param propertyName the property name
* @param listener the listener
*/
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener);
/**
* Close workbook.
*
* @throws IOException if an I/O error occurs
*/
@Override
void close() throws IOException;
/**
* Copy workbook data from another workbook.
*
* @param other workbook to copy
*/
default void copy(Workbook other) {
// copy styles
for (String styleName : other.getCellStyleNames()) {
CellStyle cellStyle = other.getCellStyle(styleName);
CellStyle newCellStyle = getCellStyle(styleName);
newCellStyle.copyStyle(cellStyle);
}
// copy sheets
for (int sheetNr = 0; sheetNr < other.getSheetCount(); sheetNr++) {
Sheet sheet = other.getSheet(sheetNr);
Sheet newSheet = createSheet(sheet.getSheetName());
newSheet.copy(sheet);
}
}
/**
* Register a copy of a cell style.
*
* @param styleName name for this cell style.
* @param style the style to copy
* @return the new cell style
*/
CellStyle copyCellStyle(String styleName, CellStyle style);
/**
* Add a new sheet as last sheet of this workbook.
*
* @param sheetName the name of the sheet
* @return the new sheet
*/
Sheet createSheet(String sheetName);
/**
* Get registered cell style. If no style is registered under {@code name}, a
* new one is created.
*
* @param name cell style name
* @return the registered cell style for {@code name}
*/
CellStyle getCellStyle(String name);
/**
* Get names of all cell styles.
*
* @return list of cell style names
*/
List<String> getCellStyleNames();
/**
* Get the current sheet.
*
* @return the current sheet.
* @throws IllegalArgumentException if the current sheet does not exist (i.e.
* the workbook does not contain any sheets)
*/
Sheet getCurrentSheet();
/**
* Get index of current sheet.
*
* @return index of current sheet
*/
int getCurrentSheetIndex();
/**
* Get default cell style for this workbook.
*
* @return the default cell style
*/
CellStyle getDefaultCellStyle();
/**
* Get sheet by number.
*
* @param sheetNr number of sheet
* @return sheet
* @throws IndexOutOfBoundsException if no sheet exists at the given index
*/
Sheet getSheet(int sheetNr);
/**
* Get sheet by name.
*
* @param sheetName name of sheet
* @return sheet
* @throws IllegalArgumentException if no sheet exists with the given name
*/
default Sheet getSheetByName(String sheetName) {
int idx = getSheetIndexByName(sheetName);
if (idx < 0) {
throw new IllegalArgumentException("No sheet with name '" + sheetName + "'.");
}
return getSheet(idx);
}
/**
* Returns number of sheets in this workbook.
*
* @return sheet
*/
int getSheetCount();
/**
* Get index of sheet by name.
*
* @param sheetName name of sheet
* @return index of sheet or -1 if no sheet with this name exists
*/
default int getSheetIndexByName(String sheetName) {
int idx = 0;
for (Sheet sheet : this) {
if (sheet.getSheetName().equals(sheetName)) {
return idx;
}
idx++;
}
return -1;
}
/**
* Get the Path for this workbook.
*
* <p>
* When a workbook is opened, the Path is set so that it can be used to later
* save the workbook back to the same location.
* </p>
*
* @return the Path for this workbook
*/
Optional<Path> getPath();
/**
* Check if a style with this name is defined.
*
* @param name the name of the cell style
* @return true, if style is present
*/
boolean hasCellStyle(String name);
boolean isObjectCachingEnabled();
/**
* Remove property change listener.
*
* @see PropertyChangeSupport#removePropertyChangeListener(PropertyChangeListener)
* @param listener the listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener);
/**
* Remove property change listener.
*
* @see PropertyChangeSupport#removePropertyChangeListener(String,
* PropertyChangeListener)
* @param propertyName the name of the property
* @param listener the listener
*/
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener);
/**
* Remove sheet by number.
*
* @param idx number of sheet
* @throws IndexOutOfBoundsException if no sheet exists at the given index
*/
void removeSheet(int idx);
/**
* Remove sheet by name.
*
* @param sheetName name of sheet
* @throws IllegalArgumentException if no sheet exists with the given name
*/
default void removeSheetByName(String sheetName) {
int idx = getSheetIndexByName(sheetName);
if (idx < 0) {
throw new IllegalArgumentException("No sheet with name '" + sheetName + "'.");
}
removeSheet(idx);
}
/**
* Set the current sheet.
*
* @param idx index of the sheet to make current
* @throws IndexOutOfBoundsException if no sheet exists at the given index
*/
void setCurrentSheet(int idx);
void setObjectCaching(boolean enabled);
/**
* Set Path for this workbook. See {@link #getPath}.
*
* @param path the Path to set.
*/
void setPath(Path path);
/**
* Writes the workbook to a path using standard options.
*
* @param path the path to write to.
* <p>
* The file format to used is determined by the extension of
* {@code path} which must be one of the extensions defined in
* {@link FileType}.
* </p>
* @throws java.io.IOException if an I/O error occurs
*/
default void write(Path path) throws IOException {
write(path, Options.empty());
}
/**
* Writes the workbook to a file.
*
* @param path the path to write to.
* <p>
* The file format to used is determined by the extension of
* {@code path} which must be one of the extensions defined in
* {@link FileType}.
* </p>
* @param options special options to use (supported options depend on the file
* type)
* @throws java.io.IOException if an I/O error occurs
*/
default void write(Path path, Options options) throws IOException {
FileType type = FileType.forPath(path).orElse(FileType.CSV);
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) {
write(type, out, options);
}
}
/**
* Writes the workbook to a stream using default options.
*
* @param fileType the file type to use
* @param out output stream to write to
* @throws java.io.IOException if an I/O error occurs
*/
default void write(FileType fileType, OutputStream out) throws IOException {
write(fileType, out, Options.empty());
}
/**
* Writes the workbook to a stream.
*
* @param fileType the file type to use
* @param out output stream to write to
* @param options special options to use (supported options depend on the file
* type)
* @throws java.io.IOException if an I/O error occurs
*/
void write(FileType fileType, OutputStream out, Options options) throws IOException;
/**
* Get cached instance of object.
*
* @param <T> object type
* @param obj the object to lookup
* @return the cached instance, if an instance equal to {@code obj} is present
* in the cache, {@code obj} otherwise
*
*/
<T> T cache(T obj);
/**
* Create a stream of the rows in this sheet.
*
* @return stream of rows
*/
default Stream<Sheet> sheets() {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator(), Spliterator.ORDERED), false);
}
}
|
923b0c35ea557fb9bebc1a7af23a94f6197b5b41 | 5,027 | java | Java | src/javacode/Audio/WaveFile.java | jeffrypig23/Mayterm | 8f12a6d598844530d51596a8902fa0e64b2d6bc9 | [
"Unlicense"
] | 3 | 2018-08-27T14:41:50.000Z | 2019-07-18T21:19:50.000Z | src/javacode/Audio/WaveFile.java | yeSpud/Mayterm | 8f12a6d598844530d51596a8902fa0e64b2d6bc9 | [
"Unlicense"
] | 3 | 2019-10-03T20:00:14.000Z | 2019-10-10T04:26:32.000Z | src/javacode/Audio/WaveFile.java | jeffrypig23/Mayterm | 8f12a6d598844530d51596a8902fa0e64b2d6bc9 | [
"Unlicense"
] | null | null | null | 26.739362 | 114 | 0.702407 | 999,432 | package javacode.Audio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ShortBuffer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javacode.Database.Environment;
import javacode.Errors.UnrecognizableOperatingSystem;
import javacode.SpectrumAlg.FFT.FTTVis;
/**
* Class responsible for analyzing a .wav file. <br>
* Taken from <a href =
* 'https://stackoverflow.com/questions/39313634/extract-amplitude-array-from-a-wav-file-using-java/39425678'>this
* stackoverflow question</a>, and modified to fit my use.
*
* @author Artem Novikov, Spud
*
*/
public class WaveFile {
public final int NOT_SPECIFIED = AudioSystem.NOT_SPECIFIED; // -1
public final int INT_SIZE = 4;
private int sampleSize = NOT_SPECIFIED;
private long framesCount = NOT_SPECIFIED;
private int sampleRate = NOT_SPECIFIED;
private int channelsNum;
private byte[] data; // wav bytes
private AudioInputStream ais;
private AudioFormat af;
private Clip clip;
private boolean canPlay;
/**
* Constructor for WaveFile.
*
* @param file
* - the .wav file.
* @throws UnsupportedAudioFileException Thrown if the file is not supported.
* @throws IOException Thrown due to some IO error. I dunno, never encountered this error in testing ¯\_(ツ)_/¯
*/
public WaveFile(File file) throws UnsupportedAudioFileException, IOException {
// Check if the file exists
if (!file.exists()) {
throw new FileNotFoundException(file.getAbsolutePath());
}
File newFile;
try {
newFile = new File(Environment.getWavFile().getAbsolutePath());
} catch (UnrecognizableOperatingSystem e1) {
e1.printStackTrace();
return;
}
newFile.createNewFile();
ais = AudioSystem.getAudioInputStream(newFile);
af = ais.getFormat();
framesCount = ais.getFrameLength();
sampleRate = (int) af.getSampleRate();
sampleSize = af.getSampleSizeInBits() / 8;
channelsNum = af.getChannels();
long dataLength = framesCount * af.getSampleSizeInBits() * af.getChannels() / 8;
data = new byte[(int) dataLength];
ais.read(data);
AudioInputStream aisForPlay = AudioSystem.getAudioInputStream(newFile);
try {
clip = AudioSystem.getClip();
clip.open(aisForPlay);
clip.setFramePosition((int) FTTVis.timestamp);
canPlay = true;
} catch (LineUnavailableException e) {
canPlay = false;
System.out.println("I can play only 8bit and 16bit music.");
}
clip.close();
}
/**
* Returns a boolean as to whether or not the file can be played.
*
* @return Boolean - whether or not the file can be played.
*/
public boolean isCanPlay() {
return canPlay;
}
/**
* Returns the current sample rate.
*
* @return int - the sample rate
*/
public int getSampleRate() {
return sampleRate;
}
/**
* Returns the <code>AudioFomat</code> of the file.
*
* @return AudioFormat - The AudioFormat of the file.
*/
public AudioFormat getAudioFormat() {
return af;
}
/**
* Returns the current sample size.
*
* @return int - The sample size.
*/
public int getSampleSize() {
return sampleSize;
}
/**
* Returns the duration.
*
* @return double - Duration
*/
public double getDurationTime() {
return getFramesCount() / getAudioFormat().getFrameRate();
}
/**
* Returns the number of frames.
*
* @return long - framesCount
*/
public long getFramesCount() {
return framesCount;
}
/**
* Returns sample (amplitude value).<br >
* Note that in case of stereo samples go one after another. I.e. 0 - first
* sample of left channel, 1 - first sample of the right channel, 2 - second
* sample of the left channel, 3 - second sample of the right channel, etc.
*
* @param sampleNumber
* - The sample number
* @return int - The sample.
*
*/
public int getSampleInt(int sampleNumber) {
if (sampleNumber < 0 || sampleNumber >= data.length / sampleSize) {
throw new IllegalArgumentException("sample number can't be < 0 or >= data.length/" + sampleSize);
}
short[] sampleBytes = new short[4]; // 4byte = int, but they need to be shorts due to overflow issues :P
short firstSampleByte[] = new short[2];
short secondSampleByte[] = new short[2];
short[] NEWsampleBytes = new short[4]; // 4byte = int
for (int i = 0; i < sampleSize; i++) {
sampleBytes[i] = data[sampleNumber * sampleSize * channelsNum + i];
}
firstSampleByte[0] = sampleBytes[0];
firstSampleByte[1] = sampleBytes[1];
secondSampleByte[0] = sampleBytes[2];
secondSampleByte[1] = sampleBytes[3];
NEWsampleBytes[0] = secondSampleByte[0];
NEWsampleBytes[1] = secondSampleByte[1];
NEWsampleBytes[2] = firstSampleByte[0];
NEWsampleBytes[3] = firstSampleByte[1];
int sample = ShortBuffer.wrap(NEWsampleBytes).get(3);
return sample;
}
} |
923b0c67a00af2b143f256e08d900868ec8e9b41 | 2,397 | java | Java | src/main/java/com/microsoft/graph/requests/extensions/CalendarPermissionCollectionRequestBuilder.java | Krisoblucki-okta/msgraph-sdk-java | 8e1960974f24aef28d8a0fde5a786a33c2f9cb3a | [
"MIT"
] | null | null | null | src/main/java/com/microsoft/graph/requests/extensions/CalendarPermissionCollectionRequestBuilder.java | Krisoblucki-okta/msgraph-sdk-java | 8e1960974f24aef28d8a0fde5a786a33c2f9cb3a | [
"MIT"
] | 22 | 2020-09-17T05:53:52.000Z | 2022-02-14T01:03:31.000Z | src/main/java/com/microsoft/graph/requests/extensions/CalendarPermissionCollectionRequestBuilder.java | Krisoblucki-okta/msgraph-sdk-java | 8e1960974f24aef28d8a0fde5a786a33c2f9cb3a | [
"MIT"
] | null | null | null | 45.226415 | 189 | 0.739257 | 999,433 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.Calendar;
import com.microsoft.graph.models.extensions.CalendarPermission;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.requests.extensions.ICalendarPermissionCollectionRequestBuilder;
import com.microsoft.graph.requests.extensions.ICalendarPermissionRequestBuilder;
import com.microsoft.graph.requests.extensions.ICalendarPermissionCollectionRequest;
import com.microsoft.graph.http.BaseRequestBuilder;
import com.microsoft.graph.core.IBaseClient;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Calendar Permission Collection Request Builder.
*/
public class CalendarPermissionCollectionRequestBuilder extends BaseRequestBuilder implements ICalendarPermissionCollectionRequestBuilder {
/**
* The request builder for this collection of Calendar
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public CalendarPermissionCollectionRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
public ICalendarPermissionCollectionRequest buildRequest() {
return buildRequest(getOptions());
}
public ICalendarPermissionCollectionRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
return new CalendarPermissionCollectionRequest(getRequestUrl(), getClient(), requestOptions);
}
public ICalendarPermissionRequestBuilder byId(final String id) {
return new CalendarPermissionRequestBuilder(getRequestUrlWithAdditionalSegment(id), getClient(), getOptions());
}
}
|
923b0ca252f1e40f08bc0d8b565baead288a2a40 | 2,698 | java | Java | src/test/java/hu/akarnokd/reactive4javaflow/TestSchedulerServiceTest.java | akarnokd/Reactive4JavaFlow | b5438d45f60c749676aa057f16baec21706704b7 | [
"Apache-2.0"
] | 49 | 2017-07-28T01:54:15.000Z | 2022-02-13T18:44:23.000Z | src/test/java/hu/akarnokd/reactive4javaflow/TestSchedulerServiceTest.java | akarnokd/Reactive4JavaFlow | b5438d45f60c749676aa057f16baec21706704b7 | [
"Apache-2.0"
] | 46 | 2017-12-25T17:08:23.000Z | 2022-02-28T04:30:16.000Z | src/test/java/hu/akarnokd/reactive4javaflow/TestSchedulerServiceTest.java | akarnokd/Reactive4JavaFlow | b5438d45f60c749676aa057f16baec21706704b7 | [
"Apache-2.0"
] | 4 | 2017-08-18T05:55:32.000Z | 2022-03-08T12:00:45.000Z | 26.45098 | 105 | 0.634544 | 999,434 | /*
* Copyright 2017 David Karnok
*
* 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 hu.akarnokd.reactive4javaflow;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class TestSchedulerServiceTest implements Runnable {
TestSchedulerService scheduler = new TestSchedulerService();
int counter;
@Override
public void run() {
counter++;
}
@Test
public void scheduleDirect() {
scheduler.schedule(this);
scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);
assertEquals(1, counter);
}
@Test
public void scheduleDirectPeriodically() {
scheduler.schedulePeriodically(this, 1, 1, TimeUnit.MILLISECONDS);
scheduler.advanceTimeBy(3, TimeUnit.MILLISECONDS);
assertEquals(3, counter);
}
@Test
public void workerRejected() {
SchedulerService.Worker w = scheduler.worker();
w.close();
assertSame(SchedulerService.REJECTED, w.schedule(this));
assertSame(SchedulerService.REJECTED, w.schedule(this, 1, TimeUnit.MILLISECONDS));
assertSame(SchedulerService.REJECTED, w.schedulePeriodically(this, 1, 1, TimeUnit.MILLISECONDS));
}
@Test
public void workerRejectedRace1() {
for (int i = 0; i < 1000; i++) {
SchedulerService.Worker w = scheduler.worker();
Runnable r1 = w::close;
Runnable r2 = () -> w.schedule(this);
TestHelper.race(r1, r2);
}
}
@Test
public void workerRejectedRace2() {
for (int i = 0; i < 1000; i++) {
SchedulerService.Worker w = scheduler.worker();
Runnable r1 = w::close;
Runnable r2 = () -> w.schedule(this, 1, TimeUnit.MILLISECONDS);
TestHelper.race(r1, r2);
}
}
@Test
public void workerRejectedRace3() {
for (int i = 0; i < 1000; i++) {
SchedulerService.Worker w = scheduler.worker();
Runnable r1 = w::close;
Runnable r2 = () -> w.schedulePeriodically(this, 1, 1, TimeUnit.MILLISECONDS);
TestHelper.race(r1, r2);
}
}
}
|
923b0d151867abd8888c51592fbec7d74c88e99f | 5,450 | java | Java | spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java | aleksandarsajdovski/jenkins2-course-spring-boot | 6dcf7b1ee4dde2b8f5ceba58d2240a9130dded6e | [
"Apache-2.0"
] | 90 | 2016-09-04T09:17:09.000Z | 2021-01-25T03:50:54.000Z | spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java | aleksandarsajdovski/jenkins2-course-spring-boot | 6dcf7b1ee4dde2b8f5ceba58d2240a9130dded6e | [
"Apache-2.0"
] | 225 | 2021-03-10T01:27:30.000Z | 2021-09-15T01:03:46.000Z | spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java | aleksandarsajdovski/jenkins2-course-spring-boot | 6dcf7b1ee4dde2b8f5ceba58d2240a9130dded6e | [
"Apache-2.0"
] | 1,574 | 2016-08-30T04:09:26.000Z | 2022-03-24T08:14:58.000Z | 27.114428 | 89 | 0.701651 | 999,435 | /*
* Copyright 2012-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.boot.cli.infrastructure;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.util.Assert;
/**
* Utility to invoke the command line in the same way as a user would, i.e. via the shell
* script in the package's bin directory.
*
* @author Andy Wilkinson
* @author Phillip Webb
*/
public final class CommandLineInvoker {
private final File workingDirectory;
public CommandLineInvoker() {
this(new File("."));
}
public CommandLineInvoker(File workingDirectory) {
this.workingDirectory = workingDirectory;
}
public Invocation invoke(String... args) throws IOException {
return new Invocation(runCliProcess(args));
}
private Process runCliProcess(String... args) throws IOException {
List<String> command = new ArrayList<String>();
command.add(findLaunchScript().getAbsolutePath());
command.addAll(Arrays.asList(args));
ProcessBuilder processBuilder = new ProcessBuilder(command)
.directory(this.workingDirectory);
processBuilder.environment().remove("JAVA_OPTS");
return processBuilder.start();
}
private File findLaunchScript() {
File dir = new File("target");
dir = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory() && pathname.getName().contains("-bin");
}
})[0];
dir = new File(dir,
dir.getName().replace("-bin", "").replace("spring-boot-cli", "spring"));
dir = new File(dir, "bin");
File launchScript = new File(dir, isWindows() ? "spring.bat" : "spring");
Assert.state(launchScript.exists() && launchScript.isFile(),
"Could not find CLI launch script " + launchScript.getAbsolutePath());
return launchScript;
}
private boolean isWindows() {
return File.separatorChar == '\\';
}
/**
* An ongoing Process invocation.
*/
public static final class Invocation {
private final StringBuffer err = new StringBuffer();
private final StringBuffer out = new StringBuffer();
private final StringBuffer combined = new StringBuffer();
private final Process process;
private final List<Thread> streamReaders = new ArrayList<Thread>();
public Invocation(Process process) {
this.process = process;
this.streamReaders.add(new Thread(new StreamReadingRunnable(
this.process.getErrorStream(), this.err, this.combined)));
this.streamReaders.add(new Thread(new StreamReadingRunnable(
this.process.getInputStream(), this.out, this.combined)));
for (Thread streamReader : this.streamReaders) {
streamReader.start();
}
}
public String getOutput() {
return postProcessLines(getLines(this.combined));
}
public String getErrorOutput() {
return postProcessLines(getLines(this.err));
}
public String getStandardOutput() {
return postProcessLines(getStandardOutputLines());
}
public List<String> getStandardOutputLines() {
return getLines(this.out);
}
private String postProcessLines(List<String> lines) {
StringWriter out = new StringWriter();
PrintWriter printOut = new PrintWriter(out);
for (String line : lines) {
if (!line.startsWith("Maven settings decryption failed")) {
printOut.println(line);
}
}
return out.toString();
}
private List<String> getLines(StringBuffer buffer) {
BufferedReader reader = new BufferedReader(
new StringReader(buffer.toString()));
String line;
List<String> lines = new ArrayList<String>();
try {
while ((line = reader.readLine()) != null) {
if (!line.startsWith("Picked up ")) {
lines.add(line);
}
}
}
catch (IOException ex) {
throw new RuntimeException("Failed to read output");
}
return lines;
}
public int await() throws InterruptedException {
for (Thread streamReader : this.streamReaders) {
streamReader.join();
}
return this.process.waitFor();
}
/**
* {@link Runnable} to copy stream output.
*/
private final class StreamReadingRunnable implements Runnable {
private final InputStream stream;
private final StringBuffer[] outputs;
private final byte[] buffer = new byte[4096];
private StreamReadingRunnable(InputStream stream, StringBuffer... outputs) {
this.stream = stream;
this.outputs = outputs;
}
@Override
public void run() {
int read;
try {
while ((read = this.stream.read(this.buffer)) > 0) {
for (StringBuffer output : this.outputs) {
output.append(new String(this.buffer, 0, read));
}
}
}
catch (IOException ex) {
// Allow thread to die
}
}
}
}
}
|
923b0da04690e16a175a34087a7f26792f2a9ba4 | 3,826 | java | Java | src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSContainer.java | Vilsol/NMSWrapper | 4736cca94f5a668e219a78ef9ae4746137358e6e | [
"Apache-2.0"
] | 1 | 2016-03-06T05:08:02.000Z | 2016-03-06T05:08:02.000Z | src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSContainer.java | Vilsol/NMSWrapper | 4736cca94f5a668e219a78ef9ae4746137358e6e | [
"Apache-2.0"
] | null | null | null | src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSContainer.java | Vilsol/NMSWrapper | 4736cca94f5a668e219a78ef9ae4746137358e6e | [
"Apache-2.0"
] | null | null | null | 36.438095 | 157 | 0.691845 | 999,436 | package me.vilsol.nmswrapper.wraps.unparsed;
import me.vilsol.nmswrapper.NMSWrapper;
import me.vilsol.nmswrapper.reflections.ReflectiveClass;
import me.vilsol.nmswrapper.reflections.ReflectiveMethod;
import me.vilsol.nmswrapper.wraps.NMSItemStack;
import me.vilsol.nmswrapper.wraps.NMSWrap;
import org.bukkit.inventory.InventoryView;
@ReflectiveClass(name = "Container")
public class NMSContainer extends NMSWrap {
public NMSContainer(Object nmsObject){
super(nmsObject);
}
public NMSContainer(String nmsName, Object[] paramTypes, Object[] params) {
super(nmsName, paramTypes, params);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.Container#a(net.minecraft.server.v1_9_R1.TileEntity)
*/
@ReflectiveMethod(name = "a", types = {NMSTileEntity.class})
public int a(NMSTileEntity tileEntity){
return (int) NMSWrapper.getInstance().exec(nmsObject, tileEntity);
}
/**
* @see net.minecraft.server.v1_9_R1.Container#addSlotListener(net.minecraft.server.v1_9_R1.ICrafting)
*/
@ReflectiveMethod(name = "addSlotListener", types = {NMSICrafting.class})
public void addSlotListener(NMSICrafting iCrafting){
NMSWrapper.getInstance().exec(nmsObject, iCrafting);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.Container#b(net.minecraft.server.v1_9_R1.IInventory)
*/
@ReflectiveMethod(name = "b", types = {NMSIInventory.class})
public int b(NMSIInventory iInventory){
return (int) NMSWrapper.getInstance().exec(nmsObject, iInventory);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.Container#c(int)
*/
@ReflectiveMethod(name = "c", types = {int.class})
public int c(int i){
return (int) NMSWrapper.getInstance().exec(nmsObject, i);
}
/**
* @see net.minecraft.server.v1_9_R1.Container#clickItem(int, int, int, net.minecraft.server.v1_9_R1.EntityHuman)
*/
@ReflectiveMethod(name = "clickItem", types = {int.class, int.class, int.class, NMSEntityHuman.class})
public NMSItemStack clickItem(int i, int i1, int i2, NMSEntityHuman entityHuman){
return new NMSItemStack(NMSWrapper.getInstance().exec(nmsObject, i, i1, i2, entityHuman));
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.Container#d()
*/
@ReflectiveMethod(name = "d", types = {})
public void d(){
NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.Container#getBukkitView()
*/
@ReflectiveMethod(name = "getBukkitView", types = {})
public InventoryView getBukkitView(){
return (InventoryView) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.Container#getSlot(int)
*/
@ReflectiveMethod(name = "getSlot", types = {int.class})
public NMSSlot getSlot(int i){
return new NMSSlot(NMSWrapper.getInstance().exec(nmsObject, i));
}
/**
* @see net.minecraft.server.v1_9_R1.Container#setItem(int, net.minecraft.server.v1_9_R1.ItemStack)
*/
@ReflectiveMethod(name = "setItem", types = {int.class, NMSItemStack.class})
public void setItem(int i, NMSItemStack itemStack){
NMSWrapper.getInstance().exec(nmsObject, i, itemStack);
}
/**
* @see net.minecraft.server.v1_9_R1.Container#transferTo(net.minecraft.server.v1_9_R1.Container, org.bukkit.craftbukkit.v1_9_R1.entity.CraftHumanEntity)
*/
@ReflectiveMethod(name = "transferTo", types = {NMSContainer.class, NMSCraftHumanEntity.class})
public void transferTo(NMSContainer container, NMSCraftHumanEntity craftHumanEntity){
NMSWrapper.getInstance().exec(nmsObject, container, craftHumanEntity);
}
} |
923b0db6489445233fef3bc11d28444e5b19fc25 | 8,332 | java | Java | bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableTableAdminClientWrapper.java | zendesk/cloud-bigtable-client | d194263ffa1071151b4b85a66c1cc9168fb7795e | [
"Apache-2.0"
] | 2 | 2019-06-06T00:51:47.000Z | 2020-09-27T14:48:52.000Z | bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableTableAdminClientWrapper.java | zendesk/cloud-bigtable-client | d194263ffa1071151b4b85a66c1cc9168fb7795e | [
"Apache-2.0"
] | null | null | null | bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableTableAdminClientWrapper.java | zendesk/cloud-bigtable-client | d194263ffa1071151b4b85a66c1cc9168fb7795e | [
"Apache-2.0"
] | null | null | null | 37.363229 | 103 | 0.737038 | 999,437 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigtable.grpc;
import com.google.bigtable.admin.v2.DeleteTableRequest;
import com.google.bigtable.admin.v2.DropRowRangeRequest;
import com.google.bigtable.admin.v2.GetTableRequest;
import com.google.bigtable.admin.v2.ListTablesRequest;
import com.google.bigtable.admin.v2.ListTablesResponse;
import com.google.cloud.bigtable.admin.v2.models.CreateTableRequest;
import com.google.cloud.bigtable.admin.v2.models.ModifyColumnFamiliesRequest;
import com.google.cloud.bigtable.admin.v2.models.Table;
import com.google.cloud.bigtable.config.BigtableOptions;
import com.google.cloud.bigtable.core.IBigtableTableAdminClient;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.util.List;
import javax.annotation.Nonnull;
/**
* This class implements the {@link IBigtableTableAdminClient} interface and wraps
* {@link BigtableTableAdminClient} with Google-cloud-java's models.
*/
public class BigtableTableAdminClientWrapper implements IBigtableTableAdminClient {
private final BigtableTableAdminClient adminClient;
private final BigtableInstanceName instanceName;
public BigtableTableAdminClientWrapper(@Nonnull BigtableTableAdminClient adminClient,
@Nonnull BigtableOptions options){
Preconditions.checkNotNull(adminClient);
Preconditions.checkNotNull(options);
this.adminClient = adminClient;
this.instanceName = options.getInstanceName();
}
/** {@inheritDoc} */
@Override
public Table createTable(CreateTableRequest request) {
com.google.bigtable.admin.v2.CreateTableRequest requestProto =
request.toProto(instanceName.getProjectId(), instanceName.getInstanceId());
adminClient.createTable(requestProto);
return getTable(requestProto.getTableId());
}
/** {@inheritDoc} */
@Override
public ListenableFuture<Table> createTableAsync(CreateTableRequest request) {
com.google.bigtable.admin.v2.CreateTableRequest requestProto =
request.toProto(instanceName.getProjectId(), instanceName.getInstanceId());
return Futures.transform(adminClient.createTableAsync(requestProto),
new Function<com.google.bigtable.admin.v2.Table, Table>() {
@Override
public Table apply(com.google.bigtable.admin.v2.Table tableProto) {
return Table.fromProto(tableProto);
}
}, MoreExecutors.directExecutor());
}
/** {@inheritDoc} */
@Override
public Table getTable(String tableId) {
GetTableRequest requestProto = GetTableRequest.newBuilder()
.setName(instanceName.toTableNameStr(tableId))
.build();
return Table.fromProto(adminClient.getTable(requestProto));
}
/** {@inheritDoc} */
@Override
public ListenableFuture<Table> getTableAsync(String tableId) {
GetTableRequest requestProto = GetTableRequest.newBuilder()
.setName(instanceName.toTableNameStr(tableId))
.build();
return Futures.transform(adminClient.getTableAsync(requestProto),
new Function<com.google.bigtable.admin.v2.Table, Table>() {
@Override
public Table apply(com.google.bigtable.admin.v2.Table tableProto) {
return Table.fromProto(tableProto);
}
}, MoreExecutors.directExecutor());
}
/** {@inheritDoc} */
@Override
public List<String> listTables() {
ListTablesRequest requestProto = ListTablesRequest.newBuilder()
.setParent(instanceName.toString())
.build();
ListTablesResponse response = adminClient.listTables(requestProto);
ImmutableList.Builder<String> tableIdsBuilder =
ImmutableList.builderWithExpectedSize(response.getTablesList().size());
for(com.google.bigtable.admin.v2.Table tableProto : response.getTablesList()){
tableIdsBuilder.add(instanceName.toTableId(tableProto.getName()));
}
return tableIdsBuilder.build();
}
/** {@inheritDoc} */
@Override
public ListenableFuture<List<String>> listTablesAsync() {
ListTablesRequest request = ListTablesRequest.newBuilder()
.setParent(instanceName.toString())
.build();
ListenableFuture<ListTablesResponse> response = adminClient.listTablesAsync(request);
return Futures.transform(response, new Function<ListTablesResponse, List<String>>() {
@Override
public List<String> apply(ListTablesResponse input) {
ImmutableList.Builder<String> tableIdsBuilder =
ImmutableList.builderWithExpectedSize(input.getTablesList().size());
for(com.google.bigtable.admin.v2.Table tableProto : input.getTablesList()){
tableIdsBuilder.add(instanceName.toTableId(tableProto.getName()));
}
return tableIdsBuilder.build();
}
}, MoreExecutors.directExecutor());
}
/** {@inheritDoc} */
@Override
public void deleteTable(String tableId) {
DeleteTableRequest request = DeleteTableRequest.newBuilder()
.setName(instanceName.toTableNameStr(tableId))
.build();
adminClient.deleteTable(request);
}
/** {@inheritDoc} */
@Override
public ListenableFuture<Void> deleteTableAsync(String tableId) {
DeleteTableRequest request = DeleteTableRequest.newBuilder()
.setName(instanceName.toTableNameStr(tableId))
.build();
return Futures.transform(adminClient.deleteTableAsync(request), new Function<Empty, Void>() {
@Override
public Void apply(Empty empty) {
return null;
}
}, MoreExecutors.directExecutor());
}
/** {@inheritDoc} */
@Override
public Table modifyFamilies(ModifyColumnFamiliesRequest request) {
com.google.bigtable.admin.v2.ModifyColumnFamiliesRequest modifyColumnRequestProto =
request.toProto(instanceName.getProjectId(), instanceName.getInstanceId());
return Table.fromProto(adminClient.modifyColumnFamily(modifyColumnRequestProto));
}
/** {@inheritDoc} */
@Override
public ListenableFuture<Table> modifyFamiliesAsync(ModifyColumnFamiliesRequest request) {
com.google.bigtable.admin.v2.ModifyColumnFamiliesRequest modifyColumnRequestProto =
request.toProto(instanceName.getProjectId(), instanceName.getInstanceId());
return Futures.transform(adminClient.modifyColumnFamilyAsync(modifyColumnRequestProto),
new Function<com.google.bigtable.admin.v2.Table, Table>() {
@Override
public Table apply(com.google.bigtable.admin.v2.Table tableProto) {
return Table.fromProto(tableProto);
}
}, MoreExecutors.directExecutor());
}
/** {@inheritDoc} */
@Override
public void dropRowRange(String tableId, String rowKeyPrefix) {
DropRowRangeRequest requestProto = DropRowRangeRequest.newBuilder()
.setName(instanceName.toTableNameStr(tableId))
.setRowKeyPrefix(ByteString.copyFromUtf8(rowKeyPrefix))
.build();
adminClient.dropRowRange(requestProto);
}
/** {@inheritDoc} */
@Override
public ListenableFuture<Void> dropRowRangeAsync(String tableId, String rowKeyPrefix) {
DropRowRangeRequest requestProto = DropRowRangeRequest.newBuilder()
.setName(instanceName.toTableNameStr(tableId))
.setRowKeyPrefix(ByteString.copyFromUtf8(rowKeyPrefix))
.build();
return Futures.transform(adminClient.dropRowRangeAsync(requestProto), new Function<Empty, Void>() {
@Override
public Void apply(Empty empty) {
return null;
}
}, MoreExecutors.directExecutor());
}
}
|
923b0ec231f99cb3051e24df0d69e973aee17896 | 5,150 | java | Java | src/com/intrigus/cocoja/java/awt/GraphicsConfiguration.java | intrigus/cocoja | 30fbe7976da712d8270cb00989de29e181c2211a | [
"Apache-2.0"
] | 1 | 2016-03-15T21:15:01.000Z | 2016-03-15T21:15:01.000Z | src/com/intrigus/cocoja/java/awt/GraphicsConfiguration.java | intrigus/vis-mac-utils | 30fbe7976da712d8270cb00989de29e181c2211a | [
"Apache-2.0"
] | 2 | 2016-04-01T23:23:03.000Z | 2016-04-01T23:24:07.000Z | src/com/intrigus/cocoja/java/awt/GraphicsConfiguration.java | intrigus/vis-mac-utils | 30fbe7976da712d8270cb00989de29e181c2211a | [
"Apache-2.0"
] | null | null | null | 47.685185 | 130 | 0.746796 | 999,438 | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.intrigus.cocoja.java.awt;
import java.awt.Rectangle;
/** The <code>GraphicsConfiguration</code> class describes the characteristics of a graphics destination such as a printer or
* monitor. There can be many <code>GraphicsConfiguration</code> objects associated with a single graphics device, representing
* different drawing modes or capabilities. The corresponding native structure will vary from platform to platform. For example,
* on X11 windowing systems, each visual is a different <code>GraphicsConfiguration</code>. On Microsoft Windows,
* <code>GraphicsConfiguration</code>s represent PixelFormats available in the current resolution and color depth.
* <p>
* In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds
* of the <code>GraphicsConfiguration</code> objects are relative to the virtual coordinate system. When setting the location of a
* component, use {@link #getBounds() getBounds} to get the bounds of the desired <code>GraphicsConfiguration</code> and offset
* the location with the coordinates of the <code>GraphicsConfiguration</code>, as the following code sample illustrates:
* </p>
*
* <pre>
* Frame f = new Frame(gc); // where gc is a GraphicsConfiguration
* Rectangle bounds = gc.getBounds();
* f.setLocation(10 + bounds.x, 10 + bounds.y);
* </pre>
*
* <p>
* To determine if your environment is a virtual device environment, call <code>getBounds</code> on all of the
* <code>GraphicsConfiguration</code> objects in your system. If any of the origins of the returned bounds is not (0, 0),
* your environment is a virtual device environment.
*
* <p>
* You can also use <code>getBounds</code> to determine the bounds of the virtual device. To do this, first call
* <code>getBounds</code> on all of the <code>GraphicsConfiguration</code> objects in your system. Then calculate the union of all
* of the bounds returned from the calls to <code>getBounds</code>. The union is the bounds of the virtual device. The following
* code sample calculates the bounds of the virtual device.
*
* <pre>
* {
* @code
* Rectangle virtualBounds = new Rectangle();
* GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
* GraphicsDevice[] gs = ge.getScreenDevices();
* for (int j = 0; j < gs.length; j++) {
* GraphicsDevice gd = gs[j];
* GraphicsConfiguration[] gc = gd.getConfigurations();
* for (int i = 0; i < gc.length; i++) {
* virtualBounds = virtualBounds.union(gc[i].getBounds());
* }
* }
* }
* </pre>
*
* @see Window
* @see Frame
* @see GraphicsEnvironment
* @see GraphicsDevice */
/*
* REMIND: What to do about capabilities? The capabilities of the device can be determined by enumerating the possible
* capabilities and checking if the GraphicsConfiguration implements the interface for that capability.
*
*/
public abstract class GraphicsConfiguration {
/** This is an abstract class that cannot be instantiated directly. Instances must be obtained from a suitable factory or query
* method.
*
* @see GraphicsDevice#getConfigurations
* @see GraphicsDevice#getDefaultConfiguration
* @see GraphicsDevice#getBestConfiguration
* @see Graphics2D#getDeviceConfiguration */
protected GraphicsConfiguration () {
}
/** Returns the {@link GraphicsDevice} associated with this <code>GraphicsConfiguration</code>.
* @return a <code>GraphicsDevice</code> object that is associated with this <code>GraphicsConfiguration</code>. */
public abstract GraphicsDevice getDevice ();
/** Returns the bounds of the <code>GraphicsConfiguration</code> in the device coordinates. In a multi-screen environment with
* a virtual device, the bounds can have negative X or Y origins.
* @return the bounds of the area covered by this <code>GraphicsConfiguration</code>.
* @since 1.3 */
public abstract Rectangle getBounds ();
}
|
923b0f3d03d74dc73b4a4847928e3b587cbbceab | 1,636 | java | Java | oj-leetcode-algorithm/src/main/java/com/nxy006/project/algorithm/leetcode/p0094/binary_tree_inorder_traversal/Solution.java | nxy006/java-algorithm | 9759078d672f303ae6ac78f275d63872981ee609 | [
"MIT"
] | null | null | null | oj-leetcode-algorithm/src/main/java/com/nxy006/project/algorithm/leetcode/p0094/binary_tree_inorder_traversal/Solution.java | nxy006/java-algorithm | 9759078d672f303ae6ac78f275d63872981ee609 | [
"MIT"
] | null | null | null | oj-leetcode-algorithm/src/main/java/com/nxy006/project/algorithm/leetcode/p0094/binary_tree_inorder_traversal/Solution.java | nxy006/java-algorithm | 9759078d672f303ae6ac78f275d63872981ee609 | [
"MIT"
] | null | null | null | 34.808511 | 162 | 0.613081 | 999,439 | package com.nxy006.project.algorithm.leetcode.p0094.binary_tree_inorder_traversal;
import com.nxy006.project.alogtithm.utils.CaseAssertUtils;
import com.nxy006.project.alogtithm.utils.StructConvertUtils;
import com.nxy006.project.alogtithm.utils.struct.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* 常规解法
* 时间复杂度:O(n),空间复杂度:O(n)
*
* Runtime 0 ms , beats 100.00 % of java submissions.
* Memory 37.5 MB , beats 34.81 % of java submissions.
* 08/03/2021 22:52
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
inorderTraversal(root, ans);
return ans;
}
private void inorderTraversal(TreeNode root, List<Integer> ans) {
if (root == null) return ;
inorderTraversal(root.left, ans);
ans.add(root.val);
inorderTraversal(root.right, ans);
}
// ---------------------------------------------------------- TEST CASE ----------------------------------------------------------- //
public static void main(String[] args) {
caseCheck(new Solution(), "[1,3,2]", "[1,null,2,3]");
caseCheck(new Solution(), "[]", "[]");
caseCheck(new Solution(), "[1]", "[1]");
caseCheck(new Solution(), "[1,2]", "[2,1]");
caseCheck(new Solution(), "[1,2]", "[1,null,2]");
}
private static void caseCheck(Solution solution, String expected, String treeStr) {
CaseAssertUtils.assertEquals(StructConvertUtils.convertToIntegerList(expected), solution.inorderTraversal(StructConvertUtils.convertToTreeNode(treeStr)));
}
}
|
923b10e1c1ab238c08b1a4fcbb85feefe5f8a51e | 4,611 | java | Java | oscm-app-vmware-setup/javasrc/org/oscm/app/vmware/db/importer/DatacenterImport.java | srinathjiinfotach/billingdevelopment | 564e66593c9d272b8e04804410b633bc089aa203 | [
"Apache-2.0"
] | 56 | 2015-10-06T15:09:39.000Z | 2021-08-09T01:18:03.000Z | oscm-app-vmware-setup/javasrc/org/oscm/app/vmware/db/importer/DatacenterImport.java | srinathjiinfotach/billingdevelopment | 564e66593c9d272b8e04804410b633bc089aa203 | [
"Apache-2.0"
] | 845 | 2016-02-10T14:06:17.000Z | 2020-10-20T07:44:09.000Z | oscm-app-vmware-setup/javasrc/org/oscm/app/vmware/db/importer/DatacenterImport.java | srinathjiinfotach/billingdevelopment | 564e66593c9d272b8e04804410b633bc089aa203 | [
"Apache-2.0"
] | 41 | 2015-10-22T14:22:23.000Z | 2022-03-18T07:55:15.000Z | 35.198473 | 113 | 0.524832 | 999,440 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 2016-05-24
*
*******************************************************************************/
package org.oscm.app.vmware.db.importer;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DatacenterImport extends GenericImport {
private static final Logger logger = LoggerFactory
.getLogger(DatacenterImport.class);
public static void main(String args[]) throws Exception {
if (args.length < 5 || args.length > 6) {
throw new RuntimeException(
"Usage: DatacenterImport <driverClass> <driverURL> <userName> <userPwd> <csvFile>");
}
DatacenterImport dcImport = new DatacenterImport(args[0], args[1],
args[2], args[3], args[4]);
dcImport.execute();
}
private final Map<String, Integer> vcenterCache = new HashMap<String, Integer>();
public DatacenterImport(String driverClass, String driverURL,
String userName, String userPwd, String csvFile) {
super(driverClass, driverURL, userName, userPwd, csvFile);
}
public void execute() throws Exception {
DatacenterCSV csv = null;
try (Connection conn = getConnection();
InputStream in = getFileInputStream();) {
csv = new DatacenterCSV(in);
Map<String, String> line = csv.readNext();
while (line != null) {
String vcenter = line.get(DatacenterCSV.COL_VCENTER);
String datacenter = line.get(DatacenterCSV.COL_DATACENTER);
String dcId = line.get(DatacenterCSV.COL_DATACENTER_ID);
try {
addTableRow(conn, vcenter, datacenter, dcId);
} catch (Exception e) {
logger.error("Failed to add row: " + vcenter + " "
+ datacenter + " " + dcId);
logger.error(e.getMessage());
conn.rollback();
throw e;
}
try {
line = csv.readNext();
} catch (Exception e) {
logger.error("Failed to read line from CSV file after row: "
+ vcenter + " " + datacenter + " " + dcId);
logger.error(e.getMessage());
conn.rollback();
throw e;
}
}
conn.commit();
} catch (Exception e) {
logger.error("Failed to import datacenter. " + e.getMessage());
throw e;
} finally {
try {
if (csv != null) {
csv.close();
}
} catch (Exception e) {
logger.error("Failed to close resources", e);
throw e;
}
}
}
private void addTableRow(Connection con, String vcenter, String datacenter,
String dcId) throws Exception {
int vcenterKey = getVCenterKey(con, vcenter);
String query = "insert into datacenter (TKEY, NAME, IDENTIFIER, VCENTER_TKEY) values (DEFAULT, ?, ?, ?)";
try (PreparedStatement stmt = con.prepareStatement(query);) {
stmt.setString(1, datacenter);
stmt.setString(2, dcId);
stmt.setInt(3, vcenterKey);
stmt.execute();
}
}
private int getVCenterKey(Connection con, String vcenter) {
int vcKey = -1;
if (vcenterCache.containsKey(vcenter)) {
return vcenterCache.get(vcenter).intValue();
}
String query = "SELECT tkey FROM vcenter WHERE name = ?";
try (PreparedStatement stmt = con.prepareStatement(query);) {
stmt.setString(1, vcenter);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
vcKey = rs.getInt(1);
vcenterCache.put(vcenter, Integer.valueOf(vcKey));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("Failed to retrieve vcenter " + vcenter,
e);
}
if (vcKey == -1) {
throw new RuntimeException("Failed to retrieve vcenter " + vcenter);
}
return vcKey;
}
}
|
923b11de75e4772571ab0560aeadb8cd3cab00b8 | 18,491 | java | Java | sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/fluent/PrivateEndpointConnectionsClient.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/fluent/PrivateEndpointConnectionsClient.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/fluent/PrivateEndpointConnectionsClient.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 55.362275 | 116 | 0.751338 | 999,441 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.redis.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.redis.fluent.models.PrivateEndpointConnectionInner;
import java.nio.ByteBuffer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in PrivateEndpointConnectionsClient. */
public interface PrivateEndpointConnectionsClient {
/**
* List all the private endpoint connections associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of private endpoint connection associated with the specified storage account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<PrivateEndpointConnectionInner> listAsync(String resourceGroupName, String cacheName);
/**
* List all the private endpoint connections associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of private endpoint connection associated with the specified storage account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<PrivateEndpointConnectionInner> list(String resourceGroupName, String cacheName);
/**
* List all the private endpoint connections associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of private endpoint connection associated with the specified storage account.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<PrivateEndpointConnectionInner> list(String resourceGroupName, String cacheName, Context context);
/**
* Gets the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified private endpoint connection associated with the redis cache.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<PrivateEndpointConnectionInner>> getWithResponseAsync(
String resourceGroupName, String cacheName, String privateEndpointConnectionName);
/**
* Gets the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified private endpoint connection associated with the redis cache.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<PrivateEndpointConnectionInner> getAsync(
String resourceGroupName, String cacheName, String privateEndpointConnectionName);
/**
* Gets the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified private endpoint connection associated with the redis cache.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner get(
String resourceGroupName, String cacheName, String privateEndpointConnectionName);
/**
* Gets the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified private endpoint connection associated with the redis cache.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<PrivateEndpointConnectionInner> getWithResponse(
String resourceGroupName, String cacheName, String privateEndpointConnectionName, Context context);
/**
* Update the state of specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param properties The private endpoint connection properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Flux<ByteBuffer>>> putWithResponseAsync(
String resourceGroupName,
String cacheName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner properties);
/**
* Update the state of specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param properties The private endpoint connection properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PollerFlux<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginPutAsync(
String resourceGroupName,
String cacheName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner properties);
/**
* Update the state of specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param properties The private endpoint connection properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginPut(
String resourceGroupName,
String cacheName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner properties);
/**
* Update the state of specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param properties The private endpoint connection properties.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginPut(
String resourceGroupName,
String cacheName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner properties,
Context context);
/**
* Update the state of specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param properties The private endpoint connection properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<PrivateEndpointConnectionInner> putAsync(
String resourceGroupName,
String cacheName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner properties);
/**
* Update the state of specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param properties The private endpoint connection properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner put(
String resourceGroupName,
String cacheName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner properties);
/**
* Update the state of specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param properties The private endpoint connection properties.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
PrivateEndpointConnectionInner put(
String resourceGroupName,
String cacheName,
String privateEndpointConnectionName,
PrivateEndpointConnectionInner properties,
Context context);
/**
* Deletes the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> deleteWithResponseAsync(
String resourceGroupName, String cacheName, String privateEndpointConnectionName);
/**
* Deletes the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> deleteAsync(String resourceGroupName, String cacheName, String privateEndpointConnectionName);
/**
* Deletes the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String cacheName, String privateEndpointConnectionName);
/**
* Deletes the specified private endpoint connection associated with the redis cache.
*
* @param resourceGroupName The name of the resource group.
* @param cacheName The name of the Redis cache.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> deleteWithResponse(
String resourceGroupName, String cacheName, String privateEndpointConnectionName, Context context);
}
|
923b12f0ee883f7015cce363f4ba40f368a14725 | 5,469 | java | Java | core-api/src/main/java/com/sequenceiq/cloudbreak/cloud/VersionComparator.java | Beast2709/cloudbreak | 6fefcf8e1ba441f46d3e7fe253e41381622a6b4d | [
"Apache-2.0"
] | 174 | 2017-07-14T03:20:42.000Z | 2022-03-25T05:03:18.000Z | core-api/src/main/java/com/sequenceiq/cloudbreak/cloud/VersionComparator.java | Beast2709/cloudbreak | 6fefcf8e1ba441f46d3e7fe253e41381622a6b4d | [
"Apache-2.0"
] | 2,242 | 2017-07-12T05:52:01.000Z | 2022-03-31T15:50:08.000Z | core-api/src/main/java/com/sequenceiq/cloudbreak/cloud/VersionComparator.java | Beast2709/cloudbreak | 6fefcf8e1ba441f46d3e7fe253e41381622a6b4d | [
"Apache-2.0"
] | 172 | 2017-07-12T08:53:48.000Z | 2022-03-24T12:16:33.000Z | 38.244755 | 154 | 0.63028 | 999,442 | package com.sequenceiq.cloudbreak.cloud;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import com.sequenceiq.cloudbreak.common.type.Versioned;
public class VersionComparator implements Comparator<Versioned>, Serializable {
private static final String VERSION_SPLITTER_REGEX = "[\\.\\-]|(?<=b)(?=\\d)";
@Override
public int compare(Versioned o1, Versioned o2) {
ImmutablePair<Versioned, Versioned> versionedVersionedPair = transformByLength(new ImmutablePair<>(o1, o2));
String[] vals1 = versionedVersionedPair.getLeft().getVersion().split(VERSION_SPLITTER_REGEX);
String[] vals2 = versionedVersionedPair.getRight().getVersion().split(VERSION_SPLITTER_REGEX);
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = StringUtils.isNumeric(vals1[i]) && StringUtils.isNumeric(vals2[i]) ? Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]))
: getDiffByPreReleaseIdPrecedence(vals1[i], vals2[i]);
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other, then shorter wins
// e.g. "2.4.2.0" is newer than "2.4.2.0-9999"
return Integer.signum(vals2.length - vals1.length);
}
private ImmutablePair<Versioned, Versioned> transformByLength(ImmutablePair<Versioned, Versioned> input) {
String first = input.getLeft().getVersion();
String last = input.getRight().getVersion();
// splitting with '-'
String[] firstSplit = splitWithHyphens(first);
String[] lastSplit = splitWithHyphens(last);
if (!lastSplit[0].equals(firstSplit[0])) {
if (lastSplit.length < firstSplit.length) {
last = getLastSegmentWithZeros(last, firstSplit[1]);
} else if (firstSplit.length < lastSplit.length) {
first = getLastSegmentWithZeros(first, lastSplit[1]);
}
}
firstSplit = splitWithHyphens(first);
lastSplit = splitWithHyphens(last);
String[] firstSplitFirstSegment = splitWithPoint(first);
String[] lastSplitFirstSegment = splitWithPoint(last);
if (!lastSplit[0].equals(firstSplit[0])) {
if (lastSplitFirstSegment.length < firstSplitFirstSegment.length) {
last = getFirstSegmentWithZeros(lastSplit,
firstSplitFirstSegment.length - lastSplitFirstSegment.length);
} else if (firstSplitFirstSegment.length < lastSplitFirstSegment.length) {
first = getFirstSegmentWithZeros(firstSplit,
lastSplitFirstSegment.length - firstSplitFirstSegment.length);
}
}
String finalFirst = first;
String finalLast = last;
return new ImmutablePair<>(() -> finalFirst, () -> finalLast);
}
private String getFirstSegmentWithZeros(String[] lastSplit, int difference1) {
String last;
int difference = difference1;
String firstSegment = lastSplit[0];
for (int i = 0; i < difference; i++) {
firstSegment += ".0";
}
if (lastSplit.length > 1) {
last = firstSegment + "-" + lastSplit[1];
} else {
last = firstSegment;
}
return last;
}
private String[] splitWithPoint(String first) {
return first.trim().split("-")[0].trim().split("\\.");
}
private String[] splitWithHyphens(String input) {
return input.trim().split("-");
}
private String getLastSegmentWithZeros(String last, String end1) {
String end = end1;
last = last + "-" + end.replaceAll("[0-9]", "0");
return last;
}
private int getDiffByPreReleaseIdPrecedence(String left, String right) {
PreReleaseIdentifier leftPrecedence = getPreReleaseIdentifierPrecedence(left);
PreReleaseIdentifier rightPrecedence = getPreReleaseIdentifierPrecedence(right);
if (PreReleaseIdentifier.UNKNOWN.equals(leftPrecedence) && PreReleaseIdentifier.UNKNOWN.equals(rightPrecedence)) {
return left.compareTo(right);
} else {
return leftPrecedence.getPrecedence().compareTo(rightPrecedence.getPrecedence());
}
}
private PreReleaseIdentifier getPreReleaseIdentifierPrecedence(String preReleaseIdentifier) {
switch (preReleaseIdentifier.toLowerCase()) {
case "b":
return PreReleaseIdentifier.RE_VERSION;
case "rc":
return PreReleaseIdentifier.RC_VERSION;
case "dev":
return PreReleaseIdentifier.DEV_VERSION;
default:
return PreReleaseIdentifier.UNKNOWN;
}
}
private enum PreReleaseIdentifier {
RE_VERSION(3),
RC_VERSION(2),
DEV_VERSION(1),
UNKNOWN(0);
private final int precedence;
PreReleaseIdentifier(int precedence) {
this.precedence = precedence;
}
public Integer getPrecedence() {
return precedence;
}
}
}
|
923b1326cf32349a177afe67c0ef92dae6ac80fc | 6,232 | java | Java | Trabalho/src/java/DAO/AlimentoDAO.java | GabrielNogueiraBezerra/SistemaWEB2018 | aa6ae916e849e3d1a352e38438dcf439ea6d3203 | [
"Apache-2.0"
] | null | null | null | Trabalho/src/java/DAO/AlimentoDAO.java | GabrielNogueiraBezerra/SistemaWEB2018 | aa6ae916e849e3d1a352e38438dcf439ea6d3203 | [
"Apache-2.0"
] | null | null | null | Trabalho/src/java/DAO/AlimentoDAO.java | GabrielNogueiraBezerra/SistemaWEB2018 | aa6ae916e849e3d1a352e38438dcf439ea6d3203 | [
"Apache-2.0"
] | null | null | null | 37.317365 | 167 | 0.603017 | 999,443 | /*
* 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 DAO;
import Models.Alimento;
import Models.CategoriaAlimento;
import conexao.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Marcelo Moreira
*/
public class AlimentoDAO {
private ConnectionFactory dao = ConnectionFactory.getInstancia();
private static AlimentoDAO instancia;
public static AlimentoDAO getInstancia() {
if (instancia == null) {
instancia = new AlimentoDAO();
}
return instancia;
}
public void save(Alimento alimento) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("INSERT INTO `alimento`(`idCategoria`, `nome`, `fibras`, `carboidratos`, `calorias`) VALUES (?, ?, ?, ?, ?)");
stmt.setInt(1, alimento.getCategoriaAlimento().getId());
stmt.setString(2, alimento.getNome());
stmt.setFloat(3, alimento.getQuantidadeFibras());
stmt.setFloat(4, alimento.getQuantidadeCarboidratos());
stmt.setFloat(5, alimento.getQuantidadeCalorias());
stmt.executeUpdate();
alimento.setId(this.find());
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void update(Alimento alimento) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("UPDATE `alimento` SET `idCategoria` = ?,`nome` = ?,`fibras` = ?,`carboidratos` = ?,`calorias` = ? WHERE `id` = ?");
stmt.setInt(1, alimento.getCategoriaAlimento().getId());
stmt.setString(2, alimento.getNome());
stmt.setFloat(3, alimento.getQuantidadeFibras());
stmt.setFloat(4, alimento.getQuantidadeCarboidratos());
stmt.setFloat(5, alimento.getQuantidadeCalorias());
stmt.setInt(6, alimento.getId());
stmt.executeUpdate();
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void delete(Alimento alimento) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("DELETE FROM `alimento` WHERE `id` = ?");
stmt.setInt(1, alimento.getId());
stmt.executeUpdate();
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void find(Alimento alimento) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
try {
stmt = conexao.prepareStatement("SELECT `idCategoria`, `nome`, `fibras`, `carboidratos`, `calorias` FROM `alimento` WHERE `id` = ?");
stmt.setInt(1, alimento.getId());
result = stmt.executeQuery();
while (result.next()) {
// BUSCAR CATEGORIA ALIMENTO
CategoriaAlimento categoriaAlimento = new CategoriaAlimento(0, "");
categoriaAlimento.find(result.getInt("idCategoria"));
alimento.setCategoriaAlimento(categoriaAlimento);
alimento.setNome(result.getString("nome"));
alimento.setQuantidadeCalorias(result.getFloat("calorias"));
alimento.setQuantidadeCarboidratos(result.getFloat("carboidratos"));
alimento.setQuantidadeFibras(result.getFloat("fibras"));
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
private int find() throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
int resultado = 0;
try {
stmt = conexao.prepareStatement("SELECT AUTO_INCREMENT as id FROM information_schema.tables WHERE table_name = 'alimento' AND table_schema = 'bancoweb'");
result = stmt.executeQuery();
while (result.next()) {
resultado = result.getInt("id");
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
return resultado - 1;
}
}
public ArrayList<Alimento> buscarTodos() throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
ArrayList<Alimento> alimentos = new ArrayList<>();
try {
stmt = conexao.prepareStatement("SELECT `id`, `idCategoria`, `nome`, `fibras`, `carboidratos`, `calorias` FROM `alimento` order by id");
result = stmt.executeQuery();
while (result.next()) {
Alimento alimento = new Alimento();
alimento.setId(result.getInt("id"));
alimento.setNome(result.getString("nome"));
alimento.setQuantidadeCalorias(result.getFloat("calorias"));
alimento.setQuantidadeCarboidratos(result.getFloat("carboidratos"));
alimento.setQuantidadeFibras(result.getFloat("fibras"));
CategoriaAlimento categoria = new CategoriaAlimento();
categoria.find(result.getInt("idCategoria"));
alimento.setCategoriaAlimento(categoria);
alimentos.add(alimento);
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
return alimentos;
}
}
}
|
923b1334ef9677388d6b5833e99cba888f73733d | 1,638 | java | Java | code-sample-java/code-sample-java-hibernate/src/main/java/codesample/frameworks/hibernate/one_to_one_relation/unidirectional/OwnerUni.java | aquatir/code-samples | a3d79beeb09a53d16f088dbc5e9fd4ff3d16020c | [
"MIT"
] | 4 | 2018-08-01T12:44:42.000Z | 2021-11-22T20:57:58.000Z | code-sample-java/code-sample-java-hibernate/src/main/java/codesample/frameworks/hibernate/one_to_one_relation/unidirectional/OwnerUni.java | aquatir/code-samples | a3d79beeb09a53d16f088dbc5e9fd4ff3d16020c | [
"MIT"
] | 4 | 2021-05-03T10:36:01.000Z | 2022-01-06T10:59:46.000Z | code-sample-java/code-sample-java-hibernate/src/main/java/codesample/frameworks/hibernate/one_to_one_relation/unidirectional/OwnerUni.java | aquatir/code-samples | a3d79beeb09a53d16f088dbc5e9fd4ff3d16020c | [
"MIT"
] | 1 | 2022-02-22T22:08:32.000Z | 2022-02-22T22:08:32.000Z | 22.438356 | 98 | 0.588523 | 999,444 | package codesample.frameworks.hibernate.one_to_one_relation.unidirectional;
import javax.persistence.*;
@Entity
@Table(name = "owner_unidirectional", schema = "one_to_one")
public class OwnerUni {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "dog_id")
private DogUni dog;
@Column(nullable = false)
private String name;
public OwnerUni() {}
public OwnerUni(String name, DogUni dog) {
this.name = name;
this.dog = dog;
}
public int getId() {
return id;
}
private DogUni getDog() {
return dog;
}
public void setDog(DogUni dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OwnerUni)) return false;
OwnerUni ownerUni = (OwnerUni) o;
if (id != ownerUni.id) return false;
if (dog != null ? !dog.equals(ownerUni.dog) : ownerUni.dog != null) return false;
if (!name.equals(ownerUni.name)) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (dog != null ? dog.hashCode() : 0);
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return String.format("%3d %20s %3d %20s", id, name, getDog().getId(), getDog().getName());
}
}
|
923b13727295e6e9a827d1eb121aacc708abd3fd | 16,840 | java | Java | ph-css/src/test/java/com/helger/css/reader/CSSReader30SpecialFuncTest.java | phax/ph-css | 4f89f95a60cc11b04236a05e87502e6d2001b295 | [
"Apache-2.0"
] | 118 | 2015-02-14T13:43:21.000Z | 2022-01-31T02:31:33.000Z | ph-css/src/test/java/com/helger/css/reader/CSSReader30SpecialFuncTest.java | phax/ph-css | 4f89f95a60cc11b04236a05e87502e6d2001b295 | [
"Apache-2.0"
] | 76 | 2015-01-13T16:08:02.000Z | 2022-03-30T13:01:28.000Z | ph-css/src/test/java/com/helger/css/reader/CSSReader30SpecialFuncTest.java | phax/ph-css | 4f89f95a60cc11b04236a05e87502e6d2001b295 | [
"Apache-2.0"
] | 27 | 2015-05-17T02:36:53.000Z | 2022-01-07T13:02:35.000Z | 44.315789 | 171 | 0.712055 | 999,445 | /*
* Copyright (C) 2014-2021 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.css.reader;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.helger.commons.charset.EUnicodeBOM;
import com.helger.commons.collection.ArrayHelper;
import com.helger.commons.io.streamprovider.ByteArrayInputStreamProvider;
import com.helger.css.ECSSVersion;
import com.helger.css.decl.CSSDeclaration;
import com.helger.css.decl.CSSExpressionMemberFunction;
import com.helger.css.decl.CSSExpressionMemberMath;
import com.helger.css.decl.CSSExpressionMemberTermSimple;
import com.helger.css.decl.CSSExpressionMemberTermURI;
import com.helger.css.decl.CSSPageMarginBlock;
import com.helger.css.decl.CSSPageRule;
import com.helger.css.decl.CSSStyleRule;
import com.helger.css.decl.CascadingStyleSheet;
import com.helger.css.decl.ICSSExpressionMember;
import com.helger.css.reader.errorhandler.CollectingCSSParseErrorHandler;
import com.helger.css.reader.errorhandler.DoNothingCSSParseErrorHandler;
import com.helger.css.reader.errorhandler.LoggingCSSParseErrorHandler;
import com.helger.css.writer.CSSWriter;
import com.helger.css.writer.CSSWriterSettings;
/**
* Test reading CSS 3.0 stuff
*
* @author Philip Helger
*/
public final class CSSReader30SpecialFuncTest
{
private static final Logger LOGGER = LoggerFactory.getLogger (CSSReader30SpecialFuncTest.class);
@Test
public void testReadSpecialGood ()
{
final ECSSVersion eVersion = ECSSVersion.CSS30;
final Charset aCharset = StandardCharsets.UTF_8;
final File aFile = new File ("src/test/resources/testfiles/css30/good/issue63.css");
final CascadingStyleSheet aCSS = CSSReader.readFromFile (aFile, aCharset, eVersion);
assertNotNull (aCSS);
assertEquals ("--a", aCSS.getStyleRuleAtIndex (0).getDeclarationAtIndex (0).getProperty ());
assertEquals ("background-color:var(--A)", aCSS.getStyleRuleAtIndex (0).getDeclarationAtIndex (1).getAsCSSString ());
assertEquals ("--A", aCSS.getStyleRuleAtIndex (1).getDeclarationAtIndex (0).getProperty ());
assertEquals ("background-color:var(--A)", aCSS.getStyleRuleAtIndex (1).getDeclarationAtIndex (1).getAsCSSString ());
final String sCSS = new CSSWriter (eVersion, false).getCSSAsString (aCSS);
assertNotNull (sCSS);
if (false)
LOGGER.info (sCSS);
}
@Test
public void testReadExpressions ()
{
final ECSSVersion eVersion = ECSSVersion.CSS30;
final CSSWriterSettings aCSSWS = new CSSWriterSettings (eVersion, false);
final Charset aCharset = StandardCharsets.UTF_8;
final File aFile = new File ("src/test/resources/testfiles/css30/good/artificial/test-expression.css");
final CascadingStyleSheet aCSS = CSSReader.readFromFile (aFile, aCharset, eVersion);
assertNotNull (aCSS);
assertEquals (1, aCSS.getRuleCount ());
assertEquals (1, aCSS.getStyleRuleCount ());
final CSSStyleRule aSR = aCSS.getStyleRuleAtIndex (0);
assertEquals ("div", aSR.getSelectorsAsCSSString (aCSSWS, 0));
assertEquals (23, aSR.getDeclarationCount ());
int i = 0;
for (final CSSDeclaration aDecl : aSR.getAllDeclarations ())
{
final String sExpectedName = Character.toString ((char) ('a' + i));
assertEquals (sExpectedName, aDecl.getProperty ());
++i;
}
CSSDeclaration aDecl;
ICSSExpressionMember aMember;
// a: -5
aDecl = aSR.getDeclarationOfPropertyName ("a");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("-5", aMember.getAsCSSString (aCSSWS));
// b: +5
aDecl = aSR.getDeclarationOfPropertyName ("b");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("+5", aMember.getAsCSSString (aCSSWS));
// c: 5
aDecl = aSR.getDeclarationOfPropertyName ("c");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("5", aMember.getAsCSSString (aCSSWS));
// d: -5.12
aDecl = aSR.getDeclarationOfPropertyName ("d");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("-5.12", aMember.getAsCSSString (aCSSWS));
// e: +5.12
aDecl = aSR.getDeclarationOfPropertyName ("e");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("+5.12", aMember.getAsCSSString (aCSSWS));
// f: 5.12
aDecl = aSR.getDeclarationOfPropertyName ("f");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("5.12", aMember.getAsCSSString (aCSSWS));
// g: -5.12%
aDecl = aSR.getDeclarationOfPropertyName ("g");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("-5.12%", aMember.getAsCSSString (aCSSWS));
// h: +5.12%
aDecl = aSR.getDeclarationOfPropertyName ("h");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("+5.12%", aMember.getAsCSSString (aCSSWS));
// i: 5.12%
aDecl = aSR.getDeclarationOfPropertyName ("i");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("5.12%", aMember.getAsCSSString (aCSSWS));
// j: -5px
aDecl = aSR.getDeclarationOfPropertyName ("j");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("-5px", aMember.getAsCSSString (aCSSWS));
// k: +5px
aDecl = aSR.getDeclarationOfPropertyName ("k");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("+5px", aMember.getAsCSSString (aCSSWS));
// l: 5px
aDecl = aSR.getDeclarationOfPropertyName ("l");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("5px", aMember.getAsCSSString (aCSSWS));
// m: 'string1'
aDecl = aSR.getDeclarationOfPropertyName ("m");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("'string1'", aMember.getAsCSSString (aCSSWS));
// n: "string2"
aDecl = aSR.getDeclarationOfPropertyName ("n");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("\"string2\"", aMember.getAsCSSString (aCSSWS));
// o: abc
aDecl = aSR.getDeclarationOfPropertyName ("o");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("abc", aMember.getAsCSSString (aCSSWS));
// p: from
aDecl = aSR.getDeclarationOfPropertyName ("p");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("from", aMember.getAsCSSString (aCSSWS));
// q: to
aDecl = aSR.getDeclarationOfPropertyName ("q");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("to", aMember.getAsCSSString (aCSSWS));
// r: url(a.gif)
aDecl = aSR.getDeclarationOfPropertyName ("r");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermURI);
assertEquals ("url(a.gif)", aMember.getAsCSSString (aCSSWS));
// s: #123
aDecl = aSR.getDeclarationOfPropertyName ("s");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("#123", aMember.getAsCSSString (aCSSWS));
// t: function(5,6,abc)
aDecl = aSR.getDeclarationOfPropertyName ("t");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberFunction);
assertEquals ("function", ((CSSExpressionMemberFunction) aMember).getFunctionName ());
// 3 parameters and 2 commas
assertEquals (5, ((CSSExpressionMemberFunction) aMember).getExpression ().getMemberCount ());
assertEquals ("function(5,6,abc)", aMember.getAsCSSString (aCSSWS));
// u: calc(4 + 5)
aDecl = aSR.getDeclarationOfPropertyName ("u");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberMath);
// 2 values and 1 operator
assertEquals (3, ((CSSExpressionMemberMath) aMember).getMemberCount ());
assertEquals ("calc(4 + 5)", aMember.getAsCSSString (aCSSWS));
// v: inherit
aDecl = aSR.getDeclarationOfPropertyName ("v");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("inherit", aMember.getAsCSSString (aCSSWS));
// w: u+1234
aDecl = aSR.getDeclarationOfPropertyName ("w");
assertNotNull (aDecl);
assertEquals (1, aDecl.getExpression ().getMemberCount ());
aMember = aDecl.getExpression ().getMemberAtIndex (0);
assertTrue (aMember instanceof CSSExpressionMemberTermSimple);
assertEquals ("u+1234", aMember.getAsCSSString (aCSSWS));
// Write result
final String sCSS = new CSSWriter (aCSSWS).getCSSAsString (aCSS);
assertNotNull (sCSS);
if (false)
LOGGER.info (sCSS);
}
@Test
public void testReadSpecialBadButRecoverable ()
{
final CollectingCSSParseErrorHandler aErrors = new CollectingCSSParseErrorHandler ();
final ECSSVersion eVersion = ECSSVersion.CSS30;
final Charset aCharset = StandardCharsets.UTF_8;
final File aFile = new File ("src/test/resources/testfiles/css30/bad_but_recoverable_and_browsercompliant/test-string.css");
final CascadingStyleSheet aCSS = CSSReader.readFromFile (aFile, aCharset, eVersion, aErrors.and (new LoggingCSSParseErrorHandler ()));
assertNotNull (aFile.getAbsolutePath (), aCSS);
}
@Test
public void testReadWithBOM ()
{
final String sCSSBase = "/* comment */.class{color:red}.class{color:blue}";
for (final EUnicodeBOM eBOM : EUnicodeBOM.values ())
{
final Charset aDeterminedCharset = eBOM.getCharset ();
if (aDeterminedCharset != null)
{
final CascadingStyleSheet aCSS = CSSReader.readFromStream (new ByteArrayInputStreamProvider (ArrayHelper.getConcatenated (eBOM.getAllBytes (),
sCSSBase.getBytes (aDeterminedCharset))),
aDeterminedCharset,
ECSSVersion.CSS30,
new DoNothingCSSParseErrorHandler ());
assertNotNull ("Failed to read with BOM " + eBOM, aCSS);
assertEquals (".class{color:red}.class{color:blue}", new CSSWriter (ECSSVersion.CSS30, true).getCSSAsString (aCSS));
}
}
}
@Test
public void testReadSingleLineComments ()
{
final ECSSVersion eVersion = ECSSVersion.CSS30;
final Charset aCharset = StandardCharsets.UTF_8;
final File aFile = new File ("src/test/resources/testfiles/css30/good/artificial/test-singleline-comments.css");
final CascadingStyleSheet aCSS = CSSReader.readFromFile (aFile, aCharset, eVersion);
assertNotNull (aCSS);
assertEquals (13, aCSS.getRuleCount ());
assertEquals (13, aCSS.getStyleRuleCount ());
// #any1 - #any5
assertEquals (2, aCSS.getStyleRuleAtIndex (1).getDeclarationCount ());
assertEquals (1, aCSS.getStyleRuleAtIndex (2).getDeclarationCount ());
assertEquals (1, aCSS.getStyleRuleAtIndex (3).getDeclarationCount ());
assertEquals (0, aCSS.getStyleRuleAtIndex (4).getDeclarationCount ());
assertEquals (0, aCSS.getStyleRuleAtIndex (5).getDeclarationCount ());
// .test1 - .test7
assertEquals (2, aCSS.getStyleRuleAtIndex (6).getDeclarationCount ());
assertEquals (3, aCSS.getStyleRuleAtIndex (7).getDeclarationCount ());
assertEquals (1, aCSS.getStyleRuleAtIndex (8).getDeclarationCount ());
assertEquals (1, aCSS.getStyleRuleAtIndex (9).getDeclarationCount ());
assertEquals (2, aCSS.getStyleRuleAtIndex (10).getDeclarationCount ());
assertEquals (2, aCSS.getStyleRuleAtIndex (11).getDeclarationCount ());
assertEquals (1, aCSS.getStyleRuleAtIndex (12).getDeclarationCount ());
}
@Test
public void testReadFootnote ()
{
final ECSSVersion eVersion = ECSSVersion.CSS30;
final Charset aCharset = StandardCharsets.UTF_8;
final File aFile = new File ("src/test/resources/testfiles/css30/good/artificial/test-footnotes.css");
final CascadingStyleSheet aCSS = CSSReader.readFromFile (aFile, aCharset, eVersion);
assertNotNull (aCSS);
assertEquals (5, aCSS.getRuleCount ());
assertEquals (3, aCSS.getStyleRuleCount ());
// @page { @footnote { border-top: ..} }
assertTrue (aCSS.getRuleAtIndex (1) instanceof CSSPageRule);
assertEquals (1, ((CSSPageRule) aCSS.getRuleAtIndex (1)).getMemberCount ());
assertTrue (((CSSPageRule) aCSS.getRuleAtIndex (1)).getMemberAtIndex (0) instanceof CSSPageMarginBlock);
final CSSPageMarginBlock footnoteBlock = (CSSPageMarginBlock) ((CSSPageRule) aCSS.getRuleAtIndex (1)).getMemberAtIndex (0);
assertEquals ("@footnote", footnoteBlock.getPageMarginSymbol ());
assertEquals (1, footnoteBlock.getDeclarationCount ());
}
}
|
923b1381f5bb65f600bdd1fffd1b7b22e9b29e7a | 2,707 | java | Java | src/main/java/com/mactso/speakermod/block/WirelessSpeakerBlock.java | mactso/SpeakerMod | 2983b8dd0572bb8428bcf8696acd9ad8050a39ee | [
"MIT"
] | null | null | null | src/main/java/com/mactso/speakermod/block/WirelessSpeakerBlock.java | mactso/SpeakerMod | 2983b8dd0572bb8428bcf8696acd9ad8050a39ee | [
"MIT"
] | null | null | null | src/main/java/com/mactso/speakermod/block/WirelessSpeakerBlock.java | mactso/SpeakerMod | 2983b8dd0572bb8428bcf8696acd9ad8050a39ee | [
"MIT"
] | null | null | null | 32.614458 | 147 | 0.697082 | 999,446 | package com.mactso.speakermod.block;
import java.util.StringTokenizer;
import com.mactso.speakermod.tileentity.WirelessJukeboxTileEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
public class WirelessSpeakerBlock extends Block {
public WirelessSpeakerBlock(Properties builder) {
super(builder);
}
@Override
public void setPlacedBy(Level worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
if (worldIn.isClientSide()) {
return;
}
BlockPos jukePos = null;
String jukeLinkedPos = stack.getHoverName().getString().toString();
if (!(jukeLinkedPos.substring(0,1).equals("("))) {
worldIn.playSound(null, pos, SoundEvents.DISPENSER_FAIL, SoundSource.BLOCKS, 0.6f, 0.3f);
return;
}
// Trim leading and trailing parenthesis
jukeLinkedPos = jukeLinkedPos.substring(0,jukeLinkedPos.length()-1);
jukeLinkedPos = jukeLinkedPos.substring(1,jukeLinkedPos.length());
StringTokenizer st = new StringTokenizer(jukeLinkedPos,",");
try {
String sX = st.nextToken().trim();
String sY = st.nextToken().trim();
String sZ = st.nextToken().trim();
jukePos = new BlockPos (Integer.parseInt(sX),Integer.parseInt(sY),Integer.parseInt(sZ));
} catch (Exception e) {
// should never happen
}
BlockEntity r = worldIn.getBlockEntity(jukePos);
if ((r instanceof WirelessJukeboxTileEntity) && (calcDistance (jukePos, pos) < 8125.0d) && ((WirelessJukeboxTileEntity) r).addSpeakerPos(pos)) {
worldIn.playSound(null, pos, SoundEvents.ENDER_EYE_DEATH, SoundSource.BLOCKS, 0.6f, 0.2f);
} else {
worldIn.playSound(null, pos, SoundEvents.DISPENSER_FAIL, SoundSource.BLOCKS, 0.6f, 0.3f);
}
}
public double calcDistance(BlockPos pos1, BlockPos pos2) {
double d0 = pos1.getX() - pos2.getX();
double d1 = pos1.getY() - pos2.getY();
double d2 = pos1.getZ() - pos2.getZ();
double d = d0 * d0 + d1 * d1 + d2 * d2;
return d;
}
@SuppressWarnings("deprecation")
public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
if (!state.is(newState.getBlock())) {
worldIn.levelEvent(1010, pos, 0);
super.onRemove(state, worldIn, pos, newState, isMoving);
}
}
}
|
923b1395198df35b664dfb32d480c9ebd3d90181 | 1,976 | java | Java | super-mall-product/src/main/java/com/centersept/supermall/product/controller/SpuImagesController.java | Center-Sept/super-mall | bec7d0f07a42016d3bf1426713be606477fe3fcc | [
"Apache-2.0"
] | null | null | null | super-mall-product/src/main/java/com/centersept/supermall/product/controller/SpuImagesController.java | Center-Sept/super-mall | bec7d0f07a42016d3bf1426713be606477fe3fcc | [
"Apache-2.0"
] | null | null | null | super-mall-product/src/main/java/com/centersept/supermall/product/controller/SpuImagesController.java | Center-Sept/super-mall | bec7d0f07a42016d3bf1426713be606477fe3fcc | [
"Apache-2.0"
] | null | null | null | 23.235294 | 65 | 0.694177 | 999,447 | package com.centersept.supermall.product.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.centersept.supermall.product.entity.SpuImagesEntity;
import com.centersept.supermall.product.service.SpuImagesService;
import com.centersept.supermall.common.utils.PageUtils;
import com.centersept.supermall.common.utils.R;
/**
* spu图片
*
* @author center_sept
* @email envkt@example.com
* @date 2020-07-02 22:08:40
*/
@RestController
@RequestMapping("product/spuimages")
public class SpuImagesController {
@Autowired
private SpuImagesService spuImagesService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = spuImagesService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id){
SpuImagesEntity spuImages = spuImagesService.getById(id);
return R.ok().put("spuImages", spuImages);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody SpuImagesEntity spuImages){
spuImagesService.save(spuImages);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody SpuImagesEntity spuImages){
spuImagesService.updateById(spuImages);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
spuImagesService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
923b13e13a8065cd03f9c54e14e01e802121689b | 763 | java | Java | trader-api/src/main/java/io/horizon/trader/handler/AdaptorReportHandler.java | yellow013/horizon | c66fc845e413e33324cbae9d1012f76e01b82105 | [
"Apache-2.0"
] | 2 | 2020-11-18T09:44:51.000Z | 2021-02-28T14:52:14.000Z | trader-api/src/main/java/io/horizon/trader/handler/AdaptorReportHandler.java | yellow013/horizon | c66fc845e413e33324cbae9d1012f76e01b82105 | [
"Apache-2.0"
] | null | null | null | trader-api/src/main/java/io/horizon/trader/handler/AdaptorReportHandler.java | yellow013/horizon | c66fc845e413e33324cbae9d1012f76e01b82105 | [
"Apache-2.0"
] | null | null | null | 20.078947 | 76 | 0.754915 | 999,448 | package io.horizon.trader.handler;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import io.horizon.trader.report.AdaptorReport;
import io.mercury.common.log.Log4j2LoggerFactory;
@FunctionalInterface
public interface AdaptorReportHandler {
void onAdaptorReport(@Nonnull final AdaptorReport report);
/**
* Logger implements AdaptorEventHandler
*
* @author yellow013
*
*/
public static class AdaptorReportLogger implements AdaptorReportHandler {
private final Logger log;
public AdaptorReportLogger(Logger log) {
this.log = log == null ? Log4j2LoggerFactory.getLogger(getClass()) : log;
}
@Override
public void onAdaptorReport(final AdaptorReport report) {
log.info("AdaptorEventLogger -> {}", report);
}
}
}
|
923b151865ec73187fec468d7301dce29bb99b8b | 1,447 | java | Java | src/main/java/org/llaith/onyx/toolkit/etc/context/Configs.java | llaith/onyx-toolkit | 28bb9414927f933bde58812f9e716ab2eb9244e2 | [
"MIT"
] | null | null | null | src/main/java/org/llaith/onyx/toolkit/etc/context/Configs.java | llaith/onyx-toolkit | 28bb9414927f933bde58812f9e716ab2eb9244e2 | [
"MIT"
] | null | null | null | src/main/java/org/llaith/onyx/toolkit/etc/context/Configs.java | llaith/onyx-toolkit | 28bb9414927f933bde58812f9e716ab2eb9244e2 | [
"MIT"
] | null | null | null | 24.525424 | 117 | 0.64962 | 999,449 | /*
* Copyright (c) 2016.
*/
package org.llaith.onyx.toolkit.etc.context;
import org.llaith.onyx.toolkit.exception.UncheckedException;
import java.util.HashMap;
import java.util.Map;
/**
* This is a similar class to Register, the very simple way to config and share services. Primarily
* this avoids having to do lots of Guard.notNull()'s around the code, and also stops duplicate
* registrations.
*
* USAGE: be careful of anon config classes like new SomeConfig() {{}} It will work, but you will only get
* to put one in.
*/
public class Configs {
private final Map<Class<?>,Object> index = new HashMap<>();
public Configs register(final Object config) {
final Class<?> klass = config.getClass().isAnonymousClass() ?
config.getClass().getSuperclass() :
config.getClass();
if (index.containsKey(klass)) throw new UncheckedException("Duplicate registration of config class: "+klass);
this.index.put(
klass,
config);
return this;
}
public boolean hasConfigFor(final Class<?> klass) {
return this.index.containsKey(klass);
}
@SuppressWarnings("unchecked")
public final <X> X configFor(final Class<X> klass) {
final X config = (X)this.index.get(klass);
if (config == null) throw new UncheckedException("Cannot find config for class: "+klass);
return config;
}
}
|
923b1547f1b978631892672f1ab79a84691e8f3f | 956 | java | Java | bundles/sirix-core/src/main/java/org/sirix/index/cas/CASIndexListenerFactory.java | PLSV/sirix | f91322d293404d0568b5562dc8bc021741822cd1 | [
"BSD-3-Clause"
] | null | null | null | bundles/sirix-core/src/main/java/org/sirix/index/cas/CASIndexListenerFactory.java | PLSV/sirix | f91322d293404d0568b5562dc8bc021741822cd1 | [
"BSD-3-Clause"
] | null | null | null | bundles/sirix-core/src/main/java/org/sirix/index/cas/CASIndexListenerFactory.java | PLSV/sirix | f91322d293404d0568b5562dc8bc021741822cd1 | [
"BSD-3-Clause"
] | null | null | null | 39.833333 | 106 | 0.794979 | 999,450 | package org.sirix.index.cas;
import static com.google.common.base.Preconditions.checkNotNull;
import org.sirix.api.PageTrx;
import org.sirix.index.IndexDef;
import org.sirix.index.redblacktree.RBTreeWriter;
import org.sirix.index.redblacktree.keyvalue.CASValue;
import org.sirix.index.redblacktree.keyvalue.NodeReferences;
import org.sirix.index.path.summary.PathSummaryReader;
public final class CASIndexListenerFactory {
public CASIndexListener create(final PageTrx pageTrx,
final PathSummaryReader pathSummaryReader, final IndexDef indexDef) {
final var pathSummary = checkNotNull(pathSummaryReader);
final var avlTreeWriter =
RBTreeWriter.<CASValue, NodeReferences>getInstance(pageTrx, indexDef.getType(), indexDef.getID());
final var type = checkNotNull(indexDef.getContentType());
final var paths = checkNotNull(indexDef.getPaths());
return new CASIndexListener(pathSummary, avlTreeWriter, paths, type);
}
}
|
923b16674d906e147b9412aa3f932eabb161df5b | 1,266 | java | Java | src/gsynlib/particles/ParticlesCache.java | gsynuh/processinglib | 2d62db885bd0bb5a8f967ca0f6d0cf1135a148d2 | [
"Apache-2.0"
] | null | null | null | src/gsynlib/particles/ParticlesCache.java | gsynuh/processinglib | 2d62db885bd0bb5a8f967ca0f6d0cf1135a148d2 | [
"Apache-2.0"
] | null | null | null | src/gsynlib/particles/ParticlesCache.java | gsynuh/processinglib | 2d62db885bd0bb5a8f967ca0f6d0cf1135a148d2 | [
"Apache-2.0"
] | null | null | null | 20.095238 | 87 | 0.699842 | 999,451 | package gsynlib.particles;
import processing.core.*;
import static processing.core.PApplet.*;
import java.util.*;
import java.util.Map.*;
public class ParticlesCache {
public float precisionAngle = 0.1f;
public float minDist = 0f;
public float maxDist = 20f;
public Boolean enabled = false;
Map<Particle,CachedParticle> cachedParticles = new HashMap<Particle,CachedParticle>();
public Map<Particle,CachedParticle> getCache() {
return cachedParticles;
}
public CachedParticle getParticleCache(Particle p) {
return cachedParticles.get(p);
}
public void clearParticles() {
cachedParticles.clear();
}
public void clearPoints() {
for(Entry<Particle,CachedParticle> kvp : cachedParticles.entrySet()) {
CachedParticle cp = kvp.getValue();
cp.clear();
}
}
public void AddParticle(Particle p) {
if(cachedParticles.containsKey(p))
return;
CachedParticle cp = new CachedParticle();
cp.cache = this;
cachedParticles.put(p, cp);
}
public void update() {
for(Entry<Particle,CachedParticle> kvp : cachedParticles.entrySet()) {
Particle p = kvp.getKey();
if(!p.live)
continue;
CachedParticle cp = kvp.getValue();
cp.addPoint(p.position.copy());
}
}
public void simplify() {
}
}
|
923b18c0e9f2cf8c7a4dfa719cd39a19d7320d14 | 792 | java | Java | components/studio-platform/plugins/org.wso2.integrationstudio.utils/src/org/wso2/integrationstudio/utils/wst/WebConstants.java | chanikag/integration-studio | 860542074068146e95960889e281d9dbdeeaeaba | [
"Apache-2.0"
] | 23 | 2020-12-09T09:52:23.000Z | 2022-03-23T03:59:39.000Z | components/studio-platform/plugins/org.wso2.integrationstudio.utils/src/org/wso2/integrationstudio/utils/wst/WebConstants.java | sajithaliyanage/integration-studio | 3329da9fa47e75028edf51f79264b6816bc4e333 | [
"Apache-2.0"
] | 751 | 2020-12-16T12:30:50.000Z | 2022-03-31T07:53:21.000Z | components/studio-platform/plugins/org.wso2.integrationstudio.utils/src/org/wso2/integrationstudio/utils/wst/WebConstants.java | sajithaliyanage/integration-studio | 3329da9fa47e75028edf51f79264b6816bc4e333 | [
"Apache-2.0"
] | 25 | 2020-12-09T09:52:29.000Z | 2022-03-16T06:18:08.000Z | 34.434783 | 75 | 0.728535 | 999,452 | /*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) 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.wso2.integrationstudio.utils.wst;
public class WebConstants {
public static final String DIR_WEB_INF="WEB-INF"; //$NON-NLS-1$
}
|
923b1a838bbb67de20f2c164b60528ea7ee07154 | 326 | java | Java | app/src/main/java/com/yaoh/AndroidDemo2/anim/MyEvaluator.java | desireyao/AndroidDemo2 | 5ba95dd3a2d62a2dd82ec8076be4cb9762e49138 | [
"MIT"
] | null | null | null | app/src/main/java/com/yaoh/AndroidDemo2/anim/MyEvaluator.java | desireyao/AndroidDemo2 | 5ba95dd3a2d62a2dd82ec8076be4cb9762e49138 | [
"MIT"
] | null | null | null | app/src/main/java/com/yaoh/AndroidDemo2/anim/MyEvaluator.java | desireyao/AndroidDemo2 | 5ba95dd3a2d62a2dd82ec8076be4cb9762e49138 | [
"MIT"
] | null | null | null | 19.176471 | 80 | 0.711656 | 999,453 | package com.yaoh.AndroidDemo2.anim;
import android.animation.TypeEvaluator;
/**
* @author yaoh
* @date 2020-03-17 17:24
* @description TODO
*/
public class MyEvaluator implements TypeEvaluator {
@Override
public Object evaluate(float fraction, Object startValue, Object endValue) {
return null;
}
}
|
923b1ac143f775614bfc59335d3d756ac8ae66f4 | 114,628 | java | Java | management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkSecurityGroupOperationsImpl.java | xindzhan/azure-sdk-for-java | 97b4f2a28f212d76fa8fdaea77f59358fabbd955 | [
"Apache-2.0"
] | null | null | null | management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkSecurityGroupOperationsImpl.java | xindzhan/azure-sdk-for-java | 97b4f2a28f212d76fa8fdaea77f59358fabbd955 | [
"Apache-2.0"
] | 1 | 2021-06-04T01:23:47.000Z | 2021-06-04T01:23:47.000Z | management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkSecurityGroupOperationsImpl.java | xindzhan/azure-sdk-for-java | 97b4f2a28f212d76fa8fdaea77f59358fabbd955 | [
"Apache-2.0"
] | null | null | null | 51.013796 | 339 | 0.647913 | 999,454 | /**
*
* Copyright (c) Microsoft and contributors. 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.
*
*/
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
package com.microsoft.windowsazure.management.network;
import com.microsoft.windowsazure.core.OperationStatus;
import com.microsoft.windowsazure.core.OperationStatusResponse;
import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete;
import com.microsoft.windowsazure.core.utils.BOMInputStream;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.network.models.NetworkSecurityGroup;
import com.microsoft.windowsazure.management.network.models.NetworkSecurityGroupAddToSubnetParameters;
import com.microsoft.windowsazure.management.network.models.NetworkSecurityGroupCreateParameters;
import com.microsoft.windowsazure.management.network.models.NetworkSecurityGroupGetForSubnetResponse;
import com.microsoft.windowsazure.management.network.models.NetworkSecurityGroupGetResponse;
import com.microsoft.windowsazure.management.network.models.NetworkSecurityGroupListResponse;
import com.microsoft.windowsazure.management.network.models.NetworkSecurityRule;
import com.microsoft.windowsazure.management.network.models.NetworkSecuritySetRuleParameters;
import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler;
import com.microsoft.windowsazure.tracing.CloudTracing;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* The Network Management API includes operations for managing the Network
* Security Groups for your subscription.
*/
public class NetworkSecurityGroupOperationsImpl implements ServiceOperations<NetworkManagementClientImpl>, NetworkSecurityGroupOperations {
/**
* Initializes a new instance of the NetworkSecurityGroupOperationsImpl
* class.
*
* @param client Reference to the service client.
*/
NetworkSecurityGroupOperationsImpl(NetworkManagementClientImpl client) {
this.client = client;
}
private NetworkManagementClientImpl client;
/**
* Gets a reference to the
* microsoft.windowsazure.management.network.NetworkManagementClientImpl.
* @return The Client value.
*/
public NetworkManagementClientImpl getClient() {
return this.client;
}
/**
* Adds a Network Security Group to a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param parameters Required. Parameters supplied to the Add Network
* Security Group to subnet operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> addToSubnetAsync(final String virtualNetworkName, final String subnetName, final NetworkSecurityGroupAddToSubnetParameters parameters) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return addToSubnet(virtualNetworkName, subnetName, parameters);
}
});
}
/**
* Adds a Network Security Group to a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param parameters Required. Parameters supplied to the Add Network
* Security Group to subnet operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse addToSubnet(String virtualNetworkName, String subnetName, NetworkSecurityGroupAddToSubnetParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException {
NetworkManagementClient client2 = this.getClient();
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("virtualNetworkName", virtualNetworkName);
tracingParameters.put("subnetName", subnetName);
tracingParameters.put("parameters", parameters);
CloudTracing.enter(invocationId, this, "addToSubnetAsync", tracingParameters);
}
try {
if (shouldTrace) {
client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
}
OperationStatusResponse response = client2.getNetworkSecurityGroupsOperations().beginAddingToSubnetAsync(virtualNetworkName, subnetName, parameters).get();
if (response.getStatus() == OperationStatus.Succeeded) {
return response;
}
OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
int delayInSeconds = 30;
if (client2.getLongRunningOperationInitialTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationInitialTimeout();
}
while ((result.getStatus() != OperationStatus.InProgress) == false) {
Thread.sleep(delayInSeconds * 1000);
result = client2.getOperationStatusAsync(response.getRequestId()).get();
delayInSeconds = 30;
if (client2.getLongRunningOperationRetryTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationRetryTimeout();
}
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
if (result.getStatus() != OperationStatus.Succeeded) {
if (result.getError() != null) {
ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage());
ex.setErrorCode(result.getError().getCode());
ex.setErrorMessage(result.getError().getMessage());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
} else {
ServiceException ex = new ServiceException("");
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
}
return result;
} finally {
if (client2 != null && shouldTrace) {
client2.close();
}
}
}
/**
* Adds a Network Security Group to a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param parameters Required. Parameters supplied to the Add Network
* Security Group to subnet operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> beginAddingToSubnetAsync(final String virtualNetworkName, final String subnetName, final NetworkSecurityGroupAddToSubnetParameters parameters) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return beginAddingToSubnet(virtualNetworkName, subnetName, parameters);
}
});
}
/**
* Adds a Network Security Group to a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param parameters Required. Parameters supplied to the Add Network
* Security Group to subnet operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginAddingToSubnet(String virtualNetworkName, String subnetName, NetworkSecurityGroupAddToSubnetParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
// Validate
if (virtualNetworkName == null) {
throw new NullPointerException("virtualNetworkName");
}
if (subnetName == null) {
throw new NullPointerException("subnetName");
}
if (parameters == null) {
throw new NullPointerException("parameters");
}
if (parameters.getName() == null) {
throw new NullPointerException("parameters.Name");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("virtualNetworkName", virtualNetworkName);
tracingParameters.put("subnetName", subnetName);
tracingParameters.put("parameters", parameters);
CloudTracing.enter(invocationId, this, "beginAddingToSubnetAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/virtualnetwork/" + virtualNetworkName.trim() + "/subnets/" + subnetName.trim() + "/networksecuritygroups";
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
HttpPost httpRequest = new HttpPost(url);
// Set Headers
httpRequest.setHeader("Content-Type", "application/xml");
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Serialize Request
String requestContent = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document requestDoc = documentBuilder.newDocument();
Element networkSecurityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
requestDoc.appendChild(networkSecurityGroupElement);
Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
networkSecurityGroupElement.appendChild(nameElement);
DOMSource domSource = new DOMSource(requestDoc);
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(domSource, streamResult);
requestContent = stringWriter.toString();
StringEntity entity = new StringEntity(requestContent);
httpRequest.setEntity(entity);
httpRequest.setHeader("Content-Type", "application/xml");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_ACCEPTED) {
ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
result = new OperationStatusResponse();
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Creates a new Network Security Group.
*
* @param parameters Required. Parameters supplied to the Create Network
* Security Group operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> beginCreatingAsync(final NetworkSecurityGroupCreateParameters parameters) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return beginCreating(parameters);
}
});
}
/**
* Creates a new Network Security Group.
*
* @param parameters Required. Parameters supplied to the Create Network
* Security Group operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginCreating(NetworkSecurityGroupCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
// Validate
if (parameters == null) {
throw new NullPointerException("parameters");
}
if (parameters.getLocation() == null) {
throw new NullPointerException("parameters.Location");
}
if (parameters.getName() == null) {
throw new NullPointerException("parameters.Name");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("parameters", parameters);
CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/networksecuritygroups";
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
HttpPost httpRequest = new HttpPost(url);
// Set Headers
httpRequest.setHeader("Content-Type", "application/xml");
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Serialize Request
String requestContent = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document requestDoc = documentBuilder.newDocument();
Element networkSecurityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
requestDoc.appendChild(networkSecurityGroupElement);
Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
networkSecurityGroupElement.appendChild(nameElement);
if (parameters.getLabel() != null) {
Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
networkSecurityGroupElement.appendChild(labelElement);
}
Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Location");
locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
networkSecurityGroupElement.appendChild(locationElement);
DOMSource domSource = new DOMSource(requestDoc);
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(domSource, streamResult);
requestContent = stringWriter.toString();
StringEntity entity = new StringEntity(requestContent);
httpRequest.setEntity(entity);
httpRequest.setHeader("Content-Type", "application/xml");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_ACCEPTED) {
ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
result = new OperationStatusResponse();
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Deletes the pecified Network Security Group from your subscription.If the
* Network Security group is still associated with some VM/Role/Subnet, the
* deletion will fail. In order to successfully delete the Network
* Security, it needs to be not used.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group to delete.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> beginDeletingAsync(final String networkSecurityGroupName) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return beginDeleting(networkSecurityGroupName);
}
});
}
/**
* Deletes the pecified Network Security Group from your subscription.If the
* Network Security group is still associated with some VM/Role/Subnet, the
* deletion will fail. In order to successfully delete the Network
* Security, it needs to be not used.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group to delete.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginDeleting(String networkSecurityGroupName) throws IOException, ServiceException, ParserConfigurationException, SAXException {
// Validate
if (networkSecurityGroupName == null) {
throw new NullPointerException("networkSecurityGroupName");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/networksecuritygroups/" + networkSecurityGroupName.trim();
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
CustomHttpDelete httpRequest = new CustomHttpDelete(url);
// Set Headers
httpRequest.setHeader("Content-Type", "application/xml");
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_ACCEPTED) {
ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
result = new OperationStatusResponse();
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Deletes a rule from the specified Network Security Group.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group.
* @param ruleName Required. The name of the rule to delete.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> beginDeletingRuleAsync(final String networkSecurityGroupName, final String ruleName) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return beginDeletingRule(networkSecurityGroupName, ruleName);
}
});
}
/**
* Deletes a rule from the specified Network Security Group.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group.
* @param ruleName Required. The name of the rule to delete.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginDeletingRule(String networkSecurityGroupName, String ruleName) throws IOException, ServiceException {
// Validate
if (networkSecurityGroupName == null) {
throw new NullPointerException("networkSecurityGroupName");
}
if (ruleName == null) {
throw new NullPointerException("ruleName");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.put("ruleName", ruleName);
CloudTracing.enter(invocationId, this, "beginDeletingRuleAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/networksecuritygroups/" + networkSecurityGroupName.trim() + "/rules/" + ruleName.trim();
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
CustomHttpDelete httpRequest = new CustomHttpDelete(url);
// Set Headers
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_ACCEPTED) {
ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
result = new OperationStatusResponse();
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Removes a Network Security Group from a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param networkSecurityGroupName Required.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> beginRemovingFromSubnetAsync(final String virtualNetworkName, final String subnetName, final String networkSecurityGroupName) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return beginRemovingFromSubnet(virtualNetworkName, subnetName, networkSecurityGroupName);
}
});
}
/**
* Removes a Network Security Group from a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param networkSecurityGroupName Required.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginRemovingFromSubnet(String virtualNetworkName, String subnetName, String networkSecurityGroupName) throws IOException, ServiceException {
// Validate
if (virtualNetworkName == null) {
throw new NullPointerException("virtualNetworkName");
}
if (subnetName == null) {
throw new NullPointerException("subnetName");
}
if (networkSecurityGroupName == null) {
throw new NullPointerException("networkSecurityGroupName");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("virtualNetworkName", virtualNetworkName);
tracingParameters.put("subnetName", subnetName);
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
CloudTracing.enter(invocationId, this, "beginRemovingFromSubnetAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/virtualnetwork/" + virtualNetworkName.trim() + "/subnets/" + subnetName.trim() + "/networksecuritygroups/" + networkSecurityGroupName.trim();
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
CustomHttpDelete httpRequest = new CustomHttpDelete(url);
// Set Headers
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_ACCEPTED) {
ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
result = new OperationStatusResponse();
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Sets a new Network Security Rule to existing Network Security Group.
*
* @param networkSecurityGroupName Optional.
* @param ruleName Optional.
* @param parameters Required. Parameters supplied to the Set Network
* Security Rule operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> beginSettingRuleAsync(final String networkSecurityGroupName, final String ruleName, final NetworkSecuritySetRuleParameters parameters) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return beginSettingRule(networkSecurityGroupName, ruleName, parameters);
}
});
}
/**
* Sets a new Network Security Rule to existing Network Security Group.
*
* @param networkSecurityGroupName Optional.
* @param ruleName Optional.
* @param parameters Required. Parameters supplied to the Set Network
* Security Rule operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginSettingRule(String networkSecurityGroupName, String ruleName, NetworkSecuritySetRuleParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
// Validate
if (parameters == null) {
throw new NullPointerException("parameters");
}
if (parameters.getAction() == null) {
throw new NullPointerException("parameters.Action");
}
if (parameters.getDestinationAddressPrefix() == null) {
throw new NullPointerException("parameters.DestinationAddressPrefix");
}
if (parameters.getDestinationPortRange() == null) {
throw new NullPointerException("parameters.DestinationPortRange");
}
if (parameters.getProtocol() == null) {
throw new NullPointerException("parameters.Protocol");
}
if (parameters.getSourceAddressPrefix() == null) {
throw new NullPointerException("parameters.SourceAddressPrefix");
}
if (parameters.getSourcePortRange() == null) {
throw new NullPointerException("parameters.SourcePortRange");
}
if (parameters.getType() == null) {
throw new NullPointerException("parameters.Type");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.put("ruleName", ruleName);
tracingParameters.put("parameters", parameters);
CloudTracing.enter(invocationId, this, "beginSettingRuleAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/networksecuritygroups/" + (networkSecurityGroupName != null ? networkSecurityGroupName.trim() : "") + "/rules/" + (ruleName != null ? ruleName.trim() : "");
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
HttpPut httpRequest = new HttpPut(url);
// Set Headers
httpRequest.setHeader("Content-Type", "application/xml");
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Serialize Request
String requestContent = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document requestDoc = documentBuilder.newDocument();
Element ruleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rule");
requestDoc.appendChild(ruleElement);
Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type");
typeElement.appendChild(requestDoc.createTextNode(parameters.getType()));
ruleElement.appendChild(typeElement);
Element priorityElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Priority");
priorityElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getPriority())));
ruleElement.appendChild(priorityElement);
Element actionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Action");
actionElement.appendChild(requestDoc.createTextNode(parameters.getAction()));
ruleElement.appendChild(actionElement);
Element sourceAddressPrefixElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceAddressPrefix");
sourceAddressPrefixElement.appendChild(requestDoc.createTextNode(parameters.getSourceAddressPrefix()));
ruleElement.appendChild(sourceAddressPrefixElement);
Element sourcePortRangeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourcePortRange");
sourcePortRangeElement.appendChild(requestDoc.createTextNode(parameters.getSourcePortRange()));
ruleElement.appendChild(sourcePortRangeElement);
Element destinationAddressPrefixElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DestinationAddressPrefix");
destinationAddressPrefixElement.appendChild(requestDoc.createTextNode(parameters.getDestinationAddressPrefix()));
ruleElement.appendChild(destinationAddressPrefixElement);
Element destinationPortRangeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DestinationPortRange");
destinationPortRangeElement.appendChild(requestDoc.createTextNode(parameters.getDestinationPortRange()));
ruleElement.appendChild(destinationPortRangeElement);
Element protocolElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
protocolElement.appendChild(requestDoc.createTextNode(parameters.getProtocol()));
ruleElement.appendChild(protocolElement);
DOMSource domSource = new DOMSource(requestDoc);
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(domSource, streamResult);
requestContent = stringWriter.toString();
StringEntity entity = new StringEntity(requestContent);
httpRequest.setEntity(entity);
httpRequest.setHeader("Content-Type", "application/xml");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_ACCEPTED) {
ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
result = new OperationStatusResponse();
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Creates a new Network Security Group.
*
* @param parameters Required. Parameters supplied to the Create Network
* Security Group operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> createAsync(final NetworkSecurityGroupCreateParameters parameters) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return create(parameters);
}
});
}
/**
* Creates a new Network Security Group.
*
* @param parameters Required. Parameters supplied to the Create Network
* Security Group operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse create(NetworkSecurityGroupCreateParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException {
NetworkManagementClient client2 = this.getClient();
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("parameters", parameters);
CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
}
try {
if (shouldTrace) {
client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
}
OperationStatusResponse response = client2.getNetworkSecurityGroupsOperations().beginCreatingAsync(parameters).get();
if (response.getStatus() == OperationStatus.Succeeded) {
return response;
}
OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
int delayInSeconds = 30;
if (client2.getLongRunningOperationInitialTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationInitialTimeout();
}
while ((result.getStatus() != OperationStatus.InProgress) == false) {
Thread.sleep(delayInSeconds * 1000);
result = client2.getOperationStatusAsync(response.getRequestId()).get();
delayInSeconds = 30;
if (client2.getLongRunningOperationRetryTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationRetryTimeout();
}
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
if (result.getStatus() != OperationStatus.Succeeded) {
if (result.getError() != null) {
ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage());
ex.setErrorCode(result.getError().getCode());
ex.setErrorMessage(result.getError().getMessage());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
} else {
ServiceException ex = new ServiceException("");
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
}
return result;
} finally {
if (client2 != null && shouldTrace) {
client2.close();
}
}
}
/**
* The Delete Network Security Group operation removes thespecified Network
* Security Group from your subscription.If the Network Security group is
* still associated with some VM/Role/Subnet, the deletion will fail. In
* order to successfully delete the Network Security, it needs to be not
* used.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group to delete.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> deleteAsync(final String networkSecurityGroupName) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return delete(networkSecurityGroupName);
}
});
}
/**
* The Delete Network Security Group operation removes thespecified Network
* Security Group from your subscription.If the Network Security group is
* still associated with some VM/Role/Subnet, the deletion will fail. In
* order to successfully delete the Network Security, it needs to be not
* used.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group to delete.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse delete(String networkSecurityGroupName) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException {
NetworkManagementClient client2 = this.getClient();
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
}
try {
if (shouldTrace) {
client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
}
OperationStatusResponse response = client2.getNetworkSecurityGroupsOperations().beginDeletingAsync(networkSecurityGroupName).get();
if (response.getStatus() == OperationStatus.Succeeded) {
return response;
}
OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
int delayInSeconds = 30;
if (client2.getLongRunningOperationInitialTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationInitialTimeout();
}
while ((result.getStatus() != OperationStatus.InProgress) == false) {
Thread.sleep(delayInSeconds * 1000);
result = client2.getOperationStatusAsync(response.getRequestId()).get();
delayInSeconds = 30;
if (client2.getLongRunningOperationRetryTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationRetryTimeout();
}
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
if (result.getStatus() != OperationStatus.Succeeded) {
if (result.getError() != null) {
ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage());
ex.setErrorCode(result.getError().getCode());
ex.setErrorMessage(result.getError().getMessage());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
} else {
ServiceException ex = new ServiceException("");
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
}
return result;
} finally {
if (client2 != null && shouldTrace) {
client2.close();
}
}
}
/**
* The Delete Network Security Rule operation removes a rule from the
* specified Network Security Group.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group.
* @param ruleName Required. The name of the rule to delete.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> deleteRuleAsync(final String networkSecurityGroupName, final String ruleName) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return deleteRule(networkSecurityGroupName, ruleName);
}
});
}
/**
* The Delete Network Security Rule operation removes a rule from the
* specified Network Security Group.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group.
* @param ruleName Required. The name of the rule to delete.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse deleteRule(String networkSecurityGroupName, String ruleName) throws InterruptedException, ExecutionException, ServiceException, IOException {
NetworkManagementClient client2 = this.getClient();
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.put("ruleName", ruleName);
CloudTracing.enter(invocationId, this, "deleteRuleAsync", tracingParameters);
}
try {
if (shouldTrace) {
client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
}
OperationStatusResponse response = client2.getNetworkSecurityGroupsOperations().beginDeletingRuleAsync(networkSecurityGroupName, ruleName).get();
if (response.getStatus() == OperationStatus.Succeeded) {
return response;
}
OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
int delayInSeconds = 30;
if (client2.getLongRunningOperationInitialTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationInitialTimeout();
}
while ((result.getStatus() != OperationStatus.InProgress) == false) {
Thread.sleep(delayInSeconds * 1000);
result = client2.getOperationStatusAsync(response.getRequestId()).get();
delayInSeconds = 30;
if (client2.getLongRunningOperationRetryTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationRetryTimeout();
}
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
if (result.getStatus() != OperationStatus.Succeeded) {
if (result.getError() != null) {
ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage());
ex.setErrorCode(result.getError().getCode());
ex.setErrorMessage(result.getError().getMessage());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
} else {
ServiceException ex = new ServiceException("");
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
}
return result;
} finally {
if (client2 != null && shouldTrace) {
client2.close();
}
}
}
/**
* Gets the details for the specified Network Security Group in the
* subscription.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group to retrieve.
* @param detailLevel Optional. Use 'Full' to list rules.
* @return A Network Security Group associated with your subscription.
*/
@Override
public Future<NetworkSecurityGroupGetResponse> getAsync(final String networkSecurityGroupName, final String detailLevel) {
return this.getClient().getExecutorService().submit(new Callable<NetworkSecurityGroupGetResponse>() {
@Override
public NetworkSecurityGroupGetResponse call() throws Exception {
return get(networkSecurityGroupName, detailLevel);
}
});
}
/**
* Gets the details for the specified Network Security Group in the
* subscription.
*
* @param networkSecurityGroupName Required. The name of the Network
* Security Group to retrieve.
* @param detailLevel Optional. Use 'Full' to list rules.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return A Network Security Group associated with your subscription.
*/
@Override
public NetworkSecurityGroupGetResponse get(String networkSecurityGroupName, String detailLevel) throws IOException, ServiceException, ParserConfigurationException, SAXException {
// Validate
if (networkSecurityGroupName == null) {
throw new NullPointerException("networkSecurityGroupName");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.put("detailLevel", detailLevel);
CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/networksecuritygroups/" + networkSecurityGroupName.trim() + "?";
if (detailLevel != null) {
url = url + "detaillevel=" + URLEncoder.encode(detailLevel != null ? detailLevel.trim() : "", "UTF-8");
}
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
HttpGet httpRequest = new HttpGet(url);
// Set Headers
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
NetworkSecurityGroupGetResponse result = null;
// Deserialize Response
InputStream responseContent = httpResponse.getEntity().getContent();
result = new NetworkSecurityGroupGetResponse();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));
Element networkSecurityGroupElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
if (networkSecurityGroupElement != null) {
Element nameElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupElement, "http://schemas.microsoft.com/windowsazure", "Name");
if (nameElement != null) {
String nameInstance;
nameInstance = nameElement.getTextContent();
result.setName(nameInstance);
}
Element labelElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupElement, "http://schemas.microsoft.com/windowsazure", "Label");
if (labelElement != null) {
String labelInstance;
labelInstance = labelElement.getTextContent();
result.setLabel(labelInstance);
}
Element locationElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupElement, "http://schemas.microsoft.com/windowsazure", "Location");
if (locationElement != null) {
String locationInstance;
locationInstance = locationElement.getTextContent();
result.setLocation(locationInstance);
}
Element rulesSequenceElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupElement, "http://schemas.microsoft.com/windowsazure", "Rules");
if (rulesSequenceElement != null) {
for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").size(); i1 = i1 + 1) {
org.w3c.dom.Element rulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").get(i1));
NetworkSecurityRule ruleInstance = new NetworkSecurityRule();
result.getRules().add(ruleInstance);
Element nameElement2 = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Name");
if (nameElement2 != null) {
String nameInstance2;
nameInstance2 = nameElement2.getTextContent();
ruleInstance.setName(nameInstance2);
}
Element typeElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Type");
if (typeElement != null) {
String typeInstance;
typeInstance = typeElement.getTextContent();
ruleInstance.setType(typeInstance);
}
Element priorityElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Priority");
if (priorityElement != null) {
int priorityInstance;
priorityInstance = DatatypeConverter.parseInt(priorityElement.getTextContent());
ruleInstance.setPriority(priorityInstance);
}
Element actionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Action");
if (actionElement != null) {
String actionInstance;
actionInstance = actionElement.getTextContent();
ruleInstance.setAction(actionInstance);
}
Element sourceAddressPrefixElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "SourceAddressPrefix");
if (sourceAddressPrefixElement != null) {
String sourceAddressPrefixInstance;
sourceAddressPrefixInstance = sourceAddressPrefixElement.getTextContent();
ruleInstance.setSourceAddressPrefix(sourceAddressPrefixInstance);
}
Element sourcePortRangeElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "SourcePortRange");
if (sourcePortRangeElement != null) {
String sourcePortRangeInstance;
sourcePortRangeInstance = sourcePortRangeElement.getTextContent();
ruleInstance.setSourcePortRange(sourcePortRangeInstance);
}
Element destinationAddressPrefixElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "DestinationAddressPrefix");
if (destinationAddressPrefixElement != null) {
String destinationAddressPrefixInstance;
destinationAddressPrefixInstance = destinationAddressPrefixElement.getTextContent();
ruleInstance.setDestinationAddressPrefix(destinationAddressPrefixInstance);
}
Element destinationPortRangeElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "DestinationPortRange");
if (destinationPortRangeElement != null) {
String destinationPortRangeInstance;
destinationPortRangeInstance = destinationPortRangeElement.getTextContent();
ruleInstance.setDestinationPortRange(destinationPortRangeInstance);
}
Element protocolElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Protocol");
if (protocolElement != null) {
String protocolInstance;
protocolInstance = protocolElement.getTextContent();
ruleInstance.setProtocol(protocolInstance);
}
Element stateElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "State");
if (stateElement != null) {
String stateInstance;
stateInstance = stateElement.getTextContent();
ruleInstance.setState(stateInstance);
}
Element isDefaultElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "IsDefault");
if (isDefaultElement != null) {
boolean isDefaultInstance;
isDefaultInstance = DatatypeConverter.parseBoolean(isDefaultElement.getTextContent().toLowerCase());
ruleInstance.setIsDefault(isDefaultInstance);
}
}
}
}
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Gets the Network Security Group applied to a specific subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @return The Network Security Group associated with a subnet.
*/
@Override
public Future<NetworkSecurityGroupGetForSubnetResponse> getForSubnetAsync(final String virtualNetworkName, final String subnetName) {
return this.getClient().getExecutorService().submit(new Callable<NetworkSecurityGroupGetForSubnetResponse>() {
@Override
public NetworkSecurityGroupGetForSubnetResponse call() throws Exception {
return getForSubnet(virtualNetworkName, subnetName);
}
});
}
/**
* Gets the Network Security Group applied to a specific subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The Network Security Group associated with a subnet.
*/
@Override
public NetworkSecurityGroupGetForSubnetResponse getForSubnet(String virtualNetworkName, String subnetName) throws IOException, ServiceException, ParserConfigurationException, SAXException {
// Validate
if (virtualNetworkName == null) {
throw new NullPointerException("virtualNetworkName");
}
if (subnetName == null) {
throw new NullPointerException("subnetName");
}
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("virtualNetworkName", virtualNetworkName);
tracingParameters.put("subnetName", subnetName);
CloudTracing.enter(invocationId, this, "getForSubnetAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/virtualnetwork/" + virtualNetworkName.trim() + "/subnets/" + subnetName.trim() + "/networksecuritygroups";
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
HttpGet httpRequest = new HttpGet(url);
// Set Headers
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
NetworkSecurityGroupGetForSubnetResponse result = null;
// Deserialize Response
InputStream responseContent = httpResponse.getEntity().getContent();
result = new NetworkSecurityGroupGetForSubnetResponse();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));
Element networkSecurityGroupElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
if (networkSecurityGroupElement != null) {
Element nameElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupElement, "http://schemas.microsoft.com/windowsazure", "Name");
if (nameElement != null) {
String nameInstance;
nameInstance = nameElement.getTextContent();
result.setName(nameInstance);
}
Element stateElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupElement, "http://schemas.microsoft.com/windowsazure", "State");
if (stateElement != null) {
String stateInstance;
stateInstance = stateElement.getTextContent();
result.setState(stateInstance);
}
}
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Lists all of the Network Security Groups for the subscription.
*
* @return The List Definitions operation response.
*/
@Override
public Future<NetworkSecurityGroupListResponse> listAsync() {
return this.getClient().getExecutorService().submit(new Callable<NetworkSecurityGroupListResponse>() {
@Override
public NetworkSecurityGroupListResponse call() throws Exception {
return list();
}
});
}
/**
* Lists all of the Network Security Groups for the subscription.
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The List Definitions operation response.
*/
@Override
public NetworkSecurityGroupListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException {
// Validate
// Tracing
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
CloudTracing.enter(invocationId, this, "listAsync", tracingParameters);
}
// Construct URL
String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null ? this.getClient().getCredentials().getSubscriptionId().trim() : "") + "/services/networking/networksecuritygroups";
String baseUrl = this.getClient().getBaseUri().toString();
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
}
if (url.charAt(0) == '/') {
url = url.substring(1);
}
url = baseUrl + "/" + url;
url = url.replace(" ", "%20");
// Create HTTP transport objects
HttpGet httpRequest = new HttpGet(url);
// Set Headers
httpRequest.setHeader("x-ms-version", "2014-10-01");
// Send Request
HttpResponse httpResponse = null;
try {
if (shouldTrace) {
CloudTracing.sendRequest(invocationId, httpRequest);
}
httpResponse = this.getClient().getHttpClient().execute(httpRequest);
if (shouldTrace) {
CloudTracing.receiveResponse(invocationId, httpResponse);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
// Create Result
NetworkSecurityGroupListResponse result = null;
// Deserialize Response
InputStream responseContent = httpResponse.getEntity().getContent();
result = new NetworkSecurityGroupListResponse();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));
Element networkSecurityGroupsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroups");
if (networkSecurityGroupsSequenceElement != null) {
for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(networkSecurityGroupsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup").size(); i1 = i1 + 1) {
org.w3c.dom.Element networkSecurityGroupsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(networkSecurityGroupsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup").get(i1));
NetworkSecurityGroup networkSecurityGroupInstance = new NetworkSecurityGroup();
result.getNetworkSecurityGroups().add(networkSecurityGroupInstance);
Element nameElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Name");
if (nameElement != null) {
String nameInstance;
nameInstance = nameElement.getTextContent();
networkSecurityGroupInstance.setName(nameInstance);
}
Element labelElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Label");
if (labelElement != null) {
String labelInstance;
labelInstance = labelElement.getTextContent();
networkSecurityGroupInstance.setLabel(labelInstance);
}
Element locationElement = XmlUtility.getElementByTagNameNS(networkSecurityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Location");
if (locationElement != null) {
String locationInstance;
locationInstance = locationElement.getTextContent();
networkSecurityGroupInstance.setLocation(locationInstance);
}
}
}
result.setStatusCode(statusCode);
if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
return result;
} finally {
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().getContent().close();
}
}
}
/**
* Removes a Network Security Group from a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param networkSecurityGroupName Required.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> removeFromSubnetAsync(final String virtualNetworkName, final String subnetName, final String networkSecurityGroupName) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return removeFromSubnet(virtualNetworkName, subnetName, networkSecurityGroupName);
}
});
}
/**
* Removes a Network Security Group from a subnet.
*
* @param virtualNetworkName Required.
* @param subnetName Required.
* @param networkSecurityGroupName Required.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse removeFromSubnet(String virtualNetworkName, String subnetName, String networkSecurityGroupName) throws InterruptedException, ExecutionException, ServiceException, IOException {
NetworkManagementClient client2 = this.getClient();
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("virtualNetworkName", virtualNetworkName);
tracingParameters.put("subnetName", subnetName);
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
CloudTracing.enter(invocationId, this, "removeFromSubnetAsync", tracingParameters);
}
try {
if (shouldTrace) {
client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
}
OperationStatusResponse response = client2.getNetworkSecurityGroupsOperations().beginRemovingFromSubnetAsync(virtualNetworkName, subnetName, networkSecurityGroupName).get();
if (response.getStatus() == OperationStatus.Succeeded) {
return response;
}
OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
int delayInSeconds = 30;
if (client2.getLongRunningOperationInitialTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationInitialTimeout();
}
while ((result.getStatus() != OperationStatus.InProgress) == false) {
Thread.sleep(delayInSeconds * 1000);
result = client2.getOperationStatusAsync(response.getRequestId()).get();
delayInSeconds = 30;
if (client2.getLongRunningOperationRetryTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationRetryTimeout();
}
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
if (result.getStatus() != OperationStatus.Succeeded) {
if (result.getError() != null) {
ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage());
ex.setErrorCode(result.getError().getCode());
ex.setErrorMessage(result.getError().getMessage());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
} else {
ServiceException ex = new ServiceException("");
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
}
return result;
} finally {
if (client2 != null && shouldTrace) {
client2.close();
}
}
}
/**
* Add new Network Security Rule to existing Network Security Group.
*
* @param networkSecurityGroupName Optional.
* @param ruleName Optional.
* @param parameters Required. Parameters supplied to the Set Network
* Security Rule operation.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public Future<OperationStatusResponse> setRuleAsync(final String networkSecurityGroupName, final String ruleName, final NetworkSecuritySetRuleParameters parameters) {
return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
@Override
public OperationStatusResponse call() throws Exception {
return setRule(networkSecurityGroupName, ruleName, parameters);
}
});
}
/**
* Add new Network Security Rule to existing Network Security Group.
*
* @param networkSecurityGroupName Optional.
* @param ruleName Optional.
* @param parameters Required. Parameters supplied to the Set Network
* Security Rule operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse setRule(String networkSecurityGroupName, String ruleName, NetworkSecuritySetRuleParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException {
NetworkManagementClient client2 = this.getClient();
boolean shouldTrace = CloudTracing.getIsEnabled();
String invocationId = null;
if (shouldTrace) {
invocationId = Long.toString(CloudTracing.getNextInvocationId());
HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
tracingParameters.put("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.put("ruleName", ruleName);
tracingParameters.put("parameters", parameters);
CloudTracing.enter(invocationId, this, "setRuleAsync", tracingParameters);
}
try {
if (shouldTrace) {
client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
}
OperationStatusResponse response = client2.getNetworkSecurityGroupsOperations().beginSettingRuleAsync(networkSecurityGroupName, ruleName, parameters).get();
if (response.getStatus() == OperationStatus.Succeeded) {
return response;
}
OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
int delayInSeconds = 30;
if (client2.getLongRunningOperationInitialTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationInitialTimeout();
}
while ((result.getStatus() != OperationStatus.InProgress) == false) {
Thread.sleep(delayInSeconds * 1000);
result = client2.getOperationStatusAsync(response.getRequestId()).get();
delayInSeconds = 30;
if (client2.getLongRunningOperationRetryTimeout() >= 0) {
delayInSeconds = client2.getLongRunningOperationRetryTimeout();
}
}
if (shouldTrace) {
CloudTracing.exit(invocationId, result);
}
if (result.getStatus() != OperationStatus.Succeeded) {
if (result.getError() != null) {
ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage());
ex.setErrorCode(result.getError().getCode());
ex.setErrorMessage(result.getError().getMessage());
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
} else {
ServiceException ex = new ServiceException("");
if (shouldTrace) {
CloudTracing.error(invocationId, ex);
}
throw ex;
}
}
return result;
} finally {
if (client2 != null && shouldTrace) {
client2.close();
}
}
}
}
|
923b1ce0e002617911996abda5edacc591365370 | 3,234 | java | Java | back-end/hospital-api/src/main/java/net/pladema/auditable/service/AuditableDocumentServiceImpl.java | eamanu/HistorialClinica-LaRioja | 988cd5fae4b9b9bd3a17518b7e55585df5ef7218 | [
"Apache-2.0"
] | null | null | null | back-end/hospital-api/src/main/java/net/pladema/auditable/service/AuditableDocumentServiceImpl.java | eamanu/HistorialClinica-LaRioja | 988cd5fae4b9b9bd3a17518b7e55585df5ef7218 | [
"Apache-2.0"
] | null | null | null | back-end/hospital-api/src/main/java/net/pladema/auditable/service/AuditableDocumentServiceImpl.java | eamanu/HistorialClinica-LaRioja | 988cd5fae4b9b9bd3a17518b7e55585df5ef7218 | [
"Apache-2.0"
] | 1 | 2021-12-31T09:59:53.000Z | 2021-12-31T09:59:53.000Z | 35.933333 | 120 | 0.685529 | 999,455 | package net.pladema.auditable.service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
import net.pladema.sgx.files.StreamFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import net.pladema.clinichistory.documents.events.OnGenerateDocumentEvent;
import net.pladema.clinichistory.documents.repository.entity.DocumentFile;
import net.pladema.sgx.pdf.PDFDocumentException;
import net.pladema.sgx.pdf.PdfService;
@Component
public class AuditableDocumentServiceImpl implements AuditableService {
private static final Logger LOG = LoggerFactory.getLogger(AuditableDocumentServiceImpl.class);
public static final String OUTPUT = "Output -> {}";
private final StreamFile streamFile;
private final PdfService pdfService;
private final AuditableContextBuilder auditableContextBuilder;
public AuditableDocumentServiceImpl(
StreamFile streamFile,
PdfService pdfService,
AuditableContextBuilder auditableContextBuilder
) {
super();
this.streamFile = streamFile;
this.pdfService = pdfService;
this.auditableContextBuilder = auditableContextBuilder;
}
@Override
public Optional<DocumentFile> save(OnGenerateDocumentEvent event) {
Map<String,Object> contextMap = auditableContextBuilder.buildContext(event.getDocument(), event.getPatientId());
String path = streamFile.buildPathAsString(event.getRelativeDirectory());
String realFileName = event.getUuid();
String fictitiousFileName = event.buildDownloadName();
String checksum = null;
try {
ByteArrayOutputStream output = pdfService.writer(event.getTemplateName(), contextMap);
streamFile.saveFileInDirectory(path, false, output);
checksum = getHash(path);
} catch (IOException | PDFDocumentException e) {
LOG.error("Save document file -> {}", event, e);
}
return Optional.of(new DocumentFile(
event.getDocument().getId(),
event.getSourceId(),
event.getSourceType(),
event.getDocumentTypeId(), path, fictitiousFileName, realFileName, checksum));
}
private static String getHash(String path) {
LOG.debug("Input parameters -> path {}", path);
String result;
String algorithm = "SHA-256";
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] sha256Hash = md.digest(Files.readAllBytes(Paths.get(path)));
result = Base64.getEncoder().encodeToString(sha256Hash);
} catch (NoSuchAlgorithmException e) {
LOG.error("Algorithm doesn't exist -> {} ",algorithm);
result = null;
}
catch (IOException e) {
LOG.error("Error with path file {} ", path, e);
result = null;
}
LOG.debug(OUTPUT, result);
return result;
}
}
|
923b1d76f686580ba83cfe9bd33e67632aedc850 | 3,261 | java | Java | src/main/java/info/loenwind/enderioaddons/EnderIOAddons.java | Dewandrew/Newenderio | cbbaae9e797dcf2a44a7d375d5c2b827e8c85ea8 | [
"Unlicense"
] | 24 | 2015-08-26T01:02:15.000Z | 2021-04-27T04:23:56.000Z | src/main/java/info/loenwind/enderioaddons/EnderIOAddons.java | Dewandrew/Newenderio | cbbaae9e797dcf2a44a7d375d5c2b827e8c85ea8 | [
"Unlicense"
] | 55 | 2015-09-20T06:02:02.000Z | 2021-07-11T23:14:53.000Z | src/main/java/info/loenwind/enderioaddons/EnderIOAddons.java | Dewandrew/Newenderio | cbbaae9e797dcf2a44a7d375d5c2b827e8c85ea8 | [
"Unlicense"
] | 15 | 2015-12-16T02:55:01.000Z | 2019-04-11T17:56:55.000Z | 33.96875 | 240 | 0.774302 | 999,456 | package info.loenwind.enderioaddons;
import info.loenwind.enderioaddons.common.InitAware;
import info.loenwind.enderioaddons.config.ConfigHandler;
import info.loenwind.enderioaddons.machine.part.CommandReloadFortune;
import info.loenwind.enderioaddons.network.Manager;
import info.loenwind.enderioaddons.recipe.Recipes;
import info.loenwind.enderioaddons.timer.Celeb11;
import info.loenwind.enderioaddons.timer.Celeb24;
import info.loenwind.enderioaddons.timer.Scheduler;
import info.loenwind.enderioaddons.timer.Ticker;
import java.util.Locale;
import javax.annotation.Nonnull;
import com.enderio.core.common.Lang;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
@Mod(modid = EnderIOAddons.MODID, name = EnderIOAddons.MOD_NAME, version = EnderIOAddons.VERSION, dependencies = "required-after:EnderIO;after:waterhooks;after:AgriCraft", guiFactory = "info.loenwind.enderioaddons.config.gui.ConfigFactory")
public class EnderIOAddons implements InitAware {
@Nonnull
public static final String MODID = "enderioaddons";
@SuppressWarnings("null")
@Nonnull
public static final String DOMAIN = MODID.toLowerCase(Locale.US);
@Nonnull
public static final String MOD_NAME = "Ender IO Addons";
@Nonnull
public static final String VERSION = "@VERSION@";
@Nonnull
public static final String ENDERIO_VERSION = "@enderio_version@";
@Nonnull
public static final String UPDATE_URL = "http://enderioaddons.loenwind.info/versioninfo_" + ENDERIO_VERSION + ".json?" + VERSION;
@SidedProxy(clientSide = "info.loenwind.enderioaddons.proxy.ClientOnlyProxy", serverSide = "info.loenwind.enderioaddons.proxy.ClientAndServerProxy")
public static InitAware proxy;
@Nonnull
public static final InitAware config = new ConfigHandler();
@Nonnull
public static final InitAware recipes = new Recipes();
@Nonnull
public static final Manager network = new Manager();
@Nonnull
public static final Lang lang = new Lang(DOMAIN);
public static boolean mode24 = false;
@Override
@EventHandler
public void init(FMLPreInitializationEvent event) {
config.init(event);
proxy.init(event);
recipes.init(event);
network.init(event);
}
@Override
@EventHandler
public void init(FMLInitializationEvent event) {
FMLInterModComms.sendRuntimeMessage(MODID, "VersionChecker", "addVersionCheck", UPDATE_URL);
config.init(event);
proxy.init(event);
recipes.init(event);
network.init(event);
}
@Override
@EventHandler
public void init(FMLPostInitializationEvent event) {
config.init(event);
proxy.init(event);
recipes.init(event);
network.init(event);
Ticker.create();
Celeb11.create();
Celeb24.create();
Scheduler.instance.start();
}
@SuppressWarnings("static-method")
@EventHandler
public void serverLoad(FMLServerStartingEvent event) {
event.registerServerCommand(new CommandReloadFortune());
}
}
|
923b1d89aafbc0549f107e386fb4c0e9cc1b6a26 | 767 | java | Java | library/src/main/java/com/github/iojjj/rcbs/BackgroundHolder.java | Iojjj/RoundedCornersBackgroundSpan | 16eceb3a6dba07014f625d187dd95b361ec1826d | [
"Unlicense",
"MIT"
] | 118 | 2016-05-27T08:39:07.000Z | 2022-03-23T00:18:59.000Z | library/src/main/java/com/github/iojjj/rcbs/BackgroundHolder.java | Iojjj/RoundedCornersBackgroundSpan | 16eceb3a6dba07014f625d187dd95b361ec1826d | [
"Unlicense",
"MIT"
] | 7 | 2017-04-13T09:47:26.000Z | 2017-11-30T11:26:31.000Z | library/src/main/java/com/github/iojjj/rcbs/BackgroundHolder.java | Iojjj/RoundedCornersBackgroundSpan | 16eceb3a6dba07014f625d187dd95b361ec1826d | [
"Unlicense",
"MIT"
] | 35 | 2016-07-19T14:06:24.000Z | 2021-04-29T06:01:23.000Z | 15.653061 | 71 | 0.551499 | 999,457 | package com.github.iojjj.rcbs;
/**
* Holder that stores info about background color and position in text.
*/
final class BackgroundHolder {
/**
* Background color.
*/
private int mBgColor;
/**
* Start offset of background.
*/
private int mStart;
/**
* End offset of background.
*/
private int mEnd;
BackgroundHolder(int bgColor) {
mBgColor = bgColor;
}
int getBgColor() {
return mBgColor;
}
int getStart() {
return mStart;
}
int getEnd() {
return mEnd;
}
BackgroundHolder setStart(int start) {
mStart = start;
return this;
}
BackgroundHolder setEnd(int end) {
mEnd = end;
return this;
}
}
|
923b1d947bdc223be4d065582cf159d33526965e | 3,291 | java | Java | src/main/java/us/ihmc/simulationconstructionset/gui/SwingWorker.java | ihmcrobotics/simulation-construction-set | 98d7bb859164025aad1a7ce5d1a021051c8c2537 | [
"Apache-2.0"
] | 11 | 2018-11-03T02:51:24.000Z | 2022-01-08T03:11:31.000Z | src/main/java/us/ihmc/simulationconstructionset/gui/SwingWorker.java | ihmcrobotics/simulation-construction-set | 98d7bb859164025aad1a7ce5d1a021051c8c2537 | [
"Apache-2.0"
] | 28 | 2018-08-13T21:01:10.000Z | 2022-03-01T19:45:50.000Z | src/main/java/us/ihmc/simulationconstructionset/gui/SwingWorker.java | ihmcrobotics/simulation-construction-set | 98d7bb859164025aad1a7ce5d1a021051c8c2537 | [
"Apache-2.0"
] | 3 | 2018-06-22T19:06:27.000Z | 2022-01-06T23:00:57.000Z | 21.651316 | 99 | 0.561228 | 999,458 | package us.ihmc.simulationconstructionset.gui;
//import com.sun.java.swing.SwingUtilities; //old package name
import javax.swing.SwingUtilities;
/**
* An abstract class that you subclass to perform GUI-related work in a dedicated thread. For
* instructions on using this class, see
* http://java.sun.com/products/jfc/swingdoc-current/threads2.html
*/
public abstract class SwingWorker
{
private Object value; // see getValue(), setValue()
@SuppressWarnings("unused")
private Thread thread;
/**
* Class to maintain reference to current worker thread under separate synchronization control.
*/
private static class ThreadVar
{
private Thread thread;
ThreadVar(Thread t)
{
thread = t;
}
synchronized Thread get()
{
return thread;
}
synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;
/**
* Get the value produced by the worker thread, or null if it hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}
/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}
/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();
/**
* Called on the event dispatching thread (not on the worker thread) after the
* <code>construct</code> method has returned.
*/
public void finished()
{
}
/**
* A new method that interrupts the worker thread. Call this method to force the worker to abort
* what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}
/**
* Return the value created by the <code>construct</code> method. Returns null if either the
* constructing thread or the current thread was interrupted before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}
/**
* Start a thread that will call the <code>construct</code> method and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{
@Override
public void run()
{
finished();
}
};
Runnable doConstruct = new Runnable()
{
@Override
public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct, "SCSSwingWorkerConstruct");
threadVar = new ThreadVar(t);
t.start();
}
}
|
923b1de87ac32619d81c273470b4cd22b87f78f6 | 1,951 | java | Java | src/test/java/uw/task/product/ReturnData.java | axeon/uw-task | 3c7ab08415bb6433ba2a4a511de9e20e4f09a732 | [
"Apache-2.0"
] | 10 | 2017-05-11T16:02:36.000Z | 2020-09-21T08:31:22.000Z | src/test/java/uw/task/product/ReturnData.java | axeon/uw-task | 3c7ab08415bb6433ba2a4a511de9e20e4f09a732 | [
"Apache-2.0"
] | null | null | null | src/test/java/uw/task/product/ReturnData.java | axeon/uw-task | 3c7ab08415bb6433ba2a4a511de9e20e4f09a732 | [
"Apache-2.0"
] | 14 | 2017-04-21T05:24:15.000Z | 2021-11-30T06:54:48.000Z | 16.258333 | 52 | 0.497181 | 999,459 | package uw.task.product;
/**
* @author liliang
* @since 2018-05-30
*/
public final class ReturnData {
public static final String SUCCESS = "success";
public static final String ERROR = "error";
public static final String UNKOWN = "unknow";
/**
* 状态
*/
private String state = UNKOWN;
/**
* 信息。
*/
private String msg;
/**
* 代码,可能代表错误代码。
*/
private String code;
public ReturnData() {
}
protected ReturnData(String state, String msg) {
this.state = state;
this.msg = msg;
}
/**
* 附带消息的成功返回值。
*
* @param msg
* @return
*/
public static ReturnData success(String msg) {
return new ReturnData(SUCCESS, msg);
}
/**
* 成功返回值。
*
* @return
*/
public static ReturnData success() {
return new ReturnData(SUCCESS, null);
}
/**
* 附带消息的错误返回值。
*
* @param msg
* @return
*/
public static ReturnData error(String msg) {
return new ReturnData(ERROR, msg);
}
/**
* 是否成功。
*
* @return
*/
public boolean isSuccess() {
return SUCCESS.equals(this.state);
}
/**
* 设置代码。
*
* @param code
* @return
*/
public ReturnData code(String code) {
this.code = code;
return this;
}
@Override
public String toString() {
return "ReturnData{" +
"state=" + state +
", msg='" + msg + '\'' +
'}';
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
|
923b1e2c2351db4eee5e5bb4f4b867c51d22f4f6 | 1,205 | java | Java | app/src/main/java/com/example/naturae_ui/containers/SplashScreenActivityContainer.java | nanaeaubry/Naturae_UI | bb32336bceab73bcd2a6349eab710c9fef97e28c | [
"MIT"
] | null | null | null | app/src/main/java/com/example/naturae_ui/containers/SplashScreenActivityContainer.java | nanaeaubry/Naturae_UI | bb32336bceab73bcd2a6349eab710c9fef97e28c | [
"MIT"
] | null | null | null | app/src/main/java/com/example/naturae_ui/containers/SplashScreenActivityContainer.java | nanaeaubry/Naturae_UI | bb32336bceab73bcd2a6349eab710c9fef97e28c | [
"MIT"
] | 1 | 2019-05-16T19:12:54.000Z | 2019-05-16T19:12:54.000Z | 34.428571 | 107 | 0.698755 | 999,460 | package com.example.naturae_ui.containers;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.naturae_ui.util.UserUtilities;
public class SplashScreenActivityContainer extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//If the user's had already login into the app. If the user had already logged in then it wil takes
//the users to the main activity page and clear the top activity from the stack
System.out.println(UserUtilities.isLoggedIn(this));
if (UserUtilities.isLoggedIn(this)){
startActivity(new Intent(SplashScreenActivityContainer.this, MainActivityContainer.class));
}
//If the user's haven't login or logout of the account then the app will take the user to the login
//screen
else{
startActivity(new Intent(SplashScreenActivityContainer.this, StartUpActivityContainer.class));
}
}
/**
* stops the application
*/
@Override
protected void onStop() {
super.onStop();
finish();
}
}
|
923b1e621a9438fbfc6cbb136e32f7e1f9999304 | 1,982 | java | Java | oop/oop2017-2018/homeworks/03-card-game-sequel/src/org/elsys/cardgame/Main.java | mdatsev/elsys_homeworks | 11c170ae215c6d731092d6147331837a3f306134 | [
"Unlicense"
] | null | null | null | oop/oop2017-2018/homeworks/03-card-game-sequel/src/org/elsys/cardgame/Main.java | mdatsev/elsys_homeworks | 11c170ae215c6d731092d6147331837a3f306134 | [
"Unlicense"
] | 45 | 2020-02-25T23:36:11.000Z | 2022-03-30T23:19:18.000Z | oop/oop2017-2018/homeworks/03-card-game-sequel/src/org/elsys/cardgame/Main.java | mdatsev/elsys_homeworks | 11c170ae215c6d731092d6147331837a3f306134 | [
"Unlicense"
] | null | null | null | 31.460317 | 75 | 0.686176 | 999,461 | package org.elsys.cardgame;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import org.elsys.cardgame.api.CardException;
import org.elsys.cardgame.api.CardGame;
import org.elsys.cardgame.api.Game;
import org.elsys.cardgame.api.PlayingCard;
import org.elsys.cardgame.api.Rank;
import org.elsys.cardgame.api.Suit;
import static org.elsys.cardgame.factory.GameFactory.*;
public class Main {
private static Suit getSuit(String str) {
return Arrays.stream(Suit.values())
.filter(c -> c.getSymbol().equals(str))
.findFirst().orElseThrow(() -> new CardException("Invalid card!"));
}
// how to make this generic?? java??
private static Rank getRank(String str) {
return Arrays.stream(Rank.values())
.filter(c -> c.getSymbol().equals(str))
.findFirst().orElseThrow(() -> new CardException("Invalid card!"));
}
public static List<PlayingCard> extractCards(String str)
{
return Arrays.stream(str.split(" "))
.map(card -> new PlayingCard(getSuit(card.substring(0, 1)),
getRank(card.substring(1))))
.collect(Collectors.toList());
}
public static class GameWrapper { public Game game; }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<PlayingCard> cards = extractCards(sc.nextLine());
GameWrapper slave = new GameWrapper();
CardGame hubGame = new CardGame()
.addOperation( "War", () -> slave.game = createWarGame(cards))
.addOperation( "Belote", () -> slave.game = createBeloteGame(cards))
.addOperation("Santase", () -> slave.game = createSantaseGame(cards))
.addOperation( "quit", () -> System.exit(0))
.addDefaultOperation((String cmd) -> {
if(slave.game == null)
throw new CardException("No deck.");
slave.game.process(cmd);
});
while(true)
try{
hubGame.process(sc.nextLine());
}catch(CardException e){
System.out.println("ERROR: " + e.getMessage());
}
}
}
|
923b1f1cb625c8da550334314756102d18dd068e | 6,202 | java | Java | buildSrc/src/main/java/com/uber/okbuck/extension/ExternalDependenciesExtension.java | amalyoman/okbuck | ab61ea5582387545612816f0667b073fab630dc7 | [
"MIT"
] | null | null | null | buildSrc/src/main/java/com/uber/okbuck/extension/ExternalDependenciesExtension.java | amalyoman/okbuck | ab61ea5582387545612816f0667b073fab630dc7 | [
"MIT"
] | null | null | null | buildSrc/src/main/java/com/uber/okbuck/extension/ExternalDependenciesExtension.java | amalyoman/okbuck | ab61ea5582387545612816f0667b073fab630dc7 | [
"MIT"
] | null | null | null | 33.344086 | 107 | 0.683489 | 999,462 | package com.uber.okbuck.extension;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.uber.okbuck.core.dependency.ExternalDependency;
import com.uber.okbuck.core.dependency.VersionlessDependency;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.gradle.api.Project;
public class ExternalDependenciesExtension {
/** Stores the dependencies which are allowed to have latest version. */
private List<String> allowLatestVersion = new ArrayList<>();
/** Stores the dependencies which are allowed to have more than 1 version. */
private List<String> allowAllVersions = new ArrayList<>();
/** Stores the dependencies and their allowed versions */
private Map<String, List<String>> allowSpecificVersions = new HashMap<>();
private boolean versionless = false;
private boolean allowLatestForAll = false;
@Nullable private Set<VersionlessDependency> allowLatestVersionSet;
@Nullable private Set<VersionlessDependency> allowAllVersionsSet;
@Nullable private Map<VersionlessDependency, List<String>> allowedVersionsMap;
public ExternalDependenciesExtension(Project project) {
project.afterEvaluate(
evaluatedProject -> {
validateExtension();
});
}
private void validateExtension() {
Set<VersionlessDependency> allowLatest = getAllowLatestVersionSet();
Set<VersionlessDependency> allowAll = getAllowAllVersionsSet();
Set<VersionlessDependency> allowSpecific = getAllowSpecificVersionsMap().keySet();
checkIntersection(
Sets.intersection(allowLatest, allowAll), "allowLatestVersion", "allowAllVersions");
checkIntersection(
Sets.intersection(allowLatest, allowSpecific),
"allowLatestVersion",
"allowSpecificVersions");
checkIntersection(
Sets.intersection(allowAll, allowSpecific), "allowAllVersions", "allowSpecificVersions");
}
private static void checkIntersection(
Sets.SetView<VersionlessDependency> intersect, String setA, String setB) {
String intersectErrorString =
intersect
.stream()
.map(VersionlessDependency::mavenCoords)
.collect(Collectors.joining("\n"));
Preconditions.checkArgument(
intersect.size() == 0,
String.format(
"'%s' found in both '%s' & '%s', please remove from one of them.",
intersectErrorString, setA, setB));
}
private synchronized Map<VersionlessDependency, List<String>> getAllowSpecificVersionsMap() {
if (allowedVersionsMap == null) {
allowedVersionsMap =
allowSpecificVersions
.entrySet()
.stream()
.peek(
entry ->
Preconditions.checkArgument(
entry.getValue().size() > 1,
String.format(
"%s should have more than one versions specified in 'allowSpecificVersions'",
entry.getKey())))
.collect(
Collectors.toMap(
entry -> VersionlessDependency.fromMavenCoords(entry.getKey()),
Map.Entry::getValue));
}
return allowedVersionsMap;
}
private synchronized Set<VersionlessDependency> getAllowAllVersionsSet() {
if (allowAllVersionsSet == null) {
allowAllVersionsSet =
allowAllVersions
.stream()
.map(VersionlessDependency::fromMavenCoords)
.collect(ImmutableSet.toImmutableSet());
}
return allowAllVersionsSet;
}
private synchronized Set<VersionlessDependency> getAllowLatestVersionSet() {
if (allowLatestVersionSet == null) {
allowLatestVersionSet =
allowLatestVersion
.stream()
.map(VersionlessDependency::fromMavenCoords)
.collect(ImmutableSet.toImmutableSet());
}
return allowLatestVersionSet;
}
/**
* Returns whether versionless is enabled or not. This is a global flag to turn on/off
* versionless.
*
* @return boolean stating above.
*/
public boolean versionlessEnabled() {
return versionless;
}
/**
* Returns whether using latest version is enabled for any dependency.
*
* @return boolean stating above.
*/
public boolean allowLatestEnabled() {
return allowLatestForAll || getAllowLatestVersionSet().size() > 0;
}
/**
* Checks if the latest version should be used for this dependency.
*
* @param versionlessDependency dependency to check.
* @return boolean stating above.
*/
public boolean isAllowLatestFor(VersionlessDependency versionlessDependency) {
if (!versionless) {
return false;
}
return allowLatestForAll || getAllowLatestVersionSet().contains(versionlessDependency);
}
/**
* Checks whether the given dependency should be versioned or not.
*
* @param versionlessDependency dependency to check.
* @return boolean stating above.
*/
public boolean isVersioned(VersionlessDependency versionlessDependency) {
if (!versionlessEnabled()) {
return true;
}
if (isAllowLatestFor(versionlessDependency)) {
return false;
}
return getAllowAllVersionsSet().contains(versionlessDependency)
|| getAllowSpecificVersionsMap().containsKey(versionlessDependency);
}
/**
* Checks whether the given versioned dependency is allowed.
*
* @param dependency dependency to check.
* @return boolean stating above.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isAllowedVersion(ExternalDependency dependency) {
if (!versionlessEnabled()) {
return true;
}
if (getAllowAllVersionsSet().contains(dependency.getVersionless())) {
return true;
}
List<String> allowedVersions = getAllowSpecificVersionsMap().get(dependency.getVersionless());
return allowedVersions != null && allowedVersions.contains(dependency.getVersion());
}
}
|
923b1f1ceb8bcadb238fc81dfa1ed181e3cfe1c5 | 192 | java | Java | src/drlc/interpret/type/Method.java | turbodiesel4598/Dodd-Redstone-Language-Compiler | 9adee176cbbb0ec4a077ca4c2ae2df7acf88ce12 | [
"MIT"
] | 2 | 2021-04-17T13:02:31.000Z | 2021-04-22T12:13:27.000Z | src/drlc/interpret/type/Method.java | turbodiesel4598/Dodd-Redstone-Language-Compiler | 9adee176cbbb0ec4a077ca4c2ae2df7acf88ce12 | [
"MIT"
] | null | null | null | src/drlc/interpret/type/Method.java | turbodiesel4598/Dodd-Redstone-Language-Compiler | 9adee176cbbb0ec4a077ca4c2ae2df7acf88ce12 | [
"MIT"
] | 1 | 2021-08-28T14:33:48.000Z | 2021-08-28T14:33:48.000Z | 14.769231 | 39 | 0.692708 | 999,463 | package drlc.interpret.type;
public class Method {
public final String name;
public final int args;
public Method(String name, int args) {
this.name = name;
this.args = args;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.