hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
80d50eeb71222e2ea95fc71790bcd32f28036ac3
1,323
package com.yunpian.stargate.core.annotation.impl; import com.yunpian.stargate.annotation.StargateDelayLevel; import com.yunpian.stargate.core.annotation.AbsProcessAnnotationProducer; import com.yunpian.stargate.core.dto.StargateDelayDTO; import com.yunpian.stargate.core.exception.StargateException; import com.yunpian.stargate.core.utils.DelayUtils; import java.lang.reflect.Method; /** * Created with IntelliJ IDEA. User: ZhouKaifan Date:2018/11/23 Time:4:42 PM */ public class StargateDelayLevelProcessAnnotation extends AbsProcessAnnotationProducer<StargateDelayDTO> { @Override protected void processProducer(StargateDelayDTO stargateDelayDTO, Class aClass, Object o, Method method) throws Throwable { StargateDelayLevel stargateDelayLevel = null; if (method == null) { stargateDelayLevel = (StargateDelayLevel) aClass.getAnnotation(StargateDelayLevel.class); } else { stargateDelayLevel = method.getAnnotation(StargateDelayLevel.class); } if (stargateDelayLevel == null || stargateDelayLevel.value() < 0) { return; } if (stargateDelayLevel.value() >= DelayUtils.delayLevel.length) { throw new StargateException("delayLevel greater than " + (DelayUtils.delayLevel.length - 1)); } stargateDelayDTO.setLevel(stargateDelayLevel.value()); } }
37.8
99
0.770219
704cc7af8a5159499e166f0c70823da3f41d33b3
216
package org.snpeff.interval; /** * A Marker that has 'frame' information (Exon and Cds) * * @author pcingola */ public interface MarkerWithFrame { public int getFrame(); public void setFrame(int frame); }
14.4
55
0.699074
3972419b1900dab3a949b685c285d1504f0db79d
612
package me.coley.analysis; import me.coley.analysis.value.AbstractValue; import org.objectweb.asm.Type; /** * Factory for generating {@link AbstractValue} for method parameter values. * These values populate the initial frame of the analysis process. * * @author Matt */ public interface ParameterFactory { /** * @param isInstanceMethod * {@code false} when the method is static. * @param local * Local variable index. * @param type * Local variable type. * * @return Parameter value. */ AbstractValue createParameterValue(boolean isInstanceMethod, int local, Type type); }
24.48
84
0.71732
871dd763f822a3f747d07f8d615d1ccb2abd3449
2,984
package ro.pub.cs.systems.eim.practicaltest02; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import cz.msebera.android.httpclient.client.ClientProtocolException; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.client.ResponseHandler; import cz.msebera.android.httpclient.client.methods.HttpGet; import cz.msebera.android.httpclient.impl.client.BasicResponseHandler; import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; /** * Created by Luciana on 18/05/2017. */ public class CommunicationThread extends Thread { private Socket socket; public CommunicationThread(Socket socket) { this.socket = socket; } @Override public void run() { try { Log.v(Constants.TAG, "Connection opened with " + socket.getInetAddress() + ":" + socket.getLocalPort()); String result = null; BufferedReader reader = Utilities.getReader(socket); String string = reader.readLine(); if (string == null || string.isEmpty()) { Log.v(Constants.TAG, "No query text!"); socket.close(); return; } Log.v(Constants.TAG, "Query --------------------------" + string); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(Constants.GET_WEB_SERVICE_ADDRESS + "aq?" + Constants.QUERY + "=" + string); ResponseHandler<String> responseHandlerGet = new BasicResponseHandler(); try { result = httpClient.execute(httpGet, responseHandlerGet); } catch (ClientProtocolException clientProtocolException) { Log.e(Constants.TAG, clientProtocolException.getMessage()); if (Constants.DEBUG) { clientProtocolException.printStackTrace(); } } catch (IOException ioException) { Log.e(Constants.TAG, ioException.getMessage()); if (Constants.DEBUG) { ioException.printStackTrace(); } } if (result == null) { Log.v(Constants.TAG, "No result from server"); socket.close(); return; } Log.d(Constants.TAG, "got server result " + result); PrintWriter printWriter = Utilities.getWriter(socket); printWriter.println(result.substring(result.indexOf("name") + 4)); printWriter.flush(); socket.close(); Log.v(Constants.TAG, "Connection closed"); } catch (IOException ioException) { Log.e(Constants.TAG, "An exception has occurred: " + ioException.getMessage()); if (Constants.DEBUG) { ioException.printStackTrace(); } } } }
36.390244
116
0.59685
2b60555e32097b7583a8809c230a2e5ca1d4d77e
75,102
/* * This the client side code for the Gym. This enables the users to ADD, UPDATE, DELETE, and LIST bookings through * an inituitive GUI. It also has a Login page for security verification. The client connects to the server and * requests the server for any information. The server does all the computations and sends the data to the client. * The client side then displays the results from the GUI. */ package cst2550_coursework; import java.io.*; import java.net.Socket; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.*; import javafx.application.Application; import javafx.event.*; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.Pane; import javafx.scene.text.*; import javafx.stage.Stage; /** * This the client side code for the Gym. This enables the users to ADD, UPDATE, * DELETE, and LIST bookings through an intuitive GUI. It also has a Login page * for security verification. The client connects to the server and requests the * server for any information. The server does all the computations and sends * the data to the client. The client side then displays the results from the * GUI. * * @author Ammar Ali Moazzam */ public class CST2550_Coursework extends Application { //creating global array list to store trainer names List<String> trainerNamesList; List<String> clientNamesList; //creating global array list to store trainer speciality List<String> trainerFocusList; //creating socket for connecting to the server Socket clientSocket; String trainerName; String clientNameSelected = " "; @Override public void start(Stage primaryStage) { try { //initializing the Socket at the beginning of the client program clientSocket = new Socket("localhost", 6789); //Login Screen layout //Creating and styling the main Heading for the Screen Label title1 = new Label("Middlesex Gym"); //Creating and setting font to the title Font f1 = new Font("System", 45); title1.setFont(f1); //specifying the posistion of the label title1.setLayoutX(40); title1.setLayoutY(10); //Adding a label that says "Staff Login" Label title2 = new Label("Staff Login"); //Creating new font to be used. Font f2 = new Font("System", 43); title2.setFont(f2); //specifying the posistion of the label title2.setLayoutX(110); title2.setLayoutY(130); //Cretaing a font to use for the labels in all the screens Font f5 = new Font("System", 14); //label for username Label userName = new Label("Username: "); //specifying the posistion of the label userName.setLayoutX(80); userName.setLayoutY(225); //setting custom font to the label userName.setFont(f5); //Creating textfield to get username TextField userNameTF = new TextField(); userNameTF.setPromptText("Enter username here"); //specifying the posistion of the text field userNameTF.setLayoutX(180); userNameTF.setLayoutY(225); //Creating label for password Label password = new Label("Password: "); //specifying the posistion of the label password.setLayoutX(80); password.setLayoutY(285); //setting custom font to the label password.setFont(f5); //Creating password field to getpassword from the user. PasswordField passwordPF = new PasswordField(); passwordPF.setPromptText("Enter password here"); //specifying the posistion of the password field passwordPF.setLayoutX(180); passwordPF.setLayoutY(285); //Creating a button for login Button loginBtn = new Button("Login"); loginBtn.setFont(f5); //specifying the posistion of the button loginBtn.setLayoutX(80); loginBtn.setLayoutY(350); //setting minimum size for the button loginBtn.setMinSize(250, 40); //////////////////////////////////////////////////////// //'Add Booking' Screen Layout //Creating and styling the main Heading for this Screen Label newBookingTitle = new Label("New Booking"); //Creating and setting font to the title Font f3 = new Font("System", 45); newBookingTitle.setFont(f3); //specifying the posistion of the label newBookingTitle.setLayoutX(58); newBookingTitle.setLayoutY(17); //Creating label for trainer id Label trainer = new Label("Trainer "); //specifying the posistion of the label trainer.setLayoutX(77); trainer.setLayoutY(153); ////setting custom font to the label trainer.setFont(f5); //Creating ChoiceBox to get trainer id ChoiceBox trainerCB = new ChoiceBox(); //specifying the position of the choice box. trainerCB.setLayoutX(161); trainerCB.setLayoutY(158); //specifying the size of the choice box trainerCB.setPrefSize(150, 16); //Creating label for client name Label clientName = new Label("Client Name "); //specifying the posistion of the label clientName.setLayoutX(77); clientName.setLayoutY(213); //setting custom font to the label clientName.setFont(f5); //creating choice box for client name choice box ChoiceBox clientNameCB = new ChoiceBox(); ////specifying the posistion of the choice box clientNameCB.setLayoutX(161); clientNameCB.setLayoutY(214); //specifying the size of the choicebox clientNameCB.setPrefSize(150, 16); //Creating label for Date Label date = new Label("Date "); //specifying the posistion of the label date.setLayoutX(77); date.setLayoutY(263); //setting custom font to the label date.setFont(f5); //Creating date picker to get date DatePicker dp = new DatePicker(); //setting today's date as the default date. dp.setValue(LocalDate.now()); //specifying the position of the date picker dp.setLayoutX(161); dp.setLayoutY(264); //setting the size of the date picker dp.setPrefSize(150, 16); //Creating label for startTime Label startTime = new Label("Start Time"); //specifying the posistion of the label startTime.setLayoutX(77); startTime.setLayoutY(313); //setting custom font to the label startTime.setFont(f5); //Creating a choicebox menuu for startTime ChoiceBox startTimeCB = new ChoiceBox(); //adding options to the choice box startTimeCB.getItems().addAll(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22); //specifying the posistion of the choice box startTimeCB.setLayoutX(161); startTimeCB.setLayoutY(314); //specifying the size of the choice box startTimeCB.setPrefSize(50, 16); //creating a label for "End Time" Label endTime = new Label("End Time"); //setting custom font to the label endTime.setFont(f5); //specifying the postion of the label endTime.setLayoutX(220); endTime.setLayoutY(313); //creating choice box to get end time ChoiceBox endTimeCB = new ChoiceBox(); //specifying the position of the choice box endTimeCB.setLayoutX(280); endTimeCB.setLayoutY(314); //specifying the size of the choice box endTimeCB.setPrefSize(50, 16); //Creating label for focus Label focus = new Label("Focus "); //specifying the posistion of the label focus.setLayoutX(77); focus.setLayoutY(351); //setting custom font to the label focus.setFont(f5); //Creating a choicebox menuu for focus ChoiceBox focusCB = new ChoiceBox(); //specifying the posistion of the choice box focusCB.setLayoutX(161); focusCB.setLayoutY(354); //specifying the size of the choice box focusCB.setPrefSize(150, 16); //Creating a button to add bookings Button addBookingBtn = new Button("Add Booking"); //setting custom font to the label addBookingBtn.setFont(f5); //specifying the posistion of the button addBookingBtn.setLayoutX(76); addBookingBtn.setLayoutY(404); //specifyiing the size of the button addBookingBtn.setMinSize(237, 40); //creating a label to let the user know whether the booking has been successful Label message = new Label(""); //specifying the position of the label message.setLayoutX(150); message.setLayoutY(450); //Hiding the label from the user initially message.setVisible(false); //Creating a button to go to the previous screen Button backFromAddBooking = new Button("Back"); //specifying the posistion of the button backFromAddBooking.setLayoutX(10); backFromAddBooking.setLayoutY(10); //piece of code that doesnt allow the user to select date from the past dp.setDayCellFactory(picker -> new DateCell() { @Override public void updateItem(LocalDate date, boolean empty) { super.updateItem(date, empty); LocalDate today = LocalDate.now(); setDisable(empty || date.compareTo(today) < 0); } }); //Event handler for start Time Choice box. Defines what happens when a user selects an option from the choice box startTimeCB.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //reoving items from end time choice box endTimeCB.getItems().clear(); int startTiming = Integer.parseInt(startTimeCB.getValue().toString()); //adding values to end time choice box. //these values begin with start time + 1 and end at 23 for (int i = startTiming + 1; i < 24; i++) { endTimeCB.getItems().add(i); } } }); //////////////////////////////////////////////////////////// //event handler for the trainer choice box. Defines what happens when the user selects a trainer. trainerCB.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //creating a data output stream DataOutputStream dos = null; try { //sets the gobal variable trainer name to the value that the user selected by selecting an option from the choice box. trainerName = trainerCB.getValue().toString(); //removing everything from focus speciality focusCB.getItems().clear(); //checking if the trainer name is equal to the trainer name in the array list. //then takes that trainer's speciality from the arraylist and adds it to the choice box. for (int i = 0; i < trainerNamesList.size(); i++) { if (trainerName.equals(trainerNamesList.get(i))) { List<String> list = Arrays.asList(trainerFocusList.get(i).split(",")); for (int j = 0; j < list.size(); j++) { focusCB.getItems().add(list.get(j)); } } } } catch (NullPointerException ex) { } } }); //event handler for the client name choice box. Defines what happens when the user selects a trainer. clientNameCB.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //sets the gobal variable trainer name to the value that the user selected by selecting an option from the choice box. clientNameSelected = clientNameCB.getValue().toString(); } catch (NullPointerException ex) { } } }); //////////////////////////////////////////////////////////////// //Home Screen Layout //creating label for home screen Label homeScreenTitle = new Label("Middlesex Gym"); //setting custom font to the label homeScreenTitle.setFont(f1); //specifying the position of the label homeScreenTitle.setLayoutX(41); homeScreenTitle.setLayoutY(20); //creating a font for the text in buttons Font f4 = new Font("System", 15); //Creating a button to add new bookings Button newBookingBtn = new Button("New Booking"); //specifying the posistion of the button newBookingBtn.setLayoutX(14); newBookingBtn.setLayoutY(152); //specifying the size of the button newBookingBtn.setMinSize(169, 104); //setting custom font to the button newBookingBtn.setFont(f4); //Creating a button to update bookings Button updateBookingBtn = new Button("Update Booking"); //specifying the posistion of the button updateBookingBtn.setLayoutX(14); updateBookingBtn.setLayoutY(302); //specifying the size of the button updateBookingBtn.setMaxSize(169, 110); updateBookingBtn.setPrefSize(169, 110); //setting custom font to the button updateBookingBtn.setFont(f4); updateBookingBtn.setWrapText(true); //center alligning the text inside the button updateBookingBtn.setTextAlignment(TextAlignment.CENTER); //Creating a button to delete bookings Button deleteBookingBtn = new Button("Delete Booking"); //specifying the posistion of the button deleteBookingBtn.setLayoutX(205); deleteBookingBtn.setLayoutY(302); //specifying the size of the button deleteBookingBtn.setMaxSize(169, 110); deleteBookingBtn.setPrefSize(169, 110); //setting custom font to the button deleteBookingBtn.setFont(f4); deleteBookingBtn.setWrapText(true); //center alligning the text inside the button deleteBookingBtn.setTextAlignment(TextAlignment.CENTER); //Creating a button to add new bookings Button listBookingBtn = new Button("List Booking"); //specifying the posistion of the button listBookingBtn.setLayoutX(205); listBookingBtn.setLayoutY(152); //specifying the size of the button listBookingBtn.setMinSize(169, 104); //setting custom font to the button listBookingBtn.setFont(f4); //Creating a button to disconnect from the server Button disconnectBtn = new Button("Disconnect"); //specifying the posistion of the button disconnectBtn.setLayoutX(150); disconnectBtn.setLayoutY(430); //setting custom font to the button disconnectBtn.setFont(f5); disconnectBtn.setStyle("-fx-background-color: red"); //event handler for disconnect button. Defines what happens when the disconnect button is pressed. disconnectBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //creating a data output stream to send data to the server DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream()); // sending "stop" to the server dos.writeUTF("stop"); //closing the application System.exit(0); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //////////////////////////////////////////////////////// //'Update Booking' Screen Layout //Creating and styling the main Heading for this Screen Label updateBookingTitle = new Label("Update Booking"); //setting font to the title updateBookingTitle.setFont(f3); //specifying the posistion of the label updateBookingTitle.setLayoutX(35); updateBookingTitle.setLayoutY(17); //Creating label for booking id Label updateBookingID = new Label("Booking ID "); //specifying the posistion of the label updateBookingID.setLayoutX(77); updateBookingID.setLayoutY(121); //setting custom font to the label updateBookingID.setFont(f5); //Creating textfield to get booking id TextField updateBookingIDTF = new TextField(); updateBookingIDTF.setPromptText("Enter BookingID here"); //specifying the posistion of the text field updateBookingIDTF.setLayoutX(161); updateBookingIDTF.setLayoutY(122); //Creating label for trainer id Label updateTrainerID = new Label("Trainer "); //specifying the posistion of the label updateTrainerID.setLayoutX(77); updateTrainerID.setLayoutY(173); //setting custom font to the label updateTrainerID.setFont(f5); //Creating choice box to get trainer id ChoiceBox updateTrainerCB = new ChoiceBox(); //specifying the posistion of the choice box updateTrainerCB.setLayoutX(161); updateTrainerCB.setLayoutY(178); //specifying the size of the choice box updateTrainerCB.setPrefSize(150, 16); //Creating label for client name Label updateClientName = new Label("Client Name "); //specifying the posistion of the label updateClientName.setLayoutX(77); updateClientName.setLayoutY(225); //setting custom font to the label updateClientName.setFont(f5); //Creating drop-down to get client name ChoiceBox updateClientNameCB = new ChoiceBox(); //specifying the posistion of the choice box updateClientNameCB.setLayoutX(161); updateClientNameCB.setLayoutY(225); //specifying the size of the choice box updateClientNameCB.setPrefSize(150, 16); //Creating label for Date Label updateDate = new Label("Date "); //specifying the posistion of the label updateDate.setLayoutX(77); updateDate.setLayoutY(273); //setting custom font to the label updateDate.setFont(f5); //Creating date picker to get date DatePicker updateDp = new DatePicker(); updateDp.setValue(LocalDate.now()); //specifying the posistion of the date picker updateDp.setLayoutX(161); updateDp.setLayoutY(274); //specifying the size of the date picker updateDp.setPrefSize(150, 16); //Creating label for startTime Label updateStartTime = new Label("Start Time"); //specifying the posistion of the label updateStartTime.setLayoutX(77); updateStartTime.setLayoutY(313); //setting custom font to the label updateStartTime.setFont(f5); //Creating a choicebox menu for startTime ChoiceBox updateStartTimeCB = new ChoiceBox(); //adding options to the choice box updateStartTimeCB.getItems().addAll(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22); //specifying the posistion of the choice box updateStartTimeCB.setLayoutX(161); updateStartTimeCB.setLayoutY(314); //specifying the size of the choice box updateStartTimeCB.setPrefSize(50, 16); //creating a label for updating End time Label updateEndTime = new Label("End Time"); //setting custom font to the label updateEndTime.setFont(f5); //specifying the posistion of the label updateEndTime.setLayoutX(220); updateEndTime.setLayoutY(313); //Creating a choicebox menu for end time ChoiceBox updateEndTimeCB = new ChoiceBox(); //specifying the posistion of the choice box updateEndTimeCB.setLayoutX(280); updateEndTimeCB.setLayoutY(314); //specifying the size of the choice box updateEndTimeCB.setPrefSize(50, 16); //Creating label for focus Label updateFocus = new Label("Focus "); //specifying the posistion of the label updateFocus.setLayoutX(77); updateFocus.setLayoutY(351); //setting custom font to the label updateFocus.setFont(f5); //Creating a choicebox menuu for focus ChoiceBox updateFocusCB = new ChoiceBox(); //specifying the posistion of the choice box updateFocusCB.setLayoutX(161); updateFocusCB.setLayoutY(354); //specifying the size of the choice box updateFocusCB.setPrefSize(150, 16); //Creating a button to update bookings Button updateBtn = new Button("Update Booking"); //setting custom font to the button updateBtn.setFont(f5); //specifying the posistion of the button updateBtn.setLayoutX(76); updateBtn.setLayoutY(404); //specifying the size of the button updateBtn.setMinSize(237, 40); //Creating a button to go to the previous screen Button backFromUpdateBooking = new Button("Back"); //specifying the posistion of the button backFromUpdateBooking.setLayoutX(10); backFromUpdateBooking.setLayoutY(10); //ceating a label for informinig the user about the result of the update Label updateMessage = new Label(""); //specifying the position of the label updateMessage.setLayoutX(150); updateMessage.setLayoutY(450); //initially hiding the label from the user updateMessage.setVisible(false); //piece of code that doesnt allow the user to select date from the past updateDp.setDayCellFactory(picker -> new DateCell() { @Override public void updateItem(LocalDate date, boolean empty) { super.updateItem(date, empty); LocalDate today = LocalDate.now(); setDisable(empty || date.compareTo(today) < 0); } }); //event handler for update client name choice box updateClientNameCB.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //sets the gobal variable trainer name to the value that the user selected by selecting an option from the choice box. clientNameSelected = updateClientNameCB.getValue().toString(); } catch (NullPointerException ex) { } } }); //event handler defining whta should be done when the user selects an option from the start time updateStartTimeCB.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //removing all items from end time choice box. updateEndTimeCB.getItems().clear(); //getting start time value from start time choice box int updateStartTiming = Integer.parseInt(updateStartTimeCB.getValue().toString()); //adding values to end time choice box. //these values begin with start time + 1 and end at 23 for (int i = updateStartTiming + 1; i < 24; i++) { updateEndTimeCB.getItems().add(i); } } }); //////////////////////////////////////////////////////////// //event handler defining what needs to done when a trainer name is selected from the choice box. updateTrainerCB.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { DataOutputStream dos = null; try { //sets the gobal variable trainer name to the value that the user selected by selecting an option from the choice box. trainerName = updateTrainerCB.getValue().toString(); //removing everything from the update focus choice box. updateFocusCB.getItems().clear(); //checking if the trainer name is equal to the trainer name in the array list. //then takes that trainer's specialities from the arraylist and adds it to the choice box. for (int i = 0; i < trainerNamesList.size(); i++) { if (trainerName.equals(trainerNamesList.get(i))) { List<String> list = Arrays.asList(trainerFocusList.get(i).split(",")); for (int j = 0; j < list.size(); j++) { updateFocusCB.getItems().add(list.get(j)); } } } } catch (NullPointerException ex) { } } }); ////////////////////////////////////////////////////////////// //'List Booking' Screen layout //creating a heading for this screen Label listBookingTitle = new Label("List Booking"); //setting font to the title listBookingTitle.setFont(f3); //specifying the posistion of the label listBookingTitle.setLayoutX(61); listBookingTitle.setLayoutY(21); //Creating label for the trainer id to search bookings for Label listTrainerID = new Label("Staff/Trainer ID "); //specifying the posistion of the label listTrainerID.setLayoutX(87); listTrainerID.setLayoutY(198); //setting custom font to the label listTrainerID.setFont(f5); //hiding the label from the users initially listTrainerID.setVisible(false); //Creating textfield to get trainer id TextField listTrainerIDTF = new TextField(); listTrainerIDTF.setPromptText("Enter Staff/TrainerID here"); //specifying the posistion of the text field listTrainerIDTF.setLayoutX(185); listTrainerIDTF.setLayoutY(194); //hiding the textField from the users initially listTrainerIDTF.setVisible(false); //Creating label for the client id to search bookings for Label listClientID = new Label("Client ID "); //specifying the posistion of the label listClientID.setLayoutX(87); listClientID.setLayoutY(198); //setting custom font to the label listClientID.setFont(f5); //Creating textfield to get client id TextField listClientIDTF = new TextField(); listClientIDTF.setPromptText("Enter ClientID here"); //specifying the posistion of the text field listClientIDTF.setLayoutX(165); listClientIDTF.setLayoutY(194); //hiding the textField from the users initially listClientIDTF.setVisible(true); //Creating label for the date to search bookings for Label listDate = new Label("Date "); //specifying the posistion of the label listDate.setLayoutX(87); listDate.setLayoutY(198); //setting custom font to the label listDate.setFont(f5); //hiding the label from the users initially listDate.setVisible(false); //Creating date picker to get date to show bookings for DatePicker listDp = new DatePicker(); listDp.setValue(LocalDate.now()); //specifying the posistion of the date picker listDp.setLayoutX(165); listDp.setLayoutY(194); //specifying the size of the date picker listDp.setPrefSize(149, 25); //hiding the date picker from the users initially listDp.setVisible(false); //Creating a button to list bookings Button listBtn = new Button("List Bookings"); //setting custom font to the button text listBtn.setFont(f5); //specifying the posistion of the button listBtn.setLayoutX(82); listBtn.setLayoutY(282); //specifying the size of the button listBtn.setMinSize(237, 40); //creating a teext area for displaying the results TextArea listBookingsTA = new TextArea(); //specifying the posistion and size of the text area listBookingsTA.setLayoutX(13); listBookingsTA.setLayoutY(333); //specifying the posistion of the text area listBookingsTA.setMaxSize(374, 153); listBookingsTA.setEditable(false); // the text area cant be edited by the user listBookingsTA.setVisible(false); //initially the textarea is not visible to the user //creating a toggle group for the radio buttons ToggleGroup toggleGroup = new ToggleGroup(); //creating radio button for listing results by client id RadioButton byClientId = new RadioButton("By Client ID"); //specifying the position of the radio button. byClientId.setLayoutX(12); byClientId.setLayoutY(133); //this radio button is selected by default byClientId.setSelected(true); //creating radio button for listing results by trainer id RadioButton byTrainerId = new RadioButton("By Trainer/Staff ID"); //specifying the position of the radio button. byTrainerId.setLayoutX(114); byTrainerId.setLayoutY(133); //creating radio button for listing results by date RadioButton byDate = new RadioButton("By Date"); //specifying the position of the radio button. byDate.setLayoutX(233); byDate.setLayoutY(133); //creating radio button for listing all bookings RadioButton listAll = new RadioButton("List All"); //specifying the position of the radio button. listAll.setLayoutX(326); listAll.setLayoutY(133); //adding all the radio buttons to the toggle group byClientId.setToggleGroup(toggleGroup); byTrainerId.setToggleGroup(toggleGroup); byDate.setToggleGroup(toggleGroup); listAll.setToggleGroup(toggleGroup); //Creating a button to go to the previous screen Button backFromListBooking = new Button("Back"); //specifying the posistion of the button backFromListBooking.setLayoutX(10); backFromListBooking.setLayoutY(10); ////////////////////////////////////////////////// //'Delete Boking' Screen //creating a heading for this screen Label deleteBookingTitle = new Label("Delete Booking"); //setting font to the title deleteBookingTitle.setFont(f3); //specifying the posistion of the label deleteBookingTitle.setLayoutX(35); deleteBookingTitle.setLayoutY(21); //Creating label for the client id to searh bookings for Label deleteBookingID = new Label("Booking ID "); //setting a custom font for the label deleteBookingID.setFont(f5); //specifying the posistion of the label deleteBookingID.setLayoutX(87); deleteBookingID.setLayoutY(185); //Creating textfield to get client id TextField deleteBookingIDTF = new TextField(); deleteBookingIDTF.setPromptText("Enter Booking ID to delete"); //specifying the position of the text field deleteBookingIDTF.setLayoutX(165); deleteBookingIDTF.setLayoutY(186); //Creating a button to delete bookings Button deleteBooking = new Button("Delete Booking"); //setting custom font to the button deleteBooking.setFont(f5); //specifying the posistion of the button deleteBooking.setLayoutX(82); deleteBooking.setLayoutY(250); //specifying the size of the button. deleteBooking.setMinSize(237, 40); //Creating a button to go to the previous screen Button backFromDeleteBooking = new Button("Back"); //specifying the posistion of the button backFromDeleteBooking.setLayoutX(10); backFromDeleteBooking.setLayoutY(10); //creating label to inform the user about th results of the delete operation Label deleteMessage = new Label(); //specifying the position of the label deleteMessage.setLayoutX(150); deleteMessage.setLayoutY(450); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Scene 1 --Login Screen Pane loginScreen = new Pane(); //adding nodes onto the pane loginScreen.getChildren().addAll(title1, title2, userName, userNameTF, password, passwordPF, loginBtn); Scene loginScene = new Scene(loginScreen, 400, 500); loginScene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm()); loginScreen.setStyle("-fx-background: BEIGE;"); //Scene 2 --'Add Bookng' Screen Pane addBookingScreen = new Pane(); //creating a new pane for scene 2 //adding nodes onto the pane addBookingScreen.getChildren().addAll(newBookingTitle, trainer, clientName, date, startTime, startTimeCB, focus, trainerCB, clientNameCB, dp, focusCB, addBookingBtn, backFromAddBooking, message, endTimeCB, endTime); //setting background color for the pane addBookingScreen.setStyle("-fx-background: BEIGE;"); Scene addBookingScene = new Scene(addBookingScreen, 400, 500); //setting up the scene //adding css styles sheets to the pane addBookingScene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm()); //Scene 3 --'Update Bookng' Screen Pane updateBookingScreen = new Pane(); //creating a new pane for scene 3 //adding nodes onto the pane updateBookingScreen.getChildren().addAll(updateBookingID, updateBookingIDTF, updateBookingTitle, updateBtn, updateClientNameCB, updateClientName, updateDate, updateDp, updateStartTime, updateStartTimeCB, updateFocus, updateTrainerID, updateTrainerCB, updateFocusCB, backFromUpdateBooking, updateMessage, updateEndTimeCB, updateEndTime); updateBookingScreen.setStyle("-fx-background: BEIGE;"); Scene updateBookingScene = new Scene(updateBookingScreen, 400, 500); //setting up the scene updateBookingScene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm()); //Scene 4 --'Home' Screen Pane homeScreen = new Pane(); //creating a new pane for scene 4 //adding nodes onto the pane homeScreen.getChildren().addAll(homeScreenTitle, newBookingBtn, updateBookingBtn, deleteBookingBtn, listBookingBtn, disconnectBtn); homeScreen.setStyle("-fx-background: BEIGE;"); Scene homeScene = new Scene(homeScreen, 400, 500); //setting up the scene homeScene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm()); //Scene 5 --'list Bookings' Screen Pane listBookingScreen = new Pane(); //creating a new pane for scene 5 //adding nodes onto the pane listBookingScreen.getChildren().addAll(listBookingTitle, listClientID, listClientIDTF, listDate, listDp, listTrainerID, listTrainerIDTF, listBtn, listBookingsTA, backFromListBooking, byClientId, byDate, byTrainerId, listAll); listBookingScreen.setStyle("-fx-background: BEIGE;"); Scene listBookingScene = new Scene(listBookingScreen, 400, 500); //setting up the scene listBookingScene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm()); //Scene 6 --'Delete Bookings' Screen Pane deleteBookingScreen = new Pane(); //creating a new pane for scene 6 //adding nodes onto the pane deleteBookingScreen.getChildren().addAll(deleteBookingTitle, deleteBookingIDTF, deleteBookingID, deleteBooking, backFromDeleteBooking, deleteMessage); deleteBookingScreen.setStyle("-fx-background: BEIGE;"); Scene deleteBookingScene = new Scene(deleteBookingScreen, 400, 500); //setting up the scene deleteBookingScene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm()); primaryStage.setTitle("Middlesex GYM"); //title for the stage primaryStage.setScene(loginScene); primaryStage.show(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Event handler for the login buttons loginBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //checkinng if the user has filled in all the text fields. if (userNameTF.getText().isEmpty() || passwordPF.getText().isEmpty()) { throw new NullPointerException(); } else { //creating data output stream to send data to the server DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream()); //sending username and password to the server dos.writeUTF(userNameTF.getText().toUpperCase() + "," + passwordPF.getText()); //creating data input stream to read data from the server DataInputStream dis = new DataInputStream(clientSocket.getInputStream()); String reply = dis.readUTF(); //if the server repies with a 'true' it means the login is successful and the scene is changed if (reply.equalsIgnoreCase("true")) { primaryStage.setScene(homeScene); //reading trainer names from the server and assigning it to a variable String trainerNames = dis.readUTF(); //reading trainer focus from server and assigning it to a variable String trainerFocus = dis.readUTF(); //splitting the trainer names string using ',' and storing it into an arraylist trainerNamesList = Arrays.asList(trainerNames.split(",")); //splitting the trainer focus string using ':' and storing it into an arraylist trainerFocusList = Arrays.asList(trainerFocus.split(":")); //getting client names from the user and storing them in a list String clientNames = dis.readUTF(); clientNamesList = Arrays.asList(clientNames.split(",")); } else { //if the credentials are invalid then a pop up alert is shown to the user. Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Invalid username or Password"); alert.show(); } } } catch (NullPointerException ex) { //if any text field is left empty by the user, an alert box is shown alerting the user Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in all the details! "); alert.show(); } catch (IOException ex) { System.out.println("Error : " + ex.getMessage()); } } }); //event handler for add booking button addBookingBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { boolean isChoiceBoxSelected = false; boolean isCorrectTimeSelected = false; //checks if an option is selected from all the choice boxes if (trainerCB.getSelectionModel().isEmpty() || focusCB.getSelectionModel().isEmpty() || startTimeCB.getSelectionModel().isEmpty() || endTimeCB.getSelectionModel().isEmpty() || clientNameCB.getSelectionModel().isEmpty()) { throw new Exception(); } else { isChoiceBoxSelected = true; } //making sure that the time selected by the user should not be less than the current time if(Integer.parseInt(startTimeCB.getValue().toString()) <= getCurrentTime() && dp.getValue().toString().equals(LocalDate.now().toString())){ throw new ArithmeticException(); } else { isCorrectTimeSelected = true; } //if everything is rightly filled in, then it creates a Booking object and sets all the user inputs to the object if (isChoiceBoxSelected && isCorrectTimeSelected) { Booking b1 = new Booking(); b1.setDate(dp.getValue().toString()); b1.setStartTime(Integer.parseInt(startTimeCB.getValue().toString())); b1.setEndTime(Integer.parseInt((endTimeCB.getValue().toString()))); b1.setFocus(focusCB.getValue().toString()); b1.setTrainerName(trainerName); b1.setClientName(clientNameSelected); //sending the object to the server ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); oos.writeObject(b1); //reading Booking object from the server ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); Booking b = (Booking) ois.readObject(); //checking the servers reply to see if the booking is valid or is a duplicate if ((b.getFocus().equals("Duplicate Booking"))) { //if the booking is a duplicate, then an alert is shown and the message label is set to "duplicate booking" Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Duplicate Booking\nBooking for these details already exists"); alert.setContentText("Please check the timings\nThe trainer is busy during those hours\nTry changing the time or the trainer"); alert.show(); message.setText("Duplicate Booking\nBooking for these details already exists"); message.setVisible(true); } else { //sets the message label on the user GUI to read SUCCESSFUL BOOKING message.setText("Booking Successful\nBooking ID: " + b.getBookindId()); message.setVisible(true); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setHeaderText("Booking Successful\nBooking ID: " + b.getBookindId()); alert.show(); } } // Below are the alert boxes that will be shown if any of the above validation checks are false. } catch (NumberFormatException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in the deatils in the correct format! "); alert.show(); } catch (NullPointerException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in all the details! "); alert.show(); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } catch (ArithmeticException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Cannot make a booking in the past!!!"); alert.setContentText("Please change the start time\nMake sure start time is not less than or equal to the current time."); alert.show(); } catch (Exception ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please select a value from all the drop down boxes "); alert.show(); } } }); //event handler for update button updateBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { boolean isChoiceBoxSelected = false; boolean isCorrectTimeSelected = false; //checks if an option is selected from all the choice boxes if (updateBookingIDTF.getText().isEmpty() || updateTrainerCB.getSelectionModel().isEmpty() || updateFocusCB.getSelectionModel().isEmpty() || updateStartTimeCB.getSelectionModel().isEmpty() || updateEndTimeCB.getSelectionModel().isEmpty() || updateClientNameCB.getSelectionModel().isEmpty()) { throw new Exception(); } else { isChoiceBoxSelected = true; } //making sure that the time selected by the user should not be less than the current time if(Integer.parseInt(updateStartTimeCB.getValue().toString()) <= getCurrentTime()&& updateDp.getValue().toString().equals(LocalDate.now().toString())){ throw new ArithmeticException(); } else { isCorrectTimeSelected = true; } //if everything is rightly filled in, then it creates a Booking object and sets all the user inputs to the object if (isChoiceBoxSelected && isCorrectTimeSelected) { Booking b1 = new Booking(); b1.setBookindId(Integer.parseInt(updateBookingIDTF.getText().toUpperCase())); b1.setDate(updateDp.getValue().toString()); b1.setStartTime(Integer.parseInt(updateStartTimeCB.getValue().toString())); b1.setEndTime(Integer.parseInt((updateEndTimeCB.getValue().toString()))); b1.setFocus(updateFocusCB.getValue().toString()); b1.setTrainerName(trainerName); b1.setClientName(clientNameSelected); //sending the object to the server ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); oos.writeObject(b1); //reading the object from the server ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); Booking b = (Booking) ois.readObject(); //checking the server's reply to see if the booking is valid or is a duplicate or is invalid if ((b.getFocus().equals("Duplicate Booking"))) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Update Failed\nBooking for these details already exists"); alert.show(); updateMessage.setText("Duplicate Booking\nBooking for these details already exists"); updateMessage.setVisible(true); } else if (b.getFocus().equals("Invalid BookingID")) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Invalid Booking ID\nNo record with this ID exists"); alert.show(); updateMessage.setText("Invalid Booking ID\nNo record with this ID exists"); updateMessage.setVisible(true); }else { //if the reply is not equal to invalid booking or duplicate booking then it means that the booking update is valid updateMessage.setText("Update Successful\nBooking ID: " + b.getBookindId()); updateMessage.setVisible(true); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setHeaderText("Update Successful\nBooking ID: " + b.getBookindId()); alert.show(); } } // Below are the alert boxes that will be shown if any of the above validation checks are false. } catch (NumberFormatException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in the deatils in the correct format! "); alert.show(); } catch (NullPointerException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in all the details! "); alert.show(); ex.printStackTrace(); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } catch (ArithmeticException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Cannot make a booking in the past!!!"); alert.setContentText("Please change the start time\nMake sure start time is not less than or equal to the current time."); alert.show(); } catch (Exception ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please select a value from all the drop down boxes "); alert.show(); } } }); //event handler for the new bookings button on the home screen newBookingBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //changing the scene to add booking scene primaryStage.setScene(addBookingScene); //creating data output stream to send data to the server DataOutputStream dos = null; try { //sends "ADD" to the server dos = new DataOutputStream(clientSocket.getOutputStream()); dos.writeUTF("ADD"); trainerCB.getItems().clear(); //add items/options to the trainer choice box by getting the values from the list for (int i = 0; i < trainerNamesList.size(); i++) { trainerCB.getItems().add(trainerNamesList.get(i)); } clientNameCB.getItems().clear(); //add items/options to the client name choice box by getting the values from the list for (int i = 0; i < clientNamesList.size(); i++) { clientNameCB.getItems().add(clientNamesList.get(i)); } } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //event handler for the update bookings button on the home screen updateBookingBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //changing the scene to update booking scene primaryStage.setScene(updateBookingScene); //creating data output stream to send data to the server DataOutputStream dos = null; try { //sends "UPDATE" to the server dos = new DataOutputStream(clientSocket.getOutputStream()); dos.writeUTF("UPDATE"); updateTrainerCB.getItems().clear(); //add items/options to the trainer choice box by getting the values from the list for (int i = 0; i < trainerNamesList.size(); i++) { updateTrainerCB.getItems().add(trainerNamesList.get(i)); } updateClientNameCB.getItems().clear(); //add items/options to the client name choice box by getting the values from the list for (int i = 0; i < clientNamesList.size(); i++) { updateClientNameCB.getItems().add(clientNamesList.get(i)); } } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //event handler for the list bookings button on the home screen listBookingBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //changing the scene to list booking scene primaryStage.setScene(listBookingScene); //creating data output stream to send data to the server DataOutputStream dos = null; //sends "LIST" to the server dos = new DataOutputStream(clientSocket.getOutputStream()); dos.writeUTF("LIST"); dos.flush(); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //event handler for byClientId radio button byClientId.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //setting all the nodes except the client id text field to invisible listDp.setVisible(false); listTrainerIDTF.setVisible(false); listClientIDTF.setVisible(true); listBookingsTA.setVisible(false); listDate.setVisible(false); listClientID.setVisible(true); listTrainerID.setVisible(false); } }); //event handler for byDate radio button byDate.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //setting all the nodes except the date picker to invisible listDp.setVisible(true); listTrainerIDTF.setVisible(false); listClientIDTF.setVisible(false); listBookingsTA.setVisible(false); listDate.setVisible(true); listClientID.setVisible(false); listTrainerID.setVisible(false); } }); //event handler for byTrainerID radio button byTrainerId.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //setting all the nodes except the trainer Id text field to invisible listDp.setVisible(false); listTrainerIDTF.setVisible(true); listClientIDTF.setVisible(false); listBookingsTA.setVisible(false); listDate.setVisible(false); listClientID.setVisible(false); listTrainerID.setVisible(true); } }); //event handler for listAll radio button listAll.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //setting all the nodes to be invisible listDp.setVisible(false); listTrainerIDTF.setVisible(false); listClientIDTF.setVisible(false); listBookingsTA.setVisible(false); listDate.setVisible(false); listClientID.setVisible(false); listTrainerID.setVisible(false); } }); //event handler for the listBtn on list screen listBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { // Switch cases to check whoch radio button is selected and then send and recieve data from the server accordingly RadioButton selectedRadioButton = (RadioButton) toggleGroup.getSelectedToggle(); DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream()); DataInputStream dis = new DataInputStream(clientSocket.getInputStream()); //checks if any of the radio button is selected if (!byClientId.isSelected() && !byDate.isSelected() && !byTrainerId.isSelected() && !listAll.isSelected()) { throw new Exception(); } //switch to control the radio button selection switch (selectedRadioButton.getText()) { case "By Client ID": if (listClientIDTF.getText().isEmpty()) { throw new NullPointerException(); } dos.writeUTF("By Client ID"); dos.flush(); //sending client id to the server String clientID1 = listClientIDTF.getText().toUpperCase(); dos.writeUTF(clientID1); dos.flush(); dis = new DataInputStream(clientSocket.getInputStream()); String listResults = dis.readUTF(); //displaying the results on the text area listBookingsTA.setText(listResults); listBookingsTA.setVisible(true); break; case "By Date": //check to make sure a date is selected if (listDp.getValue().toString().equals("")) { throw new NullPointerException(); } //writing to the server dos.writeUTF("By Date"); dos.flush(); //sending date to the server String date1 = listDp.getValue().toString(); dos.writeUTF(date1); dos.flush(); //reading results from the server and displaying them on the text area listResults = dis.readUTF(); listBookingsTA.setText(listResults); listBookingsTA.setVisible(true); break; case "By Trainer/Staff ID": //check to make sure that trainer/Staff id text field is not empty if (listTrainerIDTF.getText().isEmpty()) { throw new NullPointerException(); } //write to the server dos.writeUTF("By Trainer/Staff ID"); dos.flush(); //sending trainer id/Staff to the server. String trainerId = listTrainerIDTF.getText().toUpperCase(); dos.writeUTF(trainerId); dos.flush(); //reading results from the server and displaying the results on the text area listResults = dis.readUTF(); listBookingsTA.setText(listResults); listBookingsTA.setVisible(true); break; case "List All": dos.writeUTF("List All"); dos.flush(); //reading results from the server and displaying the results on the text area listResults = dis.readUTF(); listBookingsTA.setText(listResults); listBookingsTA.setVisible(true); break; } } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } catch (NullPointerException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in all the fields! "); alert.show(); } catch (Exception ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please select a radio button! "); alert.show(); } } }); //event handler for the delete bookings button on the home screen deleteBookingBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //changing the scene to delete booking scene primaryStage.setScene(deleteBookingScene); //creating data output stream to send data to the server DataOutputStream dos = null; dos = new DataOutputStream(clientSocket.getOutputStream()); dos.writeUTF("DELETE"); dos.flush(); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //event handler for delete button on the delete booking scene deleteBooking.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //check to make sure that the text field is not empty if (deleteBookingIDTF.getText().isEmpty()) { throw new Exception(); } //getting nooking id value from the text field coverting it into an integer // and then setting it in a booking object and finally sending the Booking object to the server int bookingId = Integer.parseInt(deleteBookingIDTF.getText()); if (bookingId != 0) { ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); Booking b = new Booking(); b.setBookindId(bookingId); oos.writeObject(b); //reading data from the server and checking the status of the operation DataInputStream dis = new DataInputStream(clientSocket.getInputStream()); String deleteReply = dis.readUTF(); //if the reply = "Deleted" then we display the message accordingly to the user if (deleteReply.equals("Deleted")) { deleteMessage.setText("Booking number: " + bookingId + " deleted successfully!!"); deleteMessage.setVisible(true); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setHeaderText("Booking number: " + bookingId + " deleted successfully!!"); alert.show(); } else { //else we display the message to the user that the booking doesnt exist deleteMessage.setText("Booking ID " + bookingId + " does not exist!!"); deleteMessage.setVisible(true); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Booking ID " + bookingId + " does not exist!!"); alert.show(); } } else { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("BookingID cannot be 0 "); alert.show(); } } catch (NumberFormatException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in the BookingId in the correct format! "); alert.show(); } catch (Exception ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setHeaderText("Please fill in the BookingId field! "); alert.show(); } } }); /////////////////////////////////////////////////// //event handlers for back buttons backFromAddBooking.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //sending data to the server Booking b = new Booking(); b.setTrainerName("back"); ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); oos.writeObject(b); //changing the scene primaryStage.setScene(homeScene); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //event handler for back button backFromDeleteBooking.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { ObjectOutputStream oos = null; try { //sending data to the server oos = new ObjectOutputStream(clientSocket.getOutputStream()); Booking b = new Booking(); b.setBookindId(0000); oos.writeObject(b); oos.flush(); //changing the scene primaryStage.setScene(homeScene); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //event handler for back button backFromUpdateBooking.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //sending data to the server Booking b = new Booking(); b.setTrainerName("back"); ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); oos.writeObject(b); //changing the scene primaryStage.setScene(homeScene); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); //event handler for back button backFromListBooking.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { //sending data to the server DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream()); dos.writeUTF("back"); dos.flush(); //changing the scene primaryStage.setScene(homeScene); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }); } catch (IOException ex) { System.out.println("ERROR: " + ex.getMessage()); } } public static int getCurrentTime() { LocalTime time = LocalTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH"); String formattedTime = time.format(formatter); return Integer.parseInt(formattedTime); } /////////////////////////////////////////////////////////////////////////////////// /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
49.835435
316
0.530652
819e544922cc9f6307822b374ed4ee6a03aa8444
302
open module xyz.cofe.text.lex { requires java.base; requires transitive java.logging; requires transitive java.desktop; requires transitive java.scripting; requires transitive xyz.cofe.text; exports xyz.cofe.text.lex; //uses xyz.cofe.typeconv.spi.GetTypeConvertor; }
33.555556
51
0.718543
ba4679ba9f08c9f0490f51e87dd493fc0e538e30
834
package theinternet; import aquality.selenium.core.applications.IApplication; import aquality.selenium.core.elements.ElementState; import aquality.selenium.core.elements.interfaces.IElementStateProvider; import org.openqa.selenium.By; import tests.elements.factory.CustomWebElement; import java.util.function.Function; import java.util.function.Supplier; public class InputsForm extends BaseForm { private static final CustomWebElement INPUT_TEXT_BOX = new CustomWebElement(By.xpath("//input[@type='number']"), "Input", ElementState.EXISTS_IN_ANY_STATE); public InputsForm(Supplier<IApplication> appSupplier, Function<By, IElementStateProvider> stateProviderFunction) { super(appSupplier, stateProviderFunction); } public static CustomWebElement getInputTextBox(){ return INPUT_TEXT_BOX; } }
34.75
160
0.798561
91f9cd5fafc79fcf19ccba8994eea5b5eaad4d27
474
package ru.stq.pft.sandbox; import Homework2.Point; import org.testng.Assert; import org.testng.annotations.Test; public class PointTest { @Test public void testdistance () { Point p1 = new Point(3, 7); Point p2 = new Point(30, 40); Point p3 = new Point(50, 60); Assert.assertEquals(p1.distance (p2),42.638011210655684); Assert.assertEquals(p2.distance (p3),28.284271247461901); Assert.assertEquals(p1.distance (p3),70.83784299369935); } }
23.7
61
0.704641
1922ca04d3ef51be85bc04f1f9c782c6fd7d3834
3,289
/* * Copyright 2002-2007 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 com.baidu.jprotobuf.pbrpc.server; import java.util.Map; /** * RPC data object. * * @author xiemalin * @since 1.1 */ public class RpcData { /** user data. */ private byte[] data; /** user attachment data. */ private byte[] attachment; /** user authentiction data. */ private byte[] authenticationData; /** extra params. */ private byte[] extraParams; /** log id. */ private Long logId; /** extended fields. */ private Map<String, String> extFields; /** * Gets the extended fields * * @return the extended fields */ public Map<String, String> getExtFields() { return extFields; } /** * Sets the extended fields * * @param extFields the extended fields */ public void setExtFields(Map<String, String> extFields) { this.extFields = extFields; } /** * Gets the log id. * * @return the log id */ public Long getLogId() { return logId; } /** * Sets the log id. * * @param logId the new log id */ public void setLogId(Long logId) { this.logId = logId; } /** * Gets the user data. * * @return the user data */ public byte[] getData() { return data; } /** * Sets the user data. * * @param data the new user data */ public void setData(byte[] data) { this.data = data; } /** * Gets the user attachment data. * * @return the user attachment data */ public byte[] getAttachment() { return attachment; } /** * Sets the user attachment data. * * @param attachment the new user attachment data */ public void setAttachment(byte[] attachment) { this.attachment = attachment; } /** * Gets the user authentiction data. * * @return the user authentiction data */ public byte[] getAuthenticationData() { return authenticationData; } /** * Sets the user authentiction data. * * @param authenticationData the new user authentiction data */ public void setAuthenticationData(byte[] authenticationData) { this.authenticationData = authenticationData; } /** * Gets the extra params. * * @return the extra params */ public byte[] getExtraParams() { return extraParams; } /** * Sets the extra params. * * @param extraParams the new extra params */ public void setExtraParams(byte[] extraParams) { this.extraParams = extraParams; } }
21.083333
75
0.591061
b979cfa20092d15c210efd870ba475b63edda0d8
337
package cf.witcheskitchen.common.statuseffect; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectCategory; //Todo: This public class VolantStatusEffect extends StatusEffect { public VolantStatusEffect(StatusEffectCategory category, int color) { super(category, color); } }
28.083333
73
0.792285
dc0feac447ad214e9e4fbdf1eca30ac0e9495968
6,670
package com.artwl.update; import android.app.IntentService; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.Builder; import android.support.v4.content.FileProvider; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.Okio; import okhttp3.internal.Util; public class DownloadService extends IntentService { private static final String DOWNLOAD_NOTIFY_CHANNEL = "DOWNLOAD_NOTIFY_CHANNEL"; private static final int notificationId = 1; private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K private static final String TAG = "AutoUpdate"; private NotificationManager mNotifyManager; private Builder mBuilder; public DownloadService() { super("DownloadService"); } @Override public void onCreate() { super.onCreate(); // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String description = "Download Update Notification"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(DOWNLOAD_NOTIFY_CHANNEL, "UpdateCheckerNotification", importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } @Override protected void onHandleIntent(Intent intent) { mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(this, DOWNLOAD_NOTIFY_CHANNEL); String appName = getString(getApplicationInfo().labelRes); int icon = getApplicationInfo().icon; mBuilder.setContentTitle(appName).setSmallIcon(icon); String urlStr = intent.getStringExtra(Constants.APK_DOWNLOAD_URL); boolean isAutoInstall = intent.getBooleanExtra(Constants.APK_IS_AUTO_INSTALL, false); boolean checkExternal = intent.getBooleanExtra(Constants.APK_CHECK_EXTERNAL, true); BufferedSink sink = null; BufferedSource source = null; try { // apk local file paths. File dir = StorageUtils.getCacheDirectory(this, checkExternal); String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length()); File apkFile = new File(dir, apkName); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(urlStr) .addHeader("Charset", "UTF-8") .addHeader("Connection", "Keep-Alive") .addHeader("Charset", "UTF-8") .addHeader("Accept-Encoding", "gzip, deflate") .build(); Response response = client.newCall(request).execute(); ResponseBody body = response.body(); long contentLength = body.contentLength(); source = body.source(); sink = Okio.buffer(Okio.sink(apkFile)); Buffer sinkBuffer = sink.buffer(); long totalBytesRead = 0; int bufferSize = 8 * 1024; long bytesRead; int lastProgress = -1; while ((bytesRead = source.read(sinkBuffer, bufferSize)) != -1) { sink.emit(); totalBytesRead += bytesRead; int progress = (int) ((totalBytesRead * 100) / contentLength); if (progress != lastProgress) { lastProgress = progress; updateProgress(lastProgress); } } sink.flush(); apkFile.setReadable(true, false); Log.d(TAG, String.format("Download Apk to %s", apkFile)); mBuilder.setContentText(getString(R.string.download_success)).setProgress(0, 0, false); Uri fileUri = StorageUtils.getFileUri(this, apkFile); Intent installAPKIntent = new Intent(Intent.ACTION_VIEW); installAPKIntent.setDataAndType(fileUri, "application/vnd.android.package-archive"); if (isAutoInstall) { installAPKIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= 24) { intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true); installAPKIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } startActivity(installAPKIntent); mNotifyManager.cancel(notificationId); return; } String[] command = {"chmod", "777", apkFile.toString()}; ProcessBuilder builder = new ProcessBuilder(command); builder.start(); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, installAPKIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingIntent); Notification noti = mBuilder.build(); noti.flags = android.app.Notification.FLAG_AUTO_CANCEL; mNotifyManager.notify(notificationId, noti); } catch (Exception e) { Log.e(TAG, "download apk file error", e); } finally { Util.closeQuietly(sink); Util.closeQuietly(source); } } private void updateProgress(int progress) { mBuilder.setContentText(this.getString(R.string.download_progress, progress)).setProgress(100, progress, false); PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingintent); mNotifyManager.notify(notificationId, mBuilder.build()); } }
39.702381
132
0.65982
78ccd0a31ce2f27cd1a0952dd968c109971233d2
2,066
package code.arithmetic; import code.FunctionCall; import code.Instruction; import code.SpecyficValue; import errors.BadArgumentsError; import errors.BadTableUsingException; import errors.BadTypeError; import errors.NotInicializedVariableException; import errors.ZeroDivideException; public class ArithmeticExpression extends Instruction { public enum Sign { Add, Subtract, Multiply, Divide}; protected ArithmeticExpression left; protected ArithmeticExpression right; protected Boolean unary = true; protected SpecyficValue value; protected Instruction instructionValue; protected Sign sign; public Sign getSign() { return sign; } public void setSign(Sign sign) { this.sign = sign; } public Instruction getInstructionValue() { return instructionValue; } public void setInstructionValue(Instruction instructionValue) { this.instructionValue = instructionValue; } public void setValue(SpecyficValue value) { this.value = value; } @Override public void execute() throws BadTypeError { } @Override public SpecyficValue getValue() throws BadTypeError, BadTableUsingException, NumberFormatException, BadArgumentsError, ZeroDivideException, NotInicializedVariableException { if(instructionValue != null) { if(instructionValue instanceof FunctionCall) instructionValue.execute(); value = instructionValue.getValue(); } if(value == null) { NotInicializedVariableException error = new NotInicializedVariableException(); throw error; } return value; } public ArithmeticExpression getLeft() { return left; } public void setLeft(ArithmeticExpression left) { this.left = left; } public ArithmeticExpression getRight() { return right; } public void setRight(ArithmeticExpression right) { this.right = right; if(right == null) unary = true; else unary = false; } public Boolean getUnary() { return unary; } public void setUnary(Boolean unary) { this.unary = unary; } }
21.978723
175
0.727009
420b806024fef890a511301ba949d5fa189c75b8
291
package yes.tdd.users.domain; import yes.tdd.frameworks.domain.core.DomainField; public class UserName extends DomainField<String> { public UserName(String name) { super(name.trim(), "error.name-too-long"); } public String name() { return super.get(); } }
20.785714
51
0.66323
0837598689259f60a60a51548b52a0242a8c649f
26
package com.guilherme.gui;
26
26
0.846154
5230fe0cb6b912b08cf8e78756187fdcf1e53f46
352
package io.swagger.oas.inflector.config; import io.swagger.v3.core.filter.OpenAPISpecFilter; public class FilterFactory { protected static OpenAPISpecFilter FILTER = null; public static OpenAPISpecFilter getFilter() { return FILTER; } public static void setFilter(OpenAPISpecFilter filter) { FILTER = filter; } }
23.466667
60
0.721591
0d5b6256a47463197d9b02b90527da2768f90461
342
package com.dongkap.master.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.dongkap.master.entity.LanguageEntity; public interface LanguageRepo extends JpaRepository<LanguageEntity, String>, JpaSpecificationExecutor<LanguageEntity> { }
34.2
119
0.853801
465f88cde85e04c487a0607f73304e07aec79841
266
package krasa.laboratory.commons.proxy; public class SpyContext { private LoggingInvocationHandler filter; public void setFilter(LoggingInvocationHandler filter) { this.filter = filter; } public LoggingInvocationHandler getFilter() { return filter; } }
17.733333
57
0.781955
3d196fccff90ecf34d43dae873bdf5e2d37e1c30
1,133
package org.smartregister.fp.features.profile.contract; import android.content.Context; import org.jeasy.rules.api.Facts; import org.smartregister.fp.common.model.Task; import java.util.List; import java.util.Map; /** * Created by ndegwamartin on 13/07/2018. */ public interface ProfileFragmentContract { interface Presenter { ProfileFragmentContract.View getProfileView(); Facts getImmediatePreviousContact(Map<String, String> client, String baseEntityId, String contactNo); void getContactTasks(String baseEntityId, String contactNo); void updateTask(Task task, String contactNo); } interface View { void setContactTasks(List<Task> contactTasks); void updateTask(Task task); void refreshTasksList(boolean refresh); Context getContext(); } interface Interactor { void onDestroy(boolean isChangingConfiguration); void refreshProfileView(String baseEntityId, boolean isForEdit); List<Task> getContactTasks(String baseEntityId, String contactNo); void updateTask(Task task, String contactNo); } }
24.630435
109
0.719329
4176e5410209e6f2fb76814c51287d8b67e3011b
12,880
package solution; import instance.Instance; import instance.Request; import network.Client; import network.Depot; import network.Point; import java.util.Collections; import java.util.LinkedList; public abstract class Tournee { /* * PARAMETRE */ protected int coutTotal; protected Instance instance; protected Point depot; protected int jour; protected final LinkedList<Request> listRequest; /* * CONSTRUCTEUR */ public Tournee(Tournee t) { coutTotal = t.coutTotal; instance = t.instance; depot = t.depot; jour = t.jour; listRequest = new LinkedList<>(t.listRequest); } public Tournee() { this.coutTotal = 0; this.instance = null; this.listRequest = new LinkedList<Request>(); } public Tournee(Instance instance, int jour) { this.coutTotal = 0; this.listRequest = new LinkedList<Request>(); this.jour = jour; this.instance = instance; } /* * METHODES */ public int getCoutTotal() { return coutTotal; } public LinkedList<Request> getListRequest() { return listRequest; } public boolean isEmpty() { return listRequest.isEmpty(); } public Point getDepot(){ return this.depot; }; /** * Fonction qui renvoie le client à la position pos de la liste de clients * @param pos la position du client à récupérer * @return le client à la position pos ou null */ public Request getRequestAt(int pos) { if (pos < 0 || pos >= listRequest.size()) return null; return listRequest.get(pos); } /** * Fonction qui ajoute un client à la tournée * @param request le client à ajouter à la tournée * @return true si l'ajout a pu se faire et false sinon */ public abstract boolean ajouterRequest(Request request); /** * Fonction testant la possibilité d'insérer un client * @param request le client à insérer * @return true si le client peut être inséré et false sinon */ public abstract boolean canInsererRequest(Request request); public abstract boolean check(); public boolean isPositionvalide(int pos) { return pos >= 0 && pos < listRequest.size(); } public int calculCoutAjoutRequest(Request request){ // considére que la requette est ajouté en derniére position, à update plus tard pour prendre en compte une position n int delta=0; if(listRequest.isEmpty()){ //System.out.println("client ["+request.getClient().getId()+"]-> depot = "+request.getClient().getCoutVers(depot)); //System.out.println("getMapRoutes="+request.getClient().getMapRoutes()); delta += depot.getCoutVers(request.getClient())*2; } else { //System.out.println("else"); delta += listRequest.get(listRequest.size() - 1).getClient().getCoutVers(request.getClient()); delta -= listRequest.get(listRequest.size() - 1).getClient().getCoutVers(depot); // :friJudge: delta += request.getClient().getCoutVers(depot); } //System.out.println("delta ="+delta); return delta; } /** * Fonction qui calcule le coût total en itérant sur tous les clients et vérifie s'il correspond au deltaCout total de la * tournée * @return true si le coût total théorique correspond au coût total effectif */ private boolean checkCalculerCoutTotal() { int cTotal = 0; for (int i = 0; i < listRequest.size() - 1; i++) { // On calcul les liens entre tous les clients cTotal += listRequest.get(i).getClient().getCoutVers(listRequest.get(i+1).getClient()); } // On ajoute les liens entre le premier et dernier points au dépôt cTotal += depot.getCoutVers(listRequest.getFirst().getClient()) + listRequest.getLast().getClient().getCoutVers(depot); boolean test = cTotal == coutTotal; if (!test) System.out.println("Erreur Test checkCalculerCoutTotal:\n\tcoût total théorique: " + cTotal + "\n\tcoût effectif: " + coutTotal); return test; } /** * Fonction textant la possibilité de fusionner deux tournées * @param tournee la tournée à fusionner * @return true si la fusion est possible et false sinon private boolean canFusionnerTournee(Tournee tournee) { if (tournee == null || tournee.isEmpty() || this.isEmpty()) return false; return tournee != this && this.demandeTotale + tournee.demandeTotale < capacite; }*/ /** * Fonction qui calcule en O(1) le deltaCout total de la tournée à partir du dernier client ajouté * @param c le dernier client ajouté à la liste private void calculerCoutTotal(Client c) { coutTotal += deltaCoutInsertion(listClient.size(), c); }*/ /** * Fonction qui renvoie le point de la tournée qui précède la position pos * @param pos la position à interroger * @return le point en position pos-1, si pos <= 0 il s'agit du dépot private Point getPrec(int pos) { if (pos < 0 || pos > listClient.size()) return null; if (pos == 0) return depot; return listClient.get(pos-1); } /** * Fonction qui renvoie le point de la tournée qui est en position pos * @param pos la position à interroger * @return le point en position pos, si pos >= taille listeClients ils s'agit du dépot private Point getCurrent(int pos) { if (pos < 0 || pos > listClient.size()) return null; if (pos == listClient.size()) return depot; return listClient.get(pos); }*/ /** * Fonction qui renvoie le point suivant la position pos * @param pos la position actuelle * @return le point en position pos+1 si pos est la position du dernier client alors pos+1 est le dépôt private Point getNext(int pos) { if (pos+1 <= 0 || pos+1 > listClient.size()) return null; if (pos+1 == listClient.size()) return depot; return listClient.get(pos+1); }*/ /** * Fonction qui vérifie si une position est valide * @param pos la position à tester * @return true si la position est valide et false sinon */ /** * Fonction qui teste si une position est valide pour une insertion * @param pos la position où insérer * @return true si la position est possible et false sinon private boolean isPositionInsertionValide(int pos) { return getPrec(pos) != null && getCurrent(pos) != null; } /** * Fonction qui calcule en O(1) le deltaCout total de la tournée à partir du dernier client ajouté en position pos * @param pos la position d'insertion du client * @param client le client à insérer * @return le deltaCout de l'insertion du client à la position donnée (= infini si la position est invalide) public int deltaCoutInsertion(int pos, Client client) { if (!isPositionInsertionValide(pos)) return Integer.MAX_VALUE; if (listClient.isEmpty()) return 2 * client.getCoutVers(depot); else { Point prec = getPrec(pos); Point curr = getCurrent(pos); if (prec == null || curr == null) return Integer.MAX_VALUE; return prec.getCoutVers(client) + client.getCoutVers(curr) - prec.getCoutVers(curr); } } public int deltaCoutInsertionInter(int pos, Client client) { if (!canInsererClient(client)) return Integer.MAX_VALUE; return deltaCoutInsertion(pos, client); } /** * Fonction qui calcule le deltaCout pour fusionner une tournée avec cette tournée * @param aFusionner la tournée à fusionner avec cette instance * @return le deltaCout engendré par la fusion public int deltaCoutFusion(Tournee aFusionner) { if (aFusionner == null || listClient.isEmpty() || aFusionner.listClient.isEmpty()) return Integer.MAX_VALUE; Client dernier = listClient.getLast(); Client premier = aFusionner.listClient.getLast(); return dernier.getCoutVers(premier) - dernier.getCoutVers(depot) - depot.getCoutVers(premier); } /** * Fonction qui calcule le deltaCout pour supprimer le client en position pos de cette tournée * @param pos la position du client à retirer * @return le deltaCout engendré par la suppression du client de la tournée public int deltaCoutSupression(int pos) { if (!isPositionvalide(pos)) return Integer.MAX_VALUE; if (listClient.size() == 1) return -getCoutTotal(); Point prec = getPrec(pos); Point curr = getCurrent(pos); Point next = getNext(pos); if (prec == null || curr == null || next == null) return Integer.MAX_VALUE; return prec.getCoutVers(next) - prec.getCoutVers(curr) - curr.getCoutVers(next); } /** * Fonction qui calcule le deltaCout pour déplacer le client d'une position I à une position J * @param posI la position de départ du client * @param posJ la position d'insertion du client * @return le deltaCout engendré par le déplacement du client public int deltaCoutDeplacement(int posI, int posJ) { if (!doublePositionValide(posI, posJ)) return Integer.MAX_VALUE; return deltaCoutSupression(posI) + deltaCoutInsertion(posJ, getClientAt(posI)); } private boolean doublePositionValide(int pI, int pJ) { return isPositionvalide(pI) && isPositionvalide(pJ) && pI != pJ && Math.abs(pI - pJ) != 1; }*/ /** * Fonction qui calcule le deltaCout pour échanger les clients en position I et J * @param posI la position du client I * @param posJ la position du client J * @return le deltaCout engendré par l'échange public int deltaCoutEchange(int posI, int posJ) { if (!isPositionvalide(posI) || !isPositionvalide(posJ)) return Integer.MAX_VALUE; if (posI == posJ) return 0; if (posJ < posI) return deltaCoutEchange(posJ, posI); if (posI+1 == posJ) return deltaCoutEchangeConsecutif(posI); return deltaCoutRemplacement(posI, posJ); }*/ /** private int deltaCoutEchangeConsecutif(int pos) { Client i = listClient.get(pos); Client j = listClient.get(pos+1); Point prec = getPrec(pos); Point next = getNext(pos+1); if (prec == null || next == null) return Integer.MAX_VALUE; return prec.getCoutVers(j) + i.getCoutVers(next) - (prec.getCoutVers(i) + j.getCoutVers(next)); } private int deltaCoutRemplacement(int posI, int posJ) { Client i = listClient.get(posI); Point precI = getPrec(posI); Point nextI = getNext(posI); Client j = listClient.get(posJ); Point precJ = getPrec(posJ); Point nextJ = getNext(posJ); if (precI == null || nextI == null || precJ == null || nextJ == null) return Integer.MAX_VALUE; return precI.getCoutVers(j) + j.getCoutVers(nextI) + precJ.getCoutVers(i) + i.getCoutVers(nextJ) - (precI.getCoutVers(i) + i.getCoutVers(nextI) + precJ.getCoutVers(j) + nextJ.getCoutVers(j)); }*/ /** * Fonction qui calcule le cout de remplacement du client à la position pos par le client c * @param pos la position du client à remplacer * @param c le client qui remplace * @return le delatCout engendré public int deltaCoutRemplacement(int pos, Client c) { if (!isPositionvalide(pos) || c == null) return Integer.MAX_VALUE; Client i = listClient.get(pos); Point prec = getPrec(pos); Point next = getNext(pos); if (prec == null || next == null) return Integer.MAX_VALUE; if (demandeTotale + c.getDemande() - i.getDemande() > capacite) return Integer.MAX_VALUE; return prec.getCoutVers(c) + c.getCoutVers(next) - (prec.getCoutVers(i) + i.getCoutVers(next)); }*/ /** * Fonction qui permet de tester si une tournée est réalisable ou non * @return true si la tournée est réalisable et false sinon */ /** * Fonction qui vérifie que la demande totale et le coût total sont corrects * @return true si tout est correct et false sinon private boolean checkCalculsDemandeCoutTotal() { return checkCalculerDemandeTotale() && checkCalculerCoutTotal(); }*/ /** * Fonction qui calcule la demande totale en itérant sur tous les clients et vérifie si elle est conorme à la * demande totale de la tournée * @return true si la demande totale théorique correspond à la demande totale effective */ @Override public String toString() { return "Tournee{" + ", coutTotal=" + coutTotal + '}'; } }
35.191257
127
0.639829
c62868aa5ad72ab80a25202953a6a12efbe520d8
19,142
/* * Copyright (C) 2017 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.exoplayer; import android.Manifest; import android.annotation.SuppressLint; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.DefaultRenderersFactory; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.audio.AudioRendererEventListener; import com.google.android.exoplayer2.decoder.DecoderCounters; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.source.ConcatenatingMediaSource; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.video.VideoRendererEventListener; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; /** * A fullscreen activity to play audio or video streams. */ public class PlayerActivity extends AppCompatActivity implements View.OnClickListener { SimpleExoPlayerView playerView; SimpleExoPlayer player; ComponentListner componentListner; // Button takeSnapshot; ImageView snapshotResultImg; ImageButton increaseSpeed; ImageButton decreaseSpeed; ImageButton imgBtn_snapshot; TextView txt_speedValue; View ExoPlayerDisplayArea; private long playbackPosition = 0; private int currentWindow = 0; private float playbackSpeed = 1.0f; private boolean playWhenReady; private static final int PERMISSION_REQUEST_CODE = 1; private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter(); // private TextureView textureView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_player); playerView = findViewById(R.id.videoView); increaseSpeed = findViewById(R.id.speed_increase); decreaseSpeed = findViewById(R.id.speed_decrease); imgBtn_snapshot = findViewById(R.id.snapshot); txt_speedValue = findViewById(R.id.speed_value); // textureView = findViewById(R.id.textureView); ExoPlayerDisplayArea = findViewById(R.id.exo_progress); increaseSpeed.setOnClickListener(this); decreaseSpeed.setOnClickListener(this); imgBtn_snapshot.setOnClickListener(this); checkStoragePermission(); } private void checkStoragePermission() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it"); String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; requestPermissions(permissions, PERMISSION_REQUEST_CODE); } } } @Override public void onClick(View v) { if(v.getId() == R.id.speed_increase) { playbackSpeed += 0.25f; txt_speedValue.setText(Float.toString(playbackSpeed)); player.setPlaybackParameters(new PlaybackParameters(playbackSpeed,1.0f)); } else if(v.getId() == R.id.speed_decrease) { playbackSpeed -= 0.25f; txt_speedValue.setText(Float.toString(playbackSpeed)); player.setPlaybackParameters(new PlaybackParameters(playbackSpeed,1.0f)); } else if(v.getId() == R.id.snapshot) { // takeScreenshot(); takeSnapsAndSaveToDrive(); } } private void takeSnapsAndSaveToDrive() { Bitmap b = takeScreenShot(); Screenshot.SaveImageToLocalDirectory(b); } public Bitmap takeScreenShot() { // v.setDrawingCacheEnabled(true); // v.buildDrawingCache(true); // Bitmap snap = Bitmap.createBitmap(v.getDrawingCache()); // v.setDrawingCacheEnabled(false); // return snap; // View v1 = getWindow().getDecorView().getRootView(); TextureView textureView = (TextureView) playerView.getVideoSurfaceView(); Bitmap bitmap = textureView.getBitmap(); return bitmap; } // private void captureScreen() { // View v = getWindow().getDecorView().getRootView(); // v.setDrawingCacheEnabled(true); // Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache()); // v.setDrawingCacheEnabled(false); // try { // FileOutputStream fos = new FileOutputStream(new File(Environment // .getExternalStorageDirectory().toString(), "SCREEN" // + System.currentTimeMillis() + ".png")); // bmp.compress(Bitmap.CompressFormat.PNG, 100, fos); // fos.flush(); // fos.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // } @Override public void onStart() { super.onStart(); if (Util.SDK_INT > 23) { initializePlayer(); } } @Override public void onResume() { super.onResume(); hideSystemUi(); if ((Util.SDK_INT <= 23 || player == null)) { initializePlayer(); } } @Override public void onPause() { super.onPause(); if (Util.SDK_INT <= 23) { releasePlayer(); } // TakeSnapshot(); } @Override public void onStop() { super.onStop(); if (Util.SDK_INT > 23) { releasePlayer(); } } private void releasePlayer() { if (player != null) { playbackPosition = player.getCurrentPosition(); currentWindow = player.getCurrentWindowIndex(); playWhenReady = player.getPlayWhenReady(); player.release(); player = null; } } @SuppressLint("InlinedApi") private void hideSystemUi() { playerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } private void initializePlayer() { if(player==null) { TrackSelection.Factory adaptiveTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); player = ExoPlayerFactory.newSimpleInstance( new DefaultRenderersFactory(this), new DefaultTrackSelector(adaptiveTrackSelectionFactory), new DefaultLoadControl()); playerView.setPlayer(player); // player.setVideoTextureView(textureView); player.setPlayWhenReady(playWhenReady); player.seekTo(currentWindow, playbackPosition); player.setPlaybackParameters(new PlaybackParameters(1.0f,1.0f)); Uri uri = Uri.parse(getString(R.string.media_url_mp4)); MediaSource mediaSource = buildMediaSource(uri); player.prepare(mediaSource, true, false); } } /* private void TakeSnapshot() { View textureView = playerView.getVideoSurfaceView(); // Bitmap bitmap = Bitmap.createBitmap(textureView.getWidth(), textureView.getHeight(), Bitmap.Config.ARGB_8888); Bitmap bitmap = getViewBitmapNew(textureView); // Canvas canvas = new Canvas(bitmap); snapshotResultImg.setImageBitmap(bitmap); // textureView.draw(canvas); Log.i("bitmap", "TakeSnapshot: "+bitmap.getWidth()); }*/ /* private void storeImage(Bitmap image) { File pictureFile = getOutputMediaFile(); if (pictureFile == null) { Log.d("hjk", "Error creating media file, check storage permissions: ");// e.getMessage()); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); image.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); } catch (FileNotFoundException e) { Log.d("ds", "File not found: " + e.getMessage()); } catch (IOException e) { Log.d("sd", "Error accessing file: " + e.getMessage()); } }*/ private File getOutputMediaFile(){ // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/HubblerPictures/" + getApplicationContext().getPackageName() + "/Files"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (! mediaStorageDir.exists()){ if (! mediaStorageDir.mkdirs()){ return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date()); File mediaFile; String mImageName="MI_"+ timeStamp +".jpg"; mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName); return mediaFile; } /*private Bitmap getViewBitmapNew(View v) { v.clearFocus(); v.setPressed(false); boolean willNotCache = v.willNotCacheDrawing(); v.setWillNotCacheDrawing(false); // Reset the drawing cache background color to fully transparent // for the duration of this operation int color = v.getDrawingCacheBackgroundColor(); v.setDrawingCacheBackgroundColor(0); if (color != 0) { v.destroyDrawingCache(); } v.buildDrawingCache(); Bitmap cacheBitmap = v.getDrawingCache(); if (cacheBitmap == null) { Log.e("img", "failed getViewBitmap(" + v + ")", new RuntimeException()); return null; } Bitmap bitmap = Bitmap.createBitmap(cacheBitmap); // Restore the view v.destroyDrawingCache(); v.setWillNotCacheDrawing(willNotCache); v.setDrawingCacheBackgroundColor(color); return bitmap; }*/ /*Bitmap getViewBitmap(View view) { //Get the dimensions of the view so we can re-layout the view at its current size //and create a bitmap of the same size int width = view.getWidth(); int height = view.getHeight(); int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY); int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY); //Cause the view to re-layout view.measure(measuredWidth, measuredHeight); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); //Create a bitmap backed Canvas to draw the view into Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); //Now that the view is laid out and we have a canvas, ask the view to draw itself into the canvas view.draw(c); return b; }*/ private MediaSource buildMediaSource(Uri uri) { // these are reused for both media sources we create below DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory(); DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory( "user-agent"); ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory( new DefaultHttpDataSourceFactory("exoplayer-codelab")). createMediaSource(uri); // HlsSampleSource sampleSource = new HlsSampleSource(chunkSource, loadControl, MAIN_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE); // ExtractorMediaSource videoSource = // new ExtractorMediaSource.Factory( // new DefaultHttpDataSourceFactory("exoplayer-codelab")). // createMediaSource(uri); // Uri audioUri = Uri.parse(getString(R.string.media_url_mp4)); ExtractorMediaSource audioSource = new ExtractorMediaSource.Factory( new DefaultHttpDataSourceFactory("exoplayer-codelab")). createMediaSource(uri); return new ConcatenatingMediaSource(audioSource, videoSource); // DataSource.Factory manifestDataSourceFactory = // new DefaultHttpDataSourceFactory("ua"); // DashChunkSource.Factory dashChunkSourceFactory = // new DefaultDashChunkSource.Factory( // new DefaultHttpDataSourceFactory("ua", BANDWIDTH_METER)); // return new DashMediaSource.Factory(dashChunkSourceFactory, // manifestDataSourceFactory).createMediaSource(uri); } private void takeScreenshot() { Date now = new Date(); String outputDir; android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now); try { // image naming and path to include sd card appending name you choose for file // String mPath = Environment.DIRECTORY_DOWNLOADS + "/" + now + ".jpg"; String path = Environment.getExternalStorageDirectory() + "/" + "HubblerPictures/"; File dir = new File(path); if(!dir.exists()) { dir.mkdirs(); } outputDir = dir.getAbsolutePath()+"/abc.JPEG"; // create bitmap screen capture View v1 = getWindow().getDecorView().getRootView(); v1.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache()); v1.setDrawingCacheEnabled(false); File imageFile = new File(outputDir); FileOutputStream outputStream = new FileOutputStream(imageFile); int quality = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream); outputStream.flush(); outputStream.close(); // openScreenshot(imageFile); } catch (Throwable e) { // Several error may come out with file handling or DOM e.printStackTrace(); } } private class ComponentListner implements ExoPlayer.EventListener, VideoRendererEventListener, AudioRendererEventListener{ @Override public void onTimelineChanged(Timeline timeline, Object manifest) { } @Override public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { } @Override public void onLoadingChanged(boolean isLoading) { } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { } @Override public void onRepeatModeChanged(int repeatMode) { } @Override public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) { } @Override public void onPlayerError(ExoPlaybackException error) { } @Override public void onPositionDiscontinuity(int reason) { } @Override public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { } @Override public void onSeekProcessed() { } @Override public void onAudioEnabled(DecoderCounters counters) { } @Override public void onAudioSessionId(int audioSessionId) { } @Override public void onAudioDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { } @Override public void onAudioInputFormatChanged(Format format) { } @Override public void onAudioSinkUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) { } @Override public void onAudioDisabled(DecoderCounters counters) { } @Override public void onVideoEnabled(DecoderCounters counters) { } @Override public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { } @Override public void onVideoInputFormatChanged(Format format) { } @Override public void onDroppedFrames(int count, long elapsedMs) { } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { } @Override public void onRenderedFirstFrame(Surface surface) { } @Override public void onVideoDisabled(DecoderCounters counters) { } } }
33.760141
131
0.655417
879099894b56008983198291468d62dec7407053
2,405
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("43") class Record_975 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 975: FirstName is Andre") void FirstNameOfRecord975() { assertEquals("Andre", customers.get(974).getFirstName()); } @Test @DisplayName("Record 975: LastName is Ribble") void LastNameOfRecord975() { assertEquals("Ribble", customers.get(974).getLastName()); } @Test @DisplayName("Record 975: Company is American Hackney Horse Society") void CompanyOfRecord975() { assertEquals("American Hackney Horse Society", customers.get(974).getCompany()); } @Test @DisplayName("Record 975: Address is 900 Grand St") void AddressOfRecord975() { assertEquals("900 Grand St", customers.get(974).getAddress()); } @Test @DisplayName("Record 975: City is Brooklyn") void CityOfRecord975() { assertEquals("Brooklyn", customers.get(974).getCity()); } @Test @DisplayName("Record 975: County is Kings") void CountyOfRecord975() { assertEquals("Kings", customers.get(974).getCounty()); } @Test @DisplayName("Record 975: State is NY") void StateOfRecord975() { assertEquals("NY", customers.get(974).getState()); } @Test @DisplayName("Record 975: ZIP is 11211") void ZIPOfRecord975() { assertEquals("11211", customers.get(974).getZIP()); } @Test @DisplayName("Record 975: Phone is 718-782-2065") void PhoneOfRecord975() { assertEquals("718-782-2065", customers.get(974).getPhone()); } @Test @DisplayName("Record 975: Fax is 718-782-0036") void FaxOfRecord975() { assertEquals("718-782-0036", customers.get(974).getFax()); } @Test @DisplayName("Record 975: Email is andre@ribble.com") void EmailOfRecord975() { assertEquals("andre@ribble.com", customers.get(974).getEmail()); } @Test @DisplayName("Record 975: Web is http://www.andreribble.com") void WebOfRecord975() { assertEquals("http://www.andreribble.com", customers.get(974).getWeb()); } }
25.052083
82
0.728898
20709d93c0e2e608909d3fc826e058bace98752a
13,861
package edu.umass.eflux; import java.util.*; import edu.umass.eflux.AtomicDeclaration; import edu.umass.eflux.ErrorHandler; import edu.umass.eflux.FlowStatement; /** * The top level representation of a Flux program * @author Brendan Burns * @version $version: $ * @revised Matt Brennan **/ public class Program { private Vector<Source> sources; private Vector<TimerSource> timersources; private Vector<Platform> platforms; private Vector<TimeConstraint> time_bounds; private Vector<FlowStatement> exps; private Vector<ErrorHandler> errors; private Hashtable<String, TaskDeclaration> decls; private Hashtable<String, TypeDeclaration> type_decs; private Hashtable<String, AtomicDeclaration> atomic_defs; private StateOrder stateorder; public final String EonSend = "EonSend"; public final String EonRecv = "EonRecv"; /** * Constructor * @param kick The function which kicks off this program * @param types A Vector of TypeDeclarations defining types. * @param decl_list A Vector of TaskDeclarations defining functions * @param program A Vector of FlowStatements defining the program **/ public Program(Vector<Source> sources, Vector<Platform> platforms, Vector<TimeConstraint> times, Vector<TypeDeclaration> types, Vector<Vector<String>> states, Vector<FlowStatement> program, Vector<AtomicDeclaration> atomic_decls, Vector<ErrorHandler> errors) throws Exception { this.platforms = platforms; this.sources = sources; this.exps = program; this.errors = errors; this.stateorder = new StateOrder(states); this.time_bounds = times; this.timersources = new Vector<TimerSource>(); this.decls = new Hashtable<String, TaskDeclaration>(); //System.out.println("\n\n "); //include network code? boolean sends, recvs; sends = false; recvs = false; for (FlowStatement exp : this.exps) { if (exp.inRightHandSide(this.EonSend)) { sends = true; } if (exp.getAssignee().equals(this.EonRecv)) { recvs = true; } } for (Platform platform: platforms) { //TODO: make sure that we don't have duplicate names... for now we ignore this problem. for (int i=0;i<platform.tasks.size();i++) { platform.tasks.get(i).setPlatformName(platform.getName()); this.decls.put((platform.tasks.get(i)).getName(), platform.tasks.get(i)); } if (sends) { this.decls.put(this.EonSend, getNetworkSendTD(platform)); } if (recvs) { this.decls.put(this.EonRecv, getNetworkRecvTD(platform)); } } for (Source s: sources) { if (s instanceof TimerSource) { this.timersources.add((TimerSource)s); //TaskDeclaration TaskDeclaration newTD = new TaskDeclaration(s.getSourceFunction()); TaskDeclaration target = this.decls.get(s.getTarget()); if (target == null) { System.out.println("ERROR: Abstract node "+s.getTarget()+" is used but not declared!"); System.exit(1); } newTD.setPlatformName(target.getPlatformName()); this.decls.put(s.getSourceFunction(),newTD); } } this.type_decs = new Hashtable<String, TypeDeclaration>(); for (int i=0;i<types.size();i++) { this.type_decs.put((types.get(i)).getName(), types.get(i)); } this.atomic_defs = new Hashtable<String, AtomicDeclaration>(); for (AtomicDeclaration ad : atomic_decls) { this.atomic_defs.put(ad.getName(), ad); } } private TaskDeclaration getNetworkSendTD(Platform plat) { Vector<Argument> inputs = new Vector<Argument>(); Vector<Argument> outputs = new Vector<Argument>(); inputs.add(new Argument("eon_message_t", "msg")); inputs.add(new Argument("uint16_t", "addr")); return new TaskDeclaration(inputs, this.EonSend, outputs, plat.getName()); } private TaskDeclaration getNetworkRecvTD(Platform plat) { Vector<Argument> inputs = new Vector<Argument>(); Vector<Argument> outputs = new Vector<Argument>(); outputs.add(new Argument("eon_message_t", "msg")); outputs.add(new Argument("uint16_t", "addr")); return new TaskDeclaration(inputs, this.EonRecv, outputs, plat.getName()); } public Source getSessionStart(FlowStatement fs) { for (Source s : sources) { if (s.getTarget().equals(fs.getAssignee())) return s; } return null; } /** * Get the set of atomic declarations * @return a Vector of AtomicDeclarations **/ public Collection<AtomicDeclaration> getAtomicDeclarations() { return atomic_defs.values(); } /** * Get a particular atomic declaration * @param name The name of the fn * @return The named atomic declaration **/ public AtomicDeclaration getAtomicDeclaration(String name) { return atomic_defs.get(name); } /** * Get the set of error handlers * @return A Vector of ErrorHandlers * @see ErrorHandler **/ public Vector<ErrorHandler> getErrorHandlers() { return errors; } /** * Get the set of sources for this Eon program * @return A vector of the String names of the sources * @see getTask **/ public Vector<Source> getSources() { return sources; } /** * Get the set of sources for this Markov program * @return A vector of the String names of the sources * @see getTask **/ public StateOrder getStates() { return this.stateorder; } /** * Get all of the functions in this Program * @return A Collection containing the TaskDeclarations in the program **/ public Collection<TaskDeclaration> getFunctions() { return this.decls.values(); } public Vector<Platform> getPlatforms() { return this.platforms; } /** * Get all of the types in this program * @return A Collection containing the TypeDeclarations **/ public Collection getTypes() { return this.type_decs.values(); } /** * Get the main function. The main function (not to be confused with * the kickstart) is the expression whose left-hand side appears in * no right hand sides. * @return The FlowStatement which is the main expression for this program **/ public FlowStatement getMain() { Vector stmts = (Vector) this.exps.clone(); Iterator it = stmts.iterator(); while (it.hasNext()) { FlowStatement stmt = (FlowStatement)it.next(); String name = stmt.getAssignee(); for (int i=0; i < this.exps.size(); i++) { FlowStatement temp = this.exps.get(i); if (temp.inRightHandSide(name)) { System.err.println("Removing: " + it.toString()); it.remove(); } } } //System.out.println(stmts.toString()); return (FlowStatement)stmts.get(0); } /** * Get a named type * @param name The name of the type * @return The type, or null if it can't be found. **/ public TypeDeclaration getType(String name) { return this.type_decs.get(name); } /** * Get a named task * @param name The name of the type * @return The task, or null if it can't be found. **/ public TaskDeclaration getTask(String name) { return this.decls.get(name); } public Vector<TimeConstraint> getTimeConstraints() { return this.time_bounds; } /** * Get all expressions * @return a Vector of FlowStatements containing all expressions **/ public Vector getExpressions() { return this.exps; } /** * Get an indexe expression * @param ix The index of the expression * @return The expression **/ public FlowStatement getExpression(int ix) { return this.exps.get(ix); } /** * Get a named flow statement * @param name The name of the left-hand side of the statement * @return The FlowStatement whose left-hand side matches name, or null **/ public FlowStatement getFlow(String name) { for (int i=0; i < this.exps.size(); i++) { if ((this.exps.get(i)).getAssignee().equals(name)) return this.exps.get(i); } return null; } /** * Find all instances of SimpleFlowStatements matching the left-hand * side of the specified statement, remove them from the program * and create a TypedFlowStatement containing them. * @param stmt The statement to unify * @return The new compound TypedFlowStatement **/ public TypedFlowStatement unifyExpression(FlowStatement stmt) { //System.out.println("Unifying statement : "+stmt.toString()); TypedFlowStatement result = new TypedFlowStatement(stmt.getAssignee()); result.addFlowStatement(stmt); Iterator it = this.exps.iterator(); while (it.hasNext()) { FlowStatement fs = (FlowStatement)it.next(); //System.out.println("Now unifying: " + fs.toString()); if (fs != stmt) { if (fs.getAssignee().equals(result.getAssignee())) { it.remove(); result.addFlowStatement(fs); } } } System.out.println("TypedFlowStatement: " + result.toString()); return result; } /** * Find all instances of typed SimpleFlowStatements and merge them into * compound TypedFlowStatements * @see TypedFlowStatement **/ public void unifyExpressions() { for (int i=0; i < this.exps.size(); i++) { if (this.exps.get(i) instanceof SimpleFlowStatement) { SimpleFlowStatement fs = (SimpleFlowStatement) this.exps.get(i); //System.out.println("SFS: " + fs.toString()); if (fs.getTypes() != null || fs.getState() != null) { TypedFlowStatement tfs = unifyExpression(fs); this.exps.set(i, tfs); } } } //System.out.println("\n\n\n"); } /** * Verify an expression to insure that input types match output types * @param stmt The expression to verify * @return true if the expression is valid, false otherwise **/ public boolean verifyExpression(SimpleFlowStatement stmt) { Vector types = stmt.getTypes(); Vector args = stmt.getArguments(); String left = stmt.getAssignee(); TaskDeclaration td = this.decls.get(left); if (td == null) { System.err.println("Error, "+left+" is undefined."); return false; } if (types != null) { if (types.size() != td.getInputs().size()) { System.err.println("Type specification for "+ stmt.getAssignee()+ " doesn't match arguments ("+ types.size()+":"+td.getInputs().size()+")"); return false; } for (int i=0;i<types.size();i++) { String type = (String)types.get(i); if (!type.equals("*") && this.type_decs.get(type)==null) { System.err.println("Type "+type+" is undefined."); return false; } } } if (args.size() > 0) { String now = (String)args.get(0); TaskDeclaration current = this.decls.get(now); if (current == null) { System.err.println("Error, "+now+" is undefined."); return false; } if (!current.isInMatch(td)) { System.err.println("Inputs of "+now+" don't match inputs of "+ left); return false; } int i=1; while (i<args.size()) { String next = (String)args.get(i++); TaskDeclaration next_td = this.decls.get(next); if (next_td == null) { System.err.println("Error, "+next+" is undefined."); return false; } if (!current.isOutInMatch(next_td)) { System.err.println("Outputs of "+now+ " don't match inputs of "+next+"."); return false; } now = next; current = next_td; } if (!current.isOutMatch(td)) { System.err.println("Outputs of "+now+ " don't match inputs of "+left+"."); return false; } } return true; } /** * Verify all expression to insure that input types match output types * @return true if the expression is valid, false otherwise **/ public boolean verifyExpressions() { for (int i=0; i < this.exps.size(); i++) { if (!verifyExpression((SimpleFlowStatement)this.exps.get(i))) { return false; } } return true; } /** * String representation of this program * @return The string representing this program **/ public String toString() { return this.decls+"\n::\n"+this.exps; } /** * Get a source by name * @param name The name * @param srcs The list of sources **/ Source getSource(String name) { for (Source src : sources) { if (src.getSourceFunction().equals(name)) return src; } return null; } /** * Is this task declaration a source? * @param task The task * @return true if the task declaration is a source **/ boolean isSource(TaskDeclaration td) { String name = td.getName(); for (Source src : sources) { if (src.getSourceFunction().equals(name)) return true; } return false; } }
30.067245
93
0.593392
bc91260eed7c663ddd7f12429233dd8ea57c19f7
1,849
package com.github.rogerli; import org.springframework.boot.Banner; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; /** * @author roger.li */ //@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) // same as @Configuration @EnableAutoConfiguration @ComponentScan @Configuration @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) @ComponentScan(basePackages = "com.github.rogerli") //@EnableAspectJAutoProxy(proxyTargetClass = true) //@Order(1) @EnableWebMvc public class ApplicationTest { /** * jar包 * * @param args */ public static void main(String[] args) { // SpringApplication.run(ApplicationTest.class, args); new SpringApplicationBuilder(ApplicationTest.class).bannerMode(Banner.Mode.OFF).run(args); } // /** // * 普通war包 // * @param builder // * @return // */ // @Override // protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { // return builder.sources(ApplicationTest.class); // } @Bean public CharacterEncodingFilter characterEncodingFilter() { final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); return characterEncodingFilter; } }
34.240741
137
0.75987
04ebe2467b12c3a5dd193a54fec00b7cfa513650
7,802
package com.freight.model; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.math.BigDecimal; import java.time.Instant; /** * Created by toshikijahja on 11/7/18. */ @Entity public class Location { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column private String externalId; @Column private String mainName; @Column private String secondaryName; @Column private BigDecimal lat; @Column private BigDecimal lon; @Column private String route; @Column private String locality; /** * kelurahan / desa */ @Column private String village; /** * kecamatan */ @Column private String subdistrict; /** * kota / kabupaten */ @Column private String city; @Column private String province; @Column private String country; @Column @CreationTimestamp private Instant created; @Column @UpdateTimestamp private Instant lastModified; public Location() {} private Location(final Builder builder) { this.id = builder.id; this.externalId = builder.externalId; this.mainName = builder.mainName; this.secondaryName = builder.secondaryName; this.lat = builder.lat; this.lon = builder.lon; this.route = builder.route; this.locality = builder.locality; this.village = builder.village; this.subdistrict = builder.subdistrict; this.city = builder.city; this.province = builder.province; this.country = builder.country; } public int getId() { return id; } public String getExternalId() { return externalId; } public String getMainName() { return mainName; } public String getSecondaryName() { return secondaryName; } public BigDecimal getLat() { return lat; } public BigDecimal getLon() { return lon; } public String getRoute() { return route; } public String getLocality() { return locality; } public String getVillage() { return village; } public String getSubdistrict() { return subdistrict; } public String getCity() { return city; } public String getProvince() { return province; } public String getCountry() { return country; } public Instant getCreated() { return created; } public Instant getLastModified() { return lastModified; } public static class Builder { private int id; private String externalId; private String mainName; private String secondaryName; private BigDecimal lat; private BigDecimal lon; private String route; private String locality; private String village; private String subdistrict; private String city; private String province; private String country; public Builder id(final int id) { this.id = id; return this; } public Builder externalId(final String externalId) { this.externalId = externalId; return this; } public Builder mainName(final String mainName) { this.mainName = mainName; return this; } public Builder secondaryName(final String secondaryName) { this.secondaryName = secondaryName; return this; } public Builder lat(final BigDecimal lat) { this.lat = lat; return this; } public Builder lon(final BigDecimal lon) { this.lon = lon; return this; } public Builder route(final String route) { this.route = route; return this; } public Builder locality(final String locality) { this.locality = locality; return this; } public Builder village(final String village) { this.village = village; return this; } public Builder subdistrict(final String subdistrict) { this.subdistrict = subdistrict; return this; } public Builder city(final String city) { this.city = city; return this; } public Builder province(final String province) { this.province = province; return this; } public Builder country(final String country) { this.country = country; return this; } public Location build() { return new Location(this); } } @Override public int hashCode() { return new HashCodeBuilder() .append(id) .append(externalId) .append(mainName) .append(secondaryName) .append(lat) .append(lon) .append(route) .append(locality) .append(village) .append(subdistrict) .append(city) .append(province) .append(country) .append(created) .append(lastModified) .toHashCode(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Location that = (Location) o; return new EqualsBuilder() .append(id, that.id) .append(id, that.id) .append(externalId, that.externalId) .append(mainName, that.mainName) .append(secondaryName, that.secondaryName) .append(lat, that.lat) .append(lon, that.lon) .append(route, that.route) .append(locality, that.locality) .append(village, that.village) .append(subdistrict, that.subdistrict) .append(city, that.city) .append(province, that.province) .append(country, that.country) .append(created, that.created) .append(lastModified, that.lastModified) .isEquals(); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE) .append("id", id) .append("id", id) .append("externalId", externalId) .append("mainName", mainName) .append("secondaryName", secondaryName) .append("lat", lat) .append("lon", lon) .append("route", route) .append("locality", locality) .append("village", village) .append("subdistrict", subdistrict) .append("city", city) .append("province", province) .append("country", country) .append("created", created) .append("lastModified", lastModified) .toString(); } }
24.534591
68
0.556139
c4a63ef685eadc60c3462ad7a6e54272fe527b64
398
package org.modelio.module.attacktreedesigner.api; import com.modeliosoft.modelio.javadesigner.annotations.objid; import org.modelio.api.module.IPeerModule; @objid ("bbd2491a-c005-46f1-80e2-5370d1fd7230") public interface IAttackTreeDesignerPeerModule extends IPeerModule { @objid ("6e21714d-90ef-4676-87cb-baa9888b56f7") public static final String MODULE_NAME = "AttackTreeDesigner"; }
33.166667
68
0.811558
02553c68e3b7f5b3800e0424aba1137dd9955e56
465
package accumulator.opaque; import accumulator.AccumulatorFactory; import org.apache.commons.collections4.Bag; import accumulator.SingleAccumulator; import org.rookit.utils.collection.BagUtils; import java.util.Optional; public interface ModeAccumulator<T> extends SingleAccumulator<ModeAccumulator<T>, T, AccumulatorFactory> { @Override default Optional<T> get() { return BagUtils.getHighestCount(getValues()); } Bag<T> getValues(); }
24.473684
106
0.769892
5541237f0f3e95598589e81f8ce1795f4ec34944
825
package com.amaze.filemanager.ui.views; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageButton; /** * @author Emmanuel * on 8/5/2017, at 13:39. */ public class ThemedImageButton extends ThemedImageView { public ThemedImageButton(Context context) { super(context); } public ThemedImageButton(Context context, AttributeSet attrs) { super(context, attrs); } public ThemedImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setFocusable(true); } @Override protected boolean onSetAlpha(int alpha) { return false; } @Override public CharSequence getAccessibilityClassName() { return ImageButton.class.getName(); } }
21.710526
85
0.683636
14686ad6fbf6788638bf2e2071c7e63d9889a26f
41
public interface Iface { Iface foo(); }
13.666667
24
0.682927
43e46fc39024d5d4b1c5acb784bddcb5b6fb6d17
575
package com.github.geekcloud.gateway.web; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @ClassName: GeekcloudGatewayWebApplication * @author: jeffrey * @date: 2020年05月26日 * @Description: TODO */ @SpringBootApplication @EnableDiscoveryClient public class GeekcloudGatewayWebApplication { public static void main(String[] args) { SpringApplication.run(GeekcloudGatewayWebApplication.class, args); } }
28.75
74
0.801739
a7eafbdc407fa6fa2b5b634855bb2b49d1a4a1e4
6,606
/* * Copyright 2019 Steinar Bang * * 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 no.priv.bang.osgiservice.users; import java.util.List; import java.util.Map; /** * This is an OSGi service that encapsulates user management * * Implementations of this interface will typically be used to * manage users, groups and roles for a software application. * * The structure of this interface is based on what's convenient * for the implementation of a REST API: JSON-friendly beans are * both arguments and return values, and update operations returns * updated state in a form that is convenient for e.g. updating * a redux model in a react/redux frontend. */ public interface UserManagementService { /** * Get a User from a username. * * Typically called after login to get a {@link User} object * for the logged in user * * @param username the username for the user that is to be retrieved * @return a {@link User} object for the user with the username */ User getUser(String username); /** * Typically called after login to get the list of {@link Role}s for * the logged in user * * @param username the username for the user whose roles should be retrieved * @return a list of {@link Role} objects */ List<Role> getRolesForUser(String username); /** * Typically called after login to get the list of all {@link Permission}s for * the logged in user. * * @param username the username for the user whose permissions should be retrieved * @return a list of {@link Permission} objects */ List<Permission> getPermissionsForUser(String username); /** * Get all users in the database. * * @return a list of {@link User} objects */ List<User> getUsers(); /** * Update a user in the database. * What can be updated, are the username, the email address * and the first- and lastnames of the user. * * @param user The user object to update. The id property of this object defines what user to update * @return The list of users in the database after the update of a user */ List<User> modifyUser(User user); /** * Change the passwords of a user in the database * * @param userAndPasswords an object containing a {@link User} used to identify the user the passwords should be changed for and two copies of the new password * @return The list of users in the database */ List<User> updatePassword(UserAndPasswords userAndPasswords); /** * Create a new user in the database. * * @param newUserWithPasswords an object containing a {@link User} object and two copies of the new password * @return The list of users in the database including the newly created user */ List<User> addUser(UserAndPasswords newUserWithPasswords); /** * Return the list of roles defined in the database. * * @return a list of {@link Role} beans */ List<Role> getRoles(); /** * Modify a {@link Role} in the database. * * @param role the {@link Role} to modify in the database * @return the roles in the database containing the modified role */ List<Role> modifyRole(Role role); /** * Add a {@link Role} to the database. * * @param newRole the {@link Role} to add * @return the roles in the database, including the new role */ List<Role> addRole(Role newRole); /** * Return the list of roles defined in the database. * * @return a {@link Permission} objekts */ List<Permission> getPermissions(); /** * Modify a {@link Permission} in the database. * * @param permission the {@link Permission} object to modify in the database * @return the permissions in the database containing the modified permission */ List<Permission> modifyPermission(Permission permission); /** * Add a {@link Permission} to the database. * * @param newPermission the {@link Permission} to add to the database * @return the permissions in the database including the new permission */ List<Permission> addPermission(Permission newPermission); /** * Get all {@link User#getUsername()} to {@link Role} mappings in the database. * * @return a {@link Map} from usernames to lists of roles */ Map<String, List<Role>> getUserRoles(); /** * Add one or more roles to a user. * * @param userroles contains the {@link User} to add {@link Role}s and the roles to add * @return the all username to role mappings with the new roles in place */ Map<String, List<Role>> addUserRoles(UserRoles userroles); /** * Remove one or more roles from a user * * @param userroles the {@link User} to remove {@link Role}s from and the roles to remove * @return the all username to role mappings with the removed roles gone */ Map<String, List<Role>> removeUserRoles(UserRoles userroles); /** * Get all role to permission mappings in the database. * * @return a map from rolenames to list of permissions */ Map<String, List<Permission>> getRolesPermissions(); /** * Add one or more permissions to a role. * * @param rolepermissions the {@link Role} to add permissions to and the list of {@link Permission}s to add to the role * @return all rolename to permission mappings in the database, including the permissions added in this operation */ Map<String, List<Permission>> addRolePermissions(RolePermissions rolepermissions); /** * Remove one or more permissions from a role. * * @param rolepermissions the {@link Role} to remove permissions from and the list of {@link Permission}s to remove from the role * @return all rolename to permission mappings in the database, not including the permissions removed in this operation */ Map<String, List<Permission>> removeRolePermissions(RolePermissions rolepermissions); }
34.768421
163
0.672116
aec9d08db1e0ebbee4e9c86bf21f894427a02753
448
package standings; import java.util.Vector; public class Game { private int numberOfPlayers; private Vector<Result> results; public Game(int players) { numberOfPlayers = players; results = new Vector<Result>(); } public int getNumberOfPlayers() { return numberOfPlayers; } public void setNumberOfPlayers(int players) { numberOfPlayers = players; } public void addResult(Result newResult) { results.add(newResult); } }
17.230769
46
0.729911
69ff4b0fa9e4baa0d2e70cd69a57d7579fe5437c
958
package io.ciera.runtime.summit.types; import java.util.Calendar; import io.ciera.runtime.summit.application.IRunContext; public class Date extends TimeStamp { private Calendar cal; public Date() { this(0L); } public Date(long timestamp) { super(timestamp); cal = Calendar.getInstance(); cal.setTimeInMillis(timestamp); } public int getYear() { return cal.get(Calendar.YEAR); } public int getMonth() { return cal.get(Calendar.MONTH) + 1; } public int getDay() { return cal.get(Calendar.DAY_OF_MONTH); } public int getHour() { return cal.get(Calendar.HOUR_OF_DAY); } public int getMinute() { return cal.get(Calendar.MINUTE); } public int getSecond() { return cal.get(Calendar.SECOND); } public static Date now(IRunContext runContext) { return new Date(runContext.time() / 1000L); } }
19.16
55
0.615866
7492861f00cca47a47df085e9d08016ee070f9fc
3,214
package algs.model.problems.eightpuzzle; import algs.model.searchtree.DepthTransition; import algs.model.searchtree.INode; import algs.model.searchtree.IScore; /** * Fair evaluation, subset of GoodEvaluator from Nilsson, p. 66. * * @author George Heineman * @version 2.0, 8/30/15 * @since 1.0 */ public class FairEvaluator implements IScore { /** Known goal state. */ static EightPuzzleNode goal = new EightPuzzleNode(new int[][]{ {1,2,3},{8,0,4},{7,6,5} }); /** index values [r][c] for proper locations, based on goal above. */ static int[][] diffs = new int[][] { {1, 1}, // who cares about the blank? But here for consistency {0, 0}, // location where 1 belongs [0][0] {0, 1}, {0, 2}, {1, 2}, {2, 2}, {2, 1}, {2, 0}, {1, 0} }; /** * Description of this measure. */ public String toString() { return "P(n) where P(n) is the sum of the Manhattan distances" + "\n" + "that each tile is from \"home.\""; } /** * @see algs.model.searchtree.IScore#score(INode) */ public void score(INode state) { state.score(eval(state)); } /** * h(n) = P(n), where P(n) is the sum of the distances (via Manhattan * metric) that each tile is from "home". * <p> * Compute f(n) = g(n) + h(n) where g(n) is the length of the path from the * start node n to the state. * * @see algs.model.searchtree.IScore#score(INode) * @param state game state to be evaluated * @return integer evaluation. */ public int eval(INode state) { EightPuzzleNode node = (EightPuzzleNode) state; // Each tile is between 0 and 4 moves away from its proper position. int Pn = 0; for (int r = 0; r <= EightPuzzleNode.MaxR; r++) { for (int c = 0; c <= EightPuzzleNode.MaxC; c++) { if (node.isEmpty(r,c)) { continue; } int digit = node.cell(r, c); Pn += Math.abs(diffs[digit][0] - r); Pn += Math.abs(diffs[digit][1] - c); } } // compute g(n) int gn = 0; DepthTransition t = (DepthTransition) state.storedData(); if (t != null) { gn = t.depth; } return gn + Pn; } /** * Return string representing the evaluation g(n) + P(n) where P(n) is * the sum of the distances (via Manhattan metric) that each tile is from "home". * * @see algs.model.searchtree.IScore#score(INode) * @param state game state to be evaluated. * @return human readable string representing evaluation of state. */ public String evalString(INode state) { EightPuzzleNode node = (EightPuzzleNode) state; // Each tile is between 0 and 4 moves away from its proper position. int Pn = 0; for (int r = 0; r <= EightPuzzleNode.MaxR; r++) { for (int c = 0; c <= EightPuzzleNode.MaxC; c++) { if (node.isEmpty(r,c)) { continue; } int digit = node.cell(r, c); Pn += Math.abs(diffs[digit][0] - r); Pn += Math.abs(diffs[digit][1] - c); } } // compute g(n) int gn = 0; String eval = ""; DepthTransition t = (DepthTransition) state.storedData(); if (t != null) { if (t.depth != 0) { // protect against zero depth gn = t.depth; eval = eval + gn + "+" + Pn + "=" + (gn+Pn); } } else { eval = eval + Pn; } return eval; } }
25.919355
83
0.599253
e3c0acac8b567f87c310dfd394ff56887d60ccf7
568
package eu.jrie.abacus.core.domain.formula.impl.text; import eu.jrie.abacus.core.domain.formula.impl.infra.FormulaImplTest; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.util.stream.Stream; class LengthTest extends FormulaImplTest { @TestFactory Stream<DynamicTest> shouldCalculateStringLength() { return testTextToNumber( new Length(), "should calculate length of ", new TestCase("abc", "3"), new TestCase("", "0") ); } }
28.4
69
0.65493
2fe3a1ff400729465dc1191377fef035a893e07e
863
package com.edus.apollo.funny.ui.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.edus.apollo.funny.R; /** * Created by Panda on 2015/9/20. */ public class CategoryFragment extends BaseFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.category_fragment_layout,container,false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } }
27.83871
103
0.755504
aca86179064d46544b15a0728b9073ceadf56ab0
2,028
/* Copyright (C) 2013-2019 TU Dortmund * This file is part of AutomataLib, http://www.automatalib.net/. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.automatalib.util.tries; import net.automatalib.words.Alphabet; public class SharedSuffixTrie<I> extends SuffixTrie<I> { private final Alphabet<I> alphabet; public SharedSuffixTrie(Alphabet<I> alphabet) { super(new SharedSuffixTrieNode<>()); this.alphabet = alphabet; } public SharedSuffixTrie(Alphabet<I> alphabet, boolean graphRepresentable) { super(graphRepresentable, new SharedSuffixTrieNode<>()); this.alphabet = alphabet; } @Override @SuppressWarnings("unchecked") public SuffixTrieNode<I> add(I symbol, SuffixTrieNode<I> parent) { if (!(parent instanceof SharedSuffixTrieNode)) { throw new IllegalArgumentException("Invalid suffix trie node"); } int symbolIdx = alphabet.getSymbolIndex(symbol); SharedSuffixTrieNode<I> sparent = (SharedSuffixTrieNode<I>) parent; SharedSuffixTrieNode<I>[] children = sparent.children; if (children == null) { sparent.children = new SharedSuffixTrieNode[alphabet.size()]; children = sparent.children; } else if (children[symbolIdx] != null) { return children[symbolIdx]; } SharedSuffixTrieNode<I> child = new SharedSuffixTrieNode<>(symbol, sparent); children[symbolIdx] = child; return child; } }
35.578947
84
0.687377
718edd4d1e8e449fa54cdd92a93c271ec98650cb
54,420
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.printing; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.printing.PrintSystemObject; import system.printing.PrintSystemDesiredAccess; import system.printing.PrintServerIndexedProperty; import system.printing.PrintQueue; import system.printing.indexedproperties.PrintPropertyDictionary; import system.printing.PrintQueueAttributes; import system.printing.PrintQueueStringProperty; import system.printing.PrintQueueCollection; import system.printing.EnumeratedPrintQueueTypes; import system.printing.PrintQueueIndexedProperty; import system.printing.PrintServerEventLoggingTypes; import system.threading.ThreadPriority; /** * The base .NET class managing System.Printing.PrintServer, System.Printing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. Extends {@link NetObject}. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Printing.PrintServer" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Printing.PrintServer</a> */ public class PrintServer extends PrintSystemObject { /** * Fully assembly qualified name: System.Printing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 */ public static final String assemblyFullName = "System.Printing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; /** * Assembly name: System.Printing */ public static final String assemblyShortName = "System.Printing"; /** * Qualified class name: System.Printing.PrintServer */ public static final String className = "System.Printing.PrintServer"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link PrintServer}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link PrintServer} instance * @throws java.lang.Throwable in case of error during cast operation */ public static PrintServer cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new PrintServer(from.getJCOInstance()); } // Constructors section public PrintServer() throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(PrintSystemDesiredAccess desiredAccess) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.ArrayTypeMismatchException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(desiredAccess == null ? null : desiredAccess.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(java.lang.String path) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(path)); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(java.lang.String path, PrintServerIndexedProperty[] propertiesFilter) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.ArrayTypeMismatchException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(path, toObjectFromArray(propertiesFilter))); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(java.lang.String path, PrintServerIndexedProperty[] propertiesFilter, PrintSystemDesiredAccess desiredAccess) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.ArrayTypeMismatchException, system.IndexOutOfRangeException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(path, toObjectFromArray(propertiesFilter), desiredAccess == null ? null : desiredAccess.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(java.lang.String path, PrintSystemDesiredAccess desiredAccess) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.ArrayTypeMismatchException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(path, desiredAccess == null ? null : desiredAccess.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(java.lang.String path, java.lang.String[] propertiesFilter) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(path, propertiesFilter)); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServer(java.lang.String path, java.lang.String[] propertiesFilter, PrintSystemDesiredAccess desiredAccess) throws Throwable, system.NotSupportedException, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.FormatException, system.InvalidOperationException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.ArrayTypeMismatchException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.ObjectDisposedException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(path, propertiesFilter, desiredAccess == null ? null : desiredAccess.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Methods section public static boolean DeletePrintQueue(PrintQueue printQueue) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.PlatformNotSupportedException, system.OutOfMemoryException, system.ArrayTypeMismatchException, system.ObjectDisposedException { if (classType == null) throw new UnsupportedOperationException("classType is null."); try { return (boolean)classType.Invoke("DeletePrintQueue", printQueue == null ? null : printQueue.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public static boolean DeletePrintQueue(java.lang.String printQueueName) throws Throwable, system.PlatformNotSupportedException, system.OutOfMemoryException, system.ArgumentException, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.ArrayTypeMismatchException, system.InvalidOperationException, system.ObjectDisposedException { if (classType == null) throw new UnsupportedOperationException("classType is null."); try { return (boolean)classType.Invoke("DeletePrintQueue", printQueueName); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue GetPrintQueue(java.lang.String printQueueName) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.ObjectDisposedException, system.printing.PrintingNotSupportedException, system.printing.PrintQueueException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueue = (JCObject)classInstance.Invoke("GetPrintQueue", printQueueName); return new PrintQueue(objGetPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue GetPrintQueue(java.lang.String printQueueName, java.lang.String[] propertiesFilter) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.ObjectDisposedException, system.printing.PrintingNotSupportedException, system.printing.PrintQueueException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueue = (JCObject)classInstance.Invoke("GetPrintQueue", printQueueName, propertiesFilter); return new PrintQueue(objGetPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue GetPrintQueue(java.lang.String dupParam0, JCORefOut dupParam1) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.ObjectDisposedException, system.printing.PrintingNotSupportedException, system.printing.PrintQueueException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueue = (JCObject)classInstance.Invoke("GetPrintQueue", dupParam0, dupParam1.getJCRefOut()); return new PrintQueue(objGetPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String printQueueName, java.lang.String driverName, java.lang.String[] portNames, java.lang.String printProcessorName, PrintPropertyDictionary initialParameters) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.AccessViolationException, system.ObjectDisposedException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ArrayTypeMismatchException, system.printing.PrintQueueException, system.printing.PrintCommitAttributesException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", printQueueName, driverName, portNames, printProcessorName, initialParameters == null ? null : initialParameters.getJCOInstance()); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String dupParam0, java.lang.String dupParam1, JCORefOut dupParam2, java.lang.String dupParam3, PrintPropertyDictionary dupParam4) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.AccessViolationException, system.ObjectDisposedException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ArrayTypeMismatchException, system.printing.PrintQueueException, system.printing.PrintCommitAttributesException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", dupParam0, dupParam1, dupParam2.getJCRefOut(), dupParam3, dupParam4 == null ? null : dupParam4.getJCOInstance()); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String printQueueName, java.lang.String driverName, java.lang.String[] portNames, java.lang.String printProcessorName, PrintQueueAttributes printQueueAttributes) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.PlatformNotSupportedException, system.AccessViolationException, system.ObjectDisposedException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.printing.PrintQueueException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", printQueueName, driverName, portNames, printProcessorName, printQueueAttributes == null ? null : printQueueAttributes.getJCOInstance()); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String dupParam0, java.lang.String dupParam1, JCORefOut dupParam2, java.lang.String dupParam3, PrintQueueAttributes dupParam4) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.PlatformNotSupportedException, system.AccessViolationException, system.ObjectDisposedException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.printing.PrintQueueException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", dupParam0, dupParam1, dupParam2.getJCRefOut(), dupParam3, dupParam4 == null ? null : dupParam4.getJCOInstance()); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String printQueueName, java.lang.String driverName, java.lang.String[] portNames, java.lang.String printProcessorName, PrintQueueAttributes printQueueAttributes, PrintQueueStringProperty printQueueProperty, int printQueuePriority, int printQueueDefaultPriority) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.OutOfMemoryException, system.PlatformNotSupportedException, system.AccessViolationException, system.globalization.CultureNotFoundException, system.printing.PrintQueueException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", printQueueName, driverName, portNames, printProcessorName, printQueueAttributes == null ? null : printQueueAttributes.getJCOInstance(), printQueueProperty == null ? null : printQueueProperty.getJCOInstance(), printQueuePriority, printQueueDefaultPriority); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String dupParam0, java.lang.String dupParam1, JCORefOut dupParam2, java.lang.String dupParam3, PrintQueueAttributes dupParam4, PrintQueueStringProperty dupParam5, int dupParam6, int dupParam7) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.OutOfMemoryException, system.PlatformNotSupportedException, system.AccessViolationException, system.globalization.CultureNotFoundException, system.printing.PrintQueueException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", dupParam0, dupParam1, dupParam2.getJCRefOut(), dupParam3, dupParam4 == null ? null : dupParam4.getJCOInstance(), dupParam5 == null ? null : dupParam5.getJCOInstance(), dupParam6, dupParam7); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String printQueueName, java.lang.String driverName, java.lang.String[] portNames, java.lang.String printProcessorName, PrintQueueAttributes printQueueAttributes, java.lang.String printQueueShareName, java.lang.String printQueueComment, java.lang.String printQueueLocation, java.lang.String printQueueSeparatorFile, int printQueuePriority, int printQueueDefaultPriority) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.PlatformNotSupportedException, system.AccessViolationException, system.ObjectDisposedException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.printing.PrintQueueException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", printQueueName, driverName, portNames, printProcessorName, printQueueAttributes == null ? null : printQueueAttributes.getJCOInstance(), printQueueShareName, printQueueComment, printQueueLocation, printQueueSeparatorFile, printQueuePriority, printQueueDefaultPriority); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueue InstallPrintQueue(java.lang.String dupParam0, java.lang.String dupParam1, JCORefOut dupParam2, java.lang.String dupParam3, PrintQueueAttributes dupParam4, java.lang.String dupParam5, java.lang.String dupParam6, java.lang.String dupParam7, java.lang.String dupParam8, int dupParam9, int dupParam10) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.PlatformNotSupportedException, system.AccessViolationException, system.ObjectDisposedException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.printing.PrintQueueException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objInstallPrintQueue = (JCObject)classInstance.Invoke("InstallPrintQueue", dupParam0, dupParam1, dupParam2.getJCRefOut(), dupParam3, dupParam4 == null ? null : dupParam4.getJCOInstance(), dupParam5, dupParam6, dupParam7, dupParam8, dupParam9, dupParam10); return new PrintQueue(objInstallPrintQueue); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues"); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues(EnumeratedPrintQueueTypes[] enumerationFlag) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues", (Object)toObjectFromArray(enumerationFlag)); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues(PrintQueueIndexedProperty[] propertiesFilter) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.FormatException, system.ArrayTypeMismatchException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues", (Object)toObjectFromArray(propertiesFilter)); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues(PrintQueueIndexedProperty[] propertiesFilter, EnumeratedPrintQueueTypes[] enumerationFlag) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.FormatException, system.ArrayTypeMismatchException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues", toObjectFromArray(propertiesFilter), toObjectFromArray(enumerationFlag)); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues(java.lang.String[] propertiesFilter) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues", (Object)propertiesFilter); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues(JCORefOut dupParam0) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues", (Object)dupParam0.getJCRefOut()); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues(java.lang.String[] propertiesFilter, EnumeratedPrintQueueTypes[] enumerationFlag) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues", propertiesFilter, toObjectFromArray(enumerationFlag)); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintQueueCollection GetPrintQueues(JCORefOut dupParam0, EnumeratedPrintQueueTypes[] dupParam1) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.OutOfMemoryException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objGetPrintQueues = (JCObject)classInstance.Invoke("GetPrintQueues", dupParam0.getJCRefOut(), toObjectFromArray(dupParam1)); return new PrintQueueCollection(objGetPrintQueues); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Commit() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.OutOfMemoryException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Commit"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Refresh() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.OutOfMemoryException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Refresh"); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section public boolean getBeepEnabled() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Get("BeepEnabled"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setBeepEnabled(boolean BeepEnabled) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("BeepEnabled", BeepEnabled); } catch (JCNativeException jcne) { throw translateException(jcne); } } public boolean getNetPopup() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Get("NetPopup"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setNetPopup(boolean NetPopup) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("NetPopup", NetPopup); } catch (JCNativeException jcne) { throw translateException(jcne); } } public boolean getRestartJobOnPoolEnabled() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Get("RestartJobOnPoolEnabled"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setRestartJobOnPoolEnabled(boolean RestartJobOnPoolEnabled) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("RestartJobOnPoolEnabled", RestartJobOnPoolEnabled); } catch (JCNativeException jcne) { throw translateException(jcne); } } public byte getSubSystemVersion() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (byte)classInstance.Get("SubSystemVersion"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int getMajorVersion() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("MajorVersion"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setMajorVersion(int MajorVersion) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.OutOfMemoryException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("MajorVersion", MajorVersion); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int getMinorVersion() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("MinorVersion"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setMinorVersion(int MinorVersion) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.OutOfMemoryException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("MinorVersion", MinorVersion); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int getRestartJobOnPoolTimeout() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("RestartJobOnPoolTimeout"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setRestartJobOnPoolTimeout(int RestartJobOnPoolTimeout) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("RestartJobOnPoolTimeout", RestartJobOnPoolTimeout); } catch (JCNativeException jcne) { throw translateException(jcne); } } public PrintServerEventLoggingTypes getEventLog() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("EventLog"); return new PrintServerEventLoggingTypes(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setEventLog(PrintServerEventLoggingTypes EventLog) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("EventLog", EventLog == null ? null : EventLog.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public java.lang.String getDefaultSpoolDirectory() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (java.lang.String)classInstance.Get("DefaultSpoolDirectory"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setDefaultSpoolDirectory(java.lang.String DefaultSpoolDirectory) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.PlatformNotSupportedException, system.IndexOutOfRangeException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("DefaultSpoolDirectory", DefaultSpoolDirectory); } catch (JCNativeException jcne) { throw translateException(jcne); } } public ThreadPriority getDefaultPortThreadPriority() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("DefaultPortThreadPriority"); return new ThreadPriority(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setDefaultPortThreadPriority(ThreadPriority DefaultPortThreadPriority) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("DefaultPortThreadPriority", DefaultPortThreadPriority == null ? null : DefaultPortThreadPriority.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public ThreadPriority getDefaultSchedulerPriority() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("DefaultSchedulerPriority"); return new ThreadPriority(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setDefaultSchedulerPriority(ThreadPriority DefaultSchedulerPriority) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("DefaultSchedulerPriority", DefaultSchedulerPriority == null ? null : DefaultSchedulerPriority.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public ThreadPriority getPortThreadPriority() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("PortThreadPriority"); return new ThreadPriority(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setPortThreadPriority(ThreadPriority PortThreadPriority) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("PortThreadPriority", PortThreadPriority == null ? null : PortThreadPriority.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public ThreadPriority getSchedulerPriority() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("SchedulerPriority"); return new ThreadPriority(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setSchedulerPriority(ThreadPriority SchedulerPriority) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("SchedulerPriority", SchedulerPriority == null ? null : SchedulerPriority.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section }
72.656876
951
0.764278
1bd571ca96440984f60213fb623c27d1315fb2e9
6,182
//******************************************************************* /*! \file ORB_RemoteBT.java \author Thomas Breuer \date 21.02.2020 \brief */ //******************************************************************* package com.ORB; //******************************************************************* import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Set; import java.util.UUID; //******************************************************************* class ORB_RemoteBT extends ORB_Remote { //--------------------------------------------------------------- private BluetoothSocket BT_Socket; private OutputStream BT_OutStream; private InputStream BT_InStream; private boolean isConnected = false; //--------------------------------------------------------------- private ByteBuffer bufferIN; private ByteBuffer bufferOUT; //--------------------------------------------------------------- private boolean ready = false; private int pos = 0; private byte temp = 0; private static final String TAG = "ORB_BT"; private static final UUID MY_UUID = UUID.fromString( "00001101-0000-1000-8000-00805F9B34FB" ); //--------------------------------------------------------------- public ORB_RemoteBT( ORB_Manager orb_manager ) { super( orb_manager ); bufferIN = ByteBuffer.allocate( 256 ); bufferOUT = ByteBuffer.allocate( 256 ); isConnected = false; } //--------------------------------------------------------------- public BluetoothDevice open( String addr ) { close(); BluetoothDevice BT_Device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice( addr ); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); try { synchronized( this ) { BT_Socket = BT_Device.createRfcommSocketToServiceRecord( MY_UUID ); BT_Socket.connect(); BT_OutStream = BT_Socket.getOutputStream(); BT_InStream = BT_Socket.getInputStream(); isConnected = true; } } catch( IOException e ) { isConnected = false; } return (BT_Device); } //--------------------------------------------------------------- public void close() { isConnected = false; try { if( BT_Socket != null ) { if( BT_InStream != null ) { BT_InStream.close(); } if( BT_OutStream != null ) { BT_OutStream.close(); } BT_Socket.close(); BT_Socket = null; } } catch(IOException e) { Log.e( TAG, "BT close error" + e.toString() ); } } //--------------------------------------------------------------- public Set<BluetoothDevice> getPairedDevices() { BluetoothAdapter BT_Adapter; Set<BluetoothDevice> BT_PairedDevices; BT_Adapter = BluetoothAdapter.getDefaultAdapter(); BT_PairedDevices = BT_Adapter.getBondedDevices(); return (BT_PairedDevices); } //--------------------------------------------------------------- public boolean isConnected() { return (isConnected); } //--------------------------------------------------------------- private void updateOut() { if( !isConnected ) { return; } short crc; int size; size = orb_manager.fill( bufferOUT ); byte data[] = new byte[1024]; short len = 0; short idx = 0; data[len++] = (byte) (0x20 | ((bufferOUT.get( idx ) >> 4) & 0x0F)); data[len++] = (byte) (0x30 | ((bufferOUT.get( idx++ )) & 0x0F)); while( idx < size - 1 ) { data[len++] = (byte) (0x40 | ((bufferOUT.get( idx ) >> 4) & 0x0F)); data[len++] = (byte) (0x50 | ((bufferOUT.get( idx++ )) & 0x0F)); } data[len++] = (byte) (0x80 | ((bufferOUT.get( idx ) >> 4) & 0x0F)); data[len++] = (byte) (0x90 | ((bufferOUT.get( idx++ )) & 0x0F)); try { BT_OutStream.write( data, 0, len ); BT_OutStream.flush(); } catch( IOException e ) { } } //--------------------------------------------------------------- private boolean updateIn() { if( !isConnected ) { return (false); } int r; try { while( !ready && BT_InStream.available() > 0 && (r = BT_InStream.read()) >= 0 ) { if( (r & 0xF0) == 0x20 || pos > 255 ) { pos = 0; ready = false; } if( (r & 0xF0) == 0x90 ) { ready = true; } if( (r & 0x10) == 0x00 ) { temp = (byte) ((r << 4) & 0xf0); } else { temp |= (r & 0x0f); bufferIN.put( pos, temp ); pos++; } } } catch( IOException e ) { Log.e( TAG, "error read " ); } if( ready ) { orb_manager.process( bufferIN ); ready = false; return (true); } return (false); } //--------------------------------------------------------------- public boolean update() { boolean ret = false; synchronized( this ) { if( updateIn() ) { ret = true; } updateOut(); } return (ret); } } // end of class
26.878261
98
0.397606
fdc94bc8caaa94caa9abbf8b0fbb79f7df8c2ad3
2,216
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ververica.flink.table.gateway.rest.handler; import com.ververica.flink.table.gateway.rest.message.GetInfoResponseBody; import org.apache.flink.api.common.time.Time; import org.apache.flink.runtime.rest.handler.HandlerRequest; import org.apache.flink.runtime.rest.handler.RestHandlerException; import org.apache.flink.runtime.rest.messages.EmptyMessageParameters; import org.apache.flink.runtime.rest.messages.EmptyRequestBody; import org.apache.flink.runtime.rest.messages.MessageHeaders; import org.apache.flink.runtime.util.EnvironmentInformation; import javax.annotation.Nonnull; import java.util.Map; import java.util.concurrent.CompletableFuture; /** * Request handler for getting info. */ public class GetInfoHandler extends AbstractRestHandler<EmptyRequestBody, GetInfoResponseBody, EmptyMessageParameters> { public GetInfoHandler( Time timeout, Map<String, String> responseHeaders, MessageHeaders<EmptyRequestBody, GetInfoResponseBody, EmptyMessageParameters> messageHeaders) { super(timeout, responseHeaders, messageHeaders); } @Override protected CompletableFuture<GetInfoResponseBody> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody, EmptyMessageParameters> request) throws RestHandlerException { String version = EnvironmentInformation.getVersion(); return CompletableFuture.completedFuture(new GetInfoResponseBody("Apache Flink", version)); } }
38.206897
106
0.802347
dd9d95d79a6f7ceba4dd0cc0589c132d23eefee2
16,495
/* * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) 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. * * Contributors: * Thomas Roger <troger@nuxeo.com> * Florent Guillaume */ package org.nuxeo.ecm.quota; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelIterator; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.Filter; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.core.api.IterableQueryResult; import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; import org.nuxeo.ecm.core.work.api.Work; import org.nuxeo.ecm.core.work.api.Work.State; import org.nuxeo.ecm.core.work.api.WorkManager; import org.nuxeo.ecm.platform.userworkspace.api.UserWorkspaceService; import org.nuxeo.ecm.quota.size.QuotaAware; import org.nuxeo.ecm.quota.size.QuotaAwareDocumentFactory; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.model.ComponentContext; import org.nuxeo.runtime.model.ComponentInstance; import org.nuxeo.runtime.model.DefaultComponent; /** * Default implementation of {@link org.nuxeo.ecm.quota.QuotaStatsService}. * * @since 5.5 */ public class QuotaStatsServiceImpl extends DefaultComponent implements QuotaStatsService { private static final Log log = LogFactory.getLog(QuotaStatsServiceImpl.class); public static final String STATUS_INITIAL_COMPUTATION_QUEUED = "status.quota.initialComputationQueued"; public static final String STATUS_INITIAL_COMPUTATION_PENDING = "status.quota.initialComputationInProgress"; public static final String STATUS_INITIAL_COMPUTATION_COMPLETED = "status.quota.initialComputationCompleted"; // TODO configurable through an ep? public static final int DEFAULT_BATCH_SIZE = 1000; public static final String QUOTA_STATS_UPDATERS_EP = "quotaStatsUpdaters"; protected QuotaStatsUpdaterRegistry quotaStatsUpdaterRegistry; @Override public void activate(ComponentContext context) { quotaStatsUpdaterRegistry = new QuotaStatsUpdaterRegistry(); } @Override public List<QuotaStatsUpdater> getQuotaStatsUpdaters() { return quotaStatsUpdaterRegistry.getQuotaStatsUpdaters(); } public QuotaStatsUpdater getQuotaStatsUpdaters(String updaterName) { return quotaStatsUpdaterRegistry.getQuotaStatsUpdater(updaterName); } @Override public void updateStatistics(final DocumentEventContext docCtx, final Event event) { // Open via session rather than repo name so that session.save and sync // is done automatically new UnrestrictedSessionRunner(docCtx.getCoreSession()) { @Override public void run() { List<QuotaStatsUpdater> quotaStatsUpdaters = quotaStatsUpdaterRegistry.getQuotaStatsUpdaters(); for (QuotaStatsUpdater updater : quotaStatsUpdaters) { if (log.isTraceEnabled()) { DocumentModel doc = docCtx.getSourceDocument(); log.trace("Calling updateStatistics of " + updater.getName() + " for " + event.getName() + " on " + doc.getId() + " (" + doc.getPathAsString() + ")"); } updater.updateStatistics(session, docCtx, event); } } }.runUnrestricted(); } @Override public void computeInitialStatistics(String updaterName, CoreSession session, QuotaStatsInitialWork currentWorker, String path) { QuotaStatsUpdater updater = quotaStatsUpdaterRegistry.getQuotaStatsUpdater(updaterName); if (updater != null) { updater.computeInitialStatistics(session, currentWorker, path); } } @Override public void launchInitialStatisticsComputation(String updaterName, String repositoryName, String path) { WorkManager workManager = Framework.getService(WorkManager.class); if (workManager == null) { throw new RuntimeException("No WorkManager available"); } Work work = new QuotaStatsInitialWork(updaterName, repositoryName, path); workManager.schedule(work, true); } @Override public String getProgressStatus(String updaterName, String repositoryName) { WorkManager workManager = Framework.getService(WorkManager.class); Work work = new QuotaStatsInitialWork(updaterName, repositoryName, null); State state = workManager.getWorkState(work.getId()); if (state == null) { return null; } else if (state == State.SCHEDULED) { return STATUS_INITIAL_COMPUTATION_QUEUED; } else if (state == State.RUNNING) { return STATUS_INITIAL_COMPUTATION_PENDING; } else { // RUNNING return STATUS_INITIAL_COMPUTATION_COMPLETED; } } @Override public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (QUOTA_STATS_UPDATERS_EP.equals(extensionPoint)) { quotaStatsUpdaterRegistry.addContribution((QuotaStatsUpdaterDescriptor) contribution); } } @Override public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (QUOTA_STATS_UPDATERS_EP.equals(extensionPoint)) { quotaStatsUpdaterRegistry.removeContribution((QuotaStatsUpdaterDescriptor) contribution); } } @Override public long getQuotaFromParent(DocumentModel doc, CoreSession session) { List<DocumentModel> parents = getParentsInReverseOrder(doc, session); // if a user workspace, only interested in the qouta on its direct // parent if (parents.size() > 0 && "UserWorkspacesRoot".equals(parents.get(0).getType())) { QuotaAware qa = parents.get(0).getAdapter(QuotaAware.class); return qa != null ? qa.getMaxQuota() : -1L; } for (DocumentModel documentModel : parents) { QuotaAware qa = documentModel.getAdapter(QuotaAware.class); if (qa == null) { continue; } if (qa.getMaxQuota() > 0) { return qa.getMaxQuota(); } } return -1; } @Override public void activateQuotaOnUserWorkspaces(final long maxQuota, CoreSession session) { final String userWorkspacesRootId = getUserWorkspaceRootId(session.getRootDocument(), session); new UnrestrictedSessionRunner(session) { @Override public void run() { DocumentModel uwRoot = session.getDocument(new IdRef(userWorkspacesRootId)); QuotaAware qa = QuotaAwareDocumentFactory.make(uwRoot); qa.setMaxQuota(maxQuota); qa.save(); } }.runUnrestricted(); } @Override public long getQuotaSetOnUserWorkspaces(CoreSession session) { final String userWorkspacesRootId = getUserWorkspaceRootId(session.getRootDocument(), session); return new UnrestrictedSessionRunner(session) { long quota = -1; public long getsQuotaSetOnUserWorkspaces() { runUnrestricted(); return quota; } @Override public void run() { DocumentModel uwRoot = session.getDocument(new IdRef(userWorkspacesRootId)); QuotaAware qa = uwRoot.getAdapter(QuotaAware.class); if (qa == null) { quota = -1; } else { quota = qa.getMaxQuota(); } } }.getsQuotaSetOnUserWorkspaces(); } protected List<DocumentModel> getParentsInReverseOrder(DocumentModel doc, CoreSession session) { UnrestrictedParentsFetcher parentsFetcher = new UnrestrictedParentsFetcher(doc, session); return parentsFetcher.getParents(); } @Override public void launchSetMaxQuotaOnUserWorkspaces(final long maxSize, DocumentModel context, CoreSession session) { final String userWorkspacesId = getUserWorkspaceRootId(context, session); new UnrestrictedSessionRunner(session) { @Override public void run() { try (IterableQueryResult results = session.queryAndFetch(String.format( "Select ecm:uuid from Workspace where ecm:parentId = '%s' " + "AND ecm:isVersion = 0 AND ecm:isTrashed = 0", userWorkspacesId), "NXQL")) { int size = 0; List<String> allIds = new ArrayList<>(); for (Map<String, Serializable> map : results) { allIds.add((String) map.get("ecm:uuid")); } List<String> ids = new ArrayList<>(); WorkManager workManager = Framework.getService(WorkManager.class); for (String id : allIds) { ids.add(id); size++; if (size % DEFAULT_BATCH_SIZE == 0) { QuotaMaxSizeSetterWork work = new QuotaMaxSizeSetterWork(maxSize, ids, session.getRepositoryName()); workManager.schedule(work, true); ids = new ArrayList<>(); // don't reuse list } } if (ids.size() > 0) { QuotaMaxSizeSetterWork work = new QuotaMaxSizeSetterWork(maxSize, ids, session.getRepositoryName()); workManager.schedule(work, true); } } } }.runUnrestricted(); } public String getUserWorkspaceRootId(DocumentModel context, CoreSession session) { // get only the userworkspaces root under the first domain // it should be only one DocumentModel currentUserWorkspace = Framework.getService(UserWorkspaceService.class).getUserPersonalWorkspace( session.getPrincipal().getName(), context); return ((IdRef) currentUserWorkspace.getParentRef()).value; } @Override public boolean canSetMaxQuota(long maxQuota, DocumentModel doc, CoreSession session) { QuotaAware qa = null; DocumentModel parent = null; if ("UserWorkspacesRoot".equals(doc.getType())) { return true; } List<DocumentModel> parents = getParentsInReverseOrder(doc, session); if (!parents.isEmpty()) { if ("UserWorkspacesRoot".equals(parents.get(0).getType())) { // checks don't apply to personal user workspaces return true; } } for (DocumentModel p : parents) { qa = p.getAdapter(QuotaAware.class); if (qa == null) { // if no quota set on the parent, any value is valid continue; } if (qa.getMaxQuota() > 0) { parent = p; break; } } if (qa == null || qa.getMaxQuota() < 0) { return true; } long maxAllowedOnChildrenToSetQuota = qa.getMaxQuota() - maxQuota; if (maxAllowedOnChildrenToSetQuota < 0) { return false; } Long quotaOnChildren = new UnrestrictedQuotaOnChildrenCalculator(parent, maxAllowedOnChildrenToSetQuota, doc.getId(), session).quotaOnChildren(); if (quotaOnChildren > 0 && quotaOnChildren > maxAllowedOnChildrenToSetQuota) { return false; } return true; } class UnrestrictedQuotaOnChildrenCalculator extends UnrestrictedSessionRunner { DocumentModel parent; Long maxAllowedOnChildrenToSetQuota; long quotaOnChildren = -1; String currentDocIdToIgnore; protected UnrestrictedQuotaOnChildrenCalculator(DocumentModel parent, Long maxAllowedOnChildrenToSetQuota, String currentDocIdToIgnore, CoreSession session) { super(session); this.parent = parent; this.maxAllowedOnChildrenToSetQuota = maxAllowedOnChildrenToSetQuota; this.currentDocIdToIgnore = currentDocIdToIgnore; } @Override public void run() { quotaOnChildren = canSetMaxQuotaOnChildrenTree(maxAllowedOnChildrenToSetQuota, quotaOnChildren, parent, currentDocIdToIgnore, session); } public long quotaOnChildren() { runUnrestricted(); return quotaOnChildren; } protected Long canSetMaxQuotaOnChildrenTree(Long maxAllowedOnChildrenToSetQuota, Long quotaOnChildren, DocumentModel doc, String currentDocIdToIgnore, CoreSession session) { if (quotaOnChildren > 0 && quotaOnChildren > maxAllowedOnChildrenToSetQuota) { // quota can not be set, don't continue return quotaOnChildren; } DocumentModelIterator childrenIterator = null; childrenIterator = session.getChildrenIterator(doc.getRef(), null, null, new QuotaFilter()); while (childrenIterator.hasNext()) { DocumentModel child = childrenIterator.next(); QuotaAware qac = child.getAdapter(QuotaAware.class); if (qac == null) { continue; } if (qac.getMaxQuota() > 0 && !currentDocIdToIgnore.equals(child.getId())) { quotaOnChildren = (quotaOnChildren == -1L ? 0L : quotaOnChildren) + qac.getMaxQuota(); } if (quotaOnChildren > 0 && quotaOnChildren > maxAllowedOnChildrenToSetQuota) { return quotaOnChildren; } if (qac.getMaxQuota() == -1L) { // if there is no quota set at this level, go deeper quotaOnChildren = canSetMaxQuotaOnChildrenTree(maxAllowedOnChildrenToSetQuota, quotaOnChildren, child, currentDocIdToIgnore, session); } if (quotaOnChildren > 0 && quotaOnChildren > maxAllowedOnChildrenToSetQuota) { return quotaOnChildren; } } return quotaOnChildren; } } class UnrestrictedParentsFetcher extends UnrestrictedSessionRunner { DocumentModel doc; List<DocumentModel> parents; protected UnrestrictedParentsFetcher(DocumentModel doc, CoreSession session) { super(session); this.doc = doc; } @Override public void run() { parents = new ArrayList<>(); DocumentRef[] parentRefs = session.getParentDocumentRefs(doc.getRef()); for (DocumentRef documentRef : parentRefs) { parents.add(session.getDocument(documentRef)); } for (DocumentModel parent : parents) { parent.detach(true); } } public List<DocumentModel> getParents() { runUnrestricted(); return parents; } } class QuotaFilter implements Filter { @Override public boolean accept(DocumentModel doc) { if ("UserWorkspacesRoot".equals(doc.getType())) { return false; } return true; } } }
39.939467
119
0.623644
af9aa6f09f755bf8636d5a476beafcfa58a86d59
4,090
package hr.fer.zemris.java.hw06.shell.commands; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import hr.fer.zemris.java.hw06.shell.Environment; import hr.fer.zemris.java.hw06.shell.ShellCommand; import hr.fer.zemris.java.hw06.shell.ShellIOException; import hr.fer.zemris.java.hw06.shell.ShellStatus; /** * This Command prints to defines output all contents of a folder, * including the date when it was created, size of the file, * and also information like is it exectable, readable or writable. * @author Mateo * */ public class Ls implements ShellCommand { /** * Main command which is executed from the shell. Environment object is passed * so that current command can comunicate to the user through it. * Function prints out information about each file in a given folder, * but its not recursive,it doesnt give information about contents inside * folders that are inside given root folder. * @param env Environmen object that holds all input/outpt fn. for comunication with a user * @param arguments additional arguments that the command needs * @return returns ShellStatus enum, if there was no error ,it returns CONTINUE, or else TERMINATE */ @Override public ShellStatus executeCommand(Environment env, String arguments) { arguments= arguments.trim(); File direktorij = new File(arguments); File[] djeca = direktorij.listFiles(); if (djeca != null) { for (File file : djeca) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Path path = Paths.get(arguments); BasicFileAttributeView faView = Files.getFileAttributeView( path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS ); BasicFileAttributes attributes=null; try { attributes = faView.readAttributes(); } catch (IOException e) { e.printStackTrace(); } FileTime fileTime = attributes.creationTime(); String formattedDateTime = sdf.format(new Date(fileTime.toMillis())); print(file.isDirectory(), file.canRead(), file.canWrite(), file.canExecute(), file.length(), formattedDateTime, file.getName(), env); } } return ShellStatus.CONTINUE; } /** * Function prints out information about current file. * @param isDir if a file is directory ,prints 'd' ,otherwise '-' * @param readable if its readable prints 'r' ,otherwise '-' * @param writable if its writable prints 'w' , otherwise '-' * @param exec if its executable prints 'x',otherwise '-' * @param size size of the file * @param datetime date and time file was created * @param name name of the file * @param env object throgh which information is printed to defined output */ private void print(boolean isDir, boolean readable, boolean writable, boolean exec , long size, String datetime, String name, Environment env ) { try { env.write((isDir ? "d" : "-") + (readable ? "r" : "-") + (writable ? "w" : "-") + (exec ? "x" : "-") + " " + String.format("%10d",size) + " " + datetime + " " + name + "\n"); } catch (ShellIOException e) { e.printStackTrace(); } } /** * Funtion returns command name as a string. * @return command name */ @Override public String getCommandName() { return "ls"; } /** * Function returns a list which holds a description abouut current command. * @return returns a list which holds the description */ @Override public List<String> getCommandDescription() { List<String> desc = new LinkedList<>(); desc.add("Prints out information about each file in a given folder"); return desc; } }
27.449664
99
0.685819
65d3312a798d0841dacdf6bd0e89da3e3426f3b3
646
package com.alibaba.idst.nlu.request.v6.context.device; import com.alibaba.fastjson.annotation.JSONField; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * 请求上下文信息:地理位置信息:五级地理位置信息 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class NluContextLocationGeo { @JSONField(name = "level1") private String level1; @JSONField(name = "level2") private String level2; @JSONField(name = "level3") private String level3; @JSONField(name = "level4") private String level4; @JSONField(name = "level5") private String level5; }
19.575758
55
0.73065
b3ea9197b93db7842f566c11066fcc410322b938
930
package fr.anatom3000.gwwhit.mixin; import fr.anatom3000.gwwhit.util.OwoTransformer; import net.minecraft.client.gui.screen.ChatScreen; import net.minecraft.client.gui.widget.TextFieldWidget; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(ChatScreen.class) public class ChatScreenMixin { @Shadow protected TextFieldWidget chatField; @Inject(at = @At("RETURN"), method = "keyPressed(III)Z") private void modifyScreen(int keyCode, int scanCode, int modifiers, CallbackInfoReturnable<Boolean> info) { if (chatField != null && !chatField.getText().startsWith("/")) { chatField.setText( OwoTransformer.TRANSFORMER_SIMPLE.apply( chatField.getText() ) ); } } }
38.75
111
0.762366
6facec09b06ba70a2fad5ee630ecc81cb17eeb13
1,556
package test.projects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertLinesMatch; import org.junit.jupiter.api.Test; import test.base.ToolProviders; class MultiReleaseMultiModuleTests { @Test void build() throws Exception { var project = TestProject.of("MultiReleaseMultiModule"); assertEquals(0, project.build().waitFor()); var api = project.root().resolve(".bach/workspace/main/modules/api@99.jar"); assertLinesMatch( """ META-INF/ META-INF/MANIFEST.MF module-info.class module-info.java api/ api/Api.class api/Api.java """ .lines() .sorted(), ToolProviders.run("jar", "--list", "--file", api).lines().sorted()); var engine = project.root().resolve(".bach/workspace/main/modules/engine@99.jar"); assertLinesMatch( """ META-INF/ META-INF/MANIFEST.MF module-info.class module-info.java engine/ engine/Main.class engine/Main.java engine/Overlay.class engine/Overlay.java engine/OverlaySingleton.class engine/OverlaySingleton.java META-INF/versions/11/ META-INF/versions/11/engine/ META-INF/versions/11/engine/OverlaySingleton.class META-INF/versions/11/engine/OverlaySingleton.java """ .lines() .sorted(), ToolProviders.run("jar", "--list", "--file", engine).lines().sorted()); } }
28.290909
86
0.615681
0e43047459e9ff9f8764f7d29a694c9b518f699f
1,946
/* * Copyright 2017 Axway Software * * 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.axway.ats.action.rest; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.core.Form; import com.axway.ats.common.PublicAtsApi; /** * A representation of a REST form */ @PublicAtsApi public class RestForm { private Map<String, String> parameters; @PublicAtsApi public RestForm() { parameters = new HashMap<String, String>(); } /** * Add form parameters.<br><br> * * <b>Note:</b> For convenience this method returns the form itself, * so you can write code like new RESTForm().addParameter("username", "Will").addParameter("userpass", "Smith") * * @param parameterName the parameter name * @param parameterValue the parameter value * @return this form itself */ @PublicAtsApi public RestForm addParameter( String parameterName, String parameterValue ) { parameters.put(parameterName, parameterValue); return this; } Form getForm() { Form form = new Form(); for (Entry<String, String> pramEntry : parameters.entrySet()) { form.param(pramEntry.getKey(), pramEntry.getValue()); } return form; } }
28.202899
116
0.631038
f9381d8eb6a8789d61e1d372657b2d1dba17864e
7,143
package org.hzero.platform.domain.entity; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import io.choerodon.core.exception.CommonException; import javax.validation.constraints.NotBlank; import org.hzero.boot.platform.lov.annotation.LovValue; import com.fasterxml.jackson.annotation.JsonInclude; import io.choerodon.mybatis.annotation.ModifyAudit; import io.choerodon.mybatis.annotation.MultiLanguage; import io.choerodon.mybatis.annotation.MultiLanguageField; import io.choerodon.mybatis.annotation.VersionAudit; import io.choerodon.mybatis.domain.AuditDomain; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hzero.core.base.BaseConstants; import org.hzero.core.util.Regexs; import org.hzero.mybatis.common.query.Where; import org.hzero.mybatis.domian.Condition; import org.hzero.mybatis.util.Sqls; import org.hzero.platform.domain.repository.DashboardClauseRepository; import org.hzero.starter.keyencrypt.core.Encrypt; import org.springframework.util.Assert; import java.util.List; import java.util.Objects; /** * 工作台条目配置 * * @author jun.gao@hand-china.com 2019-01-27 19:10:25 * @author xiaoyu.zhao@hand-china.com */ @ApiModel("工作台条目配置") @VersionAudit @ModifyAudit @MultiLanguage @Table(name = "hpfm_dashboard_clause") @JsonInclude(JsonInclude.Include.NON_NULL) public class DashboardClause extends AuditDomain { public static final String FIELD_CLAUSE_ID = "clauseId"; public static final String FIELD_CLAUSE_CODE = "clauseCode"; public static final String FIELD_CLAUSE_NAME = "clauseName"; public static final String FIELD_DATA_TENANT_LEVEL = "dataTenantLevel"; public static final String FIELD_MENU_CODE = "menuCode"; public static final String FIELD_ROUTE = "route"; public static final String FIELD_STATS_EXPRESSION = "statsExpression"; public static final String FIELD_DOC_REMARK_EXPRESSION = "docRemarkExpression"; public static final String FIELD_ENABLED_FLAG = "enabledFlag"; public static final String FIELD_REMARK = "remark"; public static final String FIELD_TENANT_ID = "tenantId"; // // 业务方法(按public protected private顺序排列) // ------------------------------------------------------------------------------ /** * 校验数据是否已经存在(通过clauseCode校验唯一性) * * @param dashboardClauseRepository 卡片条目资源库 */ public void validate(DashboardClauseRepository dashboardClauseRepository) { int count = dashboardClauseRepository.selectCountByCondition(Condition.builder(DashboardClause.class) .andWhere(Sqls.custom() .andEqualTo(DashboardClause.FIELD_CLAUSE_CODE, clauseCode) .andEqualTo(DashboardClause.FIELD_TENANT_ID, tenantId) ).build()); if (count != 0) { // 数据重复 throw new CommonException(BaseConstants.ErrorCode.DATA_EXISTS); } } /** * 校验数据合法性 * * @param incomingTenantId 传入的租户id */ public void judgeClauseValidity(Long incomingTenantId) { Assert.isTrue(Objects.equals(this.tenantId, incomingTenantId), BaseConstants.ErrorCode.DATA_INVALID); } // // 数据库字段 // ------------------------------------------------------------------------------ @ApiModelProperty("表ID,主键,供其他表做外键") @Id @GeneratedValue @Where @Encrypt private Long clauseId; @ApiModelProperty(value = "条目代码") @NotBlank @Where @Pattern(regexp = Regexs.CODE) private String clauseCode; @ApiModelProperty(value = "条目名称") @NotBlank @MultiLanguageField private String clauseName; @ApiModelProperty(value = "数据租户级别HPFM.DATA_TENANT_LEVEL(SITE/平台级|TENANT/租户级)") @NotBlank @LovValue(value = "HPFM.DATA_TENANT_LEVEL",meaningField = "dataTenantLevelMeaning") private String dataTenantLevel; @ApiModelProperty(value = "跳转至功能") private String menuCode; @ApiModelProperty(value = "路由") private String route; @ApiModelProperty(value = "数据匹配表达式") @NotBlank private String statsExpression; @ApiModelProperty(value = "单据标题/备注计算表达式") private String docRemarkExpression; @ApiModelProperty(value = "启用标识") @NotNull private Integer enabledFlag; @ApiModelProperty(value = "备注说明") private String remark; @NotNull @ApiModelProperty("租户ID hpfm_tenant.tenant_id") @MultiLanguageField private Long tenantId; // // 非数据库字段 // ------------------------------------------------------------------------------ @Transient private String dataTenantLevelMeaning; @Transient private List<DashboardCardClause> dashboardCardClauseList; // // getter/setter // ------------------------------------------------------------------------------ /** * @return 表ID,主键,供其他表做外键 */ public Long getClauseId() { return clauseId; } public void setClauseId(Long clauseId) { this.clauseId = clauseId; } /** * @return 条目代码 */ public String getClauseCode() { return clauseCode; } public void setClauseCode(String clauseCode) { this.clauseCode = clauseCode; } /** * @return 条目名称 */ public String getClauseName() { return clauseName; } public void setClauseName(String clauseName) { this.clauseName = clauseName; } /** * @return 数据租户级别HPFM.DATA_TENANT_LEVEL(SITE/平台级|TENANT/租户级) */ public String getDataTenantLevel() { return dataTenantLevel; } public void setDataTenantLevel(String dataTenantLevel) { this.dataTenantLevel = dataTenantLevel; } /** * @return 跳转至功能 */ public String getMenuCode() { return menuCode; } public void setMenuCode(String menuCode) { this.menuCode = menuCode; } /** * @return 路由 */ public String getRoute() { return route; } public void setRoute(String route) { this.route = route; } /** * @return 数据匹配表达式 */ public String getStatsExpression() { return statsExpression; } public void setStatsExpression(String statsExpression) { this.statsExpression = statsExpression; } /** * @return 单据标题/备注计算表达式 */ public String getDocRemarkExpression() { return docRemarkExpression; } public void setDocRemarkExpression(String docRemarkExpression) { this.docRemarkExpression = docRemarkExpression; } /** * @return 启用标识 */ public Integer getEnabledFlag() { return enabledFlag; } public void setEnabledFlag(Integer enabledFlag) { this.enabledFlag = enabledFlag; } /** * @return 备注说明 */ public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getDataTenantLevelMeaning() { return dataTenantLevelMeaning; } public void setDataTenantLevelMeaning(String dataTenantLevelMeaning) { this.dataTenantLevelMeaning = dataTenantLevelMeaning; } public List<DashboardCardClause> getDashboardCardClauseList() { return dashboardCardClauseList; } public void setDashboardCardClauseList(List<DashboardCardClause> dashboardCardClauseList) { this.dashboardCardClauseList = dashboardCardClauseList; } public Long getTenantId() { return tenantId; } public void setTenantId(Long tenantId) { this.tenantId = tenantId; } }
26.261029
103
0.702926
9015bbef2c9765975f0ecb31dc7a1db533fd163e
150
package top.hzfq.flow.flowable.service.impl; /** * @author huzhifengqing@qq.com * @since 2022/2/27 17:05 */ public class FlowableServiceImpl { }
15
44
0.713333
46b7e80e6bf3205bb29526f31d75c83dba782f44
9,453
package org.ohdsi.webapi.estimation.comparativecohortanalysis.specification; import org.ohdsi.analysis.estimation.comparativecohortanalysis.design.CohortMethodAnalysis; import org.ohdsi.webapi.estimation.specification.AnalysisImpl; /** * CohortMethodAnalysisImpl */ public class CohortMethodAnalysisImpl extends AnalysisImpl implements CohortMethodAnalysis { private String targetType = null; private String comparatorType = null; private GetDbCohortMethodDataArgsImpl getDbCohortMethodDataArgs = null; private CreateStudyPopulationArgsImpl createStudyPopArgs = null; private Boolean createPs = false; private CreatePsArgsImpl createPsArgs = null; private Boolean trimByPs = false; private TrimByPsArgsImpl trimByPsArgs = null; private Boolean trimByPsToEquipoise = false; private TrimByPsToEquipoiseArgsImpl trimByPsToEquipoiseArgs = null; private Boolean matchOnPs = false; private MatchOnPsArgsImpl matchOnPsArgs = null; private Boolean matchOnPsAndCovariates = false; private MatchOnPsAndCovariatesArgsImpl matchOnPsAndCovariatesArgs = null; private Boolean stratifyByPs = false; private StratifyByPsArgsImpl stratifyByPsArgs = null; private Boolean stratifyByPsAndCovariates = false; private StratifyByPsAndCovariatesArgsImpl stratifyByPsAndCovariatesArgs = null; private Boolean fitOutcomeModel = false; private FitOutcomeModelArgsImpl fitOutcomeModelArgs = null; /** * * @param attrClass */ @Override public void setAttrClass(String attrClass) { super.setAttrClass("cmAnalysis"); } /** * If more than one target is provided for each drugComparatorOutcome, this field should be used to select the specific target to use in this analysis. * @return targetType **/ @Override public String getTargetType() { return targetType; } /** * * @param targetType */ public void setTargetType(String targetType) { this.targetType = targetType; } /** * If more than one comparator is provided for each drugComparatorOutcome, this field should be used to select the specific comparator to use in this analysis. * @return comparatorType **/ @Override public String getComparatorType() { return comparatorType; } /** * * @param comparatorType */ public void setComparatorType(String comparatorType) { this.comparatorType = comparatorType; } /** * Get getDbCohortMethodDataArgs * @return getDbCohortMethodDataArgs **/ @Override public GetDbCohortMethodDataArgsImpl getDbCohortMethodDataArgs() { return getDbCohortMethodDataArgs; } /** * * @param getDbCohortMethodDataArgs */ public void setGetDbCohortMethodDataArgs(GetDbCohortMethodDataArgsImpl getDbCohortMethodDataArgs) { this.getDbCohortMethodDataArgs = getDbCohortMethodDataArgs; } /** * Get createStudyPopArgs * @return createStudyPopArgs **/ @Override public CreateStudyPopulationArgsImpl getCreateStudyPopArgs() { return createStudyPopArgs; } /** * * @param createStudyPopArgs */ public void setCreateStudyPopArgs(CreateStudyPopulationArgsImpl createStudyPopArgs) { this.createStudyPopArgs = createStudyPopArgs; } /** * Should the createPs function be used in this analysis? * @return createPs **/ @Override public Boolean getCreatePs() { return createPs; } /** * * @param createPs */ public void setCreatePs(Boolean createPs) { this.createPs = createPs; } /** * Get createPsArgs * @return createPsArgs **/ @Override public CreatePsArgsImpl getCreatePsArgs() { return createPsArgs; } /** * * @param createPsArgs */ public void setCreatePsArgs(CreatePsArgsImpl createPsArgs) { this.createPsArgs = createPsArgs; } /** * Should the trimByPs function be used in this analysis? * @return trimByPs **/ @Override public Boolean getTrimByPs() { return trimByPs; } /** * * @param trimByPs */ public void setTrimByPs(Boolean trimByPs) { this.trimByPs = trimByPs; } /** * Get trimByPsArgs * @return trimByPsArgs **/ @Override public TrimByPsArgsImpl getTrimByPsArgs() { return trimByPsArgs; } /** * * @param trimByPsArgs */ public void setTrimByPsArgs(TrimByPsArgsImpl trimByPsArgs) { this.trimByPsArgs = trimByPsArgs; } /** * Should the trimByPsToEquipoise function be used in this analysis? * @return trimByPsToEquipoise **/ @Override public Boolean getTrimByPsToEquipoise() { return trimByPsToEquipoise; } /** * * @param trimByPsToEquipoise */ public void setTrimByPsToEquipoise(Boolean trimByPsToEquipoise) { this.trimByPsToEquipoise = trimByPsToEquipoise; } /** * Get trimByPsToEquipoiseArgs * @return trimByPsToEquipoiseArgs **/ @Override public TrimByPsToEquipoiseArgsImpl getTrimByPsToEquipoiseArgs() { return trimByPsToEquipoiseArgs; } /** * * @param trimByPsToEquipoiseArgs */ public void setTrimByPsToEquipoiseArgs(TrimByPsToEquipoiseArgsImpl trimByPsToEquipoiseArgs) { this.trimByPsToEquipoiseArgs = trimByPsToEquipoiseArgs; } /** * Should the matchOnPsAndCovariates function be used in this analysis? * @return matchOnPs **/ @Override public Boolean getMatchOnPs() { return matchOnPs; } /** * * @param matchOnPs */ public void setMatchOnPs(Boolean matchOnPs) { this.matchOnPs = matchOnPs; } /** * Get matchOnPsArgs * @return matchOnPsArgs **/ @Override public MatchOnPsArgsImpl getMatchOnPsArgs() { return matchOnPsArgs; } /** * * @param matchOnPsArgs */ public void setMatchOnPsArgs(MatchOnPsArgsImpl matchOnPsArgs) { this.matchOnPsArgs = matchOnPsArgs; } /** * Should the matchOnPsAndCovariates function be used in this analysis? * @return matchOnPsAndCovariates **/ @Override public Boolean getMatchOnPsAndCovariates() { return matchOnPsAndCovariates; } /** * * @param matchOnPsAndCovariates */ public void setMatchOnPsAndCovariates(Boolean matchOnPsAndCovariates) { this.matchOnPsAndCovariates = matchOnPsAndCovariates; } /** * * @param matchOnPsAndCovariatesArgs * @return */ public CohortMethodAnalysis matchOnPsAndCovariatesArgs(MatchOnPsAndCovariatesArgsImpl matchOnPsAndCovariatesArgs) { this.matchOnPsAndCovariatesArgs = matchOnPsAndCovariatesArgs; return this; } /** * Get matchOnPsAndCovariatesArgs * @return matchOnPsAndCovariatesArgs **/ @Override public MatchOnPsAndCovariatesArgsImpl getMatchOnPsAndCovariatesArgs() { return matchOnPsAndCovariatesArgs; } /** * * @param matchOnPsAndCovariatesArgs */ public void setMatchOnPsAndCovariatesArgs(MatchOnPsAndCovariatesArgsImpl matchOnPsAndCovariatesArgs) { this.matchOnPsAndCovariatesArgs = matchOnPsAndCovariatesArgs; } /** * Should the stratifyByPs function be used in this analysis? * @return stratifyByPs **/ @Override public Boolean getStratifyByPs() { return stratifyByPs; } /** * * @param stratifyByPs */ public void setStratifyByPs(Boolean stratifyByPs) { this.stratifyByPs = stratifyByPs; } /** * Get stratifyByPsArgs * @return stratifyByPsArgs **/ @Override public StratifyByPsArgsImpl getStratifyByPsArgs() { return stratifyByPsArgs; } /** * * @param stratifyByPsArgs */ public void setStratifyByPsArgs(StratifyByPsArgsImpl stratifyByPsArgs) { this.stratifyByPsArgs = stratifyByPsArgs; } /** * Should the stratifyByPsAndCovariates function be used in this analysis? * @return stratifyByPsAndCovariates **/ @Override public Boolean getStratifyByPsAndCovariates() { return stratifyByPsAndCovariates; } /** * * @param stratifyByPsAndCovariates */ public void setStratifyByPsAndCovariates(Boolean stratifyByPsAndCovariates) { this.stratifyByPsAndCovariates = stratifyByPsAndCovariates; } /** * Get stratifyByPsAndCovariatesArgs * @return stratifyByPsAndCovariatesArgs **/ @Override public StratifyByPsAndCovariatesArgsImpl getStratifyByPsAndCovariatesArgs() { return stratifyByPsAndCovariatesArgs; } /** * * @param stratifyByPsAndCovariatesArgs */ public void setStratifyByPsAndCovariatesArgs(StratifyByPsAndCovariatesArgsImpl stratifyByPsAndCovariatesArgs) { this.stratifyByPsAndCovariatesArgs = stratifyByPsAndCovariatesArgs; } /** * Should the fitOutcomeModel function be used in this analysis? * @return fitOutcomeModel **/ @Override public Boolean getFitOutcomeModel() { return fitOutcomeModel; } /** * * @param fitOutcomeModel */ public void setFitOutcomeModel(Boolean fitOutcomeModel) { this.fitOutcomeModel = fitOutcomeModel; } /** * Get fitOutcomeModelArgs * @return fitOutcomeModelArgs **/ @Override public FitOutcomeModelArgsImpl getFitOutcomeModelArgs() { return fitOutcomeModelArgs; } /** * * @param fitOutcomeModelArgs */ public void setFitOutcomeModelArgs(FitOutcomeModelArgsImpl fitOutcomeModelArgs) { this.fitOutcomeModelArgs = fitOutcomeModelArgs; } }
24.238462
162
0.708558
a81bf1ca92d9b39e7df9f484eb0c143c2be7a432
585
package com.bamdoliro.stupetition.domain.school.presentation.dto.response; import com.bamdoliro.stupetition.domain.school.domain.School; import lombok.Builder; import lombok.Getter; @Getter @Builder public class SchoolResponseDto { private Long id; private String name; private String emailDomain; public static SchoolResponseDto fromEntity(School school) { return SchoolResponseDto.builder() .id(school.getId()) .name(school.getName()) .emailDomain(school.getEmailDomain()) .build(); } }
25.434783
74
0.678632
7d3ccbe5231a1e08199b4d05c05bf32c29caa739
3,943
package com.wintertonsmith.snoolexa.intent; import com.amazon.speech.speechlet.Session; import com.amazon.speech.speechlet.SpeechletResponse; import com.amazon.speech.speechlet.User; import com.amazon.speech.ui.PlainTextOutputSpeech; import com.amazon.speech.ui.SimpleCard; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.extern.log4j.Log4j; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; @Log4j @NoArgsConstructor public class HotPostsIntent implements Intent { @Override public SpeechletResponse doIntent(@NonNull final Session session) { String speechText = "The the hottest five posts on Reddit are "; User sessionUser = session.getUser(); HttpGet getReq = new HttpGet("https://oauth.reddit.com/hot.json"); getReq.setHeader("Authorization","Bearer " + sessionUser.getAccessToken()); CloseableHttpClient client = HttpClients.custom().setUserAgent("com.wintertonsmith.snoolexa 0.1.0-SNAPSHOT").build(); //TODO: Either build or use an API wrapper for Reddit try { HttpResponse r = client.execute(getReq); String entity = EntityUtils.toString(r.getEntity()); JsonParser parser = new JsonParser(); JsonObject rootObj = parser.parse(entity).getAsJsonObject(); JsonArray posts = rootObj.get("data").getAsJsonObject().get("children").getAsJsonArray(); //TODO: Allow for post by post reading and user reprompts for manipulation/paging for(int i = 0; i < ((posts.size() > 5) ? 5 : posts.size()); ++i) { //TODO: Build a POJO representation of the JSON data JsonObject postData = posts.get(i).getAsJsonObject().get("data").getAsJsonObject(); JsonElement media = postData.get("media"); String type = "self"; if (media != null && !media.isJsonNull()) { JsonElement oembed = media.getAsJsonObject().get("oembed"); if (oembed != null && !oembed.isJsonNull()) { type = oembed.getAsJsonObject().get("type").getAsString(); if ("image".equals(type)) { type = "an " + type; } else { type = "a " + type; } } } String title = postData.get("title").getAsString(); String subreddit = postData.get("subreddit").getAsString(); speechText += type + " post with the title, " + title + " on r/" + subreddit + "."; if (i != posts.size() || i != 5) { speechText += " A "; } } speechText += " Those are the top 5 posts on Reddit. Goodbye!"; } catch (IOException e) { log.error("Hot API req failed with IOException!", e); } finally { try { client.close(); } catch (IOException ioe) { log.error("Failed to close the HTTP client stream.", ioe); } } SimpleCard card = new SimpleCard(); card.setTitle("Snoolexa"); card.setContent(speechText); // Create the plain text output. PlainTextOutputSpeech speech = new PlainTextOutputSpeech(); speech.setText(speechText); return SpeechletResponse.newTellResponse(speech, card); } }
37.552381
125
0.607659
fb28b30b7acc1fb4c5bf9a1dbb71b206ba52406a
1,324
package customer; import javax.servlet.http.*; import org.apache.struts.action.*; import tools.*; public final class CustomerAction extends Action { java.util.logging.Logger logger = LoggerInitiator.getLogger(); public CustomerAction() { logger.info("CustomerAction.java"); } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws Exception { CustomerForm kf = (CustomerForm)form; Customer k = kf.getCustomer(); javax.sql.DataSource dataSource; java.sql.Connection myConnection = null;; logger.info("Requesting Connection"); dataSource = getDataSource(req); logger.info("Have connection:" + dataSource); myConnection = dataSource.getConnection(); String sql = "INSERT INTO Customer (firstname, name, street, housenumber, " + "zipcode, city, password, mail) " + "VALUES('" + k.getFirstname() + "', '" + k.getName() + "', '" + k.getStreet() + "', " + k.getHousenumber() + ", " + k.getZipcode() + ", " + "'" + k.getCity() + "', '" + k.getPassword() + "', '" + k.getMail() + "')"; logger.info(sql); myConnection.createStatement().execute(sql); return mapping.findForward("customerCreated"); } }
31.52381
81
0.629154
fcbe8804adff769e36c64679c8083a65655d763b
2,633
/* * The MIT License * * Copyright 2015 Otwarta Platforma Wyborcza. * * 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 pl.otwartapw.opw.pre.management.ws.api; import java.util.List; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.TEXT_PLAIN; /** * Default CRUD API definition. * * @param <T> entity. * @author Adam Kowalewski * @version 2015.10.25 * */ public interface AbstractCrudApi<T> { @GET @Produces({APPLICATION_JSON, APPLICATION_XML}) List<T> findAll(); @POST @Consumes({APPLICATION_JSON, APPLICATION_XML}) void create(@NotNull @Valid T dto); @GET @Path("{id}") @Produces({APPLICATION_JSON, APPLICATION_XML}) T find(@NotNull @PathParam("id") Integer id); @DELETE @Path("{id}") void remove(@NotNull @PathParam("id") Integer id); @PUT @Path("{id}") @Consumes({APPLICATION_JSON, APPLICATION_XML}) void edit(@PathParam("id") Integer id, @NotNull @Valid T dto); @GET @Path("{from}/{to}") @Produces({APPLICATION_JSON, APPLICATION_XML}) List<T> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to); @GET @Path("count") @Produces(TEXT_PLAIN) String count(); }
31.722892
84
0.72275
2453fe44ec63178d89f0d56ec1f8ffd00e82e430
100
package com.apress.isf.spring; public interface MessageService { public String getMessage(); }
16.666667
33
0.76
67e6952264d2c71b722315cc0a71ef0663b97ac1
2,522
/** * Copyright 2015 Santhosh Kumar Tekuri * * The JLibs authors license 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 jlibs.core.io; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.nio.charset.Charset; /** * @author Santhosh Kumar T */ public class UnicodeInputStream extends FilterInputStream{ private ByteBuffer marker = ByteBuffer.allocate(4); public final String encoding; public final boolean hasBOM; public UnicodeInputStream(InputStream delegate) throws IOException{ this(delegate, EncodingDetector.DEFAULT); } public UnicodeInputStream(InputStream delegate, EncodingDetector detector) throws IOException{ super(delegate); int len = IOUtil.readFully(delegate, marker.array()); marker.limit(len); encoding = detector.detect(marker); hasBOM = marker.position()>0; if(!marker.hasRemaining()) marker = null; } @Override public int read() throws IOException{ if(marker!=null){ int b = marker.get() & 0xFF; if(!marker.hasRemaining()) marker = null; return b; }else return super.read(); } @Override public int read(byte[] b, int off, int len) throws IOException{ if(marker!=null){ int read = Math.min(marker.remaining(), len); System.arraycopy(marker.array(), marker.position(), b, off, read); if(read==marker.remaining()) marker = null; else marker.position(marker.position()+read); return read; } return super.read(b, off, len); } public InputStreamReader createReader(){ if(encoding==null) return new InputStreamReader(this); else return new InputStreamReader(this, Charset.forName(encoding)); } }
30.756098
98
0.650278
51ae0eb26d067a8542f7a8b55d99ba130642cf8b
3,279
package org.jboss.resteasy.messaging.test; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.spi.Link; import org.hornetq.rest.util.LinkStrategy; import org.junit.Assert; import org.junit.Test; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class AutoAckTopicTest { public static Link getLinkByTitle(LinkStrategy strategy, ClientResponse response, String title) { return response.getLinkHeader().getLinkByTitle(title); } @Test public void testSuccessFirst() throws Exception { ClientRequest request = new ClientRequest("http://localhost:9095/topics/jms.topic.chat"); ClientResponse response = request.head(); Assert.assertEquals("*****", 200, response.getStatus()); Link sender = getLinkByTitle(null, response, "create"); Link subscriptions = getLinkByTitle(null, response, "subscriptions"); /* ClientResponse res = subscriptions.request().post(); Assert.assertEquals(201, res.getStatus()); Link sub1 = res.getLocation(); Assert.assertNotNull(sub1); Link consumeNext1 = MessageTestBase.getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); Assert.assertNotNull(consumeNext1); System.out.println("consumeNext1: " + consumeNext1); res = subscriptions.request().post(); Assert.assertEquals(201, res.getStatus()); Link sub2 = res.getLocation(); Assert.assertNotNull(sub2); Link consumeNext2 = MessageTestBase.getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); Assert.assertNotNull(consumeNext1); res = sender.request().body("text/plain", Integer.toString(1)).post(); Assert.assertEquals(201, res.getStatus()); res = sender.request().body("text/plain", Integer.toString(2)).post(); Assert.assertEquals(201, res.getStatus()); res = consumeNext1.request().post(String.class); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals("1", res.getEntity(String.class)); consumeNext1 = MessageTestBase.getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); res = consumeNext1.request().post(String.class); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals("2", res.getEntity(String.class)); consumeNext1 = MessageTestBase.getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); res = consumeNext2.request().post(String.class); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals("1", res.getEntity(String.class)); consumeNext2 = MessageTestBase.getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); res = consumeNext2.request().post(String.class); Assert.assertEquals(200, res.getStatus()); Assert.assertEquals("2", res.getEntity(String.class)); consumeNext2 = MessageTestBase.getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); Assert.assertEquals(204, sub1.request().delete().getStatus()); Assert.assertEquals(204, sub2.request().delete().getStatus()); */ } }
41.506329
123
0.706618
5411689217f020cfa3aa039212529d9484496226
644
package com.github.megatronking.funnydraw.draw; import android.support.annotation.NonNull; /** * A drawer can draw graphs using motion events through input manager in phone screen. * * @author Magetron King * @since 18/7/26 20:05 */ public interface MotionDrawer { /** * Set the draw callback. * * @param callback Callback with different MotionEvents. */ void setCallback(@NonNull MotionDrawerCallback callback); /** * Start drawing graph with a callback {@link MotionDrawerCallback} invoked. * * @param isSmoothly Should the draw smoothly. */ void draw(boolean isSmoothly); }
22.206897
86
0.686335
77c7c6d7cf47d9ef15ecedd4213759f9bdf14120
8,837
package com.example.imalok.bmi; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { EditText name,weight,height; ToggleButton gender; CheckBox tc,toast,textView; TextView result; Button bmi; Button refresh; Button alok; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alok = (Button)findViewById(R.id.button4); alok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this); // set title alertDialogBuilder.setTitle("BMI"); // set dialog message alertDialogBuilder .setMessage("Click Yes to Exit!") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, close // current activity MainActivity.this.finish(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }); calculate(); } public void onBackPressed() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("Do You Want to Exit?"); builder.setCancelable(true); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } public void calculate() { name = (EditText)findViewById(R.id.editText); weight = (EditText)findViewById(R.id.editText2); height = (EditText)findViewById(R.id.editText3); gender = (ToggleButton)findViewById(R.id.toggleButton); tc = (CheckBox)findViewById(R.id.checkBox); toast = (CheckBox)findViewById(R.id.checkBox2); textView = (CheckBox)findViewById(R.id.checkBox3); result = (TextView)findViewById(R.id.textView2); bmi = (Button)findViewById(R.id.button); refresh = (Button)findViewById(R.id.button2); bmi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String a = name.getText().toString(); String num1 = weight.getText().toString(); String num2 = height.getText().toString(); if ((num1.compareTo(".")!=0) && (num2.compareTo(".")!=0)) { if (a.length()>0 && num1.length()>0 && num2.length()>0) { double x = Double.parseDouble(num1); double y = Double.parseDouble(num2); double b, z; b = ((y / 100) * (y / 100)); z = (x / b); if (gender.getText().equals("ON")) { if (toast.isChecked() && textView.isChecked()) { result.setText(a + ",(MALE)\nYour BMI is:" + z); Toast.makeText(getApplicationContext(), a + ",(MALE)\nYour BMI is:" + z, Toast.LENGTH_SHORT).show(); } if (!toast.isChecked() && textView.isChecked()) { result.setText(a + ",(MALE)\nYour BMI is:" + z); } if (toast.isChecked() && !textView.isChecked()) { result.setText(""); Toast.makeText(getApplicationContext(), a + ",(MALE)\nYour BMI is:" + z, Toast.LENGTH_SHORT).show(); } if (!toast.isChecked() && !textView.isChecked()) { Toast.makeText(getApplicationContext(), "Select at least 1 Checkbox", Toast.LENGTH_SHORT).show(); } } else { if (toast.isChecked() && textView.isChecked()) { result.setText(a + ",(FEMALE)\nYour BMI is:" + z); Toast.makeText(getApplicationContext(), a + ",(FEMALE)\nYour BMI is:" + z, Toast.LENGTH_SHORT).show(); } if (!toast.isChecked() && textView.isChecked()) { result.setText(a + ",(FEMALE)\nYour BMI is:" + z); } if (toast.isChecked() && (!textView.isChecked())) { result.setText(""); Toast.makeText(getApplicationContext(), a + ",(FEMALE)\nYour BMI is:" + z, Toast.LENGTH_SHORT).show(); } if (!toast.isChecked() && !textView.isChecked()) { Toast.makeText(getApplicationContext(), "Select at least 1 Checkbox", Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(getApplicationContext(),"Input All Fields",Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(),"Input Correct Input",Toast.LENGTH_SHORT).show(); } } }); tc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (tc.isChecked()) { bmi.setEnabled(true); } else { bmi.setEnabled(false); } } }); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { name.setText(""); weight.setText(""); height.setText(""); result.setText(""); toast.setChecked(false); textView.setChecked(false); tc.setChecked(false); gender.setChecked(false); } }); } }
39.10177
138
0.446758
83ee73b9b71aa2efcb3c116577a43f08e11c89d3
2,844
package com.tractusx.uploadappadapter.models; import java.security.PublicKey; public class Part { private String customerUniqueId; public String getCustomerUniqueId() {return this.customerUniqueId;} private String customerContractOneId; public String getCustomerContractOneId() {return this.customerUniqueId;} private String customerOneId; public String getCustomerOneId() {return this.customerOneId;} private String isParentOf; public String getIsParentOf() {return this.isParentOf;} private String manufacturerOneId; public String getManufacturerOneId(){return this.manufacturerOneId;} private String manufacturerUniqueId; public String getManufacturerUniqueId(){return this.manufacturerUniqueId;} private String partNameCustomer; public String getPartNameCustomer(){return this.partNameCustomer;} private String partNameManufacturer; public String getPartNameManufacturer() {return this.partNameManufacturer;} private String partNumberCustomer; public String getPartNumberCustomer() {return this.partNumberCustomer;} private String partNumberManufacturer; public String getPartNumberManufacturer() {return this.partNumberManufacturer;} private String productionCountryCode; public String getProductionCountryCode() {return this.productionCountryCode;} private String productionDateGmt; public String getProductionDateGmt(){return this.productionDateGmt;} private String qualityAlert; public String getQualityAlert(){return this.qualityAlert;} private String qualityType; public String getQualityType(){return this.qualityType;} private String manufacturerContractOneId; public String getManufacturerContractOneId(){return this.manufacturerContractOneId;} private String uniqueId; public String getUniqueId(){return this.uniqueId;} public Part(String csvString) { String[] initArray = csvString.split(","); if(initArray.length == 16) { this.customerUniqueId = initArray[0]; this.customerContractOneId = initArray[1]; this.customerOneId = initArray[2]; this.isParentOf = initArray[3]; this.manufacturerOneId = initArray[4]; this.manufacturerUniqueId = initArray[5]; this.partNameCustomer = initArray[6]; this.partNameManufacturer = initArray[7]; this.partNumberCustomer = initArray[8]; this.partNumberManufacturer = initArray[9]; this.productionCountryCode = initArray[10]; this.productionDateGmt = initArray[11]; this.qualityAlert = initArray[12]; this.qualityType = initArray[13]; this.manufacturerContractOneId = initArray[14]; this.uniqueId = initArray[15]; } } }
36.935065
88
0.722925
9c2f9244df46d02b6b3ab23f13afcfc5013dac23
1,846
package com.getsentry.raven.android; import android.content.Context; import android.util.Log; import com.getsentry.raven.*; import com.getsentry.raven.android.event.helper.AndroidEventBuilderHelper; import com.getsentry.raven.buffer.Buffer; import com.getsentry.raven.buffer.DiskBuffer; import com.getsentry.raven.dsn.Dsn; import java.io.File; /** * RavenFactory that handles Android-specific construction, like taking advantage * of the Android Context instance. */ public class AndroidRavenFactory extends DefaultRavenFactory { /** * Logger tag. */ public static final String TAG = AndroidRavenFactory.class.getName(); /** * Default Buffer directory name. */ private static final String DEFAULT_BUFFER_DIR = "raven-buffered-events"; private Context ctx; /** * Construct an AndroidRavenFactory using the specified Android Context. * * @param ctx Android Context. */ public AndroidRavenFactory(Context ctx) { this.ctx = ctx; Log.d(TAG, "Construction of Android Raven."); } @Override public com.getsentry.raven.Raven createRavenInstance(Dsn dsn) { com.getsentry.raven.Raven ravenInstance = super.createRavenInstance(dsn); ravenInstance.addBuilderHelper(new AndroidEventBuilderHelper(ctx)); return ravenInstance; } @Override protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = dsn.getOptions().get(BUFFER_DIR_OPTION); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { bufferDir = new File(ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); } }
29.301587
90
0.690683
9266755e28471b8e20384846a12ed4bf1ed6fed8
2,952
package cn.xuetang.common.config; import cn.xuetang.common.action.BaseAction; import cn.xuetang.modules.app.bean.App_info; import cn.xuetang.modules.sys.bean.Sys_config; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.dao.Sqls; import org.nutz.filepool.FilePool; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mvc.Mvcs; import org.quartz.Scheduler; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Wizzer.cn * @time 2012-9-13 上午10:54:04 */ public class Globals extends BaseAction { private final static Log log = Logs.get(); //虚拟目录路径 public static String APP_BASE_PATH = ""; //虚拟目录名称 public static String APP_BASE_NAME = ""; //应用中文名 public static String APP_NAME = ""; //系统配置 public static Map<String, String> SYS_CONFIG; //数据字典,根据ID分别初始化 public static Map<String, Object> DATA_DICT; //应用信息,用于通过mykey验证来源,放在内存里为了提高响应速度 public static Map<String, Object> APP_INFO; //定时任务实例 public static Scheduler SCHEDULER; //文件池 public static FilePool FILE_POOL; public static void InitAppInfo(Dao dao) { try { if (APP_INFO == null) { APP_INFO = new HashMap<String, Object>(); } APP_INFO.clear(); List<App_info> appInfoList = dao.query(App_info.class, Cnd.orderBy().asc("ID")); for (App_info appInfo : appInfoList) { Globals.APP_INFO.put(appInfo.getMykey(), appInfo); } } catch (Exception e) { e.printStackTrace(); log.error(e); } } public static void InitSysConfig(Dao dao) { try { if (SYS_CONFIG == null) { SYS_CONFIG = new HashMap<String, String>(); } List<Sys_config> configList = dao.query(Sys_config.class, Cnd.orderBy().asc("ID")); for (Sys_config sysConfig : configList) { Globals.SYS_CONFIG.put(sysConfig.getCname(), sysConfig.getCvalue()); } } catch (Exception e) { e.printStackTrace(); log.error(e); } } public static void InitDataDict(Dao dao) { try { if (DATA_DICT == null) { DATA_DICT = new HashMap<String, Object>(); } DATA_DICT.put(Dict.APP_TYPE, daoCtl.getHashMap(dao, Sqls.create("SELECT dkey,dval FROM sys_dict WHERE id LIKE '" + Dict.APP_TYPE + "____'"))); DATA_DICT.put(Dict.DIVSION, daoCtl.getHashMap(dao, Sqls.create("SELECT dkey,dval FROM sys_dict WHERE id LIKE '" + Dict.DIVSION + "_%'"))); DATA_DICT.put(Dict.FORM_TYPE, daoCtl.getHashMap(dao, Sqls.create("SELECT dkey,dval FROM sys_dict WHERE id LIKE '" + Dict.FORM_TYPE + "_%' order by location asc,id asc"))); } catch (Exception e) { e.printStackTrace(); log.error(e); } } }
33.168539
183
0.611789
e1a1ebd866c443dd3853a0d34ed6b913671f23d5
5,963
package nl.rug.jbi.jsm.metrics.packagemetrics.resource; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import java.util.Collection; import java.util.Map; class PackageData { private final String packageName; private final String packageSource; private final Map<String, ClassData> memberData = Maps.newHashMap(); private final Map<String, ClassData> usesClasses = Maps.newHashMap(); private final Map<String, PackageData> usesPackages = Maps.newHashMap(); private final Map<String, ClassData> extendsClasses = Maps.newHashMap(); private final Map<String, PackageData> extendsPackages = Maps.newHashMap(); private final Map<String, ClassData> usedByClasses = Maps.newHashMap(); private final Map<String, PackageData> usedByPackages = Maps.newHashMap(); private final Map<String, ClassData> extendedByClasses = Maps.newHashMap(); private final Map<String, PackageData> extendedByPackages = Maps.newHashMap(); private final Map<String, ClassData> inClasses = Maps.newHashMap(); private final Map<String, ClassData> outClasses = Maps.newHashMap(); public PackageData(final String packageName, final String packageSource) { this.packageName = packageName; this.packageSource = packageSource; } void registerMember(final ClassData classData) { Preconditions.checkNotNull(classData); Preconditions.checkArgument(this.packageName.equals(classData.getPackageName())); this.memberData.put(classData.getClassName(), classData); } public String getPackageName() { return this.packageName; } public String getPackageSource() { return this.packageSource; } public Map<String, ClassData> getMemberClasses() { return this.memberData; } public Map<String, ClassData> getUsesClasses() { return this.usesClasses; } public Map<String, PackageData> getUsesPackages() { return this.usesPackages; } public Map<String, ClassData> getExtendsClasses() { return this.extendsClasses; } public Map<String, PackageData> getExtendsPackages() { return this.extendsPackages; } public Map<String, ClassData> getUsedByClasses() { return this.usedByClasses; } public Map<String, PackageData> getUsedByPackages() { return this.usedByPackages; } public Map<String, ClassData> getExtendedByClasses() { return this.extendedByClasses; } public Map<String, PackageData> getExtendedByPackages() { return this.extendedByPackages; } public Map<String, ClassData> getOutClasses() { return this.outClasses; } public Map<String, ClassData> getInClasses() { return this.inClasses; } public boolean isInThisPackage(final ClassData classData) { return this.packageName.equals(classData.getPackageName()); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PackageData)) return false; PackageData that = (PackageData) o; return packageName.equals(that.packageName); } @Override public int hashCode() { return packageName.hashCode(); } @Override public String toString() { return Objects.toStringHelper(this) .add("packageName", packageName) .add("packageSource", packageSource) .add("memberData", memberData.keySet()) .add("usesClasses", usesClasses.keySet()) .add("usesPackages", usesPackages.keySet()) .add("extendsClasses", extendsClasses.keySet()) .add("extendsPackages", extendsPackages.keySet()) .add("usedByClasses", usedByClasses.keySet()) .add("usedByPackages", usedByPackages.keySet()) .add("extendedByClasses", extendedByClasses.keySet()) .add("extendedByPackages", extendedByPackages.keySet()) .toString(); } void calculateMappings(final Map<String, PackageData> packageDataMap) { for (final ClassData member : this.memberData.values()) { registerPackageClass( usesClasses, usesPackages, member.getUsesMap().values(), packageDataMap ); registerPackageClass( usedByClasses, usedByPackages, member.getUsedByMap().values(), packageDataMap ); registerPackageClass( extendsClasses, extendsPackages, member.getExtendsMap().values(), packageDataMap ); registerPackageClass( extendedByClasses, extendedByPackages, member.getExtendedByMap().values(), packageDataMap ); if (member.getUsedByMap().size() + member.getExtendedByMap().size() > 0) { this.inClasses.put(member.getClassName(), member); } if (member.getUsesMap().size() + member.getExtendsMap().size() > 0) { this.outClasses.put(member.getClassName(), member); } } } private void registerPackageClass( final Map<String, ClassData> classOut, final Map<String, PackageData> packageOut, final Collection<ClassData> classes, final Map<String, PackageData> packageDataMap ) { for (final ClassData clazz : classes) { if (!isInThisPackage(clazz)) { classOut.put(clazz.getClassName(), clazz); final String packageName = clazz.getPackageName(); packageOut.put(packageName, packageDataMap.get(packageName)); } } } }
33.5
89
0.627201
af45ccdddaf7c4b24fba32405839236a0f20badc
5,341
package com.planet_ink.coffee_mud.Commands; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2010 Bo Zimmerman 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. */ @SuppressWarnings("unchecked") public class Give extends StdCommand { public Give(){} private String[] access={"GIVE","GI"}; public String[] getAccessWords(){return access;} public boolean execute(MOB mob, Vector commands, int metaFlags) throws java.io.IOException { if(commands.size()<2) { mob.tell("Give what to whom?"); return false; } commands.removeElementAt(0); if(commands.size()<2) { mob.tell("To whom should I give that?"); return false; } MOB recipient=mob.location().fetchInhabitant((String)commands.lastElement()); if((recipient==null)||(!CMLib.flags().canBeSeenBy(recipient,mob))) { mob.tell("I don't see anyone called "+(String)commands.lastElement()+" here."); return false; } commands.removeElementAt(commands.size()-1); if((commands.size()>0)&&(((String)commands.lastElement()).equalsIgnoreCase("to"))) commands.removeElementAt(commands.size()-1); int maxToGive=CMLib.english().calculateMaxToGive(mob,commands,true,mob,false); if(maxToGive<0) return false; String thingToGive=CMParms.combine(commands,0); int addendum=1; String addendumStr=""; Vector V=new Vector(); boolean allFlag=(commands.size()>0)?((String)commands.elementAt(0)).equalsIgnoreCase("all"):false; if(thingToGive.toUpperCase().startsWith("ALL.")){ allFlag=true; thingToGive="ALL "+thingToGive.substring(4);} if(thingToGive.toUpperCase().endsWith(".ALL")){ allFlag=true; thingToGive="ALL "+thingToGive.substring(0,thingToGive.length()-4);} boolean onlyGoldFlag=mob.hasOnlyGoldInInventory(); Item giveThis=CMLib.english().bestPossibleGold(mob,null,thingToGive); if(giveThis!=null) { if(((Coins)giveThis).getNumberOfCoins()<CMLib.english().numPossibleGold(mob,thingToGive)) return false; if(CMLib.flags().canBeSeenBy(giveThis,mob)) V.addElement(giveThis); } boolean doBugFix = true; if(V.size()==0) while(doBugFix || ((allFlag)&&(addendum<=maxToGive))) { doBugFix=false; giveThis=mob.fetchCarried(null,thingToGive+addendumStr); if((giveThis==null) &&(V.size()==0) &&(addendumStr.length()==0) &&(!allFlag)) { giveThis=mob.fetchWornItem(thingToGive); if(giveThis!=null) { if((!(giveThis).amWearingAt(Wearable.WORN_HELD))&&(!(giveThis).amWearingAt(Wearable.WORN_WIELD))) { mob.tell("You must remove that first."); return false; } CMMsg newMsg=CMClass.getMsg(mob,giveThis,null,CMMsg.MSG_REMOVE,null); if(mob.location().okMessage(mob,newMsg)) mob.location().send(mob,newMsg); else return false; } } if((allFlag)&&(!onlyGoldFlag)&&(giveThis instanceof Coins)&&(thingToGive.equalsIgnoreCase("all"))) giveThis=null; else { if(giveThis==null) break; if(CMLib.flags().canBeSeenBy(giveThis,mob)) V.addElement(giveThis); } addendumStr="."+(++addendum); } if(V.size()==0) mob.tell("You don't seem to be carrying that."); else for(int i=0;i<V.size();i++) { giveThis=(Item)V.elementAt(i); CMMsg newMsg=CMClass.getMsg(mob,recipient,giveThis,CMMsg.MSG_GIVE,"<S-NAME> give(s) <O-NAME> to <T-NAMESELF>."); if(mob.location().okMessage(mob,newMsg)) mob.location().send(mob,newMsg); if(giveThis instanceof Coins) ((Coins)giveThis).putCoinsBack(); if(giveThis instanceof RawMaterial) ((RawMaterial)giveThis).rebundle(); } return false; } public double combatActionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCOMCMDTIME),100.0);} public double actionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCMDTIME),100.0);} public boolean canBeOrdered(){return true;} }
37.090278
133
0.677776
59cb8b777da0d13510b231126372265624886e24
247
package com.whenling.extension.cms.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/admin/article") public class ArticleController { }
22.454545
63
0.793522
b660f62e7313ef3fba48192f3cd702d0e28b6818
13,842
package com.hzf.nicholas.custom_ui.week_display; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import com.hzf.nicholas.custom_ui.R; import com.hzf.nicholas.custom_ui.util.DateAndTime; import com.hzf.nicholas.custom_ui.util.RenderUtil; import java.util.ArrayList; import java.util.List; import androidx.annotation.Nullable; public class WeekDisplay extends View { private static final int MODE_NORMAL_THIS_WEEK = 0; private static final int MODE_ENGLISH_THREE_THIS_WEEK = 1; private static final int MODE_ENGLISH_SINGLE_THIS_WEEK = 2; private static final int MODE_NORMAL = 3; private static final int MODE_ENGLISH_THREE = 4; private static final int MODE_ENGLISH_SINGLE = 5; private static final int[] SELECTED = {R.attr.selected}; private static final int[] UNSELECTED = {-R.attr.selected}; private Context mContext; private Paint mDayPaint; private Paint mDatePaint; private Paint mDotPaint; private Paint mBgPaint; private Paint mSelectedDayPaint; private Paint mSelectedDatePaint; private Paint mSelectedBgPaint; private ColorStateList mBgColorList; private ColorStateList mTextDayColorList; private ColorStateList mTextDateColorList; private int mDotColorString; private boolean mSelected; private boolean mWithData; private int mMode; private float paddingDayLR; private float paddingDayTB; private float paddingDateDot; private int screenWidth; private float cellWidth; private float cellHeight; private List<String> weekText; private List<String> dayText; private int[] data; private int selectCurIndex = 0; public WeekDisplay(Context context) { this(context,null,0); } public WeekDisplay(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public WeekDisplay(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.WeekDisplay); if (typedArray != null) { mBgColorList = typedArray.getColorStateList(R.styleable.WeekDisplay_bg_color); mTextDayColorList = typedArray.getColorStateList(R.styleable.WeekDisplay_text_day_color); mTextDateColorList = typedArray.getColorStateList(R.styleable.WeekDisplay_text_date_color); mDotColorString = typedArray.getColor(R.styleable.WeekDisplay_dot_color,Color.YELLOW); mSelected = typedArray.getBoolean(R.styleable.WeekDisplay_selected,false); mWithData = typedArray.getBoolean(R.styleable.WeekDisplay_with_data,false); mMode = typedArray.getInt(R.styleable.WeekDisplay_mode,0); paddingDayLR = typedArray.getDimension(R.styleable.WeekDisplay_padding_day_lr,0); paddingDayTB = typedArray.getDimension(R.styleable.WeekDisplay_padding_day_tb,0); paddingDateDot = typedArray.getDimension(R.styleable.WeekDisplay_padding_date_dot,0); typedArray.recycle(); } if (mTextDayColorList == null){ mDayPaint = RenderUtil.getPaint(Color.BLUE); }else{ mDayPaint = RenderUtil.getPaint(mTextDayColorList.getColorForState(getDrawableState(),Color.BLUE)); } if (mTextDateColorList == null){ mDatePaint = RenderUtil.getPaint(Color.BLUE); }else{ mDatePaint = RenderUtil.getPaint(mTextDateColorList.getColorForState(getDrawableState(),Color.BLUE)); } if (mBgColorList == null){ mBgPaint = RenderUtil.getPaint(Color.WHITE); }else { mBgPaint = RenderUtil.getPaint(mBgColorList.getColorForState(getDrawableState(),Color.WHITE)); } mDotPaint = RenderUtil.getPaint(mDotColorString); setSelected(!mSelected); initData(); initPaints(); initTextSize(); } private void initTextSize() { mDayPaint.setTextSize(cellHeight * 0.18f); mDatePaint.setTextSize(cellHeight * 0.15f); mSelectedDayPaint.setTextSize(cellHeight * 0.18f); mSelectedDatePaint.setTextSize(cellHeight * 0.15f); } private void initData() { WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(dm); screenWidth = dm.widthPixels; cellWidth = (float) screenWidth/7; cellHeight = cellWidth*1.5f; switch (mMode){ case MODE_NORMAL_THIS_WEEK: weekText = DateAndTime.getThisWeekDays(0); dayText = DateAndTime.getThisWeekDates(); break; case MODE_ENGLISH_THREE_THIS_WEEK: weekText = DateAndTime.getThisWeekDays(1); dayText = DateAndTime.getThisWeekDates(); break; case MODE_ENGLISH_SINGLE_THIS_WEEK: List<String> fullText = DateAndTime.getThisWeekDays(1); weekText = new ArrayList<>(); for (String s : fullText) { weekText.add(s.substring(0,1)); } dayText = DateAndTime.getThisWeekDates(); break; case MODE_NORMAL: weekText = DateAndTime.getFutureDays(0); dayText = DateAndTime.getFutureSevenDates(); break; case MODE_ENGLISH_THREE: weekText = DateAndTime.getFutureDays(1); dayText = DateAndTime.getFutureSevenDates(); break; case MODE_ENGLISH_SINGLE: List<String> fullText2 = DateAndTime.getFutureDays(1); weekText = new ArrayList<>(); for (String s : fullText2) { weekText.add(s.substring(0,1)); } dayText = DateAndTime.getFutureSevenDates(); break; } data = new int[7]; for (int i = 0; i < 7; i++) { data[i] = 0; } } private void initPaints() { if (mTextDayColorList == null){ mSelectedDayPaint = RenderUtil.getPaint(Color.WHITE); }else{ mSelectedDayPaint = RenderUtil.getPaint(mTextDayColorList.getColorForState(getDrawableState(),Color.WHITE)); } if (mTextDateColorList == null){ mSelectedDatePaint = RenderUtil.getPaint(Color.WHITE); }else{ mSelectedDatePaint = RenderUtil.getPaint(mTextDateColorList.getColorForState(getDrawableState(),Color.WHITE)); } if (mBgColorList == null){ mSelectedBgPaint = RenderUtil.getPaint(Color.BLUE); }else { mSelectedBgPaint = RenderUtil.getPaint(mBgColorList.getColorForState(getDrawableState(),Color.BLUE)); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = screenWidth-14*6; int height = (int) (width/7*1.5f); if (!mWithData){ height = (int) (width/7*1.5f*0.7f); } int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec); int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); if (modeWidth == MeasureSpec.AT_MOST) { // wrap_content sizeWidth = Math.min(width,sizeWidth); modeWidth = MeasureSpec.EXACTLY; } if (modeHeight == MeasureSpec.AT_MOST) { // wrap_content sizeHeight = Math.min(height,sizeHeight); modeHeight = MeasureSpec.EXACTLY; } widthMeasureSpec = MeasureSpec.makeMeasureSpec(sizeWidth, modeWidth); heightMeasureSpec = MeasureSpec.makeMeasureSpec(sizeHeight, modeHeight); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected int[] onCreateDrawableState(int extraSpace) { int[] drawableState = super.onCreateDrawableState(extraSpace + 3); if (mSelected) { mergeDrawableStates(drawableState, SELECTED); } else { mergeDrawableStates(drawableState, UNSELECTED); } return drawableState; } @Override public void setSelected(boolean selected) { if (mSelected != selected){ mSelected = selected; refreshDrawableState(); initPaints(); invalidate(); mSelected = !selected; } } @Override protected void onDraw(Canvas canvas) { cellWidth = (float) getMeasuredWidth()/7; cellHeight = cellWidth*1.5f; initTextSize(); mDotPaint = RenderUtil.getPaint(mDotColorString); if (paddingDayLR > cellWidth*0.2f){ paddingDayLR = cellWidth*0.2f; } if (paddingDayTB > cellHeight*0.1f){ paddingDayTB = cellHeight*0.1f; } for (int i = 0 ; i < 7 ; i++){ RectF rectF = new RectF(i*cellWidth+cellWidth*0.2f-paddingDayLR,0,(i+1)*cellWidth-cellWidth*0.2f+paddingDayLR,cellHeight*0.7f); if (i == selectCurIndex){ canvas.drawRoundRect(rectF,cellWidth*3/10+paddingDayLR,cellWidth*3/10+paddingDayLR,mSelectedBgPaint); drawText(canvas,i,0,mSelectedDayPaint,weekText.get(i)); drawText(canvas,i,1,mSelectedDatePaint,dayText.get(i)); }else { canvas.drawRoundRect(rectF,cellWidth*3/10+paddingDayLR,cellWidth*3/10+paddingDayLR,mBgPaint); drawText(canvas,i,0,mDayPaint,weekText.get(i)); drawText(canvas,i,1,mDatePaint,dayText.get(i)); } if (mWithData){ drawDots(canvas,i,mDotPaint); } } } private void drawText(Canvas canvas, int index, int flag, Paint paint, String text) { if(isIllegalIndex(index)){ return; } float top = cellHeight*0.1f+paddingDayTB; if (flag == 1){ top = cellHeight*0.4f+paddingDayTB; } float bottom = top + cellHeight*0.3f-paddingDayTB; if (flag == 1){ bottom = top + cellHeight*0.2f-paddingDayTB; } float baseline = RenderUtil.getBaseline(top, bottom, paint); float unitWidth = (cellWidth-paint.measureText(weekText.get(index)))/2; if (flag == 1){ unitWidth = (cellWidth-paint.measureText(dayText.get(index)))/2; } int startX = (int) (index*cellWidth+unitWidth); canvas.drawText(text, startX, baseline, paint); } private void drawDots(Canvas canvas, int index, Paint paint) { if(isIllegalIndex(index) || data[index] == 0 || data[index] > 3){ return; } float radius = cellWidth*0.05f; float unitWidth = cellWidth/2; float startX = index*cellWidth+unitWidth;//data[index] == 1 float startY = cellHeight*0.8f+paddingDateDot; if (data[index] == 2){ startX = index*cellWidth+unitWidth-2*radius;//data[index] == 2 canvas.drawCircle(startX,startY,radius,paint); startX = index*cellWidth+unitWidth+2*radius;//data[index] == 2 canvas.drawCircle(startX,startY,radius,paint); }else if (data[index] == 3){ canvas.drawCircle(startX,startY,radius,paint); startX = index*cellWidth+unitWidth-2.5f*radius;//data[index] == 3 canvas.drawCircle(startX,startY,radius,paint); startX = index*cellWidth+unitWidth+2.5f*radius;//data[index] == 3 canvas.drawCircle(startX,startY,radius,paint); }else { canvas.drawCircle(startX,startY,radius,paint); } } private boolean isIllegalIndex(int i){ return i < 0 || i >= 7; } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_UP: int location = getIndexByXY(x,y); if (location != selectCurIndex){ selectCurIndex = location; setSelected(!mSelected); if (listener != null){ listener.onClick(location,dayText.get(location),weekText.get(location)); } } break; } return true; } private int getIndexByXY(float x, float y) { if (y >= 0 && y <= cellHeight){ return (int) (x/cellWidth); } return 0; } public void setMode(int i){ if (i >=0 && i <= 5){ mMode = i; initData(); invalidate(); } } public void setDotColor(int color){ mDotColorString = color; invalidate(); } public void setData(int[] data){ this.data = data; invalidate(); } //点击事件 public interface OnItemClickListener { void onClick(int position,String day,String date); } private WeekDisplay.OnItemClickListener listener; public void setOnItemClickListener(WeekDisplay.OnItemClickListener listener) { this.listener = listener; } }
36.81383
139
0.62426
d8905a591ca066b3166ab4e8ff89c972a223b773
2,555
package org.ihtsdo.snomed.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.apache.commons.validator.routines.checkdigit.CheckDigitException; import org.apache.commons.validator.routines.checkdigit.VerhoeffCheckDigit; import org.ihtsdo.snomed.util.rf2.schema.RF2SchemaConstants; public class IdGenerator implements RF2SchemaConstants{ private String fileName; private BufferedReader availableSctIds; private int dummySequence = 100; private boolean useDummySequence = false; int idsAssigned = 0; public static IdGenerator initiateIdGenerator(String sctidFilename) throws SnomedUtilException { if (sctidFilename.equals("dummy")) { return new IdGenerator(); } File sctIdFile = new File (sctidFilename); try { if (sctIdFile.canRead()) { return new IdGenerator(sctIdFile); } } catch (Exception e) {} throw new SnomedUtilException("Unable to read sctids from " + sctidFilename); } private IdGenerator(File sctidFile) throws FileNotFoundException { fileName = sctidFile.getAbsolutePath(); availableSctIds = new BufferedReader(new FileReader(sctidFile)); } private IdGenerator() { useDummySequence = true; } public String getSCTID(PartionIdentifier partitionIdentifier) throws IOException, SnomedUtilException { if (useDummySequence) { idsAssigned++; return getDummySCTID(partitionIdentifier); } String sctId; try { sctId = availableSctIds.readLine(); } catch (IOException e) { throw new SnomedUtilException("Unable to recover SCTID from file " + fileName); } if (sctId == null || sctId.isEmpty()) { throw new SnomedUtilException("No more SCTIDs in file " + fileName + " need more than " + idsAssigned); } //Check the SCTID is valid, and belongs to the correct partition SnomedUtils.isValid(sctId, partitionIdentifier, true); //throw exception if not valid idsAssigned++; return sctId; } private String getDummySCTID(PartionIdentifier partitionIdentifier) throws SnomedUtilException { try { String sctIdBase = ++dummySequence + "0" + partitionIdentifier.ordinal(); String checkDigit = new VerhoeffCheckDigit().calculate(sctIdBase); return sctIdBase + checkDigit; } catch (CheckDigitException e) { throw new SnomedUtilException ("Failed to generate dummy sctid",e); } } public String finish() { try { availableSctIds.close(); } catch (Exception e){} return "IdGenerator supplied " + idsAssigned + " sctids."; } }
31.9375
106
0.749511
449be0abca393eb3e600b533fde35800046dca36
7,017
package igtools.analyses.recurrences.expcomp; import java.util.Map; import java.util.TreeMap; import igtools.analyses.recurrences.distances.ProperMinimalRecurrenceDistancesExtractor; import igtools.common.distributions.DistributionUtils; import igtools.common.distributions.EstimatedDistribution; import igtools.common.distributions.distance.DistributionDistance; import igtools.dictionaries.elsa.IELSAIterator; public class KExpComp { public static EstimatedDistribution getExponentialEstimator(Map<Double,Double> it_distr, double resampleP){ double[][] aa = DistributionUtils.toArray(it_distr); if(resampleP>0.0){ DistributionUtils.resample(aa, resampleP); } EstimatedDistribution estimator = new EstimatedDistribution.FExponentialBased(); //EstimatedDistribution gestimator = new EstimatedDistribution.ExponentialBased(); EstimatedDistribution gestimator = new EstimatedDistribution.GeometricBased(); //Map<Double,Double> e_distr = new TreeMap<Double,Double>(); //double[][] aa = DistributionUtils.toArray(it_distr); try{//sometimes it sucks estimator.estimateDistrParameter(aa); }catch(Exception e){ gestimator.estimateDistrParameter(aa); } return estimator; } public static Map<Double,Double> estimateExponential(Map<Double,Double> it_distr, double resampleP){ double[][] aa = DistributionUtils.toArray(it_distr); if(resampleP>0.0){ DistributionUtils.resample(aa, resampleP); } EstimatedDistribution estimator = new EstimatedDistribution.FExponentialBased(); //EstimatedDistribution gestimator = new EstimatedDistribution.ExponentialBased(); EstimatedDistribution gestimator = new EstimatedDistribution.GeometricBased(); Map<Double,Double> e_distr = new TreeMap<Double,Double>(); //double[][] aa = DistributionUtils.toArray(it_distr); try{//sometimes it sucks estimator.estimateDistrParameter(aa); for(Map.Entry<Double, Double> en : it_distr.entrySet()){ e_distr.put(en.getKey(), estimator.getValue(en.getKey())); } }catch(Exception e){ gestimator.estimateDistrParameter(aa); for(Map.Entry<Double, Double> en : it_distr.entrySet()){ e_distr.put(en.getKey(), gestimator.getValue(en.getKey())); } } return e_distr; } /** * Return the distance to the estimated exponential distribution * * @param it * @param dd * @return */ public static Double distanceToExponential(IELSAIterator it, DistributionDistance dd, double resampleP){ if(it.multiplicity() > 1){ Map<Double,Double> it_distr = ProperMinimalRecurrenceDistancesExtractor.factory(false, true).recurrenceDistanceDistributionMap(it); //DistributionUtils.normalize(it_distr); double[][] aa = DistributionUtils.toArray(it_distr); if(resampleP>0.0){ DistributionUtils.resample(aa, resampleP); } EstimatedDistribution estimator = new EstimatedDistribution.FExponentialBased(); //EstimatedDistribution gestimator = new EstimatedDistribution.ExponentialBased(); EstimatedDistribution gestimator = new EstimatedDistribution.GeometricBased(); Map<Double,Double> e_distr = new TreeMap<Double,Double>(); //double[][] aa = DistributionUtils.toArray(it_distr); try{//sometimes it sucks estimator.estimateDistrParameter(aa); for(Map.Entry<Double, Double> en : it_distr.entrySet()){ e_distr.put(en.getKey(), estimator.getValue(en.getKey())); } }catch(Exception e){ gestimator.estimateDistrParameter(aa); for(Map.Entry<Double, Double> en : it_distr.entrySet()){ e_distr.put(en.getKey(), gestimator.getValue(en.getKey())); } } DistributionUtils.normalize(it_distr); DistributionUtils.normalize(e_distr); return dd.distance(it_distr, e_distr); } return 0.0; } public static Double exponentialDistance(IELSAIterator it, DistributionDistance dd, double resampleP){ if(it.multiplicity() > 1){ Map<Double,Double> it_distr = ProperMinimalRecurrenceDistancesExtractor.factory(false, true).recurrenceDistanceDistributionMap(it); DistributionUtils.normalize(it_distr); double[][] aa = DistributionUtils.toArray(it_distr); if(resampleP>0.0){ DistributionUtils.resample(aa, resampleP); } EstimatedDistribution estimator = new EstimatedDistribution.FExponentialBased(); //EstimatedDistribution gestimator = new EstimatedDistribution.ExponentialBased(); EstimatedDistribution gestimator = new EstimatedDistribution.GeometricBased(); Map<Double,Double> e_distr = new TreeMap<Double,Double>(); //double[][] aa = DistributionUtils.toArray(it_distr); try{//sometimes it sucks estimator.estimateDistrParameter(aa); for(Map.Entry<Double, Double> en : it_distr.entrySet()){ e_distr.put(en.getKey(), estimator.getValue(en.getKey())); } }catch(Exception e){ gestimator.estimateDistrParameter(aa); for(Map.Entry<Double, Double> en : it_distr.entrySet()){ e_distr.put(en.getKey(), gestimator.getValue(en.getKey())); } } //DistributionUtils.normalize(e_distr); return dd.distance(e_distr, it_distr); } return 0.0; } // public static Double distanceToExponential(IELSAIterator it, DistributionDistance dd, double resampleP, double minCoRecc){ // if(it.multiplicity() > 1){ // double[][] it_distr = ProperMinimalRecurrenceDistancesExtractor.factory(false, true).recurrenceDistanceDistribution(it); // DistributionUtils.normalize(it_distr); // DistributionUtils.resample(it_distr, resampleP); // // double[][] e_distr = expGDistr(it_distr); // // // // // return dd.distance(it_distr, e_distr); // } // return 0.0; // } // // // public static boolean checkMinCoRecc(double[][] distr){ // for(int i=0; i<distr.length; i++){ // // } // return false; // } public static double[][] expGDistr(double[][] idistr){ EstimatedDistribution estimator = new EstimatedDistribution.FExponentialBased(); EstimatedDistribution gestimator = new EstimatedDistribution.GeometricBased(); double[][] odistr = new double[idistr.length][2]; try{//sometimes it sucks estimator.estimateDistrParameter(idistr); for(int i=0; i<idistr.length; i++){ odistr[i][1] =gestimator.getValue(odistr[i][0]); } }catch(Exception e){ gestimator.estimateDistrParameter(idistr); for(int i=0; i<idistr.length; i++){ odistr[i][1] =gestimator.getValue(odistr[i][0]); } } return odistr; } public static double expGDistrFirst(double[][] idistr){ EstimatedDistribution estimator = new EstimatedDistribution.FExponentialBased(); EstimatedDistribution gestimator = new EstimatedDistribution.GeometricBased(); double[][] odistr = new double[idistr.length][2]; try{//sometimes it sucks estimator.estimateDistrParameter(idistr); return estimator.getValue(odistr[0][0]); }catch(Exception e){ gestimator.estimateDistrParameter(idistr); return gestimator.getValue(odistr[0][0]); } } }
30.376623
134
0.724384
bfee648d7f243aa410611219248115358faf8dce
658
package com.androidopentutorials.sqlite.db; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class EmployeeDBDAO { protected SQLiteDatabase database; private DataBaseHelper dbHelper; private Context mContext; public EmployeeDBDAO(Context context) { this.mContext = context; dbHelper = DataBaseHelper.getHelper(mContext); open(); } public void open() throws SQLException { if(dbHelper == null) dbHelper = DataBaseHelper.getHelper(mContext); database = dbHelper.getWritableDatabase(); } /*public void close() { dbHelper.close(); database = null; }*/ }
21.933333
49
0.759878
ba45902faa69d7e122bcf95ae0d346aff6f0e2f3
3,886
package jacle.common.time; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; /** * An implementation of {@link TimeProvider} that is useful for unit testing * * @author rkenney */ public class MockTimeProvider implements TimeProvider { Date currentTime; @Override public Date getTime() { return this.currentTime; } /** * Creates a mock time instance initialized to the current system time */ public MockTimeProvider() { this.currentTime = new Date(); } /** * Creates a mock time instance initialized to the provided time * * @param date * The initial time of the object */ public MockTimeProvider(Date date) { this.currentTime = date; } /** * Adds to the mock clock time * * @param incrementCount * The number of units to increment * @param incrementUnits * The units to increment by * * @return The time after incrementing this object */ public Date add(long incrementCount, TimeUnit incrementUnits) { this.currentTime = new Date(this.currentTime.getTime() + incrementUnits.toMillis(incrementCount)); return this.currentTime; } /** * Adds to the mock clock time * * @param millis Duration to add * * @return The time after incrementing this object */ public Date addMillis(long millis) { return add(millis, TimeUnit.MILLISECONDS); } /** * Adds to the mock clock time * * @param seconds Duration to add * * @return The time after incrementing this object */ public Date addSeconds(long seconds) { return add(seconds, TimeUnit.SECONDS); } /** * Adds to the mock clock time * * @param minutes Duration to add * * @return The time after incrementing this object */ public Date addMinutes(long minutes) { return add(minutes, TimeUnit.MINUTES); } /** * Adds to the mock clock time * * @param hours Duration to add * * @return The time after incrementing this object */ public Date addHours(long hours) { return add(hours, TimeUnit.HOURS); } /** * Adds days to the mock clock time, according to a calendar. Note that this * means that the increment may not be the standard number of seconds (due * to leap seconds). * * @param days Duration to add * * @return The time after incrementing this object */ public Date addDaysByCalendar(int days) { return addByCalendar(days, Calendar.DATE); } /** * Adds days to the mock clock time, according to a calendar. Note that this * means that the increment may not be the standard number of days or seconds (due * to leap days and seconds). * * @param weeks Duration to add * * @return The time after incrementing this object */ public Date addWeeksByCalendar(int weeks) { return addByCalendar(weeks, Calendar.WEEK_OF_YEAR); } /** * Adds months to the mock clock time, according to a calendar. Note that this * means that the increment may not be the standard number of days or seconds (due * to leap days and seconds). * * @param months Duration to add * * @return The time after incrementing this object */ public Date addMonthsByCalendar(int months) { return addByCalendar(months, Calendar.MONTH); } /** * Adds years to the mock clock time, according to a calendar. Note that this * means that the increment may not be the standard number of days or seconds (due * to leap days and seconds). * * @param years Duration to add * * @return The time after incrementing this object */ public Date addYearsByCalendar(int years) { return addByCalendar(years, Calendar.YEAR); } private Date addByCalendar(int count, int calendarUnit) { Calendar calendar = Calendar.getInstance(); calendar.setTime(this.currentTime); calendar.add(calendarUnit, count); this.currentTime = calendar.getTime(); return this.currentTime; } }
24.751592
100
0.694802
557e47d20abdd1622fc5fc83ffbf1eccd5fbb6df
3,663
package jcop.lang; import java.lang.reflect.AccessibleObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public final class PartialMethod extends AccessibleObject implements Member{ private String declaringClass; private String returnType; private Layer _layer; private String name; private int modifier; private String[] exceptionTypes; private String[] params; private String internalSignature; public PartialMethod( Layer _layer, String name, String declaringClass, int modifier, String returnType, String[] params, String[] exceptions, String internalSignature ) { this._layer = _layer; this.name = name; this.declaringClass = declaringClass; this.modifier = modifier; this.returnType = returnType; this.params = params; this.exceptionTypes = exceptions; this.internalSignature = internalSignature; } public Class<?> getDeclaringClass() { return getClassFor(declaringClass); } public Layer getDefiningLayer() { return _layer; } public int getModifiers() { return modifier; } public String getName() { return name; } public boolean isSynthetic() { return false; } public Class[] getExceptionTypes() { Class[] exceptions = new Class[exceptionTypes.length]; for (int i = 0; i < exceptionTypes.length; i++) { String exception = exceptionTypes[i]; exceptions[i] = getClassFor(exception); } return exceptions; } public Class getReturnType() { return getClassFor(returnType); } private Class getClassFor(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { return null; } } private Class[] getParamTypes(Object... args) { List<Class> paramTypes = new ArrayList<Class>(); paramTypes.add(getDeclaringClass()); paramTypes.add(Composition.class); for (String arg : params) { if (arg.startsWith("@primitive.")) { String primType = arg.substring("@primitive.".length()); paramTypes.add(getPrimitiveType(primType)); } else { try { paramTypes.add(Class.forName(arg)); } catch(Exception e) { } } } return paramTypes.toArray(new Class[]{}); } public Class getPrimitiveType(String name) { if (name.equals("byte")) return byte.class; if (name.equals("short")) return short.class; if (name.equals("int")) return int.class; if (name.equals("long")) return long.class; if (name.equals("char")) return char.class; if (name.equals("float")) return float.class; if (name.equals("double")) return double.class; if (name.equals("boolean")) return boolean.class; if (name.equals("void")) return void.class; throw new IllegalArgumentException(); } private Object[] getInternalArgs(Object target, Object[] args) { Object[] newArgs = new Object[args.length + 2]; newArgs[0] = target; newArgs[1] = Composition.current(); System.arraycopy(args, 0, newArgs, 2, args.length); return newArgs; } public Object invoke(Object target, Object... args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method partialMethod = _layer.getClass().getMethod(internalSignature, getParamTypes()); return partialMethod.invoke(_layer, getInternalArgs(target, args)); } }
25.978723
182
0.667213
4429f02154f9b6c841094404971e8a122fb72ffa
5,405
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.mediapackage.elementbuilder; import org.opencastproject.mediapackage.MediaPackageElement; import org.opencastproject.mediapackage.MediaPackageElementFlavor; import org.opencastproject.mediapackage.MediaPackageSerializer; import org.opencastproject.mediapackage.UnsupportedElementException; import org.w3c.dom.Node; import java.net.URI; /** * An element builder plugin is an object that is able to recognize one ore more filetypes slated for ingest into * Opencast. * <p> * <strong>Implementation note:</strong> Builder plugins may be stateful. They are intended to be used as throw-away * objects. */ @Deprecated public interface MediaPackageElementBuilderPlugin { /** * This method is called once in a plugin's life cycle. When this method is called, the plugin can make sure that * everything is in place for it to work properly. If this isn't the case, it should throw an exception so it will no * longer be bothered by the element builder. * * @throws Exception * if some unrecoverable state is reached */ void init() throws Exception; /** * This method is called before the plugin is abandoned by the element builder. */ void destroy(); /** * This method is called if the media package builder tries to create a new media package element of type * <code>elementType</code>. * <p> * Every registered builder plugin will then be asked whether it is able to create a media package element from the * given element type. If this is the case for a plugin, it will then be asked to create such an element by a call to * {@link #newElement(org.opencastproject.mediapackage.MediaPackageElement.Type ,MediaPackageElementFlavor)}. * </p> * * @param type * the type * @param flavor * the element flavor * @return <code>true</code> if the plugin is able to create such an element */ boolean accept(MediaPackageElement.Type type, MediaPackageElementFlavor flavor); /** * This method is called on every registered media package builder plugin until one of these plugins returns * <code>true</code>. If no plugin recognises the file, it is rejected. * <p> * The parameters <code>type</code> and <code>flavor</code> may be taken as strong hints and may both be * <code>null</code>. * </p> * <p> * Implementers schould return the correct mime type for the given file if they are absolutely sure about the file. * Otherwise, <code>null</code> should be returned. * </p> * * @param uri * the element location * @param type * the element type * @param flavor * the element flavor * @return <code>true</code> if the plugin can handle the element */ boolean accept(URI uri, MediaPackageElement.Type type, MediaPackageElementFlavor flavor); /** * This method is called while the media package builder parses a media package manifest. * <p> * Every registered builder plugin will then be asked, whether it is able to create a media package element from the * given element definition. * </p> * <p> * The element must then be constructed and returned in the call to * {@link #elementFromManifest(Node, MediaPackageSerializer)}. * </p> * * @param elementNode * the node * @return <code>true</code> if the plugin is able to create such an element */ boolean accept(Node elementNode); /** * Creates a media package element from the given url that was previously accepted. * * @param uri * the element location * @return the new media package element * @throws UnsupportedElementException * if creating the media package element fails */ MediaPackageElement elementFromURI(URI uri) throws UnsupportedElementException; /** * Creates a media package element from the DOM element. * * @param elementNode * the DOM node * @param serializer * the media package serializer * @return the media package element * @throws UnsupportedElementException */ MediaPackageElement elementFromManifest(Node elementNode, MediaPackageSerializer serializer) throws UnsupportedElementException; /** * Creates a new media package element of the specified type. * * @param type * the element type * @param flavor * the element flavor * @return the new media package element */ MediaPackageElement newElement(MediaPackageElement.Type type, MediaPackageElementFlavor flavor); }
35.794702
119
0.710268
fa4ec7c9ee19fd0853bf4035d647dac58575fc75
300
package org.mitre.svmp.common; import org.mitre.svmp.common.StateMachine.STATE; /** * @author Joe Portner */ public interface StateObserver { // the observer receives a notification when the connection state changes public void onStateChange(STATE oldState, STATE newState, int resID); }
25
77
0.76
4ed59fd229ddea5ce2d5b91c5544a8e0ac3bcc19
4,303
package com.arise.endpoint.service; import com.alibaba.fastjson.JSON; import com.arise.base.config.Components; import com.arise.endpoint.JsonUtils; import com.arise.endpoint.service.dto.EndpointResponse; import com.arise.endpoint.service.dto.RouteDto; import com.arise.redis.AsyncRedisClient; import com.arise.server.route.RouteBean; import com.arise.server.route.manager.RouteManager; import io.netty.channel.Channel; import io.netty.handler.codec.http.FullHttpRequest; import lombok.extern.slf4j.Slf4j; import java.util.Map; import java.util.function.BiConsumer; import java.util.stream.Collectors; import static com.arise.endpoint.service.dto.EndpointResponse.standJsonResp; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static io.netty.handler.codec.http.HttpResponseStatus.OK; /** * @Author: wy * @Date: Created in 14:05 2021-07-02 * @Description: * @Modified: By: */ @Slf4j public enum Services implements BiConsumer<FullHttpRequest, Channel> { route_refresh { @Override public void accept(FullHttpRequest request, Channel channel) { AsyncRedisClient client = Components.get(AsyncRedisClient.class); RouteManager routeManager = Components.get(RouteManager.class); client.asyncExec((e, throwable) -> e.hgetall("ROUTE").whenComplete((v, ex) -> { if (ex != null) { channel.writeAndFlush(standJsonResp(new EndpointResponse(ex.getMessage()), INTERNAL_SERVER_ERROR)); return; } routeManager.clear(); v.values().forEach(x -> { //更新路由 routeManager.addRoute((RouteBean) x); }); channel.writeAndFlush(standJsonResp(new EndpointResponse("route refresh successful"), OK)); })); } }, route_get { @Override public void accept(FullHttpRequest request, Channel channel) { AsyncRedisClient client = Components.get(AsyncRedisClient.class); client.asyncExec((e, throwable) -> e.hgetall("ROUTE").whenComplete((v, ex) -> { if (ex != null) { channel.writeAndFlush(standJsonResp(new EndpointResponse("route get fail"), INTERNAL_SERVER_ERROR)); return; } channel.writeAndFlush(standJsonResp(new EndpointResponse("route get successful", v.values()), OK)); })); } }, route_put { @Override public void accept(FullHttpRequest request, Channel channel) { AsyncRedisClient client = Components.get(AsyncRedisClient.class); String s = JsonUtils.toJson(request.content()); RouteDto dto = JSON.parseObject(s, RouteDto.class); log.info("route_put,数目:{}", dto.getRoutes().size()); Map<String, Object> map = dto.getRoutes().stream() .collect(Collectors.toMap(RouteBean::getId, v -> v, (v1, v2) -> v1)); client.asyncExec((e, throwable) -> e.hset("ROUTE", map).whenComplete((v, ex) -> { if (ex != null) { channel.writeAndFlush(standJsonResp(new EndpointResponse("server error"), INTERNAL_SERVER_ERROR)); } channel.writeAndFlush(standJsonResp(new EndpointResponse("route put successful"), OK)); } )); } }, route_clear { @Override public void accept(FullHttpRequest request, Channel channel) { AsyncRedisClient client = Components.get(AsyncRedisClient.class); log.info("开始清空所有路由"); client.asyncExec((e, throwable) -> e.del("ROUTE").whenComplete((v, ex) -> { if (ex != null) { channel.writeAndFlush(standJsonResp(new EndpointResponse("server error"), INTERNAL_SERVER_ERROR)); } channel.writeAndFlush(standJsonResp(new EndpointResponse("route clear successful"), OK)); } )); } } }
43.464646
134
0.590053
f7ce31487d66e0060cebbc79d6f745fa325739de
1,782
package com.saucedo.molino.utils.parse.alamcen; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.saucedo.molino.almacen.models.RegistroIngreso; import com.saucedo.molino.utils.parse.EmpleadoParse; import com.saucedo.molino.utils.parse.IParse; import com.saucedo.molino_json_models.almacen.JRegistroIngreso; @Service public class RegistroIngresoParse implements IParse<RegistroIngreso,JRegistroIngreso> { @Autowired CamionProductorParse camionParse; @Autowired EmpleadoParse empleadoParse; @Override public RegistroIngreso parseJsonToEntity(JRegistroIngreso json) { RegistroIngreso entity=null; if(json!=null) { entity = new RegistroIngreso(); entity.setId(json.getId()); entity.setNumeroSacos(json.getNumeroSacos()); entity.setKilosPorSaco(json.getKilosPorSaco()); entity.setTotalKilos(json.getKilosPorSaco()); entity.setFecha(json.getFecha()); entity.setHora(json.getHora()); entity.setEmpleado(this.empleadoParse.parseJsonToEntity(json.getEmpleado())); entity.setTransporte(this.camionParse.parseJsonToEntity(json.getTransporte())); } return entity; } @Override public JRegistroIngreso parseEntityToJson(RegistroIngreso entity) { JRegistroIngreso json =null; if(entity!=null) { json=new JRegistroIngreso(); json.setId(entity.getId()); json.setNumeroSacos(entity.getNumeroSacos()); json.setKilosPorSaco(entity.getKilosPorSaco()); json.setTotalKilos(entity.getKilosPorSaco()); json.setFecha(entity.getFecha()); json.setHora(entity.getHora()); json.setEmpleado(this.empleadoParse.parseEntityToJson(entity.getEmpleado())); json.setTransporte(this.camionParse.parseEntityToJson(entity.getTransporte())); } return json; } }
33.622642
87
0.785634
6d5360dd19cc03814ede230ea4627ffe924a32d2
1,798
package com.zupacademy.propostas.cartao.carteira; import com.zupacademy.propostas.cartao.Cartao; import com.zupacademy.propostas.cartao.CartaoRepository; import com.zupacademy.propostas.commos.exceptions.NotFoundException; import io.opentracing.Span; import io.opentracing.Tracer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.util.UriComponentsBuilder; import javax.transaction.Transactional; import javax.validation.Valid; import java.net.URI; @RestController @RequestMapping("/cartoes") public class CarteiraController { @Autowired private CartaoRepository cartaoRepository; @Autowired private NotificaCarteira notificaCarteira; @Autowired private Tracer tracer; @PostMapping("/{id}/carteiras") @Transactional @ResponseStatus(HttpStatus.CREATED) public ResponseEntity adicionaCarteira(@PathVariable("id") Long id, @RequestBody @Valid CarteiraRequest carteiraRequest, UriComponentsBuilder uriBuilder){ Cartao cartao = cartaoRepository.findById(id).orElseThrow(() -> new NotFoundException("Cartão", "id", id)); Carteira carteira = carteiraRequest.toModel(cartao); cartao.adicionarCarteira(carteira, notificaCarteira); cartaoRepository.save(cartao); Span activeSpan = tracer.activeSpan(); activeSpan.setBaggageItem("user.email", cartao.getProposta().getEmail()); URI uri = uriBuilder.path("/cartoes/{idCartao}/carteiras/{idCarteira}").build(cartao.getId(), carteira.getUuid()); return ResponseEntity.created(uri).build(); } }
35.96
158
0.774194
e4d82d3708e36535c12e9e36614f76b879435f5c
719
import java.util.HashMap; import java.util.Map; public class MapBaseDuplicateCheckTest { public static void main(String[] args) { // Map(key, value) Map<String, Integer> m = new HashMap<>(); String[] sample = { "to", "be", "or", "not", "to", "be", "is", "a", "problem", "to" }; for(String s : sample){ // m이라는 Map에서 sample 에서 하나씩 넘어온 문자열을 key값에 검색해서 // value값을 freq에 셋팅 Integer freq = m.get(s); m.put(s, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + "개의 단어가 있습니다!"); System.out.println(m.containsKey("to")); System.out.println(m.isEmpty()); System.out.println(m); } }
28.76
94
0.529903
e16a8ec721552233da0141edb7f3cb0af0cc040e
260
package stu.napls.copdmanage.service; import stu.napls.copdmanage.model.User; import java.util.List; /** * @author Yepeng Ding */ public interface UserService { User findById(Long id); List<User> findAllUser(); User createUser(User user); }
15.294118
39
0.707692
27e0c7511b9a77b42ef3f95d6e14e89f27ff48de
1,189
package com.bitdubai.fermat_cbp_plugin.layer.negotiation.customer_broker_sale.developer.bitdubai.version_1.structure; import com.bitdubai.fermat_api.layer.all_definition.enums.FiatCurrency; import com.bitdubai.fermat_api.layer.world.interfaces.Currency; import com.bitdubai.fermat_cbp_api.all_definition.enums.PaymentType; import com.bitdubai.fermat_cbp_api.all_definition.negotiation.NegotiationPaymentCurrency; import java.util.UUID; /** * Created by angel on 07/12/15. */ public class NegotiationPaymentCurrencySale implements NegotiationPaymentCurrency { private final UUID paymentCurrencyId; private final Currency currency; private final PaymentType type; public NegotiationPaymentCurrencySale(UUID paymentCurrencyId, Currency currency, PaymentType type){ this.paymentCurrencyId = paymentCurrencyId; this.currency = currency; this.type = type; } @Override public UUID getPaymentCurrencyId() { return this.paymentCurrencyId; } @Override public Currency getPaymentCurrency() { return this.currency; } @Override public PaymentType getPaymentType() { return this.type; } }
30.487179
117
0.761985
4a65ecff696fa7bda10f5eacc3e43dbbe143ea67
3,664
package b.l.a.c.f.i; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.RandomAccess; public final class b6 extends h4<String> implements RandomAccess, c6 { /* renamed from: j reason: collision with root package name */ public static final b6 f3496j; /* renamed from: i reason: collision with root package name */ public final List<Object> f3497i; static { b6 b6Var = new b6(10); f3496j = b6Var; b6Var.f3587h = false; } public b6() { this(10); } public b6(int i2) { this.f3497i = new ArrayList(i2); } public b6(ArrayList<Object> arrayList) { this.f3497i = arrayList; } public static String l(Object obj) { if (obj instanceof String) { return (String) obj; } if (obj instanceof t4) { t4 t4Var = (t4) obj; return t4Var.l() == 0 ? "" : t4Var.y(w5.a); } Charset charset = w5.a; return new String((byte[]) obj, w5.a); } public final /* bridge */ /* synthetic */ void add(int i2, Object obj) { d(); this.f3497i.add(i2, (String) obj); this.modCount++; } public final boolean addAll(int i2, Collection<? extends String> collection) { d(); if (collection instanceof c6) { collection = ((c6) collection).g(); } boolean addAll = this.f3497i.addAll(i2, collection); this.modCount++; return addAll; } public final boolean addAll(Collection<? extends String> collection) { return addAll(size(), collection); } public final void clear() { d(); this.f3497i.clear(); this.modCount++; } /* renamed from: e */ public final String get(int i2) { Object obj = this.f3497i.get(i2); if (obj instanceof String) { return (String) obj; } if (obj instanceof t4) { t4 t4Var = (t4) obj; String y = t4Var.l() == 0 ? "" : t4Var.y(w5.a); if (t4Var.D()) { this.f3497i.set(i2, y); } return y; } byte[] bArr = (byte[]) obj; Charset charset = w5.a; String str = new String(bArr, w5.a); boolean z = false; if (d8.a.a(0, bArr, 0, bArr.length) == 0) { z = true; } if (z) { this.f3497i.set(i2, str); } return str; } public final c6 f() { return this.f3587h ? new s7(this) : this; } public final List<?> g() { return Collections.unmodifiableList(this.f3497i); } public final /* bridge */ /* synthetic */ v5 h(int i2) { if (i2 >= size()) { ArrayList arrayList = new ArrayList(i2); arrayList.addAll(this.f3497i); return new b6((ArrayList<Object>) arrayList); } throw new IllegalArgumentException(); } public final Object j(int i2) { return this.f3497i.get(i2); } public final /* bridge */ /* synthetic */ Object remove(int i2) { d(); Object remove = this.f3497i.remove(i2); this.modCount++; return l(remove); } public final /* bridge */ /* synthetic */ Object set(int i2, Object obj) { d(); return l(this.f3497i.set(i2, (String) obj)); } public final int size() { return this.f3497i.size(); } public final void w(t4 t4Var) { d(); this.f3497i.add(t4Var); this.modCount++; } }
25.444444
82
0.530841
8303f27d79ee9f0c7a01f3b16c02dec9767b2a4c
1,441
package entities; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author 794471 * * object that represents the relationship between an event and a foster/volunteer */ @Entity @Table(name = "eventstaff") public class EventStaff implements Serializable { private static final long serialVersionUID = -41211081083931205L; @Id @Column(name = "eventid") private int eventid; @Id @Column(name = "staffid") private int staffid; public int getEventid() { return eventid; } public void setEventid(int eventid) { this.eventid = eventid; } public int getStaffid() { return staffid; } public void setStaffid(int staffid) { this.staffid = staffid; } // auto-generated by Eclipse @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + eventid; result = prime * result + staffid; return result; } // auto-generated by Eclipse @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventStaff other = (EventStaff) obj; if (eventid != other.eventid) return false; if (staffid != other.staffid) return false; return true; } }
18.0125
83
0.655795
61b1c8f9ecbacfe6ab24907f692412588e110334
2,683
/** * Copyright 2006 OCLC Online Computer Library Center 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.oclc.oai.server.crosswalk; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Properties; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.oclc.oai.server.verb.OAIInternalServerError; /** * Convert native "item" to xsl. In this case, the native "item" * is assumed to already be formatted as an OAI <record> element, * with the possible exception that multiple metadataFormats may * be present in the <metadata> element. The "crosswalk", merely * involves pulling out the one that is requested. */ public class Copyxsl extends XSLTCrosswalk { // private Transformer transformer = null; /** * The constructor assigns the schemaLocation associated with this crosswalk. Since * the crosswalk is trivial in this case, no properties are utilized. * * @param properties properties that are needed to configure the crosswalk. */ public Copyxsl(Properties properties) throws OAIInternalServerError { super(properties, "http://www.w3.org/1999/XSL/Transform http://www.w3.org/1999/XSL/Transform.xsd", null); try { String xsltName = properties.getProperty("Copyxsl.xsltName"); if (xsltName != null) { StreamSource xslSource = new StreamSource(new FileInputStream(xsltName)); TransformerFactory tFactory = TransformerFactory.newInstance(); this.transformer = tFactory.newTransformer(xslSource); } } catch (Exception e) { e.printStackTrace(); throw new OAIInternalServerError(e.getMessage()); } } /** * Can this nativeItem be represented in DC format? * @param nativeItem a record in native format * @return true if DC format is possible, false otherwise. */ public boolean isAvailableFor(Object nativeItem) { ArrayList list = (ArrayList)nativeItem; return list.contains("xsl"); } }
41.276923
110
0.686918
5de0b6a76cc8b285d7293829aafbc70abe48f78d
1,469
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.communityprofile.mappers; /** * ProjectCollectionMemberMapper provides property name mapping for project collections. */ public class ProjectCollectionMemberMapper { public static final String QUALIFIED_NAME_PROPERTY_NAME = "qualifiedName"; /* from Referenceable entity */ public static final String NAME_PROPERTY_NAME = "name"; /* from Project entity */ public static final String DESCRIPTION_PROPERTY_NAME = "description"; /* from Project entity */ public static final String START_DATE_PROPERTY_NAME = "startDate"; /* from Project entity */ public static final String PLANNED_END_DATE_PROPERTY_NAME = "plannedEndDate"; /* from Project entity */ public static final String STATUS_PROPERTY_NAME = "status"; /* from Project entity */ public static final String MEMBERSHIP_RATIONALE_PROPERTY_NAME = "resourceUse"; /* from ResourceList classification */ public static final String WATCH_STATUS_PROPERTY_NAME = "watchResource"; /* from ResourceList classification */ public static final String ADDITIONAL_PROPERTIES_PROPERTY_NAME = "additionalProperties"; /* from Referenceable entity */ }
73.45
136
0.674609
a5e2682a66e93f5618c8b3decc9a1f508027297e
2,641
package binarytree; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import binarytrees.BstClosestNode; import binarytrees.TreeNode; public class BstClosestNodeTest { @Test public void emptyTree() { assertNull(BstClosestNode.findClosestNode(null, null)); } @Test public void treeWithOnlyRoot() { TreeNode<Integer> root = new TreeNode<Integer>(10); assertEquals(null, BstClosestNode.findClosestNode(root, root)); } @Test public void treeWithNoInorderPredecessorAndSubtreeInorderSuccessor() { TreeNode<Integer> subTreeNode3 = new TreeNode<Integer>(72); TreeNode<Integer> subTreeNode2 = new TreeNode<Integer>(73); subTreeNode2.setLeft(subTreeNode3); TreeNode<Integer> subTreeNode1 = new TreeNode<Integer>(74); subTreeNode1.setLeft(subTreeNode2); TreeNode<Integer> rootLeftRight = new TreeNode<Integer>(75); rootLeftRight.setLeft(subTreeNode1); TreeNode<Integer> rootLeft = new TreeNode<Integer>(100); rootLeft.setRight(rootLeftRight); TreeNode<Integer> rootRightLeft = new TreeNode<Integer>(300); TreeNode<Integer> rootRightRight = new TreeNode<Integer>(450); TreeNode<Integer> rootRight = new TreeNode<Integer>(400); rootRight.setLeft(rootRightLeft); rootRight.setRight(rootRightRight); TreeNode<Integer> root = new TreeNode<Integer>(250); root.setLeft(rootLeft); root.setRight(rootRight); TreeNode<Integer> answer = binarytrees.BstClosestNode.findClosestNode( root, rootLeft); System.out.println(answer.getValue()); assertEquals(subTreeNode3, answer); } @Test public void treeWithNoInorderSuccessorAndSubtreeInorderPredecessor() { TreeNode<Integer> subTreeNode3 = new TreeNode<Integer>(54); TreeNode<Integer> subTreeNode2 = new TreeNode<Integer>(53); subTreeNode2.setRight(subTreeNode3); TreeNode<Integer> subTreeNode1 = new TreeNode<Integer>(52); subTreeNode1.setRight(subTreeNode2); TreeNode<Integer> rootLeftLeft = new TreeNode<Integer>(50); rootLeftLeft.setRight(subTreeNode1); TreeNode<Integer> rootLeft = new TreeNode<Integer>(100); rootLeft.setLeft(rootLeftLeft); TreeNode<Integer> rootRightLeft = new TreeNode<Integer>(300); TreeNode<Integer> rootRightRight = new TreeNode<Integer>(450); TreeNode<Integer> rootRight = new TreeNode<Integer>(400); rootRight.setLeft(rootRightLeft); rootRight.setRight(rootRightRight); TreeNode<Integer> root = new TreeNode<Integer>(250); root.setLeft(rootLeft); root.setRight(rootRight); TreeNode<Integer> answer = binarytrees.BstClosestNode.findClosestNode( root, rootLeft); assertEquals(subTreeNode3, answer); } }
30.709302
72
0.771299
548c2ac5f7b12e4c9c61e93da6f0260a2c79549a
1,690
package edu.cs4730.readprofile; import android.os.Bundle; import android.provider.ContactsContract; import android.app.Fragment; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * This reads a profile and displays all the information to the screen. * */ public class MainFragment extends Fragment { Button call; TextView output; public MainFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View myView = inflater.inflate(R.layout.fragment_main, container, false); myView.findViewById(R.id.btn).setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { getprofile(); } }); output = (TextView) myView.findViewById(R.id.ouput); return myView; } public void getprofile() { Cursor c = getActivity().getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null); int count = c.getCount(); String[] columnNames = c.getColumnNames(); boolean b = c.moveToFirst(); int position = c.getPosition(); // if (count == 1 && position == 0) { for (int i = 0; i < count; i++) { for (int j = 0; j < columnNames.length; j++) { output.append("\n"+ columnNames[j] +" " + c.getString(c.getColumnIndex(columnNames[j])) ); } boolean b2 = c.moveToNext(); } // } c.close(); } }
24.852941
118
0.68284
39a40d652153326ef5eb6fa010c80dcefaf55962
3,982
package ca.uhn.fhir.batch2.coordinator; import ca.uhn.fhir.batch2.api.IJobStepWorker; import ca.uhn.fhir.batch2.api.VoidModel; import ca.uhn.fhir.batch2.model.JobDefinition; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @ExtendWith(MockitoExtension.class) class JobDefinitionRegistryTest { private JobDefinitionRegistry mySvc; @Mock private IJobStepWorker<TestJobParameters, VoidModel, TestJobStep2InputType> myFirstStep; @Mock private IJobStepWorker<TestJobParameters, TestJobStep2InputType, VoidModel> myLastStep; @BeforeEach void beforeEach() { mySvc = new JobDefinitionRegistry(); mySvc.addJobDefinition(JobDefinition .newBuilder() .setJobDefinitionId("A") .setJobDefinitionVersion(1) .setJobDescription("the description") .setParametersType(TestJobParameters.class) .addFirstStep("S1", "S1", TestJobStep2InputType.class, myFirstStep) .addLastStep("S2", "S2", myLastStep) .build()); mySvc.addJobDefinition(JobDefinition .newBuilder() .setJobDefinitionId("A") .setJobDefinitionVersion(2) .setJobDescription("the description") .setParametersType(TestJobParameters.class) .addFirstStep("S1", "S1", TestJobStep2InputType.class, myFirstStep) .addLastStep("S2", "S2", myLastStep) .build()); } @Test void testGetLatestJobDefinition() { assertEquals(2, mySvc.getLatestJobDefinition("A").orElseThrow(IllegalArgumentException::new).getJobDefinitionVersion()); } @Test void testGetJobDefinition() { assertEquals(1, mySvc.getJobDefinition("A", 1).orElseThrow(IllegalArgumentException::new).getJobDefinitionVersion()); assertEquals(2, mySvc.getJobDefinition("A", 2).orElseThrow(IllegalArgumentException::new).getJobDefinitionVersion()); } @Test void testEnsureStepsHaveUniqueIds() { try { mySvc.addJobDefinition(JobDefinition .newBuilder() .setJobDefinitionId("A") .setJobDefinitionVersion(2) .setJobDescription("The description") .setParametersType(TestJobParameters.class) .addFirstStep("S1", "S1", TestJobStep2InputType.class, myFirstStep) .addLastStep("S2", "S2", myLastStep) .build()); fail(); } catch (ConfigurationException e) { assertEquals("HAPI-2047: Multiple definitions for job[A] version: 2", e.getMessage()); } try { mySvc.addJobDefinition(JobDefinition .newBuilder() .setJobDefinitionId("A") .setJobDefinitionVersion(3) .setJobDescription("The description") .setParametersType(TestJobParameters.class) .addFirstStep("S1", "S1", TestJobStep2InputType.class, myFirstStep) .addLastStep("S1", "S2", myLastStep) .build()); fail(); } catch (ConfigurationException e) { assertEquals("HAPI-2046: Duplicate step[S1] in definition[A] version: 3", e.getMessage()); } try { mySvc.addJobDefinition(JobDefinition .newBuilder() .setJobDefinitionId("A") .setJobDefinitionVersion(2) .setParametersType(TestJobParameters.class) .addFirstStep("S1", "S1", TestJobStep2InputType.class, myFirstStep) .addLastStep("", "S2", myLastStep) .build()); fail(); } catch (IllegalArgumentException e) { assertEquals("No step ID specified", e.getMessage()); } } @Test public void getJobDefinitionOrThrowException() { String jobDefinitionId = "Ranch Dressing Expert"; int jobDefinitionVersion = 12; try { mySvc.getJobDefinitionOrThrowException(jobDefinitionId, jobDefinitionVersion); fail(); } catch (InternalErrorException e) { assertEquals("HAPI-2043: Unknown job definition ID[" + jobDefinitionId + "] version[" + jobDefinitionVersion + "]", e.getMessage()); } } }
31.603175
135
0.746861
aa49bd6688034124174c76161be70a34d6dd54dc
6,891
package Games.Hoppers.Controller; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.Label; import javafx.scene.layout.*; import javafx.stage.Stage; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import Solvers.BFS.Observer; import Games.Hoppers.Model.HoppersClientData; import Games.Hoppers.Model.HoppersModel; import java.io.IOException; import java.util.ArrayList; import java.util.Objects; public class HoppersController implements Observer<HoppersModel, HoppersClientData> { private final static String RESOURCES_DIR = "Images/"; private HoppersModel model; private final ArrayList<Button> buttonsList = new ArrayList<>(); private final Image redFrog = new Image(getClass().getResourceAsStream(RESOURCES_DIR+"red_frog.png")); private final Image greenFrog = new Image(getClass().getResourceAsStream(RESOURCES_DIR+"green_frog.png")); private final Image lilyPad = new Image(getClass().getResourceAsStream(RESOURCES_DIR+"lily_pad.png")); private final Image water = new Image(getClass().getResourceAsStream(RESOURCES_DIR+"water.png")); @FXML private BorderPane hoppersBorderPane; @FXML private Label topLabel; @FXML private ComboBox<String> puzzleChoices; public void initialize(){ hoppersBorderPane.setStyle("-fx-background-color: #0091ea;"); ObservableList<String> list = FXCollections.observableArrayList("Puzzle 1", "Puzzle 2", "Puzzle 3", "Puzzle 4", "Puzzle 5", "Puzzle 6", "Puzzle 7"); puzzleChoices.setItems(list); String filename = "src/Games/Hoppers/Resources/hoppers-7.txt"; try { this.model = new HoppersModel(filename); model.addObserver(this); } catch (IOException e){ System.out.println("Can't open file"); } //clear the buttonsList for the new stage and make the new stage this.buttonsList.clear(); //create layouts and buttons this.topLabel.setText("Loaded puzzle"); GridPane gridPane = new GridPane(); //center for (int row=0; row<this.model.getCurrentConfig().getNumRows(); ++row) { for (int col=0; col<this.model.getCurrentConfig().getNumColumns(); ++col) { int tempRow = row; int tempCol = col; Button button = new Button(); if(this.model.getCurrentConfig().getBoard()[row][col]=='.'){ button.setGraphic(new ImageView(lilyPad)); } else if(this.model.getCurrentConfig().getBoard()[row][col]=='G'){ button.setGraphic(new ImageView(greenFrog)); } else if(this.model.getCurrentConfig().getBoard()[row][col]=='R'){ button.setGraphic(new ImageView(redFrog)); } else if(this.model.getCurrentConfig().getBoard()[row][col]=='*'){ button.setGraphic(new ImageView(water)); } button.setMinSize(75, 75); button.setMaxSize(75, 75); this.buttonsList.add(button); button.setOnAction(event -> model.select(tempRow, tempCol)); gridPane.add(button, col, row); } } //set main border gridPane.setAlignment(Pos.CENTER); hoppersBorderPane.setCenter(gridPane); } @FXML private void handleResetButton(){ model.reset(); } @FXML private void handleHintButton(){ model.hint(); } @FXML private void handleHomeButton(ActionEvent event) throws IOException{ Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getClassLoader().getResource("MainResources/MainStage.fxml"))); Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML private void handlePuzzleChoices(){ switch (puzzleChoices.getValue()) { case "Puzzle 1" -> model.load("src/Games/Hoppers/Resources/hoppers-1.txt"); case "Puzzle 2" -> model.load("src/Games/Hoppers/Resources/hoppers-2.txt"); case "Puzzle 3" -> model.load("src/Games/Hoppers/Resources/hoppers-3.txt"); case "Puzzle 4" -> model.load("src/Games/Hoppers/Resources/hoppers-4.txt"); case "Puzzle 5" -> model.load("src/Games/Hoppers/Resources/hoppers-5.txt"); case "Puzzle 6" -> model.load("src/Games/Hoppers/Resources/hoppers-6.txt"); case "Puzzle 7" -> model.load("src/Games/Hoppers/Resources/hoppers-7.txt"); } } @Override public void update(HoppersModel hoppersModel, HoppersClientData hoppersClientData) { GridPane gridPane = new GridPane(); this.topLabel.setText(hoppersClientData.toString()); for (int row=0; row<this.model.getCurrentConfig().getNumRows(); ++row) { for (int col=0; col<this.model.getCurrentConfig().getNumColumns(); ++col) { int tempRow = row; int tempCol = col; if(this.model.getCurrentConfig().getBoard()[row][col]=='.'){ buttonsList.get(row*this.model.getCurrentConfig().getNumColumns()+col).setGraphic(new ImageView(lilyPad)); } else if(this.model.getCurrentConfig().getBoard()[row][col]=='G'){ buttonsList.get(row*this.model.getCurrentConfig().getNumColumns()+col).setGraphic(new ImageView(greenFrog)); } else if(this.model.getCurrentConfig().getBoard()[row][col]=='R'){ buttonsList.get(row*this.model.getCurrentConfig().getNumColumns()+col).setGraphic(new ImageView(redFrog)); } else if(this.model.getCurrentConfig().getBoard()[row][col]=='*'){ buttonsList.get(row*this.model.getCurrentConfig().getNumColumns()+col).setGraphic(new ImageView(water)); } gridPane.add(buttonsList.get(row*this.model.getCurrentConfig().getNumColumns()+col), col, row); this.buttonsList.add(buttonsList.get(row*this.model.getCurrentConfig().getNumColumns()+col)); buttonsList.get(row*this.model.getCurrentConfig().getNumColumns()+col).setOnAction(event -> model.select(tempRow, tempCol)); } } //set main border gridPane.setAlignment(Pos.CENTER); hoppersBorderPane.setCenter(gridPane); } }
42.537037
140
0.632129
3032fe9256a96d3d9d601b6c3dcce35a4e2779e8
5,305
/* * Copyright (c) 2021 Birmingham City University. All rights reserved. * Author: Reza Shams (rezashams86@gmail.com) */ package com.hotel.usermanagement.model; import javax.persistence.*; import java.util.Date; @Entity(name="user") @Table(name="user_") public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id", nullable = false) private long userId; @Column(name = "first_name", nullable = false) private String firstName; @Column(name = "last_name", nullable = false) private String lastName; @Column(name="email", nullable = false,unique=true) private String email; @Column(name="password", nullable = false) private String password; @Column(name="is_student", nullable = false) private boolean isStudent; @Column(name="is_manager", nullable = false) private boolean isManager; @Column(name ="last_update") private Date lastUpdate; public User() {} public User(String firstName, String lastName, String email, String password,boolean isManager, boolean isStudent, Date lastUpdate) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; this.isManager = isManager; this.isStudent = isStudent; this.lastUpdate = lastUpdate; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String string) { this.password = string; } public boolean isStudent() { return isStudent; } public void setStudent(boolean student) { isStudent = student; } public boolean isManager() { return isManager; } public void setManager(boolean manager) { isManager = manager; } public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return userId == user.userId; } @Override public int hashCode() { return (int) (userId ^ (userId >>> 32)); } @Override public String toString() { return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } //Builder pattern private User(UserBuilder builder) { this.firstName = builder.firstName; this.lastName = builder.lastName; this.password = builder.password; this.isManager = builder.isManager; this.isStudent = builder.isStudent; this.email = builder.email; this.lastUpdate= builder.lastUpdate; } public static class UserBuilder { private String firstName; private String lastName; private String password; private String email; private boolean isStudent; private boolean isManager; private Date lastUpdate; public UserBuilder() { } public UserBuilder(String firstName, String lastName, String email, String password, boolean isStudent, boolean isManager, Date lastUpdate) { this.firstName = firstName; this.lastName = lastName; this.password = password; this.email = email; this.isManager= isManager; this.isStudent = isStudent; this.lastUpdate = lastUpdate; } public UserBuilder setFirstName(String firstName) { this.firstName = firstName; return this; } public UserBuilder setLastName(String lastName) { this.lastName = lastName; return this; } public UserBuilder setIsStudent(boolean isStudent) { this.isStudent = isStudent; return this; } public UserBuilder setEmail(String email) { this.email = email; return this; } public UserBuilder setIsManager(boolean isManager) { this.isManager = isManager; return this; } public UserBuilder setPassword(String password) { this.password = password; return this; } public UserBuilder setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; return this; } public User build() { return new User(this); } } }
24.560185
100
0.586616
31b2971fee0c21483913d3792696e50b512a26af
420
package ex4_3; public class Main { public static void main(String[] args) { // ALL PREPARED (exercise) // Ad-hoc polymorphism is when you define every implementation possible // but the object will decide which to use when it receives the type // An example is method overloading } // Task: Create an ad-hoc polymorphic function with two different // implementations }
28
79
0.67381
216346886e8896eaabb8d1d4a0850838067ed6e3
815
package com.demo.spring.dependency.domain; import com.demo.spring.ioc.overview.domain.User; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; /** * @author ZhangShaowei on 2021/4/28 15:51 */ @Component public class UserHolder implements ObjectHolder<User>, InitializingBean { // public UserHolder() { // BeanInstantiationException // throw new RuntimeException("故意抛出异常"); // } @Override public User getObject() { User user = User.createUser(); user.setAddress("Mars"); user.setName("UserHolder"); user.setId(1L); return user; } @Override public void afterPropertiesSet() throws Exception { // BeanCreationException // throw new Exception("故意抛出异常"); } }
23.970588
73
0.674847
0ee13861c9e05b0c54ada35b2401b4d675c8de7e
225
/** * Class Cow implements MakesSound interface and returns Moo!. * @author Tumelo Lephadi * @version 18/09/2015 */ public class Cow implements MakesSound { public String makeNoise() { return "Moo!" ; } }
17.307692
62
0.657778
9d897ca547f8047963b8de9a943bf3facbb0dff5
3,428
/** * @author $Author$ * @date $Date$ * @version $Revision$ */ package net.east301.keyring; import java.util.ArrayList; import net.east301.keyring.gnome.GNOMEKeyringBackend; import net.east301.keyring.memory.UncryptedMemoryBackend; import net.east301.keyring.osx.OSXKeychainBackend; import net.east301.keyring.windows.WindowsDPAPIBackend; /** * Factory of KeyringBackend */ class KeyringBackendFactory { /** * Creates an instance of KeyringBackend */ public static KeyringBackend create() throws BackendNotSupportedException { for (Object[] entry : KeyringBackendFactory.KEYRING_BACKENDS) { String name = (String)entry[0]; Class cls = (Class)entry[1]; KeyringBackend backend = tryToCreateBackend(cls); if (backend != null) { return backend; } } throw new BackendNotSupportedException("No available keyring backend found"); } /** * Creates an instance of KeyringBackend * * @param preferred Preferred backend name */ public static KeyringBackend create(String preferred) throws BackendNotSupportedException { // Class backendClass = null; for (Object[] entry : KeyringBackendFactory.KEYRING_BACKENDS) { String name = (String)entry[0]; Class cls = (Class)entry[1]; if (name.equals(preferred)) { backendClass = cls; break; } } if (backendClass == null) { throw new BackendNotSupportedException( String.format("The backend '%s' is not registered", preferred)); } // KeyringBackend backend = tryToCreateBackend(backendClass); if (backend == null) { throw new BackendNotSupportedException( String.format("The backend '%s' is not supported", preferred)); } // return backend; } /** * Returns names of registered keyring backends */ public static String[] getAllBackendNames() { ArrayList<String> result = new ArrayList<String>(); for (Object[] entry : KeyringBackendFactory.KEYRING_BACKENDS) { result.add((String)entry[0]); } return result.toArray(new String[0]); } /** * Try to create keyring backend instance from Class * * @param backendClass Target backend class */ private static KeyringBackend tryToCreateBackend(Class backendClass) { // KeyringBackend backend; try { backend = (KeyringBackend)backendClass.newInstance(); } catch (Exception ex) { // TODO: add code to handle exception return null; } // if (!backend.isSupported()) { return null; } // try { backend.setup(); } catch (BackendNotSupportedException ex) { // TODO: add code to handle exception return null; } return backend; } /** * All keyring backends */ private static Object[][] KEYRING_BACKENDS = { { "OSXKeychain", OSXKeychainBackend.class }, { "GNOMEKeyring", GNOMEKeyringBackend.class }, { "WindowsDPAPI", WindowsDPAPIBackend.class }, { "UncryptedMemory", UncryptedMemoryBackend.class } }; } // class KeyringBackendFactory
27.645161
95
0.595974
8cc9214de649723de48d0d7e906b816ab3f9b470
35,001
package com.atlassian.plugin.connect.plugin.lifecycle; import com.atlassian.applinks.api.ApplicationLink; import com.atlassian.event.api.EventPublisher; import com.atlassian.httpclient.api.HttpClient; import com.atlassian.httpclient.api.Request; import com.atlassian.httpclient.api.Response; import com.atlassian.jwt.JwtConstants; import com.atlassian.jwt.SigningAlgorithm; import com.atlassian.oauth.Consumer; import com.atlassian.oauth.consumer.ConsumerService; import com.atlassian.oauth.util.RSAKeys; import com.atlassian.plugin.PluginState; import com.atlassian.plugin.connect.api.ConnectAddonAccessor; import com.atlassian.plugin.connect.api.auth.AuthorizationGenerator; import com.atlassian.plugin.connect.api.auth.ReKeyableAuthorizationGenerator; import com.atlassian.plugin.connect.api.lifecycle.ConnectAddonDisableException; import com.atlassian.plugin.connect.api.lifecycle.ConnectAddonEnableException; import com.atlassian.plugin.connect.api.lifecycle.ConnectAddonInitException; import com.atlassian.plugin.connect.api.lifecycle.ConnectAddonInstallException; import com.atlassian.plugin.connect.api.request.HttpHeaderNames; import com.atlassian.plugin.connect.api.request.HttpMethod; import com.atlassian.plugin.connect.api.request.RemotablePluginAccessorFactory; import com.atlassian.plugin.connect.modules.beans.AuthenticationBean; import com.atlassian.plugin.connect.modules.beans.AuthenticationType; import com.atlassian.plugin.connect.modules.beans.ConnectAddonBean; import com.atlassian.plugin.connect.modules.beans.ConnectAddonEventData; import com.atlassian.plugin.connect.modules.beans.builder.ConnectAddonEventDataBuilder; import com.atlassian.plugin.connect.modules.beans.nested.ScopeName; import com.atlassian.plugin.connect.modules.gson.ConnectModulesGsonFactory; import com.atlassian.plugin.connect.plugin.AddonSettings; import com.atlassian.plugin.connect.plugin.ConnectAddonRegistry; import com.atlassian.plugin.connect.plugin.auth.SharedSecretService; import com.atlassian.plugin.connect.plugin.auth.applinks.ConnectApplinkManager; import com.atlassian.plugin.connect.plugin.descriptor.ConnectAddonBeanFactory; import com.atlassian.plugin.connect.plugin.descriptor.InvalidDescriptorException; import com.atlassian.plugin.connect.plugin.lifecycle.event.ConnectAddonDisabledEvent; import com.atlassian.plugin.connect.plugin.lifecycle.event.ConnectAddonEnableFailedEvent; import com.atlassian.plugin.connect.plugin.lifecycle.event.ConnectAddonEnabledEvent; import com.atlassian.plugin.connect.plugin.lifecycle.event.ConnectAddonInstalledEvent; import com.atlassian.plugin.connect.plugin.lifecycle.event.ConnectAddonUninstallFailedEvent; import com.atlassian.plugin.connect.plugin.lifecycle.event.ConnectAddonUninstalledEvent; import com.atlassian.plugin.connect.plugin.lifecycle.event.LifecycleCallbackBadResponseException; import com.atlassian.plugin.connect.plugin.lifecycle.upm.LicenseRetriever; import com.atlassian.plugin.connect.plugin.request.ConnectHttpClientFactory; import com.atlassian.plugin.connect.plugin.util.IsDevModeService; import com.atlassian.plugin.connect.spi.ProductAccessor; import com.atlassian.plugin.connect.spi.auth.user.ConnectUserService; import com.atlassian.sal.api.ApplicationProperties; import com.atlassian.sal.api.UrlMode; import com.atlassian.sal.api.features.DarkFeatureManager; import com.atlassian.sal.api.message.I18nResolver; import com.atlassian.sal.api.user.UserManager; import com.atlassian.sal.api.user.UserProfile; import com.atlassian.upm.spi.PluginInstallException; import com.atlassian.uri.Uri; import com.atlassian.uri.UriBuilder; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import javax.net.ssl.SSLException; import javax.ws.rs.core.MediaType; import java.io.Serializable; import java.net.SocketTimeoutException; import java.net.URI; import java.net.UnknownHostException; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import static com.atlassian.jwt.JwtConstants.HttpRequests.AUTHORIZATION_HEADER; import static com.atlassian.plugin.connect.modules.beans.ConnectAddonEventData.newConnectAddonEventData; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.nullToEmpty; import static java.util.Arrays.asList; /** * The ConnectAddonManager handles all the stuff that needs to happen when an add-on is enabled/disabled. */ @Named public class ConnectAddonManager { private static final Logger log = LoggerFactory.getLogger(ConnectAddonManager.class); private static final String HTTP_ERROR_I18N_KEY_PREFIX = "connect.install.error.remote.host.bad.response."; private static final List<Integer> OK_INSTALL_HTTP_CODES = asList(200, 201, 204); private static final SigningAlgorithm JWT_ALGORITHM = SigningAlgorithm.HS256; // currently, this is the only algorithm that we support private static final String DARK_FEATURE_DISABLE_SIGN_INSTALL_WITH_PREV_KEY = "connect.lifecycle.install.sign_with_prev_key.disable"; private static final String USER_KEY = "user_key"; public enum SyncHandler { INSTALLED, UNINSTALLED, ENABLED, DISABLED } private final IsDevModeService isDevModeService; private final UserManager userManager; private final RemotablePluginAccessorFactory remotablePluginAccessorFactory; private final ConnectAddonAccessor connectAddonAccessor; private HttpClient httpClient; private final ConnectAddonRegistry addonRegistry; private final BeanToModuleRegistrar beanToModuleRegistrar; private final ConnectUserService connectUserService; private final EventPublisher eventPublisher; private final ConsumerService consumerService; private final ApplicationProperties applicationProperties; private final LicenseRetriever licenseRetriever; private final ProductAccessor productAccessor; private final BundleContext bundleContext; private final ConnectApplinkManager connectApplinkManager; private final I18nResolver i18nResolver; private final ConnectAddonBeanFactory connectAddonBeanFactory; private final SharedSecretService sharedSecretService; private final DarkFeatureManager darkFeatureManager; @Inject public ConnectAddonManager(IsDevModeService isDevModeService, UserManager userManager, RemotablePluginAccessorFactory remotablePluginAccessorFactory, ConnectAddonRegistry addonRegistry, BeanToModuleRegistrar beanToModuleRegistrar, ConnectUserService connectUserService, EventPublisher eventPublisher, ConsumerService consumerService, ApplicationProperties applicationProperties, LicenseRetriever licenseRetriever, ProductAccessor productAccessor, BundleContext bundleContext, ConnectApplinkManager connectApplinkManager, I18nResolver i18nResolver, ConnectAddonBeanFactory connectAddonBeanFactory, SharedSecretService sharedSecretService, ConnectHttpClientFactory connectHttpClientFactory, DarkFeatureManager darkFeatureManager, ConnectAddonAccessor connectAddonAccessor) { this.isDevModeService = isDevModeService; this.userManager = userManager; this.remotablePluginAccessorFactory = remotablePluginAccessorFactory; this.connectAddonAccessor = connectAddonAccessor; this.httpClient = connectHttpClientFactory.getInstance(); this.addonRegistry = addonRegistry; this.beanToModuleRegistrar = beanToModuleRegistrar; this.connectUserService = connectUserService; this.eventPublisher = eventPublisher; this.consumerService = consumerService; this.applicationProperties = applicationProperties; this.licenseRetriever = licenseRetriever; this.productAccessor = productAccessor; this.bundleContext = bundleContext; this.connectApplinkManager = connectApplinkManager; this.i18nResolver = i18nResolver; this.connectAddonBeanFactory = connectAddonBeanFactory; this.sharedSecretService = sharedSecretService; this.darkFeatureManager = darkFeatureManager; } public boolean hasDescriptor(String pluginKey) { return addonRegistry.hasDescriptor(pluginKey); } public Iterable<String> getAllAddonKeys() { return addonRegistry.getAllAddonKeys(); } /** * This method is public for test visibility. In preference, please use * {@link ConnectAddonInstaller#install(String)} * * @param jsonDescriptor the json descriptor of the add-on to install * @param targetState the intended state of the add-on after a successful installation * @param maybePreviousSharedSecret optionally, the previous shared secret (used for signing) * @param reusePreviousPublicKeyOrSharedSecret toggle whether or not we issue a new secret/key if the previous one is defined */ @VisibleForTesting public void installConnectAddon(String jsonDescriptor, PluginState targetState, Optional<String> maybePreviousSharedSecret, boolean reusePreviousPublicKeyOrSharedSecret) throws ConnectAddonInstallException { long startTime = System.currentTimeMillis(); ConnectAddonBean addon = connectAddonBeanFactory.fromJson(jsonDescriptor); String pluginKey = addon.getKey(); String previousDescriptor = addonRegistry.getDescriptor(pluginKey); AuthenticationType newAuthType = addon.getAuthentication().getType(); final boolean newUseSharedSecret = addonUsesSymmetricSharedSecret(newAuthType, JWT_ALGORITHM); String newSharedSecret = newUseSharedSecret ? reusePreviousPublicKeyOrSharedSecret && maybePreviousSharedSecret.isPresent() ? maybePreviousSharedSecret.get() : sharedSecretService.next() : null; String newAddonSigningKey = newUseSharedSecret ? newSharedSecret : addon.getAuthentication().getPublicKey(); // the key stored on the applink: used to sign outgoing requests and verify incoming requests String userKey = provisionUserIfNecessary(addon, previousDescriptor); AddonSettings settings = new AddonSettings() .setAuth(newAuthType.name()) .setBaseUrl(addon.getBaseUrl()) .setDescriptor(jsonDescriptor) .setRestartState(PluginState.DISABLED) .setUserKey(userKey); if (!Strings.isNullOrEmpty(newSharedSecret)) { settings.setSecret(newSharedSecret); } addonRegistry.storeAddonSettings(pluginKey, settings); //applink MUST be created before any modules but AFTER we store the settings connectApplinkManager.createAppLink(addon, addon.getBaseUrl(), newAuthType, newAddonSigningKey, userKey); //make the sync callback if needed if (!Strings.isNullOrEmpty(addon.getLifecycle().getInstalled())) { if (darkFeatureManager.isFeatureEnabledForAllUsers(DARK_FEATURE_DISABLE_SIGN_INSTALL_WITH_PREV_KEY)) { requestInstallCallback(addon, newSharedSecret, true); // sign using whatever shared secret is looked up (the old code path) } else { // TODO ACDEV-1596: Because we've got exactly one auth generator per add-on this if statement's condition // will cause us to NOT sign if the old descriptor used a shared secret but the new descriptor does NOT. if (maybePreviousSharedSecret.isPresent() && newUseSharedSecret) { requestInstallCallback(addon, newSharedSecret, maybePreviousSharedSecret.get()); // sign using the previous shared secret } else { requestInstallCallback(addon, newSharedSecret, false); // do not sign } } } eventPublisher.publish(new ConnectAddonInstalledEvent(pluginKey)); long endTime = System.currentTimeMillis(); log.info("Connect addon '" + addon.getKey() + "' installed in " + (endTime - startTime) + "ms"); if (PluginState.ENABLED == targetState) { try { enableConnectAddon(pluginKey); } catch (ConnectAddonEnableException e) { log.error("Could not enable add-on " + e.getAddonKey() + " during its installation: " + e.getMessage(), e); } } } private static boolean addonRequiresAuth(ConnectAddonBean addon) { return addon.getAuthentication() != null && !AuthenticationType.NONE.equals(addon.getAuthentication().getType()); } public String provisionUserIfNecessary(ConnectAddonBean addon, String previousDescriptor) throws ConnectAddonInstallException { return addonRequiresAuth(addon) ? provisionAddonUserAndScopes(addon, previousDescriptor) : null; } public void enableConnectAddon(final String pluginKey) throws ConnectAddonInitException, ConnectAddonEnableException { long startTime = System.currentTimeMillis(); //Instances of remotablePluginAccessor are only meant to be used for the current operation and should not be cached across operations. remotablePluginAccessorFactory.remove(pluginKey); if (addonRegistry.hasDescriptor(pluginKey)) { ConnectAddonBean addon; try { addon = connectAddonAccessor.getAddon(pluginKey).get(); beanToModuleRegistrar.registerDescriptorsForBeans(addon); } catch (InvalidDescriptorException | ConnectModuleRegistrationException e) { eventPublisher.publish(new ConnectAddonEnableFailedEvent(pluginKey, e.getMessage())); throw new ConnectAddonEnableException(pluginKey, "Module registration failed while enabling add-on, skipping.", e); } if (addonRequiresAuth(addon)) { enableAddonUser(addon); } addonRegistry.storeRestartState(pluginKey, PluginState.ENABLED); final ConnectAddonEnabledEvent enabledEvent = new ConnectAddonEnabledEvent(pluginKey, createEventData(pluginKey, SyncHandler.ENABLED.name().toLowerCase())); try { eventPublisher.publish(enabledEvent); } catch (Exception e) { log.warn(String.format("Could not fire enabled webhook event for add-on %s, continuing anyway", pluginKey), e); } long endTime = System.currentTimeMillis(); log.info("Connect addon '" + addon.getKey() + "' enabled in " + (endTime - startTime) + "ms"); } else { String message = "Tried to enable add-on before it was installed."; eventPublisher.publish(new ConnectAddonEnableFailedEvent(pluginKey, message)); throw new ConnectAddonEnableException(pluginKey, message); } } public void disableConnectAddon(final String pluginKey) throws ConnectAddonDisableException { disableConnectAddon(pluginKey, true, true); } public void disableConnectAddonWithoutPersistingState(final String pluginKey) throws ConnectAddonDisableException { disableConnectAddon(pluginKey, false, true); } private void disableConnectAddon(final String pluginKey, boolean persistState, boolean sendEvent) throws ConnectAddonDisableException { long startTime = System.currentTimeMillis(); remotablePluginAccessorFactory.remove(pluginKey); if (addonRegistry.hasDescriptor(pluginKey)) { // don't double-count disablements; // a developer looking at a dashboard would otherwise see 2 disablement events for an add-on that was first disabled and then uninstalled, // and this would both distort the total number of disablements and look like a possible bug if (sendEvent && !PluginState.DISABLED.equals(addonRegistry.getRestartState(pluginKey))) { //need to publish the event before we actually disable anything eventPublisher.publish(new ConnectAddonDisabledEvent(pluginKey, createEventData(pluginKey, SyncHandler.DISABLED.name().toLowerCase()))); } disableAddonUser(pluginKey); beanToModuleRegistrar.unregisterDescriptorsForAddon(pluginKey); if (persistState) { addonRegistry.storeRestartState(pluginKey, PluginState.DISABLED); } long endTime = System.currentTimeMillis(); log.info("Connect addon '" + pluginKey + "' disabled in " + (endTime - startTime) + "ms"); } } public void uninstallConnectAddon(final String pluginKey) throws ConnectAddonDisableException { uninstallConnectAddon(pluginKey, true); } public void uninstallConnectAddonQuietly(final String pluginKey) { try { uninstallConnectAddon(pluginKey, false); } catch (ConnectAddonDisableException e) { //uh, don't you know what "quietly" means? } } private void uninstallConnectAddon(final String pluginKey, boolean sendEvent) throws ConnectAddonDisableException { long startTime = System.currentTimeMillis(); if (addonRegistry.hasDescriptor(pluginKey)) { String descriptor = addonRegistry.getDescriptor(pluginKey); Optional<String> maybeSharedSecret = Optional.empty(); try { ConnectAddonBean addon = null; try { addon = connectAddonAccessor.getAddon(pluginKey).get(); } catch (InvalidDescriptorException e) { String message = "Tried to publish plugin uninstalled event for connect addon ['" + pluginKey + "'], but got a null ConnectAddonBean when trying to deserialize it's stored descriptor. Ignoring..."; if (sendEvent) { eventPublisher.publish(new ConnectAddonUninstallFailedEvent(pluginKey, message)); } log.warn(message); } disableConnectAddon(pluginKey, false, sendEvent); if (null != addon) { if (sendEvent && !Strings.isNullOrEmpty(addon.getLifecycle().getUninstalled())) { try { final URI callbackUri = getURI(addon.getBaseUrl(), addon.getLifecycle().getUninstalled()); callSyncHandler(addon.getKey(), addonUsesJwtAuthentication(addon), callbackUri, createEventDataForUninstallation(pluginKey, addon), getAuthHeader(callbackUri, remotablePluginAccessorFactory.get(addon.getKey()).getAuthorizationGenerator())); } catch (LifecycleCallbackException e) { log.warn("Failed to notify remote host that add-on was uninstalled.", e); } } if (sendEvent) { eventPublisher.publish(new ConnectAddonUninstalledEvent(pluginKey)); } if (addonUsesSymmetricSharedSecret(addon, JWT_ALGORITHM)) { final ApplicationLink appLink = connectApplinkManager.getAppLink(pluginKey); if (null != appLink) { maybeSharedSecret = connectApplinkManager.getSharedSecretOrPublicKey(appLink); } } connectApplinkManager.deleteAppLink(addon); } } finally { addonRegistry.removeAll(pluginKey); connectAddonBeanFactory.remove(descriptor); // if the add-on had a shared secret then store it so that we can sign an installed callback // in DefaultConnectAddonInstaller.install(java.lang.String)() if the user turns around and re-installs the add-on if (maybeSharedSecret.isPresent()) { AddonSettings uninstalledRemnant = new AddonSettings(); uninstalledRemnant.setSecret(maybeSharedSecret.get()); uninstalledRemnant.setRestartState(PluginState.UNINSTALLED); addonRegistry.storeAddonSettings(pluginKey, uninstalledRemnant); // do it in one call for efficiency } } } long endTime = System.currentTimeMillis(); log.info("Connect addon '" + pluginKey + "' uninstalled in " + (endTime - startTime) + "ms"); } // first install: no previous shared secret, no signing private void requestInstallCallback(ConnectAddonBean addon, String sharedSecret, final boolean sign) throws ConnectAddonInstallException { final URI callbackUri = getURI(addon.getBaseUrl(), addon.getLifecycle().getInstalled()); final Optional<String> authHeader = sign ? getAuthHeader(callbackUri, remotablePluginAccessorFactory.get(addon.getKey()).getAuthorizationGenerator()) : Optional.<String>empty(); requestInstallCallback(addon, sharedSecret, callbackUri, authHeader); } // reinstalls: sign with the previous shared secret so that the add-on can verify that the sender of the request is in possession of the previous shared secret private void requestInstallCallback(ConnectAddonBean addon, String sharedSecret, String previousSharedSecret) throws ConnectAddonInstallException { final URI callbackUri = getURI(addon.getBaseUrl(), addon.getLifecycle().getInstalled()); final AuthorizationGenerator authorizationGenerator = remotablePluginAccessorFactory.get(addon.getKey()).getAuthorizationGenerator(); // NB: check that the auth generator matches the request/non-request to sign with an arbitrary key on installation, not on every callback, // because signing with a previous key happens only on installation // (the runtime "instanceof ReKeyableAuthorizationGenerator" check is necessary because the OAuthSigningRemotablePluginAccessor is explicitly not re-keyable: it must sign with the same oauth key every time) if (authorizationGenerator instanceof ReKeyableAuthorizationGenerator) { String authHeader = getAuthHeader(callbackUri, (ReKeyableAuthorizationGenerator) authorizationGenerator, previousSharedSecret); requestInstallCallback(addon, sharedSecret, callbackUri, Optional.of(authHeader)); } else { // this should never happen; if it does then it will result in a "something bad happened; talk to an admin" error message in the UI throw new IllegalArgumentException(String.format("Cannot sign outgoing request to %s with an arbitrary secret because the authorization generator for add-on %s is a %s, which is not a %s!", callbackUri, addon.getKey(), authorizationGenerator.getClass().getSimpleName(), ReKeyableAuthorizationGenerator.class.getSimpleName())); } } private void requestInstallCallback(ConnectAddonBean addon, String sharedSecret, URI callbackUri, Optional<String> authHeader) throws ConnectAddonInstallException { try { callSyncHandler(addon.getKey(), addonUsesJwtAuthentication(addon), callbackUri, createEventDataForInstallation(addon.getKey(), sharedSecret, addon), authHeader); } catch (LifecycleCallbackException e) { Serializable[] params = e.getParams() != null ? e.getParams() : new Serializable[]{}; throw new ConnectAddonInstallException(e.getMessage(), e, e.getI18nKey(), params); } } // removing the property from the app link removes the Authenticator's ability to assign a user to incoming requests // and as these users cannot log in anyway this reduces their possible actions to zero // (but don't remove the user as we need to preserve the history of their actions (e.g. audit trail, issue edited by <user>) private void disableAddonUser(String addonKey) throws ConnectAddonDisableException { ApplicationLink applicationLink = connectApplinkManager.getAppLink(addonKey); if (null != applicationLink) { applicationLink.removeProperty(JwtConstants.AppLinks.ADD_ON_USER_KEY_PROPERTY_NAME); } connectUserService.disableAddonUser(addonKey); } private void enableAddonUser(ConnectAddonBean addon) throws ConnectAddonInitException { String userKey = connectUserService.getOrCreateAddonUserName(addon.getKey(), addon.getName()); ApplicationLink applicationLink = connectApplinkManager.getAppLink(addon.getKey()); if (null != applicationLink) { applicationLink.putProperty(JwtConstants.AppLinks.ADD_ON_USER_KEY_PROPERTY_NAME, userKey); } else { log.error("Unable to set the ApplicationLink user key property for add-on '{}' because the add-on has no ApplicationLink!", addon.getKey()); } } // NB: the sharedSecret should be distributed synchronously and only on installation private void callSyncHandler(String addonKey, final boolean addonUsesJwtAuthentication, URI callbackUri, String jsonEventData, Optional<String> authHeader) throws LifecycleCallbackException { // try distributing prod shared secrets over http (note the lack of "s") and it shall be rejected if (!isDevModeService.isDevMode() && addonUsesJwtAuthentication && !callbackUri.getScheme().toLowerCase().startsWith("https")) { String message = String.format("Cannot issue callback except via HTTPS. Current URL = '%s'", callbackUri); throw new LifecycleCallbackException(message, "connect.remote.upm.install.exception"); } Response response = getSyncHandlerResponse(addonKey, callbackUri, jsonEventData, authHeader); final int statusCode = response.getStatusCode(); // a selection of 2xx response codes both indicate success and are semantically valid for this callback if (!OK_INSTALL_HTTP_CODES.contains(statusCode)) { String statusText = response.getStatusText(); String responseEntity = response.getEntity(); // calling response.getEntity() multiple times results in IllegalStateException("Entity may only be accessed once") log.error("Error contacting remote application at " + callbackUri + " " + statusCode + ":[" + statusText + "]:" + responseEntity); String message = "Error contacting remote application " + statusCode + ":[" + statusText + "]:" + responseEntity; throw new LifecycleCallbackHttpCodeException(message, findI18nKeyForHttpErrorCode(statusCode), statusCode); } } private static boolean addonUsesJwtAuthentication(ConnectAddonBean addon) { return null != addon.getAuthentication() && AuthenticationType.JWT.equals(addon.getAuthentication().getType()); } private static Optional<String> getAuthHeader(final URI callbackUri, final AuthorizationGenerator authorizationGenerator) { return authorizationGenerator.generate(HttpMethod.POST, callbackUri, Collections.<String, String[]>emptyMap()); } private static String getAuthHeader(final URI callbackUri, final ReKeyableAuthorizationGenerator authorizationGenerator, final String secret) { return authorizationGenerator.generate(HttpMethod.POST, callbackUri, Collections.<String, String[]>emptyMap(), secret); } private Response getSyncHandlerResponse(String addonKey, URI callbackUri, String jsonEventData, Optional<String> authHeader) throws LifecycleCallbackException { try { Request.Builder request = httpClient.newRequest(callbackUri); request.setAttribute("purpose", "web-hook-notification"); request.setAttribute("pluginKey", addonKey); request.setContentType(MediaType.APPLICATION_JSON); request.setEntity(jsonEventData); if (authHeader.isPresent()) { request.setHeader(AUTHORIZATION_HEADER, authHeader.get()); } request.setHeader(HttpHeaderNames.ATLASSIAN_CONNECT_VERSION, getConnectPluginVersion()); return request.execute(Request.Method.POST).claim(); } catch (Exception e) { log.error("Error contacting remote application at " + callbackUri + " [" + e.getMessage() + "]", e); String message = "Error contacting remote application [" + e.getMessage() + "]"; Throwable cause = e.getCause(); if (cause instanceof UnknownHostException) { throw new LifecycleCallbackBadResponseException(message, "connect.install.error.remote.host.bad.domain", callbackUri.getHost()); } else if (cause instanceof SocketTimeoutException) { throw new LifecycleCallbackBadResponseException(message, "connect.install.error.remote.host.timeout", removeQuery(callbackUri)); } else if (cause instanceof SSLException) { throw new LifecycleCallbackBadResponseException(message, "connect.install.error.remote.host.ssl", removeQuery(callbackUri), cause.getMessage()); } throw new LifecycleCallbackException(message, "connect.remote.upm.install.exception"); } } // we don't want to see "?user_key=2c9680504384c481014384c49e6a0004" in installation failure messages show to the users private String removeQuery(URI uri) { String uriString = uri.toString(); String query = uri.getQuery(); if (query != null) { uriString = uriString.replace(query, ""); } return uriString.endsWith("?") ? uriString.substring(0, uriString.length() - 1) : uriString; } private String findI18nKeyForHttpErrorCode(final int responseCode) { String i18nKey = HTTP_ERROR_I18N_KEY_PREFIX + responseCode; final String i18nText = i18nResolver.getRawText(i18nKey); // the I18nResolver javadoc says that it will return the input key as the output raw text when the key is not found // and we also check a couple of other obvious problems, just to be save if (StringUtils.isEmpty(i18nText) || i18nKey.equals(i18nText)) { // fall back to the generic i18n key if there's no i18n key for this HTTP code i18nKey = "connect.remote.upm.install.exception"; } return i18nKey; } @VisibleForTesting URI getURI(String addonBaseUrl, String endpointRelativePath) { UriBuilder builder = new UriBuilder(Uri.parse(addonBaseUrl + endpointRelativePath)); UserProfile user = userManager.getRemoteUser(); if (null != user) { builder.addQueryParameter(USER_KEY, user.getUserKey().getStringValue()); } return builder.toUri().toJavaUri(); } @VisibleForTesting String createEventData(String pluginKey, String eventType) { return createEventDataInternal(pluginKey, eventType, null); } String createEventDataForInstallation(String pluginKey, String sharedSecret, ConnectAddonBean addon) { return createEventDataInternal(pluginKey, SyncHandler.INSTALLED.name().toLowerCase(), sharedSecret); } String createEventDataForUninstallation(String pluginKey, ConnectAddonBean addon) { return createEventDataInternal(pluginKey, SyncHandler.UNINSTALLED.name().toLowerCase(), null); } // NB: the sharedSecret should be distributed synchronously and only on installation private String createEventDataInternal(String pluginKey, String eventType, String sharedSecret) { final Consumer consumer = checkNotNull(consumerService.getConsumer()); // checkNotNull() otherwise we NPE below ConnectAddonEventDataBuilder dataBuilder = newConnectAddonEventData(); String baseUrl = applicationProperties.getBaseUrl(UrlMode.CANONICAL); dataBuilder.withBaseUrl(nullToEmpty(baseUrl)) .withPluginKey(pluginKey) .withClientKey(nullToEmpty(consumer.getKey())) .withPublicKey(nullToEmpty(RSAKeys.toPemEncoding(consumer.getPublicKey()))) .withSharedSecret(nullToEmpty(sharedSecret)) .withPluginsVersion(nullToEmpty(getConnectPluginVersion())) .withServerVersion(nullToEmpty(applicationProperties.getBuildNumber())) .withServiceEntitlementNumber(nullToEmpty(licenseRetriever.getServiceEntitlementNumber(pluginKey))) .withProductType(nullToEmpty(productAccessor.getKey())) .withDescription(nullToEmpty(consumer.getDescription())) .withEventType(eventType); ConnectAddonEventData data = dataBuilder.build(); return ConnectModulesGsonFactory.getGson().toJson(data); } private String getConnectPluginVersion() { Object bundleVersion = bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); return bundleVersion == null ? null : bundleVersion.toString(); } private boolean addonUsesSymmetricSharedSecret(ConnectAddonBean addonBean, SigningAlgorithm jwtAlgorithm) { AuthenticationBean authenticationBean = addonBean.getAuthentication(); return null != authenticationBean && addonUsesSymmetricSharedSecret(authenticationBean.getType(), jwtAlgorithm); } // TODO ACDEV-378: also check the algorithm private boolean addonUsesSymmetricSharedSecret(AuthenticationType authType, SigningAlgorithm algorithm) { return AuthenticationType.JWT.equals(authType) && algorithm.requiresSharedSecret(); } private String provisionAddonUserAndScopes(ConnectAddonBean addon, String previousDescriptor) throws PluginInstallException, ConnectAddonInstallException { Set<ScopeName> previousScopes = Sets.newHashSet(); Set<ScopeName> newScopes = addon.getScopes(); if (StringUtils.isNotBlank(previousDescriptor)) { ConnectAddonBean previousAddon = connectAddonBeanFactory.fromJson(previousDescriptor); previousScopes = previousAddon.getScopes(); } try { return connectUserService.provisionAddonUserWithScopes(addon, previousScopes, newScopes); } catch (ConnectAddonInitException e) { throw new ConnectAddonInstallException(e.getMessage(), e, e.getI18nKey(), addon.getName()); } } }
55.469097
217
0.714008
2be43bcd78427563dc56ba78e7e3bbb9c9ce76e7
2,849
/* * Copyright 2015-2016 MarkLogic Corporation * * 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. */ /** * A library that enables access to a MarkLogic-backed triple-store via the * Sesame API. */ package com.marklogic.semantics.sesame.query; import com.marklogic.client.FailedRequestException; import com.marklogic.client.semantics.GraphPermissions; import com.marklogic.client.query.QueryDefinition; import com.marklogic.client.semantics.SPARQLRuleset; import com.marklogic.semantics.sesame.client.MarkLogicClient; import org.openrdf.query.BooleanQuery; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sparql.query.SPARQLQueryBindingSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * boolean query * * @author James Fuller */ public class MarkLogicBooleanQuery extends MarkLogicQuery implements BooleanQuery,MarkLogicQueryDependent { protected final Logger logger = LoggerFactory.getLogger(MarkLogicBooleanQuery.class); /** * constructor * * @param client * @param bindingSet * @param baseUri * @param queryString */ public MarkLogicBooleanQuery(MarkLogicClient client, SPARQLQueryBindingSet bindingSet, String baseUri, String queryString, GraphPermissions graphPerms, QueryDefinition queryDef, SPARQLRuleset[] rulesets) { super(client, bindingSet, baseUri, queryString, graphPerms, queryDef, rulesets); } /** * evaluate boolean query * * @return boolean * @throws QueryEvaluationException */ @Override public boolean evaluate() throws QueryEvaluationException { try { return getMarkLogicClient().sendBooleanQuery(getQueryString(), getBindings(), getIncludeInferred(),getBaseURI()); }catch (RepositoryException e) { throw new QueryEvaluationException(e.getMessage(), e); }catch (MalformedQueryException e) { throw new QueryEvaluationException(e.getMessage(), e); }catch (IOException e) { throw new QueryEvaluationException(e.getMessage(), e); }catch(FailedRequestException e){ throw new QueryEvaluationException(e.getMessage(), e); } } }
35.6125
209
0.736399
ebf390309b23e21ae689858bb26c649c605a764a
444
package com.library.dao; public enum CoverDAOEnums { QUERY_SELECT_COVER_BY_ITEM_ID("SELECT * FROM covers WHERE Item_ID = ?"), QUERY_INSERT_COVER_BY_ITEM_ID("INSERT INTO covers (Item_ID,Cover_Blob,File_Extension) Values (?,?,?)"), QUERY_DELETE_COVER_BY_ITEM_ID("DELETE FROM covers WHERE Item_ID = ?"); String query; private CoverDAOEnums(String query) { this.query = query; } public String getQuery() { return query; } }
21.142857
104
0.734234
192a2082f506cf3d3fb48c7c6d1a25b096a7ea5f
1,776
package appointmentscheduler.repository; import appointmentscheduler.entity.appointment.Appointment; import appointmentscheduler.entity.appointment.AppointmentStatus; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.time.LocalDate; import java.util.List; import java.util.Optional; @Repository public interface AppointmentRepository extends JpaRepository<Appointment, Long> { Optional<Appointment> findByIdAndBusinessIdAndClientId(long appointmentId, long businessId, long clientId); Optional<Appointment> findByIdAndBusinessId(long appointmentId, long businessId); Optional<Appointment> findById(Long aLong); Optional<List<Appointment>> findByBusinessIdAndEmployeeId(long businessId, long employeeId); List<Appointment> findByClientId(long clientId); List<Appointment> findByBusinessId(long businessId); List<Appointment> findByClientIdAndBusinessId(long clientId, long businessId); List<Appointment> findByClientIdAndStatus(long clientId, AppointmentStatus status); List<Appointment> findByDateAndClientIdAndBusinessIdAndStatus(LocalDate date, long clientId,long businessId, AppointmentStatus status); List<Appointment> findByDateAndGuestIdAndBusinessIdAndStatus(LocalDate date, long guestId,long businessId, AppointmentStatus status); List<Appointment> findByEmployeeId(long employeeId); List<Appointment> findByDateAndEmployeeIdAndBusinessIdAndStatus(LocalDate date, long employeeId, long businessId, AppointmentStatus status); List<Appointment> findByEmployeeIdAndBusinessId(long employeeId, long businessId); List<Appointment> findByDateAndStatusAndBusinessId(LocalDate date, AppointmentStatus status, long businessId); }
41.302326
144
0.831644
cb55e8451f154b3774eed82a20863e31b3b6e5f9
18,347
package com.bsi.pontua; import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.graphics.Typeface; import android.os.AsyncTask; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import controle.CadastrosControle; import utils.SoftRadioButton; import utils.Utils; import utils.controls.VerticalScrollLayout; import vo.EventoVO; import vo.EventoVO; import vo.RelEntidadeEventoVO; public class CadastroEventos extends AppCompatActivity { TableLayout tl; TableRow tr; TextView col1, col2, col3; ProgressDialog progress; AlertDialog writeTagAlert; //lista de eventos exibidos List<EventoVO> listaEventos; Map<Integer, Integer> mapRelEntidadeEvento = new HashMap<Integer, Integer>(); Map<Integer, Integer> mapRelItemInspecaoEvento = new HashMap<Integer, Integer>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro_eventos); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle("Eventos"); final Button btnNovo = (Button) findViewById(R.id.btnNovo); final Button btnEditar = (Button) findViewById(R.id.btnEditar); final Button btnExcluir = (Button) findViewById(R.id.btnExcluir); final Button btnConfigurar = (Button) findViewById(R.id.btnConfigEvento); // Lookup the swipe container view final SwipeRefreshLayout swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //atualiza popularGridTask task = new popularGridTask(); task.isSwipe = true; task.execute(""); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_green_dark, android.R.color.holo_orange_light, android.R.color.holo_red_light); //apenas habilita swipe caso o scroll esteja no topo ((VerticalScrollLayout) findViewById(R.id.customScrollView)).setOnScrollListener(new VerticalScrollLayout.OnScrollListener() { private int _y=0; @Override public void onScrollChanged(int x, int y, int oldx, int oldy) { _y = y; swipeContainer.setEnabled(_y == 0); } @Override public void onScrollEnded() { swipeContainer.setEnabled(_y == 0); } }); btnNovo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(CadastroEventos.this, CadastroEventosNovoEditar.class); Bundle b = new Bundle(); b.putString("registro", null); myIntent.putExtras(b); //Put your id to your next Intent startActivityForResult(myIntent, 1); } }); btnEditar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registro = -1; selectedRadio(tl); if (registro != -1) { Intent myIntent = new Intent(CadastroEventos.this, CadastroEventosNovoEditar.class); Bundle b = new Bundle(); b.putString("registro", String.valueOf(registro)); myIntent.putExtras(b); //Put your id to your next Intent startActivityForResult(myIntent, 1); } else { Toast.makeText(getApplicationContext(), "Selecione algum registro a editar!", Toast.LENGTH_SHORT).show(); } } }); btnExcluir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registro = -1; selectedRadio(tl); if (registro != -1) { new AlertDialog.Builder(CadastroEventos.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("") .setMessage("Deseja realmente excluir o registro selecionado?") .setPositiveButton("Sim", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //remove String[] paramns = new String[]{String.valueOf(registro)}; new excluirRegistroTask().execute(paramns); } }) .setNegativeButton("Não", null) .show(); } else { Toast.makeText(getApplicationContext(), "Selecione algum registro a excluir!", Toast.LENGTH_SHORT).show(); } } }); btnConfigurar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registro = -1; selectedRadio(tl); if (registro != -1) { Intent myIntent = new Intent(CadastroEventos.this, CadastroEventosConfigurar.class); EventoVO evtAtual = null; for(EventoVO item : listaEventos){ if(registro == item.getId()){ evtAtual = item; } } myIntent.putExtra("oEvento", evtAtual); startActivityForResult(myIntent, 1); } else { Toast.makeText(getApplicationContext(), "Selecione o evento", Toast.LENGTH_SHORT).show(); } } }); //atualiza lista new popularGridTask().execute(""); } int registro = -1; public void selectedRadio(ViewGroup layout) { for (int i = 0; i < layout.getChildCount(); i++) { View v = layout.getChildAt(i); if (v instanceof ViewGroup) { selectedRadio((ViewGroup) v); } else if (v instanceof TableRow) { selectedRadio((TableRow) v); } else if (v instanceof SoftRadioButton) { if (((SoftRadioButton) v).isChecked()) { registro = Integer.parseInt(((SoftRadioButton) v).getText().toString()); } } } } @Override public void onPause() { //evita erro de leak super.onPause(); if (progress != null) { progress.dismiss(); progress = null; } } @Override protected void onStop() { //evita erro de leak super.onStop(); if (progress != null) { progress.dismiss(); progress = null; } } void inicializaProgressBar() { if (progress == null) { progress = new ProgressDialog(CadastroEventos.this); progress.setTitle(""); progress.setMessage("Aguarde..."); progress.setIndeterminate(true); progress.setCancelable(false); } } /** * This function add the headers to the table **/ public void addHeaders() { /** Create a TableRow **/ tr = new TableRow(this); tr.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); /** Creating a TextView to add to the row **/ TextView col1 = new TextView(this); col1.setText("Cód"); col1.setTypeface(Typeface.DEFAULT, Typeface.BOLD); col1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); col1.setPadding(5, 5, 5, 0); tr.addView(col1); // Adding textView to tablerow. /** Creating another textview **/ TextView ncol2 = new TextView(this); ncol2.setText("Nome"); ncol2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); ncol2.setPadding(5, 5, 5, 0); ncol2.setTypeface(Typeface.DEFAULT, Typeface.BOLD); tr.addView(ncol2); // Adding textView to tablerow. TextView ncol3 = new TextView(this); ncol3.setText("Qtd Entidades"); ncol3.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); ncol3.setPadding(5, 5, 5, 0); ncol3.setTypeface(Typeface.DEFAULT, Typeface.BOLD); tr.addView(ncol3); // Adding textView to tablerow. TextView ncol4 = new TextView(this); ncol4.setText("Qtd Itens"); ncol4.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); ncol4.setPadding(5, 5, 5, 0); ncol4.setTypeface(Typeface.DEFAULT, Typeface.BOLD); tr.addView(ncol4); // Adding textView to tablerow. // Add the TableRow to the TableLayout tl.addView(tr, new TableLayout.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); // we are adding two textviews for the <span id="IL_AD5" class="IL_AD">divider</span> because we have two columns tr = new TableRow(this); tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); /* *//** Creating another textview **//* TextView divider = new TextView(this); divider.setText("-----------------"); divider.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); divider.setPadding(5, 0, 0, 0); divider.setTypeface(Typeface.DEFAULT, Typeface.BOLD); tr.addView(divider); // Adding textView to tablerow. TextView divider2 = new TextView(this); divider2.setText("-------------------------"); divider2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); divider2.setPadding(5, 0, 0, 0); divider2.setTypeface(Typeface.DEFAULT, Typeface.BOLD); tr.addView(divider2); // Adding textView to tablerow.*/ // Add the TableRow to the TableLayout tl.addView(tr, new TableLayout.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); //separator TableRow tr = new TableRow(this); tr.setBackgroundColor(Color.GRAY); tr.setPadding(0, 0, 0, 2); //Border between rows TableRow.LayoutParams llp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); llp.setMargins(0, 0, 2, 0);//2px right-margin tl.addView(tr); } /** * This function add the data to the table **/ public void addData(List<EventoVO> obj) { for (EventoVO e : obj) { /** Create a TableRow dynamically **/ tr = new TableRow(this); tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); /** Creating a TextView to add to the row **/ final SoftRadioButton chk = new SoftRadioButton(this, "RadioBtn1"); chk.setText(String.valueOf(e.getId())); chk.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); chk.setPadding(5, 5, 5, 5); chk.setTextColor(Color.BLACK); chk.setWidth(200); tr.addView(chk); // Adding textView to tablerow. col1 = new TextView(this); col1.setText(e.getNome()); col1.setTextColor(Color.BLACK); col1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); col1.setPadding(5, 5, 5, 5); tr.addView(col1); col2 = new TextView(this); col2.setText(mapRelEntidadeEvento.get(e.getId()).toString()); col2.setTextColor(Color.BLACK); col2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); col2.setPadding(5, 5, 5, 5); tr.addView(col2); col3 = new TextView(this); col3.setText(mapRelItemInspecaoEvento.get(e.getId()).toString()); col3.setTextColor(Color.BLACK); col3.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); col3.setPadding(5, 5, 5, 5); tr.addView(col3); // Add the TableRow to the TableLayout tl.addView(tr, new TableLayout.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); //separator TableRow tr = new TableRow(this); tr.setBackgroundColor(Color.GRAY); tr.setPadding(0, 0, 0, 2); //Border between rows TableRow.LayoutParams llp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); llp.setMargins(0, 0, 2, 0);//2px right-margin tl.addView(tr); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == Activity.RESULT_OK) { //atualiza lista new popularGridTask().execute(""); } } } class popularGridTask extends AsyncTask<String, Integer, List> { boolean isSwipe = false; @Override protected void onPreExecute() { if(!isSwipe){ inicializaProgressBar(); progress.show(); } } @Override protected List<EventoVO> doInBackground(String... param) { try(CadastrosControle cc = new CadastrosControle()){ try { List<EventoVO> lista = cc.listarEvento(""); for (EventoVO item : lista){ //preenche totais.. int totalEntidades = 0; int totalItens = 0; totalEntidades = cc.obterQtdEntidadesPorEvento(item); totalItens = cc.obterQtdItensPorEvento(item); mapRelEntidadeEvento.put(item.getId(), totalEntidades); mapRelItemInspecaoEvento.put(item.getId(), totalItens); } return lista; } catch (Exception e) { e.printStackTrace(); return null; } } } @Override protected void onPostExecute(List result) { if(result==null){ return; } tl = (TableLayout) findViewById(R.id.maintable); tl.removeAllViewsInLayout(); addHeaders(); addData(result); listaEventos = result; if (progress != null && progress.isShowing()) { progress.dismiss(); } if(isSwipe){ final SwipeRefreshLayout swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); swipeContainer.setRefreshing(false); } } } class excluirRegistroTask extends AsyncTask<String, Integer, Boolean> { @Override protected void onPreExecute() { inicializaProgressBar(); progress.show(); } @Override protected Boolean doInBackground(String... param) { try(CadastrosControle cc = new CadastrosControle()){ try { EventoVO o = new EventoVO(); o.setId(Integer.parseInt(param[0])); cc.excluirEvento(o); return true; } catch (Exception e) { e.printStackTrace(); return false; } } } @Override protected void onPostExecute(Boolean result) { if (progress != null && progress.isShowing()) { progress.dismiss(); } if (result) { //atualiza lista de Eventos AsyncTask t = new popularGridTask().execute(""); try { t.get(); } catch (Exception ex) { ex.printStackTrace(); } Toast.makeText(getApplicationContext(), "Registro removido com sucesso!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Erro ao realizar a exclusão!", Toast.LENGTH_SHORT).show(); } } } }
33.297641
138
0.579604
33b792503ec93b8d67d0b7a7032ec29f7eab9a5d
1,064
package com.xxy.seckill.seckillmanagement.error; /** * @ClassName: BusinessException * @Description: 定义业务异常类, 包装器业务异常实现 * @Author: 13688 * @Date: 2019/4/29 0:17 * @Version: v1.0 **/ public class BusinessException extends Exception implements CommonError { private CommonError commonError; /** * 直接接收EmBusinessError的传参用于构造业务异常 * * @param commonError */ public BusinessException(CommonError commonError) { super(); this.commonError = commonError; } /** * 接收自定义errMsg的方式构造业务异常 */ public BusinessException(CommonError commonError, String errMsg) { super(); this.commonError = commonError; this.commonError.setErrMsg(errMsg); } @Override public int getErrCode() { return this.commonError.getErrCode(); } @Override public String getErrMsg() { return this.commonError.getErrMsg(); } @Override public CommonError setErrMsg(String errMsg) { this.commonError.setErrMsg(errMsg); return this; } }
21.714286
73
0.645677
236601f71ee821170f03cea836353b5b9bee1e47
2,679
package com.imenez.sms.producer.config; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.*; import java.util.HashMap; import java.util.Map; @Configuration @Slf4j @RequiredArgsConstructor public class SpringKafkaProducerConfig { @Value("${kafka.local.server.config}") public String KAFKA_LOCAL_SERVER_CONFIG; @Value("${kafka.listener.container.factory}") public String KAFKA_LISTENER_CONTAINER_FACTORY; @Value("${kafka.producer.key.serializer}") public String KAFKA_PRODUCER_KEY_SERIALIZER; @Value("${kafka.producer.value.serializer}") public String KAFKA_PRODUCER_VALUE_SERIALIZER; @Value("${kafka.producer.factory.groupid}") public String KAFKA_GROUP_ID_STRING; /*@Autowired private Environment env; private static Environment environment; environment.getProperty("handlesmsms.url")*/ @Bean public Map<String, Object> producerConfigs() { Map<String, Object> props = new HashMap<>(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_LOCAL_SERVER_CONFIG); //props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KAFKA_PRODUCER_KEY_SERIALIZER); //props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KAFKA_PRODUCER_VALUE_SERIALIZER); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.springframework.kafka.support.serializer.JsonSerializer"); //props.put(ProducerConfig.GROUP_ID_CONFIG, KAFKA_GROUP_ID_STRING); log.info("KAFKA_LOCAL_SERVER_CONFIG=> " + KAFKA_LOCAL_SERVER_CONFIG); log.info("KAFKA_LISTENER_CONTAINER_FACTORY=> " + KAFKA_LISTENER_CONTAINER_FACTORY); log.info("KAFKA_PRODUCER_KEY_SERIALIZER=> " + KAFKA_PRODUCER_KEY_SERIALIZER); log.info("KAFKA_PRODUCER_VALUE_SERIALIZER=> " + KAFKA_PRODUCER_VALUE_SERIALIZER); log.info("KAFKA_GROUP_ID_STRING=> " + KAFKA_GROUP_ID_STRING); return props; } @Bean public ProducerFactory<String, Object> producerFactory() { return new DefaultKafkaProducerFactory<>(producerConfigs()); } @Bean public KafkaTemplate<String, Object> kafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } }
38.271429
101
0.760732
4a3643748e8e783c621b15c4b3315224d0ab0c0f
180
package localhost.huskroot; /** * Created by Aaron Segbedzi on 11/27/2017. */ public class Config { public static final String remoteHost = "http://api.leefranco.com"; }
15
71
0.694444
7dfcd13fa33d5937286e1b26e6da38344431aca9
4,296
package com.jiuye.mcp.param.enums; /** * 应用信息 * * @author kevin * @date 2018-07-23 */ public enum ApplicationErrorCode { INVALID_ARGUMENTS("INVALID_ARGUMENTS", "Invalid parameter!"), ILLEGAL_ARGUMENTS("ILLEGAL_ARGUMENTS", "Illegal parameter: "), MISS_PARAM("MISS_PARAM","Missing parameter: vo is empty!"), QUERY_ERROR("QUERY_ERROR","Query failed!"), UPDATE_ERROR("UPDATE_ERROR","Updated failed!"), DELETE_ERROR("DELETE_ERROR","Deleted failed!"), CREATE_ERROR("CREATE_ERROR","Save failed!"), RESET_ERROR("RESET_ERROR","Reset failed!"), LOGIN_ERROR("LOGIN_ERROR","Login failed!"), LOGOUT_ERROR("LOGOUT_ERROR","Logout failed!"), USER_INVALID_STATUS("USER_INVALID_STATUS", "User is disabled!"), MISS_USER_EMAIL("MISS_USER_EMAIL", "Email is required!"), MISS_USER_PHONE("MISS_USER_PHONE", "Phone is required!"), MISS_USER_STATUS("MISS_USER_STATUS", "Please select user status!"), MISS_USER_ROLE("MISS_USER_ROLE", "Please select a user role!"), MISS_USER_PWD("MISS_USER_PWD", "Password is required!"), PWD_SAME_ERROR("PWD_SAME_ERROR", "New password and old password cannot be the same!"), EMAIL_PHONE_EXIST("EMAIL_PHONE_EXIST", "Email or mobile phone number has been duplicated, please modify.!"), SAME_USER_ERROR("SAME_USER_ERROR", "The username already exists and cannot be added!"), TOKEN_AUTHENTICATION_ERROR("TOKEN_AUTHENTICATION_ERROR","Identity authentication failed, please log in again!"), USER_PWD_ERROR("USER_PWD_ERROR","The username or password is incorrect!"), MISS_RULE_SUFFIX("MISS_RULE_SUFFIX","Rule suffix is required!"), TALE_RULE_SUFFIX_NULL("TALE_RULE_SUFFIX_NULL","Database table names do not contain rule suffixes!"), TRANSFORM_ERROR("TRANSFORM_ERROR","The rule intercepts the length beyond the field!"), SAME_ADD_ERROR("SAME_ROUTE_ERROR", "The same record information already exists in the database and cannot be added!"), SAME_EDIT_ERROR("SAME_EDIT_ERROR", "The same record information already exists in the database and cannot be edited!"), SAME_DATA_ERROR("SAME_DATA_ERROR", "The data record of the same name already exists in the database and cannot be continued!"), SAME_ROUTE_STATUS_ERROR("SAME_ROUTE_STATUS_ERROR", "A routing record with the same name already exists in the database. This route cannot be enabled!"), NO_PRIMAY_ERROR("NO_PRIMAY_ERROR", "There is a table with no primary key in the table you are converting, and you cannot batch convert it!"), CREATE_SCHEMA_ERROR("CREATE_SCHEMA_ERROR","Create target schema table error!"), MISS_ROUTENAME("MISS_ROUTENAME", "Route name is empty!"), MISS_SCHEMANAME("MISS_SCHEMANAME", "The schema name is empty or contains invalid characters!"), MISS_TARGETNAME("MISS_TARGETNAME", "The target name is empty!"), MISS_USER_NAME("MISS_USER_NAME", "Username is required!"), TARGET_GENERATION_ERROR("UPDATE_ERROR","Table generation failed!"), CREATE_JOB_ERROR("CREATE_JOB_ERROR","Save job failed!"), UPDATE_JOB_ERROR("UPDATE_JOB_ERROR","Modify job failed!"), CREATE_GROUP_ERROR("CREATE_GROUP_ERROR","Save job group failed!"), QUERY_TARGET_SCHEMA_ERROR("QUERY_TARGET_SCHEMA_ERROR","Terget schema information is not queried!"), SYNC_TABLE_NULL("SYNC_TABLE_NULL","There is no synchronizable table!"), CREATE_SYNC_TABLE_ERROR("CREATE_SYNC_TABLE_ERROR","Save full sync table failed!"), UPDATE_SYNC_TABLE_ERROR("UPDATE_SYNC_TABLE_ERROR","Modify full sync table failed!"), NODATA_ERROR("NODATA_ERROR","No data in the MCP table corresponding to the route!"), JOB_NAME_EXIST_MSG("JOB_NAME_EXIST_MSG","Job name already exists!"), JOB_RUNNING("JOB_RUNNING","The current source library's DDL Job is running!"), JOB_INCREORFULL_RUNNING("JOB_INCREORFULL_RUNNING","The current source library's INCRE OR FULL Job is running!"), NOT_FOUND_APP("NOT_FOUND_APP","Application information does not exist!"), DROP_TABLE_ERROR("DROP_TABLE_ERROR","Drop table failed!"); String code; String message; ApplicationErrorCode(String code, String message) { this.code = code; this.message = message; } public String getCode() { return this.code; } public String getMessage() { return this.message; } }
53.037037
156
0.744646
d72c2510dd5b26ba388accbc620375aba0e13700
1,645
package uk.gov.digital.ho.hocs.info.api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import uk.gov.digital.ho.hocs.info.api.dto.GetMembersAddressResponse; import uk.gov.digital.ho.hocs.info.api.dto.GetMembersResponse; import uk.gov.digital.ho.hocs.info.domain.model.Member; import java.util.Set; import java.util.UUID; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; @RestController public class MemberResource { private final MemberService memberService; @Autowired public MemberResource(MemberService memberService) { this.memberService = memberService; } @GetMapping(value = "/member", produces = APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<GetMembersResponse> getAllMembers() { Set<Member> members = memberService.getAllActiveMembers(); return ResponseEntity.ok(GetMembersResponse.from(members)); } @GetMapping(value = "/member/{uuid}", produces = APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<GetMembersAddressResponse> getMember(@PathVariable UUID uuid) { Member member = memberService.getMember(uuid); return ResponseEntity.ok(GetMembersAddressResponse.from(member)); } @GetMapping(value = "/admin/member/refresh") public ResponseEntity getFromApi() { memberService.updateWebMemberLists(); return ResponseEntity.ok().build(); } }
37.386364
89
0.771429