text
stringlengths 10
2.72M
|
|---|
package org.alienideology.jcord.internal.object.managers;
import org.alienideology.jcord.Identity;
import org.alienideology.jcord.handle.IInvite;
import org.alienideology.jcord.handle.audit.AuditAction;
import org.alienideology.jcord.handle.channel.IGuildChannel;
import org.alienideology.jcord.handle.guild.IGuild;
import org.alienideology.jcord.handle.managers.IInviteManager;
import org.alienideology.jcord.handle.permission.Permission;
import org.alienideology.jcord.internal.exception.PermissionException;
import org.alienideology.jcord.internal.object.IdentityImpl;
import org.alienideology.jcord.internal.object.ObjectBuilder;
import org.alienideology.jcord.internal.object.guild.Guild;
import org.alienideology.jcord.internal.rest.HttpPath;
import org.alienideology.jcord.internal.rest.Requester;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* @author AlienIdeology
*/
public final class InviteManager implements IInviteManager {
private Guild guild;
private IGuildChannel channel;
boolean isGuild;
public InviteManager(Guild guild) {
this.guild = guild;
this.channel = guild.getDefaultChannel();
this.isGuild = true;
}
public InviteManager(IGuildChannel channel) {
this.guild = (Guild) channel.getGuild();
this.channel = channel;
this.isGuild = false;
}
@Override
public Identity getIdentity() {
return guild.getIdentity();
}
@Override
public IGuild getGuild() {
return guild;
}
@Override
public IGuildChannel getGuildChannel() {
return channel;
}
@Override
public List<IInvite> getGuildInvites() {
if (!guild.getSelfMember().hasPermissions(true, Permission.MANAGE_SERVER)) {
throw new PermissionException(Permission.ADMINISTRATOR, Permission.MANAGE_SERVER);
}
List<IInvite> invites = new ArrayList<>();
ObjectBuilder builder = new ObjectBuilder((IdentityImpl) getIdentity());
JSONArray guildInvites = new Requester(getIdentity(), HttpPath.Invite.GET_GUILD_INVITES).request(guild.getId())
.getAsJSONArray();
for (int i = 0; i < guildInvites.length(); i++) {
JSONObject invite = guildInvites.getJSONObject(i);
invites.add(builder.buildInvite(invite));
}
return invites;
}
@Override
public List<IInvite> getChannelInvites() {
if (!channel.hasPermission(guild.getSelfMember(), Permission.ADMINISTRATOR, Permission.MANAGE_CHANNELS)) {
throw new PermissionException(Permission.ADMINISTRATOR, Permission.MANAGE_CHANNELS);
}
List<IInvite> invites = new ArrayList<>();
ObjectBuilder builder = new ObjectBuilder((IdentityImpl) getIdentity());
JSONArray guildInvites = new Requester(getIdentity(), HttpPath.Invite.GET_CHANNEL_INVITES).request(channel.getId())
.getAsJSONArray();
for (int i = 0; i < guildInvites.length(); i++) {
JSONObject invite = guildInvites.getJSONObject(i);
invites.add(builder.buildInvite(invite));
}
return invites;
}
@Override
@Nullable
public IInvite getInvite(String code) {
List<IInvite> invites = isGuild ? getChannelInvites() : getChannelInvites();
for (IInvite invite : invites) {
if (invite.getCode().equals(code)) {
return invite;
}
}
return null;
}
@Override
public AuditAction<IInvite> createInvite(int maxUses, long maxAge, boolean isTemporary, boolean isUnique) {
if (!guild.getSelfMember().hasPermissions(true, Permission.CREATE_INSTANT_INVITE)) {
throw new PermissionException(Permission.ADMINISTRATOR, Permission.CREATE_INSTANT_INVITE);
}
JSONObject json = new JSONObject()
.put("max_uses", maxUses)
.put("max_age", maxAge)
.put("temporary", isTemporary)
.put("unique", isUnique);
return new AuditAction<IInvite>((IdentityImpl) getIdentity(), HttpPath.Invite.CREATE_CHANNEL_INVITE, channel.getId()) {
@Override
protected IInvite request(Requester requester) {
JSONObject invite = requester.updateRequestWithBody(request -> request.body(json)).getAsJSONObject();
return new ObjectBuilder((IdentityImpl) getIdentity()).buildInvite(invite);
}
};
}
@Override
public AuditAction<Void> deleteInvite(String code) {
if (!guild.getSelfMember().hasPermissions(true, Permission.MANAGE_CHANNELS)) {
throw new PermissionException(Permission.ADMINISTRATOR, Permission.MANAGE_CHANNELS);
}
return new AuditAction<Void>((IdentityImpl) getIdentity(), HttpPath.Invite.DELETE_INVITE, code) {
@Override
protected Void request(Requester requester) {
requester.performRequest();
return null;
}
};
}
}
|
/*
* AppletGui.java
*
* Created on February 18, 2008, 6:05 PM
*/
package my.gui.applet;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container.*;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
//import java.awt.peer.FramePeer;
import java.io.*;
import java.net.*;
import java.net.URL;
import java.awt.Image;
import javax.imageio.*;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.table.TableColumn;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JComponent;
import java.awt.*;
import javax.swing.*;
import my.gui.applet.StringTokenizer;
import java.lang.Math;
import java.beans.PropertyVetoException;
import java.util.Arrays;
//Jimmy's change
import java.awt.font.*;
import java.awt.geom.*;
import java.util.zip.DataFormatException;
import java.util.Vector;
// ends of Jimmy's change
/**
*
* @author Nikhil, Jimmy
*/
public class AppletGui extends java.applet.Applet{
public boolean validRobotData = false;
public boolean validCommand0 = false;
public boolean validCommand1 = false;
public int pathPoints = 0;
public String[] path = new String[512];
public int historyPathPoints = 0;
public String[] historyPath = new String[1024];
public String objectString = "";
public int points = 0;
public int TrackCount = 0;
public int[] path_DataX= new int[1500];
public int[] path_DataY= new int[1500];
public int[] path_CamX= new int[1500];
public int[] path_CamY= new int[1500];
public int pathCamLength = 0;
//public int[] path_DataPreX= new int[1000];
//public int[] path_DataPreY= new int[1000];
public int pathLength = 0;
public int x_shift=200, y_shift=200;
public int SAFETY_REGION=15;
public byte RED = 1;
public byte GREEN = 2;
public byte BLUE = 3;
public double pi = 3.14159;
public String command;
//public String baseServer = "152.7.206.82";
public String baseServer = "152.7.206.28";
public String imageServer = "";
mySocket baseSocket = new mySocket();
//mySocket baseSocketUDP = new mySocket();
private int PORT_UDP_SEND = 4005;
private int PORT_UDP_RECV = 4006;
private int PORT_NUM_BASE = 5500;
// public String cppServer = "152.14.96.61";
public int selectedCam = 1;
private String imageData;
public String cData;
public boolean dataSocketConnected;
public String consoleCommand;
public String[] ParseIt;
public TableColumn column;
public String[] baseData;
public String objectData;
public boolean baseDataSocketConnected = false;
public boolean disconnectBaseDataThread = false;
public int oldRobotX = 0, oldRobotY = 0, robotX = 0, robotY = 0;
public double oldRobotO[] = new double[3];
public String[] robotData;
public int numberInHistory = 0;
public boolean robotInit = true;
boolean firsttime=true;
private static final int width = 340;
private static final int height = 320;
private double XRef = 210.0;
private double YRef = 160.0;
private BufferedImage Field = new BufferedImage(width+40, height+30, BufferedImage.TYPE_INT_ARGB);
//Graphics graphicsView = Field.getGraphics();
private int drawingSize = 10;
private int drawingSize2 = 12;
Font font = new Font("Dialog", Font.PLAIN, 12);
private double X[] = new double[3];
private double Y[] = new double[3];
//camNewX[] are predefined in prepare()
private int camNewX[] = new int[3];
private int camNewY[] = new int[3];
private int cam[] = new int[3];
public URL url1, url2, url3, url4;
public BufferedImage image1, image2, image3, image4;
public BufferedImage image = new BufferedImage(370, 270, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = image.getGraphics();
public BufferedImage imageAll = new BufferedImage(370, 270, BufferedImage.TYPE_INT_ARGB);
Graphics graphicsAll = imageAll.getGraphics();
private short cameraImage = 0;
private boolean gridOn = false;
private boolean curveGridOn = false;
final static float dash1[] = {1.0f};
private static BasicStroke dashed = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
private static BasicStroke dashed1 = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
private static BasicStroke dashed2 = new BasicStroke(1.9f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
final static BasicStroke normalStroke = new BasicStroke(2.0f);
final static BasicStroke thinStroke = new BasicStroke(1.0f);
private int destinationX = 0;
private int destinationY = 0;
private boolean coordinatesLabel = true;
private double safetyRegion = 0.15;
private int PathPlanning = 0;
private int abNetwork = 0;
private int bcNetwork = 0;
private boolean toBaseUsingTCP = true;
private boolean toCPPUsingTCP = true;
private boolean GSMOn = false;
private String ManualInput = "";
private String[] obstacles;// = {"5","1", "-72","75",
// "2", "-50","-14",
// "3", "27","-27",
// "2","-46","-123",
// "3","134","60"};
private String[] obstaclesEX;
private boolean getCoordinate = false;
private boolean firstDestination = true;
private boolean firstPath = true;
private boolean fvGrid = false;
private boolean getPath = false;
private boolean showPlanPath = false;
private double delay = 0.0;
private int columnOfDelay = 10;
private int rowOfCurvature = 20;
private double maxOfDelay = 5;
private double maxOfCurvature = 9999;
private double GSMGain[][] = new double[columnOfDelay][rowOfCurvature];
double kappa=0.0;
private double gain = 1;
private int currentRobot = 1; // 0 is red, 1 is green, 2 is blue
private boolean RefreshOn = false;
private int currentCam = 1;
//private int keysPressed = 0;
public static String BROADCAST_PORT1 = "42";
public static int PORT1 = 100;
public static String BROADCAST_PORT2 = "45";
public static int PORT2 = 110;
public static String BROADCAST_PORT3 = "48";
public static int PORT3 = 120;
public static String SPOT_ID1 = "0014.4F01.0000.049F"; //the Spot's IEEE address
public static String SPOT_ID2 = "0014.4F01.0000.06F0"; //the Spot's IEEE address
public static String SPOT_ID3 = "0014.4F01.0000.0499"; //the Spot's IEEE address
/****Second Thread for running the socket for the image processing****/
public Thread robotSocketThread= new Thread() {
public void run() {
System.out.println("Robot Loop Started");
pathCamLength = 0;
}
};
//This thread manages the automatic update functionality
public Thread camRefreshThread= new Thread() {
public void run() {
System.out.println("Cam Refresh Thread Started");
while(true) {
if (RefreshOn) {
double refreshTime = Double.parseDouble(RefreshRateInputField.getText());
realTimeRefreshCamera(cameraImage);
try {
camRefreshThread.sleep((int)refreshTime);
}
catch(InterruptedException e){
System.out.println(e);
}
}
else {
try {
camRefreshThread.sleep(100);
}
catch(InterruptedException e){
System.out.println(e);
}
}
}
}
};
public Thread baseDataThread= new Thread() {
String objectString="";
public void run() {
System.out.println("Thread baseDataThread started...");
while(true){
if (baseDataSocketConnected){
//System.out.println("Inside while loop : baseDataThread");
try {
baseDataThread.sleep(10);
}
catch(InterruptedException e){
System.out.println(e);
}
String baseInfo = "";
baseInfo = baseSocket.genRead();//if this returns null the socket has been closed
System.out.println(baseInfo);
if (baseInfo.length() > 0){
baseData = StringTokenizer.parseStringAsArray(baseInfo, " ");
if (baseData[0] == null){
System.out.println("NULL received");
}else if(baseData[0].equalsIgnoreCase("Exit")){//disconnect and exit the thread
baseSocket.stopClient();
baseDataSocketConnected = false;
disconnectBaseDataThread = true;
}
else if(baseData[0].equalsIgnoreCase("data")){//Update the table
updateTableBase(baseData);
}
else if(baseData[0].equalsIgnoreCase("object")){
commandHistory.setText(commandHistory.getText() + "\n" + "Object Data: " + baseInfo + "\n" + "--------------\n");
getCoordinate = true;
System.out.println("Obstacle data received");
objectString = baseInfo.substring(6);
//showObstacles(objectString);
getObstaclesCoordinates(baseInfo.substring(6));
getCoordinate = true;
//System.out.println("Obstacle data received "+baseInfo.substring(6));
DrawFieldView();
updateTableObjects(baseInfo.substring(6));
}else if(baseData[0].equalsIgnoreCase("robot")){
// getting the controlled robot data (only one robot) in a formate of: "robot # x y o"
cData = baseInfo.substring(7);
robotData = StringTokenizer.parseStringAsArray(cData, " ");
try{
Y[currentRobot] = Double.parseDouble(robotData[1]);//try reading array to see if its valid
validRobotData = true;
}
catch (NumberFormatException ex){
validRobotData = false;
}
if(validRobotData) {
System.out.println("robot data: " + cData);
X[currentRobot] = Double.parseDouble(robotData[0]);
Y[currentRobot] = Double.parseDouble(robotData[1]);
camNewX[currentRobot] = (int)TranslateX(Double.parseDouble(robotData[0]));
camNewY[currentRobot] = (int)TranslateY(Double.parseDouble(robotData[1]));
if( camNewX[currentRobot]>40 && camNewX[currentRobot]<width+40 && camNewY[currentRobot]>0 && camNewY[currentRobot]<height){
Graphics graphicsView = Field.getGraphics();
graphics.setColor(Color.BLACK);
oldRobotO[currentRobot] = Double.parseDouble(robotData[2]);
path_CamX[pathCamLength] = camNewX[currentRobot];
path_CamY[pathCamLength] = camNewY[currentRobot];
pathCamLength++;
DrawFieldView();
updateTableRobot();
}
}
else System.out.println("robot data was not valid");
}else if(baseData[0].equalsIgnoreCase("robots")){
//robot data for all trispots in format of "robots robot# x y o robot# x y o robot# x y o..."
//the incoming data can have two sets of data for one robot, the getRobotCoordinates function will overwrite the first one
cData = baseInfo.substring(6);
getRobotCoordinates(cData);
updateTableRobot();
DrawFieldView();
}
else if(baseData[0].equalsIgnoreCase("Robot_Selected")){
commandHistory.setText(commandHistory.getText() + "Current TriSpot:"+baseData[1]+ "\n");
updateTableRobot();
}
else if(baseData[0].equalsIgnoreCase("path")){
System.out.println("path received: " + baseInfo);
if(Integer.parseInt(baseData[1]) == 999) pathPoints = 0;
else if(Integer.parseInt(baseData[1]) == 997) {
//pathLength = pathPoints;
//System.out.println("path generated with " + pathLength + " points");
commandtoBase("imagecommand g"); //get the path
}
else if (Integer.parseInt(baseData[1]) == 998){
//
pathLength = pathPoints;
if(pathLength > 0) {
System.out.println("path generated with " + pathLength + " points");
DrawFieldView();
commandHistory.setText(commandHistory.getText() + "\n" + "Path Generation Successful!");
}
else commandHistory.setText(commandHistory.getText() + "\n" + "Path Generation Failed!");
}
else{
// getting world frame coordinates for path points
path_DataX[pathPoints] = (int)Double.parseDouble(baseData[1])-x_shift;
path_DataY[pathPoints] = (int)Double.parseDouble(baseData[2])-y_shift;
System.out.println("wX: "+path_DataX[pathPoints]+" wY: "+path_DataY[pathPoints]);
// convert path points to field view coordinates
path_DataX[pathPoints]=(TranslateX(path_DataX[pathPoints]));
path_DataY[pathPoints]=(TranslateY(path_DataY[pathPoints]));
System.out.println("X: "+path_DataX[pathPoints]+" Y: "+path_DataY[pathPoints]);
pathPoints++;
}
firstPath = false;
showPlanPath = true;
//DrawFieldView();
//UNNATI THE ARRAY OF PATH POINTS IS SAVED HERE
//path[pathPoints] = baseData[1] + " " + baseData[2];
//pathPoints++;
}
//GSM
else if(baseData[0].equalsIgnoreCase("gain")){
commandHistory.setText(commandHistory.getText() + "\n" + "Gain =" + Double.parseDouble(baseData[1]));
}
else if(baseData[0].equalsIgnoreCase("TCP")){
commandHistory.setText(commandHistory.getText() + "\n" + "Going to TCP Mode");
baseSocket.UDPCommands = false;
}
else if(baseData[0].equalsIgnoreCase("UDP")){
commandHistory.setText(commandHistory.getText() + "\n" + "Going to UDP Mode");
baseSocket.UDPCommands = true;
}
else {
commandHistory.setText(commandHistory.getText() + "\n" + "Base Message: " +baseInfo+ "\n" + "--------------\n");
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JScrollBar scrollBar = jScrollPane1.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
}
if (disconnectBaseDataThread){
break;
}
}
}
};
/** Initializes the applet AppletGui */
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
setSize(1035,710);
prepare();
setGSMGainTable();
System.out.println("Starting Socket Thread");
robotSocketThread.start();
camRefreshThread.start();
System.out.println("base Thread Started. Initializing Components");
System.out.println("Socket Thread Started. Initializing Components");
initComponents();
drawFieldViewRuler();
appletbaseCombo.setEnabled(false);
basecppnetwork.setEnabled(false);
System.out.println("Components Initialized");
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Handle the key typed event from the text field. */
public void keyTyped(KeyEvent evt) {
System.out.println("Key Code " + (int)evt.getKeyChar());
if ((int)evt.getKeyChar() == 27) {
EmergencyStop();
}
}
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
camLabel = new javax.swing.JLabel();
CamViewLabel = new javax.swing.JLabel();
Cam1Button = new javax.swing.JButton();
Cam2Button = new javax.swing.JButton();
Cam4Button = new javax.swing.JButton();
Cam3Button = new javax.swing.JButton();
allCamButton = new javax.swing.JButton();
refreshButton = new javax.swing.JButton();
gridButton = new javax.swing.JButton();
curveGrid = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
RefreshRateInputField = new javax.swing.JTextField();
RefreshDelayOn = new javax.swing.JRadioButton();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
SafetyRegionLabel = new javax.swing.JLabel();
SafetyRegionTextField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
PathPlanningCombo = new javax.swing.JComboBox();
GSMLabel = new javax.swing.JLabel();
GSMCombo = new javax.swing.JComboBox();
DelayGemLabel = new javax.swing.JLabel();
DelayGenTextField = new javax.swing.JTextField();
MoreButton = new javax.swing.JButton();
appletbaseCombo = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
basecppnetwork = new javax.swing.JComboBox();
FieldViewPanel = new javax.swing.JPanel();
FieldViewLabel = new javax.swing.JLabel();
clearButton = new javax.swing.JButton();
CoordinateLabelButton = new javax.swing.JButton();
GridOnOffButton = new javax.swing.JButton();
GetPathButton = new javax.swing.JButton();
RobotControlPanel = new javax.swing.JPanel();
ManualInputWindow = new javax.swing.JInternalFrame();
ManualInputTextField = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
ManualInputButton = new javax.swing.JButton();
ControlPanel = new javax.swing.JLabel();
RunButton = new javax.swing.JButton();
Trispot0Button = new javax.swing.JButton();
Trispot2Button = new javax.swing.JButton();
Trispot1Button = new javax.swing.JButton();
Trispot3Button = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
commandHistory = new javax.swing.JTextPane();
commandEntry = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
TablePanel = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
TableData = new javax.swing.JTable();
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
formPropertyChange(evt);
}
});
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Camera View"));
jPanel1.setName("Camera View"); // NOI18N
camLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
camLabel.setText("Camera");
CamViewLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
CamViewLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
CamViewLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CamViewLabelMouseClicked(evt);
}
});
Cam1Button.setText("Camera1");
Cam1Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Cam1ButtonActionPerformed(evt);
}
});
Cam2Button.setText("Camera2");
Cam2Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Cam2ButtonActionPerformed(evt);
}
});
Cam4Button.setText("Camera4");
Cam4Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Cam4ButtonActionPerformed(evt);
}
});
Cam3Button.setText("Camera3");
Cam3Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Cam3ButtonActionPerformed(evt);
}
});
allCamButton.setText("All Cam");
allCamButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
allCamButtonActionPerformed(evt);
}
});
refreshButton.setText("Refresh");
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshButtonActionPerformed(evt);
}
});
gridButton.setText("Grid On/Off");
gridButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gridButtonActionPerformed(evt);
}
});
curveGrid.setText("AccurateGrid");
curveGrid.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
curveGridActionPerformed(evt);
}
});
jLabel1.setText("Image Refresh Time (ms):");
RefreshRateInputField.setText("1000");
RefreshDelayOn.setText("Refresh Delay On");
RefreshDelayOn.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
RefreshDelayOn.setMargin(new java.awt.Insets(0, 0, 0, 0));
RefreshDelayOn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
RefreshDelayOnMousePressed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(141, 141, 141)
.addComponent(camLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(CamViewLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(6, 6, 6)
.addComponent(RefreshRateInputField, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Cam2Button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Cam1Button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(Cam3Button, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Cam4Button, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(allCamButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(refreshButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(RefreshDelayOn, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(gridButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(curveGrid, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(camLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CamViewLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(16, 16, 16)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Cam1Button)
.addComponent(Cam4Button)
.addComponent(allCamButton)
.addComponent(gridButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Cam2Button)
.addComponent(Cam3Button)
.addComponent(refreshButton)
.addComponent(curveGrid))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(RefreshRateInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(RefreshDelayOn))
.addContainerGap())
);
add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 0, 410, 440));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Parameter Setting"));
SafetyRegionLabel.setText("Safety Region");
SafetyRegionTextField.setText("0.15");
SafetyRegionTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SafetyRegionTextFieldActionPerformed(evt);
}
});
jLabel3.setText("Path Planning");
PathPlanningCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "FM", "OUM", "QPF" }));
PathPlanningCombo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PathPlanningComboActionPerformed(evt);
}
});
GSMLabel.setText("GSM");
GSMCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "GSM On", "GSM Off" }));
GSMCombo.setSelectedIndex(1);
GSMCombo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GSMComboActionPerformed(evt);
}
});
DelayGemLabel.setText("Delay Gen");
DelayGenTextField.setText("0.0");
DelayGenTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DelayGenTextFieldActionPerformed(evt);
}
});
MoreButton.setText("More");
MoreButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MoreButtonActionPerformed(evt);
}
});
appletbaseCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TCP", "UDP" }));
appletbaseCombo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
appletbaseComboActionPerformed(evt);
}
});
jLabel4.setText("Applet-Base Network");
jLabel6.setText("Base-Server Network");
basecppnetwork.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hybrid", "TCP", "UDP" }));
basecppnetwork.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basecppnetworkActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(SafetyRegionLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
.addComponent(SafetyRegionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
.addComponent(PathPlanningCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(GSMLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
.addComponent(GSMCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(11, 11, 11))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(DelayGemLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DelayGenTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(MoreButton, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addComponent(basecppnetwork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(appletbaseCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SafetyRegionLabel)
.addComponent(SafetyRegionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(PathPlanningCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(GSMLabel)
.addComponent(GSMCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel4)
.addComponent(appletbaseCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(basecppnetwork, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(DelayGemLabel))
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(MoreButton)
.addComponent(DelayGenTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(820, 0, 220, 190));
FieldViewPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Field View"));
FieldViewPanel.setName("Field View"); // NOI18N
FieldViewPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
FieldViewLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
FieldViewLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
FieldViewLabelMouseClicked(evt);
}
});
FieldViewPanel.add(FieldViewLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 390, 350));
clearButton.setText("Clear");
clearButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
clearButtonMouseClicked(evt);
}
});
FieldViewPanel.add(clearButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 390, 70, -1));
CoordinateLabelButton.setLabel("Label On/Off");
CoordinateLabelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CoordinateLabelButtonMouseClicked(evt);
}
});
FieldViewPanel.add(CoordinateLabelButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 390, 110, -1));
GridOnOffButton.setText("Grid On/Off");
GridOnOffButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
GridOnOffButtonMouseClicked(evt);
}
});
FieldViewPanel.add(GridOnOffButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 390, 100, -1));
GetPathButton.setText("Get Path");
GetPathButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GetPathButtonActionPerformed(evt);
}
});
FieldViewPanel.add(GetPathButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 390, -1, -1));
add(FieldViewPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 410, 440));
RobotControlPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Robot Control\n"));
RobotControlPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
ManualInputWindow.setClosable(true);
ManualInputWindow.setTitle("Manual Input");
ManualInputWindow.setNormalBounds(new java.awt.Rectangle(0, 0, 180, 180));
ManualInputWindow.setVerifyInputWhenFocusTarget(false);
ManualInputTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ManualInputTextFieldActionPerformed(evt);
}
});
javax.swing.GroupLayout ManualInputWindowLayout = new javax.swing.GroupLayout(ManualInputWindow.getContentPane());
ManualInputWindow.getContentPane().setLayout(ManualInputWindowLayout);
ManualInputWindowLayout.setHorizontalGroup(
ManualInputWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ManualInputWindowLayout.createSequentialGroup()
.addContainerGap()
.addComponent(ManualInputTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
.addContainerGap())
);
ManualInputWindowLayout.setVerticalGroup(
ManualInputWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ManualInputWindowLayout.createSequentialGroup()
.addContainerGap()
.addComponent(ManualInputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
RobotControlPanel.add(ManualInputWindow, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 210, 130));
jLabel10.setFont(new java.awt.Font("Tahoma", 3, 14));
jLabel10.setText("L");
RobotControlPanel.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 120, -1, -1));
jLabel11.setFont(new java.awt.Font("Tahoma", 3, 14));
jLabel11.setText("B");
RobotControlPanel.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 200, -1, -1));
jLabel12.setFont(new java.awt.Font("Tahoma", 3, 14));
jLabel12.setText("R");
RobotControlPanel.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 120, 10, -1));
jLabel9.setFont(new java.awt.Font("Tahoma", 3, 14));
jLabel9.setText("F");
RobotControlPanel.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 80, 10, -1));
ManualInputButton.setText("Manual Input");
ManualInputButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ManualInputButtonActionPerformed(evt);
}
});
RobotControlPanel.add(ManualInputButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 220, -1, -1));
ControlPanel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/gui/applet/Control_Panel.GIF"))); // NOI18N
ControlPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ControlPanelMouseClicked(evt);
}
});
RobotControlPanel.add(ControlPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 80, -1, -1));
RunButton.setText("Run");
RunButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
RunButtonMousePressed(evt);
}
});
RobotControlPanel.add(RunButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 220, -1, -1));
Trispot0Button.setText("Trispot0");
Trispot0Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Trispot0ButtonActionPerformed(evt);
}
});
RobotControlPanel.add(Trispot0Button, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, -1, -1));
Trispot2Button.setText("Trispot2");
Trispot2Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Trispot2ButtonActionPerformed(evt);
}
});
RobotControlPanel.add(Trispot2Button, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 50, -1, -1));
Trispot1Button.setText("Trispot1");
Trispot1Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Trispot1ButtonActionPerformed(evt);
}
});
RobotControlPanel.add(Trispot1Button, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 20, -1, -1));
Trispot3Button.setText("Trispot3");
Trispot3Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Trispot3ButtonActionPerformed(evt);
}
});
RobotControlPanel.add(Trispot3Button, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 50, -1, -1));
add(RobotControlPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(820, 190, 220, 250));
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Message Console"));
jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
commandHistory.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
commandHistoryCaretUpdate(evt);
}
});
jScrollPane1.setViewportView(commandHistory);
jPanel5.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 20, 270, 210));
commandEntry.setCursor(Cursor.getDefaultCursor());
commandEntry.setName(""); // NOI18N
commandEntry.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandEntryActionPerformed(evt);
}
});
jPanel5.add(commandEntry, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 240, 160, 20));
jLabel2.setText("Message");
jPanel5.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 46, -1, -1));
jLabel5.setText("History");
jPanel5.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 60, -1, -1));
jLabel7.setText("Command");
jPanel5.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(8, 233, -1, -1));
jLabel8.setText("Line");
jPanel5.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 247, -1, -1));
jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/gui/applet/halt.GIF"))); // NOI18N
jLabel13.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel13MouseClicked(evt);
}
});
jPanel5.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 230, 100, 30));
add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 440, 350, 270));
TablePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Data Viewer"));
TableData.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"Tri-Spot 1", null, null, null},
{" Encoder (mL, mR)", "", "", null},
{" Position (m)", null, null, null},
{" Velocity (m/s)", null, null, null},
{" Acceleration (m/s^2)", null, null, null},
{" Accelerometer (m/s^2)", null, null, null},
{" Cameras (cm)", null, null, null},
{null, null, null, null},
{"", "", "", null},
{null, null, "", null},
{null, null, "", null},
{null, null, "", null},
{null, null, "", null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Object Type", " X", " Y", "Orientation (rads)"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(TableData);
javax.swing.GroupLayout TablePanelLayout = new javax.swing.GroupLayout(TablePanel);
TablePanel.setLayout(TablePanelLayout);
TablePanelLayout.setHorizontalGroup(
TablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TablePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 658, Short.MAX_VALUE)
.addContainerGap())
);
TablePanelLayout.setVerticalGroup(
TablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
);
add(TablePanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 440, 690, 270));
}// </editor-fold>//GEN-END:initComponents
//Starts the currently selected UV tracking the generated path
private void RunButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RunButtonMousePressed
// TODO add your handling code here:
commandtoBase("track start");
}//GEN-LAST:event_RunButtonMousePressed
//Activates the emergency stop when the user hits the escape key (in theory) provided the applet has keyboard focus
//This does not seem to work when the UVs are actually connected and running
//When pressed stops the movement of all UVs
//This is the emergency stop button
private void jLabel13MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel13MouseClicked
// TODO add your handling code here:
EmergencyStop();
}//GEN-LAST:event_jLabel13MouseClicked
//Toggles the automatic Camera View refresh function on and off
private void RefreshDelayOnMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RefreshDelayOnMousePressed
// TODO add your handling code here:
RefreshOn = !RefreshDelayOn.isSelected();
if(!RefreshOn){camRefreshThread.interrupt();}
}//GEN-LAST:event_RefreshDelayOnMousePressed
//Increases the daly inserted by the delay generator by .05 seconds
private void MoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MoreButtonActionPerformed
// TODO add your handling code here:
commandtoBase("DELAY" + " " + (Double.parseDouble(DelayGenTextField.getText()) + 0.05));
double get = (Double.parseDouble(DelayGenTextField.getText()) + 0.05);
get = (int)(get*100); get = (double)(get/100);
String set = "" + get;
DelayGenTextField.setText(set);
}//GEN-LAST:event_MoreButtonActionPerformed
//Sets the currently controlled UV to UV 3
private void Trispot3ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Trispot3ButtonActionPerformed
// TODO add your handling code here:
String send = "connect trispot 0014.4F01.0000.0498 48 120";
commandtoBase(send);
Trispot3Button.setEnabled(false);
commandHistory.setText(commandHistory.getText() + "\n" + "Action: "+ send);
}//GEN-LAST:event_Trispot3ButtonActionPerformed
private void commandHistoryCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_commandHistoryCaretUpdate
// TODO add your handling code here:
}//GEN-LAST:event_commandHistoryCaretUpdate
//Sets the applet-base communication protocol to be used
private void appletbaseComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_appletbaseComboActionPerformed
// TODO add your handling code here:
JComboBox cb = (JComboBox)evt.getSource();
abNetwork = cb.getSelectedIndex();
if (abNetwork == 0) commandtoBase("TCP"); //TCP
else commandtoBase("UDP"); //UDP
}//GEN-LAST:event_appletbaseComboActionPerformed
//Selects the base-server communication protocol to be used
private void basecppnetworkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basecppnetworkActionPerformed
// TODO add your handling code here:
JComboBox cb = (JComboBox)evt.getSource();
bcNetwork = cb.getSelectedIndex();
if (bcNetwork == 0) {
commandtoBase("imagecommand u OFF"); //Hybrid: TCP for commands, UDP for data
try {Thread.sleep(250);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("imagecommand u2 ON");
}
else if (bcNetwork == 1) {
commandtoBase("imagecommand u OFF"); //All TCP
try {Thread.sleep(250);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("imagecommand u2 OFF");
}
else{
commandtoBase("imagecommand u ON"); //All UDP
try {Thread.sleep(250);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("imagecommand u2 ON");
}
}//GEN-LAST:event_basecppnetworkActionPerformed
private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange
// TODO add your handling code here:
}//GEN-LAST:event_formPropertyChange
//Sets the currently controlled UV to UV 2
private void Trispot2ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Trispot2ButtonActionPerformed
if(currentRobot !=2){
currentRobot = 2;// TODO add your handling code here:
pathCamLength = 0;
pathLength = 0;
DrawFieldView();
commandtoBase("imagecommand 2");
//commandHistory.setText(commandHistory.getText() + "Current TriSpot:"+baseSocket.readLine()+ "\n");
String send = "spotselect "+SPOT_ID3+" "+BROADCAST_PORT3+" "+PORT3;
commandtoBase(send);
commandHistory.setText(commandHistory.getText() + "\n" + "Action: "+ send);
}
}//GEN-LAST:event_Trispot2ButtonActionPerformed
//Sets the currently controlled Uv to UV 1
private void Trispot1ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Trispot1ButtonActionPerformed
if(currentRobot !=1){
currentRobot = 1;// TODO add your handling code here:
pathCamLength = 0;
pathLength = 0;
DrawFieldView();
commandtoBase("imagecommand 1");
String send = "spotselect "+SPOT_ID2+" "+BROADCAST_PORT2+" "+PORT2;
commandtoBase(send);
commandHistory.setText(commandHistory.getText() + "\n" + "Action: "+ send);
} //commandHistory.setText(commandHistory.getText()+ "Current TriSpot:" +baseSocket.readLine()+ "\n");
}//GEN-LAST:event_Trispot1ButtonActionPerformed
//Sets the currently controlled UV to UV 0
private void Trispot0ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Trispot0ButtonActionPerformed
if(currentRobot !=0){
currentRobot = 0;// TODO add your handling code here:
pathCamLength = 0;
pathLength = 0;
DrawFieldView();
commandtoBase("imagecommand 0");
String send = "spotselect "+SPOT_ID1+" "+BROADCAST_PORT1+" "+PORT1;
commandtoBase(send);
commandHistory.setText(commandHistory.getText() + "\n" + "Action: "+ send);
}//commandHistory.setText(commandHistory.getText() + "Current TriSpot:"+baseSocket.readLine()+ "\n");
}//GEN-LAST:event_Trispot0ButtonActionPerformed
//Gets the delay from the delay input field
//input in seconds
private void DelayGenTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelayGenTextFieldActionPerformed
delay = Double.parseDouble(DelayGenTextField.getText());
commandtoBase( "DELAY" + " " + DelayGenTextField.getText());
}//GEN-LAST:event_DelayGenTextFieldActionPerformed
//Gets the value input in the safety region field
private void SafetyRegionTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SafetyRegionTextFieldActionPerformed
SAFETY_REGION = (int)((Double.parseDouble(SafetyRegionTextField.getText()))*100);
safetyRegion = Double.parseDouble(SafetyRegionTextField.getText());
SafetyRegionTextField.setText("0.0");
SafetyRegionTextField.setText(Double.toString(safetyRegion));
commandtoBase("imagecommand s " + SAFETY_REGION + " " + SAFETY_REGION + " ");
}//GEN-LAST:event_SafetyRegionTextFieldActionPerformed
//Sets the selected path planning method
private void PathPlanningComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PathPlanningComboActionPerformed
JComboBox cb = (JComboBox)evt.getSource();
PathPlanning = cb.getSelectedIndex();
}//GEN-LAST:event_PathPlanningComboActionPerformed
//Toggles the GSM on or off
private void GSMComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GSMComboActionPerformed
int index = 0;
JComboBox cb = (JComboBox)evt.getSource();
index = cb.getSelectedIndex();
if(index == 0){
GSMOn = true;
commandtoBase("GSM true");
} else{
commandtoBase("GSM false");
GSMOn = false;
}
}//GEN-LAST:event_GSMComboActionPerformed
//Draws the planned path for the UV on the field view
private void GetPathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetPathButtonActionPerformed
ParseIt[1] = "";
getPath = true;
commandtoBase("imagecommand p " + destinationX + " " + destinationY);
getPath = false;
}//GEN-LAST:event_GetPathButtonActionPerformed
//Toggles the field view grid on and off when the GridOnOff button is pressed
private void GridOnOffButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_GridOnOffButtonMouseClicked
if(!fvGrid){
fvGrid = true;
}
else{
fvGrid = false;
}
DrawFieldView();
}//GEN-LAST:event_GridOnOffButtonMouseClicked
//Toggles the coordinate label of objects off and on when the LabelOn/Off button is pressed
private void CoordinateLabelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CoordinateLabelButtonMouseClicked
if(coordinatesLabel){
coordinatesLabel = false;
}
else{
coordinatesLabel = true;
}
DrawFieldView();
}//GEN-LAST:event_CoordinateLabelButtonMouseClicked
//Gets the text from the pop up text field that pops up when the user clicks on the Manual Input button
private void ManualInputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ManualInputTextFieldActionPerformed
ManualInput = ManualInputTextField.getText();
//destinationPreX = destinationX;
//destinationPreY = destinationY;
destinationX = (int)(Double.parseDouble(StringTokenizer.getX(ManualInput))*100);
destinationY = (int)(Double.parseDouble(StringTokenizer.getY(ManualInput))*100);
if(destinationX<180 && destinationX>-180 && destinationY<150 && destinationY>-150){
showPlanPath = false;
firstDestination = false;
DrawFieldView();
}
String trispotNumber = StringTokenizer.getTriNumber(ManualInput);
ManualInputTextField.setText("");
commandHistory.setText(commandHistory.getText() + "\n" +
" Move Trispot" + trispotNumber + " to (" + destinationX + "," + destinationY + ")");
try{ManualInputWindow.setClosed(true);}
catch(PropertyVetoException ex){System.out.println("closing not possible"+ex);}
}//GEN-LAST:event_ManualInputTextFieldActionPerformed
//Pops up a text field in a panel allowing the user to manually input movement commands to the currently controlled UV
private void ManualInputButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ManualInputButtonActionPerformed
//ManualInputWindow.show();
ManualInputWindow.setVisible(true);
try{ManualInputWindow.setClosed(false);}
catch(PropertyVetoException ex){System.out.println("closing not possible"+ex);}
ManualInputWindow.moveToFront();
}//GEN-LAST:event_ManualInputButtonActionPerformed
private void CamViewLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CamViewLabelMouseClicked
if (evt.getSource() == CamViewLabel){
int x = evt.getX();
int y = evt.getY();
switch(cameraImage){
case 1:
if(x>40 && x<=360 && y>0 && y<=240){
x=x - 40;
calCam1X(x);
calCam1Y(y);
}
break;
case 2:
if(x>40 && x<=360 && y>0 && y<=240){
x=x - 40-3;
y=y-2;
calCam2X(x);
calCam2Y(y);
}
break;
case 3:
if(x>40 && x<=360 && y>0 && y<=240){
x=x - 40;
y=y+3;
calCam3X(x);
calCam3Y(y);
}
break;
case 4:
if(x>40 && x<=360 && y>0 && y<=240){
x=x - 40;
calCam4X(x);
calCam4Y(y);
}
break;
case 5:
//destinationPreX = destinationX;
//destinationPreY = destinationY;
destinationX = (int)( ((double)(x-200))*100/75.0 );
destinationY = (int)( ((double)(120-y))*100/72.0 );
System.out.println("destinationx: " + destinationX);
break;
}
if(destinationX<180 && destinationX>-180 && destinationY<150 && destinationY>-150){
showPlanPath = false;
firstDestination = false;
DrawFieldView();
}
}
}//GEN-LAST:event_CamViewLabelMouseClicked
//Toggles the more accurate grid on the Camera View on and off
private void curveGridActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_curveGridActionPerformed
if(curveGridOn){
curveGridOn = false;
}
else{
curveGridOn = true;
}
switch(cameraImage){
case 1:
getCam1Image();
break;
case 2:
getCam2Image();
break;
case 3:
getCam3Image();
break;
case 4:
getCam4Image();
break;
case 5:
getAllImage1();
break;
}
}//GEN-LAST:event_curveGridActionPerformed
//Toggles the straight lined grid on the Camera View on and off
private void gridButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gridButtonActionPerformed
if(gridOn){
gridOn = false;
}
else{
gridOn = true;
}
switch(cameraImage){
case 1:
getCam1Image();
break;
case 2:
getCam2Image();
break;
case 3:
getCam3Image();
break;
case 4:
getCam4Image();
break;
case 5:
getAllImage1();
break;
}
}//GEN-LAST:event_gridButtonActionPerformed
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
switch(cameraImage){
case 1:
getCam1Image();
break;
case 2:
getCam2Image();
break;
case 3:
getCam3Image();
break;
case 4:
getCam4Image();
break;
case 5:
getAllImage1();
break;
}
//commandtoBase("imagecommand r"); //need to check if image server connected
}//GEN-LAST:event_refreshButtonActionPerformed
//This function is called in a thread to provide real time refreshing of the current camera view
private void realTimeRefreshCamera(int camera) {
switch(cameraImage){
case 1:
getCam1Image();
break;
case 2:
getCam2Image();
break;
case 3:
getCam3Image();
break;
case 4:
getCam4Image();
break;
case 5:
getAllImage1();
break;
}
}
private void allCamButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_allCamButtonActionPerformed
cameraImage = 5;
camLabel.setText("All 4 Camera View");
getAllImage1();
}//GEN-LAST:event_allCamButtonActionPerformed
//Sets the current camera view to camera four
private void Cam4ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Cam4ButtonActionPerformed
cameraImage = 4;
camLabel.setText("Camera 4 View");
getCam4Image();
}//GEN-LAST:event_Cam4ButtonActionPerformed
//Sets the current camera view to camera three
private void Cam3ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Cam3ButtonActionPerformed
cameraImage = 3;
camLabel.setText("Camera 3 View");
getCam3Image();
}//GEN-LAST:event_Cam3ButtonActionPerformed
//Sets the current camera view to camera two
private void Cam2ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Cam2ButtonActionPerformed
cameraImage = 2;
camLabel.setText("Camera 2 View");
getCam2Image();
}//GEN-LAST:event_Cam2ButtonActionPerformed
//Sets the current camera view to camera one
private void Cam1ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Cam1ButtonActionPerformed
cameraImage = 1;
camLabel.setText("Camera 1 View");
getCam1Image();
}//GEN-LAST:event_Cam1ButtonActionPerformed
//reacts to a user entering a manual command in the command line text field
private void commandEntryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandEntryActionPerformed
// TODO add your handling code here:
consoleCommand = commandEntry.getText();
commandEntry.setText("");
ParseIt = StringTokenizer.parseStringAsArray(consoleCommand, " ");
if(ParseIt[0].equalsIgnoreCase("set")){
if(ParseIt[1].equalsIgnoreCase("baseip")) baseServer = ParseIt[2];
if(ParseIt[1].equalsIgnoreCase("imageip")) imageServer = ParseIt[2];
}
else if(ParseIt[0].equalsIgnoreCase("init")){
ClearFieldView();
cameraImage = 5;
camLabel.setText("All 4 Camera View");
getAllImage1();
commandtoBase("base connect");
try {Thread.sleep(250);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("image connect");
try {Thread.sleep(250);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("imagecommand s " + SAFETY_REGION + " " + SAFETY_REGION + " ");
try {Thread.sleep(250);}
catch(InterruptedException e) {System.out.println(e);}
// scan all the camera, get all the trispots' coordinates, and set the current controlled trispot to trispot1
commandtoBase("imagecommand 0");
try {Thread.sleep(1000);}
catch(InterruptedException e) {System.out.println(e);}
//scan one camera where the current controlled trispot is at and get back the coordinate
commandtoBase("imagecommand o");
try {Thread.sleep(1000);}
catch(InterruptedException e) {System.out.println(e);}
//scan for all the robots
commandtoBase("imagecommand a");
try {Thread.sleep(1000);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("imagecommand r");
try {Thread.sleep(200);}
catch(InterruptedException e) {System.out.println(e);}
//commandtoBase("trispot connect");
commandtoBase("setID "+SPOT_ID1+" "+BROADCAST_PORT1+" "+PORT1+" "+SPOT_ID2+" "+BROADCAST_PORT2+" "+PORT2+" "+SPOT_ID3+" "+BROADCAST_PORT3+" "+PORT3);
try {Thread.sleep(1000);}
catch(InterruptedException e) {System.out.println(e);}
connectSpots();
}
else if(ParseIt[0].equalsIgnoreCase("mimic")){
destinationX = (int)(X[1]);
destinationY = (int)(Y[1]);
if(destinationX<180 && destinationX>-180 && destinationY<150 && destinationY>-150){
showPlanPath = false;
firstDestination = false;
DrawFieldView();
}
commandtoBase("imagecommand g");
}
else{
commandHistory.setText(commandHistory.getText() + "\n" + "Base Station Information: " + consoleCommand);
commandtoBase(consoleCommand); /*send Data to base*/
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JScrollBar scrollBar = jScrollPane1.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
}//GEN-LAST:event_commandEntryActionPerformed
public void connectSpots(){
String send = "";
send = "connect trispot "+SPOT_ID1+" "+BROADCAST_PORT1+" "+PORT1;
commandtoBase(send);
commandHistory.setText(commandHistory.getText() + "\n" + "Action: "+ send);
try {Thread.sleep(2000);}
catch(InterruptedException e) {System.out.println(e);}
send = "connect trispot "+SPOT_ID2+" "+BROADCAST_PORT2+" "+PORT2;
commandtoBase(send);
commandHistory.setText(commandHistory.getText() + "\n" + "Action: "+ send);
}
private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_formMouseClicked
private void FieldViewLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_FieldViewLabelMouseClicked
if (evt.getSource() == FieldViewLabel){
System.out.println(evt.getPoint().toString());
}
}//GEN-LAST:event_FieldViewLabelMouseClicked
//Clears the field view and redraws the obstacles, UV position, and destination when the clear button is pressed
private void clearButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearButtonMouseClicked
ClearFieldView();
//should check if image server is connect
//commandtoBase("imagecommand r");
DrawFieldView();
}//GEN-LAST:event_clearButtonMouseClicked
//When clicked gets the coordinate of the mousclick, and generates the appropriate command to the currently selected UV
private void ControlPanelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ControlPanelMouseClicked
if (evt.getSource() == ControlPanel) {
System.out.println(evt.getPoint().toString());
//This is a string of text commands to be sent to the UV. This way only the index of the command has to be assigned
String commands[] = {"f -1 0.08", "f -1 0.15", "f -1 0.22", "f -1 .3", "b -1 0.08","b -1 0.15", "b -1 0.22", "b -1 .3", "r -1 0.08","r -1 0.15", "r -1 0.22", "r -1 .3","l -1 0.08","l -1 0.15", "l -1 0.22", "l -1 .3", "s 0 0"};
int commandIndex = -1;
int X = evt.getX();
int Y = evt.getY();
//Forward Control
if(((X > 47)&&(X < 86))&&((Y > 28)&&(Y < 36))) commandIndex = 0;
if((X > 52&&X<81)&&(Y>21&&Y<27)) commandIndex = 1;
if((X > 56&&X<76)&&(Y>11&&Y<19)) commandIndex = 2;
if((X >61&&X<72)&&(Y>5&&Y<10)) commandIndex = 3;
//Backward Control
if((X >48&&X<86)&&(Y>97&&Y<105)) commandIndex = 4;
if((X >55&&X<81)&&(Y>107&&Y<113)) commandIndex = 5;
if((X >58&&X<78)&&(Y>115&&Y<122)) commandIndex = 6;
if((X >63&&X<73)&&(Y>124&&Y<131)) commandIndex = 7;
//Right Control
if((X >97&&X<105)&&(Y>46&&Y<85)) commandIndex = 8;
if((X >107&&X<113)&&(Y>52&&Y<80)) commandIndex = 9;
if((X >115&&X<122)&&(Y>57&&Y<75)) commandIndex = 10;
if((X >124&&X<132)&&(Y>62&&Y<71)) commandIndex = 11;
//Left Control
if((X >29&&X<36)&&(Y>49&&Y<87)) commandIndex = 12;
if((X >21&&X<27)&&(Y>54&&Y<82)) commandIndex = 13;
if((X >11&&X<19)&&(Y>58&&Y<77)) commandIndex = 14;
if((X >1&&X<10)&&(Y>63&&Y<73)) commandIndex = 15;
//Stop Button
if((X >39&&X<95)&&(Y>40&&Y<95)) commandIndex = 16;
if(commandIndex > -1){
if(baseDataSocketConnected){
baseSocket.genSend("spotcommand "+commands[commandIndex]);
if(commandIndex == 16){
baseSocket.genSend("track stop");
commandHistory.setText(commandHistory.getText() + "\n" + "Track STOP");
}
}
else System.out.println("Base Socket is not connected!");
System.out.println("command is: " + commands[commandIndex]);
commandHistory.setText(commandHistory.getText() + "\n" + "Motion Command: " + commands[commandIndex] + "\n" + "--------------\n");
}
}
}//GEN-LAST:event_ControlPanelMouseClicked
// Calculate the Destinatioin world frame X in cm when click anyone point on Camera 1 view
public void calCam1X(int x){
//destinationPreX = destinationX;
destinationX = (int)(6.0*30.38*((float)x-268.5)/223.5);
}
// Calculate the Destinatioin world frame Y in cm when click anyone point on Camera 1 view
public void calCam1Y(int y){
//destinationPreY = destinationY;
destinationY = (int)(5.0*30.38*(213.5-(float)y)/187.5);
}
// Calculate the Destinatioin world frame X in cm when click anyone point on Camera 2 view
public void calCam2X(int x){
//destinationPreX = destinationX;
destinationX = (int)(6.0*30.38*((float)x-276.5)/222.0);
}
// Calculate the Destinatioin world frame Y in cm when click anyone point on Camera 2 view
public void calCam2Y(int y){
//destinationPreY = destinationY;
destinationY = (int)(5.0*30.38*(40.0-(float)y)/182.0);
}
// Calculate the Destinatioin world frame X in cm when click anyone point on Camera 3 view
public void calCam3X(int x){
//destinationPreX = destinationX;
destinationX = (int)(6.0*30.38*((float)x-42.0)/222.0);
}
// Calculate the Destinatioin world frame Y in cm when click anyone point on Camera 3 view
public void calCam3Y(int y){
//destinationPreY = destinationY;
destinationY = (int)(5.0*30.38*(15.0-(float)y)/183.0);
}
// Calculate the Destinatioin world frame X in cm when click anyone point on Camera 4 view
public void calCam4X(int x){
//destinationPreX = destinationX;
destinationX = (int)(6.0*30.38*((float)x-43.0)/223.0);
}
// Calculate the Destinatioin world frame Y in cm when click anyone point on Camera 4 view
public void calCam4Y(int y){
//destinationPreY = destinationY;
destinationY = (int)(5.0*30.38*(206.5-(float)y)/186.0);
}
// Clear all the graphics on Field View
public void ClearFieldView() {
DrawIt();
}
// Connect to Base station through socket program
private void commandtoBase(String command){
ParseIt = StringTokenizer.parseStringAsArray(command, " ");
try{ //check if the 0 command is valid
if(ParseIt[0].equals(""));
validCommand0 = true;
}
catch( ArrayIndexOutOfBoundsException ex){
validCommand0 = false;
}
if(validCommand0)
{
if (ParseIt[0].equalsIgnoreCase("exit")){
baseSocket.genSend("exit");
baseDataSocketConnected = false;
disconnectBaseDataThread = true;
baseSocket.stopClient();
}
try{
if(ParseIt[1].equals(""));
validCommand1 = true;
}
catch( ArrayIndexOutOfBoundsException ex){
validCommand1 = false;
}
if(validCommand1){
if(ParseIt[1].equalsIgnoreCase("Connect")){
if (ParseIt[0].equalsIgnoreCase("base")){
try{
if(ParseIt[2].length() > 7) baseServer = ParseIt[2];
}
catch(ArrayIndexOutOfBoundsException e){
baseServer = baseServer;
}
System.out.println("base server; " + baseServer);
baseSocket.connectToServer(baseServer, PORT_NUM_BASE);
baseSocket.createUDPListener(PORT_UDP_RECV);
baseSocket.setUDPDestAddr(baseServer);
baseSocket.setUDPDestPort(PORT_UDP_SEND);
baseSocket.UDPCommands = false;
appletbaseCombo.setEnabled(true);
baseDataSocketConnected = true;
disconnectBaseDataThread = false;
new Thread(baseDataThread).start();
commandHistory.setText(commandHistory.getText() + "Connected to Base !\n");
commandHistory.setText(commandHistory.getText() + "TCP Connection to: " + baseServer + "::" + PORT_NUM_BASE + "\n");
commandHistory.setText(commandHistory.getText() + "UDP Listener on Port: " + PORT_UDP_RECV + "\n");
commandHistory.setText(commandHistory.getText() + "UDP Sender to: " + baseServer + "::" + PORT_UDP_SEND + "\n");
}else if(ParseIt[0].equalsIgnoreCase("image")){
if(imageServer.length() > 7) baseSocket.genSend("connect image " + imageServer);
else baseSocket.genSend("connect image");
basecppnetwork.setEnabled(true);
commandHistory.setText(commandHistory.getText() + "Connected to ImageProcessing Server !" + "\n" + "--------------\n");
}else if(ParseIt[0].equalsIgnoreCase("trispot")){
baseSocket.genSend("connect trispot");
commandHistory.setText(commandHistory.getText() + "\nConnecting to trispot");
}
}else if(ParseIt[1].equalsIgnoreCase("Disconnect")){
if (ParseIt[0].equalsIgnoreCase("base")){
baseSocket.genSend("disconnect base");
/*baseDataSocketConnected = false;
disconnectBaseDataThread = true;
baseSocket.stopClient();
baseSocketUDP.closeUDP();*/
appletbaseCombo.setEnabled(false);
commandHistory.setText(commandHistory.getText() + "\n" + "Disconnected from Base !" + "\n" + "--------------\n");
}else if(ParseIt[0].equalsIgnoreCase("image")){
basecppnetwork.setEnabled(false);
baseSocket.genSend("disconnect image");
commandHistory.setText(commandHistory.getText() + "\n" + "Disconnected from imageProcessing Server !" + "\n" + "--------------\n");
}
}else if(ParseIt[0].equalsIgnoreCase("imagecommand")){
if (ParseIt[1].equals("0")) currentRobot = 0;
else if (ParseIt[1].equals("1")) currentRobot = 1;
else if (ParseIt[1].equals("2")) currentRobot = 2; }
else if(ParseIt[1].equalsIgnoreCase("o")) commandHistory.setText(commandHistory.getText() + "\n" + "Request for Obstacle sent !" + "\n" + "--------------\n");
else if(ParseIt[1].equalsIgnoreCase("a")) commandHistory.setText(commandHistory.getText() + "\n" + "Request for all trispots sent !" + "\n" + "--------------\n");
baseSocket.genSend(command);
}
else{
baseSocket.genSend(command);
//commandHistory.setText(commandHistory.getText() + "\n" + "Received Data: " + baseSocket.readLine() + "\n" + "--------------\n");
}
}
else{
baseSocket.genSend(command);
//commandHistory.setText(commandHistory.getText() + "\n" + "Received Data: " + baseSocket.readLine() + "\n" + "--------------\n");
}
//}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JScrollBar scrollBar = jScrollPane1.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
}
// Draw destination on Field View with input of world frame X and Y
public void DrawDestination(int x, int y) {
Graphics graphicsView = Field.getGraphics();
//if(!firstDestination){
//System.out.println("erase");
//double x1=(double)destinationPreX;
//double y1=(double)destinationPreY;
//graphicsView.setColor(new Color(234,236,248));
//Polygon oct = GenerateOctagon((int)TranslateX(x1), (int)TranslateY(y1));
//graphicsView.drawPolygon(oct);
//String string1 = "Destination";
//String string2 = "(" + destinationPreX + "," + destinationPreY + ")";
//drawLabel(string1, string2, (int)TranslateX(x1), (int)TranslateY(y1)-drawingSize,new Color(234,236,248) );
//}
double x1=(double)x;
double y1=(double)y;
graphicsView.setColor(Color.MAGENTA);
Polygon oct = GenerateOctagon((int)TranslateX(x1), (int)TranslateY(y1));
graphicsView.drawPolygon(oct);
String string1 = "Destination";
String string2 = "(" + x + "," + y + ")";
drawLabel(string1, string2, (int)TranslateX(x1), (int)TranslateY(y1)-drawingSize, Color.MAGENTA);
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
firstDestination = false;
}
// Draw ruler on Field View
public void drawFieldViewRuler(){
Graphics graphicsView = Field.getGraphics();
graphicsView.setColor(Color.BLACK);
Graphics2D g3 = (Graphics2D) graphicsView;
g3.setColor(Color.BLACK);
g3.setStroke(normalStroke);
g3.drawRect(40,0,340,320);
//y axis and label
g3.drawString(" 1.5", 0,14);
g3.drawLine(36,10,40,10);
g3.drawString(" 1.0", 0,64);
g3.drawLine(36,60,40,60);
g3.drawString(" 0.5", 0,114);
g3.drawLine(36,110,40,110);
g3.drawString(" 0.0", 0,164);
g3.drawLine(36,160,40,160);
g3.drawString("-0.5", 0,214);
g3.drawLine(36,210,40,210);
g3.drawString("-1.0", 0,264);
g3.drawLine(36,260,40,260);
g3.drawString("-1.5", 0,314);
g3.drawLine(36,310,40,310);
//x axis and label
g3.drawString(" 1.8", 350,350);
g3.drawLine(363,320,363,324);
g3.drawString(" 1.5", 324,350);
g3.drawLine(337,320,337,324);
g3.drawString(" 1.0", 282,350);
g3.drawLine(295,320,295,324);
g3.drawString(" 0.5", 239,350);
g3.drawLine(252,320,252,324);
g3.drawString(" 0.0", 197,350);
g3.drawLine(210,320,210,324);
g3.drawString("-0.5", 154,350);
g3.drawLine(167,320,167,324);
g3.drawString("-1.0", 112,350);
g3.drawLine(125,320,125,324);
g3.drawString("-1.5", 69,350);
g3.drawLine(82,320,82,324);
g3.drawString("-1.8", 44,350);
g3.drawLine(57,320,57,324);
g3.setStroke(thinStroke);
g3.dispose();
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
}
// Fill a rectangler with background color to cover the Field View
public void DrawIt() {
Graphics graphicsView = Field.getGraphics();
//System.out.println(FieldViewLabel.getWidth());
//System.out.println(FieldViewLabel.getHeight());
graphicsView.setColor(new Color(234,236,248));
graphicsView.fillRect(41,0,379,319);
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
pathCamLength = 0;
fvGrid = false;
firstDestination = true;
}
// Draw all the components on Field View
public void DrawFieldView(){
Graphics graphicsView = Field.getGraphics();
String string1, string2;
// Cover old Field View Image
graphicsView.setColor(new Color(234,236,248));
graphicsView.fillRect(41,0,379,319);
// Draw Origin
graphicsView.setColor(Color.YELLOW);
graphicsView.fillOval((int)(XRef - 3), (int)(YRef - 3),6,6);
// Draw grid if grid is on
if(fvGrid){
Graphics2D g3 = (Graphics2D) graphicsView;
g3.setColor(Color.YELLOW);
g3.setStroke(dashed);
g3.drawLine(380,10,40,10);
g3.drawLine(380,60,40,60);
g3.drawLine(380,110,40,110);
g3.drawLine(380,160,40,160);
g3.drawLine(380,210,40,210);
g3.drawLine(380,260,40,260);
g3.drawLine(380,310,40,310);
//x axis and label
g3.drawLine(363,320,363,0);
g3.drawLine(337,320,337,0);
g3.drawLine(295,320,295,0);
g3.drawLine(252,320,252,0);
g3.drawLine(210,320,210,0);
g3.drawLine(167,320,167,0);
g3.drawLine(125,320,125,0);
g3.drawLine(82,320,82,0);
g3.drawLine(57,320,57,0);
g3.setStroke(thinStroke);
}
//Draw Obstacles
if(getCoordinate){
graphicsView.setColor(Color.BLACK);
for(int i = 1; i<(Integer.parseInt(obstacles[0])*3);){
int x = (int)Double.parseDouble(obstacles[i]);
i++;
int y = (int)Double.parseDouble(obstacles[i]);
i++;
i++;
graphicsView.drawOval((TranslateX(x)-10), (TranslateY(y)-10), 20, 20);
}
if(coordinatesLabel){
int i = 1;
while(i<(3*Integer.parseInt(obstacles[0]))){
int x = (int)Double.parseDouble(obstacles[i]);
i++;
int y = (int)Double.parseDouble(obstacles[i]);
i++;
String z = (obstacles[i]);
i++;
string1 = "Obstacle " + z;
string2 = "(" + x + "," + y + ")";
drawLabel(string1, string2, TranslateX(x), TranslateY(y)-drawingSize,Color.BLACK );
}
}
}
//Draw Trispot
if(!robotInit){
int i = 0;
while(i < 3){
Color mycolor = Color.BLACK;
if(i == 0){mycolor = (Color.RED);}
if(i == 1){mycolor = (Color.GREEN);}
if(i == 2){mycolor = (Color.BLUE);}
graphicsView.setColor(mycolor);
drawTrispot(camNewX[i], camNewY[i],oldRobotO[i], mycolor);
graphicsView.drawString(Integer.toString(i),camNewX[i]-2,camNewY[i]+3);
//System.out.println("drawing trispot here.................look at it");
if(coordinatesLabel){
graphicsView.setColor(Color.BLACK);
string1 = "Trispot"+i;
string2 = "(" + roundTwoDecimal(getRealX(camNewX[i])) + ", "
+ roundTwoDecimal(getRealY(camNewY[i]))+ ", "
+ roundTwoDecimal(Math.toDegrees(oldRobotO[i])) + ")";
drawLabel(string1, string2, camNewX[i], camNewY[i] - drawingSize,mycolor);
}
i++;
}
graphicsView.setColor(Color.BLACK);
graphicsView.drawPolyline(path_CamX,path_CamY,pathCamLength);
}
//Draw Destination and planning path
if(!firstDestination){
graphicsView.setColor(Color.MAGENTA);
Polygon oct = GenerateOctagon((int)TranslateX(destinationX), (int)TranslateY(destinationY));
graphicsView.drawPolygon(oct);
if(showPlanPath){
graphicsView.drawPolyline(path_DataX,path_DataY,pathLength);
}
if(coordinatesLabel){
string1 = "Destination";
string2 = "(" + destinationX + "," + destinationY + ")";
drawLabel(string1, string2, (int)TranslateX(destinationX), (int)TranslateY(destinationY)-drawingSize,Color.MAGENTA );
}
}
//Draw path
//Draw encoder path
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
//System.out.println("HAHA..................................333333333333333");
}
// Draw labels for obstacles and trispots on the Field View with input of two label strings and Field View coordinates of the objects.
public void drawLabel(String s1, String s2, double x, double y, Color c){
Graphics graphicsView = Field.getGraphics();
graphicsView.setColor(c);
FontRenderContext frc = ((Graphics2D)graphicsView).getFontRenderContext();
Rectangle2D bounds1 = font.getStringBounds(s1, frc);
Rectangle2D bounds2 = font.getStringBounds(s2, frc);
int xText1 =(int)x - (int)bounds1.getWidth()/2;
int yText1 =(int)y - (int)bounds2.getHeight()-(int)bounds1.getHeight()-(int)bounds1.getY();
int xText2 = (int)x - (int)bounds2.getWidth()/2;
int yText2 = (int)y - (int)bounds2.getHeight()-(int)bounds2.getY();
if ( (xText1 + (int)bounds1.getWidth())>(width+30)){
xText1 = (int)width+30 - (int)bounds1.getWidth()-drawingSize;
if(x > 500){
xText1 = (int)x;
}
}
if ( (yText1 - (int)bounds1.getHeight())<10){
yText1 = (int)y + 2*drawingSize +(int)bounds1.getHeight();
yText2 = yText1 + (int)bounds1.getHeight();
}
if ( (xText2 + (int)bounds2.getWidth())>(width+30)){
xText2 = (int)width+30 - (int)bounds2.getWidth()-drawingSize;
if(x > 500){
xText2 = (int)x;
}
}
if (xText1 < 40){
xText1 = 40+drawingSize;
}
if (xText2 < 40){
xText2 = 40+drawingSize;
}
graphicsView.drawString(s1, xText1, yText1);
graphicsView.drawString(s2, xText2, yText2);
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
}
// Draw the obstacle on the Field View with input of Field View coordinates of the objects and objects' number
public void DrawObstacle (int x, int y, int z) {
Graphics graphicsView = Field.getGraphics();
graphicsView.setColor(Color.red);
graphicsView.drawOval((TranslateX(x)-10), (TranslateY(y)-10), 20, 20);
String string1 = "Obstacle " + z;
String string2 = "(" + x + "," + y + ")";
drawLabel(string1, string2, TranslateX(x), TranslateY(y)-drawingSize, Color.BLACK);
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
}
// Draw the trispot on the Field View with input of Field View coordinates and orientation of the trispot
public void drawTrispot(int x, int y, double a, Color color){
Graphics graphicsView = Field.getGraphics();
graphicsView.setColor(color);
int[] X = {(int)(x + drawingSize2*Math.cos(a)),
(int)(x + drawingSize2*Math.cos(Math.toRadians(150) - a)),
(int)(x-drawingSize2*Math.cos(a - Math.toRadians(30)))};
int[] Y = {(int)(y - drawingSize2*Math.sin(a)),
(int)(y + drawingSize2*Math.sin(Math.toRadians(150) - a)),
(int)(y + drawingSize2*Math.sin(a - Math.toRadians(30)))};
graphicsView.drawPolygon(X, Y, 3);
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
}
// Generate an octagon for the destination of the trispot with input of Field View coordinates
public Polygon GenerateOctagon(int x, int y) {
int[] X = {x-10,x-4,x+4,x+10,x+10,x+4,x-4,x-10};
int[] Y = {y-4,y-10,y-10,y-4,y+4,y+10,y+10,y+4};
Polygon oct = new Polygon(X, Y, 8);
return oct;
}
// Get 4 camera images, combine them, and put it on Camera View with gird/noGrid, boundaries, and rulers.
public void getAllImage1(){
//dashed = dashed2;
//graphicsAll.setColor(new Color(240,240,240));
//graphicsAll.fillRect(0,0,40,240);
//graphicsAll.fillRect(0,240,370,270);
Graphics2D g2 = (Graphics2D) graphicsAll;
//g2.setColor(Color.BLACK);
//g2.setStroke(normalStroke);
//g2.drawLine(39,0,39,242);
//g2.drawLine(38,241,360,241);
getCam4Image();
if(graphicsAll.drawImage(image,200,0,360, 120, 42+40, 0, 320+40, 205, null)){
getCam3Image();
if(graphicsAll.drawImage(image,200,120,360, 240, 40+40,10, 310+40, 220, null)){
getCam2Image();
if(graphicsAll.drawImage(image,40,120,200, 240, 19+40,38, 280+40, 240, null)){
getCam1Image();
if(graphicsAll.drawImage(image,40,0,200,120, 0+40,5, 270+40, 215, null)){
g2.setStroke(thinStroke);
g2.setColor(Color.GREEN);
g2.drawRect(59,8,282,224);
dashed = dashed2;
graphicsAll.setColor(new Color(240,240,240));
graphicsAll.fillRect(0,0,40,240);
graphicsAll.fillRect(0,240,370,270);
g2.setColor(Color.BLACK);
g2.setStroke(normalStroke);
g2.drawLine(39,0,39,242);
g2.drawLine(38,241,360,241);
graphicsAll.setColor(Color.BLACK);
graphicsAll.drawString("(0,0)", 203, 117);
graphicsAll.drawLine(200,0, 200,242);
graphicsAll.drawLine(40,120,360,120);
//y labels
g2.drawString(" 1.5m",0,13 );
g2.drawLine(36,27, 40, 27);
g2.drawString(" 1.0m",0,52 );
g2.drawLine(36,65, 40, 65);
g2.drawString(" 0.5m",0,88 );
g2.drawLine(36,102, 40, 102);
g2.drawString(" 0.0m",0,124 );
g2.drawLine(36,137, 40, 137);
g2.drawString(" -0.5m",0,159 );
g2.drawLine(36,174, 40, 174);
g2.drawString(" -1.0m",0,198 );
g2.drawLine(36,212, 40, 212);
g2.drawString(" -1.5m",0,235 );
//x labels
g2.drawString("-2.0m", 32,260);
g2.drawLine(68,240, 68, 244);
g2.drawString("-1.5m", 69,260);
g2.drawLine(106,240, 106, 244);
g2.drawString("-1.0m", 107,260);
g2.drawLine(144,240, 144, 244);
g2.drawString("-0.5m", 145,260);
g2.drawLine(181,240, 181, 244);
g2.drawString(" 0.0m", 182,260);
g2.drawLine(217,240, 217, 244);
g2.drawString(" 0.5m", 217,260);
g2.drawLine(254,240, 254, 244);
g2.drawString(" 1.0m", 255,260);
g2.drawLine(291,240, 291, 244);
g2.drawString(" 1.5m", 292,260);
g2.drawLine(326,240, 326, 244);
g2.drawString(" 2.0m", 324,260);
g2.drawLine(360,240, 360, 244);
g2.setStroke(normalStroke);
g2.drawLine(36,9, 40, 9);
g2.drawLine(36,46, 40, 46);
g2.drawLine(36,84, 40, 84);
g2.drawLine(36,120, 40, 120);
g2.drawLine(36,155, 40, 155);
g2.drawLine(36,194, 40, 194);
g2.drawLine(36,231, 40, 231);
g2.drawLine(50,240, 50, 244);
g2.drawLine(87,240, 87, 244);
g2.drawLine(125,240, 125, 244);
g2.drawLine(163,240, 163, 244);
g2.drawLine(200,240, 200, 244);
g2.drawLine(235,240, 235, 244);
g2.drawLine(273,240, 273, 244);
g2.drawLine(310,240, 310, 244);
g2.drawLine(342,240, 342, 244);
if(gridOn){
dashed = dashed1;
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
g2.drawLine(342,0, 342, 242);
g2.drawLine(310,0, 310, 242);
g2.drawLine(273,0, 273, 242);
g2.drawLine(235,0, 235, 242);
g2.drawLine(163,0, 163, 242);
g2.drawLine(125,0, 125, 242);
g2.drawLine(87,0, 87, 242);
g2.drawLine(50,0, 50, 242);
//x direction grid
g2.drawLine(40,9, 360, 9);
g2.drawLine(40,46, 360, 46);
g2.drawLine(40,84, 360, 84);
g2.drawLine(40,155, 360, 155);
g2.drawLine(40,194, 360, 194);
g2.drawLine(40,231, 360, 231);
}
CamViewLabel.setIcon(new ImageIcon(imageAll));
}
}
}
}
dashed = dashed1;
}
// Get camera 1 images, put it on Camera View with grid/noGrid, boundaries, and rulers.
public void getCam1Image(){
try{
image1 = ImageIO.read(url1);
Graphics2D g2 = (Graphics2D) graphics;
if(graphics.drawImage(image1,40,0,360, 240, 0,0, 320, 240, null)){
// Boundry of the field
if(cameraImage==1){
g2.setColor(Color.GREEN);
g2.drawLine(80,23,360,23);
g2.drawLine(80,240,80,23);
}
if(gridOn && (cameraImage!= 5)){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
// Y direction grid
g2.drawLine(358,0, 358, 242);
g2.drawLine(335,0, 335, 242);
g2.drawLine(309,0, 309, 242);
g2.drawLine(279,0, 279, 242);
g2.drawLine(249,0, 249, 242);
g2.drawLine(216,0, 216, 242);
g2.drawLine(184,0, 184, 242);
g2.drawLine(154,0, 154, 242);
g2.drawLine(121,0, 121, 242);
g2.drawLine(90,0, 90, 242);
g2.drawLine(59,0, 59, 242);
//x direction grid
g2.drawLine(40,27, 360, 27);
g2.drawLine(40,57, 360, 57);
g2.drawLine(40,89, 360, 89);
g2.drawLine(40,121, 360, 121);
g2.drawLine(40,151, 360, 151);
g2.drawLine(40,182, 360, 182);
g2.drawLine(40,212, 360, 212);
}
if(curveGridOn){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
// Y direction grid
QuadCurve2D q = new QuadCurve2D.Float();
q.setCurve(354,0, 366, 220,348, 242);
g2.draw(q);
q.setCurve(330,0, 346, 150, 326, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(307,0, 315, 220, 302, 242);
g2.draw(q);
q.setCurve(279,0, 283, 220, 274, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(249,0, 253, 220, 245, 242);
g2.draw(q);
q.setCurve(217,0, 223, 180, 213, 241);
if(cameraImage !=5)g2.draw(q);
q.setCurve(186,0, 187, 220, 183, 242);
g2.draw(q);
if(cameraImage !=5)g2.drawLine(154,0, 154, 242);
q.setCurve(125,0, 111, 220, 123, 242);
g2.draw(q);
q.setCurve(95,0, 78, 180, 94, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(66,0, 45, 160, 65, 242);
g2.draw(q);
//x direction grid
q.setCurve(40,25, 190, 16, 360, 36);
g2.draw(q);
q.setCurve(40,57, 190, 48, 360, 63);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,87, 190, 81, 360, 93);
g2.draw(q);
q.setCurve(40,119, 190, 121, 360, 121);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,148, 190, 158, 360, 148);
g2.draw(q);
q.setCurve(40,178, 200, 189, 360, 178);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,210, 220, 225, 360, 204);
g2.draw(q);
}
if(cameraImage ==5){
g2.setStroke(normalStroke);
}
else{
g2.setStroke(thinStroke);
}
if(getCoordinate){
int i = 0;
while(i<(Integer.parseInt(obstacles[0])*3)){
int x1=0, y1=0;
//if(Integer.parseInt(obstacles[i+1])==1){
double x = Double.parseDouble(obstacles[i+1]);
double y = Double.parseDouble(obstacles[i+2]);
x1 = getSR1X(x)+40;
y1 = getSR1Y(y);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
int srx = (int)(safetyRegion*75);
//System.out.println("sr " + srx );
//int sry = safetyRegion*72;
if(srx !=0){
g2.setColor(Color.GREEN);
g2.drawOval(x1-25-srx,y1-25-srx,50+2*srx,50+2*srx);
}
//}
i=i+3;
}
}
if(!robotInit){
//if(cam[0]==1){
int i =0;
while(i<3){
int x1=0, y1=0;
x1 = getSR1X(X[i])+40;
y1 = getSR1Y(Y[i]);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
i++;
}
//}
}
}
graphics.setColor(new Color(240,240,240));
graphics.fillRect(0,0,40,240);
graphics.fillRect(0,240,370,270);
g2.setColor(Color.BLACK);
g2.setStroke(normalStroke);
g2.drawLine(39,0,39,242);
g2.drawLine(38,241,360,241);
g2.setColor(Color.BLACK);
if(gridOn){
//y labels
g2.drawString(" 1.5m",0,31 );
g2.drawLine(36,27, 40, 27);
g2.drawLine(36,57, 40, 57);
g2.drawString(" 1.0m",0,93 );
g2.drawLine(36,89, 40, 89);
g2.drawLine(36,121, 40, 121);
g2.drawString(" 0.5m",0,155 );
g2.drawLine(36,151, 40, 151);
g2.drawLine(36,182, 40, 182);
g2.drawString(" 0.0m",0,216 );
g2.drawLine(36,212, 40, 212);
g2.drawLine(36,236, 40, 236);
//x labels
g2.drawString("-2.0m", 41,260);
g2.drawLine(59,240, 59, 244);
g2.drawLine(90,240, 90, 244);
g2.drawString("-1.5m", 103,260);
g2.drawLine(121,240, 121, 244);
g2.drawLine(154,240, 154, 244);
g2.drawString("-1.0m", 166,260);
g2.drawLine(184,240, 184, 244);
g2.drawLine(216,240, 216, 244);
g2.drawString("-0.5m", 231,260);
g2.drawLine(249,240, 249, 244);
g2.drawLine(279,240, 279, 244);
g2.drawString(" 0.0m", 291,260);
g2.drawLine(309,240, 309, 244);
g2.drawLine(335,240, 335, 244);
g2.drawString(" 0.5m", 340,260);
g2.drawLine(358,240, 358, 244);
}
else{
//y labels
g2.drawString(" 1.5m",0,29 );
g2.drawLine(36,25, 40, 25);
g2.drawLine(36,57, 40, 57);
g2.drawString(" 1.0m",0,91 );
g2.drawLine(36,87, 40, 87);
g2.drawLine(36,119, 40, 119);
g2.drawString(" 0.5m",0,152 );
g2.drawLine(36,148, 40, 148);
g2.drawLine(36,178, 40, 178);
g2.drawString(" 0.0m",0,214 );
g2.drawLine(36,210, 40, 210);
g2.drawLine(36,238, 40, 238);
//x labels
g2.drawString("-2.0m", 47,260);
g2.drawLine(65,240, 65, 244);
g2.drawLine(94,240, 94, 244);
g2.drawString("-1.5m", 105,260);
g2.drawLine(123,240, 123, 244);
g2.drawLine(154,240, 154, 244);
g2.drawString("-1.0m", 165,260);
g2.drawLine(183,240, 183, 244);
g2.drawLine(213,240, 213, 244);
g2.drawString("-0.5m", 227,260);
g2.drawLine(245,240, 245, 244);
g2.drawLine(274,240, 274, 244);
g2.drawString(" 0.0m", 284,260);
g2.drawLine(302,240, 302, 244);
g2.drawLine(326,240, 326, 244);
g2.drawString(" 0.5m", 332,260);
g2.drawLine(348,240, 348, 244);
}
if (cameraImage !=5)
CamViewLabel.setIcon(new ImageIcon(image));
}
catch (IOException error){
System.out.println("Did you pitch an exception?");
System.out.println(error.toString());
}
}
// Get camera 2 images, put it on Camera View with grid/noGrid, boundaries, and rulers.
public void getCam2Image(){
try{
image2 = ImageIO.read(url2);
Graphics2D g2 = (Graphics2D) graphics;
if(graphics.drawImage(image2,40,0,360, 240, 0,0, 320, 240, null)){
if(cameraImage==2){
g2.setColor(Color.GREEN);
g2.drawLine(62,227,360,227);
g2.drawLine(62,0,62,227);
}
if(gridOn&& (cameraImage!= 5)){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
g2.drawLine(345,0, 345, 242);
g2.drawLine(320,0, 320, 242);
g2.drawLine(292,0, 292, 242);
g2.drawLine(262,0, 262, 242);
g2.drawLine(231,0, 231, 242);
g2.drawLine(199,0, 199, 242);
g2.drawLine(168,0, 168, 242);
g2.drawLine(137,0, 137, 242);
g2.drawLine(107,0, 107, 242);
g2.drawLine(78,0, 78, 242);
g2.drawLine(47,0, 47, 242);
//x direction grid
g2.drawLine(40,12, 360, 12);
g2.drawLine(40,42, 360, 42);
g2.drawLine(40,67, 360, 67);
g2.drawLine(40,96, 360, 96);
g2.drawLine(40,129, 360, 129);
g2.drawLine(40,160, 360, 160);
g2.drawLine(40,191, 360, 191);
g2.drawLine(40,223, 360, 223);
}
if(curveGridOn){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
QuadCurve2D q = new QuadCurve2D.Float();
q.setCurve(331,0, 355, 50,342, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(309,0, 328, 60,319, 242);
g2.draw(q);
q.setCurve(286,0, 296, 60,295, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(257,0, 268, 60,264, 242);
g2.draw(q);
q.setCurve(228,0, 235, 60,229, 242);
if(cameraImage !=5)g2.draw(q);
g2.drawLine(200,0, 200, 242);
q.setCurve(171,0, 167, 60,168, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(143,0, 131, 60,137, 242);
g2.draw(q);
q.setCurve(113,0, 103, 60,107, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(88,0, 70, 60,78, 242);
g2.draw(q);
q.setCurve(55,0, 38, 60,47, 242);
if(cameraImage !=5)g2.draw(q);
//x direction grid
q.setCurve(40,20, 200, 3,360, 20);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,45, 200, 24,360, 48);
g2.draw(q);
q.setCurve(40,70, 200, 57,360, 71);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,99, 200, 90,360, 99);
g2.draw(q);
q.setCurve(40,132, 200, 127,360, 130);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,157, 200, 161,360, 157);
g2.draw(q);
q.setCurve(40,187, 200, 197,360, 187);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,220, 200, 236,360, 218);
g2.draw(q);
}
if(cameraImage ==5){
g2.setStroke(normalStroke);
}
else{
g2.setStroke(thinStroke);
}
if(getCoordinate){
int i = 0;
while(i<(Integer.parseInt(obstacles[0])*3)){
int x1=0, y1=0;
//if(Integer.parseInt(obstacles[i+1])==2){
double x = Double.parseDouble(obstacles[i+1]);
double y = Double.parseDouble(obstacles[i+2]);
x1 = getSR2X(x)+40;
y1 = getSR2Y(y);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
int srx = (int)(safetyRegion*75);
//int sry = safetyRegion*72;
if(srx!=0){
g2.setColor(Color.GREEN);
g2.drawOval(x1-25-srx,y1-25-srx,50+2*srx,50+2*srx);
}
//}
i=i+3;
}
}
if(!robotInit){
//if(cam[0]==2){
int i =0;
while(i<3){
int x1=0, y1=0;
x1 = getSR2X(X[i])+40;
y1 = getSR2Y(Y[i]);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
i++;
}
//}
}
}
graphics.setColor(new Color(240,240,240));
graphics.fillRect(0,0,40,240);
graphics.fillRect(0,240,370,270);
g2.setColor(Color.BLACK);
g2.setStroke(normalStroke);
g2.drawLine(39,0,39,242);
g2.drawLine(38,241,360,241);
g2.setColor(Color.BLACK);
if(gridOn){
//y labels
g2.drawString(" 0.0m",0,46 );
g2.drawLine(36,12, 40, 12);
g2.drawLine(36,42, 40, 42);
g2.drawLine(36,67, 40, 67);
g2.drawString(" -0.5m",0,100 );
g2.drawLine(36,96, 40, 96);
g2.drawLine(36,129, 40, 129);
g2.drawString(" -1.0m",0,164 );
g2.drawLine(36,160, 40, 160);
g2.drawLine(36,191, 40, 191);
g2.drawString(" -1.5m",0,227 );
g2.drawLine(36,223, 40, 223);
//x labels
g2.drawString("-2.0m", 60,260);
g2.drawLine(47,240, 47, 244);
g2.drawLine(78,240, 78, 244);
g2.drawLine(107,240, 107, 244);
g2.drawString("-1.5m", 119,260);
g2.drawLine(137,240, 137, 244);
g2.drawLine(168,240, 168, 244);
g2.drawString("-1.0m", 181,260);
g2.drawLine(199,240, 199, 244);
g2.drawLine(231,240, 231, 244);
g2.drawString("-0.5m", 244,260);
g2.drawLine(262,240, 262, 244);
g2.drawLine(292,240, 292, 244);
g2.drawString(" 0.0m", 302,260);
g2.drawLine(320,240, 320, 244);
g2.drawLine(345,240, 345, 244);
}
else{
//y labels
g2.drawString(" 0.0m",0,49 );
g2.drawLine(36,20, 40, 20);
g2.drawLine(36,45, 40, 45);
g2.drawLine(36,70, 40, 70);
g2.drawString(" -0.5m",0,104 );
g2.drawLine(36,99, 40, 99);
g2.drawLine(36,132, 40, 132);
g2.drawString(" -1.0m",0,161 );
g2.drawLine(36,157, 40, 157);
g2.drawLine(36,187, 40, 187);
g2.drawString(" -1.5m",0,224 );
g2.drawLine(36,220, 40, 220);
//x labels
g2.drawString("-2.0m", 60,260);
g2.drawLine(47,240, 47, 244);
g2.drawLine(78,240, 78, 244);
g2.drawLine(107,240, 107, 244);
g2.drawString("-1.5m", 119,260);
g2.drawLine(137,240, 137, 244);
g2.drawLine(168,240, 168, 244);
g2.drawString("-1.0m", 182,260);
g2.drawLine(200,240, 200, 244);
g2.drawLine(229,240, 229, 244);
g2.drawString("-0.5m", 246,260);
g2.drawLine(264,240, 264, 244);
g2.drawLine(295,240, 295, 244);
g2.drawString(" 0.0m", 301,260);
g2.drawLine(319,240, 319, 244);
g2.drawLine(342,240, 342, 244);
}
if (cameraImage !=5)
CamViewLabel.setIcon(new ImageIcon(image));
}
catch (IOException error){
System.out.println("Did you pitch an exception?");
System.out.println(error.toString());
}
}
// Get camera 3 images, put it on Camera View with grid/noGrid, boundaries, and rulers.
public void getCam3Image(){
try{
image3 = ImageIO.read(url3);
Graphics2D g2 = (Graphics2D) graphics;
if(graphics.drawImage(image3,40,0,360, 240, 0,0, 320, 240, null)){
if(cameraImage==3){
g2.setColor(Color.GREEN);
g2.drawLine(316,0,316,200);
g2.drawLine(40,200,316,200);
}
if(gridOn&& (cameraImage!= 5)){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
g2.drawLine(345,0, 345, 242);
g2.drawLine(321,0, 321, 242);
g2.drawLine(293,0, 293, 242);
g2.drawLine(265,0, 265, 242);
g2.drawLine(234,0, 234, 242);
g2.drawLine(204,0, 204, 242);
g2.drawLine(173,0, 173, 242);
g2.drawLine(140,0, 140, 242);
g2.drawLine(110,0, 110, 242);
g2.drawLine(80,0, 80, 242);
g2.drawLine(52,0, 52, 242);
//x direction grid
g2.drawLine(40,11, 360, 11);
g2.drawLine(40,38, 360, 38);
g2.drawLine(40,68, 360, 68);
g2.drawLine(40,101, 360, 101);
g2.drawLine(40,133, 360, 133);
g2.drawLine(40,167, 360, 167);
g2.drawLine(40,198, 360, 198);
g2.drawLine(40,230, 360, 230);
}
if(curveGridOn){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
QuadCurve2D q = new QuadCurve2D.Float();
q.setCurve(335,0, 355, 50,355, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(315,0, 329, 60,330, 242);
g2.draw(q);
q.setCurve(288,0, 301, 50,303, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(261,0, 271, 50,272, 242);
g2.draw(q);
q.setCurve(232,0, 241, 50,241, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(202,0, 208, 50,208, 242);
g2.draw(q);
q.setCurve(172,0, 174, 50,174, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(142,0, 140, 50,140, 242);
g2.draw(q);
q.setCurve(113,0, 109, 50,110, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(85,0, 76, 50,80, 242);
g2.draw(q);
q.setCurve(59,0, 50, 50,52, 242);
if(cameraImage !=5)g2.draw(q);
//x direction grid
q.setCurve(40,17, 200, 0,360, 17);
g2.draw(q);
q.setCurve(40,43, 200, 30,360, 44);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,75, 200, 60,360, 70);
g2.draw(q);
q.setCurve(40,104, 200, 99,360, 100);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,136, 200, 130,360, 129);
g2.draw(q);
q.setCurve(40,165, 200, 174,360, 156);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,196, 200, 205,360, 185);
g2.draw(q);
q.setCurve(40,221, 200, 245,360, 210);
if(cameraImage !=5)g2.draw(q);
}
g2.setColor(Color.orange);
if(cameraImage ==5){
g2.setStroke(normalStroke);
}
else{
g2.setStroke(thinStroke);
}
if(getCoordinate){
int i = 0;
while(i<(Integer.parseInt(obstacles[0])*3)){
int x1=0, y1=0;
//if(Integer.parseInt(obstacles[i+1])==3){
double x = Double.parseDouble(obstacles[i+1]);
double y = Double.parseDouble(obstacles[i+2]);
x1 = getSR3X(x)+40;
y1 = getSR3Y(y);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
int srx = (int)(safetyRegion*75);
//int sry = safetyRegion*72;
if(srx!=0){
g2.setColor(Color.GREEN);
g2.drawOval(x1-25-srx,y1-25-srx,50+2*srx,50+2*srx);
}
//}
i=i+3;
}
//if(camX[0]>210 && camY[0]>160){
//}
}
if(!robotInit){
//if(cam[0]==3){
int i = 0;
while(i<3){
int x1=0, y1=0;
x1 = getSR3X(X[i])+40;
y1 = getSR3Y(Y[i]);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
i++;
}
//}
}
}
graphics.setColor(new Color(240,240,240));
graphics.fillRect(0,0,40,240);
graphics.fillRect(0,240,370,270);
g2.setColor(Color.BLACK);
g2.setStroke(normalStroke);
g2.drawLine(39,0,39,242);
g2.drawLine(38,241,360,241);
if(gridOn){
//y labels
g2.drawString(" 0.0m",0,15 );
g2.drawLine(36,11, 40, 11);
g2.drawLine(36,38, 40, 38);
g2.drawString(" -0.5m",0,72 );
g2.drawLine(36,68, 40, 68);
g2.drawLine(36,101, 40, 101);
g2.drawString(" -1.0m",0,137 );
g2.drawLine(36,133, 40, 133);
g2.drawLine(36,167, 40, 167);
g2.drawString(" -1.5m",0,202 );
g2.drawLine(36,198, 40, 198);
g2.drawLine(36,230, 40, 230);
//x labels
g2.drawString(" 0.0m", 62,260);
g2.drawLine(52,240, 52, 244);
g2.drawLine(80,240, 80, 244);
g2.drawLine(110,240, 110, 244);
g2.drawString(" 0.5m", 122,260);
g2.drawLine(140,240, 140, 244);
g2.drawLine(173,240, 173, 244);
g2.drawString(" 1.0m", 186,260);
g2.drawLine(204,240, 204, 244);
g2.drawLine(234,240, 234, 244);
g2.drawString(" 1.5m", 247,260);
g2.drawLine(265,240, 265, 244);
g2.drawLine(293,240, 293, 244);
g2.drawString(" 2.0m", 303,260);
g2.drawLine(321,240, 321, 244);
g2.drawLine(345,240, 345, 244);
}
else{
//y labels
g2.drawString(" 0.0m",0,21 );
g2.drawLine(36,17, 40, 17);
g2.drawLine(36,43, 40, 43);
g2.drawLine(36,75, 40, 75);
g2.drawString(" -0.5m",0,79 );
g2.drawLine(36,104, 40, 104);
g2.drawLine(36,136, 40, 136);
g2.drawString(" -1.0m",0,140 );
g2.drawLine(36,165, 40, 165);
g2.drawLine(36,196, 40, 196);
g2.drawString(" -1.5m",0,200 );
g2.drawLine(36,221, 40, 221);
//x labels
g2.drawString(" 0.0m", 62,260);
g2.drawLine(52,240, 52, 244);
g2.drawLine(80,240, 80, 244);
g2.drawLine(110,240, 110, 244);
g2.drawString(" 0.5m", 122,260);
g2.drawLine(140,240, 140, 244);
g2.drawLine(174,240, 174, 244);
g2.drawString(" 1.0m", 190,260);
g2.drawLine(208,240, 208, 244);
g2.drawLine(241,240, 241, 244);
g2.drawString(" 1.5m", 254,260);
g2.drawLine(272,240, 272, 244);
g2.drawLine(303,240, 303, 244);
g2.drawString(" 2.0m", 312,260);
g2.drawLine(330,240, 330, 244);
g2.drawLine(355,240, 355, 244);
}
if (cameraImage !=5)
CamViewLabel.setIcon(new ImageIcon(image));
}
catch (IOException error){
System.out.println("Did you pitch an exception?");
System.out.println(error.toString());
}
}
// Get camera 4 images, put it on Camera View with grid/noGrid, boundaries, and rulers.
public void getCam4Image(){
try{
image4 = ImageIO.read(url4);
Graphics2D g2 = (Graphics2D) graphics;
if(graphics.drawImage(image4,40,0,360, 240, 0, 0, 320, 240, null)){
if(cameraImage==4){
g2.setColor(Color.GREEN);
g2.drawLine(40,21,335,21);
g2.drawLine(335,21,335,240);
}
if(gridOn&& (cameraImage!= 5)){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
g2.drawLine(355,0, 355, 242);
g2.drawLine(330,0, 330, 242);
g2.drawLine(302,0, 302, 242);
g2.drawLine(272,0, 272, 242);
g2.drawLine(244,0, 244, 242);
g2.drawLine(211,0, 211, 242);
g2.drawLine(177,0, 177, 242);
g2.drawLine(145,0, 145, 242);
g2.drawLine(113,0, 113, 242);
g2.drawLine(83,0, 83, 242);
g2.drawLine(55,0, 55, 242);
//x direction grid
g2.drawLine(40,19, 360, 19);
g2.drawLine(40,47, 360, 47);
g2.drawLine(40,80, 360, 80);
g2.drawLine(40,110, 360, 110);
g2.drawLine(40,145, 360, 145);
g2.drawLine(40,175, 360, 175);
g2.drawLine(40,206, 360, 206);
g2.drawLine(40,236, 360, 236);
}
if(curveGridOn){
g2.setColor(Color.YELLOW);
g2.setStroke(dashed);
QuadCurve2D q = new QuadCurve2D.Float();
q.setCurve(352,0, 369, 50,347, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(328,0, 340, 100,324, 242);
g2.draw(q);
q.setCurve(300,0, 313, 100,296, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(272,0, 280, 100,270, 242);
g2.draw(q);
q.setCurve(244,0, 250, 100,241, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(211,0, 214, 100,211, 242);
g2.draw(q);
q.setCurve(180,0, 176, 100,179, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(148,0, 144, 100,149, 242);
g2.draw(q);
q.setCurve(117,0, 108, 100,118, 242);
if(cameraImage !=5)g2.draw(q);
q.setCurve(88,0, 80, 100,89, 242);
g2.draw(q);
q.setCurve(62,0, 49, 100,61, 242);
if(cameraImage !=5)g2.draw(q);
//g2.drawLine(55,0, 55, 242);
//x direction grid
q.setCurve(40,25, 200, 0,360, 28);
g2.draw(q);
q.setCurve(40,50, 200, 35,360, 55);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,80, 200, 71,360, 83);
g2.draw(q);
q.setCurve(40,110, 200, 110,360, 114);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,142, 200, 147,360, 141);
g2.draw(q);
q.setCurve(40,173, 200, 183,360, 170);
if(cameraImage !=5)g2.draw(q);
q.setCurve(40,202, 200, 211,360, 201);
g2.draw(q);
q.setCurve(40,229, 200, 245,360, 226);
if(cameraImage !=5)g2.draw(q);
}
if(cameraImage ==5){
g2.setStroke(normalStroke);
}
else{
g2.setStroke(thinStroke);
}
if(getCoordinate){
int i = 0;
while(i<(Integer.parseInt(obstacles[0])*3)){
int x1=0, y1=0;
//if(Integer.parseInt(obstacles[i+1])==4){
double x = Double.parseDouble(obstacles[i+1]);
double y = Double.parseDouble(obstacles[i+2]);
x1 = getSR4X(x)+40;
y1 = getSR4Y(y);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
int srx = (int)(safetyRegion*75);
//int sry = safetyRegion*72;
if(srx!=0){
g2.setColor(Color.GREEN);
g2.drawOval(x1-25-srx,y1-25-srx,50+2*srx,50+2*srx);
}
//}
i=i+3;
}
}
if(!robotInit){
//if(cam[0]==4){
int i =0;
while(i<3){
int x1=0, y1=0;
x1 = getSR4X(X[i])+40;
y1 = getSR4Y(Y[i]);
g2.setColor(Color.orange);
g2.drawOval(x1-25,y1-25,50,50);
i++;
}
//}
}
}
graphics.setColor(new Color(240,240,240));
graphics.fillRect(0,0,40,240);
graphics.fillRect(0,240,370,270);
g2.setColor(Color.BLACK);
g2.setStroke(normalStroke);
g2.drawLine(39,0,39,242);
g2.drawLine(38,241,360,241);
if(gridOn){
//y labels
g2.drawString(" 1.5m",0,23 );
g2.drawLine(36,19, 40, 19);
g2.drawLine(36,47, 40, 47);
g2.drawString(" 1.0m",0,84 );
g2.drawLine(36,80, 40, 80);
g2.drawLine(36,110, 40, 110);
g2.drawString(" 0.5m",0,149 );
g2.drawLine(36,145, 40, 145);
g2.drawLine(36,175, 40, 175);
g2.drawString(" 0.0m",0,210 );
g2.drawLine(36,206, 40, 206);
g2.drawLine(36,236, 40, 236);
//x labels
g2.drawString("-0.5m", 37,260);
g2.drawLine(55,240, 55, 244);
g2.drawLine(83,240, 83, 244);
g2.drawString("-0.0m", 95,260);
g2.drawLine(113,240, 113, 244);
g2.drawLine(145,240, 145, 244);
g2.drawString(" 0.5m", 159,260);
g2.drawLine(177,240, 177, 244);
g2.drawLine(211,240, 211, 244);
g2.drawString(" 1.0m", 226,260);
g2.drawLine(244,240, 244, 244);
g2.drawLine(272,240, 272, 244);
g2.drawString(" 1.5m", 284,260);
g2.drawLine(302,240, 302, 244);
g2.drawLine(330,240, 330, 244);
g2.drawString(" 2.0m", 337,260);
g2.drawLine(355,240, 355, 244);
}
else{
//y labels
g2.drawString(" 1.5m",0,29 );
g2.drawLine(36,25, 40, 25);
g2.drawLine(36,50, 40, 50);
g2.drawString(" 1.0m",0,84 );
g2.drawLine(36,80, 40, 80);
g2.drawLine(36,110, 40, 110);
g2.drawString(" 0.5m",0,146 );
g2.drawLine(36,142, 40, 142);
g2.drawLine(36,173, 40, 173);
g2.drawString(" 0.0m",0,206 );
g2.drawLine(36,202, 40, 202);
g2.drawLine(36,229, 40, 229);
//x labels
g2.drawString("-0.5m", 43,260);
g2.drawLine(61,240, 61, 244);
g2.drawLine(89,240, 89, 244);
g2.drawString(" 0.0m", 100,260);
g2.drawLine(118,240, 118, 244);
g2.drawLine(149,240, 149, 244);
g2.drawString(" 0.5m", 161,260);
g2.drawLine(179,240, 179, 244);
g2.drawLine(211,240, 211, 244);
g2.drawString(" 1.0m", 225,260);
g2.drawLine(243,240, 243, 244);
g2.drawLine(270,240, 270, 244);
g2.drawString(" 1.5m", 278,260);
g2.drawLine(296,240, 296, 244);
g2.drawLine(324,240, 324, 244);
g2.drawString(" 2.0m", 329,260);
g2.drawLine(347,240, 347, 244);
}
if (cameraImage !=5)
CamViewLabel.setIcon(new ImageIcon(image));
}
catch (IOException error){
System.out.println("Did you pitch an exception?");
System.out.println(error.toString());
}
}
// Calculate and reture GSM gain based on delay and curvature inputs
public double getGSMGain(double dela, double curv){
int c = (int)Math.round( ((double)columnOfDelay - 1.0) * dela / maxOfDelay) + 1;
int r = (int)Math.round( ((double)rowOfCurvature - 1.0) * curv / maxOfCurvature) + 1;
commandHistory.setText(commandHistory.getText() + "\n" + "New Gain is: " + GSMGain[c][r]
+ ", with delay: "+ dela + " and curvature: " + curv + "\n" + "--------------\n");
commandHistory.setText(commandHistory.getText() + "C: " + c + ", R: "+ r + "\n" + "--------------\n");
return GSMGain[c][r];
}
// Get obstacles' world frame coordinates with input string data from base station and store them to an array with formate of:
// [0] = number of obstacles, [1] or [4]..[1+3*i] = world frame X of the obstacles,
// [2] or [5]..[2+3*i] = world frame Y of the obstacles
// [3] or [6]..[3+3*i]= obstacle number
public void getObstaclesCoordinates(String obstacleData){
obstacles = new String[16];
obstacles = StringTokenizer.parseStringAsArray(obstacleData, " ");
int count = Integer.parseInt(obstacles[0]);
//int x = 0;
//int y = 0;
//int z = 0;
//for(int i = 1; i<(count*3);){
//x = (int)Double.parseDouble(obstacles[i]);
//i++;
//y = (int)Double.parseDouble(obstacles[i]);
//i++;
//if(x<=0 && y>=0){
//obstacles[i-3]="1";
//}
//if(x<=0 && y<0){
//obstacles[i-3]="2";
//}
//if(x>0 && y<0){
//obstacles[i-3]="3";
//}
//if(x>0 && y>0){
//obstacles[i-3]="4";
//}
//}
}
// Get trispot' world frame coordinates with input string data from base station and store them to an array with formate of:
// [0] or [4]..[0+4*i] = world frame # of the trispot
// [1] or [5]..[1+4*i] = world frame X of the trispot
// [2] or [6]..[2+4*i] = world frame Y of the trispot
// [3] or [7]..[3+4*i] = world frame angle of the trispot
public void getRobotCoordinates(String data){
String robotsData[] = new String[24];
robotsData = StringTokenizer.parseStringAsArray(data, " ");
int i = 0;
while(i < robotsData.length){
X[Integer.parseInt(robotsData[i])] = Double.parseDouble(robotsData[i+1]);
Y[Integer.parseInt(robotsData[i])] = Double.parseDouble(robotsData[i+2]);
camNewX[Integer.parseInt(robotsData[i])] = (int)TranslateX(Double.parseDouble(robotsData[i+1]));
camNewY[Integer.parseInt(robotsData[i])] = (int)TranslateY(Double.parseDouble(robotsData[i+2]));
oldRobotO[Integer.parseInt(robotsData[i])] = (Double.parseDouble(robotsData[i+3]));
System.out.println("robot" + i + "x " + robotsData[i+1] + " y " + robotsData[i+2] + " o " + robotsData[i+3]);
i = i+4;
}
robotInit = false;
}
// Get the Camera View X coordinate for camera 1 view with input of world frame X coordinate in cm
public int getSR1X (double x){
return (int)(x*223.5/6.0/30.38+268.5);
}
// Get the Camera View Y coordinate for camera 1 view with input of world frame Y coordinate in cm
public int getSR1Y (double y){
return (int)(213.5 - y*187.5/5.0/30.38);
}
// Get the Camera View X coordinate for camera 2 view with input of world frame X coordinate in cm
public int getSR2X (double x){
return (int)(x*222.0/6.0/30.38+276.5);
}
// Get the Camera View Y coordinate for camera 2 view with input of world frame Y coordinate in cm
public int getSR2Y (double y){
return (int)(40 - y*183.0/5.0/30.38);
}
// Get the Camera View X coordinate for camera 3 view with input of world frame X coordinate in cm
public int getSR3X (double x){
return (int)(x*222.0/6.0/30.38+42.0);
}
// Get the Camera View Y coordinate for camera 3 view with input of world frame Y coordinate in cm
public int getSR3Y (double y){
return (int)(15.0 - y*183.0/5.0/30.38);
}
// Get the Camera View X coordinate for camera 4 view with input of world frame X coordinate in cm
public int getSR4X (double x){
return (int)(x*223.0/6.0/30.38+43.0);
}
// Get the Camera View Y coordinate for camera 4 view with input of world frame Y coordinate in cm
public int getSR4Y (double y){
return (int)(206.5 - y*186.0/5.0/30.38);
}
// Get the world frame X in cm coordinate for Field View labels with input of Field View X coordinate
public double getRealX(double x){
double realX = (x-XRef)*400/(double)width;
return realX;
}
// Get the world frame Y in cm coordinate for Field View labels with input of Field View Y coordinate
public double getRealY(double y){
double realY = ((double)YRef-y)*320/(double)height;
return realY;
}
// Initialize all the url addresses
public void prepare(){
try
{
url1 = new URL("http://152.14.97.66:8001/axis-cgi/jpg/image.cgi?resolution=320x240");
//url2 = new URL("http://152.14.97.66:8002/axis-cgi/jpg/image.cgi?resolution=320x240");
url3 = new URL("http://152.14.97.66:8003/axis-cgi/jpg/image.cgi?resolution=320x240");
url4 = new URL("http://152.14.97.66:8004/axis-cgi/jpg/image.cgi?resolution=320x240");
url2 = new URL("http://152.14.97.66:8001/axis-cgi/jpg/image.cgi?resolution=320x240");
}
catch(MalformedURLException e)
{
System.out.println(e.toString());
}
camNewX[0]=1000;
camNewX[1]=1000;
camNewX[2]=1000;
}
// Draw obstacles with its labels on Field View with input of string data from C++
public void showObstacles(String obstacleData){
Graphics graphicsView = Field.getGraphics();
graphicsView.setColor(Color.YELLOW);
graphicsView.fillOval((int)(XRef - 3), (int)(YRef - 3),6,6);
obstaclesEX = new String[15];
obstaclesEX = StringTokenizer.parseStringAsArray(obstacleData, " ");
int count = Integer.parseInt(obstaclesEX[0]);
int x = 0;
int y = 0;
int z = 0;
for(int i = 1; i<(count*3);){
z = Integer.parseInt(obstaclesEX[i]);
i++;
x = (int)Double.parseDouble(obstaclesEX[i]);
i++;
y = (int)Double.parseDouble(obstaclesEX[i]);
i++;
//System.out.println("xyz " + x + " " + y + " " + z);
DrawObstacle(x,y,z);
}
graphicsView.dispose();
FieldViewLabel.setIcon(new ImageIcon(Field));
}
// Set the values for GSM gain table
public void setGSMGainTable(){
int c = 0; int r = 0;
while(c<columnOfDelay){
while(r<rowOfCurvature){
GSMGain[c][r] = 1;
//System.out.println("GSMGain[" + c + "][" + r + "]=" + GSMGain[c][r]);
r++;
}
c++;
r=0;
}
}
// Calculate the world frame X in cm to Field View X coordinate (int input, int output)
public int TranslateX (int x) {
return (int)((double)XRef + (double)x*((double)width/400.0));
}
// Calculate the world frame Y in cm to Field View Y coordinate (int input, int output)
public int TranslateY (int y) {
return (int)((double)YRef - (double)y*((double)height/320.0));
}
// Calculate the world frame X in cm to Field View X coordinate (double input, double output)
public double TranslateX (double x) {
return (double)XRef + x*((double)width/400.0);
}
// Calculate the world frame Y in cm to Field View Y coordinate (double input, double output)
public double TranslateY (double y) {
return (double)YRef - y*((double)height/320.0);
}
// Round all the double value with two decimal points
public double roundTwoDecimal(double value){
int intValue = (int)(value*100);
return ((double)intValue)/100;
}
// Update table objects information from C++
public void updateTableObjects(String info) {
int k = 1;
String[] objects = StringTokenizer.parseStringAsArray(info, " ");
int i = Integer.parseInt(objects[0]);
for(int j=1;j<i*3;j=j+3){
TableData.setValueAt("Object " + objects[j+2], k+7,0);
TableData.setValueAt(objects[j], k+7,1);
TableData.setValueAt(objects[j+1], k+7,2);
k++;
}
}
// Update table with information from Base station
public void updateTableBase(String[] info) {
TableData.setValueAt(info[2], 5,1);
TableData.setValueAt(info[3], 5,2);
TableData.setValueAt(info[4], 1,1);
TableData.setValueAt(info[5], 1,2);
TableData.setValueAt(info[6], 3,1);
TableData.setValueAt(info[7], 3,2);
TableData.setValueAt(info[8], 2,1);
TableData.setValueAt(info[9], 2,2);
TableData.setValueAt(info[10], 4,1);
TableData.setValueAt(info[11], 4,2);
TableData.setValueAt(info[12], 0,3);
}
// Update table trispot informatioin from C++
public void updateTableRobot() {
System.out.println("update table for robot");
TableData.setValueAt("Tri-spot" + currentRobot, 0,0);
TableData.setValueAt(camNewX[currentRobot], 6,1);
TableData.setValueAt(camNewY[currentRobot], 6,2);
TableData.setValueAt(oldRobotO[currentRobot], 6,3);
}
//This function performs an emergency stop on all UVs
private void EmergencyStop() {
//Code here to stop the vehicles
System.out.println("Emergency Stop Performed");
String send = "spotselect "+SPOT_ID1+" "+BROADCAST_PORT2+" "+PORT2;
commandtoBase(send);
try {Thread.sleep(100);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("spotcommand s 0 0");
try {Thread.sleep(100);}
catch(InterruptedException e) {System.out.println(e);}
send = "spotselect "+SPOT_ID2+" "+BROADCAST_PORT2+" "+PORT2;
commandtoBase(send);
try {Thread.sleep(100);}
catch(InterruptedException e) {System.out.println(e);}
commandtoBase("spotcommand s 0 0");
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Cam1Button;
private javax.swing.JButton Cam2Button;
private javax.swing.JButton Cam3Button;
private javax.swing.JButton Cam4Button;
private javax.swing.JLabel CamViewLabel;
private javax.swing.JLabel ControlPanel;
private javax.swing.JButton CoordinateLabelButton;
private javax.swing.JLabel DelayGemLabel;
private javax.swing.JTextField DelayGenTextField;
private javax.swing.JLabel FieldViewLabel;
private javax.swing.JPanel FieldViewPanel;
private javax.swing.JComboBox GSMCombo;
private javax.swing.JLabel GSMLabel;
private javax.swing.JButton GetPathButton;
private javax.swing.JButton GridOnOffButton;
private javax.swing.JButton ManualInputButton;
private javax.swing.JTextField ManualInputTextField;
private javax.swing.JInternalFrame ManualInputWindow;
private javax.swing.JButton MoreButton;
private javax.swing.JComboBox PathPlanningCombo;
private javax.swing.JRadioButton RefreshDelayOn;
private javax.swing.JTextField RefreshRateInputField;
private javax.swing.JPanel RobotControlPanel;
private javax.swing.JButton RunButton;
private javax.swing.JLabel SafetyRegionLabel;
private javax.swing.JTextField SafetyRegionTextField;
private javax.swing.JTable TableData;
private javax.swing.JPanel TablePanel;
private javax.swing.JButton Trispot0Button;
private javax.swing.JButton Trispot1Button;
private javax.swing.JButton Trispot2Button;
private javax.swing.JButton Trispot3Button;
private javax.swing.JButton allCamButton;
private javax.swing.JComboBox appletbaseCombo;
private javax.swing.JComboBox basecppnetwork;
private javax.swing.JLabel camLabel;
private javax.swing.JButton clearButton;
private javax.swing.JTextField commandEntry;
private javax.swing.JTextPane commandHistory;
private javax.swing.JButton curveGrid;
private javax.swing.JButton gridButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton refreshButton;
// End of variables declaration//GEN-END:variables
}
|
package org.ecsoya.yamail.ui.views;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.ecsoya.yamail.model.Yamail;
import org.ecsoya.yamail.utils.MailUtils;
import org.ecsoya.yamail.utils.StringUtils;
public class ContentView {
private Composite contents;
private Label subjectLabel;
private Label fromLabel;
private Label dateLabel;
private Label toLabel;
private Yamail currentYamail;
private Label hiddenPart;
private Composite visiblePart;
private Browser browser;
@Inject
public ContentView() {
}
@PostConstruct
public void postConstruct(Composite parent) {
contents = new Composite(parent, SWT.BORDER);
StackLayout layout = new StackLayout();
contents.setLayout(layout);
hiddenPart = new Label(contents, SWT.CENTER);
layout.topControl = hiddenPart;
visiblePart = new Composite(contents, SWT.NONE);
visiblePart.setLayout(new GridLayout());
Composite headerControl = new Composite(visiblePart, SWT.NONE);
headerControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL));
headerControl.setLayout(new GridLayout(2, false));
// headerControl.setData("style", "background-color:blue;");
Label label = new Label(headerControl, SWT.RIGHT);
label.setText("Subject:");
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
label.setData("style", "font-weight:bold;");
subjectLabel = new Label(headerControl, SWT.NONE);
subjectLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL));
label = new Label(headerControl, SWT.RIGHT);
label.setText("From:");
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
label.setData("style", "font-weight:bold;");
fromLabel = new Label(headerControl, SWT.NONE);
fromLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL));
label = new Label(headerControl, SWT.RIGHT);
label.setText("Date:");
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
label.setData("style", "font-weight:bold;");
dateLabel = new Label(headerControl, SWT.NONE);
dateLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL));
label = new Label(headerControl, SWT.RIGHT);
label.setText("To:");
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
label.setData("style", "font-weight:bold;");
toLabel = new Label(headerControl, SWT.NONE);
toLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL));
browser = new Browser(visiblePart, SWT.NONE);
browser.setLayoutData(new GridData(GridData.FILL_BOTH
| GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
}
@PreDestroy
public void preDestroy() {
}
@Focus
public void onFocus() {
if (contents != null && !contents.isDisposed()) {
contents.setFocus();
}
}
@Inject
public void setSelection(
@Optional @Named(IServiceConstants.ACTIVE_SELECTION) Object selection) {
Yamail newYamail = null;
if (selection instanceof IStructuredSelection) {
Object firstElement = ((IStructuredSelection) selection)
.getFirstElement();
if (firstElement instanceof Yamail) {
newYamail = (Yamail) firstElement;
}
}
setYamail(newYamail);
}
public void setYamail(Yamail newYamail) {
boolean equals = currentYamail == null ? newYamail == null
: currentYamail.equals(newYamail);
if (equals) {
return;
}
currentYamail = newYamail;
if (contents == null || contents.isDisposed()) {
return;
}
contents.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
refresh();
}
});
}
protected void refresh() {
if (contents == null || contents.isDisposed()) {
return;
}
StackLayout layout = (StackLayout) contents.getLayout();
if (currentYamail == null) {
layout.topControl = hiddenPart;
} else {
layout.topControl = visiblePart;
subjectLabel.setText(StringUtils.trimToEmpty(currentYamail
.getSubject()));
fromLabel.setText(StringUtils.toString(currentYamail.getFrom()));
dateLabel
.setText(StringUtils.toString(currentYamail.getSentDate()));
toLabel.setText(StringUtils.toString(currentYamail.getRecipients()));
String html = null;
try {
html = MailUtils.getHTMLText(currentYamail.getMessage());
} catch (Exception e) {
try {
String text = MailUtils.getBody(currentYamail.getMessage());
if (text != null) {
html = text;
}
} catch (Exception e1) {
}
}
browser.setText(html == null ? "" : html);
}
contents.layout();
}
}
|
import java.util.Scanner;
public class Faktoriyel {
static int fonksiyon(int sayi) {
int faktor = 1;
for (int i = 1; i <= sayi; i++) {
faktor = faktor * i;
}
return faktor;
}
public static void main(String[] args) {
int sayi, faktoriyel;
Scanner input = new Scanner(System.in);
do {
System.out.println("Faktöriyel almak için sayı giriniz(Çıkmak için -1 giriniz):");
sayi = input.nextInt();
if (sayi != -1) {
faktoriyel = fonksiyon(sayi);
System.out.println(sayi + "!=" + faktoriyel);
}
} while (sayi != -1);
System.out.println("Güle güle...");
}
}
|
package org.devapriya.shoppingbasket;
import java.util.ArrayList;
/**
* Main application entry point
* @author dbherath
*/
public class App
{
final static int itemListSize = 10;
final static int categoryListSize = 20;
private ArrayList<Category> categoryList;
private ShoppingBasketService basketService;
public App() {
basketService = new ShoppingBasketService();
basketService.fillShoppingBasket();
basketService.printShoppingBasket();
}
/**
* Main entry point
* @param args
*/
public static void main( String[] args )
{
App objApp = new App();
}
}
|
import java.io.Serializable;
public class City implements Serializable {
private static final double EQUATORIAL_RADIUS = 6378.1370D;
private double xPoint;
private double yPoint;
private String name;
public City() {}
// Construct a city with x, y location
public City(String name, double xPoint, double yPoint) {
this.xPoint = xPoint;
this.yPoint = yPoint;
this.name = name;
}
// Gets city's x coordinate
public double getxPoint() {
return xPoint;
}
// Sets city's x coordinate
public void setxPoint(double xPoint) {
this.xPoint = xPoint;
}
// Gets city's y coordinate
public double getyPoint() {
return yPoint;
}
// Sets city's y coordinate
public void setyPoint(double yPoint) {
this.yPoint = yPoint;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* calculate the distance to given city
* @param city
* @return the distance
*/
public double measureDistance(City city) {
double deltaX = (city.getxPoint() - this.getxPoint());
double deltaY = (city.getyPoint() - this.getyPoint());
double a = Math.pow(Math.sin(deltaY / 2D), 2D) + Math.cos(this.getyPoint()) * Math.cos(city.getyPoint()) *
Math.pow(Math.sin(deltaX / 2D), 2D);
return EQUATORIAL_RADIUS * 2D * Math.atan2(Math.sqrt(a), Math.sqrt(1D - a));
}
@Override
public String toString() {
return "{" + name + "}";
}
}
|
package com.bonree.dataspout;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @date 2019/11/6 11:35
* @author: <a href=mailto:xuzj@bonree.com>胥智钧</a>
* @Description:
**/
@SpringBootApplication
public class DataSpoutApplication {
public static void main(String[] args) {
SpringApplication.run(DataSpoutApplication.class, args);
}
}
|
package br.com.hbsis.testeandroidnatan.util;
import android.os.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by natan on 08/02/17.
*/
public class ApkUpdater {
private String urlApk="http://185.28.21.78/app.zip";
public File downloadNewVersion() throws IOException {
URL url = new URL(urlApk);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory().toString();
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "appv2.zip");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[4096];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
File newApk = new File(file,"hbsisv2.apk");
UnzipUtility unzipUtility = new UnzipUtility();
unzipUtility.unzip(outputFile.getAbsolutePath(),newApk.getAbsolutePath());
return newApk;
}
}
|
package com.tencent.mm.ui.chatting.viewitems;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.ak.g;
import com.tencent.mm.ak.o;
import com.tencent.mm.bg.d;
import com.tencent.mm.g.a.hv;
import com.tencent.mm.g.a.iy;
import com.tencent.mm.sdk.platformtools.c;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.viewitems.b.a;
class aa$d extends a {
ImageView uai;
TextView ucQ;
LinearLayout udr;
TextView uds;
ProgressBar udt;
ImageView udu;
ProgressBar udv;
ImageView udw;
aa$d() {
}
public final a q(View view, boolean z) {
super.dx(view);
this.hrs = (TextView) view.findViewById(R.h.chatting_time_tv);
this.ucQ = (TextView) view.findViewById(R.h.chatting_location_info);
this.uds = (TextView) view.findViewById(R.h.chatting_location_title);
this.udr = (LinearLayout) view.findViewById(R.h.chatting_location_panel);
this.udt = (ProgressBar) view.findViewById(R.h.chatting_load_progress);
this.hrH = view.findViewById(R.h.chatting_click_area);
this.mQc = (TextView) view.findViewById(R.h.chatting_user_tv);
this.jBR = (CheckBox) view.findViewById(R.h.chatting_checkbox);
this.gFD = view.findViewById(R.h.chatting_maskview);
this.udu = (ImageView) view.findViewById(R.h.chatting_location_bg);
this.udv = (ProgressBar) view.findViewById(R.h.chatting_location_address_progress);
this.udw = (ImageView) view.findViewById(R.h.chatting_content_pin);
if (!z) {
this.tZv = (ImageView) view.findViewById(R.h.chatting_state_iv);
this.uai = (ImageView) view.findViewById(R.h.chatting_status_tick);
}
this.uds.setTextSize(1, 16.0f);
this.ucQ.setTextSize(1, 12.0f);
return this;
}
public static void a(aa$d aa_d, bd bdVar, boolean z, int i, com.tencent.mm.ui.chatting.c.a aVar, aa$c aa_c, OnLongClickListener onLongClickListener) {
if (aa_d != null) {
Object obj;
aa_d.udr.setVisibility(8);
int fromDPToPix = com.tencent.mm.bp.a.fromDPToPix(aVar.tTq.getContext(), 236);
int fromDPToPix2 = com.tencent.mm.bp.a.fromDPToPix(aVar.tTq.getContext(), 90);
aa_d.uds.setMaxLines(1);
aa_d.ucQ.setMaxLines(1);
aa_d.ucQ.setText("");
if (d.QS("location")) {
x.d("MicroMsg.LocationItemHolder", "plugin found!");
iy iyVar = new iy();
iyVar.bSB.bSv = 1;
iyVar.bSB.bGS = bdVar;
com.tencent.mm.sdk.b.a.sFg.m(iyVar);
CharSequence charSequence = iyVar.bSC.bPu;
CharSequence charSequence2 = iyVar.bSC.bSE;
if ((charSequence != null || b(charSequence2, aVar)) && ((charSequence == null || !charSequence.equals("") || b(charSequence2, aVar)) && (charSequence == null || !charSequence.equals("err_not_started")))) {
aa_d.udv.setVisibility(8);
aa_d.udr.setVisibility(0);
x.d("MicroMsg.LocationItemHolder", "location info : " + charSequence);
if (b(charSequence2, aVar)) {
aa_d.uds.setVisibility(0);
aa_d.uds.setText(charSequence2);
if (charSequence == null || charSequence.equals("")) {
aa_d.ucQ.setVisibility(8);
} else {
aa_d.ucQ.setVisibility(0);
aa_d.ucQ.setText(charSequence);
}
} else {
aa_d.uds.setMaxLines(2);
aa_d.uds.setText(charSequence);
aa_d.ucQ.setVisibility(8);
}
} else {
x.d("MicroMsg.LocationItemHolder", "info error or subcore not started!");
aa_d.udv.setVisibility(0);
aa_d.udr.setVisibility(0);
aa_d.uds.setText("");
aa_d.ucQ.setText("");
}
} else {
aa_d.udt.setVisibility(0);
aa_d.udr.setVisibility(8);
}
ImageView imageView = aa_d.udu;
g Pf = o.Pf();
int i2 = R.g.location_msg;
int i3 = R.g.map_bg_mask_normal;
if (z) {
obj = "location_backgroup_key_from";
} else {
String obj2 = "location_backgroup_key_tor";
}
Bitmap bitmap = (Bitmap) Pf.dUr.get(obj2);
if (bitmap == null || bitmap.isRecycled()) {
bitmap = c.y(i2, i3, fromDPToPix, fromDPToPix2);
Pf.dUr.m(obj2, bitmap);
}
imageView.setImageBitmap(bitmap);
hv hvVar = new hv();
hvVar.bRi.bGS = bdVar;
hvVar.bRi.w = fromDPToPix;
hvVar.bRi.h = fromDPToPix2;
hvVar.bRi.bRn = R.g.map_bg_mask_normal;
hvVar.bRi.bRk = aa_d.udu;
hvVar.bRi.bRm = aa_d.udt;
hvVar.bRi.bRl = aa_d.udw;
com.tencent.mm.sdk.b.a.sFg.m(hvVar);
aa_d.hrH.setTag(new au(bdVar, aVar.cwr(), i, null, 0));
aa_d.hrH.setOnClickListener(aa_c);
aa_d.hrH.setOnLongClickListener(onLongClickListener);
aa_d.hrH.setOnTouchListener(((com.tencent.mm.ui.chatting.b.b.g) aVar.O(com.tencent.mm.ui.chatting.b.b.g.class)).ctw());
}
}
private static boolean b(String str, com.tencent.mm.ui.chatting.c.a aVar) {
return (str == null || str.equals("") || str.equals(aVar.tTq.getMMResources().getString(R.l.location_selected))) ? false : true;
}
}
|
package intheritance.constructor;
public class Motor extends Vehicle {
public String name ="자동차";
public int displacement;
public Motor() {
}
public Motor(double maxSpeed , int seater , int displacement) {
super(maxSpeed,seater);
//this.maxSpeed = maxSpeed;
//this.seater = seater;
}
public void printInfo() {
System.out.print(super.name+ " : "+ this.name);
System.out.println(",: 최대속도" + maxSpeed + " km");
System.out.print("정원 :" +seater + " 명");
System.out.println(", 배기량 :" + displacement + " cc ");
}
public static void main(String[] args) {
Motor myCar = new Motor(300,4,5000);
myCar.printInfo();
}
}
|
package objects;
import java.util.Objects;
/**
* CocktailImage representing an entry in the cocktail_images table
* @author Joel Benseler
*
*/
public class CocktailImage {
private Integer cocktailId;
private byte[] image;
public CocktailImage(Integer cocktailId, byte[] image) {
this.cocktailId = Objects.requireNonNull(cocktailId);
this.image = Objects.requireNonNull(image);
}
public Integer getCocktailId() {
return cocktailId;
}
public byte[] getImage() {
return image;
}
}
|
package besic.borna.youtubemp3downloader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.PowerManager;
import android.widget.Toast;
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;
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock wakeLock;
private String filename;
private ProgressDialog progressDialog;
private Activity activity;
public DownloadTask(Context context, Activity activity, String filename, ProgressDialog progressDialog) {
this.context = context;
this.activity=activity;
this.filename=filename.replace("/", "");
this.progressDialog=progressDialog;
}
@Override
protected String doInBackground(String... urls) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
File dir = new File(Environment.getExternalStorageDirectory(), "YouTube MP3 Downloader");
if(!dir.exists()) dir.mkdirs();
File file = new File(dir, filename);
try {
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
this.activity.finish();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wakeLock.acquire();
progressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
wakeLock.release();
progressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Download successful!", Toast.LENGTH_SHORT).show();
this.activity.finish();
}
}
|
package ca.aequilibrium.weather.network;
public class NetworkConstants {
public static String openWeatherApiUrl = "http://api.openweathermap.org/data/2.5";
public static String openWeatherImgUrl = "http://api.openweathermap.org/img/w/";
public static String openWeatherCurrentForecastPath = "/weather";
public static String openWeatherFiveDayForecastPath = "/forecast";
}
|
package com.argentinatecno.checkmanager.main.activity_maturities;
import android.content.Context;
import com.argentinatecno.checkmanager.db.DataBaseController;
import com.argentinatecno.checkmanager.entities.Check;
import com.argentinatecno.checkmanager.entities.Maturities;
import com.argentinatecno.checkmanager.lib.base.EventBus;
import com.argentinatecno.checkmanager.main.activity_maturities.events.MaturitiesEvent;
import java.util.ArrayList;
import java.util.List;
public class MaturitiesRepositoryImpl implements MaturitiesRepository {
EventBus eventBus;
DataBaseController dataBaseController;
Double amountOwn = 0.0, amountOtherInBag = 0.0, amountOtherDelivery = 0.0, totalAmount = 0.0;
int quantityOwn = 0, quantityOtherInBag = 0, quantityOtherDelivery = 0, totalQuantity = 0;
String numbersOwn = null;
String numbersOtherInBag = null;
String numbersOtherDelivery = null;
List<Check> arrayChecks = new ArrayList<Check>();
Maturities maturities;
Context context;
public MaturitiesRepositoryImpl(Context context, EventBus eventBus) {
this.context = context;
this.eventBus = eventBus;
}
@Override
public void selectMaturities(String since, String until) {
try {
if (since != null && until != null) {
instanceController(context);
arrayChecks = dataBaseController.selectMaturities(since, until);
if (arrayChecks != null) {
maturities = new Maturities();
if (arrayChecks.size() > 0) {
for (int i = 0; i < arrayChecks.size(); i++) {
if (arrayChecks.get(i).getType() == 1) {//own
amountOwn += Double.parseDouble(arrayChecks.get(i).getAmount());
quantityOwn++;
} else if (arrayChecks.get(i).getType() == 0 && (arrayChecks.get(i).getDestiny() == "" || arrayChecks.get(i).getDestiny() == null)) {//other in bag
amountOtherInBag += Double.parseDouble(arrayChecks.get(i).getAmount());
quantityOtherInBag++;
} else {
amountOtherDelivery += Double.parseDouble(arrayChecks.get(i).getAmount());
quantityOtherDelivery++;
}
}
totalAmount = amountOtherDelivery + amountOtherInBag + amountOwn;
totalQuantity = quantityOtherDelivery + quantityOtherInBag + quantityOwn;
addEntityPost(maturities, false, arrayChecks);
cleanString();
} else {
cleanString();
addEntityPost(maturities, true, arrayChecks);
}
}
} else if (since == null) {
post("Fecha invalida.(Desde)", true);
} else if (until == null) {
post("Fecha invalida.(Hasta)", true);
}
} catch (Exception e) {
post(MaturitiesEvent.errorSelect, true);
}
}
public void addEntityPost(Maturities maturities, boolean isEmpty, List<Check> checkList) {
addEntity(maturities);
if (isEmpty)
post(MaturitiesEvent.emptySelect, false);
else
post(maturities);
}
private void post(Maturities checkMaturities, String error, String empty, List<Check> checkList) {
MaturitiesEvent event = new MaturitiesEvent();
event.setError(error);
event.setEmpty(empty);
event.setCheckList(checkList);
event.setMaturities(checkMaturities);
eventBus.post(event);
}
private void post(String errorOrEmpty, boolean isError) {
if (isError)
post(null, errorOrEmpty, null, null);
else
post(maturities, null, errorOrEmpty, arrayChecks);
}
private void post(Maturities maturities) {
post(maturities, null, null, arrayChecks);
}
public void instanceController(Context context) {
dataBaseController = new DataBaseController(context);
}
public void addEntity(Maturities maturities) {
maturities.setAmountTotal(String.valueOf(totalAmount));
maturities.setQuantityTotal(String.valueOf(totalQuantity));
maturities.setAmountOther(String.valueOf(amountOtherDelivery+amountOtherInBag));
maturities.setQuantityOther(String.valueOf(quantityOtherDelivery+quantityOtherInBag));
maturities.setAmountOwn(String.valueOf(amountOwn));
maturities.setQuantityOwn(String.valueOf(quantityOwn));
}
public void cleanString() {
numbersOwn = "";
numbersOtherInBag = "";
numbersOtherDelivery = "";
arrayChecks.isEmpty();
amountOwn = 0.0;
amountOtherInBag = 0.0;
amountOtherDelivery = 0.0;
totalAmount = 0.0;
quantityOwn = 0;
quantityOtherInBag = 0;
quantityOtherDelivery = 0;
totalQuantity = 0;
}
}
|
package com.lingnet.vocs.dao.impl.monit;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.lingnet.common.dao.impl.BaseDaoImplInit;
import com.lingnet.util.JsonUtil;
import com.lingnet.util.Pager;
import com.lingnet.vocs.dao.monit.MonitoringDao;
import com.lingnet.vocs.entity.ConstantData;
import com.lingnet.vocs.entity.Equipment;
@Repository("monitoringDao")
public class MonitoringDaoImpl extends BaseDaoImplInit<ConstantData, String>
implements MonitoringDao {
@SuppressWarnings("unchecked")
@Override
public List<Object[]> findConstantData(String boxId, String uid) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuffer sql = new StringBuffer();
Calendar calendar= Calendar.getInstance();
String tablename = "constant_data_";
int month = calendar.get(Calendar.MONTH)+1;
if(month<10){
tablename = tablename + calendar.get(Calendar.YEAR)+"0"+(calendar.get(Calendar.MONTH)+1);
}else{
tablename = tablename + calendar.get(Calendar.YEAR)+(calendar.get(Calendar.MONTH)+1);
}
sql.append(" SELECT distinct TOP 5 ");
//sql.append(" Fbox_uid,max(value) value,CONVERT(varchar(16), time_stamp, 120) time_stamp ");
sql.append(" Fbox_uid,value,CONVERT(varchar(16), time_stamp, 120) time_stamp ,flag ");
sql.append(" FROM V_Constant ");
sql.append(" where fbox_uid='" + boxId + "' ");
sql.append(" and CONVERT(varchar(50), time_stamp, 120)<'"+sdf.format(new Date())+"' ");
sql.append(" and name='" + uid + "' ");//正式数据使用,测试数据注释,方便返回数据
//sql.append(" group by CONVERT(varchar(16), time_stamp, 120),Fbox_uid ");
sql.append(" order by time_stamp desc ");
SQLQuery sqlQuery = this.getSession().createSQLQuery(sql.toString());
// 进行数据查询
List<Object[]> resultList = sqlQuery.list();
return resultList;
}
@SuppressWarnings("unchecked")
@Override
public List<Object[]> findConstantDataNew(String boxId, String uid) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuffer sql = new StringBuffer();
Calendar calendar= Calendar.getInstance();
String tablename = "constant_data_";
int month = calendar.get(Calendar.MONTH)+1;
if(month<10){
tablename = tablename + calendar.get(Calendar.YEAR)+"0"+(calendar.get(Calendar.MONTH)+1);
}else{
tablename = tablename + calendar.get(Calendar.YEAR)+(calendar.get(Calendar.MONTH)+1);
}
sql.append(" SELECT distinct TOP 5 ");
//sql.append(" Fbox_uid,max(value),CONVERT(varchar(16), time_stamp, 120) time_stamp ,flag ");
sql.append(" Fbox_uid,value,CONVERT(varchar(16), time_stamp, 120) time_stamp ,flag ");
sql.append(" FROM V_Constant ");
sql.append(" where fbox_uid='" + boxId + "' ");
sql.append(" and CONVERT(varchar(16), time_stamp, 120)<'"+sdf.format(new Date())+"' ");
sql.append(" and name='" + uid + "' ");//正式数据使用,测试数据注释,方便返回数据
//sql.append(" group by CONVERT(varchar(16), time_stamp, 120),Fbox_uid ,flag ");
sql.append(" order by time_stamp desc ");
SQLQuery sqlQuery = this.getSession().createSQLQuery(sql.toString());
// 进行数据查询
List<Object[]> resultList = sqlQuery.list();
return resultList;
}
@SuppressWarnings("unchecked")
@Override
public Object[] findLastData(String boxId, String uid) {
StringBuffer sql = new StringBuffer();
Calendar calendar= Calendar.getInstance();
String tablename = "constant_data_";
int month = calendar.get(Calendar.MONTH)+1;
if(month<10){
tablename = tablename + calendar.get(Calendar.YEAR)+"0"+(calendar.get(Calendar.MONTH)+1);
}else{
tablename = tablename + calendar.get(Calendar.YEAR)+(calendar.get(Calendar.MONTH)+1);
}
/*sql.append(" SELECT TOP 1 ");
sql.append(" name,value,CONVERT(varchar(100), time_stamp, 24),quality,flag ");
sql.append(" FROM "+tablename+" ");
sql.append(" where fbox_uid='" + boxId + "' ");
sql.append(" and uid='" + uid + "' ");
sql.append(" order by time_stamp desc ");*/
sql.append(" SELECT TOP 1 ");
sql.append(" name,value,CONVERT(varchar(100), time_stamp, 24),quality,flag ");
sql.append(" FROM V_Constant ");
sql.append(" where fbox_uid='" + boxId + "' ");
sql.append(" and name='" + uid + "' order by time_stamp desc");//正式系统使用
// sql.append(" order by newid()");//测试数据,保证有数据返回
SQLQuery sqlQuery = this.getSession().createSQLQuery(sql.toString());
// 进行数据查询
List<Object[]> resultList = sqlQuery.list();
if(resultList!=null&&resultList.size()>0){
return resultList.get(0);
}else{
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public List<HashMap<String, Object>> findPagerData(Pager pager,
HashMap<String, Object> map) {
StringBuffer sqlBuffer = new StringBuffer();
List<HashMap<String, Object>> mapList = new ArrayList<HashMap<String,Object>>();
//计算分页开始条数
Integer start = pager.getPageNumber()*pager.getPageSize();
sqlBuffer.append(" select top "+pager.getPageSize()+" v.id,Fbox_uid,time_stamp,value,quality,e.air_volume,e.name from V_Constant v ");
sqlBuffer.append(" left join EQUIPMENT e on e.equipment_code = v.fbox_uid ");
sqlBuffer.append(" where 1=1 ");
if(map.get("equipmentCode")!=null&&!"".equals(map.get("equipmentCode").toString())){
sqlBuffer.append(" and v.fbox_uid='"+map.get("equipmentCode")+"' ");
}
if(map.get("owner")!=null&&!"".equals(map.get("owner").toString())){
sqlBuffer.append(" and e.owner='"+map.get("owner")+"'");
}
if(map.get("start")!=null&&!"".equals(map.get("start").toString())){
sqlBuffer.append(" and v.time_stamp>= '"+map.get("start")+"'");
}
if(map.get("end")!=null&&!"".equals(map.get("end").toString())){
sqlBuffer.append(" and v.time_stamp<= '"+map.get("end")+"'");
}
if(map.get("navVal")!=null&&!"".equals(map.get("navVal").toString())){
sqlBuffer.append(" and v.name= '"+map.get("navVal")+"'");
}
sqlBuffer.append(" and v.id in( ");
sqlBuffer.append(" SELECT top "+pager.getPageSize()+" ID FROM ( ");
sqlBuffer.append(" SELECT top "+start+" ID, createdate from V_Constant order by createdate desc ");
sqlBuffer.append(" ) w order by w.createdate asc ) ");
sqlBuffer.append(" order by v.createdate desc ");
//获取总记录数
StringBuffer sqlCount = new StringBuffer();
sqlCount.append(" select count(id) from V_Constant v where 1=1");
if(map.get("start")!=null&&!"".equals(map.get("start").toString())){
sqlCount.append(" and v.time_stamp>= '"+map.get("start")+"'");
}
if(map.get("end")!=null&&!"".equals(map.get("end").toString())){
sqlCount.append(" and v.time_stamp<= '"+map.get("end")+"'");
}
if(map.get("navVal")!=null&&!"".equals(map.get("navVal").toString())){
sqlCount.append(" and v.name= '"+map.get("navVal")+"'");
}
if(map.get("equipmentCode")!=null&&!"".equals(map.get("equipmentCode").toString())){
sqlCount.append(" and v.fbox_uid='"+map.get("equipmentCode")+"' ");
}
SQLQuery sqlQuery = this.getSession().createSQLQuery(sqlCount.toString());
Integer total = Integer.parseInt(sqlQuery.list().get(0).toString());
pager.setTotalCount(total);
SQLQuery sqlQuery1 = this.getSession().createSQLQuery(sqlBuffer.toString());
List<Object[]> obs = sqlQuery1.list();
SimpleDateFormat from = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
if(obs!=null&&obs.size()>0){
//循环数据
for(Object[] ob:obs){
HashMap<String, Object> mp = new HashMap<String, Object>();
mp.put("id", ob[0]);
mp.put("equipmentCode", ob[1]);
mp.put("timeStamp", from.format(ob[2]));
mp.put("content", ob[3]);
mp.put("quality", ob[4]);
mp.put("standard", ob[5]);
mp.put("name", ob[6]);
mapList.add(mp);
}
}
return mapList;
}
@Override
public String getDuData(String boxId) {
Equipment ment = (Equipment) this.getSession().createCriteria(Equipment.class).add(Restrictions.eq("equipmentCode", boxId)).uniqueResult();
StringBuilder sql = new StringBuilder();
sql.append(" SELECT ");
sql.append(" * ");
sql.append(" FROM ");
sql.append(" V_constant con, ");
sql.append(" ( ");
sql.append(" SELECT ");
sql.append(" max(time_stamp) date, ");
sql.append(" NAME ");
sql.append(" FROM ");
sql.append(" V_constant ");
sql.append(" WHERE ");
sql.append(" Fbox_uid IN ( ");
sql.append(" SELECT ");
sql.append(" plc_identification_code ");
sql.append(" FROM ");
sql.append(" EQUIPMENT ");
sql.append(" WHERE ");
sql.append(" plc_identification_code IS NOT NULL ");
sql.append(" ) ");
sql.append(" GROUP BY ");
sql.append(" NAME ");
sql.append(" ) t ");
sql.append(" WHERE ");
sql.append(" t. NAME = con. NAME ");
sql.append(" AND t.date = con.time_stamp ");
sql.append(" AND con.Fbox_uid = '"+ment.getPlcIdentificationCode()+"' ");
sql.append(" order by t.name asc ");
return JsonUtil.Encode(this.getSession().createSQLQuery(sql.toString()).list());
}
}
|
/**
*
*/
package kit.edu.pse.goapp.server.validation;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import kit.edu.pse.goapp.server.daos.UserDAO;
import kit.edu.pse.goapp.server.daos.UserDaoImpl;
import kit.edu.pse.goapp.server.datamodels.User;
import kit.edu.pse.goapp.server.exceptions.CustomServerException;
/**
* @author Iris
*
*/
public class UserValidation {
/**
* checks if user exists at all
*
* @param userId
* the user
* @return true if user exists
* @throws IOException
* if something goes wrong in the database
* @throws CustomServerException
* if user doesn't exist
*/
public boolean userExists(int userId) throws IOException, CustomServerException {
UserDAO dao = new UserDaoImpl();
List<User> users = dao.getAllUsers();
return userExists(users, userId);
}
protected boolean userExists(List<User> users, int userId) throws IOException, CustomServerException {
for (User tmpUser : users) {
if (tmpUser.getId() == userId) {
return true;
}
}
throw new CustomServerException("This user doesn't exist!", HttpServletResponse.SC_BAD_REQUEST);
}
}
|
package com.nightlife.repository;
import com.nightlife.model.RegisterEventPlace;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface EventPlace extends JpaRepository<RegisterEventPlace, Long> {
RegisterEventPlace findByPartyPlaceIgnoreCase(String name);
List<RegisterEventPlace> findAllByOrderByPartyPlaceAsc();
List<RegisterEventPlace> findAllByOrderByPartyPlaceDesc();
}
|
package com.jim.mpviews.calendar;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.TextView;
import com.jim.mpviews.R;
import com.jim.mpviews.interfaces.OnDayViewClickListener;
import com.jim.mpviews.utils.CalendarDate;
import com.jim.mpviews.utils.CalendarMonth;
public class CalendarMonthView extends FrameLayout implements View.OnClickListener {
private GridLayout mGridLayout;
private ViewGroup mLayoutDays;
private OnDayViewClickListener mListener;
private CalendarDate mSelectedDate;
public CalendarMonthView(Context context) {
super(context);
init();
}
public void setOnDayViewClickListener(OnDayViewClickListener listener) {
mListener = listener;
}
public void setSelectedDate(CalendarDate selectedDate) {
mSelectedDate = selectedDate;
}
private void init() {
inflate(getContext(), R.layout.mp_calendar_month, this);
mGridLayout = (GridLayout) findViewById(R.id.mpCalendarMonthGrid);
mLayoutDays = (ViewGroup) findViewById(R.id.mpWeekDays);
}
public void buildView(CalendarMonth calendarMonth) {
// buildDaysLayout();
buildGridView(calendarMonth);
}
private void buildDaysLayout() {
String[] days;
days = getResources().getStringArray(R.array.days_sunday_array);
for (int i = 0; i < mLayoutDays.getChildCount(); i++) {
TextView textView = (TextView) mLayoutDays.getChildAt(i);
textView.setText(days[i]);
}
}
private void buildGridView(CalendarMonth calendarMonth) {
int row = CalendarMonth.NUMBER_OF_WEEKS_IN_MONTH;
int col = CalendarMonth.NUMBER_OF_DAYS_IN_WEEK;
mGridLayout.setRowCount(row);
mGridLayout.setColumnCount(col);
for (CalendarDate date : calendarMonth.getDays()) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.width = LayoutParams.WRAP_CONTENT;
params.height = LayoutParams.WRAP_CONTENT;
CalendarDayView dayView = new CalendarDayView(getContext(), date);
dayView.setContentDescription(date.toString());
dayView.setLayoutParams(params);
dayView.setOnClickListener(this);
decorateDayView(dayView, date, calendarMonth.getMonth());
mGridLayout.addView(dayView);
}
}
private void decorateDayView(CalendarDayView dayView, CalendarDate day, int month) {
if (day.getMonth() != month) {
dayView.setOtherMothTextColor();
dayView.setGreyBackground();
} else {
dayView.setThisMothTextColor();
dayView.setWhiteBackground();
}
if (day.isToday()) {
dayView.setGreenBackground();
} else {
if (day.getMonth() != month){
dayView.setGreyBackground();
} else
dayView.setWhiteBackground();
}
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onDayViewClick((CalendarDayView) view);
}
}
}
|
package com.sushichet.sushichet.rest.callbacks;
import com.sushichet.sushichet.model.GalleryModel;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface GalleryInterface {
@GET("http://www.webcreation.net.np/sushichet/wp-json/wp/v2/sliders")
Call<List<GalleryModel>> getSlider();
}
|
package com.sinata.rwxchina.component_basic.ktv.adapter;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sinata.rwxchina.component_basic.R;
import com.sinata.rwxchina.component_basic.ktv.entity.KTVReserveEntity;
import java.util.List;
/**
* @author HRR
* @datetime 2017/12/19
* @describe KTV预约包间适配器
* @modifyRecord
*/
public class KTVTypeAdapter extends BaseQuickAdapter<KTVReserveEntity,BaseViewHolder> {
private Context mC;
public KTVTypeAdapter(Context context,@LayoutRes int layoutResId, @Nullable List<KTVReserveEntity> data) {
super(layoutResId, data);
this.mC=context;
}
@Override
protected void convert(BaseViewHolder helper, KTVReserveEntity item) {
helper.setText(R.id.item_ktvtype,item.getTitle());
}
}
|
package Flowers.Observer;
import Flowers.Bouquet;
import Flowers.Flower;
import Flowers.Item;
import Flowers.Tulip;
import java.util.LinkedList;
/**
* Created by Yasya on 25.12.16.
*/
public class TulipSupplierObserver extends Observer<LinkedList<Item>> {
public TulipSupplierObserver(Observable subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update(LinkedList<Item> order){
int quantity = 0;
Bouquet bouquet = new Bouquet();
for(Item item: order) {
if (item.getClass() == new Bouquet().getClass()) {
bouquet = (Bouquet) item;
for(Flower flower : bouquet.arrOfF){
if(flower instanceof Tulip) {
quantity += 1;
}
}
}
}
System.out.println("We will supply you with " + Integer.toString(quantity) + " tulips\n");
}
}
|
package multithread;
/**
* notifyAll test
*
* @author zhoubo
* @create 2018-09-30 11:06
*/
public class NotifyAllTest {
public static void main(String[] args) {
NotifyAllTest notifyAllTest = new NotifyAllTest();
TestClass testClass = notifyAllTest.new TestClass();
ConcreateRunnable[] concreateRunnables = {notifyAllTest.new ConcreateRunnable(testClass), notifyAllTest.new ConcreateRunnable(testClass), notifyAllTest.new ConcreateRunnable(testClass)};
for (ConcreateRunnable concreateRunnable : concreateRunnables) {
new Thread(concreateRunnable).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
testClass.singalAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finish!");
}
private class TestClass {
private Object lock = new Object();
public void await() {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "acquire lock");
}
}
public void singalAll() {
synchronized (lock) {
lock.notifyAll();
}
}
}
private class ConcreateRunnable implements Runnable {
private TestClass testClass;
public ConcreateRunnable(TestClass testClass) {
this.testClass = testClass;
}
@Override
public void run() {
testClass.await();
}
}
}
|
package com.immotor.bluetoothadvertiser.command.request;
import android.bluetooth.BluetoothGattCharacteristic;
import com.immotor.bluetoothadvertiser.command.Command;
/**
* Created by ForestWang on 2016/4/1.
*/
public class ConnectionAuthRequest extends Command {
private String mSerialNumber;
private static final int COMMAND_VERSION = 1;
private static final int OFFSET_SERIAL_LEN = OFFSET_DATA;
private static final int TOTAL_LEN = OFFSET_SERIAL_LEN + 1;
private static final int OFFSET_SERIAL_NUMBER = OFFSET_SERIAL_LEN+1;
private ConnectionAuthRequest(String serialNumber){
super(CMD_TYPE_CONNECTION_AUTH,COMMAND_VERSION);
mSerialNumber = serialNumber;
}
public String getSerialNumber() {
return mSerialNumber;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("mSerialNumber:").append(mSerialNumber);
return sb.toString();
}
@Override
public BluetoothGattCharacteristic setValue(BluetoothGattCharacteristic characteristic) {
byte[] data = mSerialNumber.getBytes();
characteristic.setValue(new byte[TOTAL_LEN]);
characteristic.setValue(mCommandType, BluetoothGattCharacteristic.FORMAT_UINT8, OFFSET_CMD_TYPE);
characteristic.setValue(mVersion, BluetoothGattCharacteristic.FORMAT_UINT8, OFFSET_CMD_VERSION);
characteristic.setValue(data.length, BluetoothGattCharacteristic.FORMAT_UINT8, OFFSET_SERIAL_LEN);
byte[] value = new byte[TOTAL_LEN + data.length];
System.arraycopy(characteristic.getValue(), 0, value, 0, TOTAL_LEN);
System.arraycopy(data, 0, value, TOTAL_LEN, data.length);
characteristic.setValue(value);
return characteristic;
}
public static final class Parser {
private BluetoothGattCharacteristic mCharacteristic;
public Parser(BluetoothGattCharacteristic characteristic) {
mCharacteristic = characteristic;
}
public ConnectionAuthRequest parse() {
String serialNumber = mCharacteristic.getStringValue(OFFSET_SERIAL_NUMBER);
return new ConnectionAuthRequest(serialNumber);
}
}
public static final class Builder {
private String mSerialNumber;
public Builder setSerialNumber(String serialNumber) {
this.mSerialNumber = serialNumber;
return this;
}
public ConnectionAuthRequest build() {
return new ConnectionAuthRequest(mSerialNumber);
}
}
}
|
package com.mideas.rpg.v2.hud;
import java.util.Arrays;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import com.mideas.rpg.v2.Interface;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.FontManager;
import com.mideas.rpg.v2.game.CharacterStuff;
import com.mideas.rpg.v2.game.IconsManager;
import com.mideas.rpg.v2.game.item.Item;
import com.mideas.rpg.v2.render.Draw;
import com.mideas.rpg.v2.render.Sprites;
import com.mideas.rpg.v2.utils.Color;
public class DragBagManager {
private static boolean[] hoverBag = new boolean[5];
private static boolean [] clickBag = new boolean[5];
private static boolean leftClickDown;
private static int mouseX;
private static int mouseY;
private static boolean deleteItem;
private static boolean hoverDelete;
private static boolean hoverSave;
private static Item draggedBag;
private static String yes = "Yes";
private static String no = "No";
public static void draw() { //TODO: rewrite the whole class
hoverDelete = false;
hoverSave = false;
if(draggedBag != null) {
Draw.drawQuad(IconsManager.getSprite37(draggedBag.getSpriteId()), Mideas.mouseX(), Mideas.mouseY());
Draw.drawQuad(Sprites.stuff_border, Mideas.mouseX()-5, Mideas.mouseY()-5);
}
if(deleteItem && draggedBag != null) {
Draw.drawQuad(Sprites.alert, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2-105, Display.getHeight()/2-80);
if(Mideas.mouseX() >= Display.getWidth()/2-130 && Mideas.mouseX() <= Display.getWidth()/2-6 && Mideas.mouseY() <= Display.getHeight()/2-18 && Mideas.mouseY() >= Display.getHeight()/2-37) {
Draw.drawQuad(Sprites.button_hover, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2-70, Display.getHeight()/2-43);
hoverDelete = true;
}
else {
Draw.drawQuad(Sprites.button, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2-70, Display.getHeight()/2-43);
}
if(Mideas.mouseX() >= Display.getWidth()/2+7 && Mideas.mouseX() <= Display.getWidth()/2+134 && Mideas.mouseY() <= Display.getHeight()/2-15 && Mideas.mouseY() >= Display.getHeight()/2-38) {
Draw.drawQuad(Sprites.button_hover2, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2+70, Display.getHeight()/2-43);
hoverSave = true;
}
else {
Draw.drawQuad(Sprites.button2, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2+70, Display.getHeight()/2-43);
}
if(Interface.getEscapeFrameStatus()) {
draggedBag = null;
deleteItem = false;
}
FontManager.get("FRIZQT", 16).drawStringShadow(Display.getWidth()/2-FontManager.get("FRIZQT", 16).getWidth("Voulez vous supprimer "+draggedBag.getStuffName())/2, Display.getHeight()/2-65, "Voulez vous supprimer "+draggedBag.getStuffName(), Color.WHITE, Color.BLACK, 1, 1, 1);
FontManager.get("FRIZQT", 13).drawStringShadow(Display.getWidth()/2-FontManager.get("FRIZQT", 13).getWidth(yes)/2-69, Display.getHeight()/2-41, yes, Color.WHITE, Color.BLACK, 1, 1, 1);
FontManager.get("FRIZQT", 13).drawStringShadow(Display.getWidth()/2-FontManager.get("FRIZQT", 13).getWidth(no)/2+70, Display.getHeight()/2-40, no, Color.WHITE, Color.BLACK, 1, 1, 1);
}
}
public static boolean mouseEvent() {
//hover BagFrame
if(Mouse.getEventButton() == 0) {
if(Mouse.getEventButtonState()) {
if(checkBagClick() && draggedBag == null) {
leftClickDown = true;
mouseX = Mideas.mouseX();
mouseY = Mideas.mouseY();
}
}
else {
if(draggedBag != null) {
if(draggedBag != null && !leftClickDown && !deleteItem && !DragManager.isSpellBarHover() && !DragManager.isHoverCharacterFrame() && !DragManager.isHoverBagFrame()) {
deleteItem = true;
return true;
}
int i = 0;
while(i < Mideas.joueur1().bag().getEquippedBag().length) {
if(clickBag(i)) {
return true;
}
i++;
}
}
Arrays.fill(clickBag, false);
leftClickDown = false;
}
}
if(leftClickDown && draggedBag == null) {
if(Math.abs(Math.abs(Mideas.mouseX())-Math.abs(mouseX)) >= 27 || Math.abs(Math.abs(Mideas.mouseY())-Math.abs(mouseY)) >= 27) {
setDraggedItemForBag();
Arrays.fill(clickBag, false);
return true;
}
}
if(Mouse.getEventButton() == 0) {
if(!Mouse.getEventButtonState()) {
if(hoverDelete && deleteItem) {
if(checkEmptyBag()) {
deleteBag(draggedBag);
draggedBag = null;
//CharacterStuff.setEquippedBags();
//CharacterStuff.setBagItems();
deleteItem = false;
ContainerFrame.setBagchange(true);
}
}
if(hoverSave && deleteItem) {
draggedBag = null;
deleteItem = false;
}
if(deleteItem) {
draggedBag = null;
}
deleteItem = false;
}
}
if(Mouse.getEventButton() == 1) {
if(Mouse.getEventButtonState()) {
if(draggedBag != null) {
draggedBag = null;
}
}
}
return false;
}
public static void openBag() {
Arrays.fill(hoverBag, false);
//System.out.println(Mideas.joueur1().bag().getBag().length);
int i = 0;
float x = 491*Mideas.getDisplayXFactor();
float xShift = 48.2f*Mideas.getDisplayXFactor();
while(i < hoverBag.length) {
bagHover(i, x-xShift*i);
i++;
}
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
if(!Mouse.getEventButtonState()) {
i = 0;
if(Mideas.mouseX() >= Display.getWidth()/2+539*Mideas.getDisplayXFactor() && Mideas.mouseX() <= Display.getWidth()/2+579*Mideas.getDisplayXFactor() && Mideas.mouseY() >= Display.getHeight()-41*Mideas.getDisplayYFactor() && Mideas.mouseY() <= Display.getHeight()-3) {
ContainerFrame.setBagOpen(0, !ContainerFrame.getBagOpen(0));
}
while(i < hoverBag.length) {
if(hoverBag[i]) {
ContainerFrame.setBagOpen(i+1, !ContainerFrame.getBagOpen(i+1));
break;
}
i++;
}
}
}
}
private static void bagHover(int i, float x) {
if(Mideas.mouseX() >= Display.getWidth()/2+x && Mideas.mouseX() <= Display.getWidth()/2+x+37*Mideas.getDisplayXFactor() && Mideas.mouseY() >= Display.getHeight()-41*Mideas.getDisplayYFactor() && Mideas.mouseY() <= Display.getHeight()-3) {
hoverBag[i] = true;
}
}
private static boolean clickBag(int i) {
if(hoverBag[i]) {
if(Mideas.joueur1().bag().getEquippedBag(i) != null) {
}
}
return false;
}
private static boolean checkBagClick() {
int i = 0 ;
while(i < clickBag.length) {
if(hoverBag[i] == true && draggedBag == null) {
clickBag[i] = true;
return true;
}
i++;
}
return false;
}
private static boolean setDraggedItemForBag() {
int i = 0;
while(i < clickBag.length) {
if(clickBag[i] == true) {
draggedBag = Mideas.joueur1().bag().getEquippedBag(i);
return true;
}
i++;
}
return false;
}
private static boolean checkEmptyBag() {
int i = 0;
int position = -1;
while(i < Mideas.joueur1().bag().getEquippedBag().length) {
if(draggedBag == Mideas.joueur1().bag().getEquippedBag(i)) {
position = i;
break;
}
i++;
}
int size = 0;
i = 0;
while(i < position) {
size+= Mideas.joueur1().bag().getEquippedBagSize(i);
i++;
}
i = size+16;
while(i < size+Mideas.joueur1().bag().getEquippedBagSize(position)+16) {
if(Mideas.joueur1().bag().getBag(i) != null) {
return false;
}
i++;
}
return true;
}
private static void deleteBag(Item item) {
int i = 0;
while(i < Mideas.joueur1().bag().getEquippedBag().length) {
if(Mideas.joueur1().bag().getEquippedBag(i) == item) {
Mideas.joueur1().bag().setEquippedBag(i, null);
return;
}
i++;
}
}
public static boolean getHoverBag(int i) {
if(i < hoverBag.length) {
return hoverBag[i];
}
return false;
}
public static boolean getClickBag(int i) {
if(i < clickBag.length) {
return clickBag[i];
}
return false;
}
public static Item getDraggedBag() {
return draggedBag;
}
}
|
package com.smxknife.java2.string;
/**
* @author smxknife
* 2019-05-18
*/
public class StringEqualDemo {
public static void main(String[] args) {
String string1 = "hello";
String string2 = "hello";
System.out.println(string1 == string2);
System.out.println(string1.getClass());
System.out.println(string2.getClass());
}
}
|
package com.andyadc.seckill.starter.config;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@ServletComponentScan(value = {"com.andyadc.seckill"})
@ComponentScan(value = {"com.andyadc.seckill"})
@Configuration
@Import({RedisConfig.class})
public class SeckillConfig {
}
|
package app0512.graphic;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PhotoAlbum extends JFrame{
JPanel p_north;//썸네일 올려놓을 패널
JPanel canvas;//그림이 그려질 패널
Thumbnail[] list=new Thumbnail[8];
DetailView detailView;//상세보기 패널
//썸네일 생성 메서드
public void createThumb() {
for(int i=0; i<list.length; i++) {
list[i]=new Thumbnail(this);
p_north.add(list[i]);
}
}
public PhotoAlbum() {
p_north=new JPanel();
detailView=new DetailView(this);
p_north.setPreferredSize(new Dimension(900,100));
p_north.setBackground(Color.gray);
add(p_north,BorderLayout.NORTH);
createThumb();
add(detailView);
setBounds(160, 50, 900, 600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new PhotoAlbum();
}
}
|
package com.wuyan.masteryi.admin.service;
/*
*project:master-yi
*file:ImageService
*@author:wsn
*date:2021/7/15 9:19
*/
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
public interface ImageService {
Map<String,Object> saveImage(MultipartFile file,int goodId);
Map<String,Object> saveSpecImage(MultipartFile file,int id);
Map<String,Object> changeUserImage(MultipartFile file,int userId);
}
|
import market.*;
public class Main {
public static void main(String[] args) {
if( args.length != 1 ) {
System.out.println("Hasznalat: Main inputfajl");
System.exit(1);
}
Market market = new Market(args[0]);
for( Fruit fruit : market.sale() ) {
System.out.println(fruit.show());
}
}
}
|
package com.giraldo.parqueo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="TBL_PARQUEO")
public class Parqueo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
@JoinColumn(name="ID_VEHICULO")
private Vehiculo vehiculo;
@Column(name="FECHAINGRESO")
private String fechaIngreso;
@Column(name="FECHASALIDA", nullable = true)
private String fechaSalida;
@Column(name="OBSERVACION")
private String observacion;
@ManyToOne
@JoinColumn(name="ID_USUARIOREGISTRAINGRESO")
private Usuario usuarioRegistraIngreso;
@ManyToOne
@JoinColumn(name="ID_USUARIOREGISTRASALIDA", nullable = true)
private Usuario usuarioRegistraSalida;
//se crean los gett y los sett
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFechaIngreso() {
return fechaIngreso;
}
public void setFechaIngreso(String fechaIngreso) {
this.fechaIngreso = fechaIngreso;
}
public Vehiculo getVehiculo() {
return vehiculo;
}
public void setVehiculo(Vehiculo vehiculo) {
this.vehiculo = vehiculo;
}
public Usuario getUsuarioRegistraIngreso() {
return usuarioRegistraIngreso;
}
public void setUsuarioRegistraIngreso(Usuario usuarioRegistraIngreso) {
this.usuarioRegistraIngreso = usuarioRegistraIngreso;
}
public Usuario getUsuarioRegistraSalida() {
return usuarioRegistraSalida;
}
public void setUsuarioRegistraSalida(Usuario usuarioRegistraSalida) {
this.usuarioRegistraSalida = usuarioRegistraSalida;
}
public String getFechaSalida() {
return fechaSalida;
}
public void setFechaSalida(String fechaSalida) {
this.fechaSalida = fechaSalida;
}
public String getObservacion() {
return observacion;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
protected Parqueo(Vehiculo vehiculo, String fechaIngreso, String fechaSalida, String observacion,
Usuario usuarioRegistraIngreso, Usuario usuarioRegistraSalida) {
super();
this.vehiculo = vehiculo;
this.fechaIngreso = fechaIngreso;
this.fechaSalida = fechaSalida;
this.observacion = observacion;
this.usuarioRegistraIngreso = usuarioRegistraIngreso;
this.usuarioRegistraSalida = usuarioRegistraSalida;
}
@Override
public String toString() {
return "Parqueo [id=" + id + ", vehiculo=" + vehiculo.toString() + ", fechaIngreso=" + fechaIngreso + ", fechaSalida="
+ fechaSalida + ", observacion=" + observacion + ", usuarioRegistraIngreso="
+ usuarioRegistraIngreso.toString() + ", usuarioRegistraSalida=" + usuarioRegistraSalida.toString() + "]";
}
protected Parqueo() {
super();
// TODO Auto-generated constructor stub
}
}
|
package g_seventhexp.queen;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.*;
public class Paints extends JPanel {
private int[][] chessPaint;
Paints(int[][] chess) {
this.chessPaint = chess;
}
@Override
public void paintComponent(Graphics g) {
for (int i = 1; i < 9; i++) {
for (int j = 1; j < 9; j++) {
if (chessPaint[i][j] == 0) {
g.setColor(Color.white);
} else {
g.setColor(Color.black);
}
g.fillRect(20 + 20 * i, 20 + 20 * j, 20, 20);
}
}
g.setColor(Color.gray);
for (int i = 0; i <= 8; i++) {
g.drawLine(40, 40 + 20 * i, 200, 40 + 20 * i);
g.drawLine(40 + 20 * i, 40, 40 + 20 * i, 200);
}
}
}
|
/*******************************************************************************
* Name : SubstringDivisibility.java
* Authors : Theodore Jagodits, Alex Kubecka, Kurt Von Autenried
* Version : 1.0
* Date : 1/29/2020
* Description : parse permutations of pandigital strings
* Link : https://projecteuler.net/problem=43
* Pledge: "I pledge my honor that I have abided by the Stevens Honor System"
* Reference: https://www.geeksforgeeks.org/johnson-trotter-algorithm/
******************************************************************************/
import java.lang.*;
class SubstringDivisibility{
public static int divisors[] = new int[]{2,3,5,7,11,13,17};
public static long sum = 0;
//declared booleans to show direction -- might remove -- just for readability
private final static boolean LEFT_TO_RIGHT = true;
private final static boolean RIGHT_TO_LEFT = false;
//finds the factorial so that we don't need to calculate more perms
public static int factorial(int n){
int i = 1;
int res = 1;
for( ; i <= n; i++){
res *= i;
}
return res;
}
//checks for the substring modifications
public static void panCheck(int[] num, int n){
boolean check = true;
int mult = 1000, i = 4;
int total = num[0] + num[1]*10 + num[2]*100 + num[3] * 1000;
for(; i < ){
}
}
//find the largest mobile int
public static int findLargestMobileIdx(int[] arr, boolean[] dir, int n){
int i;
int mobile = -1;
int mobilePos = 0;
//maybe bound for loop???? -- check later
for(i = 0; i < n; i++){
//look in direction of bool arr and check size
if(i != 0 && dir[i] == RIGHT_TO_LEFT ){
if(arr[i-1] < arr[i] && mobile < arr[i]){
mobile = arr[i];
mobilePos = i;
}
//look the other direction
} else if(i != n-1 && dir[i] == LEFT_TO_RIGHT){
if(arr[i+1] < arr[i] && mobile < arr[i]){
mobile = arr[i];
mobilePos = i;
}
}
}
return mobilePos;
}
//finds the permutations
public static void onePermutation(int[] arr, boolean[] direction, int n){
//find the largest mobile int pos
int mobilePos = findLargestMobileIdx(arr, direction, n);
int mobileVal = arr[mobilePos];
int temp;
boolean tempbool;
//pointing to left
if(direction[mobilePos] == RIGHT_TO_LEFT){
//swap
temp = arr[mobilePos];
arr[mobilePos] = arr[mobilePos-1];
arr[mobilePos-1] = temp;
//swap bools
tempbool = direction[mobilePos];
direction[mobilePos] = direction[mobilePos-1];
direction[mobilePos-1] = tempbool;
//pointing to the right
}else if(direction[mobilePos] == LEFT_TO_RIGHT){
temp = arr[mobilePos];
arr[mobilePos] = arr[mobilePos+1];
arr[mobilePos+1] = temp;
//swap bools
tempbool = direction[mobilePos];
direction[mobilePos] = direction[mobilePos+1];
direction[mobilePos+1] = tempbool;
}
//swap dir elements greater than mobile PROBLEM
for(int i = 0; i < n; i++){
if(arr[i] > mobileVal){
if(direction[i] == LEFT_TO_RIGHT){
direction[i] = RIGHT_TO_LEFT;
}else if(direction[i] == RIGHT_TO_LEFT){
direction[i] = LEFT_TO_RIGHT;
}
}
}
//permutation done...check if hits params
panCheck(arr, n);
}
public static void main(String[] args){
//checks if correct amount of args
if(args.length != 1){
System.out.printf("incorrect amount of args\n");
return;
}
//check int size
int numSize = args[0].length();
if(numSize <= 3 || numSize > 10){
System.out.printf("Input must be at least 4 digits, at most 10\n");
return;
}
//initialize array to read in to function
int[] buf = new int[numSize];
int i;
for(i = 0 ; i < numSize; i++){
//read in each value into buffer
buf[i] = args[0].charAt(i) - 48;
}
//initialize bool array facing right to left
boolean[] direction = new boolean[numSize];
for(i = 0 ; i < numSize; i++){
direction[i] = RIGHT_TO_LEFT;
}
//checks execution time
long start = System.nanoTime();
//check the first permutation and add to sum if it hits reqs
panCheck(buf, numSize);
//generate permutations and build sum
for(i = 1; i < factorial(numSize); i++){
onePermutation(buf, direction, numSize);
}
//print sum
System.out.println("Sum: " + sum);
System.out.printf("Elapsed time: %.6f ms\n", (System.nanoTime() - start) / 1e6);
}
}
|
/* */ package de.stuuupiiid.dungeonpack;
/* */
/* */ import java.util.Random;
/* */
/* */
/* */
/* */
/* */ public class NPCTownStable
/* */ extends NPCTownBase
/* */ {
/* */ public boolean generate(Random r, int par1, int par2, int par3)
/* */ {
/* 13 */ for (int v1 = -7; v1 < 8; v1++) {
/* 14 */ for (int v2 = -7; v2 < 8; v2++) {
/* 15 */ for (int v3 = 0; v3 < 10; v3++) {
/* 16 */ addAir(par1 + v1, par2 + v3, par3 + v2);
/* */ }
/* */ }
/* */ }
/* */
/* 21 */ for (int v1 = -7; v1 < 8; v1++) {
/* 22 */ for (int v2 = -7; v2 < 8; v2++) {
/* 23 */ for (int v3 = -8; v3 < 0; v3++) {
/* 24 */ if ((isAir(par1 + v1, par2 + v3, par3 + v2)) || (getBlock(par1 + v1, par2 + v3, par3 + v2) == 8) || (getBlock(par1 + v1, par2 + v3, par3 + v2) == 9) || (getBlock(par1 + v1, par2 + v3, par3 + v2) == 31)) {
/* 25 */ addBlock(par1 + v1, par2 + v3, par3 + v2, 3);
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* 31 */ for (int v1 = -7; v1 < 8; v1++) {
/* 32 */ addBlock(par1 + v1, par2, par3 + 7, 85);
/* 33 */ addBlock(par1 + v1, par2, par3 - 7, 85);
/* 34 */ addBlock(par1 + 7, par2, par3 + v1, 85);
/* 35 */ addBlock(par1 - 7, par2, par3 + v1, 85);
/* */ }
/* */
/* 38 */ for (int v1 = 0; v1 < 18; v1++) {
/* 39 */ spawnCow(par1, par2, par3);
/* 40 */ spawnPig(par1, par2, par3);
/* */ }
/* */
/* 43 */ return true;
/* */ }
/* */ }
/* Location: C:\Users\IyadE\Desktop\Mod Porting Tools\dungeonpack-1.8.jar!\de\stuuupiiid\dungeonpack\NPCTownStable.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.unpack200;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.harmony.pack200.Pack200Exception;
/**
* Stores a mapping from attribute names to their corresponding layout types.
* Note that names of attribute layouts and their formats are NOT
* internationalized, and should not be translated.
*/
class AttributeLayoutMap {
private static final String STACK_MAP_LAYOUTS; //5.5.5
private static final String NON_PARAMETER_METADATA_ANNOTATIONS;
private static final String METHOD_PARAMETER_ANNOTATIONS;
private static final String RUNTIME_TYPE_ANNOTATIONS;
static {
StringBuilder sb = new StringBuilder(1024);
// STACK_MAP_LAYOUTS
sb.append("[NH[(1)]]");
sb.append("[TB");
for (int i = 64, l = 128; i < l; i++){
sb.append('(').append(i).append(")[(2)]");
}
sb.append("(247)[(1)(2)]");
for (int i = 248, l = 252; i<l; i++){
sb.append('(').append(i).append(")[(1)]");
}
sb.append("(252)[(1)(2)]");
sb.append("(253)[(1)(2)(2)]");
sb.append("(254)[(1)(2)(2)(2)]");
sb.append("(255)[(1)NH[(2)]NH[(2)]]");
sb.append("()[]");
sb.append(']');
sb.append("[H]");
sb.append("[TB");
sb.append("(7)[RCH]");
sb.append("(8)[PH]");
sb.append("()[]");
sb.append(']');
STACK_MAP_LAYOUTS = sb.toString();
sb.delete(0, sb.length());
// METADATA_LAYOUTS common
sb.append("[RSHNH[RUH(1)]]");
sb.append("[TB");
sb.append("(66)[KIH]");
sb.append("(67)[KIH]");
sb.append("(73)[KIH]");
sb.append("(83)[KIH]");
sb.append("(90)[KIH]");
sb.append("(68)[KDH]");
sb.append("(70)[KFH]");
sb.append("(74)[KJH]");
sb.append("(99)[RSH]");
sb.append("(101)[RSHRUH]");
sb.append("(115)[RUH]");
sb.append("(91)[NH[(0)]]");
sb.append("(64)[RSHNH[RUH(0)]]");
sb.append("()[]");
sb.append(']');
String metadataLayoutCommon = sb.toString();
sb.delete(0, sb.length());
// NON PARAMETER METADATA ANNOTATIONS
sb.append("[NH[(1)]]");
sb.append(metadataLayoutCommon);
NON_PARAMETER_METADATA_ANNOTATIONS = sb.toString();
sb.delete(0, sb.length());
// METHOD_PARAMETER_ANNOTATIONS
sb.append("[NH[(1)]]");
sb.append("[NH[(1)]]");
sb.append(metadataLayoutCommon);
METHOD_PARAMETER_ANNOTATIONS = sb.toString();
sb.delete(0, sb.length());
// RUNTIME_TYPE_ANNOTATIONS
sb.append("[NH[(1)(2)(3)]]");
sb.append("[TB");
sb.append("(0)[B]");
sb.append("(1)[B]");
sb.append("(16)[FH]");
sb.append("(17)[BB]");
sb.append("(18)[BB]");
sb.append("(19)[]");
sb.append("(20)[]");
sb.append("(21)[]");
sb.append("(22)[B]");
sb.append("(23)[H]");
sb.append("(64)[NH[PHOHH]]");
sb.append("(65)[NH[PHOHH]]");
sb.append("(66)[H]");
sb.append("(67)[PH]");
sb.append("(68)[PH]");
sb.append("(69)[PH]");
sb.append("(70)[PH]");
sb.append("(71)[PHB]");
sb.append("(72)[PHB]");
sb.append("(73)[PHB]");
sb.append("(74)[PHB]");
sb.append("(75)[PHB]");
sb.append("()[]");
sb.append(']');
sb.append("[NB[BB]]");
sb.append(metadataLayoutCommon);
RUNTIME_TYPE_ANNOTATIONS = sb.toString();
}
// Create all the default AttributeLayouts here
private static AttributeLayout[] getDefaultAttributeLayouts()
throws Pack200Exception {
return new AttributeLayout[] {
new AttributeLayout(AttributeLayout.ACC_PUBLIC,
AttributeLayout.CONTEXT_CLASS, "", 0),
new AttributeLayout(AttributeLayout.ACC_PUBLIC,
AttributeLayout.CONTEXT_FIELD, "", 0),
new AttributeLayout(AttributeLayout.ACC_PUBLIC,
AttributeLayout.CONTEXT_METHOD, "", 0),
new AttributeLayout( // Java 6
AttributeLayout.ATTRIBUTE_STACK_MAP_TABLE,
AttributeLayout.CONTEXT_CODE,
STACK_MAP_LAYOUTS,
0),
new AttributeLayout(AttributeLayout.ACC_PRIVATE,
AttributeLayout.CONTEXT_CLASS, "", 1),
new AttributeLayout(AttributeLayout.ACC_PRIVATE,
AttributeLayout.CONTEXT_FIELD, "", 1),
new AttributeLayout(AttributeLayout.ACC_PRIVATE,
AttributeLayout.CONTEXT_METHOD, "", 1),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_LINE_NUMBER_TABLE,
AttributeLayout.CONTEXT_CODE, "NH[PHH]", 1),
new AttributeLayout(AttributeLayout.ACC_PROTECTED,
AttributeLayout.CONTEXT_CLASS, "", 2),
new AttributeLayout(AttributeLayout.ACC_PROTECTED,
AttributeLayout.CONTEXT_FIELD, "", 2),
new AttributeLayout(AttributeLayout.ACC_PROTECTED,
AttributeLayout.CONTEXT_METHOD, "", 2),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_LOCAL_VARIABLE_TABLE,
AttributeLayout.CONTEXT_CODE, "NH[PHOHRUHRSHH]", 2),
new AttributeLayout(AttributeLayout.ACC_STATIC,
AttributeLayout.CONTEXT_CLASS, "", 3),
new AttributeLayout(AttributeLayout.ACC_STATIC,
AttributeLayout.CONTEXT_FIELD, "", 3),
new AttributeLayout(AttributeLayout.ACC_STATIC,
AttributeLayout.CONTEXT_METHOD, "", 3),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_LOCAL_VARIABLE_TYPE_TABLE,
AttributeLayout.CONTEXT_CODE, "NH[PHOHRUHRSHH]", 3),
new AttributeLayout(AttributeLayout.ACC_FINAL,
AttributeLayout.CONTEXT_CLASS, "", 4),
new AttributeLayout(AttributeLayout.ACC_FINAL,
AttributeLayout.CONTEXT_FIELD, "", 4),
new AttributeLayout(AttributeLayout.ACC_FINAL,
AttributeLayout.CONTEXT_METHOD, "", 4),
new AttributeLayout(AttributeLayout.ACC_SYNCHRONIZED,
AttributeLayout.CONTEXT_CLASS, "", 5),
new AttributeLayout(AttributeLayout.ACC_SYNCHRONIZED,
AttributeLayout.CONTEXT_FIELD, "", 5),
new AttributeLayout(AttributeLayout.ACC_SYNCHRONIZED,
AttributeLayout.CONTEXT_METHOD, "", 5),
new AttributeLayout(AttributeLayout.ACC_VOLATILE,
AttributeLayout.CONTEXT_CLASS, "", 6),
new AttributeLayout(AttributeLayout.ACC_VOLATILE,
AttributeLayout.CONTEXT_FIELD, "", 6),
new AttributeLayout(AttributeLayout.ACC_VOLATILE,
AttributeLayout.CONTEXT_METHOD, "", 6),
new AttributeLayout(AttributeLayout.ACC_TRANSIENT,
AttributeLayout.CONTEXT_CLASS, "", 7),
new AttributeLayout(AttributeLayout.ACC_TRANSIENT,
AttributeLayout.CONTEXT_FIELD, "", 7),
new AttributeLayout(AttributeLayout.ACC_TRANSIENT,
AttributeLayout.CONTEXT_METHOD, "", 7),
new AttributeLayout(AttributeLayout.ACC_NATIVE,
AttributeLayout.CONTEXT_CLASS, "", 8),
new AttributeLayout(AttributeLayout.ACC_NATIVE,
AttributeLayout.CONTEXT_FIELD, "", 8),
new AttributeLayout(AttributeLayout.ACC_NATIVE,
AttributeLayout.CONTEXT_METHOD, "", 8),
new AttributeLayout(AttributeLayout.ACC_INTERFACE,
AttributeLayout.CONTEXT_CLASS, "", 9),
new AttributeLayout(AttributeLayout.ACC_INTERFACE,
AttributeLayout.CONTEXT_FIELD, "", 9),
new AttributeLayout(AttributeLayout.ACC_INTERFACE,
AttributeLayout.CONTEXT_METHOD, "", 9),
new AttributeLayout(AttributeLayout.ACC_ABSTRACT,
AttributeLayout.CONTEXT_CLASS, "", 10),
new AttributeLayout(AttributeLayout.ACC_ABSTRACT,
AttributeLayout.CONTEXT_FIELD, "", 10),
new AttributeLayout(AttributeLayout.ACC_ABSTRACT,
AttributeLayout.CONTEXT_METHOD, "", 10),
new AttributeLayout(AttributeLayout.ACC_STRICT,
AttributeLayout.CONTEXT_CLASS, "", 11),
new AttributeLayout(AttributeLayout.ACC_STRICT,
AttributeLayout.CONTEXT_FIELD, "", 11),
new AttributeLayout(AttributeLayout.ACC_STRICT,
AttributeLayout.CONTEXT_METHOD, "", 11),
new AttributeLayout(AttributeLayout.ACC_SYNTHETIC,
AttributeLayout.CONTEXT_CLASS, "", 12),
new AttributeLayout(AttributeLayout.ACC_SYNTHETIC,
AttributeLayout.CONTEXT_FIELD, "", 12),
new AttributeLayout(AttributeLayout.ACC_SYNTHETIC,
AttributeLayout.CONTEXT_METHOD, "", 12),
new AttributeLayout(AttributeLayout.ACC_ANNOTATION,
AttributeLayout.CONTEXT_CLASS, "", 13),
new AttributeLayout(AttributeLayout.ACC_ANNOTATION,
AttributeLayout.CONTEXT_FIELD, "", 13),
new AttributeLayout(AttributeLayout.ACC_ANNOTATION,
AttributeLayout.CONTEXT_METHOD, "", 13),
new AttributeLayout(AttributeLayout.ACC_ENUM,
AttributeLayout.CONTEXT_CLASS, "", 14),
new AttributeLayout(AttributeLayout.ACC_ENUM,
AttributeLayout.CONTEXT_FIELD, "", 14),
new AttributeLayout(AttributeLayout.ACC_ENUM,
AttributeLayout.CONTEXT_METHOD, "", 14),
new AttributeLayout(AttributeLayout.ATTRIBUTE_SOURCE_FILE,
AttributeLayout.CONTEXT_CLASS, "RUNH", 17),
new AttributeLayout(AttributeLayout.ATTRIBUTE_CONSTANT_VALUE,
AttributeLayout.CONTEXT_FIELD, "KQH", 17),
new AttributeLayout(AttributeLayout.ATTRIBUTE_CODE,
AttributeLayout.CONTEXT_METHOD, "", 17),
new AttributeLayout(AttributeLayout.ATTRIBUTE_ENCLOSING_METHOD,
AttributeLayout.CONTEXT_CLASS, "RCHRDNH", 18),
new AttributeLayout(AttributeLayout.ATTRIBUTE_EXCEPTIONS,
AttributeLayout.CONTEXT_METHOD, "NH[RCH]", 18),
new AttributeLayout(AttributeLayout.ATTRIBUTE_SIGNATURE,
AttributeLayout.CONTEXT_CLASS, "RSH", 19),
new AttributeLayout(AttributeLayout.ATTRIBUTE_SIGNATURE,
AttributeLayout.CONTEXT_FIELD, "RSH", 19),
new AttributeLayout(AttributeLayout.ATTRIBUTE_SIGNATURE,
AttributeLayout.CONTEXT_METHOD, "RSH", 19),
new AttributeLayout(AttributeLayout.ATTRIBUTE_DEPRECATED,
AttributeLayout.CONTEXT_CLASS, "", 20),
new AttributeLayout(AttributeLayout.ATTRIBUTE_DEPRECATED,
AttributeLayout.CONTEXT_FIELD, "", 20),
new AttributeLayout(AttributeLayout.ATTRIBUTE_DEPRECATED,
AttributeLayout.CONTEXT_METHOD, "", 20),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS,
AttributeLayout.CONTEXT_CLASS,
// "*",
NON_PARAMETER_METADATA_ANNOTATIONS,
21),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS,
AttributeLayout.CONTEXT_FIELD,
// "*",
NON_PARAMETER_METADATA_ANNOTATIONS,
21),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS,
AttributeLayout.CONTEXT_METHOD,
// "*",
NON_PARAMETER_METADATA_ANNOTATIONS,
21),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS,
AttributeLayout.CONTEXT_CLASS,
// "*",
NON_PARAMETER_METADATA_ANNOTATIONS,
22),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS,
AttributeLayout.CONTEXT_FIELD,
// "*",
NON_PARAMETER_METADATA_ANNOTATIONS,
22),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS,
AttributeLayout.CONTEXT_METHOD,
// "*",
NON_PARAMETER_METADATA_ANNOTATIONS,
22),
new AttributeLayout(AttributeLayout.ATTRIBUTE_INNER_CLASSES,
AttributeLayout.CONTEXT_CLASS, "", 23),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS,
AttributeLayout.CONTEXT_METHOD,
// "*",
METHOD_PARAMETER_ANNOTATIONS,
23),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_CLASS_FILE_VERSION,
AttributeLayout.CONTEXT_CLASS, "", 24),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS,
AttributeLayout.CONTEXT_METHOD,
// "*",
METHOD_PARAMETER_ANNOTATIONS,
24),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_ANNOTATION_DEFAULT,
AttributeLayout.CONTEXT_METHOD,
// "*",
NON_PARAMETER_METADATA_ANNOTATIONS,
25), // TODO: CHECK METADATA LAYOUT
new AttributeLayout(
AttributeLayout.ATTRIBUTE_METHOD_PARAMETERS,
AttributeLayout.CONTEXT_METHOD, "NB[RUNHFH]", 26),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_CLASS, RUNTIME_TYPE_ANNOTATIONS, 27),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_FIELD, RUNTIME_TYPE_ANNOTATIONS, 27),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_METHOD, RUNTIME_TYPE_ANNOTATIONS, 27),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_VISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_CODE, RUNTIME_TYPE_ANNOTATIONS, 27),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_CLASS, RUNTIME_TYPE_ANNOTATIONS, 28),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_FIELD, RUNTIME_TYPE_ANNOTATIONS, 28),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_METHOD, RUNTIME_TYPE_ANNOTATIONS, 28),
new AttributeLayout(
AttributeLayout.ATTRIBUTE_RUNTIME_INVISIBLE_TYPE_ANNOTATIONS,
AttributeLayout.CONTEXT_CODE, RUNTIME_TYPE_ANNOTATIONS, 28),
};
}
private final Map classLayouts = new HashMap();
private final Map fieldLayouts = new HashMap();
private final Map methodLayouts = new HashMap();
private final Map codeLayouts = new HashMap();
// The order of the maps in this array should not be changed as their
// indices correspond to
// the value of their context constants (AttributeLayout.CONTEXT_CLASS etc.)
private final Map[] layouts = new Map[] { classLayouts, fieldLayouts,
methodLayouts, codeLayouts };
private final Map layoutsToBands = new HashMap();
public AttributeLayoutMap() throws Pack200Exception {
AttributeLayout[] defaultAttributeLayouts = getDefaultAttributeLayouts();
for (int i = 0; i < defaultAttributeLayouts.length; i++) {
add(defaultAttributeLayouts[i]);
}
}
public void add(AttributeLayout layout) {
layouts[layout.getContext()]
.put(Integer.valueOf(layout.getIndex()), layout);
}
public void add(AttributeLayout layout, NewAttributeBands newBands) {
add(layout);
layoutsToBands.put(layout, newBands);
}
public AttributeLayout getAttributeLayout(String name, int context)
throws Pack200Exception {
Map map = layouts[context];
for (Iterator iter = map.values().iterator(); iter.hasNext();) {
AttributeLayout layout = (AttributeLayout) iter.next();
if (layout.getName().equals(name)) {
return layout;
}
}
return null;
}
public AttributeLayout getAttributeLayout(int index, int context)
throws Pack200Exception {
Map map = layouts[context];
return (AttributeLayout) map.get(Integer.valueOf(index));
}
/**
* The map should not contain the same layout and name combination more than
* once for each context.
*
* @throws Pack200Exception
*
*/
public void checkMap() throws Pack200Exception {
for (int i = 0; i < layouts.length; i++) {
Map map = layouts[i];
Collection c = map.values();
if (!(c instanceof List)) {
c = new ArrayList(c);
}
List l = (List) c;
for (int j = 0; j < l.size(); j++) {
AttributeLayout layout1 = (AttributeLayout) l.get(j);
for (int j2 = j + 1; j2 < l.size(); j2++) {
AttributeLayout layout2 = (AttributeLayout) l.get(j2);
if (layout1.getName().equals(layout2.getName())
&& layout1.getLayout().equals(layout2.getLayout())) {
throw new Pack200Exception(
"Same layout/name combination: "
+ layout1.getLayout()
+ "/"
+ layout1.getName()
+ " exists twice for context: "
+ AttributeLayout.contextNames[layout1
.getContext()]);
}
}
}
}
}
public NewAttributeBands getAttributeBands(AttributeLayout layout) {
return (NewAttributeBands) layoutsToBands.get(layout);
}
}
|
package com.dscalzi.realisticelevators.command;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.dscalzi.realisticelevators.command.sub.Create;
import com.dscalzi.realisticelevators.command.sub.Reload;
import com.dscalzi.realisticelevators.util.MessageManager;
public class MainCommandExecutor implements CommandExecutor{
private Map<String, SubCommandExecutor> subCommandRegistry;
public MainCommandExecutor(){
subCommandRegistry = new HashMap<String, SubCommandExecutor>();
subCommandRegistry.put("create", new Create());
subCommandRegistry.put("reload", new Reload());
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(args.length > 0){
try{
this.cmdList(sender, Integer.parseInt(args[0]));
return true;
} catch (NumberFormatException e){
this.reroute(sender, cmd, label, args);
return true;
}
}
this.cmdList(sender, 1);
return true;
}
private void cmdList(CommandSender sender, int page){
MessageManager.getInstance().sendMessage(sender, "Command list coming soon!");
}
private void reroute(CommandSender sender, Command cmd, String label, String[] args){
for(Map.Entry<String, SubCommandExecutor> entry : subCommandRegistry.entrySet()){
if(args[0].equalsIgnoreCase(entry.getKey())){
entry.getValue().handle(sender, cmd, label, args);
return;
}
}
MessageManager.getInstance().sendError(sender, "Unknown subcommand: " + args[0].toLowerCase());
}
}
|
public class Factorial {
public static void main(String[] args) {
System.out.println(factorialFx(3));
}
public static int factorialFx(int num){
if(num == 0){
return 1;
}else if(num == 1){
return 1;
}else{
return num * factorialFx(num-1) ;
}
}
}
|
package com.box.androidsdk.content.requests;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.widget.Toast;
import com.box.androidsdk.content.BoxCache;
import com.box.androidsdk.content.BoxCacheFutureTask;
import com.box.androidsdk.content.BoxConfig;
import com.box.androidsdk.content.BoxConstants;
import com.box.androidsdk.content.BoxException;
import com.box.androidsdk.content.BoxFutureTask;
import com.box.androidsdk.content.auth.BlockedIPErrorActivity;
import com.box.androidsdk.content.auth.BoxAuthentication;
import com.box.androidsdk.content.listeners.ProgressListener;
import com.box.androidsdk.content.models.BoxArray;
import com.box.androidsdk.content.models.BoxJsonObject;
import com.box.androidsdk.content.models.BoxObject;
import com.box.androidsdk.content.models.BoxSession;
import com.box.androidsdk.content.models.BoxSharedLinkSession;
import com.box.androidsdk.content.utils.BoxLogUtils;
import com.box.androidsdk.content.utils.SdkUtils;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.net.MalformedURLException;
/**
* This class represents a request made to the Box server.
* @param <T> The object that data from the server should be parsed into.
* @param <R> The child class extending this object.
*/
public abstract class BoxRequest<T extends BoxObject, R extends BoxRequest<T, R>> implements Serializable{
public static final String JSON_OBJECT = "json_object";
protected String mRequestUrlString;
protected Methods mRequestMethod;
protected HashMap<String, String> mQueryMap = new HashMap<String, String>();
protected LinkedHashMap<String, Object> mBodyMap = new LinkedHashMap<String, Object>();
protected LinkedHashMap<String, String> mHeaderMap = new LinkedHashMap<String, String>();
protected ContentTypes mContentType = ContentTypes.JSON;
protected BoxSession mSession;
protected transient ProgressListener mListener;
protected int mTimeout;
transient BoxRequestHandler mRequestHandler;
Class<T> mClazz;
private String mStringBody;
private String mIfMatchEtag;
private String mIfNoneMatchEtag;
private transient WeakReference<SSLSocketFactoryWrapper> mSocketFactoryRef;
protected boolean mRequiresSocket = false;
/**
* Constructs a new BoxRequest.
* @param clazz The class of the object that should be returned, the class specified by the child in T.
* @param requestUrl the url to use to connect to Box.
* @param session the session used to authenticate the given request.
*/
public BoxRequest(Class<T> clazz, String requestUrl, BoxSession session) {
mClazz = clazz;
mRequestUrlString = requestUrl;
mSession = session;
setRequestHandler(new BoxRequestHandler(this));
}
/**
* Helper constructor used to copy the fields of one BoxRequest to another.
* @param request the request to copy data from.
*/
protected BoxRequest(BoxRequest request) {
this.mSession = request.getSession();
this.mClazz = request.mClazz;
this.mRequestHandler = request.getRequestHandler();
this.mRequestMethod = request.mRequestMethod;
this.mContentType = request.mContentType;
this.mIfMatchEtag = request.getIfMatchEtag();
this.mListener = request.mListener;
this.mRequestUrlString = request.mRequestUrlString;
this.mIfNoneMatchEtag = request.getIfNoneMatchEtag();
this.mTimeout = request.mTimeout;
this.mStringBody = request.mStringBody;
importRequestContentMapsFrom(request);
}
/**
* Copies data from query and body maps into the current request.
* @param source the request to copy data from.
*/
protected void importRequestContentMapsFrom(BoxRequest source) {
this.mQueryMap = new HashMap<String, String>(source.mQueryMap);
this.mBodyMap = new LinkedHashMap<String, Object>(source.mBodyMap);
}
/**
* Gets session used to authenticate this request.
*
* @return the session used to authenticate this request.
*/
public BoxSession getSession() {
return mSession;
}
/**
* Gets the request handler.
*
* @return request handler.
*/
public BoxRequestHandler getRequestHandler() {
return mRequestHandler;
}
/**
* Sets a request handler to handle sending the request.
* @param handler the request handler to use for handling given request.
* @return current request.
*/
@SuppressWarnings("unchecked")
public R setRequestHandler(BoxRequestHandler handler) {
mRequestHandler = handler;
return (R) this;
}
/**
* Set the content type encoding.
* @param contentType sets the encoding type of this request.
* @return current request.
*/
public R setContentType(ContentTypes contentType) {
mContentType = contentType;
return (R) this;
}
/**
* Set the time out for this request in milliseconds via the method in HttpUrlConnection.
*
* <p><strong>Warning:</strong> if the hostname resolves to multiple IP
* addresses, this client will try each in <a
* href="http://www.ietf.org/rfc/rfc3484.txt">RFC 3484</a> order. If
* connecting to each of these addresses fails, multiple timeouts will
* elapse before the connect attempt throws an exception. Host names that
* support both IPv6 and IPv4 always have at least 2 IP addresses.
*
* @param timeOut time in milliseconds to wait for request to finish.
* @return current request.
*/
public R setTimeOut(int timeOut){
mTimeout = timeOut;
return (R) this;
}
/**
* Synchronously make the request to Box and handle the response appropriately.
*
* @return the expected BoxObject if the request is successful.
* @throws BoxException thrown if there was a problem with handling the request.
*/
public final T send() throws BoxException {
Exception ex = null;
T result = null;
// Pattern to check for relative paths
Pattern RELATIVE_PATH = Pattern.compile(".*\\/\\.+.*");
if (mRequestUrlString != null && RELATIVE_PATH.matcher(mRequestUrlString).matches()) {
throw new BoxException("An invalid path parameter passed. Relative path parameters cannot be passed.");
}
try {
result = onSend();
} catch (Exception e){
ex = e;
}
// We catch the exception so that onSendCompleted can be called in case additional actions need to be taken
onSendCompleted(new BoxResponse(result, ex, this));
if (ex != null) {
if (ex instanceof BoxException){
throw (BoxException)ex;
} else {
throw new BoxException("unexpected exception ",ex);
}
}
return result;
}
/**
*
* Synchronously make the request to Box and handle the response appropriately.
* @return the expected BoxObject if the request is successful.
* @throws BoxException thrown if there was a problem with handling the request.
*/
protected T onSend() throws BoxException {
BoxRequest.BoxRequestHandler requestHandler = getRequestHandler();
BoxHttpResponse response = null;
HttpURLConnection connection = null;
try {
// Create the HTTP request and send it
BoxHttpRequest request = createHttpRequest();
connection = request.getUrlConnection();
if (mRequiresSocket && connection instanceof HttpsURLConnection) {
final SSLSocketFactory factory = ((HttpsURLConnection) connection).getSSLSocketFactory();
SSLSocketFactoryWrapper wrappedFactory = new SSLSocketFactoryWrapper(factory);
mSocketFactoryRef = new WeakReference<SSLSocketFactoryWrapper>(wrappedFactory);
((HttpsURLConnection) connection).setSSLSocketFactory(wrappedFactory);
}
if (mTimeout > 0) {
connection.setConnectTimeout(mTimeout);
connection.setReadTimeout(mTimeout);
}
response = sendRequest(request, connection);
logDebug(response);
// Process the response through the provided handler
if (requestHandler.isResponseSuccess(response)) {
T result = (T) requestHandler.onResponse(mClazz, response);
return result;
}
// All non successes will throw
throw new BoxException("An error occurred while sending the request", response);
}
catch (IOException e) {
return handleSendException(requestHandler, response, e);
} catch (InstantiationException e) {
return handleSendException(requestHandler, response, e);
} catch (IllegalAccessException e) {
return handleSendException(requestHandler, response, e);
} catch (BoxException e) {
return handleSendException(requestHandler, response, e);
}
finally {
if (connection != null){
connection.disconnect();
}
}
}
/**
* Post action that will be performed after a successful send occurs. Example useage would include
* updating the cache after a request is made
*
* @param response response of the BoxRequest
* @throws BoxException thrown if there was a problem with handling the request.
*/
protected void onSendCompleted(BoxResponse<T> response) throws BoxException {
// Child classes to provide implementation if needed
}
private T handleSendException(BoxRequestHandler requestHandler, BoxHttpResponse response, Exception ex) throws BoxException {
if (ex instanceof BoxException) {
if (requestHandler.onException(this, response, (BoxException) ex)) {
return send();
} else {
throw (BoxException) ex;
}
} else {
BoxException e = new BoxException("Couldn't connect to the Box API due to a network error.", ex);
requestHandler.onException(this, response, e);
throw e;
}
}
/**
* Creates a BoxFutureTask to make the request asynchronously.
*
* @return a BoxFutureTask that can be used to make the same request as the send method asynchronously.
*/
public BoxFutureTask<T> toTask() {
return new BoxFutureTask<T>(mClazz, this);
}
protected BoxHttpRequest createHttpRequest() throws IOException, BoxException {
URL requestUrl = buildUrl();
BoxHttpRequest httpRequest = new BoxHttpRequest(requestUrl, mRequestMethod, mListener);
setHeaders(httpRequest);
setBody(httpRequest);
return httpRequest;
}
protected BoxHttpResponse sendRequest(BoxHttpRequest request, HttpURLConnection connection) throws IOException, BoxException {
BoxHttpResponse response = new BoxHttpResponse(connection);
response.open();
return response;
}
protected URL buildUrl() throws MalformedURLException, UnsupportedEncodingException {
String queryString = createQuery(mQueryMap);
URL requestUrl = TextUtils.isEmpty(queryString) ? new URL(mRequestUrlString) : new URL(String.format(Locale.ENGLISH, "%s?%s", mRequestUrlString,
queryString));
return requestUrl;
}
protected String createQuery(Map<String, String> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
String queryPattern = "%s=%s";
boolean first = true;
for (Map.Entry<String, String> pair : map.entrySet()) {
sb.append(String.format(Locale.ENGLISH, queryPattern, URLEncoder.encode(pair.getKey(), "UTF-8"), URLEncoder.encode(pair.getValue(), "UTF-8")));
if (first) {
queryPattern = "&" + queryPattern;
first = false;
}
}
return sb.toString();
}
protected void createHeaderMap() {
mHeaderMap.clear();
BoxAuthentication.BoxAuthenticationInfo info = mSession.getAuthInfo();
String accessToken = (info == null ? null : info.accessToken());
if (!SdkUtils.isEmptyString(accessToken)) {
mHeaderMap.put("Authorization", String.format(Locale.ENGLISH, "Bearer %s", accessToken));
}
mHeaderMap.put("User-Agent", mSession.getUserAgent());
mHeaderMap.put("Accept-Encoding", "gzip");
mHeaderMap.put("Accept-Charset", "utf-8");
if (mContentType != null) {
mHeaderMap.put("Content-Type", mContentType.toString());
}
if (mIfMatchEtag != null) {
mHeaderMap.put("If-Match", mIfMatchEtag);
}
if (mIfNoneMatchEtag != null) {
mHeaderMap.put("If-None-Match", mIfNoneMatchEtag);
}
if (mSession instanceof BoxSharedLinkSession) {
BoxSharedLinkSession slSession = (BoxSharedLinkSession) mSession;
if (!TextUtils.isEmpty(slSession.getSharedLink())) {
String shareLinkHeader = String.format(Locale.ENGLISH, "shared_link=%s", slSession.getSharedLink());
if (!TextUtils.isEmpty(slSession.getPassword())) {
shareLinkHeader += String.format(Locale.ENGLISH, "&shared_link_password=%s", slSession.getPassword());
}
mHeaderMap.put("BoxApi", shareLinkHeader);
}
}
}
protected void setHeaders(BoxHttpRequest request) {
createHeaderMap();
for (Map.Entry<String,String> h : mHeaderMap.entrySet()) {
request.addHeader(h.getKey(), h.getValue());
}
}
protected R setIfMatchEtag(String etag) {
mIfMatchEtag = etag;
return (R) this;
}
protected String getIfMatchEtag() {
return mIfMatchEtag;
}
protected R setIfNoneMatchEtag(String etag) {
mIfNoneMatchEtag = etag;
return (R) this;
}
protected String getIfNoneMatchEtag() {
return mIfNoneMatchEtag;
}
protected void setBody(BoxHttpRequest request) throws IOException {
if (!mBodyMap.isEmpty()) {
String body = getStringBody();
byte[] bytes = body.getBytes("UTF-8");
request.setBody(new ByteArrayInputStream(bytes));
}
}
/**
* Gets the string body for the request.
*
* @return the string body associated with this request.
* @throws UnsupportedEncodingException thrown if there was a problem with the encoding of the body.
*/
public String getStringBody() throws UnsupportedEncodingException {
if (mStringBody != null)
return mStringBody;
if (mContentType != null) {
switch (mContentType) {
case JSON:
JsonObject jsonBody = new JsonObject();
for (Map.Entry<String, Object> entry : mBodyMap.entrySet()) {
parseHashMapEntry(jsonBody, entry);
}
mStringBody = jsonBody.toString();
break;
case URL_ENCODED:
HashMap<String, String> stringMap = new HashMap<String, String>();
for (Map.Entry<String, Object> entry : mBodyMap.entrySet()) {
stringMap.put(entry.getKey(), (String) entry.getValue());
}
mStringBody = createQuery(stringMap);
break;
case JSON_PATCH:
mStringBody = ((BoxArray) mBodyMap.get(JSON_OBJECT)).toJson();
break;
}
}
return mStringBody;
}
protected void parseHashMapEntry(JsonObject jsonBody, Map.Entry<String, Object> entry) {
Object obj = entry.getValue();
if (obj instanceof BoxJsonObject) {
jsonBody.add(entry.getKey(), parseJsonObject(obj));
} else if (obj instanceof Double) {
jsonBody.add(entry.getKey(), Double.toString((Double) obj));
} else if (obj instanceof Enum || obj instanceof Boolean) {
jsonBody.add(entry.getKey(), obj.toString());
} else if (obj instanceof JsonArray) {
jsonBody.add(entry.getKey(), (JsonArray) obj);
} else if (obj instanceof Long) {
jsonBody.add(entry.getKey(), JsonValue.valueOf((Long)obj));
} else if (obj instanceof Integer) {
jsonBody.add(entry.getKey(), JsonValue.valueOf((Integer)obj));
} else if (obj instanceof Float) {
jsonBody.add(entry.getKey(), JsonValue.valueOf((Float)obj));
} else if (obj instanceof String) {
jsonBody.add(entry.getKey(), (String) obj);
} else {
BoxLogUtils.e("Unable to parse value " + obj, new RuntimeException("Invalid value"));
}
}
protected JsonValue parseJsonObject(Object obj) {
String json = ((BoxJsonObject) obj).toJson();
JsonValue value = JsonValue.readFrom(json);
return value;
}
protected void logDebug(BoxHttpResponse response) throws BoxException {
try {
logRequest();
BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Response (%s): %s", response.getResponseCode(), response.getStringBody()));
} catch (Exception e){
// do not throw exceptions for debugging
BoxLogUtils.e("logDebug", e);
}
}
protected void logRequest() {
String urlString = null;
try {
URL requestUrl = buildUrl();
urlString = requestUrl.toString();
} catch (MalformedURLException e) {
// Do nothing
} catch (UnsupportedEncodingException e) {
// Do nothing
}
BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Request (%s): %s", mRequestMethod, urlString));
BoxLogUtils.i(BoxConstants.TAG, "Request Header", mHeaderMap);
if (mContentType != null) {
switch (mContentType) {
case JSON:
case JSON_PATCH:
if (!SdkUtils.isBlank(mStringBody)) {
BoxLogUtils.i(BoxConstants.TAG, String.format(Locale.ENGLISH, "Request JSON: %s", mStringBody));
}
break;
case URL_ENCODED:
HashMap<String, String> stringMap = new HashMap<String, String>();
for (Map.Entry<String, Object> entry : mBodyMap.entrySet()) {
stringMap.put(entry.getKey(), (String) entry.getValue());
}
BoxLogUtils.i(BoxConstants.TAG, "Request Form Data", stringMap);
break;
default:
break;
}
}
}
private <T extends BoxRequest & BoxCacheableRequest> T getCacheableRequest() {
return (T) this;
}
/**
* Default implementation for sending a request. If fromCache is false, this will default to
* the standard #send() method.
*
* @return The result of sending the request to cache implementation.
* @throws BoxException Exception from sending the request. A {@link com.box.androidsdk.content.BoxException.CacheImplementationNotFound}
* will be thrown if a cache implementation is not provided in BoxConfig and fromCache is true
*/
protected T handleSendForCachedResult() throws BoxException {
BoxCache cache = BoxConfig.getCache();
if (cache == null) {
throw new BoxException.CacheImplementationNotFound();
}
return cache.get(getCacheableRequest());
}
/**
* Default implementation for getting a task to execute the request.
* @param <R> A BoxRequest that implements BoxCaceableRequest
* @return The task used to get data from cache implementation.
* @throws BoxException thrown if there is no cache implementation set in BoxConfig.
*/
protected <R extends BoxRequest & BoxCacheableRequest> BoxFutureTask<T> handleToTaskForCachedResult() throws BoxException {
BoxCache cache = BoxConfig.getCache();
if (cache == null) {
throw new BoxException.CacheImplementationNotFound();
}
return new BoxCacheFutureTask<T, R>(mClazz, (R) getCacheableRequest(), cache);
}
/**
* If available, makes a call to update the cache with the provided result
*
* @param response the new result to update the cache with
* @throws BoxException thrown if there was an issue updating cache for given response.
*/
protected void handleUpdateCache(BoxResponse<T> response) throws BoxException {
BoxCache cache = BoxConfig.getCache();
if (cache != null) {
cache.put(response);
}
}
/**
* This class handles parsing the response from Box's server into the correct data object if successful or throw the appropriate exception if not.
* The default implementation of this class is designed to handle JSON objects.
*/
public static class BoxRequestHandler<R extends BoxRequest> {
public final static String OAUTH_ERROR_HEADER = "error";
public final static String OAUTH_INVALID_TOKEN = "invalid_token";
public final static String WWW_AUTHENTICATE = "WWW-Authenticate";
protected static final int DEFAULT_NUM_RETRIES = 1;
protected final static int DEFAULT_RATE_LIMIT_WAIT = 20;
private static final int DEFAULT_AUTH_REFRESH_RETRY = 4;
protected R mRequest;
protected int mNumRateLimitRetries = 0;
private int mRefreshRetries = 0;
public BoxRequestHandler(R request) {
mRequest = request;
}
/**
* Check the response returned from the server.
*
* @param response the response from the server.
* @return true if the response is a success condition, false if the response indicates a failure.
*/
public boolean isResponseSuccess(BoxHttpResponse response) {
int responseCode = response.getResponseCode();
return (responseCode >= 200 && responseCode < 300) || responseCode == BoxConstants.HTTP_STATUS_TOO_MANY_REQUESTS;
}
/**
* Parse the response from the server into the expected object T. clazz is used to create a new instance of this object in this implementation,
* so if using this implementation, it is important that T be an instance of BoxJsonObject.
*
* @param clazz the class to use to construct an instance of T in which to parse data to.
* @param response the response from the server.
* @param <T> the class to return an instance of.
* @return an instance of T parsed from the server response.
* @throws IllegalAccessException thrown if clazz this class does not have access to the constructor for clazz.
* @throws InstantiationException thrown if clazz cannot be instantiated for example if it does not have a default contsructor.
* @throws BoxException thrown for any type of server exception or server response indicating an error.
*/
public <T extends BoxObject> T onResponse(Class<T> clazz, BoxHttpResponse response) throws IllegalAccessException, InstantiationException, BoxException {
if (response.getResponseCode() == BoxConstants.HTTP_STATUS_TOO_MANY_REQUESTS) {
return retryRateLimited(response);
}
if (Thread.currentThread().isInterrupted()){
disconnectForInterrupt(response);
}
String contentType = response.getContentType();
T entity = clazz.newInstance();
if (entity instanceof BoxJsonObject && contentType.contains(ContentTypes.JSON.toString())) {
String json = response.getStringBody();
((BoxJsonObject) entity).createFromJson(json);
}
return entity;
}
protected <T extends BoxObject> T retryRateLimited(BoxHttpResponse response) throws BoxException {
if (mNumRateLimitRetries < DEFAULT_NUM_RETRIES) {
mNumRateLimitRetries++;
int defaultWait = DEFAULT_RATE_LIMIT_WAIT + (int) (10 * Math.random());
int retryAfter = getRetryAfterFromResponse(response, defaultWait);
try {
Thread.sleep(retryAfter);
} catch (InterruptedException e) {
throw new BoxException(e.getMessage(), e);
}
return (T) mRequest.send();
}
throw new BoxException.RateLimitAttemptsExceeded("Max attempts exceeded", mNumRateLimitRetries, response);
}
protected void disconnectForInterrupt(BoxHttpResponse response) throws BoxException{
try {
response.getHttpURLConnection().disconnect();
} catch (Exception e){
BoxLogUtils.e("Interrupt disconnect", e);
}
throw new BoxException("Thread interrupted request cancelled ",new InterruptedException());
}
/**
*
* @param request The request that has failed.
* @param response the response from sending the request.
* @param ex The exception thrown from sending the failed request.
* @return true if exception is handled well and request can be re-sent. false otherwise.
* @throws BoxException.RefreshFailure thrown when request cannot be retried due to a bad access token that cannoth be refreshed.
*/
public boolean onException(BoxRequest request, BoxHttpResponse response, BoxException ex) throws BoxException.RefreshFailure{
BoxSession session = request.getSession();
if (oauthExpired(response)) {
try {
BoxResponse<BoxSession> refreshResponse = session.refresh().get();
if (refreshResponse.isSuccess()) {
return true;
} else if (refreshResponse.getException() != null) {
if (refreshResponse.getException() instanceof BoxException.RefreshFailure) {
throw (BoxException.RefreshFailure)refreshResponse.getException();
} else {
return false;
}
}
} catch (InterruptedException e){
BoxLogUtils.e("oauthRefresh","Interrupted Exception",e);
} catch (ExecutionException e1){
BoxLogUtils.e("oauthRefresh", "Interrupted Exception", e1);
}
} else if (authFailed(response)) {
BoxException.ErrorType type = ex.getErrorType();
if (!session.suppressesAuthErrorUIAfterLogin()) {
Context context = session.getApplicationContext();
if (type == BoxException.ErrorType.IP_BLOCKED || type == BoxException.ErrorType.LOCATION_BLOCKED) {
Intent intent = new Intent(session.getApplicationContext(), BlockedIPErrorActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
return false;
} else if (type == BoxException.ErrorType.TERMS_OF_SERVICE_REQUIRED) {
SdkUtils.toastSafely(context,
com.box.sdk.android.R.string.boxsdk_error_terms_of_service,
Toast.LENGTH_LONG);
}
try {
if (mRefreshRetries > DEFAULT_AUTH_REFRESH_RETRY) {
String msg = " Exceeded max refresh retries for "
+ request.getClass().getName() + " response code" + ex.getResponseCode() + " response " + response;
if (ex.getAsBoxError() != null) {
msg += ex.getAsBoxError().toJson();
}
BoxLogUtils.nonFatalE("authFailed",msg, ex);
return false;
}
// attempt to refresh as a last attempt. This also acts to standardize in case this particular request behaves differently.
BoxResponse<BoxSession> refreshResponse = session.refresh().get();
if (refreshResponse.isSuccess()) {
mRefreshRetries++;
return true;
} else if (refreshResponse.getException() != null) {
if (refreshResponse.getException() instanceof BoxException.RefreshFailure) {
throw (BoxException.RefreshFailure)refreshResponse.getException();
} else {
return false;
}
}
} catch (InterruptedException e){
BoxLogUtils.e("oauthRefresh","Interrupted Exception",e);
} catch (ExecutionException e1){
BoxLogUtils.e("oauthRefresh", "Interrupted Exception", e1);
}
}
} else if (response != null && response.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
BoxException.ErrorType type = ex.getErrorType();
if (type == BoxException.ErrorType.IP_BLOCKED || type == BoxException.ErrorType.LOCATION_BLOCKED) {
Context context = session.getApplicationContext();
Intent intent = new Intent(session.getApplicationContext(), BlockedIPErrorActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
return false;
}
}
return false;
}
protected static int getRetryAfterFromResponse(BoxHttpResponse response, int defaultSeconds) {
int retryAfterSeconds = defaultSeconds;
String value = response.getHttpURLConnection().getHeaderField("Retry-After");
if (!SdkUtils.isBlank(value)) {
try {
retryAfterSeconds = Integer.parseInt(value);
} catch (NumberFormatException ex) {
// Do nothing
}
// Ensure the wait is never 0
retryAfterSeconds = retryAfterSeconds > 0 ? retryAfterSeconds : 1;
}
return retryAfterSeconds * 1000;
}
private boolean authFailed(BoxHttpResponse response) {
if (response == null){
return false;
}
return response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED;
}
private boolean oauthExpired(BoxHttpResponse response) {
if (response == null) {
return false;
}
if (HttpURLConnection.HTTP_UNAUTHORIZED != response.getResponseCode()) {
return false;
}
String header = response.mConnection.getHeaderField(WWW_AUTHENTICATE);
if (!SdkUtils.isEmptyString(header)) {
String[] authStrs = header.split(",");
for (String str : authStrs) {
if (isInvalidTokenError(str)) {
return true;
}
}
}
return false;
}
private boolean isInvalidTokenError(String str) {
String[] parts = str.split("=");
if (parts.length == 2 && parts[0] != null && parts[1] != null) {
if (OAUTH_ERROR_HEADER.equalsIgnoreCase(parts[0].trim()) && OAUTH_INVALID_TOKEN.equalsIgnoreCase(parts[1].replace("\"", "").trim())) {
return true;
}
}
return false;
}
}
/**
* Serialize object.
*
* @serialData The capacity (int), followed by elements (each an {@code Object}) in the proper order, followed by a null
* @param s the stream
* @throws java.io.IOException thrown if there is an issue serializing object.
*/
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
// Write out capacity and any hidden stuff
s.defaultWriteObject();
}
/**
* Deserialize object.
*
* @param s the stream
* @throws java.io.IOException thrown if there is an issue deserializing object.
* @throws ClassNotFoundException java.io.Cl thrown if a class cannot be found when deserializing.
*/
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
mRequestHandler = new BoxRequestHandler(this);
}
@Override
public int hashCode() {
StringBuilder sb = new StringBuilder();
sb.append(mRequestMethod);
sb.append(mRequestUrlString);
appendPairsToStringBuilder(sb, mHeaderMap);
appendPairsToStringBuilder(sb, mQueryMap);
return sb.toString().hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BoxRequest)) {
return false;
}
BoxRequest other = (BoxRequest)o;
return mRequestMethod == other.mRequestMethod
&& mRequestUrlString.equals(other.mRequestUrlString)
&& areHashMapsSame(mHeaderMap, other.mHeaderMap)
&& areHashMapsSame(mQueryMap, other.mQueryMap);
}
private void appendPairsToStringBuilder(StringBuilder sb, HashMap<String, String> hashmap) {
for (String key: hashmap.keySet()) {
sb.append(key);
sb.append(hashmap.get(key));
}
}
private boolean areHashMapsSame(HashMap<String, String> first, HashMap<String, String> second) {
if (first.size() != second.size()) {
return false;
}
for (String key: first.keySet()) {
if (!second.containsKey(key)) {
return false;
}
if (!first.get(key).equals(second.get(key))) {
return false;
}
}
return true;
}
/**
* The different type of methods to communicate with the Box server.
*/
public enum Methods {
GET, POST, PUT, DELETE, OPTIONS
}
/**
* The different content types used to encode data sent to the Box Server.
*/
public enum ContentTypes {
JSON("application/json"), URL_ENCODED("application/x-www-form-urlencoded"),
JSON_PATCH("application/json-patch+json"), APPLICATION_OCTET_STREAM ("application/octet-stream");
private String mName;
private ContentTypes(String name) {
mName = name;
}
@Override
public String toString() {
return mName;
}
}
/**
* This method requires mRequiresSocket to be set to true before connecting.
* @return the socket that ran this request if one was created for it.
*/
protected Socket getSocket(){
if (mSocketFactoryRef != null && mSocketFactoryRef.get() != null) {
return ((SSLSocketFactoryWrapper)mSocketFactoryRef.get()).getSocket();
}
return null;
}
static class SSLSocketFactoryWrapper extends SSLSocketFactory {
public SSLSocketFactory mFactory;
private WeakReference<Socket> mSocket;
public SSLSocketFactoryWrapper(SSLSocketFactory factory) {
mFactory = factory;
}
@Override
public String[] getDefaultCipherSuites() {
return mFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return mFactory.getDefaultCipherSuites();
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return wrapSocket(mFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return wrapSocket(mFactory.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return wrapSocket(mFactory.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return wrapSocket(mFactory.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return wrapSocket(mFactory.createSocket(address, port, localAddress, localPort));
}
Socket wrapSocket(Socket socket) {
mSocket = new WeakReference<Socket>(socket);
return socket;
}
public Socket getSocket(){
if (mSocket != null){
return mSocket.get();
}
return null;
}
}
private static SSLSocketFactory getTLSFactory(){
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, null, null);
return sc.getSocketFactory();
} catch (Exception e){
BoxLogUtils.e("Unable to create SSLContext", e);
}
return null;
}
public static class TLSSSLSocketFactory extends SSLSocketFactoryWrapper {
private final String[] TLS_VERSIONS = {"TLSv1.1", "TLSv1.2"};
public TLSSSLSocketFactory(){
super(getTLSFactory());
}
@Override
Socket wrapSocket(Socket socket) {
if (socket instanceof SSLSocket){
((SSLSocket) socket).setEnabledProtocols(TLS_VERSIONS);
}
return super.wrapSocket(socket);
}
}
}
|
package com.dayuanit.shop.service;
import java.util.List;
import java.util.Map;
import com.dayuanit.shop.domain.Goods;
import com.dayuanit.shop.domain.GoodsSort;
public interface DisplayService {
Map<String, Object> display(Integer sortId);
List<GoodsSort> listSort();
List<Goods> listGoods(Integer sortId);
Goods getGoodsById(Integer goodsId);
void subGoodsRepertory(Integer goodsAccount,Integer goodsId);
}
|
package lesson4.homework.appliances;
//холодильник
public class Refrigerator extends Appliances {
private int cell; //количество камер
}
|
package com.simpson.kisen.idol.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class IdolMv {
private int mvNo;
private int idolNo;
private String mvLink;
}
|
package mvc_demo.DAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import mvc_demo.interfaces.DAOInterface;
public class DAO implements DAOInterface{
boolean enableLog = true;
Connection connection = null;
String dbName = "webprog2";
String dbUser = "root";
String dbPass = "";
String tblName = "events";
String connectionString = "jdbc:mysql://localhost/"
+ dbName
+ "?user="
+ dbUser
+ "&password="
+ dbPass;
String driver = "com.mysql.jdbc.Driver";
public DAO() {
log("initiating DAO");
openConnection();
}
public Connection getConnection(){
try {
Class.forName(this.driver);
log(this.driver);
if(connection == null){
log("Creating connection..");
connection = DriverManager.getConnection(this.connectionString);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public void setTblName(String tblName){
log("Table name set to \"" + tblName + "\"");
this.tblName = tblName;
}
private boolean exec(String stmt) {
try {
PreparedStatement preparedStatement = this.connection.prepareStatement(stmt);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
private List<HashMap<String, String>> execQuery(String query) {
List<HashMap<String, String>> models = new LinkedList<HashMap<String, String>>();
try {
Statement stmt = this.connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
while (rs.next()){
HashMap<String, String> row = new HashMap<String, String>(columns);
for(int i=1; i<=columns; ++i){
row.put(md.getColumnName(i), rs.getString(i));
}
models.add(row);
}
log(models.size() + " row(s) found in table " + this.tblName);
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return models;
}
/**
* if given model has no id, create row.
* else, update the row.
*/
public boolean save(HashMap<String, String> model){
log("Saving model: " + model.toString());
String stmt = "";
if(model.get("id") == null){
stmt = this.prepareInsertStmt(model);
}else{
stmt = this.prepareUpdateStmt(model);
}
return this.exec(stmt);
}
/**
* delete model. model must have id or deletion will fail.
*
* @param model
* @return boolean
*/
public boolean delete(HashMap<String, String> model){
log("Deleting model: " + model.toString());
if(model.get("id") == null){
log("Failed to delete model: undefined id");
return false;
}
String stmt = "DELETE FROM "
+ this.tblName
+ " WHERE id = "
+ model.get("id");
return this.exec(stmt);
}
public void closeConnection(){
try {
if (connection != null) {
connection.close();
log("DB connection closed.");
}
} catch (Exception e) {
//do nothing
}
}
private void openConnection(){
if(connection == null){
connection = getConnection();
log("Connected to db: " + connection);
}
}
private String prepareInsertStmt(HashMap<String, String> model){
ArrayList<String> columnsArray = new ArrayList<>();
ArrayList<String> valuesArray = new ArrayList<>();
Iterator<?> it = model.entrySet().iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry pair = (Map.Entry)it.next();
columnsArray.add((String) pair.getKey());
valuesArray.add("\"" + pair.getValue() + "\"");
// avoids a ConcurrentModificationException
it.remove();
}
String stmt = "INSERT INTO "
+ this.tblName
+ " (" + String.join(", ", columnsArray) + ") "
+ " VALUES "
+ " (" + String.join(", ", valuesArray) + ");";
log("Prepared insert statement: " + stmt);
return stmt;
}
private String prepareUpdateStmt(HashMap<String, String> model){
// Create new ArrayList.
ArrayList<String> stmtArray = new ArrayList<>();
Iterator<?> it = model.entrySet().iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry pair = (Map.Entry)it.next();
String stmt = pair.getKey() + " = \"" + pair.getValue() + "\"";
stmtArray.add(stmt);
// avoids a ConcurrentModificationException
it.remove();
}
String stmt = "UPDATE "
+ this.tblName
+ " set "
+ String.join(", ", stmtArray)
+ " WHERE id = "
+ model.get("id")
+ ";";
log("Prepared update statement: " + stmt);
return stmt;
}
private void log(String msg){
if(this.enableLog){
System.out.println(msg);
}
}
@Override
public HashMap<String, String> find(int id) {
String query = "SELECT * from "
+ this.tblName
+ " WHERE id = "
+ id
+ " LIMIT 1;";
List<HashMap<String, String>> models = this.execQuery(query);
if(models.size() > 0){
return models.get(0);
}
return new HashMap<String, String>();
}
public List<HashMap<String, String>> select(String columns){
String query = "SELECT " + columns + " from " + this.tblName;
return this.execQuery(query);
}
public List<HashMap<String, String>> all(){
String query = "SELECT * from " + this.tblName;
return this.execQuery(query);
}
protected void finalize() throws Throwable {
// Invoke the finalizer of our superclass
// We haven't discussed superclasses or this syntax yet
super.finalize();
log("destroying instance of DAO");
closeConnection();
}
}
|
package com.fillikenesucn.petcare.activities;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.fillikenesucn.petcare.R;
import com.fillikenesucn.petcare.models.Pet;
import com.fillikenesucn.petcare.adapters.DataHelper;
import com.fillikenesucn.petcare.utils.IOHelper;
import java.util.Calendar;
/**
* Esta clase representa a la actividad que se encarga de agregar la información de una mascota para un EPC ya escaneado
* @author: Rodrigo Dorat Merejo
* @version: 06/04/2020
*/
public class RegisterScannedPetFragmentActivity extends FragmentActivity {
// VARIABLES
private Button btnFechaNacimiento;
private EditText et_fechaNacimiento;
private static final int DATE_ID = 0;
private int nYearIni, nMonthIni, nDayIni, sYearIni, sMonthIni, sDayIni;
private Calendar calendar = Calendar.getInstance();
private Spinner spinner;
private Button btnRegist;
private EditText txtName;
private RadioGroup radioGroup;
private RadioButton radioButton;
private EditText txtAddress;
private EditText txtAllergies;
private TextView txtEPC;
/**
* CONSTRUCTOR de la actividad
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_scanned_pet_fragment);
this.spinner = findViewById(R.id.spinnerRegisterPet);
ArrayAdapter<String> petsAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, DataHelper.GetSpecies());
petsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.spinner.setAdapter(petsAdapter);
this.sMonthIni = this.calendar.get(Calendar.MONTH);
this.sYearIni = this.calendar.get(Calendar.YEAR);
this.sDayIni = this.calendar.get(Calendar.DAY_OF_MONTH);
LoadInputs();
LoadExtraEPC();
btnFechaNacimiento.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePickerDialog dpd = new DatePickerDialog(RegisterScannedPetFragmentActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
et_fechaNacimiento.setText(i2 + "/" + (i1+1) + "/" + i);
}
}, sYearIni, sMonthIni, sDayIni);
dpd.show();
}
});
btnRegist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RegisterPet();
}
});
}
/**
* Método que crea el objeto mascota
* @return retorna la nueva mascota creada
*/
private Pet NewPet(){
// Obtenemos el ID de la opción seleccionada
int selectedId = radioGroup.getCheckedRadioButtonId();
// Obtenemos el botón
radioButton = (RadioButton) findViewById(selectedId);
// Extraemos la información de los inputs
String name = txtName.getText().toString();
String sex = radioButton.getText().toString();
String species = spinner.getSelectedItem().toString();
String birthdate = et_fechaNacimiento.getText().toString();
String address = txtAddress.getText().toString();
String allergies = txtAllergies.getText().toString();
String epc = txtEPC.getText().toString();
Log.d("DORAT", "done pet");
// Creamos el objeto mascota y lo guardamos en el archivo de texto
return new Pet(name,sex,birthdate,address,allergies,species,epc);
}
/**
* Método que registra la mascota en el sistema
*/
private void RegisterPet() {
Pet pet = NewPet();
// Revisamos que la información sea válida
if(DataHelper.VerificarMascotaValida(RegisterScannedPetFragmentActivity.this,pet)){
// Si puede agregar a la mascota cierra la actividad
if (IOHelper.AddPet(RegisterScannedPetFragmentActivity.this,pet)) {
Toast.makeText(RegisterScannedPetFragmentActivity.this, "INGRESO EXITOSO", Toast.LENGTH_SHORT).show();
RedirectToPetList();
}
}
}
/**
* Método que redirecciona a la lista de mascotas
*/
private void RedirectToPetList(){
Intent intent = new Intent(RegisterScannedPetFragmentActivity.this, PetListFragmentActivity.class);
startActivity(intent);
finish();
}
/**
* Método que recibe el EPC de la actividad anterior y lo setea en una variable local
*/
private void LoadExtraEPC(){
Bundle extras = getIntent().getExtras();
String txtExtra = extras.getString("EPC");
txtEPC.setText(txtExtra);
}
/**
* Método que carga los inputs del Layout
*/
private void LoadInputs(){
et_fechaNacimiento = (EditText)findViewById(R.id.fechaNacimiento);
btnFechaNacimiento = (Button)findViewById(R.id.btnFechaNacimiento);
radioGroup = (RadioGroup) findViewById(R.id.radioGroupRegistedPet);
txtName = (EditText) findViewById(R.id.txtRegistedPetNombre);
txtAddress = (EditText) findViewById(R.id.txtRegistedPetDireccion);
txtAllergies = (EditText) findViewById(R.id.txtRegistedPetAllergies);
txtEPC = (TextView) findViewById(R.id.txtRegistedPetEPC);
btnRegist = (Button) findViewById(R.id.btnAddRegistedPet);
}
}
|
package com.sixmac.service.impl;
import com.sixmac.core.Constant;
import com.sixmac.dao.*;
import com.sixmac.entity.BigRace;
import com.sixmac.entity.MessageRecord;
import com.sixmac.entity.MessageWatching;
import com.sixmac.service.BigRaceService;
import com.sixmac.service.MessageRecordService;
import com.sixmac.service.MessageWatchingService;
import com.sixmac.service.WatchingRaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* Created by Administrator on 2016/6/2 0002 下午 3:01.
*/
@Service
public class MessageWatchingServiceImpl implements MessageWatchingService {
@Autowired
private MessageWatchingDao messageWatchingDao;
@Autowired
private UserDao userDao;
@Autowired
private WatchingRaceDao watchingRaceDao;
@Autowired
private BigRaceDao bigRaceDao;
@Autowired
private MessageRecordDao messageRecordDao;
@Override
public List<MessageWatching> findAll() {
return messageWatchingDao.findAll();
}
@Override
public Page<MessageWatching> find(int pageNum, int pageSize) {
return messageWatchingDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
}
@Override
public Page<MessageWatching> find(int pageNum) {
return find(pageNum, Constant.PAGE_DEF_SZIE);
}
@Override
public MessageWatching getById(Long id) {
return messageWatchingDao.findOne(id);
}
@Override
public MessageWatching deleteById(Long id) {
MessageWatching messageWatching = getById(id);
messageWatchingDao.delete(messageWatching);
return messageWatching;
}
@Override
public MessageWatching create(MessageWatching messageWatching) {
return messageWatchingDao.save(messageWatching);
}
@Override
public MessageWatching update(MessageWatching messageWatching) {
return messageWatchingDao.save(messageWatching);
}
@Override
@Transactional
public void deleteAll(Long[] ids) {
for (Long id : ids) {
deleteById(id);
}
}
@Override
public List<MessageWatching> findByToUserId(Long userId) {
return messageWatchingDao.findByToUserId(userId);
}
@Override
public void inviteBall(HttpServletResponse response, Integer type, Long id, Long userId, Long toUserId) {
MessageWatching messageWatching = new MessageWatching();
messageWatching.setUser(userDao.findOne(userId));
messageWatching.setType(type);
messageWatching.setToUser(userDao.findOne(toUserId));
// 类型:0:现场看球,1:直播看球
if (type == 0) {
messageWatching.setBigRace(bigRaceDao.findOne(id));
} else if (type == 1) {
messageWatching.setWatchingRace(watchingRaceDao.findOne(id));
}
messageWatchingDao.save(messageWatching);
// 新增约看消息
MessageRecord messageRecord = new MessageRecord();
messageRecord.setUserId(toUserId);
messageRecord.setStatus(0);
messageRecord.setMessageId(messageWatching.getId());
// 类型(3:约看)
messageRecord.setType(3);
messageRecordDao.save(messageRecord);
}
}
|
package ServiceDao;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 自动生成接口 service dao
* @author gq
*
*/
public class ServiceDaoAudo {
public static String directory="D:\\java\\workspace\\gyl_zsl_v0.27\\src"; //绝对目录
public static String toDirectory="com.zsl.web.modules.company.service";
public static TypeEnum type=TypeEnum.SERVICE;
// public static TypeEnum type=TypeEnum.DAO;
public final static String toFile="CompanyGradeDetail";
private static List<File> listFileResults=new ArrayList<File>();
private static File findFile(File dir) {
String[] toFiles=toDirectory.split("\\.");
for (String child : toFiles) {
dir=new File(dir,child);
}
dir=new File(dir,toFile);
return dir;
}
private static void test1(){
File file=new File(directory);
File resultFile=findFile(file);
System.out.println(resultFile.getName());
recursionFile(resultFile.getParentFile());
}
private static void recursionFile2(List<File> files){
for (File file : files) {
if(file.isDirectory()){
listFileResults.add(file);
System.out.println("目录:"+file.getName());
List<File> list=Arrays.asList(file.listFiles());
recursionFile2(list);
}else{
System.out.println("文件:"+file.getName());
}
}
}
private static List<File> recursionFile(File dir){
FileFilter filter=new FileFilter() {
@Override
public boolean accept(File paramFile) {
if(paramFile.getName().contains(toFile)){
return true;
}
return false;
}
};
File[] files = dir.listFiles(filter);
for (File file : files) {
System.out.println("结果文件:"+file.getName());
}
return Arrays.asList(files);
}
/**
* 类型枚举
*/
public enum TypeEnum {
SERVICE(1,"service方法"),
DAO(10,"dao方法");
private Integer key;
private String value;
private TypeEnum(Integer key, String value) {
this.key = key;
this.value = value;
}
public static String getValue(Integer key) {
for (TypeEnum c : TypeEnum.values()) {
if (c.getKey().equals(key)) {
return c.getValue();
}
}
return null;
}
public Integer getKey() {
return key;
}
public void setKey(Integer key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static void main(String[] args) throws IOException {
List<File> list=new ArrayList<File>();
List<File> listFiles=new ArrayList<File>();
list.add(new File(directory));
recursionFile2(list);
for (File file : listFileResults) {
listFiles.addAll(recursionFile(file));
}
System.out.println("--------------------------");
File serviceFile=null;
File serviceImplFile=null;
File daoFile=null;
File daoImplFile=null;
for (File file : listFiles) {
System.out.println("结果文件:"+file.getName());
String fileName=file.getName().substring(0, file.getName().lastIndexOf("."));
if(fileName.endsWith("Service")){
serviceFile=file;
}
if(fileName.endsWith("ServiceImpl")){
serviceImplFile=file;
}
if(fileName.endsWith("Dao")){
daoFile=file;
}
if(fileName.endsWith("DaoImpl")){
daoImplFile=file;
}
}
AddToContent.getContent(serviceFile);//获得注释接口
AddToContent.addContentInterface(daoFile);//生成dao层接口
AddToContent.addContentDao(daoImplFile);//生成dao层实现
}
}
|
package de.johni0702.minecraft.gui.versions;
public class MatrixStack {
}
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileIO {
public BinarySearchTreeInterface<IMedia> ReadInventory(){
BufferedReader reader;
BinarySearchTreeInterface<IMedia> binarySearchTree = new BinarySearchTree<>();
try {
reader = new BufferedReader(new FileReader(
"src/CENG112_HW4_Media.txt"));
String line = reader.readLine();
while (line != null && line.length()>1) {
IMedia newMedia= null;
String[] mediaArr=line.split(",");
String mediaName= mediaArr[1];
int mediaPrice = Integer.parseInt(mediaArr[2]);
int mediaYear = Integer.parseInt(mediaArr[3]);
if (mediaArr[0].equals("Book")) {
String authorName=mediaArr[4];
newMedia = new Book(mediaName,mediaPrice,mediaYear,authorName);
}else {
String directorName = mediaArr[4];
String actressName= mediaArr[5];
String actorName=mediaArr[6];
newMedia = new Movie(mediaName,mediaPrice,mediaYear,directorName,actressName,actorName);
}
binarySearchTree.add(newMedia);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return binarySearchTree;
}
}
|
package com.github.enemes2000.topology;
import com.github.enemes2000.Login;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.processor.TimestampExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
public class LoginTimestampExtractor implements TimestampExtractor {
Logger LOGGER = LoggerFactory.getLogger(LoginTimestampExtractor.class);
@Override
public long extract(ConsumerRecord<Object, Object> record, long partitionTime) {
String eventTime = ((Login)record.value()).getTimestamp().toString();
LOGGER.info("parsing the EventTime {}", eventTime);
return Instant.parse(eventTime).toEpochMilli();
}
}
|
package com.jack.jkbase.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jack.jkbase.entity.SysUserRole;
/**
* <p>
* 服务类
* </p>
*
* @author LIBO
* @since 2020-09-23
*/
public interface ISysUserRoleService extends IService<SysUserRole> {
}
|
package com.shewim.game.demo;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.ColorInt;
import android.util.AttributeSet;
import android.view.View;
import java.util.Random;
/**
* Created by shewim on 2016/7/21.
*/
public class NumberView extends View {
private int value = 0;
private int width = 0,height = 0;
public void setValue(int value){
if(this.value != value)
{
this.value = value;
invalidate();
}
}
public void initValue() {
int x = new Random().nextInt(40);
setValue(x == 1?2:1);
}
public void clearValue(){
setValue(0);
}
public void setScore(){
}
public int getValue(){
return value;
}
public NumberView(Context context) {
super(context);
init(context);
}
public NumberView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public NumberView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(21)
public NumberView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context) {
}
@Override
protected void onDraw(Canvas canvas) {
if(width <= 0){
width = getMeasuredWidth();
height = getMeasuredHeight();
}
Paint paint = new Paint();
@ColorInt int color = 0xff555555;
color = color + value%3 * 0xff330000 + value/3%5*0xff001100 + value/15%5*0xff000011;
paint.setColor(color);
canvas.drawRect(0,0,width,height,paint);
if(value > 0){
int x = (int) Math.pow(2,value);
Paint paint2 = new Paint();
paint2.setColor(0xff000000);
if(x<100){
paint2.setTextSize(width / 2);
}else if(x > 100 && x < 1000){
paint2.setTextSize(width /3);
}else{
paint2.setTextSize(width / 4);
}
canvas.drawText(String.valueOf(x),width*2/5,height*3/5,paint2);
}
}
@Override
public boolean equals(Object o) {
return o instanceof NumberView && ((NumberView) o).getValue() == value;
}
public boolean isEmpty() {
return value == 0;
}
}
|
package chapter18;
import java.util.Scanner;
public class Exercise18_25 {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("Enter a string: ");
String s = input.next();
displayPermutation(s);
}
}
public static void displayPermutation(String s) {
displayPermutation("", s);
}
public static void displayPermutation(String s1, String s2) {
if (s2.length() == 0) {
System.out.println(s1);
}
for (int i = 0; i < s2.length(); i++) {
displayPermutation(s1 + s2.charAt(i), s2.substring(0, i) + s2.substring(i + 1));
}
}
}
|
package com.deltastuido.payment.port.wepay.api;
import com.deltastuido.shared.ClassUtils;
import javax.xml.bind.annotation.XmlTransient;
/**
* @author
*/
public class WepayRequest {
protected String sign = "";
protected String key = "";
public String getSign() {
return this.sign;
}
public void setSign(String sign) {
this.sign = sign;
}
@XmlTransient
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String toString() {
return ClassUtils.beanValues(this).toString();
}
}
|
package com.klocek.lowrez;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Disposable;
/**
* Created by Konrad on 2016-04-30.
*/
public class BeerLife implements Disposable {
private static final int LIFES = 3;
private static final int X_POS = 0;
private static final int SIZE = 32;
private static final int Y_POS = 8 + 128;
private int currLifes = LIFES;
private Texture littleBeerTexture;
private Texture lifesTexture;
private SpriteBatch batch;
public BeerLife(Game gameManager) {
batch = gameManager.getBatch();
littleBeerTexture = new Texture(Gdx.files.internal("littleBeer.png"));
lifesTexture = new Texture(Gdx.files.internal("lifes.png"));
}
public void update(float delta) {
batch.draw(lifesTexture, X_POS, Y_POS);
for (int i = 1; i <= currLifes; i++) {
batch.draw(littleBeerTexture, X_POS + i * SIZE + lifesTexture.getWidth() - 8, Y_POS); //TODO: Better fit!
}
}
public int getLifes() {
return currLifes;
}
public void lostBeer() {
currLifes--;
}
public void reset() {
currLifes = LIFES;
}
@Override
public void dispose() {
littleBeerTexture.dispose();
lifesTexture.dispose();
}
}
|
package com.gtfs.controller.json;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gtfs.bean.AccessList;
import com.gtfs.controller.constants.AccessListConstant;
import com.gtfs.dao.interfaces.AccessListDao;
@Controller
public class AccessListControllerJson {
@Autowired
private AccessListDao accessListDao;
@RequestMapping(value = AccessListConstant.FIND_ALL, method = RequestMethod.GET)
public @ResponseBody List<AccessList> findAll() {
List<AccessList> list = new ArrayList<AccessList>();
for(AccessList obj:accessListDao.findAll()){
AccessList accessList = new AccessList();
accessList.setAccessId(obj.getAccessId());
accessList.setAccessName(obj.getAccessName());
accessList.setUrlName(obj.getUrlName());
accessList.setCreatedBy(obj.getCreatedBy());
accessList.setModifiedBy(obj.getModifiedBy());
accessList.setDeletedBy(obj.getDeletedBy());
accessList.setDeleteFlag(obj.getDeleteFlag());
accessList.setCreatedDate(obj.getCreatedDate());
accessList.setModifiedDate(obj.getModifiedDate());
accessList.setDeletedDate(obj.getDeletedDate());
list.add(accessList);
}
return list;
}
@RequestMapping(value = AccessListConstant.FIND_BY_ID, method = RequestMethod.GET)
public @ResponseBody AccessList findById(@PathVariable("id") Long accessId) {
AccessList obj = accessListDao.findById(accessId);
AccessList accessList = new AccessList();
accessList.setAccessId(obj.getAccessId());
accessList.setAccessName(obj.getAccessName());
accessList.setUrlName(obj.getUrlName());
accessList.setCreatedBy(obj.getCreatedBy());
accessList.setModifiedBy(obj.getModifiedBy());
accessList.setDeletedBy(obj.getDeletedBy());
accessList.setDeleteFlag(obj.getDeleteFlag());
accessList.setCreatedDate(obj.getCreatedDate());
accessList.setModifiedDate(obj.getModifiedDate());
accessList.setDeletedDate(obj.getDeletedDate());
return accessList;
}
}
|
package com.meebu.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.meebu.CustomerCareActivity;
import com.meebu.FullscreenActivity;
import com.meebu.HistoryActivity;
import com.meebu.InviteFriendsActivity;
import com.meebu.MeebuWalletActivity;
import com.meebu.MyProfileActivity;
import com.meebu.OrderStatusActivity;
import com.meebu.R;
import com.meebu.RewardsActivity;
import com.meebu.SavedAddressActivity;
import com.meebu.model.HomeData;
import java.util.ArrayList;
/**
* Created by eleganz on 1/3/19.
*/
public class MyRecycler extends RecyclerView.Adapter<MyRecycler.MyViewHolder> {
Context context;
ArrayList<HomeData> arrayList;
Activity activity;
public MyRecycler(Context context, ArrayList<HomeData> arrayList) {
this.context = context;
this.activity = (Activity) context;
this.arrayList = arrayList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.homegrid, viewGroup, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {
HomeData homeData = arrayList.get(i);
myViewHolder.imageView.setImageResource(homeData.getImage());
myViewHolder.textView.setText(homeData.getTitle());
myViewHolder.main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i == 0) {
context.startActivity(new Intent(context, FullscreenActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (i == 1) {
context.startActivity(new Intent(context, OrderStatusActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (i == 2) {
context.startActivity(new Intent(context, MyProfileActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (i == 5) {
context.startActivity(new Intent(context, SavedAddressActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (i==4)
{
context.startActivity(new Intent(context, HistoryActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
if(i==3)
{
context.startActivity(new Intent(context, MeebuWalletActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
if (i == 6) {
context.startActivity(new Intent(context, CustomerCareActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}if (i == 7) {
context.startActivity(new Intent(context, RewardsActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (i == 8) {
context.startActivity(new Intent(context, InviteFriendsActivity.class));
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
});
}
@Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
ImageView imageView;
TextView textView;
RelativeLayout main;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
textView = itemView.findViewById(R.id.title);
main = itemView.findViewById(R.id.main);
}
}
}
|
package project.graphic;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import project.interfaces.Selectable;
import project.object.Ordinatore;
import project.object.Selezionatore;
import project.strutture.Edificio;
public class SelectFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private ArrayList<Edificio> collezioneLotti = new ArrayList<>();
private ArrayList<Edificio> risultato = new ArrayList<>();
private JTextField text;
private JRadioButton sel1;
private JRadioButton sel2;
private JRadioButton sel3;
private JRadioButton sort1;
private JRadioButton sort2;
private JRadioButton sort3;
private JTextArea areaText;
private ArrayList<Selectable<Edificio>> mM;
private ArrayList<Comparator<Edificio>> oO;
public SelectFrame(ArrayList<Edificio> cUrbano) {
JPanel panelGeneral = new JPanel();
panelGeneral.setLayout(new GridLayout(3, 1));
panelGeneral.add(selectorPanel());
panelGeneral.add(sorterPanel());
panelGeneral.add(areaResult());
add(panelGeneral);
add(stampaRicerca(), BorderLayout.SOUTH);
collezioneLotti = cUrbano;
creaArrayComparator();
creaArraySelectable();
}
public JPanel selectorPanel() {
JPanel selectPanel = new JPanel();
text = new JTextField(10);
selectPanel.setLayout(new GridLayout(5, 1));
selectPanel.setBorder(new TitledBorder(new EtchedBorder(), "Metodo di Selezione"));
sel1 = new JRadioButton("Valore Superiore a");
sel2 = new JRadioButton("Efficienza Superiore a");
sel3 = new JRadioButton("Danneggiamento Ricevuto Superiore a");
sel1.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(sel1);
group.add(sel2);
group.add(sel3);
selectPanel.add(sel1);
selectPanel.add(sel2);
selectPanel.add(sel3);
selectPanel.add(text);
selectPanel.add(selezionaButton());
return selectPanel;
}
public JPanel sorterPanel() {
JPanel sortPanel = new JPanel();
sortPanel.setBorder(new TitledBorder(new EtchedBorder(), "Metodo di Ordinamento"));
sortPanel.setLayout(new GridLayout(4, 1));
sort1 = new JRadioButton("Coeff Efficienza");
sort2 = new JRadioButton("Coeff Invecchiamento");
sort3 = new JRadioButton("Valore");
ButtonGroup group = new ButtonGroup();
group.add(sort1);
group.add(sort2);
group.add(sort3);
sortPanel.add(sort1);
sortPanel.add(sort2);
sortPanel.add(sort3);
sort1.setSelected(true);
sortPanel.add(sortButton());
return sortPanel;
}
public JPanel areaResult() {
JPanel textPanel = new JPanel();
textPanel.setBorder(new TitledBorder(new EtchedBorder(), "Risultato Ricerca"));
areaText = new JTextArea(6, 35);
JScrollPane scroll = new JScrollPane(areaText);
textPanel.add(scroll);
return textPanel;
}
public JButton stampaRicerca() {
JButton stampaButton = new JButton("Stampa Ricerca");
stampaButton.addActionListener((y)->{
areaText.setText("");
for(int i = 0; i < risultato.size(); i++) {
areaText.append(risultato.get(i).toString() + "\n");
}
});
return stampaButton;
}
private JButton selezionaButton() {
JButton sel = new JButton("Seleziona");
sel.addActionListener((z)->{
risultato.clear();
int intro = 0;
if(sel1.isSelected()) {
intro = 0;
}
if(sel2.isSelected()) {
intro = 1;
}
if(sel3.isSelected()) {
intro = 2;
}
for(int i = 0; i < collezioneLotti.size(); i++) {
if(mM.get(intro).seleziona(collezioneLotti.get(i), Integer.parseInt(text.getText())))
risultato.add(collezioneLotti.get(i));
}
});
return sel;
}
private JButton sortButton() {
JButton sort = new JButton("Ordina");
sort.addActionListener((z)->{
int index = 0;
if(sort1.isSelected()) {
index = 0;
}
if(sort2.isSelected()) {
index = 1;
}
if(sort3.isSelected()) {
index = 2;
}
Collections.sort(risultato, oO.get(index));;
});
return sort;
}
public void creaArrayComparator() {
oO = new ArrayList<>();
oO.add(new Ordinatore.OrdinatoreCoeffEfficienza());
oO.add(new Ordinatore.OrdinatoreCoeffInvecchiamento());
oO.add(new Ordinatore.OrdinatoreValore());
}
public void creaArraySelectable() {
mM = new ArrayList<>();
mM.add(new Selezionatore.SelezionatoreValore());
mM.add(new Selezionatore.SelezionatoreEfficienza());
mM.add(new Selezionatore.SelezionatoreDanneggiamento());
}
}
|
package fr.lteconsulting;
public class Client
{
private String nom;
private Compte compte;
public Client( String nom, Compte compte )
{
this.nom = nom;
this.compte = compte;
}
public String getNom()
{
return nom;
}
public Compte getCompte()
{
return compte;
}
public void afficher()
{
System.out.println( "Client '" + nom + "'" );
compte.afficher();
}
}
|
package script.memodb.data;
import java.io.IOException;
interface MMFileSerializable {
void resurrect(MemoryMappedFile memoFile, int offset) throws IOException;
void persistent(MemoryMappedFile memoFile, int offset) throws IOException;
}
|
package enumeracije;
public enum TipVozila {
AUTO,
KOMBI
}
|
package com.tencent.mm.pluginsdk.model.app;
import android.os.Looper;
import android.os.Message;
import com.tencent.mm.plugin.ac.a;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
class e$2 extends ag {
final /* synthetic */ e qzD;
e$2(e eVar, Looper looper) {
this.qzD = eVar;
super(looper);
}
public final void handleMessage(Message message) {
v vVar = (v) message.obj;
r rVar = new r(vVar.appId, vVar.efG);
if (this.qzD.qzB.contains(rVar)) {
this.qzD.qzB.remove(rVar);
if (!a.bmf().e(vVar.appId, vVar.data, vVar.efG)) {
x.e("MicroMsg.AppIconService", "handleMessage, saveIcon fail");
}
}
while (this.qzD.mTQ.size() > 0) {
r rVar2 = (r) this.qzD.mTQ.remove(0);
if (this.qzD.a(rVar2)) {
this.qzD.qzB.add(rVar2);
return;
}
}
}
}
|
public class Cordinate {
private int y;
private int x;
public Cordinate(int givenY, int givenX) {
this.y = givenY;
this.x = givenX;
}
//palauttaa koordinaatin y (rivi)
public int getY() {
return y;
}
//palauttaa koordinaatin x (sarake)
public int getX() {
return x;
}
}
|
package com.tencent.mm.ui.base;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class CustomScrollView extends ScrollView {
private a tso;
public CustomScrollView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public CustomScrollView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
}
public void setOnScrollChangeListener(a aVar) {
this.tso = aVar;
}
protected void onScrollChanged(int i, int i2, int i3, int i4) {
super.onScrollChanged(i, i2, i3, i4);
if (this.tso != null) {
this.tso.a(this, i2, i4);
}
}
}
|
package com.mytravels.flights.service.impl;
import com.mytravels.flights.domain.vo.CountryListVO;
import com.mytravels.flights.domain.vo.CountryVO;
import com.mytravels.flights.service.SkyScannerService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class SkyScannerServiceImpl implements SkyScannerService {
private final RestTemplate skyScannerRestTemplate;
@Override
public List<CountryVO> getCountries() {
ResponseEntity<CountryListVO> countryResponse = skyScannerRestTemplate.getForEntity(COUNTRIES_URI, CountryListVO.class);
return Optional.ofNullable(countryResponse.getBody())
.map(CountryListVO::getCountries)
.orElse(Collections.emptyList());
}
}
|
package funcionarios;
public class teste {
public static void main(String[] args) {
Gerente vander = new Gerente();
vander.setNome("Vander Lima de Andrade");
vander.setSenha(1919);
vander.setSalario(1000);
ControleDeBonus controle = new ControleDeBonus();
controle.registra(vander);
// System.out.println(vander.getNome());
// System.out.println(vander.getBonus());
Gerente f1 = new Gerente();
f1.setSalario(5000.0);
controle.registra(f1);
Funcionario f2 = new Gerente();
f2.setSalario(1000.0);
controle.registra(f2);
System.out.println(controle.getTotalDeBonificacoes());
}
}
|
package cqu.shy.data;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import javax.imageio.ImageIO;
public class ImagePacket implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public BufferedImage img;
public ImagePacket(BufferedImage img){
this.img = img;
}
public ByteArrayOutputStream getByteOutputStream() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// 将img对象写入输出流
ImageIO.write(img, "png", out);
} catch (Exception ex) {
ex.printStackTrace();
}
return out;
}
}
|
package reversi.view;
import javafx.fxml.FXML;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class ErrorController {
private Stage stage;
public ErrorController() {
}
public Stage getStage() {
return this.stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
@FXML
private Text text;
public void setText(String uzenet) {
text.setText(uzenet);
}
@FXML
private void handleOk() {
stage.close();
}
}
|
package com.tencent.mm.plugin.fts.ui.widget;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tencent.mm.ak.a.a.c.a;
import com.tencent.mm.ak.o;
import com.tencent.mm.plugin.appbrand.n.g;
import com.tencent.mm.plugin.appbrand.n.g.b;
import com.tencent.mm.plugin.appbrand.n.g.c;
import com.tencent.mm.plugin.fts.ui.m;
import com.tencent.mm.plugin.fts.ui.n;
import com.tencent.mm.plugin.fts.ui.n.d;
import com.tencent.mm.plugin.fts.ui.n.e;
import com.tencent.mm.plugin.fts.ui.n.f;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.websearch.api.r;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.w;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONArray;
import org.json.JSONObject;
public class FTSMainUIEducationLayout extends LinearLayout {
public float fto;
public float ftp;
public float gcx = ((float) ViewConfiguration.get(getContext()).getScaledTouchSlop());
public OnClickListener jxn;
public List<LinearLayout> jzM;
public Map<Integer, TextView> jzN = new HashMap();
private String jzO = "";
public long jzP;
private boolean jzQ = true;
public TextView jzR;
protected boolean jzS = true;
private boolean jzT;
public OnClickListener jzU;
private OnClickListener jzV;
public FTSMainUIEducationLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
initView();
}
public FTSMainUIEducationLayout(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
initView();
}
private void initView() {
setOrientation(1);
this.jzM = new ArrayList();
}
public void setNeedHotWord(boolean z) {
this.jzS = z;
}
public final void aL() {
LinearLayout linearLayout;
aQZ();
try {
if (!K(r.PX("educationTab"))) {
aRa();
}
} catch (Exception e) {
aRa();
}
try {
if (this.jzS) {
CharSequence optString = r.PX("educationHotword").optJSONArray("items").optJSONObject(0).optString("hotword");
if (!bi.oW(optString)) {
linearLayout = (LinearLayout) inflate(getContext(), e.fts_main_ui_education_hotword_layout, null);
((TextView) linearLayout.findViewById(d.hotword_tv)).setText(optString);
linearLayout.setOnClickListener(this.jzU);
linearLayout.setTag(optString);
addView(linearLayout);
this.jzM.add(linearLayout);
}
}
} catch (Exception e2) {
}
if (this.jzT) {
b adj = ((g) com.tencent.mm.kernel.g.l(g.class)).adj();
if (adj.dEw != null && adj.dEw.size() > 0) {
linearLayout = (LinearLayout) inflate(getContext(), e.fts_main_ui_education_wxapp_layout, null);
((TextView) linearLayout.findViewById(d.title_tv)).setText(adj.bSc);
ImageView[] imageViewArr = new ImageView[]{(ImageView) linearLayout.findViewById(d.app1_iv), (ImageView) linearLayout.findViewById(d.app2_iv), (ImageView) linearLayout.findViewById(d.app3_iv), (ImageView) linearLayout.findViewById(d.app4_iv)};
ImageView imageView = (ImageView) linearLayout.findViewById(d.more_iv);
int i = 0;
while (i < adj.dEw.size() && i < 4) {
c cVar = (c) adj.dEw.get(i);
a aVar = new a();
aVar.dXN = f.default_avatar;
aVar.dXW = true;
o.Pj().a(cVar.fmD, imageViewArr[i], aVar.Pt());
imageViewArr[i].setVisibility(0);
imageViewArr[i].setTag(cVar);
if (this.jzV != null) {
imageViewArr[i].setOnClickListener(this.jzV);
}
i++;
}
if (adj.dEw.size() > 0) {
imageView.setVisibility(0);
imageView.setTag("more-click");
imageView.setOnClickListener(this.jzV);
}
addView(linearLayout);
this.jzM.add(linearLayout);
String str = "";
Iterator it = adj.dEw.iterator();
while (true) {
String str2 = str;
if (it.hasNext()) {
str = str2 + ((c) it.next()).username + ";";
} else {
h.mEJ.h(14630, new Object[]{com.tencent.mm.plugin.fts.a.e.jqM, adj.bSc, str2, Integer.valueOf(adj.gsQ), Long.valueOf(System.currentTimeMillis() / 1000)});
return;
}
}
}
}
}
public void setNeedWXAPP(boolean z) {
this.jzT = z;
}
public final void J(JSONObject jSONObject) {
aQZ();
try {
if (!K(jSONObject)) {
aRa();
}
} catch (Exception e) {
aRa();
}
}
private void aQZ() {
for (LinearLayout removeView : this.jzM) {
removeView(removeView);
}
this.jzM.clear();
this.jzN.clear();
this.jzO = "";
}
public boolean K(JSONObject jSONObject) {
if (jSONObject == null) {
return false;
}
jSONObject.optString("title");
JSONArray optJSONArray = jSONObject.optJSONArray("items");
if (optJSONArray == null) {
return false;
}
int ad;
if (w.fD(ad.getContext()).equalsIgnoreCase("en")) {
ad = com.tencent.mm.bp.a.ad(getContext(), n.b.BigerMoreTextSize);
} else {
ad = com.tencent.mm.bp.a.ad(getContext(), n.b.NormalTextSize);
}
Object obj = null;
Object obj2 = null;
String str = null;
String str2 = null;
for (int i = 0; i < Math.min(optJSONArray.length(), 9); i++) {
JSONObject optJSONObject = optJSONArray.optJSONObject(i);
if (i % 3 == 0) {
str2 = optJSONObject.optString("hotword");
obj2 = optJSONObject;
} else if (i % 3 == 1) {
str = optJSONObject.optString("hotword");
JSONObject obj3 = optJSONObject;
} else {
a(str2, obj2, str, obj3, optJSONObject.optString("hotword"), optJSONObject, ad);
obj3 = null;
obj2 = null;
str = null;
str2 = null;
}
}
if (!(str2 == null || obj2 == null)) {
a(str2, obj2, str, obj3, null, null, ad);
}
return true;
}
private void aRa() {
a(getContext().getString(n.g.search_education_timeline), null, getContext().getString(n.g.search_education_article), null, getContext().getString(n.g.search_education_biz_contact), null, com.tencent.mm.bp.a.ad(getContext(), n.b.NormalTextSize));
aRb();
}
public void aRb() {
}
public final void a(String str, Object obj, String str2, Object obj2, String str3, Object obj3, int i) {
x.i("MicroMsg.FTS.FTSMainUIEducationLayout", "addCellLayout %s %s %s", new Object[]{str, str2, str3});
if (!bi.oW(str)) {
LinearLayout linearLayout = (LinearLayout) inflate(getContext(), e.fts_main_ui_education_cell_layout, null);
TextView textView = (TextView) linearLayout.findViewById(d.textview_1);
textView.setText(str);
textView.setTag(obj);
textView.setVisibility(0);
textView.setOnClickListener(this.jxn);
textView.setClickable(this.jzQ);
this.jzN.put(Integer.valueOf(m.a((JSONObject) obj, str, getContext())), textView);
bA(obj);
if (!bi.oW(str2)) {
textView = (TextView) linearLayout.findViewById(d.textview_2);
textView.setText(str2);
textView.setTag(obj2);
textView.setVisibility(0);
textView.setOnClickListener(this.jxn);
textView.setClickable(this.jzQ);
View findViewById = linearLayout.findViewById(d.divider_1);
findViewById.getLayoutParams().height = i;
findViewById.setVisibility(0);
this.jzN.put(Integer.valueOf(m.a((JSONObject) obj2, str2, getContext())), textView);
bA(obj2);
if (!bi.oW(str3)) {
textView = (TextView) linearLayout.findViewById(d.textview_3);
textView.setText(str3);
textView.setTag(obj3);
textView.setVisibility(0);
textView.setOnClickListener(this.jxn);
textView.setClickable(this.jzQ);
findViewById = linearLayout.findViewById(d.divider_2);
findViewById.getLayoutParams().height = i;
findViewById.setVisibility(0);
this.jzN.put(Integer.valueOf(m.a((JSONObject) obj3, str3, getContext())), textView);
bA(obj3);
}
}
this.jzM.add(linearLayout);
addView(linearLayout);
}
}
private void bA(Object obj) {
if (obj != null && (obj instanceof JSONObject)) {
String optString = ((JSONObject) obj).optString("businessType");
if (!bi.oW(optString)) {
this.jzO = this.jzO == null ? "" : this.jzO;
if (this.jzO.length() > 0) {
this.jzO += "|";
}
this.jzO += optString;
}
}
}
public String getVertBizTypes() {
return this.jzO == null ? "" : this.jzO;
}
public void setOnCellClickListener(OnClickListener onClickListener) {
this.jxn = onClickListener;
}
public void setOnHotwordClickListener(OnClickListener onClickListener) {
this.jzU = onClickListener;
}
public void setOnWxAppClickListener(OnClickListener onClickListener) {
this.jzV = onClickListener;
}
public void setSelected(int i) {
for (Entry entry : this.jzN.entrySet()) {
if (((Integer) entry.getKey()).intValue() == i) {
((TextView) entry.getValue()).setTextColor(Color.parseColor("#B5B5B5"));
} else {
((TextView) entry.getValue()).setTextColor(Color.parseColor("#45C01A"));
}
}
}
public void setCellClickable(boolean z) {
this.jzQ = z;
}
}
|
package com.example.android.sunshine.app;
import android.content.Context;
import android.graphics.Canvas;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import java.util.jar.Attributes;
/**
* Created by Ody on 08-Nov-15.
*/
public class CustomView extends View {
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defaultStyle) {
super(context, attrs, defaultStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.aws.s3.core;
/**
* The Core interface for performing various operations on Amazon S3 like listing objects
* in the bucket, get an object, put an object and remove an object
*
* @author Amol Nayak
*
* @since 0.5
*
*/
public interface AmazonS3Operations {
public static final String CONTENT_MD5_HEADER = "Content-MD5";
/**
* Lists Objects in the given bucket and given folder. Provide / if you
* wish to list objects at the root of the bucket
*
* @param bucketName
* @param folder
* @param nextMarker
* @param pageSize
* @return the {@link PaginatedObjectsView} of the matching result
*/
PaginatedObjectsView listObjects(String bucketName,String folder,String nextMarker,int pageSize);
/**
* Put the given {@link AmazonS3Object} in the provided bucket in the folder specified with the name given
* The object if exists, will be overwritten and the folder path hierarchy
* if absent will be created
*
* @param bucketName
* @param folder
* @param objectName
* @param s3Object
*/
void putObject(String bucketName,String folder,String objectName,AmazonS3Object s3Object);
/**
* Gets the Object from Amazon S3 from the specified bucket,folder and with
* the given objectName
*
* @param bucketName
* @param folder
* @param objectName
* @return The S3 object corresponding to the given details. Null if no object found
*/
AmazonS3Object getObject(String bucketName,String folder,String objectName);
/**
* Removes the specified object from the bucket given, folder specified
* and the given object name from S3
* @param bucketName
* @param folder
* @param objectName
* @return true if the object was successfully removed else false
*/
boolean removeObject(String bucketName,String folder,String objectName);
}
|
package com.goldgov.gtiles.module.organization.service;
import java.util.List;
import com.goldgov.gtiles.core.service.Query;
public class OrganizationQuery extends Query<Organization> {
private String searchOrganizationName;
private String searchOrganizationID;
private String searchParentID;
private String searchRoleId;//角色ID
private String searchDataPath;
private String searchPartyOrganizationID;
private List<String> searchTreepaths;
private String searchOrganizationIds;
private String[] searchOrgIDs;
private Integer isAll;
public Integer getIsAll() {
return isAll;
}
public void setIsAll(Integer isAll) {
this.isAll = isAll;
}
public List<String> getSearchTreepaths() {
return searchTreepaths;
}
public void setSearchTreepaths(List<String> searchTreepaths) {
this.searchTreepaths = searchTreepaths;
}
public String getSearchPartyOrganizationID() {
return searchPartyOrganizationID;
}
public void setSearchPartyOrganizationID(String searchPartyOrganizationID) {
this.searchPartyOrganizationID = searchPartyOrganizationID;
}
public String getSearchOrganizationIds() {
return searchOrganizationIds;
}
public void setSearchOrganizationIds(String searchOrganizationIds) {
this.searchOrganizationIds = searchOrganizationIds;
}
public String getSearchRoleId() {
return searchRoleId;
}
public void setSearchRoleId(String searchRoleId) {
this.searchRoleId = searchRoleId;
}
public String getSearchOrganizationName() {
return searchOrganizationName;
}
public void setSearchOrganizationName(String searchOrganizationName) {
this.searchOrganizationName = searchOrganizationName;
}
public String getSearchOrganizationID() {
return searchOrganizationID;
}
public void setSearchOrganizationID(String searchOrganizationID) {
this.searchOrganizationID = searchOrganizationID;
}
public String getSearchParentID() {
return searchParentID;
}
public void setSearchParentID(String searchParentID) {
this.searchParentID = searchParentID;
}
public String[] getSearchOrgIDs() {
return searchOrgIDs;
}
public void setSearchOrgIDs(String[] searchOrgIDs) {
this.searchOrgIDs = searchOrgIDs;
}
public String getSearchDataPath() {
return searchDataPath;
}
public void setSearchDataPath(String searchDataPath) {
this.searchDataPath = searchDataPath;
}
}
|
import java.util.*;
class Main{
static class Doc{
int index;
int num;
Doc(int index, int num){
this.index = index;
this.num = num;
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int[] answer = new int[T];
for(int t=0;t<T;t++){
int N = sc.nextInt();
int M = sc.nextInt();
int[] max = new int[N];
ArrayList<Doc> q = new ArrayList<>();
for(int i=0;i<N;i++){
int n = sc.nextInt();
max[i]=n;
q.add(new Doc(i,n));
}
Arrays.sort(max);
int count = 1;
int index =N-1;
Loop1: while(!q.isEmpty()){
Doc d = q.get(0);
if(d.num<max[index]){
q.remove(0);
q.add(d);
continue Loop1;
}
if(d.num==max[index]){
index--;
}
if(d.index==M){
break Loop1;
}
count++;
q.remove(0);
}
answer[t] = count;
}
for(int i=0;i<T;i++){
System.out.println(answer[i]);
}
}
}
|
package io.github.btj.junitverboseprovider;
import java.util.Objects;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
class TestRun {
final String test;
int runningTime;
TestRun(String test) {
this.test = test;
}
}
public class JUnitVerboseProvider implements TestExecutionListener {
private TestRun run;
private synchronized void setCurrentRun(TestRun run) {
timerThread.interrupt();
this.run = run;
}
private synchronized TestRun getCurrentRun() {
Thread.interrupted(); // Clear interrupted flag
return run;
}
private synchronized void testRanForFiveSeconds(TestRun run) {
if (this.run != null && this.run == run) {
run.runningTime += 5;
System.out.println("Test " + run.test + " has been running for " + run.runningTime + " seconds");
}
}
private Thread timerThread = new Thread() {
public void run() {
for (;;) {
try {
TestRun run = getCurrentRun();
if (run == null)
Thread.sleep(Integer.MAX_VALUE);
else {
Thread.sleep(5000);
testRanForFiveSeconds(run);
}
} catch (InterruptedException e) {}
}
}
};
{
timerThread.setDaemon(true);
timerThread.start();
}
@Override
public void executionStarted(TestIdentifier testIdentifier) {
if (testIdentifier.isTest()) {
String test = testIdentifier.getUniqueId();
setCurrentRun(new TestRun(test));
}
}
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
setCurrentRun(null);
}
}
|
/*
* Copyright 2005-2010 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 sdloader.javaee.impl;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionContext;
import javax.servlet.http.HttpSessionEvent;
import sdloader.javaee.InternalWebApplication;
import sdloader.javaee.ListenerEventDispatcher;
import sdloader.log.SDLoaderLog;
import sdloader.log.SDLoaderLogFactory;
import sdloader.util.CollectionsUtil;
import sdloader.util.IteratorEnumeration;
/**
* HttpSession実装クラス
*
* @author c9katayama
*/
@SuppressWarnings("deprecation")
public class HttpSessionImpl implements HttpSession {
private static SDLoaderLog log = SDLoaderLogFactory
.getLog(HttpSessionImpl.class);
private String id;
private long creationTime;
private long lastAccessedTime;
private int maxInactiveInterval;
private Map<String, Object> attributeMap = CollectionsUtil.newHashMap();
private boolean invalidate = false;
private boolean isNew = true;
private InternalWebApplication internalWebApplication;
public HttpSessionImpl(InternalWebApplication webApp, String sessionId) {
this.id = sessionId;
this.creationTime = System.currentTimeMillis();
this.internalWebApplication = webApp;
dispatchCreateEvent();
}
public long getCreationTime() {
checkInvalidate();
return creationTime;
}
public String getId() {
checkInvalidate();
return id;
}
public long getLastAccessedTime() {
checkInvalidate();
return lastAccessedTime;
}
public ServletContext getServletContext() {
checkInvalidate();
return internalWebApplication.getServletContext();
}
public void setMaxInactiveInterval(int interval) {
checkInvalidate();
this.maxInactiveInterval = interval;
}
public int getMaxInactiveInterval() {
checkInvalidate();
return maxInactiveInterval;
}
public HttpSessionContext getSessionContext() {
throw new RuntimeException("getSessionConetxt not implemented");
}
public Object getAttribute(String key) {
checkInvalidate();
return attributeMap.get(key);
}
public Object getValue(String key) {
checkInvalidate();
return getAttribute(key);
}
public Enumeration<String> getAttributeNames() {
checkInvalidate();
return new IteratorEnumeration<String>(
attributeMap.keySet().iterator(), true);
}
public String[] getValueNames() {
checkInvalidate();
return attributeMap.keySet().toArray(new String[] {});
}
public void setAttribute(String key, Object value) {
checkInvalidate();
if (key == null) {
throw new IllegalArgumentException("Session attribute key is null.");
}
if (value == null) {
removeAttribute(key);
} else {
Object oldValue = attributeMap.get(key);
if (value == oldValue) {
return;
}
if (value instanceof HttpSessionBindingListener) {
HttpSessionBindingEvent boundEvent = new HttpSessionBindingEvent(
this, key, value);
try {
((HttpSessionBindingListener) value).valueBound(boundEvent);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
this.attributeMap.put(key, value);
ListenerEventDispatcher dispatcher = internalWebApplication
.getListenerEventDispatcher();
if (oldValue == null) {
HttpSessionBindingEvent event = new HttpSessionBindingEvent(
this, key, value);
dispatcher
.dispatchHttpSessionAttributeListener_attributeAdded(event);
} else {
if (oldValue instanceof HttpSessionBindingListener) {
HttpSessionBindingEvent unBoundEvent = new HttpSessionBindingEvent(
this, key, oldValue);
try {
((HttpSessionBindingListener) oldValue)
.valueUnbound(unBoundEvent);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
HttpSessionBindingEvent event = new HttpSessionBindingEvent(
this, key, oldValue);
dispatcher
.dispatchHttpSessionAttributeListener_attributeReplaced(event);
}
}
}
public void putValue(String key, Object value) {
checkInvalidate();
setAttribute(key, value);
}
public void removeAttribute(String key) {
checkInvalidate();
Object oldValue = attributeMap.remove(key);
if (oldValue != null) {
HttpSessionBindingEvent event = new HttpSessionBindingEvent(this,
key, oldValue);
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue).valueUnbound(event);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
ListenerEventDispatcher dispatcher = internalWebApplication
.getListenerEventDispatcher();
dispatcher
.dispatchHttpSessionAttributeListener_attributeRemoved(event);
}
}
public void removeValue(String key) {
checkInvalidate();
removeAttribute(key);
}
public void invalidate() {
if (!invalidate) {
dispatchDestroyEvent();
this.invalidate = true;
internalWebApplication = null;
attributeMap.clear();
attributeMap = null;
}
}
public boolean isNew() {
return isNew;
}
// /non interface method
protected void dispatchCreateEvent() {
if (internalWebApplication == null) {
return;
}
HttpSessionEvent event = new HttpSessionEvent(this);
ListenerEventDispatcher dispatcher = internalWebApplication
.getListenerEventDispatcher();
dispatcher.dispatchHttpSessionListener_sessionCreated(event);
}
protected void dispatchDestroyEvent() {
if (internalWebApplication == null) {
return;
}
HttpSessionEvent event = new HttpSessionEvent(this);
ListenerEventDispatcher dispatcher = internalWebApplication
.getListenerEventDispatcher();
dispatcher.dispatchHttpSessionListener_sessionDestroyed(event);
}
public void setLastAccessedTime(long lastAccessedTime) {
this.lastAccessedTime = lastAccessedTime;
}
public boolean isInvalidate() {
return invalidate;
}
private void checkInvalidate() {
if (invalidate) {// 使用不可能
throw new IllegalStateException("Session invalidated.");
}
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
}
|
package br.com.packapps.aidlclientcalculator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import br.com.packapps.aidlservercalculator.IMyAidlInterface;
public class MainActivity extends AppCompatActivity {
IMyAidlInterface aidlInterface;
private TextView tvResultCalculate;
private ServiceConnection serviceConnection;
private EditText etNumber1;
private EditText etNumber2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tvResultCalculate = (TextView) findViewById(R.id.tvResultCalculate);
etNumber1 = (EditText) findViewById(R.id.etNumber1);
etNumber2 = (EditText) findViewById(R.id.etNumber2);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
double number1 = Double.parseDouble(etNumber1.getText().toString());
double number2 = Double.parseDouble(etNumber2.getText().toString());
double result = aidlInterface.soma(number1, number2);
tvResultCalculate.setText("" + result);
}catch (Exception e){
Log.e("TAG", "error: "+ e.getMessage());
}
}
});
//Service Connection for comunication App Server
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("TAG", "onServiceConnected");
aidlInterface = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i("TAG", "onServiceDisconnected");
aidlInterface = null;
}
};
//Intent initialize service
Intent intent = new Intent("br.com.packapps.aidlservercalculator.CALCULATE");
intent.setPackage("br.com.packapps.aidlservercalculator");
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
}
}
|
package com.tencent.mm.plugin.emoji.ui.v2;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.R;
class EmojiStoreV2SingleProductDialogUI$3 implements OnClickListener {
final /* synthetic */ EmojiStoreV2SingleProductDialogUI iqU;
EmojiStoreV2SingleProductDialogUI$3(EmojiStoreV2SingleProductDialogUI emojiStoreV2SingleProductDialogUI) {
this.iqU = emojiStoreV2SingleProductDialogUI;
}
public final void onClick(View view) {
this.iqU.setResult(0);
this.iqU.finish();
this.iqU.overridePendingTransition(R.a.pop_in, R.a.pop_out);
}
}
|
package com.example.rikvanbelle.drinksafe.models;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import java.io.Serializable;
/**
* Created by Rik Van Belle on 7/12/2017.
*/
@Entity
public class Contact implements Serializable{
@PrimaryKey(autoGenerate = true)
private int contactID;
@ColumnInfo(name="name")
private String name;
@ColumnInfo(name="number")
private String number;
public Contact(String name, String number) {
this.name = name;
this.number = number;
}
public int getContactID() {
return contactID;
}
public void setContactID(int contactID) {
this.contactID = contactID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
|
/* */ package de.stuuupiiid.dungeonpack;
/* */
/* */ import java.util.Random;
import net.minecraft.util.ResourceLocation;
/* */
/* */ public class DungeonGeneratorFort
/* */ extends DungeonGenerator
/* */ {
/* */ public boolean generate(Random random, int par1, int par2, int par3)
/* */ {
/* 10 */ for (int v1 = 0; v1 < 2 + random.nextInt(2); v1++) {
/* 11 */ generateFort(random, par1 + random.nextInt(24) - 12, par2, par3 + random.nextInt(24) - 12);
/* */ }
/* */
/* 14 */ return true;
/* */ }
/* */
/* */
/* */ public boolean generateFort(Random random, int par1, int par2, int par3)
/* */ {
/* 20 */ for (int v1 = -7; v1 < 11; v1++) {
/* 21 */ for (int v2 = -7; v2 < 11; v2++) {
/* 22 */ addAir(par1 + v1, getTop(par1 + v1, par3 + v2) - 1, par3 + v2);
/* 23 */ addAir(par1 + v1, getTop(par1 + v1, par3 + v2), par3 + v2);
/* 24 */ addAir(par1 + v1, getTop(par1 + v1, par3 + v2) + 1, par3 + v2);
/* 25 */ addAir(par1 + v1, getTop(par1 + v1, par3 + v2) + 2, par3 + v2);
/* 26 */ addAir(par1 + v1, getTop(par1 + v1, par3 + v2) + 3, par3 + v2);
/* 27 */ addAir(par1 + v1, getTop(par1 + v1, par3 + v2) + 4, par3 + v2);
/* 28 */ byte v3 = 0;
/* 29 */ if (random.nextInt(3) == 0) {
/* 30 */ v3 = 1;
/* */ }
/* */
/* 33 */ addBlockAndMetadata(par1 + v1, getTop(par1 + v1, par3 + v2) - 1, par3 + v2, 98, v3);
/* 34 */ addBlockAndMetadata(par1 + v1, getTop(par1 + v1, par3 + v2) - 2, par3 + v2, 98, v3);
/* 35 */ addBlockAndMetadata(par1 + v1, getTop(par1 + v1, par3 + v2) - 3, par3 + v2, 98, v3);
/* 36 */ addBlockAndMetadata(par1 + v1, getTop(par1 + v1, par3 + v2) - 4, par3 + v2, 98, v3);
/* 37 */ addBlockAndMetadata(par1 + v1, getTop(par1 + v1, par3 + v2) - 5, par3 + v2, 98, v3);
/* */ }
/* */ }
/* */
/* 41 */ for (int v1 = -7; v1 < 8; v1++) {
/* 42 */ generateWallPartX(random, par1 + 9, getTop(par1 + 9, par3 + v1) - 6, par3 + v1);
/* 43 */ generateWallPartX(random, par1 - 9, getTop(par1 - 9, par3 + v1) - 6, par3 + v1);
/* 44 */ generateWallPartZ(random, par1 + v1, getTop(par1 + v1, par3 + 9) - 6, par3 + 9);
/* 45 */ generateWallPartZ(random, par1 + v1, getTop(par1 + v1, par3 - 9) - 6, par3 - 9);
/* */ }
/* */
/* 48 */ generateTower(random, par1 + 9, getTop(par1 + 9, par3 + 9) - 6, par3 + 9);
/* 49 */ generateTower(random, par1 - 9, getTop(par1 - 9, par3 + 9) - 6, par3 + 9);
/* 50 */ generateTower(random, par1 + 9, getTop(par1 + 9, par3 - 9) - 6, par3 - 9);
/* 51 */ generateTower(random, par1 - 9, getTop(par1 - 9, par3 - 9) - 6, par3 - 9);
/* */
/* */
/* 54 */ for (int v1 = 0; v1 < 1 + random.nextInt(3); v1++) {
/* 55 */ int v2 = random.nextInt(12) - 6;
/* 56 */ int var8 = random.nextInt(12) - 6;
/* 57 */ addMobSpawner(par1 + v2, getTop(par1 + v2, par3 + var8), par3 + var8, new ResourceLocation(getMob(random)));
/* */ }
/* */
/* 60 */ for (int v1 = 0; v1 < 1 + random.nextInt(4); v1++) {
/* 61 */ int v2 = random.nextInt(12) - 6;
/* 62 */ int var8 = random.nextInt(12) - 6;
/* 63 */ if (random.nextInt(3) == 0) {
/* 64 */ addChestWithDefaultLoot(random, par1 + v2, getTop(par1 + v2, par3 + var8), par3 + var8);
/* */ }
/* */ }
/* */
/* 68 */ return true;
/* */ }
/* */
/* */
/* */ public boolean generateWallPartX(Random random, int par1, int par2, int par3)
/* */ {
/* 74 */ for (int v1 = -6; v1 < 11; v1++) {
/* 75 */ byte id = 0;
/* 76 */ if (random.nextInt(3) == 0) {
/* 77 */ id = 1;
/* */ }
/* */
/* 80 */ addBlockAndMetadata(par1, par2 + v1, par3, 98, id);
/* */ }
/* */
/* 83 */ for (int v1 = -6; v1 < 12; v1++) {
/* 84 */ byte id = 0;
/* 85 */ if (random.nextInt(3) == 0) {
/* 86 */ id = 1;
/* */ }
/* */
/* 89 */ addBlockAndMetadata(par1 + 1, par2 + v1, par3, 98, id);
/* 90 */ addBlockAndMetadata(par1 - 1, par2 + v1, par3, 98, id);
/* */ }
/* */
/* 93 */ return true;
/* */ }
/* */
/* */
/* */ public boolean generateWallPartZ(Random random, int par1, int par2, int par3)
/* */ {
/* 99 */ for (int v1 = -6; v1 < 11; v1++) {
/* 100 */ byte id = 0;
/* 101 */ if (random.nextInt(3) == 0) {
/* 102 */ id = 1;
/* */ }
/* */
/* 105 */ addBlockAndMetadata(par1, par2 + v1, par3, 98, id);
/* */ }
/* */
/* 108 */ for (int v1 = -6; v1 < 12; v1++) {
/* 109 */ byte id = 0;
/* 110 */ if (random.nextInt(3) == 0) {
/* 111 */ id = 1;
/* */ }
/* */
/* 114 */ addBlockAndMetadata(par1, par2 + v1, par3 + 1, 98, id);
/* 115 */ addBlockAndMetadata(par1, par2 + v1, par3 - 1, 98, id);
/* */ }
/* */
/* 118 */ return true;
/* */ }
/* */
/* */ public boolean generateTower(Random random, int par1, int par2, int par3) {
/* 122 */ for (int v1 = -6; v1 < 16; v1++) {
/* 123 */ for (int v2 = -1; v2 < 2; v2++) {
/* 124 */ for (int v3 = -1; v3 < 2; v3++) {
/* 125 */ byte id = 0;
/* 126 */ if (random.nextInt(3) == 0) {
/* 127 */ id = 1;
/* */ }
/* */
/* 130 */ addBlockAndMetadata(par1 + v2, par2 + v1, par3 + v3, 98, id);
/* */ }
/* */ }
/* */ }
/* */
/* 135 */ addAir(par1, par2 + 14, par3);
/* 136 */ addAir(par1, par2 + 15, par3);
/* 137 */ addAir(par1 + 1, par2 + 15, par3);
/* 138 */ addAir(par1 - 1, par2 + 15, par3);
/* 139 */ addAir(par1, par2 + 15, par3 + 1);
/* 140 */ addAir(par1, par2 + 15, par3 - 1);
/* 141 */ return true;
/* */ }
/* */
/* */ private String getMob(Random random) {
/* 145 */ int var2 = random.nextInt(4);
/* 146 */ return var2 == 3 ? "Spider" : var2 == 2 ? "Zombie" : var2 == 1 ? "Zombie" : var2 == 0 ? "Skeleton" : "";
/* */ }
/* */ }
/* Location: C:\Users\IyadE\Desktop\Mod Porting Tools\dungeonpack-1.8.jar!\de\stuuupiiid\dungeonpack\DungeonGeneratorFort.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
package com.smxknife.java2.thread.scheduledexecutorservice.demo06;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author smxknife
* 2019/8/30
*/
public class _Run_cancel_has_task_in_queue {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
MyRunnable06 r1 = new MyRunnable06("R1");
ScheduledFuture<?> r1Future = executor.schedule(r1, 1, TimeUnit.SECONDS);
System.out.println(r1Future.cancel(true));
System.out.println();
executor.getQueue().stream().forEach(runnable -> {
System.out.println("队列 中: " + runnable);
});
System.out.println("end");
System.out.println("==================");
System.out.println("队列中输出了,说明,虽然执行了cancel,但是任务还是在队列中,也不会再执行");
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package latihan47.nilaimahasiswa;
/**
*
* @author Alfi Nurizkya
* Nama : Alfi Nurizkya
* NIM : 10119036
* Kelas : IF-1
* Deskripsi Program : Program Menghitung Nilai Mahasiswa
*/
public class Latihan47NilaiMahasiswa {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
NilaiMahasiswa nilai = new NilaiMahasiswa(75, 45,34);
double NA = nilai.hitungNA();
char Index = nilai.menentukanIndex(NA);
System.out.println("QUIZ = " + nilai.getQUIZ());
System.out.println("UTS = " + nilai.getUTS());
System.out.println("UAS = " + nilai.getUAS());
System.out.println("\nNIlai Akhir = " + NA);
System.out.println("\nIndex = " + Index);
System.out.println("Keterangan = " + nilai.hasilKeterangan(Index));
}
}
|
package jp.noxi.collection;
import javax.annotation.Nonnegative;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
public class RepeatCollectionTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testRepeat() throws Exception {
final Object object = new Object();
Iterable iterable = Linq.repeat(object, 10);
int count = 0;
for (Object value : iterable) {
assertThat(value, is(sameInstance(object)));
count++;
}
assertThat(count, is(10));
}
@Test
public void testRepeatAsEnumerable() throws Exception {
final Object object = new Object();
Enumerable<Object> enumerable = Linq.repeatAsEnumerable(object, 10);
enumerable = enumerable.where(new IndexPredicate<Object>() {
@Override
public boolean apply(@Nullable Object element, @Nonnegative int index) {
return index % 2 == 0;
}
});
int count = 0;
for (Object value : enumerable) {
assertThat(value, is(sameInstance(object)));
count++;
}
assertThat(count, is(5));
}
@Test
public void testRepeat_negativeCount() throws Exception {
thrown.expect(IllegalArgumentException.class);
Linq.repeat(new Object(), -1);
}
@Test
public void testRepeatAsEnumerable_negativeCount() throws Exception {
thrown.expect(IllegalArgumentException.class);
Linq.repeatAsEnumerable(new Object(), -1);
}
}
|
package com.bfchengnuo.security.core.properties;
import lombok.Data;
/**
* session 管理相关配置
*
* @author 冰封承諾Andy
* @date 2019-09-22
*/
@Data
public class SessionProperties {
/**
* 同一个用户在系统中的最大session数,默认1
*/
private int maximumSessions = 1;
/**
* 达到最大session时是否阻止新的登录请求,默认为false,不阻止,新的登录会将老的登录失效掉
*/
private boolean maxSessionsPreventsLogin;
/**
* session失效时跳转的地址
*/
private String sessionInvalidUrl = SecurityConstants.DEFAULT_SESSION_INVALID_URL;
}
|
package com.server.pool.handle;
import com.server.pool.util.RemoteUtil;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConnectionHandler extends ChannelDuplexHandler {
private Logger logger = LoggerFactory.getLogger(ConnectionHandler.class);
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
logger.info("[{}] register ", RemoteUtil.getHost(ctx.channel()));
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
logger.info("[{}] active ", RemoteUtil.getHost(ctx.channel()));
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
logger.info("[{}] in_active ", RemoteUtil.getHost(ctx.channel()));
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
super.channelUnregistered(ctx);
logger.info("[{}] un_register ", RemoteUtil.getHost(ctx.channel()));
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
super.close(ctx, promise);
logger.info("[{}] close ", RemoteUtil.getHost(ctx.channel()));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
logger.info("[{}] exception ", RemoteUtil.getHost(ctx.channel()), cause);
}
}
|
package com.days.moment.qna.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
@Configuration
@MapperScan(basePackages = "com.days.moment.qna.mapper")
@ComponentScan(basePackages = "com.days.moment.qna.service")
@Import(QnaAOPConfig.class)
public class QnaRootConfig {
}
|
package com.lyx.pattern.factory;
public class ChangChengCar implements ICar {
public void produce() {
System.out.println("生产长城轿车");
}
}
|
package controllers.rest;
import common.utils.UserUtils;
import model.common.JSONResponseWithId;
import model.domain.*;
import model.forms.GrupStocFormModel;
import model.forms.InventarFormModel;
import model.forms.StocFormModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import services.inventory.InventoryService;
import services.inventory.LocService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/app/secure/inventory")
public class InventoryRestController {
@Autowired
private InventoryService inventoryService;
@Autowired
private LocService locService;
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
binder.registerCustomEditor(long.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
if (text.trim().length() == 0) {
text = "0";
}
long ch = Long.parseLong(text);
setValue(ch);
}
});
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/getinventory", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<Stoc> getAllStockItems() {
List<Stoc> items;
if (UserUtils.isUserInRole("ROLE_ADMIN") || UserUtils.isUserInRole("ROLE_SUPERUSER")) {
items = inventoryService.findAllItems();
} else {
items = inventoryService.findItemsForUser();
}
return items;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/getcategories", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<CategorieStoc> getAllCategorii() {
return inventoryService.findAllCategorii();
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/gettypes/{idCategorieStoc}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<GrupStoc> getAllTipuriByCategorieStoc(@PathVariable Long idCategorieStoc) {
return inventoryService.findTipuriByCategorieStoc(idCategorieStoc);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/getplaces", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<Loc> getAllPlaces() {
return inventoryService.findAllLocuri();
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/getpersoane", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<Persoana> getAllPersoane() {
return inventoryService.findAllPersoane();
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/getstari", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<StareStoc> getAllStari() {
return inventoryService.findAllStari();
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/tranzactie/history/{idArticol}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<TranzactieStoc> getHistory(@PathVariable Long idArticol) {
return inventoryService.findAllTranzactiiForArticol(idArticol);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/tranzactie/{idArticol}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public TranzactieStoc getTranzactie(@PathVariable Long idArticol) {
return inventoryService.findLastTranzactieForArticol(idArticol);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/articol/{idArticol}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Stoc getArticol(@PathVariable Long idArticol) {
return inventoryService.findArticol(idArticol);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/articol-by-code/{codStoc}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Stoc getArticolByCode(@PathVariable String codStoc) {
return inventoryService.findArticolByCodStoc(codStoc);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/generatebarcode/{barcode}", method = RequestMethod.GET)
@ResponseBody
public String generateBarcode(@PathVariable String barcode) {
return inventoryService.generateBarcode(barcode);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_DOWNLOAD','ROLE_SUPERUSER')")
@RequestMapping(value = "/downloadbarcode/{barcode}", method = RequestMethod.GET)
@ResponseBody
public String barcodeDownload(@PathVariable String barcode, HttpServletResponse response) throws IOException, ServletException {
return inventoryService.downloadBarcode(barcode, response);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER', 'ROLE_INVENTAR')")
@RequestMapping(value = "/iesire", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public JSONResponseWithId iesire(@RequestBody InventarFormModel iesire) {
JSONResponseWithId response = new JSONResponseWithId();
try {
boolean success = inventoryService.iesire(iesire);
response.setId(1);
String articolarticole = iesire.getArticole().length == 1 ? "-a predat articolul" : "-au predat articolele";
response.setMessage("S" + articolarticole);
} catch (DataAccessException e) {
response.setId(-1);
response.setMessage("Eroare la iesire");
}
return response;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER', 'ROLE_INVENTAR')")
@RequestMapping(value = "/intrare", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public JSONResponseWithId intrare(@RequestBody InventarFormModel model) {
JSONResponseWithId response = new JSONResponseWithId();
try {
boolean success = inventoryService.intrare(model);
response.setId(1);
String articolarticole = model.getArticole().length == 1 ? "-a primit articolul" : "-au primit articolele";
response.setMessage("S" + articolarticole);
} catch (DataAccessException e) {
response.setId(-1);
response.setMessage("Eroare la intrare");
}
return response;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER')")
@RequestMapping(value = "/addstockitem", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public JSONResponseWithId addStoc(@RequestBody StocFormModel stoc) {
JSONResponseWithId response = new JSONResponseWithId();
try {
Stoc addedStoc = inventoryService.save(stoc);
response.setId(addedStoc.getIdStoc());
response.setMessage("S-a adăugat articolul: " + stoc.getNumeStoc());
} catch (DataAccessException e) {
response.setId(-1);
response.setMessage("Articolul nu s-a adăugat");
}
return response;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER')")
@RequestMapping(value = "/editstockitem", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public JSONResponseWithId editStoc(@RequestBody StocFormModel stoc) {
JSONResponseWithId response = new JSONResponseWithId();
try {
Stoc edited = inventoryService.edit(stoc);
response.setId(edited.getIdStoc());
response.setMessage("S-a editat articolul: " + stoc.getNumeStoc());
} catch (DataAccessException e) {
response.setId(-1);
response.setMessage("Articolul nu s-a editat");
}
return response;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER')")
@RequestMapping(value = "/addcategory", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public JSONResponseWithId addCategory(@RequestBody CategorieStoc categorieStoc) {
JSONResponseWithId response = new JSONResponseWithId();
try {
CategorieStoc categorie = inventoryService.saveCategorie(categorieStoc);
response.setId(categorie.getIdCategorieStoc());
response.setMessage("S-a adăugat categoria: " + categorieStoc.getNumeCategorie());
} catch (DataAccessException e) {
response.setId(-1);
response.setMessage("Categoria nu s-a adăugat");
}
return response;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER')")
@RequestMapping(value = "/addtype", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public JSONResponseWithId addType(@RequestBody GrupStocFormModel grupStoc) {
JSONResponseWithId response = new JSONResponseWithId();
try {
GrupStoc tip = inventoryService.saveGrup(grupStoc);
response.setId(tip.getIdGrupStoc());
response.setMessage("S-a adăugat tipul: " + grupStoc.getNumeGrup());
} catch (DataAccessException e) {
response.setId(-1);
response.setMessage("Tipul nu s-a adăugat");
}
return response;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER')")
@RequestMapping(value = "/addplace", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public JSONResponseWithId addPlace(@RequestBody Loc loc) {
JSONResponseWithId response = new JSONResponseWithId();
try {
Loc saveLoc = inventoryService.saveLoc(loc);
response.setId(saveLoc.getIdLoc());
response.setMessage("S-a adăugat locul: " + loc.getNumeLoc());
} catch (DataAccessException e) {
response.setId(-1);
response.setMessage("Locul nu s-a adăugat");
}
return response;
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_INVENTAR')")
@RequestMapping(value = "/loc/{idLoc}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Loc getLoc(@PathVariable Long idLoc) {
return locService.findById(idLoc);
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPERUSER')")
@RequestMapping(value = "/removestockitem/{idStoc}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public JSONResponseWithId removeStoc(@PathVariable Long idStoc) {
JSONResponseWithId response = new JSONResponseWithId();
try {
Stoc stoc = inventoryService.removeStoc(idStoc);
response.setId(stoc.getIdStoc());
response.setMessage("S-a șters articolul: " + stoc.getNumeStoc());
} catch (Exception e) {
response.setId(-1);
response.setMessage("Articolul nu s-a șters");
}
return response;
}
}
|
package com.classcheck.gen;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import com.classcheck.analyzer.source.CodeVisitor;
import com.classcheck.autosource.MyClass;
import com.classcheck.type.JudgementMockType;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class TestSkeltonCodeVisitor extends VoidVisitorAdapter<Void> {
//このクラスのテストコードに対応する学生のコード
private CodeVisitor codeVisitor;
//同様にこのクラスのスケルトンコード
private MyClass myClass;
private BidiMap<MyClass, CodeVisitor> tableMap;
private BidiMap<CodeVisitor, MyClass> inverseTableMap;
private Map<MyClass, Map<String, String>> fieldChangeMap;
private Map<MyClass, Map<String, String>> methodChangeMap;
private List<String> mockFinalParamsList;
private HashMap<String, String> mockMethodMap;
private Collection<CodeVisitor> codeCollection;
//スケルトンコードのフィールドに定義されている変数名と
//実際のコードのフィールドの変数名を結びつける
private HashMap<String, String> variableFieldNameMap;
//<ソースコードのフィールドの変数名,型>
private HashMap<String, MyClass> varTypeMap;
public TestSkeltonCodeVisitor(CodeVisitor codeVisitor,
Map<MyClass, CodeVisitor> tableMap,
Map<MyClass, Map<String, String>> fieldChangeMap,
Map<MyClass, Map<String, String>> methodChangeMap,
Collection<CodeVisitor> codeCollection) {
this.codeVisitor = codeVisitor;
this.tableMap = new DualHashBidiMap<MyClass, CodeVisitor>(tableMap);
this.inverseTableMap = this.tableMap.inverseBidiMap();
this.fieldChangeMap = fieldChangeMap;
this.varTypeMap = new HashMap<String, MyClass>();
this.methodChangeMap = methodChangeMap;
this.codeCollection = codeCollection;
this.mockFinalParamsList = new ArrayList<String>();
this.mockMethodMap = new HashMap<String, String>();
this.variableFieldNameMap = new HashMap<String, String>();
this.myClass = interactCodeClass_from_table(codeVisitor.getClassName());
}
public HashMap<String, String> getVariableFieldNameMap() {
return variableFieldNameMap;
}
public List<String> getMockFieldList() {
return mockFinalParamsList;
}
public HashMap<String, String> getMockMethodMap() {
return mockMethodMap;
}
@Override
public void visit(FieldDeclaration n, Void arg) {
String fieldDec = n.toString();
String[] splitStr;
StringBuilder sb = new StringBuilder();
fieldDec = fieldDec.replaceAll(";", "");
splitStr = fieldDec.split(" ");
//ユーザー定義の参照型のみモックするようにする
//intのような基本型はMockしない
for(CodeVisitor codeVisitor : codeCollection){
if (splitStr[splitStr.length-2].equals(codeVisitor.getClassName())) {
String typeName = splitStr[splitStr.length-2];
String varName = splitStr[splitStr.length-1];
String skeltonFieldVariableName;
sb.append("@Mocked " + "final "+typeName+" "+varName);
skeltonFieldVariableName = interactCodeVariableName_from_panel(myClass, varName);
this.variableFieldNameMap.put(skeltonFieldVariableName, varName);
this.varTypeMap.put(varName, inverseTableMap.get(codeVisitor));
mockFinalParamsList.add(sb.toString());
}
}
super.visit(n, arg);
}
@Override
public void visit(MethodDeclaration n, Void arg) {
String methodSigNature_str = n.getDeclarationAsString();
BlockStmt bs = n.getBody();
List<Statement> stmts = bs.getStmts();
Statement st;
StringBuilder sb = new StringBuilder();
String statement_str;
MyClass fieldTypeClass = null;
//make Expectation State
for(int i=0;i<stmts.size();i++){
st = stmts.get(i);
if (st.toString().contains("return")) {
break;
}
statement_str = replaceVariableNameUsedBySkeltonVariableName(st.toString());
for (String varName : varTypeMap.keySet()) {
String targetVarName = statement_str.split("\\.")[0];
if (targetVarName.equals(varName)) {
fieldTypeClass = varTypeMap.get(varName);
break;
}
}
statement_str = replaceMethodSignatureFollowSouceCode(statement_str,fieldTypeClass);
sb.append("\r\t\t\t\t"+statement_str+"\n");
//VerificationsInOrderのみにするのでtimesは不要
//sb.append("\r\t\t\t\t"+"times=1;" + "\n");
}
mockMethodMap.put(methodSigNature_str, sb.toString());
super.visit(n, arg);
}
//FIXME
private String replaceMethodSignatureFollowSouceCode(String statement_str,MyClass fieldTypeClass) {
Map<String, String> methodMap = methodChangeMap.get(fieldTypeClass);
String[] split;
String varName = null;
String methodName = null;
String replacedMethodSigNature_str = null;
String replacedMethodName = null;
StringBuilder methodSigNature_sb = new StringBuilder();
JudgementMockType judgementMockType = new JudgementMockType();
Pattern methodNamePattern = Pattern.compile("([0-9a-zA-Z_]+)\\(");
Matcher methodNameMatcher = null;
split = statement_str.split("\\.");
varName = split[0];
split = split[1].split("\\(");
methodName = split[0];
for (String skeltonMethod : methodMap.keySet()) {
if (skeltonMethod.contains(methodName)) {
replacedMethodSigNature_str = methodMap.get(skeltonMethod);
}
}
methodNameMatcher = methodNamePattern.matcher(replacedMethodSigNature_str);
//split = replacedMethodSigNature_str.split(" [");
//replacedMethodName = split[split.length - 1].split("\\(")[0];
if (methodNameMatcher.find()) {
replacedMethodName = methodNameMatcher.group(1);
}
//FIXME
//スケルトンコードのメソッドをソースコードのメソッドに変更する
//また,パラメータがある場合はそれに合わせた引数にする
//ex) mockObj.add(int num); => mockObj.add(1);
methodSigNature_sb.append(varName);
methodSigNature_sb.append(".");
methodSigNature_sb.append(replacedMethodName);
methodSigNature_sb.append("(");
DisassemblyMethodSignature disassemblyMethod = new DisassemblyMethodSignature(replacedMethodSigNature_str);
List<String> paramTypeList = disassemblyMethod.getParamTypeList();
for(int i_paramTypeList=0;i_paramTypeList<paramTypeList.size();i_paramTypeList++){
String type_str = paramTypeList.get(i_paramTypeList);
methodSigNature_sb.append(judgementMockType.toDefaultValue_Str(type_str));
if (i_paramTypeList < paramTypeList.size() - 1) {
methodSigNature_sb.append(",");
}
}
methodSigNature_sb.append(")");
methodSigNature_sb.append(";");
return methodSigNature_sb.toString();
}
private String replaceVariableNameUsedBySkeltonVariableName(String statement_str){
String replaced_statement;
String codeFieldName;
for (String skeltonFieldName : variableFieldNameMap.keySet()) {
//正規表現を使ってスケルトンコードから生成したフィールド変数名をコードの変数名にする
//if (statement_str.matches(skeltonFieldName+"\\.[a-zA-Z_0-9]+\\(")) {
if (statement_str.contains(skeltonFieldName+".")) {
codeFieldName = variableFieldNameMap.get(skeltonFieldName);
replaced_statement = statement_str.replaceFirst(skeltonFieldName+"\\.",codeFieldName+".");
return replaced_statement;
}
}
return statement_str;
}
private String interactCodeVariableName_from_panel(MyClass myClass,String targetCodeFieldVariableName){
String rtnSkeltonFieldVariableName = null;
//クラスのフィールドのマップを取得する(インタラクティブにユーザに設定してもらった対応関係のマップ)
Map<String, String> classFieldMap = fieldChangeMap.get(myClass);
String codeFieldVariableName;
String[] split_str;
for (String skeltonField : classFieldMap.keySet()) {
String codeField = classFieldMap.get(skeltonField);
split_str = codeField.split(" ");
codeFieldVariableName = split_str[split_str.length-1];
//コードに書いてあるターゲットのフィールドの変数名を見つけ、
//対応するスケルトンコードのクラスのフィールドの変数名を取得する
if (codeFieldVariableName.equals(targetCodeFieldVariableName)) {
split_str = skeltonField.split(" ");
String skeltonFieldVariableName = split_str[split_str.length -1];
rtnSkeltonFieldVariableName = skeltonFieldVariableName;
break;
}
}
return rtnSkeltonFieldVariableName;
}
private MyClass interactCodeClass_from_table(String codeClass_str){
MyClass rtnSkeltonClass = null;
Set<MyClass> myClass_Set = tableMap.keySet();
for (MyClass myClass : myClass_Set) {
CodeVisitor codeVisitor = tableMap.get(myClass);
if (codeVisitor.getClassName().equals(codeClass_str)) {
rtnSkeltonClass = myClass;
break;
}
}
return rtnSkeltonClass;
}
}
|
package Raghu1;
public class conditional {
public static void main(String[] args) {
for(int i=1;i<=50;i++) {
if(i%2==0) {
System.out.println(i);
}
}
for(int j=1;j<=49;j++) {
if(j%2!=0){
System.out.println(j);
}
}
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import f.a.a.b;
import java.util.LinkedList;
public final class cco extends a {
public bhy rcn;
public String rhV;
public bhy rhZ;
public String syo;
protected final int a(int i, Object... objArr) {
int h;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.rhZ == null) {
throw new b("Not all required fields were included: KSid");
} else if (this.rcn == null) {
throw new b("Not all required fields were included: ImgBuf");
} else {
if (this.syo != null) {
aVar.g(1, this.syo);
}
if (this.rhZ != null) {
aVar.fV(2, this.rhZ.boi());
this.rhZ.a(aVar);
}
if (this.rhV != null) {
aVar.g(3, this.rhV);
}
if (this.rcn == null) {
return 0;
}
aVar.fV(4, this.rcn.boi());
this.rcn.a(aVar);
return 0;
}
} else if (i == 1) {
if (this.syo != null) {
h = f.a.a.b.b.a.h(1, this.syo) + 0;
} else {
h = 0;
}
if (this.rhZ != null) {
h += f.a.a.a.fS(2, this.rhZ.boi());
}
if (this.rhV != null) {
h += f.a.a.b.b.a.h(3, this.rhV);
}
if (this.rcn != null) {
h += f.a.a.a.fS(4, this.rcn.boi());
}
return h;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) {
if (!super.a(aVar2, this, h)) {
aVar2.cJS();
}
}
if (this.rhZ == null) {
throw new b("Not all required fields were included: KSid");
} else if (this.rcn != null) {
return 0;
} else {
throw new b("Not all required fields were included: ImgBuf");
}
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
cco cco = (cco) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
byte[] bArr;
a bhy;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
cco.syo = aVar3.vHC.readString();
return 0;
case 2:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, a.a(aVar4))) {
}
cco.rhZ = bhy;
}
return 0;
case 3:
cco.rhV = aVar3.vHC.readString();
return 0;
case 4:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, a.a(aVar4))) {
}
cco.rcn = bhy;
}
return 0;
default:
return -1;
}
}
}
}
|
package kodlamaio.hrms.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kodlamaio.hrms.business.abstracts.EmployerService;
import kodlamaio.hrms.core.utilities.result.DataResult;
import kodlamaio.hrms.core.utilities.result.Result;
import kodlamaio.hrms.core.utilities.result.SuccessDataResult;
import kodlamaio.hrms.core.utilities.result.SuccessResult;
import kodlamaio.hrms.dataAccess.abstacts.EmployerDao;
import kodlamaio.hrms.entities.concretes.Employer;
@Service
public class EmployerManager implements EmployerService{
private EmployerDao employerDao;
@Autowired
public EmployerManager(EmployerDao employerDao) {
super();
this.employerDao = employerDao;
}
@Override
public Result add(Employer employer) {
this.employerDao.save(employer);
return new SuccessResult("İşveren eklendi!");
}
@Override
public DataResult<List<Employer>> getAll() {
return new SuccessDataResult<List<Employer>>(this.employerDao.findAll(), "İşverenler başarıyla getirildi");
}
@Override
public DataResult<Employer> getByEmail(String email) {
return new SuccessDataResult<Employer>(this.employerDao.getByEmail(email));
}
}
|
package com.example.wristband.activities;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.wristband.R;
import com.example.wristband.charts.BubblePlaceholderFragment;
import com.example.wristband.charts.ColumnPlaceholderFragment;
import com.example.wristband.charts.LinePlaceholderFragment;
import java.util.ArrayList;
import java.util.List;
import lecho.lib.hellocharts.animation.ChartAnimationListener;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.BubbleChartOnValueSelectListener;
import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.BubbleChartData;
import lecho.lib.hellocharts.model.BubbleValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.BubbleChartView;
import lecho.lib.hellocharts.view.Chart;
import lecho.lib.hellocharts.view.LineChartView;
public class StatisticsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
//默认加载线型
getSupportFragmentManager().beginTransaction().add(R.id.container, new com.example.wristband.charts.LinePlaceholderFragment()).commit();
getSupportFragmentManager().beginTransaction().add(R.id.container2, new com.example.wristband.charts.ColumnPlaceholderFragment()).commit();
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.sta_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chart_style,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: //点击返回
finish();
break;
case R.id.line_chart:
getSupportFragmentManager().beginTransaction().replace(R.id.container,new LinePlaceholderFragment()).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.container2,new LinePlaceholderFragment()).commit();
break;
case R.id.bubble_chart:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new BubblePlaceholderFragment()).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.container2, new BubblePlaceholderFragment()).commit();
break;
case R.id.column_chart:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new ColumnPlaceholderFragment()).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.container2, new ColumnPlaceholderFragment()).commit();
default:
break;
}
return true;
}
}
|
package com.twu.biblioteca.interfaces;
public interface MediaList {
void printAvaliableMedia();
}
|
package com.cpz.Demo19;
public class DemoRunnable {
public static void main(String[] args) {
MyRunnableImpl runnable=new MyRunnableImpl();
Thread t=new Thread(new MyRunnableImpl2());
Thread t2=new Thread(runnable);
t.start();
t2.start();
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+"-->"+i);
}
demo();
}
//匿名内部类
private static void demo() {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("匿名:"+i);
}
}
}).start();
new Thread(){
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("匿名2:"+i);
}
}
}.start();
Runnable r= new Runnable(){
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("匿名3:"+i);
}
}
};
Thread thread=new Thread(r);
thread.start();
}
}
|
package com.library.bexam.entity;
import com.library.bexam.form.ClassForm;
/**
* 学生实体
* @author caoqian
* @date 20181213
*/
public class StudentEntity {
private int studentId;
//学生真实名称
private String realName;
//学生编号
private String code;
//年龄
private int age;
//性别
private int gender;
//班级id
private int classId;
private ClassForm classEntity;
//创建时间
private String createTime;
public StudentEntity() {
}
public StudentEntity(int studentId, String realName, String code, int age, int gender, int classId,String createTime) {
this.studentId = studentId;
this.realName = realName;
this.code = code;
this.age = age;
this.gender = gender;
this.classId = classId;
this.createTime = createTime;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getClassId() {
return classId;
}
public void setClassId(int classId) {
this.classId = classId;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public ClassForm getClassEntity() {
return classEntity;
}
public void setClassEntity(ClassForm classEntity) {
this.classEntity = classEntity;
}
}
|
package com.porsche.sell.dao;
import com.porsche.sell.entity.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.List;
import static org.junit.Assert.*;
/**
* 商品dao测试类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class ProductInfoRepositoryTest {
@Autowired
private ProductInfoRepository productInfoRepository;
@Test
public void save(){
ProductInfo productInfo = new ProductInfo();
productInfo.setProductId("1798123791");
productInfo.setProductName("皮蛋粥");
productInfo.setProductPrice(new BigDecimal(6));
productInfo.setProductStock(100);
productInfo.setProductDescription("很好喝的粥");
productInfo.setProductIcon("D:/123.jpg");
productInfo.setProductStatus(0);
productInfo.setCategoryType(11);
ProductInfo result = productInfoRepository.save(productInfo);
Assert.assertNotNull(result);
}
@Test
public void findByProductStatus() {
List<ProductInfo> productInfos = productInfoRepository.findByProductStatus(0);
Assert.assertEquals(1, productInfos.size());
}
}
|
package kz.sagrad.ufix;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by adik on 12/22/16.
*/
public class PageFragment extends Fragment {
public static final String IMAGE = "ARG_PAGE";
public static final String CURRENT = "CURRENT";
public static final String SIZE = "SIZE";
private String mPage;
public static PageFragment newInstance(String page, int current, int size) {
Bundle args = new Bundle();
args.putString(IMAGE, page);
args.putInt(CURRENT, current);
args.putInt(SIZE, size);
PageFragment pageFragment = new PageFragment();
pageFragment.setArguments(args);
return pageFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getString(IMAGE);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.page);
TextView pageCount = (TextView) view.findViewById(R.id.page_count);
mPage = getArguments().getString(IMAGE);
pageCount.setText((getArguments().getInt(CURRENT) + 1) + "/" + getArguments().getInt(SIZE));
if (mPage.equalsIgnoreCase("no photo")) {
imageView.setImageResource(R.drawable.tire_wrench);
} else {
CameraAndPictures.getPicFromFirebase(mPage, imageView);
}
}
}
|
package com.isen.regardecommeilfaitbeau.api.Request.darkSky;
import com.isen.regardecommeilfaitbeau.api.Request.ComptementaryClass.InputStreamOperations;
import com.isen.regardecommeilfaitbeau.typeData.Position;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DarkSkyFuturHour {
private Position position;
private String urlS;
private JSONObject jsonObject;
private JSONArray hourly;
private FileWriter file;
private boolean requestDone;
public DarkSkyFuturHour(Position position) throws JSONException {
this.position = position;
makeObject();
}
private void makeObject() throws JSONException {
makeUrlS();
doRequest();
makeJson();
}
private void makeUrlS(){
urlS = "https://api.darksky.net/forecast/c3ee733ddd59b4b4d6abbf67c824bdab/" + position.getLatitude() +
"," + position.getLongitude() +
"?lang=fr&units=ca&extend=hourly&exclude=minutely&exclude=daily&exclude=currently";
}
private void doRequest(){
try{
URL url = new URL(urlS);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
String result = InputStreamOperations.InputStreamToString(inputStream);
jsonObject = new JSONObject(result);
requestDone = true;
}catch (Exception e){
e.printStackTrace();
requestDone = false;
}
}
public boolean exportJson() throws IOException {
file = new FileWriter("DarkSkyFuturHour.json");
try{
file.write(hourly.toString());
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}finally {
try{
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void makeJson() throws JSONException {
hourly = jsonObject.getJSONObject("hourly").getJSONArray("data");
}
public String getUrlS() {
return urlS;
}
public JSONArray getHourly() {
return hourly;
}
public boolean isRequestDone() {
return requestDone;
}
}
|
package com.example.topics.delete;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.example.topics.core.TopicRepository;
import com.example.topics.create.CreateTopicCore;
import com.example.topics.create.CreateTopicRequest;
import com.example.topics.infra.GatewayResponse;
import com.example.topics.infra.JwtUserMapper;
import com.example.topics.infra.TopicRepositoryFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
@Slf4j
public class DeleteTopicHandler implements RequestHandler<Map<String, Object>, GatewayResponse<Void>> {
private final TopicRepository topicRepository;
private ObjectMapper mapper = new ObjectMapper();
public DeleteTopicHandler() {
topicRepository = TopicRepositoryFactory.getInstance().buildTopicRepositoryFactory();
}
@SneakyThrows
@Override
public GatewayResponse<Void> handleRequest(Map<String, Object> request, Context context) {
JsonNode jsonNode = mapper.valueToTree(request);
log.info("received event {}", jsonNode.toString());
String topicName = jsonNode.at("/pathParameters/topic").textValue();
topicRepository.delete(topicName);
return GatewayResponse.createHttp200Response(null);
}
}
|
package es.maltimor.genericRest;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
@Intercepts({ @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = { Statement.class }) })
public class GenericResultSetHandler implements Interceptor {
public static ResultSetMetaData md;
public static ResultSetMetaData md2;
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
Statement statement = (Statement) args[0];
ResultSet rs = getFirstResultSet(statement);
if (rs != null) {
md = new ResultSetMetaDataWrapper(rs.getMetaData());
}
Object results = invocation.proceed();
return results;
}
private ResultSet getFirstResultSet(Statement stmt) throws SQLException {
ResultSet rs = stmt.getResultSet();
while (rs == null) {
// move forward to get the first resultset in case the driver
// doesn't return the resultset as the first result (HSQLDB 2.1)
if (stmt.getMoreResults()) {
rs = stmt.getResultSet();
} else {
if (stmt.getUpdateCount() == -1) {
// no more results. Must be no resultset
break;
}
}
}
return rs;
}
private ResultSet getNextResultSet(Statement stmt) throws SQLException {
// Making this method tolerant of bad JDBC drivers
try {
if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
// Crazy Standard JDBC way of determining if there are more results
if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) {
ResultSet rs = stmt.getResultSet();
return rs;
}
}
} catch (Exception e) {
// Intentionally ignored.
}
return null;
}
private void closeResultSet(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
// ignore
}
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
// To change body of implemented methods use File | Settings | File
// Templates.
}
public class ResultSetMetaDataWrapper implements ResultSetMetaData {
private int columnCount;
private String[] columnLabel;
private String[] columnName;
private String[] columnTypeName;
private int[] columnDisplaySize;
public ResultSetMetaDataWrapper(ResultSetMetaData md) throws Exception{
this.columnCount= md.getColumnCount();
this.columnLabel = new String[this.columnCount+1];
this.columnName = new String[this.columnCount+1];
this.columnTypeName = new String[this.columnCount+1];
this.columnDisplaySize = new int[this.columnCount+1];
for (int i=1;i<=this.columnCount;i++){
this.columnLabel[i]=md.getColumnLabel(i);
this.columnName[i]=md.getColumnName(i);
this.columnTypeName[i]=md.getColumnTypeName(i);
this.columnDisplaySize[i]=md.getColumnDisplaySize(i);
}
}
public String toString(){
return "colCount:"+columnCount+" label:"+columnLabel.length+" Name:"+columnName.length;
}
public int getColumnCount() throws SQLException {
return columnCount;
}
public String getColumnLabel(int column) throws SQLException {
return this.columnLabel[column];
}
public String getColumnName(int column) throws SQLException {
return this.columnName[column];
}
public String getColumnTypeName(int column) throws SQLException {
return this.columnTypeName[column];
}
public int getColumnDisplaySize(int column) throws SQLException {
return this.columnDisplaySize[column];
}
/* METODOS SIN IMPLEMENTAR */
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
public boolean isAutoIncrement(int column) throws SQLException {
return false;
}
public boolean isCaseSensitive(int column) throws SQLException {
return false;
}
public boolean isSearchable(int column) throws SQLException {
return false;
}
public boolean isCurrency(int column) throws SQLException {
return false;
}
public int isNullable(int column) throws SQLException {
return 0;
}
public boolean isSigned(int column) throws SQLException {
return false;
}
public String getSchemaName(int column) throws SQLException {
return null;
}
public int getPrecision(int column) throws SQLException {
return 0;
}
public int getScale(int column) throws SQLException {
return 0;
}
public String getTableName(int column) throws SQLException {
return null;
}
public String getCatalogName(int column) throws SQLException {
return null;
}
public int getColumnType(int column) throws SQLException {
return 0;
}
public boolean isReadOnly(int column) throws SQLException {
return false;
}
public boolean isWritable(int column) throws SQLException {
return false;
}
public boolean isDefinitelyWritable(int column) throws SQLException {
return false;
}
public String getColumnClassName(int column) throws SQLException {
return null;
}
}
}
|
package DateRange;
import java.time.LocalDate;
public class TestDateRange {
public static void main(String []args) {
DateRange date = new DateRange(LocalDate.of(2019, 7, 10),
LocalDate.of(2019, 7, 20));
LocalDate[]dates = new LocalDate[]{
LocalDate.of(2019, 7, 10),
LocalDate.of(2019, 7, 11),
LocalDate.of(2019, 7, 12),
LocalDate.of(2019, 7, 13),
LocalDate.of(2019, 7, 14),
LocalDate.of(2019, 7, 15),
LocalDate.of(2019, 7, 16),
LocalDate.of(2019, 7, 17),
LocalDate.of(2019, 7, 18),
LocalDate.of(2019, 7, 19),
LocalDate.of(2019, 7, 20),
};
int index = 0;
for (LocalDate d: date) {
if (! d.equals(dates[index])) {
System.out.printf("should be %s got %s\n", dates[index], d);
break;
}
index++;
if (index >= dates.length) {
System.out.printf("should only has %d day(s)\n", dates.length);
break;
}
}
LocalDate date1 = LocalDate.of(2019, 7, 15);
if (!date.contains(date1)) {
System.out.printf("%s should be inside date range %s\n", date1, date);
}
DateRange date2 = new DateRange(LocalDate.of(2019, 7, 19),
LocalDate.of(2019, 7, 22));
if (!date.overlap(date2)) {
System.out.printf("%s should be overlap %s\n", date, date2);
}
}
}
|
package com.cep.main;
public class Main {
public static void main(String[] args) {
//System.out.println(MyArrays.colours);
//System.out.println(MyArrays.colours[1]);
starter();
}
public static void starter() {
CafeQA clare = new CafeQA();
System.out.println(clare.makeOrder("black coffee"));
System.out.println(clare.makeOrder("filter coffee"));
clare.showWorkingOrders();
System.out.println(clare.completeOrder(1));
clare.showWorkingOrders();
System.out.println(clare.makeOrder("hot chocolate"));
clare.showWorkingOrders();
System.out.println(clare.addToOrder(2, "whipped cream"));
clare.showWorkingOrders();
clare.clearAllOrders();
clare.showWorkingOrders();
}
}
|
package com.levi9.taster.core.memory;
import javax.inject.Named;
import com.levi9.taster.commons.memory.AbstractMemoryService;
import com.levi9.taster.core.Category;
import com.levi9.taster.core.api.CategoryService;
/**
* In-memory implementation of {@link CategoryService}.
*
* @author d.gajic
*/
@Named("inMemoryCategoryService")
public class InMemoryCategoryService extends AbstractMemoryService<Category> implements CategoryService {
@Override
public CategoryBuilder builder(String name) {
return new Builder(name);
}
private class Builder implements CategoryBuilder {
private final String name;
private Long id;
public Builder(String name) {
this.name = name;
this.id = sequence.getAndIncrement();
}
public CategoryBuilder id(Long val) {
id = val;
return this;
}
@Override
public Category build() {
return new Category() {
private static final long serialVersionUID = 6871996353733342059L;
@Override
public Long getId() {
return id;
}
@Override
public String getName() {
return name;
}
};
}
}
@Override
public Category updateName(Long id, String name) {
return save(builder(name).id(id).build());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.