text
stringlengths
10
2.72M
package com.flute.atp.domain.model; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.Transient; import java.util.ArrayList; import java.util.List; @Setter @Getter public class AggregateRoot extends Entity { public int version ; @Transient public List<DomainEvent> events = new ArrayList<>(); }
package com.example.medicapp; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Bundle; import android.telephony.SmsManager; import android.text.Html; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import java.io.IOException; import java.util.List; import java.util.Locale; public class AlertBodyParts extends AppCompatActivity { ImageView img, img2, img3, img4; TextView textView1, textView2, textView3, textView4, textView5, t; FusedLocationProviderClient fusedLocationProviderClient; FirebaseAuth fAuth; FirebaseFirestore fStore; String userId; String fullname; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alert_body_parts); // Assign variable$ t = findViewById(R.id.textView); textView1 = findViewById(R.id.text_view1); textView2 = findViewById(R.id.text_view2); textView3 = findViewById(R.id.text_view3); textView4 = findViewById(R.id.text_view4); textView5 = findViewById(R.id.text_view5); img = findViewById(R.id.coeur); img2 = findViewById(R.id.poumons); img3 = findViewById(R.id.cerveau); img4 = findViewById(R.id.yeux); fAuth = FirebaseAuth.getInstance(); fStore = FirebaseFirestore.getInstance(); userId = fAuth.getCurrentUser().getUid(); DocumentReference documentReference = fStore.collection("users").document(userId); documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException error) { fullname = (documentSnapshot.getString("userName")); System.out.println(documentSnapshot.getString("userName")); } }); ActivityCompat.requestPermissions(AlertBodyParts.this, new String[]{Manifest.permission.SEND_SMS}, PackageManager.PERMISSION_GRANTED); //initialize fusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(AlertBodyParts.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //// quand la permission est donnée getLocation(getString(R.string.coeur), fullname); //displayToast(getString(R.string.coeur)); } else { //quand la permission est refusée ActivityCompat.requestPermissions(AlertBodyParts.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); } } }); //initialize fusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); img2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(AlertBodyParts.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //quand la permission est donnée getLocation(getString(R.string.poumons), fullname); //displayToast(getString(R.string.poumons)); } else { //quand la permission est refusée ActivityCompat.requestPermissions(AlertBodyParts.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); } } }); //initialize fusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); img3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(AlertBodyParts.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //quand la permission est donnée getLocation(getString(R.string.brain), fullname); //displayToast(getString(R.string.brain)); } else { //quand la permission est refusée ActivityCompat.requestPermissions(AlertBodyParts.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); } } }); //initialize fusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); img4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(AlertBodyParts.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //quand la permission est donnée getLocation(getString(R.string.yeux), fullname); //displayToast(getString(R.string.yeux)); } else { //quand la permission est refusée ActivityCompat.requestPermissions(AlertBodyParts.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); } } }); } // private void getLocation() { // if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // // TODO: Consider calling // // ActivityCompat#requestPermissions // // here to request the missing permissions, and then overriding // // public void onRequestPermissionsResult(int requestCode, String[] permissions, // // int[] grantResults) // // to handle the case where the user grants the permission. See the documentation // // for ActivityCompat#requestPermissions for more details. // //return; // return; // } // fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() { // @Override // public void onComplete(@NonNull Task<Location> task) { // Location location = task.getResult(); // if (location != null) { // try { // //initialiser geocoder // Geocoder geocoder = new Geocoder(AlertBodyParts.this, Locale.getDefault()); // //initialiser address list // List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1); // // //set latitude sur la textView // textView1.setText(Html.fromHtml( // "<font color='#FFFFFF'><b>Latitude :</b><br></font>" // + addresses.get(0).getLatitude() // )); // //set longitude sur la text view // textView2.setText(Html.fromHtml( // "<font color='#FFFFFF'><b>Longitude :</b><br></font>" // + addresses.get(0).getLongitude() // )); // //set nom du pays sur la text view // textView3.setText(Html.fromHtml( // "<font color='#FFFFFF'><b>Country Name :</b><br></font>" // + addresses.get(0).getCountryName() // )); // //set localité // textView4.setText(Html.fromHtml( // "<font color='#FFFFFF'><b>Locality :</b><br></font>" // + addresses.get(0).getLocality() // )); // //set address // textView5.setText(Html.fromHtml( // "<font color='#FFFFFF'><b>Address :</b><br></font>" // + addresses.get(0).getAddressLine(0) // ) // // ); // // // } catch (IOException e) { // e.printStackTrace(); // } // } // } // }); private void getLocation(final String message, final String fullname) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { Location location = task.getResult(); if (location != null) { try { //initialiser geocoder Geocoder geocoder = new Geocoder(AlertBodyParts.this, Locale.getDefault()); //initialiser address list List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); //set latitude sur la textView textView1.setText(Html.fromHtml( "<font color='#FFFFFF'><b>Latitude :</b><br></font>" + addresses.get(0).getLatitude() )); //set longitude sur la text view textView2.setText(Html.fromHtml( "<font color='#FFFFFF'><b>Longitude :</b><br></font>" + addresses.get(0).getLongitude() )); //set nom du pays sur la text view textView3.setText(Html.fromHtml( "<font color='#FFFFFF'><b>Country Name :</b><br></font>" + addresses.get(0).getCountryName() )); //set localité textView4.setText(Html.fromHtml( "<font color='#FFFFFF'><b>Locality :</b><br></font>" + addresses.get(0).getLocality() )); //set address textView5.setText(Html.fromHtml( "<font color='#FFFFFF'><b>Address :</b><br></font>" + addresses.get(0).getAddressLine(0) )); Address address = addresses.get(0); StringBuilder builder = new StringBuilder(); builder.append(fullname).append(" "); builder.append(message).append(" "); builder.append(address.getLatitude()).append(" "); builder.append(address.getLongitude()).append(" "); builder.append(address.getCountryName()).append(" "); builder.append(address.getLocality()).append(" "); builder.append(address.getAddressLine(0)).append(" "); String message = builder.toString(); System.out.println(message); String phoneNumber = "0787056891"; try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNumber, null, message, null, null); Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "SMS faild, please try again later!", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } }); } public void displayToast(String message) { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } }
package tk.martijn_heil.elytraoptions.command.common; import com.sk89q.intake.Command; import com.sk89q.intake.CommandCallable; import com.sk89q.intake.dispatcher.Dispatcher; import com.sk89q.intake.parametric.annotation.Optional; import org.bukkit.command.CommandSender; public class CommonCommands { private Dispatcher dispatcher; public CommonCommands() { } @Command(aliases = {"help", "?", "h"}, desc = "Show command help", usage = "[command=overview]") public void help(@Sender CommandSender sender, @Optional CommandCallable callable) { if(callable != null) { CommonUtils.sendCommandHelp(callable, sender); } else { CommonUtils.sendCommandHelp(dispatcher, sender); } } /** * This is a bit hacky, CommonCommands depends on the dispatcher it belongs to, but when we *have* to register * the CommonCommands, the dispatcher is not initialized yet. So we have to do late-initialization as you can see below * * @param dispatcher The dispatcher this belongs to. */ public void lateInit(Dispatcher dispatcher) { this.dispatcher = dispatcher; } }
package ativ_fix_iterator_AndreLucas; import java.util.ArrayList; import java.util.Iterator; public class Aplicacao { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<Integer> numeros = new ArrayList<Integer>(); numeros.add(12); numeros.add(3); numeros.add(31); numeros.add(5); System.out.println(numeros); Iterator<Integer> it = numeros.iterator(); while (it.hasNext()); Integer i = it.next(); if(i < 10) { numeros.remove(i); } System.out.println(numeros); } }
package interviewbit.array; import java.util.ArrayList; public class Array_Plus1 { public ArrayList<Integer> plusOne(ArrayList<Integer> a) { for (int i = 0; i < a.size(); i++) { if (a.get(i) == 0) { if (a.size() == 1) { break; } else { a.remove(i); i--; } } else { break; } } if (a.get(a.size() - 1) != 9) { a.set(a.size() - 1, a.get(a.size() - 1) + 1); return a; } else { a = inc_of_9(a); } return a; } private ArrayList<Integer> inc_of_9(ArrayList<Integer> a) { for (int i = a.size() - 1; i >= 0; i--) { if (i == 0) { if (a.get(i) != 9) { a.set(i, a.get(i) + 1); return a; } else { a.set(i, 0); a.add(0, 1); return a; } } else { if (a.get(i - 1) != 9) { a.set(i, 0); a.set(i - 1, a.get(i - 1) + 1); return a; } else { a.set(i, 0); } } } return a; } }
import java.net.*; import java.util.*; import java.io.*; /** * This class, running on the main-server, handles an individual players * communications with the main set of data. This class adds-to and deletes-from * the object "LobbyOnlinePlayers" which holds all of the main data that each * thread can pull from. * * @author Brendon Murthum, Javier Ramirez * */ public class LobbyHandler extends Thread { /** This handles the stream from the command-line of client. */ private Scanner inFromClient; /** This handles the output stream by command-line to client. */ private PrintWriter outToClient; /** This is used to grab bytes over the data-line. */ private String recvMsg; /** This takes the user information from the host. */ private String userName; /** The user's IP address. Grabbed from socket connection. */ private String userIP; /** The user's port for another user to connect to. */ private String userPort; /** This thread keeps its own client informed using this. */ private boolean haveWeSentTheUpdate; /** This is for thread control. */ private boolean endThread = false; /** This will point to the object that is the main list of user details. */ private LobbyOnlinePlayers ptrOnlinePlayersList; /** * Beginning of thread. This constructor marks the beginning of a thread on * the server. Things here happen once, exclusively with THIS connected * client. * @param controlListen - The given socket for this thread to use. * @param onlinePlayersList - Passing the global arraylists by object. */ public LobbyHandler(final Socket controlListen, final LobbyOnlinePlayers onlinePlayersList) { /* Make this all... point to the total... */ ptrOnlinePlayersList = onlinePlayersList; try { /* Setting up a threaded input control-stream */ inFromClient = new Scanner(controlListen.getInputStream()); /* Setting up a threaded output control-stream */ outToClient = new PrintWriter(controlListen.getOutputStream()); /* Get IP from the control socket for future connections */ userIP = controlListen.getInetAddress().getHostAddress(); /* For debugging */ // System.out.println(" DEBUG: A new thread was successfully // setup."); // System.out.println(""); } catch (IOException ioEx) { ioEx.printStackTrace(); System.out.println(" ERROR: Could not set up a " + "threaded client input and output stream."); } } /****************************************************************** * * Beginning of main thread code. This method marks the threaded area that * this client receives commands and handles. When this receives "QUIT" from * the client, the thread closes. * ******************************************************************/ public void run() { /** Keeps tracks of when to close the thread */ boolean stayAlive = true; /** Gets user information from the host */ StringTokenizer userTokens; /** Username read from the client's data sent over the line. */ String tmpUserName = ""; try { /* This grabs the string of data from the client */ // Ex: "Alice" String userInformation = inFromClient.nextLine(); /* For Debugging. This shows what is read from control-line. */ // System.out.println(" DEBUG: Read-In: " + userInformation); /* Make the string parseable by tokens */ userTokens = new StringTokenizer(userInformation); /* Initialize and display the new user's shown username */ tmpUserName = userTokens.nextToken(); /* * If username taken, throw error, return a message, and stop * thread. */ if (ptrOnlinePlayersList.isUsernameTaken(tmpUserName)) { System.out.println(" ERROR: \"" + tmpUserName + "\" [" + userIP + "] must" + " pick another username to connect!"); /* Send notification to client to choose another username */ outToClient.println("BAD-USERNAME"); outToClient.flush(); endThread = true; throw new EmptyStackException(); } else { /* Send confirmation of username choice */ outToClient.println("GOOD-USERNAME"); outToClient.flush(); /* Set this thread's userName variable for use */ userName = tmpUserName; /* Add this player to the main list that other threads use */ ptrOnlinePlayersList.newConnectionValues(tmpUserName, userIP); } System.out.println(" Username: " + tmpUserName); } catch (Exception e) { System.out.println(" ERROR: Failure to read initial user info."); } /* End the thread */ if (endThread) { System.out.println(" ERROR: Ending user's thread"); /* Show the server data on user-leave */ System.out.println(" "); ptrOnlinePlayersList.showData(); System.out.println(" "); return; } /* For show. To separate user-logins. */ System.out.println(" "); /* For show. View the server's main data points on each new entrance! */ ptrOnlinePlayersList.showData(); /* For show. To separate information. */ System.out.println(" "); /* The controlling loop that keeps the user thread alive */ while (stayAlive) { /* This reads the command from the client */ try { recvMsg = inFromClient.nextLine(); } catch (Exception e) { /* Client left early, or otherwise */ System.out.println("Client " + userName + " [" + userIP + "] left early!"); /* Remove all rows with this username */ ptrOnlinePlayersList.remove(userName); /* Show the server data on user-leave */ System.out.println(" "); ptrOnlinePlayersList.showData(); System.out.println(" "); break; } /* For token handling */ StringTokenizer tokens = new StringTokenizer(recvMsg); /* Client command, "UPDATE" or another. */ String commandFromClient = tokens.nextToken(); /* For server log printing */ if (commandFromClient.equals("DISCONNECT")) { System.out.println("Client " + userName + " [" + userIP + "] disconnected!"); /* Remove all rows with this username */ ptrOnlinePlayersList.remove(userName); /* Show the new data */ ptrOnlinePlayersList.showData(); stayAlive = false; } else if (commandFromClient.equals("HOSTGAME")) { /* For server log printing */ System.out.println( "Client " + userName + " [" + userIP + "]: "); System.out.println("Ran Command: HOSTGAME"); /* TODO - Send an acknowledgement? */ /* Grab the user's sent open port for new players to connect */ String usersGamePort = tokens.nextToken(); /* Adds user to hosting-list, to be broadcast out. */ int result = ptrOnlinePlayersList.newUserHosting(userName, usersGamePort); /* Send the response of confirmation/denial to the client */ String toSendToClient; if (result == 1) { toSendToClient = "CONFIRMED"; } else { toSendToClient = "DECLINED"; } outToClient.println(toSendToClient); outToClient.flush(); /* Show the new data */ ptrOnlinePlayersList.showData(); } else if (commandFromClient.equals("NOTHOSTING")) { /* For server log printing */ System.out.println( "Client " + userName + " [" + userIP + "]: "); System.out.println("Ran Command: NOTHOSTING"); /* Removes user from hosting-list, to be broadcast out. */ ptrOnlinePlayersList.removeUserHosting(userName); /* Show the new data */ ptrOnlinePlayersList.showData(); } else if (commandFromClient.equals("JOINGAME")) { /* For server log printing */ System.out.println( "Client " + userName + " [" + userIP + "]: "); System.out.println("Ran Command: JOINGAME"); /* TODO - Send an acknowledgement? */ } else if (commandFromClient.equals("GETUPDATE")) { // Get the correct data to send back to client. String connectedUsers = Integer.toString(ptrOnlinePlayersList .currentConnectedUsers()); String waitingUsers = Integer.toString(ptrOnlinePlayersList .currentAvailableUsers()); String numberOfOpenGames = Integer.toString(ptrOnlinePlayersList .numberOfOpenGames()); String currentHostsAndPorts = ""; if (ptrOnlinePlayersList.shouldWeUpdateClients()) { haveWeSentTheUpdate = false; } if (!haveWeSentTheUpdate) { currentHostsAndPorts = ptrOnlinePlayersList.currentHostsAndPorts(); haveWeSentTheUpdate = true; } /* Sample Sent Strings: * "3 1 2" * This is the case of no current hosts. * * "5 2 3 Brendon 1236 Kyle 1237 Jim 1238" * 5, is the total number of connected users * 2, is the number of waiting users * 3, is the number of open games * Brendon 1236, is a username and its available port * Kyle 1237, is another username and its available port * ... * * This string is potentially sent to 10+ users two times per * second. It only sends longer versions (with hosts) * of this string on new updates to save bandwidth. */ String toSendToClient = connectedUsers + " " + waitingUsers + " " + numberOfOpenGames + " " + currentHostsAndPorts; /* Send the update to the client! */ outToClient.println(toSendToClient); outToClient.flush(); } } } }
package br.com.jdrmservices.repository.helper.compradireta; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import br.com.jdrmservices.model.CompraDireta; import br.com.jdrmservices.repository.filter.CompraDiretaFilter; public class ComprasDiretasImpl implements ComprasDiretasQueries { @PersistenceContext private EntityManager manager; @SuppressWarnings("unchecked") @Transactional(readOnly = true) @Override public Page<CompraDireta> filtrar(CompraDiretaFilter filtro, Pageable pageable) { @SuppressWarnings("deprecation") Criteria criteria = manager.unwrap(Session.class).createCriteria(CompraDireta.class); criteria.addOrder(Order.asc("numero")); int paginaAtual = pageable.getPageNumber(); int totalRegistrosPorPagina = pageable.getPageSize(); int primeiroRegistro = paginaAtual * totalRegistrosPorPagina; criteria.setFirstResult(primeiroRegistro); criteria.setMaxResults(totalRegistrosPorPagina); adicionarFiltro(filtro, criteria); return new PageImpl<>(criteria.list(), pageable, total(filtro)); } private Long total(CompraDiretaFilter filtro) { @SuppressWarnings("deprecation") Criteria criteria = manager.unwrap(Session.class).createCriteria(CompraDireta.class); adicionarFiltro(filtro, criteria); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } private void adicionarFiltro(CompraDiretaFilter filtro, Criteria criteria) { if(filtro != null) { if(filtro.getDataOrdem() != null) { criteria.add(Restrictions.eq("dataOrdem", filtro.getDataOrdem())); } if(!StringUtils.isEmpty(filtro.getNumero())) { criteria.add(Restrictions.ilike("numero", filtro.getNumero(), MatchMode.ANYWHERE)); } if(!StringUtils.isEmpty(filtro.getObjeto())) { criteria.add(Restrictions.ilike("objeto", filtro.getObjeto(), MatchMode.ANYWHERE)); } if(filtro.getFornecedor() != null) { criteria.add(Restrictions.eq("fornecedor", filtro.getFornecedor())); } if(filtro.getSecretaria() != null) { criteria.add(Restrictions.eq("secretaria", filtro.getSecretaria())); } } } }
package moderate; /* Sample code to read in test cases:*/ import java.io.*; public class ReverseAdd { public static void main (String[] args) throws IOException { File file = new File(args[0]); BufferedReader buffer = new BufferedReader(new FileReader(file)); String line; while ((line = buffer.readLine()) != null) { line = line.trim(); long n = Long.parseLong(line); long rn = Long.parseLong(revString(line)); long x = 0; int a=0; for(long i=0; i<100; i++){ x = n+rn; a++; if(isPalindrome(Long.toString(x)) && (x/10) != 0){ break; } n=x; rn = Long.parseLong(revString(Long.toString(n))); } System.out.println(a+" "+Long.toString(x)); } } private static boolean isPalindrome(String s) { long l = s.length()-1; for(long i=0; i<s.length()/2;i++){ if(s.charAt((int) i) != s.charAt((int) (l-i))){ return false; } } return true; } private static String revString(String line) { StringBuffer s = new StringBuffer(); for(long i=line.length()-1; i>=0; i--){ s.append(line.charAt((int) i)); } return s.toString(); } }
package com.example.android.currencyconversion; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; public class MainActivity extends AppCompatActivity { private TextView conversionTextView; private TextView outputTextView; private EditText answerEditText; private Button conversionButton; private View.OnClickListener onClickListener; private Firebase madReference; private double conversionRate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); conversionTextView = (TextView) findViewById(R.id.rate); outputTextView = (TextView) findViewById(R.id.output); answerEditText = (EditText) findViewById(R.id.answer); conversionButton = (Button) findViewById(R.id.convert); onClickListener = new View.OnClickListener(){ public void onClick(View v){ //do some stuff later String s = answerEditText.getText().toString(); double dollarsToConvert = Double.parseDouble(s); double frankDollars = dollarsToConvert/conversionRate; outputTextView.setText("That's worth " + frankDollars); } }; conversionButton.setOnClickListener(onClickListener); Firebase.setAndroidContext(this); Firebase madReference = new Firebase("https://madcc.firebaseio.com/"); madReference.child("conversion").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { conversionRate = (double) dataSnapshot.getValue(); conversionTextView.setText("$ to Frank$ rate is" + conversionRate); } @Override public void onCancelled(FirebaseError error) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package demo.constructors; public class EmployeeDemoTest { public static void main(String[] args) { Employee davidEmployee = new Employee("David", 25); System.out.println("Name : " + davidEmployee.getName()); System.out.println("Age : " + davidEmployee.getAge()); System.out.println("-------------------------------"); Employee johnEmployee = new Employee("John", 45); System.out.println("Name : " + johnEmployee.getName()); System.out.println("Age : " + johnEmployee.getAge()); } }
package org.apache.commons.net.examples.ntp; import java.io.IOException; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.text.DecimalFormat; import java.text.NumberFormat; import org.apache.commons.net.ntp.NTPUDPClient; import org.apache.commons.net.ntp.NtpUtils; import org.apache.commons.net.ntp.NtpV3Packet; import org.apache.commons.net.ntp.TimeInfo; import org.apache.commons.net.ntp.TimeStamp; public final class NTPClient { private static final NumberFormat numberFormat = new DecimalFormat("0.00"); public static void processResponse(TimeInfo info) { String refType; NtpV3Packet message = info.getMessage(); int stratum = message.getStratum(); if (stratum <= 0) { refType = "(Unspecified or Unavailable)"; } else if (stratum == 1) { refType = "(Primary Reference; e.g., GPS)"; } else { refType = "(Secondary Reference; e.g. via NTP or SNTP)"; } System.out.println(" Stratum: " + stratum + " " + refType); int version = message.getVersion(); int li = message.getLeapIndicator(); System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision()); System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")"); int poll = message.getPoll(); System.out.println(" poll: " + ((poll <= 0) ? 1 : (int)Math.pow(2.0D, poll)) + " seconds" + " (2 ** " + poll + ")"); double disp = message.getRootDispersionInMillisDouble(); System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble()) + ", rootdispersion(ms): " + numberFormat.format(disp)); int refId = message.getReferenceId(); String refAddr = NtpUtils.getHostAddress(refId); String refName = null; if (refId != 0) if (refAddr.equals("127.127.1.0")) { refName = "LOCAL"; } else if (stratum >= 2) { if (!refAddr.startsWith("127.127")) try { InetAddress addr = InetAddress.getByName(refAddr); String name = addr.getHostName(); if (name != null && !name.equals(refAddr)) refName = name; } catch (UnknownHostException e) { refName = NtpUtils.getReferenceClock(message); } } else if (version >= 3 && (stratum == 0 || stratum == 1)) { refName = NtpUtils.getReferenceClock(message); } if (refName != null && refName.length() > 1) refAddr = String.valueOf(refAddr) + " (" + refName + ")"; System.out.println(" Reference Identifier:\t" + refAddr); TimeStamp refNtpTime = message.getReferenceTimeStamp(); System.out.println(" Reference Timestamp:\t" + refNtpTime + " " + refNtpTime.toDateString()); TimeStamp origNtpTime = message.getOriginateTimeStamp(); System.out.println(" Originate Timestamp:\t" + origNtpTime + " " + origNtpTime.toDateString()); long destTime = info.getReturnTime(); TimeStamp rcvNtpTime = message.getReceiveTimeStamp(); System.out.println(" Receive Timestamp:\t" + rcvNtpTime + " " + rcvNtpTime.toDateString()); TimeStamp xmitNtpTime = message.getTransmitTimeStamp(); System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + " " + xmitNtpTime.toDateString()); TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime); System.out.println(" Destination Timestamp:\t" + destNtpTime + " " + destNtpTime.toDateString()); info.computeDetails(); Long offsetValue = info.getOffset(); Long delayValue = info.getDelay(); String delay = (delayValue == null) ? "N/A" : delayValue.toString(); String offset = (offsetValue == null) ? "N/A" : offsetValue.toString(); System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); } public static void main(String[] args) { if (args.length == 0) { System.err.println("Usage: NTPClient <hostname-or-address-list>"); System.exit(1); } NTPUDPClient client = new NTPUDPClient(); client.setDefaultTimeout(10000); try { client.open(); byte b; int i; String[] arrayOfString; for (i = (arrayOfString = args).length, b = 0; b < i; ) { String arg = arrayOfString[b]; System.out.println(); try { InetAddress hostAddr = InetAddress.getByName(arg); System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress()); TimeInfo info = client.getTime(hostAddr); processResponse(info); } catch (IOException ioe) { ioe.printStackTrace(); } b++; } } catch (SocketException e) { e.printStackTrace(); } client.close(); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\examples\ntp\NTPClient.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.huawei.esdk.csdemo.listener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JEditorPane; import com.huawei.esdk.csdemo.action.SiteControlAction; import com.huawei.esdk.csdemo.adapter.MouseAdapter; import com.huawei.esdk.csdemo.common.LabelText; import com.huawei.esdk.csdemo.common.MethodThread; import com.huawei.esdk.csdemo.memorydb.DataBase; import com.huawei.esdk.csdemo.utils.KeepAliveThread; import com.huawei.esdk.csdemo.view.panel.BottomPan; import com.huawei.esdk.csdemo.view.panel.SiteControlPanel; import com.huawei.esdk.csdemo.view.panel.SiteControlSiteListPan; import com.huawei.esdk.csdemo.view.panel.SiteControlVedioPan; public class SiteControlMouseListener { private SiteControlPanel siteControlPanel; private SiteControlAction siteControlAction; public void registerListener(SiteControlPanel siteControlPanel){ this.siteControlPanel = siteControlPanel; siteControlAction = new SiteControlAction(); addListenerForCameraCtrolPan(); addListenerForSitesTabel(); addListenerForSendAuxStreamBtn(); addListenerForSendAuxStreamCK(); addListenerForConnAuxStreamCK(); logoutButAction(); } private void addListenerForCameraCtrolPan(){ getSiteControlVedioPan().getUp().addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { // siteControlAction.controlCameraButAction(0); new MethodThread(siteControlAction,"controlCameraButAction",0).start(); } @Override public void mouseEntered(MouseEvent e) { getSiteControlVedioPan().getUp().setIcon(getSiteControlVedioPan().getUp_pabel_icon1()); // getEditPane().setText("摄像机控制操作\n 接口说明:Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) \n 功能描述 :指定会场摄像头控制,可以控制摄像机进行旋转、聚焦等操作 "); getEditPane().setText("Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) "); } @Override public void mouseExited(MouseEvent e) { getSiteControlVedioPan().getUp().setIcon(getSiteControlVedioPan().getUp_pabel_icon()); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }); getSiteControlVedioPan().getDown().addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { // siteControlAction.controlCameraButAction(1); new MethodThread(siteControlAction,"controlCameraButAction",1).start(); } @Override public void mouseEntered(MouseEvent e) { getSiteControlVedioPan().getDown().setIcon(getSiteControlVedioPan().getDown_pabel_icon1()); // getEditPane().setText("摄像机控制操作\n 接口说明:Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) \n 功能描述 :指定会场摄像头控制,可以控制摄像机进行旋转、聚焦等操作 "); getEditPane().setText("Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) "); } @Override public void mouseExited(MouseEvent e) { getSiteControlVedioPan().getDown().setIcon(getSiteControlVedioPan().getDown_pabel_icon()); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }); getSiteControlVedioPan().getLeft().addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { // siteControlAction.controlCameraButAction(2); new MethodThread(siteControlAction,"controlCameraButAction",2).start(); } @Override public void mouseEntered(MouseEvent e) { getSiteControlVedioPan().getLeft().setIcon(getSiteControlVedioPan().getLeft_pabel_icon1()); // getEditPane().setText("摄像机控制操作\n 接口说明:Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) \n 功能描述 :指定会场摄像头控制,可以控制摄像机进行旋转、聚焦等操作 "); getEditPane().setText("Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) "); } @Override public void mouseExited(MouseEvent e) { getSiteControlVedioPan().getLeft().setIcon(getSiteControlVedioPan().getLeft_pabel_icon()); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }); getSiteControlVedioPan().getRight().addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { // siteControlAction.controlCameraButAction(3); new MethodThread(siteControlAction,"controlCameraButAction",3).start(); } @Override public void mouseEntered(MouseEvent e) { getSiteControlVedioPan().getRight().setIcon(getSiteControlVedioPan().getRight_pabel_icon1()); // getEditPane().setText("摄像机控制操作\n 接口说明:Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) \n 功能描述 :指定会场摄像头控制,可以控制摄像机进行旋转、聚焦等操作 "); getEditPane().setText("Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) "); } @Override public void mouseExited(MouseEvent e) { getSiteControlVedioPan().getRight().setIcon(getSiteControlVedioPan().getRight_pabel_icon()); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }); getSiteControlVedioPan().getCenter().addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { // siteControlAction.controlCameraButAction(4); new MethodThread(siteControlAction,"controlCameraButAction",4).start(); } @Override public void mouseEntered(MouseEvent e) { getSiteControlVedioPan().getCenter().setIcon(getSiteControlVedioPan().getCenter_pabel_icon1()); // getEditPane().setText("摄像机控制操作\n 接口说明:Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) \n 功能描述 :指定会场摄像头控制,可以控制摄像机进行旋转、聚焦等操作 "); getEditPane().setText("Integer ctrlCameraEx(String siteUri,CameraControlEx cameraControl) "); } @Override public void mouseExited(MouseEvent e) { getSiteControlVedioPan().getCenter().setIcon(getSiteControlVedioPan().getCenter_pabel_icon()); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }); } public void addListenerForSitesTabel(){ getSiteControlSiteListPan().getSiteList().addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { // siteControlAction.sitesTabelAction(); new MethodThread(siteControlAction,"sitesTabelAction").start(); } @Override public void mouseEntered(MouseEvent e) { // if(0 == DataBase.getInstance().getLanguageFlag()) // { // getEditPane().setText("会场列表\n请选择一个会场"); // } // else // { // getEditPane().setText("Site List \nPlease choose one site"); // } getEditPane().setText(LabelText.description_pane_slectSite[DataBase.getInstance().getLanguageFlag()]); } @Override public void mouseExited(MouseEvent e) { getEditPane().setText(""); } }); } public void addListenerForSendAuxStreamBtn(){ getSiteControlVedioPan().getSendAuxStreamBtn().addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { // siteControlAction.setAuxStreamEx(); new MethodThread(siteControlAction,"setAuxStreamEx").start(); } @Override public void mouseEntered(MouseEvent e) { // getEditPane().setText("设置开始或停止发送辅流 \n 接口说明:Integer setAuxStreamEx (String siteUri, Integer controlCode) \n 功能描述 :指定会场辅流发送控制\n "); getEditPane().setText("Integer setAuxStreamEx (String siteUri, Integer controlCode) "); } @Override public void mouseExited(MouseEvent e) { } }); } public void addListenerForConnAuxStreamCK(){ getSiteControlVedioPan().getConnAuxStreamCK().addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { getEditPane().setText(""); } @Override public void mouseEntered(MouseEvent arg0) { // getEditPane().setText("查询是否接入辅流输入源\n 接口说明:Integer isConnectAuxSourceEx(String siteURI) \n 功能描述 :查询是否接入辅流输入源。如果当前终端接了辅流视频源,则可以发送辅流。反之,则不能 "); getEditPane().setText("Integer isConnectAuxSourceEx(String siteURI)"); } @Override public void mouseClicked(MouseEvent arg0) { } }); } public void addListenerForSendAuxStreamCK(){ getSiteControlVedioPan().getSendAuxStreamCK().addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { getEditPane().setText(""); } @Override public void mouseEntered(MouseEvent e) { // getEditPane().setText("查询当前是否正在发送辅流\n 接口说明:isSendAuxStreamEx(String siteURI) \n 功能描述 :查询当前是否正在发送辅流。如果当前正在发送辅流,则不可以进行发送辅流操作。反之,则可以。 "); getEditPane().setText("isSendAuxStreamEx(String siteURI) "); } @Override public void mouseClicked(MouseEvent e) { } }); } public void logoutButAction(){ getConfControlPaneBottom().getBtm_exitLoginBut().addMouseListener(new MouseAdapter() { @Override public void mouseExited(MouseEvent e) { getEditPane().setText(""); } @Override public void mouseEntered(MouseEvent e) { // if(0 == DataBase.getInstance().getLanguageFlag()) // { // getEditPane().setText("用户退出 \n功能描述:用户退出系统。 "); // } // else // { // getEditPane().setText("Logout \nExit the demo system. "); // } getEditPane().setText(LabelText.description_pane_exitLoginBtn[DataBase.getInstance().getLanguageFlag()]); } @Override public void mouseClicked(MouseEvent e) { // siteControlAction.logout(); // new MethodThread(siteControlAction,"logout").start(); KeepAliveThread.setFlag(1); try { siteControlAction.logout(); } catch(Exception exception) { System.out.println(e.toString()); } finally { System.exit(0); } } }); } public BottomPan getConfControlPaneBottom(){ return getSiteControlPanel().getBottomPanel(); } private JEditorPane getEditPane(){ return getSiteControlPanel().getBottomPanel().getDescriptionPane(); } private SiteControlVedioPan getSiteControlVedioPan(){ return getSiteControlPanel().getSiteControlVedioPan(); } private SiteControlSiteListPan getSiteControlSiteListPan(){ return getSiteControlPanel().getSiteControlSiteListPan(); } private SiteControlPanel getSiteControlPanel(){ return siteControlPanel; } public void setSiteControlPanel(SiteControlPanel siteControlPanel) { this.siteControlPanel = siteControlPanel; } }
package uz.kassa.test.exception; /** Author: Khumoyun Khujamov Date: 11/14/20 Time: 2:34 AM */ public class LoginException extends RuntimeException { public LoginException(String message) { super(message); } public LoginException(String message, Throwable cause) { super(message, cause); } }
package earth.xor.db; import java.util.List; import earth.xor.model.Bookmark; public class DatastoreFacade { private BookmarksDatastore ds; public DatastoreFacade(BookmarksDatastore ds) { this.ds = ds; } public void addBookmark(Bookmark bookmark) { this.ds.addBookmark(bookmark); } public List<Bookmark> getBookmarks() { return ds.getBookmarks(); } public Bookmark getBookmarkById(String id) { return ds.getBookmarkById(id); } public void deleteBookmarkById(String id) { this.ds.deleteBookmarkById(id); } }
package com.lubarov.daniel.data.serialization; public final class ShortSerializer extends AbstractSerializer<Short> { public static final ShortSerializer singleton = new ShortSerializer(); private ShortSerializer() {} @Override public void writeToSink(Short n, ByteSink sink) { for (int i = 0; i < 2; ++i) sink.give((byte) (n >>> (i * 8))); } @Override public Short readFromSource(ByteSource source) { short n = 0; for (int i = 0; i < 2; ++i) // The "& 0xFF" is needed to remove the bits from sign extension after the byte is promoted // to an int. n |= (source.take() & 0xFF) << (i * 8); return n; } }
package example; import javax.jws.WebService; import javax.jws.WebMethod; /** * Created by sasakin on 17.10.2017. */ @WebService public class HelloWorld { @WebMethod public String sayHelloWorldFrom(String from) { String result = "Hello, world, from " + from; System.out.println(result); return result; } }
package com.iflytek.sas.voice.transfer.server.common; import java.io.Serializable; /** * @author: JiangPing Li * @date: 2018-08-06 9:50 */ public class NullWritable implements Serializable { private static final long serialVersionUID = -7589666158575232386L; private static NullWritable instance = new NullWritable(); private NullWritable() { } public static NullWritable nullWritable() { return instance; } }
package com.tencent.mm.plugin.appbrand.page; class p$15 implements Runnable { final /* synthetic */ p gnH; final /* synthetic */ String gnK; p$15(p pVar, String str) { this.gnH = pVar; this.gnK = str; } public final void run() { this.gnH.gnn.setBackgroundColor(this.gnK); } }
// assignment 10 // pair p134 // Singh, Bhavneet // singhb // Wang, Shiyu // shiyu import java.util.*; /** Represents a US Map of States and Capitals. Use to learn about * hashCode, equals, and hashMap */ public class USMap { /** The <code>HashMap</code> to experiment with */ HashMap<City, State> states; public USMap() { this.states = new HashMap<City, State>(); } }
package com.tencent.mm.plugin.account.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; class g$5 implements OnCancelListener { final /* synthetic */ g eSt; g$5(g gVar) { this.eSt = gVar; } public final void onCancel(DialogInterface dialogInterface) { } }
package fil7.ru.examples.java.date; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Получение даты и времени из строки * Способ выделения дня, месяца и т.д. из строки */ public class DatePart { private Date fromDate = null; private SimpleDateFormat formatter = null; public DatePart(Date fromDate) { this.fromDate = fromDate; this.formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy", Locale.getDefault()); } /** * возвращает день */ public int getDay() { formatter.applyPattern("d"); return Integer.parseInt(formatter.format(fromDate)); } /** * @return Месяц */ public int getMonth() { formatter.applyPattern("M"); return Integer.parseInt(formatter.format(fromDate)); } /** * @return Год */ public int getYear() { formatter.applyPattern("y"); return Integer.parseInt(formatter.format(fromDate)); } /** * @return Час */ public int getHour() { formatter.applyPattern("h"); return Integer.parseInt(formatter.format(fromDate)); } public int getMinute() { formatter.applyPattern("m"); return Integer.parseInt(formatter.format(fromDate)); } }
import java.util.Scanner; import javax.swing.JOptionPane; import java.lang.Math; public class computingpie3 { public static void main(String[] args) { String termInput = JOptionPane.showInputDialog (null, "Please enter the number of terms you wish to view of PI ( or type exit) "); Scanner inputScanner = new Scanner (termInput); if (inputScanner.hasNextDouble()) { int mulNum1 = 2; int mulNum2 = 3; int mulNum3 = 4; int inputTerms = inputScanner.nextInt(); inputScanner.close() ; int terms = inputTerms ; double PI = 3.00; double count =0; while (count < terms ) { double multiplier = mulNum1*mulNum2*mulNum3; double division = 4/multiplier; if (count %2==0) { PI = PI + division ; } else { PI = PI - division; } mulNum1 +=2; mulNum2 +=2; mulNum3 +=2; count++; } JOptionPane.showMessageDialog (null,"PI to "+ inputTerms +" terms is " + PI); } else { JOptionPane.showMessageDialog (null,"No valid number(s) provided", "Error",JOptionPane.ERROR_MESSAGE); } } }
package com.example.billage.frontend.adapter; import android.widget.TextView; import com.example.billage.frontend.utils.DateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import androidx.databinding.BindingAdapter; public class TextBindingAdapter { @BindingAdapter({"setCalendarHeaderText"}) public static void setCalendarHeaderText(TextView view, Long date) { try { if (date != null) { view.setText(DateFormat.getDate(date, DateFormat.CALENDAR_HEADER_FORMAT)); } } catch (Exception e) { e.printStackTrace(); } } @BindingAdapter({"setCalendarHeaderEarnText"}) public static void setCalendarHeaderEarnText(TextView view, String earn) { try { if (earn != null ) { view.setText(earn); } } catch (Exception e) { e.printStackTrace(); } } @BindingAdapter({"setCalendarHeaderUsageText"}) public static void setCalendarHeaderUsageText(TextView view, String Usage) { try { if (Usage != null ) { view.setText(Usage); } } catch (Exception e) { e.printStackTrace(); } } @BindingAdapter({"setCalendarHeaderCountText"}) public static void setCalendarHeaderCountText(TextView view, String Count) { try { if (Count != null ) { view.setText(Count); } } catch (Exception e) { e.printStackTrace(); } } @BindingAdapter({"setDayText"}) public static void setDayText(TextView view, Calendar calendar) { try { if (calendar != null) { GregorianCalendar gregorianCalendar = new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0); view.setText(DateFormat.getDate(gregorianCalendar.getTimeInMillis(), DateFormat.DAY_FORMAT)); } } catch (Exception e) { e.printStackTrace(); } } @BindingAdapter({"setDayEarnText"}) public static void setDayEarnText(TextView view, String earn) { try { if (earn != null) { view.setText(earn); } } catch (Exception e) { e.printStackTrace(); } } @BindingAdapter({"setDayUsageText"}) public static void setDayUsageText(TextView view, String usage) { try { if (usage != null) { view.setText(usage); } } catch (Exception e) { e.printStackTrace(); } } }
/* * Copyright: (c) 2004-2011 Mayo Foundation for Medical Education and * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the * triple-shield Mayo logo are trademarks and service marks of MFMER. * * Except as contained in the copyright notice above, or as used to identify * MFMER as the author of this software, the trade names, trademarks, service * marks, or product names of the copyright holder shall not be used in * advertising, promotion or otherwise in connection with this software without * prior written authorization of the copyright holder. * * 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 edu.mayo.cts2.framework.core.test; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * The Class EnvironmentVariableSettingBean. * * @author <a href="mailto:kevin.peterson@mayo.edu">Kevin Peterson</a> */ public class EnvironmentVariableSettingBean implements InitializingBean { private String name; private String value; /* (non-Javadoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() throws Exception { Assert.notNull(name); Assert.notNull(value); System.setProperty(name, value); } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name the new name */ public void setName(String name) { this.name = name; } /** * Gets the value. * * @return the value */ public String getValue() { return value; } /** * Sets the value. * * @param value the new value */ public void setValue(String value) { this.value = value; } }
package MsgboxPack; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.util.ArrayList; import java.util.List; public class ScanWin extends JDialog { final long serialVersionUID = 1L; private JPanel contentPane; public JTextField scantxtfield; public JRadioButton uprbtn; public JRadioButton downbtn; public JButton scannextBtn = new JButton("Scan next"); public String searchingtxt = ""; public boolean downsearch = true; public boolean listavailable = false; public int currentindex = -1; public List<Integer> indexlist = new ArrayList(); public ScanWin() { setResizable(false); setTitle("Scan"); setAlwaysOnTop(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 491, 149); JPanel panel = new JPanel(); FlowLayout flowLayout = (FlowLayout) panel.getLayout(); flowLayout.setHgap(15); flowLayout.setVgap(15); getContentPane().add(panel, BorderLayout.CENTER); JLabel label = new JLabel("Scanning for:"); panel.add(label); label.setHorizontalAlignment(SwingConstants.CENTER); scantxtfield = new JTextField(); panel.add(scantxtfield); scantxtfield.setHorizontalAlignment(SwingConstants.CENTER); scantxtfield.setColumns(30); JPanel panel_2 = new JPanel(); panel.add(panel_2); final JRadioButton uprbtn = new JRadioButton("Up"); panel_2.add(uprbtn); final JRadioButton downrbtn = new JRadioButton("Down"); downrbtn.setSelected(true); panel_2.add(downrbtn); /* * Radio button action **/ uprbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { uprbtn.setSelected(true); downrbtn.setSelected(false); downsearch = false; } }); downrbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { downrbtn.setSelected(true); uprbtn.setSelected(false); downsearch = true; } }); /* * Radio button action end **/ scannextBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { searchingtxt = scantxtfield.getText(); } }); panel.add(scannextBtn); JButton closeBtn = new JButton("Close"); closeBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); panel.add(closeBtn); Box verticalBox = Box.createVerticalBox(); panel.add(verticalBox); } public String showScanDialog(JFrame owner) { setLocationRelativeTo(owner); setVisible(true); return searchingtxt; } }
package com.args.cineduniya; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; public class PrivacyPolicy_activity extends AppCompatActivity { WebView privacy_policy; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_privacy_policy_activity); //for the top left back button getSupportActionBar().setDisplayHomeAsUpEnabled(true); privacy_policy = findViewById(R.id.privacy); progressBar = findViewById(R.id.progressBarprivacy); privacy_policy.setWebViewClient(new WebViewClient() { //when web view starts loading @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { progressBar.setVisibility(View.VISIBLE); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { progressBar.setVisibility(View.GONE); super.onPageFinished(view, url); } }); privacy_policy.loadUrl("https://streamicmedia.web.app/privacy.html"); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
package com.formation.app; public class EmptyClass { }
package com.example.retail.services.fmcgproducts; import com.example.retail.controllers.retailer.fmcg_retailer.FMCGProductsRequestBody; import com.example.retail.models.discounts.CustomerOrdersDiscount; import com.example.retail.models.discounts.DiscountCalculator; import com.example.retail.services.discounts.CustomerOrdersDiscountServices; import com.example.retail.models.fmcgproducts.FMCGProducts; import com.example.retail.models.fmcgproducts.FMCGProductsInventory; import com.example.retail.repository.fmcgproducts.FMCGProductsInventoryRepository; import com.example.retail.repository.fmcgproducts.FMCGProductsRepository; import com.example.retail.models.taxutility.TaxCalculator; import com.example.retail.models.variantandcategory.VariantAndCategory; import com.example.retail.services.variantandcategory.VariantAndCategoryService; import com.example.retail.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; @Service public class FMCGProductsServices { @Autowired FMCGProductsRepository fmcgProductsRepository; @Autowired FMCGProductsInventoryRepository fmcgProductsInventoryRepository; @Autowired DiscountCalculator discountCalculator; @Autowired TaxCalculator taxCalculator; @Autowired CustomerOrdersDiscountServices customerOrdersDiscountServices; @Autowired JWTDetails jwtDetails; @Autowired Validations validations; @Autowired CreateResponse createResponse; @Autowired Utils utils; @Autowired VariantAndCategoryService variantAndCategoryService; @Autowired Constants constants; /** * Create a new FMCG product * @param request * @param fmcgProductsRequestBody * @param FMCGProductImages * @return FMCGProduct * @throws IOException */ public ResponseEntity<Object> addFmcgProduct(HttpServletRequest request, FMCGProductsRequestBody fmcgProductsRequestBody, List<MultipartFile> FMCGProductImages) throws IOException { /** * Create the FMCG product sub-id **/ String subId = utils.createFMCGProductSubId( fmcgProductsRequestBody.getFmcgProductManufacturer(), fmcgProductsRequestBody.getFmcgProductName(), fmcgProductsRequestBody.getFmcgProductVariant(), fmcgProductsRequestBody.getFmcgProductDenomination(), fmcgProductsRequestBody.getFmcgProductInventoryCostPrice(), fmcgProductsRequestBody.getFmcgProductInventoryFixedCost() ); /** * Perform validations **/ ValidationResponse validationResponse = validations.validateIfTaxesAvailable(fmcgProductsRequestBody.getFmcgProductApplicableTaxes()); if(validationResponse.getStatusCode() != validations.validationSuccessCode) { return ResponseEntity.status(validationResponse.getStatusCode()).body( validationResponse ); } /** * If subId already exists return error * **/ ValidationResponse productExists = validations.validateNewFMCGProductExists(subId); if(productExists.getStatusCode() != validations.validationSuccessCode) { return ResponseEntity.status(productExists.getStatusCode()).body( productExists ); } String fmcgProductAddedBy = jwtDetails.userName(request); LocalDate expiryDate = LocalDate.parse(fmcgProductsRequestBody.getFmcgProductInventoryExpiry()); /** * Create FMCGProducts object */ FMCGProducts fmcgProducts = new FMCGProducts(); // Add image for the item before saving to DB if (!FMCGProductImages.isEmpty()) { OpsResponse res = utils.saveFiles(FMCGProductImages, constants.saveImageSwitchCaseFMCGProducts); int errorCheck = res.getStatusCode(); if(errorCheck != utils.opsSuccess){ return ResponseEntity.status(errorCheck).body(res); } else { fmcgProducts.setFMCGProductImages(res.getStatusArray()); } } else { List<String> imagePlaceHolder = new ArrayList<>(); // TODO : give correct path to image placeholder imagePlaceHolder.add("src/main/resources/assets/veg-images/veg-image-placeholder.png"); fmcgProducts.setFMCGProductImages(imagePlaceHolder); } String itemCategorySubId = utils.createItemCategorySubId(fmcgProductsRequestBody.getItemCategory(), fmcgProductsRequestBody.getItemSubCategory()); /* Return error if item category does not exist */ ValidationResponse itemCategoryValidationStatus = validations.validateItemCategory(itemCategorySubId); if(itemCategoryValidationStatus.getStatusCode() != validations.validationSuccessCode) { return ResponseEntity.status(itemCategoryValidationStatus.getStatusCode()).body( itemCategoryValidationStatus ); } /**Create new VariandAndCategory**/ VariantAndCategory variantAndCategory = new VariantAndCategory(); variantAndCategory.setItemCategory(fmcgProductsRequestBody.getItemCategory()); variantAndCategory.setItemSubCategory(fmcgProductsRequestBody.getItemSubCategory()); variantAndCategory.setItemCategorySubId(itemCategorySubId); Optional<VariantAndCategory> optionalVariantAndCategory = variantAndCategoryService.findBySubId(itemCategorySubId); if(optionalVariantAndCategory.isPresent()) { /** If itemCategory and itemSubCategory (itemCategorySubId) is present add variant to existing variant list **/ List<String> variantList = new ArrayList<>(); variantList.add(fmcgProductsRequestBody.getFmcgProductVariant()); variantAndCategoryService.addVariants(itemCategorySubId, variantList); } else { List<String> variantList = new ArrayList<>(); /**Persist new variant and category**/ variantList.add(fmcgProductsRequestBody.getFmcgProductVariant()); variantAndCategory.setVariantsList(variantList); variantAndCategoryService.save(variantAndCategory); } fmcgProducts.setFmcgProductManufacturer(fmcgProductsRequestBody.getFmcgProductManufacturer()); fmcgProducts.setFmcgProductName(fmcgProductsRequestBody.getFmcgProductName()); fmcgProducts.setFmcgProductVariant(fmcgProductsRequestBody.getFmcgProductVariant()); fmcgProducts.setFmcgProductDescription(fmcgProductsRequestBody.getFmcgProductDescription()); fmcgProducts.setFmcgProductGenericName(fmcgProductsRequestBody.getFmcgProductGenericName()); fmcgProducts.setFmcgProductAlternateName(fmcgProductsRequestBody.getFmcgProductAlternateName()); fmcgProducts.setItemCategory(fmcgProductsRequestBody.getItemCategory()); fmcgProducts.setItemSubCategory(fmcgProductsRequestBody.getItemSubCategory()); fmcgProducts.setFmcgProductAvailable(fmcgProductsRequestBody.getFmcgProductAvailable()); fmcgProducts.setFmcgProductSellingPrice(fmcgProductsRequestBody.getFmcgProductSellingPrice()); fmcgProducts.setFmcgProductOfferedDiscount(fmcgProductsRequestBody.getFmcgProductOfferedDiscount()); fmcgProducts.setFmcgProductDiscountName(fmcgProductsRequestBody.getFmcgProductDiscountName()); /** * Check if discount exists **/ Optional<CustomerOrdersDiscount> proposedDiscount = customerOrdersDiscountServices.findByDiscountName(fmcgProductsRequestBody.getFmcgProductDiscountName()); /** * If discount does not exist, set the discount proposed in the payload **/ Float discountedPrice = 0F; if(proposedDiscount.isEmpty()) { discountedPrice = discountCalculator.calcDiscountedPrice( fmcgProductsRequestBody.getFmcgProductSellingPrice(), fmcgProductsRequestBody.getFmcgProductOfferedDiscount() ); } else { /** * Calculate the discounted price from the DB record **/ discountedPrice = discountCalculator.calcDiscountedPrice( fmcgProductsRequestBody.getFmcgProductSellingPrice(), proposedDiscount.get().getDiscountPercentage() ); } fmcgProducts.setFmcgProductDiscountedPrice(discountedPrice); fmcgProducts.setFmcgProductApplicableTaxes(fmcgProductsRequestBody.getFmcgProductApplicableTaxes()); fmcgProducts.setFmcgProductTaxedPrice(taxCalculator.calcAmountAfterTax(fmcgProductsRequestBody.getFmcgProductApplicableTaxes(), discountedPrice)); fmcgProducts.setFmcgProductQuantity(fmcgProductsRequestBody.getFmcgProductQuantity()); fmcgProducts.setFmcgProductMeasurementUnit(fmcgProductsRequestBody.getFmcgProductMeasurementUnit()); fmcgProducts.setFmcgProductDenomination(fmcgProductsRequestBody.getFmcgProductDenomination()); fmcgProducts.setFmcgProductSubId(subId); /** * Create FMCG products inventory object **/ FMCGProductsInventory fmcgProductsInventory = new FMCGProductsInventory(); fmcgProductsInventory.setFmcgProductInventoryCostPrice(fmcgProductsRequestBody.getFmcgProductInventoryCostPrice()); fmcgProductsInventory.setFmcgProductInventoryFixedCost(fmcgProductsRequestBody.getFmcgProductInventoryFixedCost()); /* * We set the selling price in the inventory excluding the tax and including the discounts to calculate the absolute profits */ fmcgProductsInventory.setFmcgProductInventorySellingPrice(discountedPrice); fmcgProductsInventory.setFmcgProductInventoryExpiry(expiryDate); fmcgProductsInventory.setFmcgProductInventoryAddedBy(fmcgProductAddedBy); fmcgProductsInventory.setFmcgProductInventoryAddedOn(LocalDateTime.now()); fmcgProductsInventory.setFmcgProductInventoryAddedQty(fmcgProductsRequestBody.getFmcgProductInventoryAddedQty()); fmcgProductsInventory.setSuppliers(fmcgProductsRequestBody.getSuppliers()); fmcgProductsInventory.setFmcgProductSubId(subId); fmcgProductsInventory.setFmcgProductInventoryAddedQty(fmcgProductsRequestBody.getFmcgProductQuantity()); fmcgProductsRepository.save(fmcgProducts); fmcgProductsInventoryRepository.save(fmcgProductsInventory); Map<String, Object> res = new HashMap<>(); res.put("FMCGProduct", fmcgProducts); res.put("FMCGProductInventory", fmcgProductsInventory); List< Map<String, ?>> finalRes = new ArrayList<>(); finalRes.add(res); return ResponseEntity.status(201).body( createResponse.createSuccessResponse( 201, "FMCG product created", finalRes ) ); } public List<?> findAllFMCGProductsWithInventory() { List<FMCGProducts> FMCGProducts = fmcgProductsRepository.findAll(); List<FMCGProductsInventory> FMCGProductsInventories = fmcgProductsInventoryRepository.findAll(); List<Map<String, ?>> finalRes = new ArrayList<>(); FMCGProducts.forEach((FMCGProduct) -> { FMCGProductsInventories.forEach((FMCGProductsInventory) -> { if(FMCGProduct.getFmcgProductSubId().equals(FMCGProductsInventory.getFmcgProductSubId())) { Map<String, Object> resObject = new HashMap<>(); resObject.put(constants.FMCGProduct, FMCGProduct); resObject.put(constants.FMCGProductInventory, FMCGProductsInventory); finalRes.add(resObject); } }); }); return finalRes; } public List<FMCGProducts> findAll () { return fmcgProductsRepository.findAll(); } /** * Update qty in FMCGProducts table and FMCGProductsInventory table * For MVP we update the id of the user who last updates the inventory and do not maintain each update record with * relation to which user and what time */ public Map<String, ?> increamentFMCGProductQuantity (Float fmcgProductQuantity, String fmcgProductInventoryAddedBy, String fmcgProductSubId) { LocalDateTime localDateTime = LocalDateTime.now(); FMCGProducts fmcgProducts = fmcgProductsRepository.increamentFMCGProductQty(fmcgProductQuantity, fmcgProductSubId); FMCGProductsInventory fmcgProductsInventory = fmcgProductsInventoryRepository.increamentFMCGProductsInventoryQty( fmcgProductQuantity, fmcgProductInventoryAddedBy, localDateTime, fmcgProductSubId ); Map<String, Object> res = new HashMap<>(); res.put(constants.FMCGProduct, fmcgProducts); res.put(constants.FMCGProductInventory, fmcgProductsInventory); return res; } }
package com.amsu.intelligentinsole.activity; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.amap.api.maps.AMapUtils; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.PolylineOptions; import com.amap.api.maps2d.LocationSource; import com.amap.api.trace.TraceLocation; import com.amsu.intelligentinsole.R; import com.amsu.intelligentinsole.bean.PathRecord; import com.amsu.intelligentinsole.common.BaseActivity; import com.amsu.intelligentinsole.map.DbAdapter; import com.amsu.intelligentinsole.map.Util; import com.amsu.intelligentinsole.util.MyUtil; import com.amsu.intelligentinsole.util.RunTimerTaskUtil; import java.util.ArrayList; import java.util.List; public class RunningActivity extends BaseActivity implements AMapLocationListener { private static final String TAG = "RunningActivity"; private RelativeLayout rl_run_stop; private RelativeLayout rl_run_continue; private TextView tv_run_time; private RunTimerTaskUtil runTimerTaskUtil; public static Activity activity; //声明mLocationOption对象 public AMapLocationClientOption mLocationOption = null; public static AMapLocationClient mlocationClient; public static PathRecord record; //存放未纠偏轨迹记录信息 private List<TraceLocation> mTracelocationlist = new ArrayList<>(); //偏轨后轨迹 public static long mStartTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_running); } @Override protected void initView() { activity = this; TextView tv_run_mileage = (TextView) findViewById(R.id.tv_run_mileage); tv_run_time = (TextView) findViewById(R.id.tv_run_time); TextView tv_run_stride = (TextView) findViewById(R.id.tv_run_stride); TextView tv_run_avespeed = (TextView) findViewById(R.id.tv_run_avespeed); TextView tv_run_freqstride = (TextView) findViewById(R.id.tv_run_freqstride); TextView tv_run_maxspeed = (TextView) findViewById(R.id.tv_run_maxspeed); TextView tv_run_minspeed = (TextView) findViewById(R.id.tv_run_minspeed); TextView tv_run_kcal = (TextView) findViewById(R.id.tv_run_kcal); TextView tv_run_sptop = (TextView) findViewById(R.id.tv_run_sptop); TextView tv_run_lock = (TextView) findViewById(R.id.tv_run_lock); ImageView iv_run_map = (ImageView) findViewById(R.id.iv_run_map); TextView tv_run_continue = (TextView) findViewById(R.id.tv_run_continue); TextView tv_run_analysis = (TextView) findViewById(R.id.tv_run_analysis); TextView tv_run_end = (TextView) findViewById(R.id.tv_run_end); rl_run_stop = (RelativeLayout) findViewById(R.id.rl_run_stop); rl_run_continue = (RelativeLayout) findViewById(R.id.rl_run_continue); MyOnClickListener myOnClickListener = new MyOnClickListener(); tv_run_lock.setOnClickListener(myOnClickListener); iv_run_map.setOnClickListener(myOnClickListener); tv_run_continue.setOnClickListener(myOnClickListener); tv_run_analysis.setOnClickListener(myOnClickListener); tv_run_end.setOnClickListener(myOnClickListener); runTimerTaskUtil = new RunTimerTaskUtil(this); runTimerTaskUtil.setOnTimeChangeListerner("HH:mm:ss", 1000, new RunTimerTaskUtil.OnTimeChangeListerner() { @Override public String onFormatStringTimeChange(String formatTime) { //Log.i(TAG,"formatTime:"+formatTime); tv_run_time.setText(formatTime); return null; } }); runTimerTaskUtil.startTime(); tv_run_sptop.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { rl_run_stop.setVisibility(View.GONE); rl_run_continue.setVisibility(View.VISIBLE); runTimerTaskUtil.stopTime(); return false; } }); } @Override protected void initData() { mlocationClient = new AMapLocationClient(this); mLocationOption = new AMapLocationClientOption(); mlocationClient.setLocationListener(this); mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); mLocationOption.setInterval(2000); mlocationClient.setLocationOption(mLocationOption); mlocationClient.startLocation(); if (record==null){ record = new PathRecord(); mStartTime = System.currentTimeMillis(); record.setDate(MyUtil.getCueMapDate(mStartTime)); } } @Override public void onLocationChanged(AMapLocation aMapLocation) { Log.i(TAG,"onLocationChanged:"+aMapLocation.toString()); if (aMapLocation!=null){ record.addpoint(aMapLocation); mTracelocationlist.add(Util.parseTraceLocation(aMapLocation)); } } class MyOnClickListener implements View.OnClickListener{ @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_run_lock: break; case R.id.iv_run_map: startActivity(new Intent(RunningActivity.this,RunTrailMapActivity.class)); break; case R.id.tv_run_continue: rl_run_stop.setVisibility(View.VISIBLE); rl_run_continue.setVisibility(View.GONE); if (runTimerTaskUtil!=null){ runTimerTaskUtil.startTime(); } break; case R.id.tv_run_analysis: startActivity(new Intent(RunningActivity.this, SportAnalysisActivity.class)); break; case R.id.tv_run_end: if (runTimerTaskUtil!=null){ runTimerTaskUtil.destoryTime(); runTimerTaskUtil = null; } long createrecord = Util.saveRecord(record.getPathline(), record.getDate(),RunningActivity.this,mStartTime); mlocationClient.stopLocation(); Intent intent = new Intent(RunningActivity.this, SportFinishActivity.class); if (createrecord!=-1){ intent.putExtra("createrecord",createrecord); } startActivity(intent); finish(); break; } } } @Override protected void onDestroy() { super.onDestroy(); mlocationClient.stopLocation(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK ){ return false; } return super.onKeyDown(keyCode, event); } }
package practice; public class MethodOverridingParentClass { /* Declaring a method in child class which is already present in the parent class is called Method Overriding. In simple words, overriding means to override the functionality of an existing method. In this case, if we call the method with child class object, then the child class method is called. To call the parent class method we have to use super keyword. Assume we have multiple child classes.In case one of the child classes want to use the parent class method and other class want to use their own implementation then we can use overriding feature. Method overriding is also known as runtime polymorphism. Let’s see why we call it as runtime polymorphism. ParentClass obj = new ChildClass(); When a parent class reference refers to the child class object then the call to the overridden method is determined at the runtime.So it is called runtime polymorphism.It is because during method call which method (parent class or child class) is to be executed is determined by the type of an object. */ public void myMethod(){ System.out.println("I am a method from Parent Class"); } }
package com.yixin.dsc.dto.query; import java.io.Serializable; import java.util.Date; /** * 结算放款信息DTO * Package : com.yixin.dsc.dto.query * * @author YixinCapital -- wangwenlong * 2018年9月10日 下午7:48:48 * */ public class DscSettleLoanInfoDto implements Serializable { private static final long serialVersionUID = -5949694255890191496L; /** * 第一个还款日 */ private String firstRepayDate; /** * 0:未放款,1:放款成功 */ private String isLoan; /** * 1:允许推车,0:不允许推车 */ private String isAllowed; private Date firstRepayDateTime; public String getIsAllowed() { return isAllowed; } public void setIsAllowed(String isAllowed) { this.isAllowed = isAllowed; } public Date getFirstRepayDateTime() { return firstRepayDateTime; } public void setFirstRepayDateTime(Date firstRepayDateTime) { this.firstRepayDateTime = firstRepayDateTime; } public String getFirstRepayDate() { return firstRepayDate; } public void setFirstRepayDate(String firstRepayDate) { this.firstRepayDate = firstRepayDate; } public String getIsLoan() { return isLoan; } public void setIsLoan(String isLoan) { this.isLoan = isLoan; } }
package com.tencent.mm.ui.chatting.g; import android.view.View; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.ui.chatting.a.b.a; class a$b extends a { TextView eCn; final /* synthetic */ a tXW; public a$b(a aVar, View view) { this.tXW = aVar; super(view); this.eCn = (TextView) view.findViewById(R.h.fav_detail); } }
package io.dashapp.dashembed; import android.os.Parcel; import android.os.Parcelable; public class Config implements Parcelable { // A unique identifier for the DASH Foundation (provided by DASH) public String appId; public Boolean useDevelopmentServers; public Config(String appId) { this.appId = appId; this.useDevelopmentServers = false; } public Config(String appId, Boolean useDevelopmentServers) { this.appId = appId; this.useDevelopmentServers = useDevelopmentServers; } protected Config(Parcel in) { appId = in.readString(); byte tmpUseDevelopmentServers = in.readByte(); useDevelopmentServers = tmpUseDevelopmentServers == 0 ? null : tmpUseDevelopmentServers == 1; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(appId); dest.writeByte((byte) (useDevelopmentServers == null ? 0 : useDevelopmentServers ? 1 : 2)); } @Override public int describeContents() { return 0; } public static final Creator<Config> CREATOR = new Creator<Config>() { @Override public Config createFromParcel(Parcel in) { return new Config(in); } @Override public Config[] newArray(int size) { return new Config[size]; } }; }
package co.th.aten.network.web; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.annotation.PostConstruct; import javax.enterprise.inject.Instance; import javax.faces.bean.SessionScoped; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.jboss.seam.international.status.MessageFactory; import org.jboss.seam.international.status.Messages; import org.jboss.solder.logging.Logger; import org.richfaces.event.FileUploadEvent; import org.richfaces.model.UploadedFile; import co.th.aten.network.control.CustomerControl; import co.th.aten.network.entity.AddressAmphures; import co.th.aten.network.entity.AddressDistricts; import co.th.aten.network.entity.AddressProvinces; import co.th.aten.network.entity.MasterBank; import co.th.aten.network.entity.MasterNationality; import co.th.aten.network.entity.MasterOfficialDocument; import co.th.aten.network.entity.MemberCustomer; import co.th.aten.network.entity.UserLogin; import co.th.aten.network.i18n.AppBundleKey; import co.th.aten.network.model.DropDownModel; import co.th.aten.network.model.UploadedImage; import co.th.aten.network.producer.DBDefault; import co.th.aten.network.security.annotation.Authenticated; import co.th.aten.network.util.StringUtil; //@ViewScoped @SessionScoped @Named public class EditCustomerController implements Serializable{ /** * */ private static final long serialVersionUID = 5443351151396868724L; @Inject Logger log; @Inject @Authenticated private Instance<UserLogin> user; @Inject private MessageFactory factory; @Inject private Messages messages; @Inject private FacesContext facesContext; @Inject @DBDefault private EntityManager em; private long customerId; private String searchCustomer; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.US); @Inject private CustomerControl customerControl; private String memberStr; private String titleName; private String starTitleName; private String firstName; private String starFirstName; private String businessName; private String starBusinessName; private int showName; private Date regisDate; private int sex; private String starSex; private String starBirthDay; private Date birthDay; private int nationality; private List<DropDownModel> nationalityList; private int officialDocumentId; private List<DropDownModel> officialDocumentList; private String starPersonalId; private String personalId; private String companyID; private String telephone; private String starMobile; private String mobile; private String lineId; private String email; private String starUpperLineId; private String upperLineMemberId; private String starUpperLineName; private String upperLineName; private String starSide; private int side; private String starRecomendId; private int recomendId; private String recomendStrId; private String starRecomendName; private String recomendName; private String addressNo; private String addressBuilding; private String addressVillage; private String addressLane; private String addressRoad; private String starProvince; private int provinceId; private List<DropDownModel> provinceList; private String starAmphur; private int amphurId; private List<DropDownModel> amphurList; private String starDistrict; private int districtId; private List<DropDownModel> districtList; private String addressPostCode; private String provinceStr; private String amphurStr; private String districtStr; private boolean chkNationality; private String addressNoSendDoc; private String addressBuildingSendDoc; private String addressVillageSendDoc; private String addressLaneSendDoc; private String addressRoadSendDoc; private String starProvinceSendDoc; private int provinceIdSendDoc; private List<DropDownModel> provinceSendDocList; private String starAmphurSendDoc; private int amphurIdSendDoc; private List<DropDownModel> amphurSendDocList; private String starDistrictSendDoc; private int districtIdSendDoc; private List<DropDownModel> districtSendDocList; private String addressPostCodeSendDoc; private int bankId; private List<DropDownModel> bankList; private String branch; private int accType; private String accNo; private String accName; private String remark; private boolean chkSave; private boolean chkSameAddress; // image member private UploadedImage uploadedImage; // document private UploadedImage uploadedApplication; private UploadedImage uploadedIdCard; private UploadedImage uploadedBookBank; @PostConstruct public void init(){ log.info("init method EditCustomerController"); clearData(); long startTime = System.currentTimeMillis(); chkSave = false; try{ if(user.get().getCustomerId()!=null){ MemberCustomer customer = user.get().getCustomerId(); if(customer!=null){ memberStr = customer.getCustomerMember(); titleName = customer.getTitleName(); starTitleName = ""; firstName = customer.getFirstName(); starFirstName = ""; businessName = customer.getBusinessName(); showName = StringUtil.n2b(customer.getShowNameStatus()); starBusinessName = ""; regisDate = customer.getRegisDate(); sex = StringUtil.n2b(customer.getSex()); starSex = ""; starBirthDay = ""; birthDay = customer.getBirthDay(); nationalityList = new ArrayList<DropDownModel>(); List<MasterNationality> masterNationalityList = em.createQuery("From MasterNationality Order By nationId asc",MasterNationality.class).getResultList(); if(masterNationalityList!=null){ for(MasterNationality nation:masterNationalityList){ DropDownModel model = new DropDownModel(); model.setIntKey(nation.getNationId()); model.setThLabel(StringUtil.n2b(nation.getDescTh())); model.setEnLabel(StringUtil.n2b(nation.getDescEn())); nationalityList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); nationalityList.add(0,model); if(customer.getNationId()!=null){ nationality = StringUtil.n2b(customer.getNationId().getNationId()); }else{ nationality = -1; } } officialDocumentList = new ArrayList<DropDownModel>(); List<MasterOfficialDocument> masterOfficialDocumentList = em.createQuery("From MasterOfficialDocument Order By offDocId asc",MasterOfficialDocument.class).getResultList(); if(masterOfficialDocumentList!=null){ for(MasterOfficialDocument officDoc:masterOfficialDocumentList){ DropDownModel model = new DropDownModel(); model.setIntKey(StringUtil.n2b(officDoc.getOffDocId())); model.setThLabel(StringUtil.n2b(officDoc.getDescTh())); model.setEnLabel(StringUtil.n2b(officDoc.getDescEn())); officialDocumentList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); officialDocumentList.add(0,model); if(customer.getOfficialDocumentId()!=null){ officialDocumentId = StringUtil.n2b(customer.getOfficialDocumentId().getOffDocId()); }else{ officialDocumentId = -1; } } starPersonalId = ""; personalId = customer.getPersonalId(); companyID = customer.getCompanyID(); telephone = customer.getTelephone(); mobile = customer.getMobile(); lineId = customer.getLineId(); email = customer.getEmail(); if(customer.getUpperId()!=null && customer.getUpperId()!=0){ MemberCustomer customerUpper = em.find(MemberCustomer.class, customer.getUpperId()); if(customerUpper!=null){ upperLineMemberId = customerUpper.getCustomerMember(); upperLineName = customerControl.genNameMenber(customerUpper); side = (customerUpper.getLowerLeftId()!=null &&customerUpper.getLowerLeftId()==customer.getCustomerId()) ?1:2; } }else{ upperLineMemberId = ""; upperLineName = ""; side = 0; } starUpperLineId = ""; starUpperLineName = ""; starSide = ""; starRecomendId = ""; starRecomendName = ""; if(customer.getRecommendId()!=null && customer.getRecommendId()!=0){ MemberCustomer customerRecomment = em.find(MemberCustomer.class, customer.getRecommendId()); if(customerRecomment!=null){ recomendStrId = customerRecomment.getCustomerMember(); recomendName = customerControl.genNameMenber(customerRecomment); } }else{ recomendStrId = ""; recomendId = 0; recomendName = ""; } addressNo = customer.getAddressNo(); addressBuilding = customer.getAddressBuilding(); addressVillage = customer.getAddressVillage(); addressLane = customer.getAddressLane(); addressRoad = customer.getAddressRoad(); starProvince = ""; provinceId = customer.getProvinceId()!=null?customer.getProvinceId():-1; starAmphur = ""; amphurId = customer.getAmphurId()!=null?customer.getAmphurId():-1; starDistrict = ""; districtId = customer.getDistrictId()!=null?customer.getDistrictId():-1; if(districtId!=-1){ AddressDistricts addressDistricts = em.find(AddressDistricts.class, new Integer(districtId)); if(addressDistricts!=null && addressDistricts.getPostCode()!=null){ addressPostCode = StringUtil.n2b(addressDistricts.getPostCode()); }else{ addressPostCode = StringUtil.n2b(customer.getPostCodeStr()); } } provinceStr = StringUtil.n2b(customer.getProvinceStr()); amphurStr = StringUtil.n2b(customer.getAmphurStr()); districtStr = StringUtil.n2b(customer.getDistrictStr()); // chkSameAddress = (customer.getChkSameAddress()!=null && customer.getChkSameAddress()==1)?true:false; // addressNoSendDoc = customer.getAddressNoSendDoc(); // addressBuildingSendDoc = customer.getAddressBuildingSendDoc(); // addressVillageSendDoc = customer.getAddressVillageSendDoc(); // addressLaneSendDoc = customer.getAddressLaneSendDoc(); // addressRoadSendDoc = customer.getAddressRoadSendDoc(); // starProvinceSendDoc = ""; // provinceIdSendDoc = customer.getProvinceIdSendDoc()!=null?customer.getProvinceIdSendDoc():-1; // starAmphurSendDoc = ""; // amphurIdSendDoc = customer.getAmphurIdSendDoc()!=null?customer.getAmphurIdSendDoc():-1; // starDistrictSendDoc = ""; // districtIdSendDoc = customer.getDistrictIdSendDoc()!=null?customer.getDistrictIdSendDoc():-1; // if(districtIdSendDoc!=-1){ // AddressDistricts addressDistricts = em.find(AddressDistricts.class, new Integer(districtIdSendDoc)); // if(addressDistricts!=null){ // addressPostCodeSendDoc = StringUtil.n2b(addressDistricts.getPostCode()); // } // } bankId = customer.getBankId()!=null?customer.getBankId():-1; branch = customer.getBankBranch(); accType = StringUtil.n2b(customer.getBankaccountType()); accNo = customer.getBankaccountNo(); accName = customer.getBankaccountName(); remark = customer.getRemark(); if(customer.getImageMember()!=null){ uploadedImage = new UploadedImage(); uploadedImage.setData(customer.getImageMember()); uploadedImage.setLength(customer.getImageMember().length); uploadedImage.setName(StringUtil.n2b(customer.getImageMemberName())); } if(customer.getDocumentApplication()!=null){ uploadedApplication = new UploadedImage(); uploadedApplication.setData(customer.getDocumentApplication()); uploadedApplication.setLength(customer.getDocumentApplication().length); uploadedApplication.setName(StringUtil.n2b(customer.getDocumentApplicationName())); } if(customer.getDocumentIdCard()!=null){ uploadedIdCard = new UploadedImage(); uploadedIdCard.setData(customer.getDocumentIdCard()); uploadedIdCard.setLength(customer.getDocumentIdCard().length); uploadedIdCard.setName(StringUtil.n2b(customer.getDocumentIdCardName())); } if(customer.getDocumentBookBank()!=null){ uploadedBookBank = new UploadedImage(); uploadedBookBank.setData(customer.getDocumentBookBank()); uploadedBookBank.setLength(customer.getDocumentBookBank().length); uploadedBookBank.setName(StringUtil.n2b(customer.getDocumentBookBankName())); } onChangeNationality(); onKeypress(); }else{ chkSave = true; } } }catch(Exception e){ e.printStackTrace(); } long startTime2 = System.currentTimeMillis(); provinceList = new ArrayList<DropDownModel>(); provinceSendDocList = new ArrayList<DropDownModel>(); List<AddressProvinces> provinList = em.createQuery("From AddressProvinces",AddressProvinces.class).getResultList(); if(provinList!=null){ for(AddressProvinces provin:provinList){ DropDownModel model = new DropDownModel(); model.setIntKey(provin.getProvinceId()); model.setThLabel(provin.getProvinceName()); model.setEnLabel(provin.getProvinceNameEng()); provinceList.add(model); provinceSendDocList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); provinceList.add(0,model); provinceSendDocList.add(0,model); } amphurList = new ArrayList<DropDownModel>(); amphurSendDocList = new ArrayList<DropDownModel>(); List<AddressAmphures> dataList = em.createQuery("From AddressAmphures Where provinceId=:provinceId" ,AddressAmphures.class) .setParameter("provinceId", provinceId) .getResultList(); if(dataList!=null){ for(AddressAmphures data:dataList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getAmphurId()); model.setThLabel(data.getAmphurName()); model.setEnLabel(data.getAmphurNameEng()); amphurList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); amphurList.add(0,model); } dataList = em.createQuery("From AddressAmphures Where provinceId=:provinceId" ,AddressAmphures.class) .setParameter("provinceId", provinceIdSendDoc) .getResultList(); if(dataList!=null){ for(AddressAmphures data:dataList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getAmphurId()); model.setThLabel(data.getAmphurName()); model.setEnLabel(data.getAmphurNameEng()); amphurSendDocList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); amphurSendDocList.add(0,model); } districtList = new ArrayList<DropDownModel>(); districtSendDocList = new ArrayList<DropDownModel>(); List<AddressDistricts> dataDisList = em.createQuery("From AddressDistricts " + " Where amphurId=:amphurId " + " And provinceId=:provinceId " ,AddressDistricts.class) .setParameter("amphurId", amphurId) .setParameter("provinceId", provinceId) .getResultList(); if(dataDisList!=null){ for(AddressDistricts data:dataDisList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getDistrictId()); model.setThLabel(data.getDistrictName()); model.setEnLabel(data.getDistrictNameEng()); districtList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); districtList.add(0,model); } dataDisList = em.createQuery("From AddressDistricts " + " Where amphurId=:amphurId " + " And provinceId=:provinceId " ,AddressDistricts.class) .setParameter("amphurId", amphurIdSendDoc) .setParameter("provinceId", provinceIdSendDoc) .getResultList(); if(dataDisList!=null){ for(AddressDistricts data:dataDisList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getDistrictId()); model.setThLabel(data.getDistrictName()); model.setEnLabel(data.getDistrictNameEng()); districtSendDocList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); districtSendDocList.add(0,model); } long endTime2 = System.currentTimeMillis(); log.info("SQL Time = "+((endTime2-startTime2)/1000d)+"s"); bankList = new ArrayList<DropDownModel>(); List<MasterBank> masterBankList = em.createQuery("From MasterBank",MasterBank.class).getResultList(); if(masterBankList!=null){ for(MasterBank data:masterBankList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getBankCode()); model.setThLabel(data.getBankName()); model.setEnLabel(data.getBankName()); bankList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); bankList.add(0,model); } long endTime = System.currentTimeMillis(); log.info("init method EditCustomerController Time = "+((endTime-startTime)/1000d)+"s"); } public void onChangeProvince(){ amphurList = new ArrayList<DropDownModel>(); if(provinceId!=-1){ List<AddressAmphures> dataList = em.createQuery("From AddressAmphures Where provinceId=:provinceId" ,AddressAmphures.class) .setParameter("provinceId", provinceId) .getResultList(); if(dataList!=null){ for(AddressAmphures data:dataList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getAmphurId()); model.setThLabel(data.getAmphurName()); model.setEnLabel(data.getAmphurNameEng()); amphurList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); amphurList.add(0,model); amphurId = -1; } } } public void onChangeAmphur(){ districtList = new ArrayList<DropDownModel>(); if(amphurId!=-1){ List<AddressDistricts> dataList = em.createQuery("From AddressDistricts " + " Where amphurId=:amphurId " + " And provinceId=:provinceId " ,AddressDistricts.class) .setParameter("amphurId", amphurId) .setParameter("provinceId", provinceId) .getResultList(); if(dataList!=null){ for(AddressDistricts data:dataList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getDistrictId()); model.setThLabel(data.getDistrictName()); model.setEnLabel(data.getDistrictNameEng()); districtList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); districtList.add(0,model); districtId = -1; } } } public void onChangeDistrict(){ addressPostCode = ""; if(districtId!=-1){ AddressDistricts addressDistricts = em.find(AddressDistricts.class, new Integer(districtId)); if(addressDistricts!=null){ addressPostCode = StringUtil.n2b(addressDistricts.getPostCode()); } } } public void onChangeProvinceSendDoc(){ amphurSendDocList = new ArrayList<DropDownModel>(); if(provinceIdSendDoc!=-1){ List<AddressAmphures> dataList = em.createQuery("From AddressAmphures Where provinceId=:provinceId" ,AddressAmphures.class) .setParameter("provinceId", provinceIdSendDoc) .getResultList(); if(dataList!=null){ for(AddressAmphures data:dataList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getAmphurId()); model.setThLabel(data.getAmphurName()); model.setEnLabel(data.getAmphurNameEng()); amphurSendDocList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); amphurSendDocList.add(0,model); amphurIdSendDoc = -1; } } } public void onChangeAmphurSendDoc(){ districtSendDocList = new ArrayList<DropDownModel>(); if(amphurIdSendDoc !=-1){ List<AddressDistricts> dataList = em.createQuery("From AddressDistricts " + " Where amphurId=:amphurId " + " And provinceId=:provinceId " ,AddressDistricts.class) .setParameter("amphurId", amphurIdSendDoc) .setParameter("provinceId", provinceIdSendDoc) .getResultList(); if(dataList!=null){ for(AddressDistricts data:dataList){ DropDownModel model = new DropDownModel(); model.setIntKey(data.getDistrictId()); model.setThLabel(data.getDistrictName()); model.setEnLabel(data.getDistrictNameEng()); districtSendDocList.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); districtSendDocList.add(0,model); districtIdSendDoc = -1; } } } public void onChangeDistrictSendDoc(){ addressPostCodeSendDoc = ""; if(districtIdSendDoc!=-1){ AddressDistricts addressDistricts = em.find(AddressDistricts.class, new Integer(districtIdSendDoc)); if(addressDistricts!=null){ addressPostCodeSendDoc = StringUtil.n2b(addressDistricts.getPostCode()); } } } public void paint(OutputStream stream, Object object){ try{ if(uploadedImage!=null){ stream.write(uploadedImage.getData()); stream.close(); } }catch(Exception e){ log.info("Error paint : "+e.getMessage()); } } public void listenerUploadAppication(FileUploadEvent event){ try{ UploadedFile uploadedFile = event.getUploadedFile(); uploadedApplication = new UploadedImage(); uploadedApplication.setLength(uploadedFile.getData().length); uploadedApplication.setName(uploadedFile.getName()); uploadedApplication.setData(uploadedFile.getData()); }catch(Exception e){ e.printStackTrace(); } } public void listenerUploadIdCard(FileUploadEvent event){ try{ UploadedFile uploadedFile = event.getUploadedFile(); uploadedIdCard = new UploadedImage(); uploadedIdCard.setLength(uploadedFile.getData().length); uploadedIdCard.setName(uploadedFile.getName()); uploadedIdCard.setData(uploadedFile.getData()); }catch(Exception e){ e.printStackTrace(); } } public void listenerUploadBookBank(FileUploadEvent event){ try{ UploadedFile uploadedFile = event.getUploadedFile(); uploadedBookBank = new UploadedImage(); uploadedBookBank.setLength(uploadedFile.getData().length); uploadedBookBank.setName(uploadedFile.getName()); uploadedBookBank.setData(uploadedFile.getData()); }catch(Exception e){ e.printStackTrace(); } } public void listener(FileUploadEvent event){ try{ UploadedFile uploadedFile = event.getUploadedFile(); uploadedImage = new UploadedImage(); uploadedImage.setLength(uploadedFile.getData().length); uploadedImage.setName(uploadedFile.getName()); uploadedImage.setData(uploadedFile.getData()); }catch(Exception e){ e.printStackTrace(); } } public void findRecomend(){ log.info("##### searchRecomend()"); log.info("##### recomendStrId = "+recomendStrId); recomendName = ""; if(recomendStrId!=null && recomendStrId.trim().length()>0){ MemberCustomer customerRecommend = null; try{ customerRecommend = (MemberCustomer)em.createQuery("From MemberCustomer " + " Where customerMember=:customerMember") .setParameter("customerMember", recomendStrId) .getSingleResult(); }catch(Exception e){ log.info("Error : "+e.getMessage()); } if(customerRecommend!=null){ recomendId = customerRecommend.getCustomerId(); recomendName = customerControl.genNameMenber(customerRecommend); }else{ messages.info(new AppBundleKey("error.label.notFoundMember",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage())); } }else{ messages.info(new AppBundleKey("error.label.notKeyData",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage())); } } private void clearData(){ chkSave = true; memberStr = ""; titleName = ""; starTitleName = ""; firstName = ""; starFirstName = ""; businessName = ""; starBusinessName = ""; showName = 0; regisDate = null; sex = 0; starSex = ""; starBirthDay = ""; birthDay = null; nationality = -1; officialDocumentId = -1; starPersonalId = ""; personalId = ""; companyID = ""; telephone = ""; mobile = ""; lineId = ""; email = ""; starUpperLineId = ""; upperLineMemberId = ""; starUpperLineName = ""; upperLineName = ""; starSide = ""; side = 0; starRecomendId = ""; recomendStrId = ""; recomendId = 0; starRecomendName = ""; recomendName = ""; addressNo = ""; addressBuilding = ""; addressVillage = ""; addressLane = ""; addressRoad = ""; starProvince = ""; provinceId = -1; starAmphur = ""; amphurId = -1; starDistrict = ""; districtId = -1; addressPostCode = ""; provinceStr = ""; amphurStr = ""; districtStr = ""; addressNoSendDoc = ""; addressBuildingSendDoc = ""; addressVillageSendDoc = ""; addressLaneSendDoc = ""; addressRoadSendDoc = ""; starProvinceSendDoc = ""; provinceIdSendDoc = -1; starAmphurSendDoc = ""; amphurIdSendDoc = -1; starDistrictSendDoc = ""; districtIdSendDoc = -1; addressPostCodeSendDoc = ""; bankId = -1; branch = ""; accType = 1; accNo = ""; accName = ""; remark = ""; uploadedImage = null; uploadedApplication = null; uploadedIdCard = null; uploadedBookBank = null; amphurList = null; districtList = null; amphurSendDocList = null; districtSendDocList = null; } public void cancleEditMember(){ log.info("##### cancleEditMember()"); log.info("##### memberStr = "+memberStr); init(); // clearData(); } public void sameAddress(){ log.info("##### sameAddress()"); log.info("##### chkSameAddress = "+chkSameAddress); log.info("##### addressNo = "+addressNo); log.info("##### addressBuilding = "+addressBuilding); log.info("##### addressVillage = "+addressVillage); log.info("##### addressLane = "+addressLane); log.info("##### addressRoad = "+addressRoad); log.info("##### provinceId = "+provinceId); log.info("##### amphurId = "+amphurId); log.info("##### districtId = "+districtId); log.info("##### addressPostCode = "+addressPostCode); if(chkSameAddress){ log.info("TRUE"); addressNoSendDoc = addressNo; addressBuildingSendDoc = addressBuilding; addressVillageSendDoc = addressVillage; addressLaneSendDoc = addressLane; addressRoadSendDoc = addressRoad; starProvinceSendDoc = starProvince; provinceIdSendDoc = provinceId; onChangeProvinceSendDoc(); starAmphurSendDoc = starAmphur; amphurIdSendDoc = amphurId; onChangeAmphurSendDoc(); starDistrictSendDoc = starDistrict; districtIdSendDoc = districtId; // onChangeDistrictSendDoc(); addressPostCodeSendDoc = addressPostCode; }else{ log.info("FALSE"); addressNoSendDoc = ""; addressBuildingSendDoc = ""; addressVillageSendDoc = ""; addressLaneSendDoc = ""; addressRoadSendDoc = ""; starProvinceSendDoc = ""; provinceIdSendDoc = -1; starAmphurSendDoc = ""; amphurIdSendDoc = -1; starDistrictSendDoc = ""; districtIdSendDoc = -1; addressPostCodeSendDoc = ""; } } public void onChangeNationality(){ if(nationality == -1 || nationality == 1){ chkNationality = true; }else{ chkNationality = false; } } public void confirmEditMember(){ log.info("##### confirmEditMember()"); log.info("##### user.get().getUserId = "+user.get().getUserId()); log.info("##### memberStr = "+memberStr); log.info("##### titleName = "+titleName); log.info("##### firstName = "+firstName); log.info("##### regisDate = "+regisDate!=null?sdf.format(regisDate):""); log.info("################################"); log.info("##### chkSameAddress = "+chkSameAddress); log.info("##### addressNo = "+addressNo); log.info("##### addressBuilding = "+addressBuilding); log.info("##### addressVillage = "+addressVillage); log.info("##### addressLane = "+addressLane); log.info("##### addressRoad = "+addressRoad); log.info("##### provinceId = "+provinceId); log.info("##### amphurId = "+amphurId); log.info("##### districtId = "+districtId); log.info("##### addressPostCode = "+addressPostCode); try{ user.get().getCustomerId().setRegisDate(regisDate); user.get().getCustomerId().setTitleName(titleName); user.get().getCustomerId().setFirstName(firstName); user.get().getCustomerId().setBusinessName(businessName); user.get().getCustomerId().setShowNameStatus(showName); user.get().getCustomerId().setSex(sex); user.get().getCustomerId().setBirthDay(birthDay); MasterNationality nation = em.find(MasterNationality.class, new Integer(nationality)); user.get().getCustomerId().setNationId(nation); MasterOfficialDocument offDoc = em.find(MasterOfficialDocument.class, new Integer(officialDocumentId)); user.get().getCustomerId().setOfficialDocumentId(offDoc); user.get().getCustomerId().setPersonalId(personalId); user.get().getCustomerId().setCompanyID(companyID); user.get().getCustomerId().setTelephone(telephone); user.get().getCustomerId().setMobile(mobile); user.get().getCustomerId().setLineId(lineId); user.get().getCustomerId().setEmail(email); user.get().getCustomerId().setAddressNo(addressNo); user.get().getCustomerId().setAddressBuilding(addressBuilding); user.get().getCustomerId().setAddressVillage(addressVillage); user.get().getCustomerId().setAddressLane(addressLane); user.get().getCustomerId().setAddressRoad(addressRoad); user.get().getCustomerId().setProvinceId(provinceId); user.get().getCustomerId().setAmphurId(amphurId); user.get().getCustomerId().setDistrictId(districtId); user.get().getCustomerId().setAddressNoSendDoc(addressNo); user.get().getCustomerId().setAddressBuildingSendDoc(addressBuilding); user.get().getCustomerId().setAddressVillageSendDoc(addressVillage); user.get().getCustomerId().setAddressLaneSendDoc(addressLane); user.get().getCustomerId().setAddressRoadSendDoc(addressRoad); user.get().getCustomerId().setProvinceIdSendDoc(provinceId); user.get().getCustomerId().setAmphurIdSendDoc(amphurId); user.get().getCustomerId().setDistrictIdSendDoc(districtId); user.get().getCustomerId().setProvinceStr(provinceStr); user.get().getCustomerId().setAmphurStr(amphurStr); user.get().getCustomerId().setDistrictStr(districtStr); user.get().getCustomerId().setPostCodeStr(addressPostCode); if(uploadedImage!=null){ user.get().getCustomerId().setImageMember(uploadedImage.getData()); user.get().getCustomerId().setImageMemberName(uploadedImage.getName()); } if(uploadedApplication!=null){ user.get().getCustomerId().setDocumentApplication(uploadedApplication.getData()); user.get().getCustomerId().setDocumentApplicationName(uploadedApplication.getName()); } if(uploadedIdCard!=null){ user.get().getCustomerId().setDocumentIdCard(uploadedIdCard.getData()); user.get().getCustomerId().setDocumentIdCardName(uploadedIdCard.getName()); } if(uploadedBookBank!=null){ user.get().getCustomerId().setDocumentBookBank(uploadedBookBank.getData()); user.get().getCustomerId().setDocumentBookBankName(uploadedBookBank.getName()); } // user.get().getCustomerId().setAddressNoSendDoc(addressNoSendDoc); // user.get().getCustomerId().setAddressBuildingSendDoc(addressBuildingSendDoc); // user.get().getCustomerId().setAddressVillageSendDoc(addressVillageSendDoc); // user.get().getCustomerId().setAddressLaneSendDoc(addressLaneSendDoc); // user.get().getCustomerId().setAddressRoadSendDoc(addressRoadSendDoc); // user.get().getCustomerId().setProvinceIdSendDoc(provinceIdSendDoc); // user.get().getCustomerId().setAmphurIdSendDoc(amphurIdSendDoc); // user.get().getCustomerId().setDistrictIdSendDoc(districtIdSendDoc); user.get().getCustomerId().setChkSameAddress(chkSameAddress?1:0); user.get().getCustomerId().setBankId(bankId); user.get().getCustomerId().setBankBranch(branch); user.get().getCustomerId().setBankaccountType(accType); user.get().getCustomerId().setBankaccountNo(accNo); user.get().getCustomerId().setBankaccountName(accName); user.get().getCustomerId().setRemark(remark); user.get().getCustomerId().setUpdateBy(user.get().getUserId()); user.get().getCustomerId().setUpdateDate(new Date()); em.merge(user.get().getCustomerId()); user.get().setUserName(customerControl.genNameMenber(user.get().getCustomerId())); em.merge(user.get()); messages.info(new AppBundleKey("error.label.editMemberSuccess",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage())); }catch(Exception e){ e.printStackTrace(); messages.error(new AppBundleKey("error.label.editMemberFail",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage())); } } public void onKeypress(){ if(businessName!=null && businessName.trim().length()>0){ starBusinessName = " "; }else{ starBusinessName = "*"; } if(firstName!=null && firstName.trim().length()>0){ starFirstName = " "; }else{ starFirstName = "*"; } if(personalId!=null && personalId.trim().length()>0 && officialDocumentId != -1){ starPersonalId = " "; }else{ starPersonalId = "*"; } if(mobile!=null && mobile.trim().length()>0){ starMobile = " "; }else{ starMobile = "*"; } if(starPersonalId.equals("*") || starFirstName.equals("*") || starMobile.equals("*") || starBusinessName.equals("*")){ chkSave = true; }else{ chkSave = false; } } public void exportDocumentApplication() { try { byte[] pdf = uploadedApplication.getData(); HttpServletResponse response = (HttpServletResponse) facesContext .getExternalContext().getResponse(); String extension = ""; int extDot = uploadedApplication.getName().lastIndexOf('.'); if (extDot > 0) { extension = uploadedApplication.getName().substring(extDot + 1); } if(extension.equals("pdf")){ response.setContentType("application/pdf"); } response.setContentLength(pdf.length); response.setHeader("Content-disposition", "inline; filename=" + uploadedApplication.getName() + "."+extension); ServletOutputStream out; out = response.getOutputStream(); out.write(pdf); out.flush(); // new out.close(); response.flushBuffer(); facesContext.responseComplete(); // new } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void exportDocumentIdCard() { try { byte[] pdf = uploadedIdCard.getData(); HttpServletResponse response = (HttpServletResponse) facesContext .getExternalContext().getResponse(); String extension = ""; int extDot = uploadedIdCard.getName().lastIndexOf('.'); if (extDot > 0) { extension = uploadedIdCard.getName().substring(extDot + 1); } if(extension.equals("pdf")){ response.setContentType("application/pdf"); } response.setContentLength(pdf.length); response.setHeader("Content-disposition", "inline; filename=" + uploadedIdCard.getName() + "."+extension); ServletOutputStream out; out = response.getOutputStream(); out.write(pdf); out.flush(); // new out.close(); response.flushBuffer(); facesContext.responseComplete(); // new } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void exportDocumentBookBank() { try { byte[] pdf = uploadedBookBank.getData(); HttpServletResponse response = (HttpServletResponse) facesContext .getExternalContext().getResponse(); String extension = ""; int extDot = uploadedBookBank.getName().lastIndexOf('.'); if (extDot > 0) { extension = uploadedBookBank.getName().substring(extDot + 1); } if(extension.equals("pdf")){ response.setContentType("application/pdf"); } response.setContentLength(pdf.length); response.setHeader("Content-disposition", "inline; filename=" + uploadedBookBank.getName() + "."+extension); ServletOutputStream out; out = response.getOutputStream(); out.write(pdf); out.flush(); // new out.close(); response.flushBuffer(); facesContext.responseComplete(); // new } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public long getCustomerId() { return customerId; } public void setCustomerId(long customerId) { this.customerId = customerId; } public String getSearchCustomer() { return searchCustomer; } public void setSearchCustomer(String searchCustomer) { this.searchCustomer = searchCustomer; } public String getMemberStr() { return memberStr; } public void setMemberStr(String memberStr) { this.memberStr = memberStr; } public String getTitleName() { return titleName; } public void setTitleName(String titleName) { this.titleName = titleName; } public String getStarTitleName() { return starTitleName; } public void setStarTitleName(String starTitleName) { this.starTitleName = starTitleName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getStarFirstName() { return starFirstName; } public void setStarFirstName(String starFirstName) { this.starFirstName = starFirstName; } public Date getRegisDate() { return regisDate; } public void setRegisDate(Date regisDate) { this.regisDate = regisDate; } public String getUpperLineName() { return upperLineName; } public void setUpperLineName(String upperLineName) { this.upperLineName = upperLineName; } public boolean getChkSave() { return chkSave; } public void setChkSave(boolean chkSave) { this.chkSave = chkSave; } public CustomerControl getCustomerControl() { return customerControl; } public void setCustomerControl(CustomerControl customerControl) { this.customerControl = customerControl; } public String getBusinessName() { return businessName; } public void setBusinessName(String businessName) { this.businessName = businessName; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getStarSex() { return starSex; } public void setStarSex(String starSex) { this.starSex = starSex; } public String getStarBirthDay() { return starBirthDay; } public void setStarBirthDay(String starBirthDay) { this.starBirthDay = starBirthDay; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public int getNationality() { return nationality; } public void setNationality(int nationality) { this.nationality = nationality; } public String getStarPersonalId() { return starPersonalId; } public void setStarPersonalId(String starPersonalId) { this.starPersonalId = starPersonalId; } public String getPersonalId() { return personalId; } public void setPersonalId(String personalId) { this.personalId = personalId; } public String getCompanyID() { return companyID; } public void setCompanyID(String companyID) { this.companyID = companyID; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getLineId() { return lineId; } public void setLineId(String lineId) { this.lineId = lineId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStarUpperLineId() { return starUpperLineId; } public void setStarUpperLineId(String starUpperLineId) { this.starUpperLineId = starUpperLineId; } public String getUpperLineMemberId() { return upperLineMemberId; } public void setUpperLineMemberId(String upperLineMemberId) { this.upperLineMemberId = upperLineMemberId; } public String getStarUpperLineName() { return starUpperLineName; } public void setStarUpperLineName(String starUpperLineName) { this.starUpperLineName = starUpperLineName; } public String getStarSide() { return starSide; } public void setStarSide(String starSide) { this.starSide = starSide; } public int getSide() { return side; } public void setSide(int side) { this.side = side; } public String getStarRecomendId() { return starRecomendId; } public void setStarRecomendId(String starRecomendId) { this.starRecomendId = starRecomendId; } public String getStarRecomendName() { return starRecomendName; } public void setStarRecomendName(String starRecomendName) { this.starRecomendName = starRecomendName; } public String getRecomendName() { return recomendName; } public void setRecomendName(String recomendName) { this.recomendName = recomendName; } public String getAddressNo() { return addressNo; } public void setAddressNo(String addressNo) { this.addressNo = addressNo; } public String getAddressBuilding() { return addressBuilding; } public void setAddressBuilding(String addressBuilding) { this.addressBuilding = addressBuilding; } public String getAddressVillage() { return addressVillage; } public void setAddressVillage(String addressVillage) { this.addressVillage = addressVillage; } public String getAddressLane() { return addressLane; } public void setAddressLane(String addressLane) { this.addressLane = addressLane; } public String getAddressRoad() { return addressRoad; } public void setAddressRoad(String addressRoad) { this.addressRoad = addressRoad; } public String getStarProvince() { return starProvince; } public void setStarProvince(String starProvince) { this.starProvince = starProvince; } public int getProvinceId() { return provinceId; } public void setProvinceId(int provinceId) { this.provinceId = provinceId; } public String getStarDistrict() { return starDistrict; } public void setStarDistrict(String starDistrict) { this.starDistrict = starDistrict; } public int getDistrictId() { return districtId; } public void setDistrictId(int districtId) { this.districtId = districtId; } public String getStarAmphur() { return starAmphur; } public void setStarAmphur(String starAmphur) { this.starAmphur = starAmphur; } public int getAmphurId() { return amphurId; } public void setAmphurId(int amphurId) { this.amphurId = amphurId; } public String getAddressPostCode() { return addressPostCode; } public void setAddressPostCode(String addressPostCode) { this.addressPostCode = addressPostCode; } public String getAddressNoSendDoc() { return addressNoSendDoc; } public void setAddressNoSendDoc(String addressNoSendDoc) { this.addressNoSendDoc = addressNoSendDoc; } public String getAddressBuildingSendDoc() { return addressBuildingSendDoc; } public void setAddressBuildingSendDoc(String addressBuildingSendDoc) { this.addressBuildingSendDoc = addressBuildingSendDoc; } public String getAddressVillageSendDoc() { return addressVillageSendDoc; } public void setAddressVillageSendDoc(String addressVillageSendDoc) { this.addressVillageSendDoc = addressVillageSendDoc; } public String getAddressLaneSendDoc() { return addressLaneSendDoc; } public void setAddressLaneSendDoc(String addressLaneSendDoc) { this.addressLaneSendDoc = addressLaneSendDoc; } public String getAddressRoadSendDoc() { return addressRoadSendDoc; } public void setAddressRoadSendDoc(String addressRoadSendDoc) { this.addressRoadSendDoc = addressRoadSendDoc; } public String getStarProvinceSendDoc() { return starProvinceSendDoc; } public void setStarProvinceSendDoc(String starProvinceSendDoc) { this.starProvinceSendDoc = starProvinceSendDoc; } public int getProvinceIdSendDoc() { return provinceIdSendDoc; } public void setProvinceIdSendDoc(int provinceIdSendDoc) { this.provinceIdSendDoc = provinceIdSendDoc; } public String getStarDistrictSendDoc() { return starDistrictSendDoc; } public void setStarDistrictSendDoc(String starDistrictSendDoc) { this.starDistrictSendDoc = starDistrictSendDoc; } public int getDistrictIdSendDoc() { return districtIdSendDoc; } public void setDistrictIdSendDoc(int districtIdSendDoc) { this.districtIdSendDoc = districtIdSendDoc; } public String getStarAmphurSendDoc() { return starAmphurSendDoc; } public void setStarAmphurSendDoc(String starAmphurSendDoc) { this.starAmphurSendDoc = starAmphurSendDoc; } public int getAmphurIdSendDoc() { return amphurIdSendDoc; } public void setAmphurIdSendDoc(int amphurIdSendDoc) { this.amphurIdSendDoc = amphurIdSendDoc; } public String getAddressPostCodeSendDoc() { return addressPostCodeSendDoc; } public void setAddressPostCodeSendDoc(String addressPostCodeSendDoc) { this.addressPostCodeSendDoc = addressPostCodeSendDoc; } public int getBankId() { return bankId; } public void setBankId(int bankId) { this.bankId = bankId; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getAccType() { return accType; } public void setAccType(int accType) { this.accType = accType; } public String getAccNo() { return accNo; } public void setAccNo(String accNo) { this.accNo = accNo; } public String getAccName() { return accName; } public void setAccName(String accName) { this.accName = accName; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public List<DropDownModel> getProvinceList() { return provinceList; } public void setProvinceList(List<DropDownModel> provinceList) { this.provinceList = provinceList; } public List<DropDownModel> getDistrictList() { return districtList; } public void setDistrictList(List<DropDownModel> districtList) { this.districtList = districtList; } public List<DropDownModel> getAmphurList() { return amphurList; } public void setAmphurList(List<DropDownModel> amphurList) { this.amphurList = amphurList; } public List<DropDownModel> getProvinceSendDocList() { return provinceSendDocList; } public void setProvinceSendDocList(List<DropDownModel> provinceSendDocList) { this.provinceSendDocList = provinceSendDocList; } public List<DropDownModel> getDistrictSendDocList() { return districtSendDocList; } public void setDistrictSendDocList(List<DropDownModel> districtSendDocList) { this.districtSendDocList = districtSendDocList; } public List<DropDownModel> getAmphurSendDocList() { return amphurSendDocList; } public void setAmphurSendDocList(List<DropDownModel> amphurSendDocList) { this.amphurSendDocList = amphurSendDocList; } public List<DropDownModel> getBankList() { return bankList; } public void setBankList(List<DropDownModel> bankList) { this.bankList = bankList; } public boolean getChkSameAddress() { return chkSameAddress; } public void setChkSameAddress(boolean chkSameAddress) { this.chkSameAddress = chkSameAddress; } public String getRecomendStrId() { return recomendStrId; } public void setRecomendStrId(String recomendStrId) { this.recomendStrId = recomendStrId; } public List<DropDownModel> getNationalityList() { return nationalityList; } public void setNationalityList(List<DropDownModel> nationalityList) { this.nationalityList = nationalityList; } public String getProvinceStr() { return provinceStr; } public void setProvinceStr(String provinceStr) { this.provinceStr = provinceStr; } public String getAmphurStr() { return amphurStr; } public void setAmphurStr(String amphurStr) { this.amphurStr = amphurStr; } public String getDistrictStr() { return districtStr; } public void setDistrictStr(String districtStr) { this.districtStr = districtStr; } public boolean isChkNationality() { return chkNationality; } public void setChkNationality(boolean chkNationality) { this.chkNationality = chkNationality; } public UploadedImage getUploadedImage() { return uploadedImage; } public void setUploadedImage(UploadedImage uploadedImage) { this.uploadedImage = uploadedImage; } public long getTimeStamp(){ return System.currentTimeMillis(); } public int getOfficialDocumentId() { return officialDocumentId; } public void setOfficialDocumentId(int officialDocumentId) { this.officialDocumentId = officialDocumentId; } public List<DropDownModel> getOfficialDocumentList() { return officialDocumentList; } public void setOfficialDocumentList(List<DropDownModel> officialDocumentList) { this.officialDocumentList = officialDocumentList; } public String getStarMobile() { return starMobile; } public void setStarMobile(String starMobile) { this.starMobile = starMobile; } public UploadedImage getUploadedApplication() { return uploadedApplication; } public void setUploadedApplication(UploadedImage uploadedApplication) { this.uploadedApplication = uploadedApplication; } public UploadedImage getUploadedIdCard() { return uploadedIdCard; } public void setUploadedIdCard(UploadedImage uploadedIdCard) { this.uploadedIdCard = uploadedIdCard; } public UploadedImage getUploadedBookBank() { return uploadedBookBank; } public void setUploadedBookBank(UploadedImage uploadedBookBank) { this.uploadedBookBank = uploadedBookBank; } public String getStarBusinessName() { return starBusinessName; } public void setStarBusinessName(String starBusinessName) { this.starBusinessName = starBusinessName; } public int getShowName() { return showName; } public void setShowName(int showName) { this.showName = showName; } }
package com.hxzy.controller.admin; import com.hxzy.common.util.MD5Util; import com.hxzy.common.vo.ResponseMessage; import com.hxzy.entity.Data; import com.hxzy.entity.Major; import com.hxzy.entity.Student; import com.hxzy.service.DataService; import com.hxzy.service.MajorService; import com.hxzy.service.StudentService; import com.hxzy.vo.StudentSearch; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping(value = "/admin/student") public class AdminStudentController { @Autowired private StudentService studentService; @Autowired private MajorService majorService; @Autowired private DataService dataService; @GetMapping(value = "/search") public String search(Model model){ //加载所有的专业 List<Major> arrMajor=this.majorService.searchAll(); model.addAttribute("arrMajor", arrMajor); //加载学历 List<Data> arrEdu=this.dataService.selectTypes(5); model.addAttribute("arrEdu",arrEdu); return "/admin/student/list"; } @ResponseBody @PostMapping(value = "/data") public ResponseMessage data(StudentSearch search){ return this.studentService.search(search); } @ResponseBody @PostMapping(value = "/save") public ResponseMessage save(Student student){ ResponseMessage rm=null; //新增 if(student.getId()==null || student.getId()==0){ //新增密码取手机后6位 位11 String pwd=student.getMobile().substring(5); //生成盐 String salt= MD5Util.randomSalt(5); //加密密码 String md5Pwd=MD5Util.MD5Encode(pwd,salt); student.setSalt(salt); student.setLoginPwd(md5Pwd); boolean result=this.studentService.insert(student); if(result){ rm=ResponseMessage.success("操作成功"); }else{ rm=ResponseMessage.failed(500,"新增数据失败!"); } }else{ boolean result=this.studentService.updateByPrimaryKeySelective(student); if(result){ rm=ResponseMessage.success("操作成功"); }else{ rm=ResponseMessage.failed(500,"修改数据失败!"); } } return rm; } }
package com.example.ian.rentermanager11; import android.content.DialogInterface; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import static com.example.ian.rentermanager11.R.id.pass; /** * Created by Ian on 2017/8/3 0003. */ public class forgetNum_activity extends AppCompatActivity { private EditText name; private EditText code; private Button find; private myDatabaseHelper dbHelper; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.forgetnum_layout); dbHelper=myDatabaseHelper.getInstance(this); name = (EditText) findViewById(R.id.admin_register_name1); code = (EditText) findViewById(R.id.admin_register_info1); find = (Button) findViewById(R.id.find); find.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String nameInfo = name.getText().toString(); String codeInfo = code.getText().toString(); SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.rawQuery("select name from admin where name=? ",new String[]{nameInfo}); Cursor cursor1 = db.rawQuery("select password from admin where name=?",new String[]{nameInfo}); if (cursor.moveToNext()){ if (codeInfo.equals("10086")){ AlertDialog.Builder builder = new AlertDialog.Builder(forgetNum_activity.this); LayoutInflater factory = LayoutInflater.from(forgetNum_activity.this); View textEntryView = factory.inflate(R.layout.password,null); builder.setView(textEntryView); TextView password1 = textEntryView.findViewById(pass); if (cursor1.moveToNext()){ String pi= cursor1.getString(cursor1.getColumnIndex("password")); password1.setText(pi); } builder.setNegativeButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.create().show(); }else { Toast.makeText(forgetNum_activity.this,"注册码不正确",Toast.LENGTH_SHORT).show(); } }else { Toast.makeText(forgetNum_activity.this,"管理员不存在",Toast.LENGTH_SHORT).show(); } } }); } }
package com.tencent.tencentmap.mapsdk.a; import android.graphics.PointF; public final class rn extends rl { private PointF d; private double e; private double f; public rn(sl slVar, double d, PointF pointF, long j, tt ttVar) { super(slVar, j, ttVar); this.e = d; this.d = pointF; } protected final void a(float f) { this.b.a(this.f * ((double) f), this.d, false, null); } protected final void c() { double c = this.b.c(); this.f = this.e - c; new StringBuilder("newZoom:").append(this.e).append(",oldZoom=").append(c); } protected final void d() { this.b.a(this.e, this.d, false, 0, null); } }
package String; import java.util.HashMap; public class RomanToInt_13 { /*13. 罗马数字转整数*/ /* 一张HashMap存罗马数字与整数的映射; 遍历一遍字符串,分两种情况: 1、存在2个罗马数字为一组代表一个整数的特殊情况 2、单个罗马数字代表一个整数 */ public int romanToInt(String s) { HashMap<String,Integer> map = new HashMap<>(); map.put("M",1000); map.put("CM",900); map.put("D",500); map.put("CD",400); map.put("C",100); map.put("XC",90); map.put("L",50); map.put("XL",40); map.put("X",10); map.put("IX",9); map.put("V",5); map.put("IV",4); map.put("I",1); int res = 0, index = 0; while(index < s.length()){ if(index + 1 < s.length() && map.containsKey(s.substring(index,index + 2))){ res += map.get(s.substring(index,index + 2)); index += 2; }else{ res += map.get(s.substring(index,index + 1)); index += 1; } } return res; } }
package com.literature.controller; import com.literature.common.JsonApi; import com.literature.entity.*; import com.literature.entity.Collections; import com.literature.service.IBookService; import com.literature.service.ICustomerInfoService; import com.literature.util.IDUtil; import com.literature.vo.CommentVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.*; @Controller @RequestMapping(value = "/api/book") public class BookController { @Autowired private IBookService bookService; @Autowired private ICustomerInfoService customerInfoService; // 获取书籍列表 @RequestMapping(value = "/list") @ResponseBody public JsonApi findAll(String title,Integer page) { JsonApi api = new JsonApi(); Integer total = bookService.findBooksByTitle(title).size(); List<Books> bookList = new ArrayList<>(); if (null == page || page == 1) { bookList = bookService.find(title,0,10); }else { bookList = bookService.find(title,(page-1)*10,10); } Map map = new HashMap(); map.put("total",total); map.put("bookList",bookList); api.setData(map); return api; } // 获取用户收藏的书籍 @RequestMapping(value = "/list2") @ResponseBody public JsonApi findCustAll(String title,String id,Integer page) { JsonApi api = new JsonApi(); Map map = new HashMap(); if (null == page || page == 1) { map = bookService.findCustBook(title,id,0); }else { map = bookService.findCustBook(title,id,(page-1)*10); } api.setData(map); return api; } // 删除收藏 @RequestMapping(value = "/collection/delete") @ResponseBody public JsonApi deleteCollection(String bookId,String userId) { JsonApi api = new JsonApi(); bookService.deleteCollections(bookId,userId); return api; } @RequestMapping(value = "/add") @ResponseBody public JsonApi addBook(@RequestBody Books params){ JsonApi api = new JsonApi(); String id = IDUtil.getId(); params.setId(id); params.setCollection(0); params.setUrl("/api/book/get"); bookService.addBook(params); return api; } @RequestMapping(value = "/update") @ResponseBody public JsonApi updateBook(@RequestBody Books params) { JsonApi api = new JsonApi(); bookService.updateBook(params); return api; } @RequestMapping(value = "/get") @ResponseBody public Books findById(String id) { return bookService.findById(id); } @RequestMapping(value = "/delete") @ResponseBody public JsonApi deleteBook(String id) { JsonApi api = new JsonApi(); bookService.deleteById(id); return api; } @RequestMapping("/comment/list") @ResponseBody public JsonApi findComentList(String title,Integer page) { JsonApi api = new JsonApi(); Map map = new HashMap(); Integer total = bookService.findCommentByTitle(title).size(); List<Comments> commentList = new ArrayList<>(); if (null==page || page == 1) { commentList = bookService.findComment(title,1,10); }else { commentList = bookService.findComment(title,(page-1)*10,10); } map.put("total",total); map.put("commentList",commentList); api.setData(map); return api; } @RequestMapping("/comment/list2") @ResponseBody public JsonApi findCustComentList(String title,String id,Integer page) { JsonApi api = new JsonApi(); Map map = new HashMap(); Integer total = bookService.findCustCommentByTitle(title,id).size(); List<Comments> commentList = new ArrayList<>(); if (null==page || page == 1) { commentList = bookService.findCustComment(title,id,0,10); }else { commentList = bookService.findCustComment(title,id,(page-1)*10,10); } map.put("total",total); map.put("commentList",commentList); api.setData(map); return api; } @RequestMapping("/comment/get") @ResponseBody public CommentVo findComentById(String id) { Comments c1 = bookService.findComnentById(id); CustomerInfo c2 = customerInfoService.findById(c1.getUserId()); CommentVo cv = new CommentVo(); cv.setId(c1.getId()); cv.setTitle(c1.getTitle()); cv.setUsername(c2.getUsername()); cv.setUserid(c2.getId()); cv.setContent(c1.getContent()); cv.setCreated(c1.getCreated()); cv.setRating(c1.getRating()); return cv; } @RequestMapping(value = "/comment/delete") @ResponseBody public JsonApi deleteComment(String id) { JsonApi api = new JsonApi(); bookService.deleteCommentById(id); return api; } @RequestMapping(value = "/nominate/update") @ResponseBody public JsonApi nominateSet(@RequestBody Map params) { JsonApi api = new JsonApi(); Nominate nominate = new Nominate(); nominate.setId("1"); nominate.setCondition(params.get("nominate").toString()); bookService.setNominate(nominate); return api; } @RequestMapping(value = "/collection/add") @ResponseBody public JsonApi addCollection(@RequestBody Collections params) { params.setId(IDUtil.getId()); bookService.addCollection(params); return new JsonApi(); } @RequestMapping(value = "/comment/add") @ResponseBody public JsonApi addNotes(@RequestBody Comments params) { params.setId(IDUtil.getId()); params.setCreated(new Date()); bookService.addComment(params); return new JsonApi(); } @RequestMapping(value = "/list/nominate") @ResponseBody public JsonApi getByNominate(Integer page) { JsonApi api = new JsonApi(); Integer total = bookService.findBooksByTitle(null).size(); List<Books> bookList = new ArrayList<>(); if (null == page || page == 1) { bookList = bookService.getBookListByNominate(0); }else { bookList = bookService.getBookListByNominate((page-1)*10); } Map map = new HashMap(); map.put("total",total); map.put("bookList",bookList); api.setData(map); return api; } @RequestMapping(value = "/public/get") @ResponseBody public JsonApi getBoookMessage(String id) { return bookService.getBooks(id); } @RequestMapping(value = "/comment/list/get") @ResponseBody public List<CommentVo> getComments(String id,Integer page){ return bookService.getComments(id,page); } @RequestMapping(value = "/collection/userList") @ResponseBody List<String> getUserList(String id) { return bookService.getUsersId(id); } }
package com.qgbase.config; /** * Created by lbb on 2018/4/26. * 主要用于: */ public class Constants { public final static int yesorno_Yes = 1; public final static int yesorno_No = 0; /* 系统最高级别管理员 */ public final static String user_admin = "admin"; public final static String role_admin = "admin"; public final static String role_dlsadmin = "dlsadmin"; public final static String role_dlsoper = "dlsoper"; public final static String role_dlsywer = "dlsywer"; public final static String role_client = "client"; /** * Token配置 */ public static final long EXPIRATIONTIME = 100000L * 60 * 60 * 24 * 30;// 1000秒 public static final String SECRET = "P@ssw02d"; // JWT密码 public static final String TOKEN_PREFIX = "Bearer"; // Token前缀 public static final String HEADER_STRING = "token";// 存放Token的Header Key /** * 方法执行结果 */ public static final String SUCCESS = "0"; public static final String BIZ_EXCEPTION = "1"; public static final String SYS_EXCEPTION = "2"; /** * 用户类型 */ public static final String usertype_user = "user";//系统内部用户 public static final String usertype_farmer = "farmer";//农户 public static final String usertype_chaoshi = "market";//超市 public static final String usertype_car = "vehicle";//车辆 public static final String usertype_zzc = "zzc";//中转仓 /** * 单据类型 */ public static final String orderType_inware = "inware";//采购入库单 public static final String orderType_transfer = "transfer";// 调拨单 public static final String orderType_inventory = "inventory";// 仓库盘点单 public static final String orderType_returnout = "returnout";// 退货出库单 public static final String orderType_recoverin= "recoverin";//余货入库单 public static final String orderType_outware= "outware";// 发货出库单 public static final String orderType_returnin= "returnin";//回收入库单 public final static String orderType_wmsFarmerget="farmerget";//农户确认收货 public final static String orderType_wmsFarmersend="farmersend";//农户发货 public final static String orderType_wmsMarketget="marketget";//商超确认收货 public final static String orderType_wmsMarketsend="marketsend";//商超回收 public final static String orderType_wmsPack="pack";//商超回收 /** * 入库单状态 */ public static final String orderStatus_new = "new"; public static final String orderStatus_confirm = "confirm"; public static final String orderStatus_yfp = "yfp"; public static final String orderStatus_wfp = "wfp"; public static final String orderStatus_close = "close"; public static final String Lot_type_zha="lot";// 一扎 public static final String Lot_type_TP = "TP";//托盘 /* 支付类型 */ public final static String payType_cash="cash"; public final static String payType_zfb="zfb"; public final static String payType_weixin="weixin"; public final static String payType_sys="sys"; public final static String datadic_location="Location"; public final static String locationType_finished="finished";//成品 }
package com.example.doubnut.di.module; import com.example.doubnut.ui.newlist.ListFragment; import com.example.doubnut.ui.newsdetails.DetailsFragment; import dagger.Module; import dagger.android.ContributesAndroidInjector; @Module public abstract class MainFragmentBindingModule { @ContributesAndroidInjector abstract ListFragment provideListFragment(); @ContributesAndroidInjector abstract DetailsFragment provideDetailsFragment(); }
package org.alienideology.jcord.handle.modifiers; import org.alienideology.jcord.handle.audit.AuditAction; import org.alienideology.jcord.handle.channel.IVoiceChannel; import org.alienideology.jcord.handle.guild.IGuild; import org.alienideology.jcord.handle.guild.IMember; import org.alienideology.jcord.handle.guild.IRole; import org.alienideology.jcord.internal.rest.ErrorResponse; import java.util.Collection; /** * IMemberModifier - The modifier that modifies a member. * * @author AlienIdeology */ public interface IMemberModifier extends IModifier<AuditAction<Void>> { /** * Get the guild this modifier belongs to. * * @return The guild. */ default IGuild getGuild() { return getMember().getGuild(); } /** * Get the member this modifier modifies. * * @return The member. */ IMember getMember(); /** * Modify the member's nickname. * Use empty or null nicknames to reset the nickname. * * @exception org.alienideology.jcord.internal.exception.PermissionException * If the identity does not have either {@code Change Nickname} permission to modify itself, * or {@code Manage Nicknames} permission to manage other nicknames. * * @exception org.alienideology.jcord.internal.exception.HigherHierarchyException * If the member is the server owner or have higher role than the identity. * * @exception IllegalArgumentException * <ul> * <li>If the nickname is not valid. See {@link IMember#isValidNickname(String)}</li> * <li>If the member is the identity it self. Use {@link org.alienideology.jcord.handle.managers.IMemberManager#modifyNickname(String)}, * which supports modifying self nickname.</li> * </ul> * * @param nickname The nickname. * @return IMemberModifier for chaining. */ IMemberModifier nickname(String nickname); /** * Modify the member's roles by passing all the roles this member will have. * Note that this will override all roles the member once had. * * @exception org.alienideology.jcord.internal.exception.PermissionException * If the identity does not have {@code Manage Roles} permission. * @exception org.alienideology.jcord.internal.exception.ErrorResponseException * If one of the roles does not belong to this guild. * @exception org.alienideology.jcord.internal.exception.HigherHierarchyException * If the member is the server owner or have higher role than the identity. * * @param roles The collection of roles. * @return IMemberModifier for chaining. */ IMemberModifier roles(Collection<IRole> roles); /** * Modify, or move, the voice channel this member is connected in. * * @exception org.alienideology.jcord.internal.exception.PermissionException * <ul> * <li>If the identity does not have {@code Move Members} permission.</li> * <li>If the identity does not have {@code Connect} permission to connect to the specific channel.</li> * </ul> * @exception org.alienideology.jcord.internal.exception.ErrorResponseException * If the voice channel does not belongs to this guild. * @see ErrorResponse#UNKNOWN_CHANNEL * * @param channel The voice channel. * @return IMemberModifier for chaining. */ IMemberModifier voiceChannel(IVoiceChannel channel); /** * Modify, or move, the voice channel this member is connected in. * * @exception org.alienideology.jcord.internal.exception.PermissionException * <ul> * <li>If the identity does not have {@code Move Members} permission.</li> * <li>If the identity does not have {@code Connect} permission to connect to the specific channel.</li> * </ul> * @exception org.alienideology.jcord.internal.exception.ErrorResponseException * If the voice channel does not belongs to this guild. * @see ErrorResponse#UNKNOWN_CHANNEL * * @param channelId The voice channel's id. * @return IMemberModifier for chaining. */ default IMemberModifier voiceChannel(String channelId) { return voiceChannel(getGuild().getVoiceChannel(channelId)); } /** * Mute or unmute this member. * * @exception org.alienideology.jcord.internal.exception.PermissionException * If the member does not have {@code Mute Members} permission. * @exception org.alienideology.jcord.internal.exception.HigherHierarchyException * If the member is the server owner or have higher role than the identity. * @exception org.alienideology.jcord.internal.exception.ErrorResponseException * If the member does not belong to this guild. * @see ErrorResponse#UNKNOWN_MEMBER * * @param mute True to mute, false to unmute. * @return IMemberModifier for chaining. */ IMemberModifier mute(boolean mute); /** * Deafen or undeafen this member. * * @exception org.alienideology.jcord.internal.exception.PermissionException * If the member does not have {@code Deafen Members} permission. * @exception org.alienideology.jcord.internal.exception.HigherHierarchyException * If the member is the server owner or have higher role than the identity. * @exception org.alienideology.jcord.internal.exception.ErrorResponseException If the member does not belong to this guild. * @see ErrorResponse#UNKNOWN_MEMBER * * @param deafen True to deafen the member, false to undeafen. * @return IMemberModifier for chaining. */ IMemberModifier deafen(boolean deafen); /** * Get the nickname attribute, used to modify the member's nickname. * * @return The nickname attribute. */ Attribute<IMemberModifier, String> getNicknameAttr(); /** * Get the roles attribute, used to modify the member's roles. * * @return The roles attribute. */ Attribute<IMemberModifier, Collection<IRole>> getRolesAttr(); /** * Get the voice channel attribute, used to move the member to another voice channel. * * @return The voice channel attribute. */ Attribute<IMemberModifier, IVoiceChannel> getVoiceChannelAttr(); /** * Get the mute attribute, used to mute or unmute the member. * * @return The mute attribute. */ Attribute<IMemberModifier, Boolean> getMuteAttr(); /** * Get the deafen attribute, used to deafen or undeafen the member. * * @return The deafen attribute. */ Attribute<IMemberModifier, Boolean> getDeafenAttr(); }
package com.kunsoftware.service; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.kunsoftware.bean.QuestionsRequestBean; import com.kunsoftware.entity.Questions; import com.kunsoftware.exception.KunSoftwareException; import com.kunsoftware.mapper.QuestionsMapper; import com.kunsoftware.page.PageInfo; @Service public class QuestionsService { private static Logger logger = LoggerFactory.getLogger(QuestionsService.class); @Autowired private QuestionsMapper mapper; public List<Questions> getQuestionsListPage(String audit,String reply,PageInfo page) { logger.info("query"); return mapper.getQuestionsListPage(audit,reply,null,null,page); } public List<Questions> getFrontQuestionsListPage(Integer destination,String banner,PageInfo page) { logger.info("query"); return mapper.getQuestionsListPage("1",null,destination,banner,page); } @Transactional public Questions insert(QuestionsRequestBean requestBean) throws KunSoftwareException { Questions record = new Questions(); BeanUtils.copyProperties(requestBean, record); record.setCreateTime(new Date()); record.setAudit("1"); mapper.insert(record); return record; } public Questions selectByPrimaryKey(Integer id) throws KunSoftwareException { return mapper.selectByPrimaryKey(id); } @Transactional public int updateByPrimaryKey(QuestionsRequestBean requestBean,Integer id) throws KunSoftwareException { Questions record = mapper.selectByPrimaryKey(id); BeanUtils.copyProperties(requestBean, record); record.setReplyTime(new Date()); return mapper.updateByPrimaryKeySelective(record); } @Transactional public int deleteByPrimaryKey(Integer id) throws KunSoftwareException { return mapper.deleteByPrimaryKey(id); } @Transactional public void deleteByPrimaryKey(Integer[] id) throws KunSoftwareException { for(int i = 0;i < id.length;i++) { mapper.deleteByPrimaryKey(id[i]); } } }
/* * 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.webbeans.test.injection.generics; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.webbeans.config.OwbParametrizedTypeImpl; import org.apache.webbeans.test.AbstractUnitTest; import org.junit.Test; public class FastMatchingGenericsTest extends AbstractUnitTest { @Test public void concreteGenericsAreNotAmbiguous() { startContainer(StringRepo.class, IntRepo.class); final Object stringRepo = getInstance(new OwbParametrizedTypeImpl(null, Repo.class, String.class)); assertNotNull(stringRepo); assertEquals("string", Repo.class.cast(stringRepo).get()); validateIntRepoIsOk(); } @Test public void genericGenericsAreNotAmbiguous() { startContainer(IntRepo.class, StringRepo.class, ConcreteRepo.class); final ConcreteRepo stringRepo = getInstance(ConcreteRepo.class); assertNotNull(stringRepo); assertEquals("string", stringRepo.get()); validateIntRepoIsOk(); } // just to ensure String is not a particular case or there is a iterator().next() breaking other cases private void validateIntRepoIsOk() { final Object intRepo = getInstance(new OwbParametrizedTypeImpl(null, Repo.class, Integer.class)); assertNotNull(intRepo); assertEquals(1, Repo.class.cast(intRepo).get()); } public interface Repo<A> { A get(); } public static abstract class BaseRepoAware<A> { @Inject protected Repo<A> repo; } @ApplicationScoped public static class ConcreteRepo extends BaseRepoAware<String> { public String get() { return repo.get(); } } @ApplicationScoped public static class StringRepo implements Repo<String> { @Override public String get() { return "string"; } } @ApplicationScoped public static class IntRepo implements Repo<Integer> { @Override public Integer get() { return 1; } } }
package com.rc.components; import com.rc.res.Colors; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; /** * Created by song on 17-6-4. */ public class RCProgressBar extends JProgressBar { public RCProgressBar() { setForeground(Colors.PROGRESS_BAR_START); setBorder(new LineBorder(Colors.PROGRESS_BAR_END)); } @Override protected void paintBorder(Graphics g) { } @Override public Dimension getPreferredSize() { return new Dimension(getWidth(), 6); } }
/* * 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 com.mycompany.gui.Amal; import com.codename1.components.ScaleImageButton; import com.codename1.ui.Button; import com.codename1.ui.Container; import com.codename1.ui.Display; import com.codename1.ui.Font; import com.codename1.ui.FontImage; import com.codename1.ui.Form; import com.codename1.ui.Image; import com.codename1.ui.geom.Dimension; import com.codename1.ui.layouts.BoxLayout; import com.codename1.ui.layouts.GridLayout; import com.codename1.ui.plaf.Border; import com.codename1.ui.plaf.Style; import com.codename1.ui.plaf.UIManager; import com.mycompany.entities.Amal.Animal; import com.mycompany.entities.hiba.Session; import com.mycompany.services.Amal.AdoptionService; import java.io.IOException; import java.util.ArrayList; /** * * @author amalg */ public class MyAnimals { Form f; public MyAnimals() throws IOException { f=new Form("Adoption",GridLayout.autoFit()); f.getStyle().setBgImage(Image.createImage("/vitrine.png")); f.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_TILE_BOTH); Session se=new Session(); int user=se.sessionId; //*******************Recuperer la liste de produit de la base*************************************************** AdoptionService sp1=new AdoptionService(); ArrayList<Animal> list=sp1.MyAnimals(user); //********************************Parcourir la liste**************************************************************** for(Animal a : list) { Container c1 =new Container(BoxLayout.y()); Container c2 =new Container(BoxLayout.x()); c2.getStyle().setPadding(0,0,10,0); c1.getStyle().setBorder(Border.createLineBorder(2)); Style bb = UIManager.getInstance().getComponentStyle("border-color:white;"); c1.getStyle().setMargin(1, 1, 1, 1); c1.getStyle().setPadding(5, 5, 0, 0); c1.getStyle().merge(bb); //****************************les elements du containers******************************************************** ScaleImageButton ivv=new ScaleImageButton(Image.createImage("/"+ a.getImage()).scaled(80,150)); ivv.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED); Style s = UIManager.getInstance().getComponentStyle("Button"); FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_DELETE,s); FontImage icon2 = FontImage.createMaterial(FontImage.MATERIAL_EDIT,s); Button b =new Button(icon2); Style sb = UIManager.getInstance().getComponentStyle("background-color:transparent;"); b.getStyle().merge(sb); Button b2 =new Button(icon); b2.getStyle().merge(sb); Font ff=Font.createTrueTypeFont("fontello", "fontello.ttf"); FontImage fm = FontImage.createFixed("\ue813",ff, 0xFFFFFF, Display.getInstance().convertToPixels(4), Display.getInstance().convertToPixels(4)); FontImage fm1 = FontImage.createFixed("\ue812",ff, 0xcc0000, Display.getInstance().convertToPixels(4), Display.getInstance().convertToPixels(4)); Button b4; if(sp1.isWishlist(a,user).equals("true")) {b4=new Button(fm1);} else{b4=new Button(fm);} b4.getStyle().merge(sb); Dimension d=new Dimension(5,5); c2.setSize(d); c1.add(ivv); c2.add(b); c2.add(b4); c2.add(b2); c1.add(c2); b4.setVisible(false); //*******************************Action sur le bouton add***************************************************** ivv.addActionListener(e->{ShowAnimal sp=new ShowAnimal(a.getId_animal());}); ivv.setName(a.getNick_Name()); f.add(c1); f.show(); b2.addActionListener(bb2->{ sp1.DeleteAnimal(a); c1.remove(); }); b.addActionListener(bb1->{ try { UpdateAdoption adop=new UpdateAdoption(a.getId_animal()); } catch (IOException ex) { } }); } } public Form getF() { return f; } public void setF(Form f) { this.f = f; } }
package com.example.android.quakereport; import android.content.Context; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import java.text.DecimalFormat; import android.graphics.drawable.GradientDrawable; import java.util.ArrayList; /** * Created by jb704y on 30/10/2017. */ public class DataAdapter extends ArrayAdapter<Earthquake> { /** Resource ID for the background color for this list of earthquakes */ //private int mColorResourceId; /** * Create a new {@link ArrayAdapter} object. * * @param context is the current context (i.e. Activity) that the adapter is being created in. * @param earthquakes is the list of {@link Earthquake}s to be displayed. //* @param colorResourceId is the resource ID for the background color for this list of earthquakes */ /** * Return the formatted date string (i.e. "Mar 3, 1984") from a Date object. */ String primaryLocation; String offSetLocation; private String formatDate(Date dateObject) { SimpleDateFormat dateFormat = new SimpleDateFormat("LLL dd, yyyy"); return dateFormat.format(dateObject); } /** * Return the formatted date string (i.e. "4:30 PM") from a Date object. */ private String formatTime(Date dateObject) { SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a"); return timeFormat.format(dateObject); } /** * Return the formatted magnitude string showing 1 decimal place (i.e. "3.2") * from a decimal magnitude value. */ private String formatMagnitude(double magnitude) { DecimalFormat magnitudeFormat = new DecimalFormat("0.0"); return magnitudeFormat.format(magnitude); } private static final String LOCATION_SEPARATOR = " of "; public DataAdapter(Context context, ArrayList<Earthquake> earthquakes) { super(context, 0, earthquakes); } private int getMagnitudeColor (double magnitude){ int magnitudeColorResourceId; int magnitudeFloor = (int) Math.floor(magnitude); switch (magnitudeFloor){ case 0: case 1: magnitudeColorResourceId = R.color.magnitude1; break; case 2: magnitudeColorResourceId = R.color.magnitude2; break; case 3: magnitudeColorResourceId = R.color.magnitude3; break; case 4: magnitudeColorResourceId = R.color.magnitude4; break; case 5: magnitudeColorResourceId = R.color.magnitude5; break; case 6: magnitudeColorResourceId = R.color.magnitude6; break; case 7: magnitudeColorResourceId = R.color.magnitude7; break; case 8: magnitudeColorResourceId = R.color.magnitude8; break; case 9: magnitudeColorResourceId = R.color.magnitude9; break; default: magnitudeColorResourceId = R.color.magnitude10plus; break; } return ContextCompat.getColor(getContext(), magnitudeColorResourceId); } //We override the getView method from the ArrayAdapter super class so we can control how the list items get created @Override public View getView(int position, View convertView, ViewGroup parent) { // Check if the existing view is being reused, otherwise inflate the view View listItemView = convertView; if (listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate( R.layout.list_item, parent, false); } // Get the {@link AndroidFlavor} object located at this position in the list Earthquake currentEarthquake = getItem(position); // Find the TextView in the list_item.xml layout with the ID mag_text_view TextView magTextView = (TextView) listItemView.findViewById(R.id.mag_text_view); // Format the magnitude to show 1 decimal place String formattedMagnitude = formatMagnitude(currentEarthquake.getMag()); // Get the version name from the current translation object and // set this text on the Mag TextView magTextView.setText(formattedMagnitude); // Create a new String that accepts the value from current position in the array String originalLocation = currentEarthquake.getLocation(); // Find the TextView in the list_item.xml layout with the ID primary location_text_view TextView primaryLocationTextView = (TextView) listItemView.findViewById(R.id.primary_location_text_view); // Get the the currentWord object and // set this text on the default TextView primaryLocationTextView.setText(primaryLocation); if (originalLocation.contains(LOCATION_SEPARATOR)) { String[] parts = originalLocation.split(LOCATION_SEPARATOR); offSetLocation = parts[0] + LOCATION_SEPARATOR; primaryLocation = parts[1]; } else { primaryLocation = getContext().getString(R.string.near_the); primaryLocation = originalLocation; } // Find the TextView in the list_item.xml layout with the ID offset location_text_view TextView offsetLocationTextView = (TextView) listItemView.findViewById(R.id.offset_location_text_view); // Get the the current location object and // set this text on the default TextView offsetLocationTextView.setText(offSetLocation); // Create a new Date object from the time in milliseconds of the earthquake Date dateObject = new Date(currentEarthquake.getTimeInMilliseconds()); // Find the ImageView in the list_item.xml layout with the ID date_text_view TextView dateTextView = (TextView) listItemView.findViewById(R.id.date_text_view); // Format the date string (i.e. "Mar 3, 1984") String formattedDate = formatDate(dateObject); // Display the date of the current earthquake in that TextView dateTextView.setText(formattedDate); // Find the ImageView in the list_item.xml layout with the ID date_text_view TextView timeTextView = (TextView) listItemView.findViewById(R.id.time_text_view); // Format the time string (i.e. "4:30PM") String formattedTime = formatTime(dateObject); // Display the time of the current earthquake in that TextView timeTextView.setText(formattedTime); // Set the proper background color on the magnitude circle. // Fetch the background from the TextView, which is a GradientDrawable. GradientDrawable magnitudeCircle = (GradientDrawable) magTextView.getBackground(); // Get the appropriate background color based on the current earthquake magnitude int magnitudeColor = getMagnitudeColor(currentEarthquake.getMag()); // Set the color on the magnitude circle magnitudeCircle.setColor(magnitudeColor); //return the list view with the correct data, takes all list items and displays them on screen. return listItemView; } }
package com.yksoul.pay.service; import com.yksoul.pay.domain.enums.PayErrorCodeEnum; import com.yksoul.pay.exception.EasyPayException; /** * 微信支付获取openID * * @author yk * @version 1.0 * @date 2018-06-15 */ public interface IWxPay { /** * 获取用户OpenId * * @return */ default String getOpenId() throws EasyPayException { throw new EasyPayException(PayErrorCodeEnum.NOT_EXIST_IPAYMENT_IMPL); } }
package com.rofour.baseball.controller.message; import com.rofour.baseball.controller.base.BaseController; import com.rofour.baseball.controller.model.DataGrid; import com.rofour.baseball.controller.model.ResultInfo; import com.rofour.baseball.controller.model.SelectModel; import com.rofour.baseball.controller.model.message.MsgTypeInfo; import com.rofour.baseball.service.message.MsgTypeService; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.jstl.sql.Result; import java.util.ArrayList; import java.util.List; /** * 消息类型控制器 * Created by wny on 2016-09-01. */ @Controller @RequestMapping(value = "/message/msgType") public class MsgTypeController extends BaseController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired @Qualifier("msgTypeService") private MsgTypeService msgTypeService; @RequestMapping(value = "/gotoMsgType") public ModelAndView msgTypeIndex(HttpServletRequest request) { if (request.getSession().getAttribute("user") != null) { return new ModelAndView("message/msgType/msgTypeManager"); } else { return new ModelAndView("/"); } } /** * 查询消息类型 * @param request * @param response * @return */ @RequestMapping(value = "/queryMsgTypeGrid", method = RequestMethod.GET) public @ResponseBody List<MsgTypeInfo> queryMsgTypeGrid( HttpServletRequest request, HttpServletResponse response) { List<MsgTypeInfo> list = msgTypeService.getAllData(); // DataGrid<MsgTypeInfo> dataList = new DataGrid<>(); // dataList.setRows(list); // dataList.setTotal(list.size()); return list; } /*** * 获取可用消息类型selectModel格式的json字符串 * @param request * @param response */ @RequestMapping(value = "/getMsgTypeSellList", method = RequestMethod.GET) @ResponseBody public void getMsgTypeSellList(HttpServletRequest request, HttpServletResponse response) { List<SelectModel> sellist = new ArrayList<>(); List<MsgTypeInfo> list = msgTypeService.getAllData(); for (MsgTypeInfo item :list ) { SelectModel temp = new SelectModel(); temp.setText(item.getMsgTypeName()); temp.setId(item.getMsgType().toString()); sellist.add(temp); } writeJson(sellist, response); } /*** * 获取可用的一级消息类型selectModel格式的json字符串 * @param request * @param response */ @RequestMapping(value = "/getFirstMsgTypeSellList", method = RequestMethod.POST) @ResponseBody public void getFirstMsgTypeSellList(HttpServletRequest request, HttpServletResponse response) { List<SelectModel> sellist = new ArrayList<>(); List<MsgTypeInfo> list = msgTypeService.getAllData(); for (MsgTypeInfo item :list ) { if(item.getTypeLevel()==null||!item.getTypeLevel().equals((byte)1)) { continue; } SelectModel sel = new SelectModel(); sel.setId(" "); sel.setText("请选择"); sellist.add(sel); SelectModel temp = new SelectModel(); temp.setText(item.getMsgTypeName()); temp.setId(item.getMsgType().toString()); sellist.add(temp); } writeJson(sellist, response); } @RequestMapping(value = "/addMsgType", method = RequestMethod.POST) @ResponseBody public ResultInfo addMsgType(HttpServletRequest request, HttpServletResponse response,MsgTypeInfo info) { ResultInfo result=new ResultInfo(); result.setSuccess(0); result.setMessage("操作成功!"); if(info==null||info.getMsgType()==null||info.getMsgTypeName()==null) { result.setSuccess(-1); result.setMessage("操作失败,类型名称或类型编码不能为空!"); } else { int id= msgTypeService.addInfo(info); if(id<=0) { result.setSuccess(-1); result.setMessage("操作失败,添加数据失败!"); } } return result; } @RequestMapping(value = "/updateMsgType", method = RequestMethod.POST) @ResponseBody public ResultInfo updateMsgType(HttpServletRequest request, HttpServletResponse response,MsgTypeInfo info) { ResultInfo result=new ResultInfo(); result.setSuccess(0); result.setMessage("操作成功!"); if(info==null||info.getMsgType()==null||info.getMsgTypeName()==null||info.getId()==null) { result.setSuccess(-1); result.setMessage("操作失败,类型id、类型名称或类型编码不能为空!"); } else { boolean isSucess= msgTypeService.updateInfo(info); if(!isSucess) { result.setSuccess(-1); result.setMessage("操作失败,更新数据失败!"); } } return result; } @RequestMapping(value = "/delMsgType", method = RequestMethod.POST) @ResponseBody public ResultInfo delMsgType(HttpServletRequest request, HttpServletResponse response,@Param("info") Integer info) { ResultInfo result=new ResultInfo(); result.setSuccess(0); result.setMessage("操作成功!"); if(info==null) { result.setSuccess(-1); result.setMessage("操作失败,类型id不能为空!"); } else { boolean isSucess=msgTypeService.delInfo(info); if(!isSucess) { result.setSuccess(-1); result.setMessage("操作失败,删除数据失败!"); } } return result; } }
package com.SkyBlue.base.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.SkyBlue.base.serviceFacade.BaseServiceFacade; import com.SkyBlue.base.to.MenuBean; import com.SkyBlue.common.mapper.DatasetBeanMapper; import com.tobesoft.xplatform.data.PlatformData; @Controller public class MenuController{ @Autowired private BaseServiceFacade baseServiceFacade; @Autowired private DatasetBeanMapper datasetBeanMapper; /* menu목록을 가져오는 메서드 */ @RequestMapping("/base/findMenuList.do") public void findMenuList(@RequestAttribute("inData") PlatformData inData, @RequestAttribute("outData") PlatformData outData) throws Exception{ List<MenuBean> menuList=baseServiceFacade.findMenuList(); datasetBeanMapper.beansToDataset(outData, menuList, MenuBean.class); } }
package de.snake.util; import java.awt.Color; import java.awt.Graphics; public class BigFeed extends Feed { public BigFeed(int x, int y, Randomiser randomiser) { super(x, y, randomiser); // TODO Auto-generated constructor stub } @Override public void paint(Graphics g) { // TODO Auto-generated method stub if(randomiser.isBigFeed()) { g.setColor(Color.YELLOW); g.fillOval(x, y, 20, 20); } } }
package com.semantyca.nb.definition; public class DefaultAppConst { public static String MODULE_VERSION = "1.0"; public static String NAME = ""; public static String CODE = NAME.toLowerCase(); public static String NAME_ENG = ""; public static String NAME_DEU = ""; public static String NAME_FRA = ""; public static String NAME_POR = ""; public static String NAME_SPA = ""; public static String NAME_ITA = ""; public static String NAME_CHI = ""; public static String NAME_ARA = ""; public static String NAME_BUL = ""; public static String NAME_RUS = ""; public static String NAME_KAZ = ""; public static String BASE_URL = "wrong_application_name/"; public static String AVAILABLE_THEME[] = {"azul", "cinzento", "branco", "preto"}; public static String DEFAULT_THEME = "branco"; public static boolean FORCE_DEPLOYING = false; public static String[] ROLES = {}; public static String[] ORG_LABELS = {}; public static String[] TAG_CATEGORIES = {}; public static String[] UNIT_CATEGORIES = {"quantity","area"}; }
package com.sy.s1.member; 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.OneToOne; import javax.persistence.Table; import lombok.Data; //getter setter @Data @Table(name="memberFile") //db에 저장시키고 싶은 테이블이름 @Entity //table을 따라간다. public class MemberFileVO { @Id @GeneratedValue(strategy= GenerationType.IDENTITY)//자동증가(auto-increment) //mysql은 auto-increment oracle은 시퀀스사용 private long fileNum; // -FK (Foreign Key)를 가지고 있는 테이블을 Owner(관계의 주인)라고 부른다. // -Owner VO 내에서는 FK의 멤버변수를 생략한다. > 대신, MemberVO에다가 MemberFileVO를 선언+@OneToOne 어노테이션을 쓴다. //id지우기 @Column//(name으로 이름도 바꿀 수 있다.) private String fileName; @Column private String oriName; @OneToOne @JoinColumn(name="id") private MemberVO memberVO; }
package com.kodilla.designpatterns2.adapter.bookclasifier; import com.kodilla.designpatterns2.adapter.bookclasifier.libraryb.Book; import com.kodilla.designpatterns2.adapter.bookclasifier.libraryb.BookSignature; import com.kodilla.designpatterns2.adapter.bookclasifier.libraryb.BookStatistics; import com.kodilla.designpatterns2.adapter.bookclasifier.libraryb.Statistics; import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; public class MedianAdaptee implements BookStatistics { Statistics statistics = new Statistics(); @Override public int averagePublicationYear(Map<BookSignature, Book> books) { //tutaj powinien otoczyc metody z libB return statistics.averagePublicationYear(books); } @Override public int medianPublicationYear(Map<BookSignature, Book> books) { return statistics.medianPublicationYear(books); } }
package com.dishcuss.foodie.hub.Activities; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import com.dishcuss.foodie.hub.Models.FoodItems; import com.dishcuss.foodie.hub.Models.FoodsCategory; import com.dishcuss.foodie.hub.Models.Restaurant; import com.dishcuss.foodie.hub.R; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmResults; /** * Created by Naeem Ibrahim on 7/25/2016. */ public class StatusActivity extends Activity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.post_activity_check_in_google_api); //imageView=(ImageView) findViewById(R.id.cross_button); // imageView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // finish(); // } // }); // Get a Realm instance for this thread Realm realm = Realm.getDefaultInstance(); RealmResults<Restaurant> restaurantRealmResults=realm.where(Restaurant.class).findAll(); realm.beginTransaction(); // User user = realm.createObject(User.class); // Create managed objects directly // user.setEmail("nanan"); // user.setName("nanan"); RealmList<FoodItems> foodItems =restaurantRealmResults.get(0).getFoodItemsArrayList(); for(int i=0;i<foodItems.size();i++){ // Log.e("Name : ",""+foodItems.get(i).getName()); // Log.e("ID : ",""+foodItems.get(i).getFoodID()); RealmList<FoodsCategory> foodsCategories=foodItems.get(i).getFoodsCategories(); Log.e("FoodsCategories ",""+foodsCategories.size()); // for (FoodsCategory f :foodsCategories) { // // } for (int j=0;j<foodsCategories.size();j++){ // Log.e("CAT ID : ",""+foodsCategories.get(j).getId()); // Log.e("CAT NAME : ",""+foodsCategories.get(j).getCategoryName()); } } realm.commitTransaction(); realm.close(); // // User user3=new User(); // user3.setEmail(""); // final RealmResults<User> users = realm.where(User.class).findAll(); // users.size(); // => 0 because no dogs have been added to the Realm yet // // User user1 = realm.where(User.class).findFirst(); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
package f.a.a.a; import f.a.a.a.a.b; import java.util.LinkedList; public final class a { private final b unknownTagHandler; public final f.a.a.b.a.a vHC; public int vHD = 0; public a(byte[] bArr, b bVar) { this.vHC = new f.a.a.b.a.a(bArr, bArr.length); this.unknownTagHandler = bVar; } public final int cJN() { return this.vHC.rY(); } public final LinkedList<Integer> cJO() { f.a.a.b.a.a aVar = this.vHC; LinkedList<Integer> linkedList = new LinkedList(); while (aVar.bfI < aVar.bufferSize) { linkedList.add(Integer.valueOf(aVar.rY())); } return linkedList; } public final String cJP() { return this.vHC.readString(); } public final boolean cJQ() { return this.vHC.rY() != 0; } public final com.tencent.mm.bk.b cJR() { f.a.a.b.a.a aVar = this.vHC; int rY = aVar.rY(); if (rY >= aVar.bufferSize - aVar.bfI || rY <= 0) { return com.tencent.mm.bk.b.bi(aVar.dY(rY)); } com.tencent.mm.bk.b t = com.tencent.mm.bk.b.t(aVar.buffer, aVar.bfI, rY); aVar.bfI = rY + aVar.bfI; return t; } public final void cJS() { int ef = f.a.a.b.a.ef(this.vHD); StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("FieldNumber: ").append(f.a.a.b.a.eg(this.vHD)).append(" - "); switch (ef) { case 0: stringBuffer.append("varint (long, int or boolean) value: ").append(this.vHC.rZ()); return; case 1: stringBuffer.append("double value: ").append(Double.toString(this.vHC.readDouble())); return; case 2: stringBuffer.append("Length delimited (String or ByteString) value: ").append(this.vHC.readString()); return; case 5: stringBuffer.append("float value: ").append(Float.toString(this.vHC.readFloat())); return; default: return; } } public final LinkedList<byte[]> IC(int i) { return this.vHC.IC(i); } }
package com.ssgmail.shubhammsoni.materialapp; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import java.util.ArrayList; public class Chart extends Fragment { private Integer[] yData = {1, 1}; private String[] xData = {"data A", "Data B"}; PieChart pieChart; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_chart, container, false); Log.d("chart", "onCreateView: "); Bundle bundle = getArguments(); Integer count_agree = bundle.getInt("agree"); Integer count_disagree = bundle.getInt("disagree"); yData[0] = count_agree; yData[1] = count_disagree; pieChart = (PieChart) view.findViewById(R.id.pie_chart); pieChart.setRotationEnabled(true); pieChart.setTransparentCircleAlpha(0); pieChart.setHoleRadius(0.0f); addDataSet(); return view; } private void addDataSet() { ArrayList<PieEntry> y = new ArrayList<>(); ArrayList<String> x = new ArrayList<>(); for (int i = 0; i < yData.length; i++) { y.add(new PieEntry(yData[i], i)); } for (int i = 1; i < xData.length; i++) { x.add(xData[i]); } PieDataSet piedataset = new PieDataSet(y, "pie"); piedataset.setSliceSpace(2); piedataset.setValueTextSize(12); ArrayList<Integer> color = new ArrayList<>(); color.add(Color.GREEN); color.add(Color.RED); PieData piedata = new PieData(piedataset); pieChart.setData(piedata); piedataset.setColors(color); pieChart.invalidate(); } }
package com.ibm.watson.developer_cloud.android.myapplication; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer; import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice; import java.util.ArrayList; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; /**################################################################################################# * Copyright IBM Corporation 2016 # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * # * # * Created by: Rafat Khandaker # * # * on: 12-08-16 # * Version: 1.0 # *################################################################################################*/ public class MainActivity extends AppCompatActivity{ @BindView(R.id.text_view) TextView textView; @BindView(R.id.button) Button button; @BindView(R.id.edit_text) EditText editText; @BindView(R.id.image_button) ImageButton imageButton; private static final int SPEECH = 1; public static String getEditText; private SpeechRecognizer speech; private Intent recognizerIntent; StreamPlayer streamPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); // initialize TextToSpeech executeWatsonTTS(); onMicButton(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to super.onActivityResult(requestCode, resultCode, data); switch(requestCode){ case SPEECH: if(requestCode == RESULT_OK && null!= data){ ArrayList<String> speechText = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); editText.setText(speechText.get(0)); } } } //------------------------------ACTIVATE WATSON TEXT TO SPEECH-------------------------------------- private void executeWatsonTTS(){ button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { System.out.println("The text to speech: " +editText.getText()); textView.setText("TTS: " +editText.getText()); getEditText = String.valueOf(editText.getText()); WatsonTask task = new WatsonTask(); task.execute(new String[]{}); } }); } //---------------------------------WATSON BACKGROUND THREAD----------------------------------------- private class WatsonTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... strings) { runOnUiThread(new Runnable() { @Override public void run() { textView.setText("running the Watson thread"); } }); TextToSpeech textToSpeech = initTextToSpeechService(); streamPlayer = new StreamPlayer(); streamPlayer.playStream(textToSpeech.synthesize(MainActivity.getEditText, Voice.EN_ALLISON)); return "Text to speech done"; } @Override protected void onPostExecute(String s) { textView.setText("TTS stats: " +s); } } private TextToSpeech initTextToSpeechService(){ TextToSpeech service = new TextToSpeech(); String username = "0d6f1399-7b5d-469f-93a9-c6c2fed94f01"; String password = "MZJAwre3bx8J"; service.setUsernameAndPassword(username, password); return service; } //-------------------------------------------------------------------------------------------------- public void onMicButton(){ imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { promptSpeechInput(imageButton.getContext()); } }); } public void promptSpeechInput(Context context){ speech = SpeechRecognizer.createSpeechRecognizer(context); // speech.setRecognitionListener((RecognitionListener) this); recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say Something"); try{ startActivityForResult(recognizerIntent, SPEECH); textView.setText(""); }catch(ActivityNotFoundException notFoundError){ Toast.makeText(MainActivity.this, "speech to text error", Toast.LENGTH_LONG).show(); } } //-----------------------------------Initialize TextToSpeech---------------------------------------- }
package net.createk.pdftool; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { if (args.length != 3 && args.length != 4) { System.err.println("Something went wrong: can't find batches/report file arguments."); System.exit(1); } File pershingDir = null; if (args.length == 4) { pershingDir = new File(args[3]); } File repDir = new File(args[0]); File reportFile = new File(args[1]); File clientList = new File(args[2]); ClientList list = new ClientList(clientList); Report report = null; try { report = new Report(repDir); } catch (IOException e1) { e1.printStackTrace(); } if (pershingDir != null) { Pershing pershing = null; pershing = new Pershing(pershingDir); report.pershing = pershing; } report.run(); try { report.exportReport(reportFile, list); } catch (IOException e) { e.printStackTrace(); } } }
package pages.moproDCC; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import moproDCC.moproDCC.baseFile; public class projectPage extends baseFile { @FindBy(xpath="//input[@id='txtSearch' and @value='Search' ]") WebElement search; @FindBy(xpath="//input[@id='divGobtn' and @class='blackBtn']") WebElement go; @FindBy(xpath="//input[@id='divCreateProject']") WebElement createNewProjectBtn; @FindBy(xpath="//a[@id='ucProjectstatus_anDashboard' ]") WebElement dashLink; public projectPage() { PageFactory.initElements(driver, this); } public String geturl() { String link = dashLink.getAttribute("href"); return link; } public void gotoCreateProject() { createNewProjectBtn.click(); } public void searchProject(String searchData) { search.sendKeys(searchData); go.click(); String url = dashLink.getAttribute("href"); System.out.println(url); } }
package geeks; import java.util.*; import java.util.stream.Collectors; /** * Created by kreddy on 2/20/18. */ public class WordBoggleWorking { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); String[] dic; char[][] boggle; int dicLen, nRow, nCol; while(tc-- > 0) { dicLen = sc.nextInt(); dic = new String[dicLen]; for(int i = 0; i < dicLen; i++) { dic[i] = sc.next(); } nRow = sc.nextInt(); nCol = sc.nextInt(); boggle = new char[nRow][nCol]; for(int r = 0; r < nRow; r++) { for(int c = 0; c < nCol; c++) { boggle[r][c] = sc.next().charAt(0); } } Set<String> wordSet = findWords(dic, dicLen, boggle, nRow, nCol); System.out.println(wordSet.size() == 0 ? "-1" : wordSet.stream().collect(Collectors.joining(" "))); } } private static class Trie { boolean leaf; Trie[] children; Trie() { leaf = false; children = new Trie[256]; } void addWord(String word) { int n = word.length(); Trie node = this; char key; for(int i = 0; i < n; i++) { if(node.children[key = word.charAt(i)] == null) { node.children[key] = new Trie(); } node = node.children[key]; } node.leaf = true; } Trie getChild(char key) { return children[key]; } } private static Set<String> findWords(String[] dic, int dicLen, char[][] boggle, int nRow, int nCol) { Trie dicTrie = new Trie(); for(int i = 0; i < dicLen; i++) { dicTrie.addWord(dic[i]); } Set<String> wordSet = new TreeSet<>(); boolean[][] vis = new boolean[nRow][nCol]; for(int r = 0; r < nRow; r++) { for(int c = 0; c < nCol; c++) { findWords(dicTrie.getChild(boggle[r][c]), boggle, vis, nRow, nCol, r, c, String.valueOf(boggle[r][c]), wordSet); } } return wordSet; } private static void findWords(Trie dicTrie, char[][] boggle, boolean[][] vis, int nRow, int nCol, int row, int col, String word, Set<String> wordSet) { if(dicTrie == null) return; if(dicTrie.leaf) { wordSet.add(word); } vis[row][col] = true; for(int r = Math.max(0, row-1); r <= row+1 && r < nRow; r++) { for(int c = Math.max(0, col-1); c <= col+1 && c < nCol; c++) { if(!vis[r][c]) { findWords(dicTrie.getChild(boggle[r][c]), boggle, vis, nRow, nCol, r, c, word+boggle[r][c], wordSet); } } } vis[row][col] = false; } private static class Pair { int x, y; Pair(int a, int b) { x = a; y = b; } @Override public String toString() { return x + " " + y; } } private static void swap(int[] arr, int x, int y) { int _x = arr[x]; arr[x] = arr[y]; arr[y] = _x; } private static String flatString(int[] arr) { return Arrays.stream(arr) .mapToObj(String::valueOf) .collect(java.util.stream.Collectors.joining(" ")); } private static String flatString2d(int[][] arr) { return Arrays.stream(arr) .flatMapToInt(a->Arrays.stream(a)) .mapToObj(String::valueOf) .collect(java.util.stream.Collectors.joining(" ")); } }
package com.canfield010.mygame.gui; import com.canfield010.mygame.Main; import com.canfield010.mygame.MapHolder; import com.canfield010.mygame.actors.Actor; import com.canfield010.mygame.actors.Villager; import com.canfield010.mygame.item.Log; import com.canfield010.mygame.item.tool.Axe; import com.canfield010.mygame.item.weapon.IronSword; import com.canfield010.mygame.mapsquare.FinalPoint; import com.canfield010.mygame.mapsquare.MapSquare; import com.canfield010.mygame.mapsquare.uppermapsquare.UpperMapSquare; import com.canfield010.mygame.mapsquare.uppermapsquare.plant.OakTree; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; public class Gui extends JFrame { public boolean onMenu = true; public static MapHolder<MapSquare, Integer> mapSquares = Main.backgroundSquares; //public static ActionListener actionListener; public Border btnBorder = BorderFactory.createLineBorder(Color.GREEN, 2); public static final int STARTING_SCREEN_WIDTH = 856; public static final int STARTING_SCREEN_HEIGHT = 482; private int cols = 32; private int rows = 32; private double rowSize = 32; private double colSize = 32; public static final boolean DEBUG = false; private JLayeredPane layeredPane = new JLayeredPane(); JButton[] myBtns = new JButton[1089]; JPanel btnPanel = new JPanel(); JButton playButton = new JButton("Play"); JButton settingsButton = new JButton("Settings"); JPanel panel = new JPanel(); JPanel buttonPanel = new JPanel(); JPanel inventoryPanel = new JPanel(); JPanel hud = new JPanel(); JLabel healthBar = new JLabel(); //JOptionPane inventoryPane = new JOptionPane(); private Gui(String name) { super(name); } //enum InitialSquares { //GRASS, //TREE, //WATER, //STONE, //STONE_WALL //} private void initComponents() { this.setPreferredSize(new Dimension(STARTING_SCREEN_WIDTH, STARTING_SCREEN_HEIGHT)); this.setLayout(new BorderLayout()); btnPanel.setLayout(null); for (int i = 0; i<myBtns.length; i++) { myBtns[i] = makeButton(i); btnPanel.add(myBtns[i]); } playButton.setAlignmentX(Component.CENTER_ALIGNMENT); playButton.setFont(new Font("Arial", Font.PLAIN, Math.min((STARTING_SCREEN_WIDTH /4)/6, (STARTING_SCREEN_HEIGHT /10)))); if (!DEBUG) { playButton.setContentAreaFilled(false); } playButton.setCursor(new Cursor(Cursor.HAND_CURSOR)); settingsButton.setAlignmentX(Component.CENTER_ALIGNMENT); settingsButton.setFont(new Font("Arial", Font.PLAIN, Math.min((STARTING_SCREEN_WIDTH /4)/6, (STARTING_SCREEN_HEIGHT /10)))); if (!DEBUG) { settingsButton.setContentAreaFilled(false); } settingsButton.setCursor(new Cursor(Cursor.HAND_CURSOR)); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); // OMG it took me SO LONG to find this!!! Here's the solution: buttonPanel.setOpaque(false); //inventoryPanel.setOpaque(false); hud.setOpaque(false); hud.setLayout(new BoxLayout(hud, BoxLayout.PAGE_AXIS)); hud.add(healthBar); healthBar.setText(Main.player.health+" health"); panel.setOpaque(false); panel.setLayout(new GridBagLayout()); //inventoryPanel.setLayout(new GridLayout(3,8)); resetSizes(); } public void addListeners() { this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent componentEvent) { resetSizes(); //playButton.setLocation(buttonPanel.getWidth()/2, buttonPanel.getHeight()/2); //settingsButton.setLocation(buttonPanel.getWidth()/2, buttonPanel.getHeight()/2); } });this.addWindowStateListener(event -> { resetSizes(); //playButton.setLocation(buttonPanel.getWidth()/2, buttonPanel.getHeight()/2); //settingsButton.setLocation(buttonPanel.getWidth()/2, buttonPanel.getHeight()/2); }); playButton.addActionListener(e -> { Main.initializeMap(); mapSquares = Main.mapSquares; resetSizes(); // cuz I'm lazy and don't want to redraw here; onMenu = false; layeredPane.remove(panel); layeredPane.moveToFront(btnPanel); layeredPane.moveToFront(hud); healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } getMovableSquares(); //System.out.println("Click 1"); //System.out.println(mapSquares.get(0,0).occupant); }); settingsButton.addActionListener(e -> { System.out.println("Click 2"); }); addButtonListeners(); } public void addButtonListeners() { /*for (int index = 0; index<myBtns.length; index++) { int finalIndex = index; myBtns[index].addActionListener(e -> { System.out.println((finalIndex/rows)+Main.playerPosition.x-(rows/2) +", "+((finalIndex%rows)+Main.playerPosition.y-(cols/2))+", "+rows); System.out.println(mapSquares.get((finalIndex/rows)+Main.playerPosition.x-(rows/2), (finalIndex%rows)+Main.playerPosition.x-(cols/2)).lowerMapSquare.name); System.out.println(Main.playerPosition.x+", "+Main.playerPosition.y); //System.out.println(Main.mapSquares.get(finalIndex/rows, finalIndex%rows).lowerMapSquare); FinalPoint pos = mapSquares.get((finalIndex/rows)+Main.playerPosition.x-(rows/2), (finalIndex%rows)+Main.playerPosition.x-(cols/2)).coordinates; //Main.playerPosition = new Point(pos.x, pos.y); for (JButton btn: myBtns) { btn.removeActionListener(ex->{}); } movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), mapSquares.get(Main.playerPosition.x, Main.playerPosition.y).coordinates); });*/ /*for (int index = 0; index<myBtns.length; index++) { int finalIndex = index; myBtns[index].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println((finalIndex/rows)+Main.playerPosition.x-(rows/2) +", "+((finalIndex%rows)+Main.playerPosition.y-(cols/2))+", "+rows); System.out.println(mapSquares.get((finalIndex/rows)+Main.playerPosition.x-(rows/2), (finalIndex%rows)+Main.playerPosition.x-(cols/2)).lowerMapSquare.name); System.out.println(Main.playerPosition.x+", "+Main.playerPosition.y); movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint((finalIndex/rows)+Main.playerPosition.x-(rows/2), (finalIndex%rows)+Main.playerPosition.x-(cols/2))); } }); }*/ for (int index = 0; index<myBtns.length; index++) { int finalIndex = index; /*actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //if (((JButton)e.getSource()).getBorder().equals(btnBorder)) { if (btnBorder.equals(((JButton)e.getSource()).getBorder())) { //System.out.println((finalIndex / rows) + Main.playerPosition.x - (cols / 2) + ", " + ((finalIndex % rows) + Main.playerPosition.y - (rows / 2)) + ", " + rows); //System.out.println(mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.x - (rows / 2)).lowerMapSquare.name); movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); //getMovableSquares(); resetMovableSquares(); //System.out.println(Main.playerPosition.x + ", " + Main.playerPosition.y); } } };*/ MouseAdapter mouseAdapter = new MouseAdapter() { public void mouseClicked(MouseEvent e) { layeredPane.remove(inventoryPanel); if (e.getButton()==MouseEvent.BUTTON3) { JPopupMenu popupMenu = new JPopupMenu(); if (btnBorder.equals(((JButton)e.getSource()).getBorder())) { popupMenu.add(new JMenuItem("Move")).addActionListener(event -> { if (btnBorder.equals(((JButton) e.getSource()).getBorder())) { movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); resetMovableSquares(); Main.tickActors(); } healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } }); } if (Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).getButtons()!=null) { for (UpperMapSquare.Button btn : Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).getButtons()) { //System.out.println(btn); switch (btn) { /*case DESTROY -> { if (Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).upperMapSquare instanceof OakTree && Main.player.inventory.axe != null) { FinalPoint point = null; if (!(myBtns[finalIndex + 1].getBorder()==null)) { point = new FinalPoint((finalIndex / rows) + 1 + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)); } if (!(myBtns[finalIndex - 1].getBorder() == null)) { point = new FinalPoint((finalIndex / rows) - 1 + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)); } if (!(myBtns[finalIndex + cols].getBorder() == null)) { point = new FinalPoint((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + 1 + Main.playerPosition.y - (rows / 2)); } if (!(myBtns[finalIndex - cols].getBorder() == null)) { point = new FinalPoint((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) - 1 + Main.playerPosition.y - (rows / 2)); } //if (point != null) { //System.out.println(point.x + ", " + point.y); //} else { //System.out.println("null"); //} if (point != null) { int finalX = point.x; int finalY = point.y; popupMenu.add(new JMenuItem("Destroy")).addActionListener(event -> { movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint(finalX, finalY)); resetMovableSquares(); //Main.player.inventory.axe.use(Main.mapSquares.get(finalX, finalY)); Main.player.inventory.axe.use(Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); resetSizes(); }); } } }*/ case ATTACK -> popupMenu.add(new JMenuItem("Attack")).addActionListener(event -> { //System.out.println("attacking"); if (Main.player.inventory.meleeWeapon != null) { Main.player.inventory.meleeWeapon.use(Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); } else { Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).occupant.damage(Math.random() > 0.5 ? 1 : 2); } if (Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).occupant==null) { resetSizes(); } Main.tickActors(); healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } }); case USE_ITEM -> popupMenu.add(new JMenuItem("Use Item")).addActionListener(event -> { loadInventory(Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); layeredPane.add(inventoryPanel); layeredPane.moveToFront(inventoryPanel); healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } }); case SHOOT -> { if (Main.player.inventory.rangedWeapon!=null) { popupMenu.add(new JMenuItem("Shoot")).addActionListener(event -> { Main.player.inventory.rangedWeapon.use(Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); Main.tickActors(); healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } }); } } case TRADE -> popupMenu.add(new JMenuItem("Trade")).addActionListener(event -> { loadInventoryTrades(Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); layeredPane.add(inventoryPanel); layeredPane.moveToFront(inventoryPanel); healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } }); } } } /*if (Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).upperMapSquare!=null) { if (Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).upperMapSquare.buttons!=null) { for (com.canfield010.mygame.mapsquare.uppermapsquare.UpperMapSquare.Button btn : Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2)).upperMapSquare.buttons) { switch (btn) { case USE_ITEM -> popupMenu.add(new JMenuItem("Use Item")).addActionListener(event -> { //if (btnBorder.equals(((JButton) e.getSource()).getBorder())) { //System.out.println("usingItem"); loadInventory(Main.mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); //inventoryPanel.setBackground(Color.RED); layeredPane.add(inventoryPanel); layeredPane.moveToFront(inventoryPanel); //for (int index = 0; index<24; index++) { //switch (index) { //case 0 -> //} //} //inventoryPanel.setVisible(true); // inventoryPanel.setVisible(true); //} }); case DESTROY -> popupMenu.add(new JMenuItem("Destroy")).addActionListener(event -> { if (btnBorder.equals(((JButton) e.getSource()).getBorder())) { movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); resetMovableSquares(); } }); } } } }*/ popupMenu.show(e.getComponent(), e.getX(), e.getY()); } else { if (btnBorder.equals(((JButton)e.getSource()).getBorder())) { movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.y - (rows / 2))); resetMovableSquares(); Main.tickActors(); } } healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } } }; myBtns[index].addMouseListener(mouseAdapter); } } private void addComponentsToPane() { //inventoryPanel.add(inventoryPanel); buttonPanel.add(playButton); buttonPanel.add(settingsButton); panel.add(buttonPanel); layeredPane.add(btnPanel, 0, 2); layeredPane.add(panel, 0, 0); layeredPane.add(hud, 0, 1); this.add(layeredPane, BorderLayout.CENTER); } private JButton makeButton(int i){ return new JButton(); } private void resetSizes() { btnPanel.setBounds(0, 0, layeredPane.getWidth(), layeredPane.getHeight()); panel.setBounds(0, 0, layeredPane.getWidth(), layeredPane.getHeight()); hud.setBounds(0, 0, layeredPane.getWidth(), layeredPane.getHeight()); inventoryPanel.setBounds(layeredPane.getWidth()/10, layeredPane.getHeight()/10, layeredPane.getWidth()-(layeredPane.getWidth()/5), layeredPane.getHeight()-(layeredPane.getHeight()/5)); double rowPerColumn = (double)layeredPane.getWidth()/(double)layeredPane.getHeight(); double columnsPerRow = (double)layeredPane.getHeight()/(double)layeredPane.getWidth(); int cols1 = (int)Math.floor(Math.sqrt(1089/rowPerColumn)); int rows1 = (int)Math.floor(1089D/(double)cols1); int rows2 = (int)Math.floor(Math.sqrt(1089/columnsPerRow)); int cols2 = (int)Math.floor(1089D/(double)rows2); // choosing minimum values to keep more zoomed in. if (rows1*cols1>rows2*cols2) { cols = cols2; rows = rows2; } else { cols = cols1; rows = rows1; } //cols = Math.min(cols1, cols2); //rows = Math.min(rows1, rows2); //double rowSize; //double colSize; if (layeredPane.getWidth()==0 || layeredPane.getHeight()==0) { rowSize = 1; colSize = 1; } else { rowSize = layeredPane.getWidth()/(rows-1); colSize = layeredPane.getHeight()/(cols-1); } //MapSquare.initalizeImages(); for (int index = 0; index<myBtns.length; index++) { myBtns[index].setBounds((int)(Math.floor(((double)index)%((double)rows))*colSize), (int)(Math.floor(((double)index)/((double)rows))*rowSize), (int)rowSize+1, (int)colSize+1); if (rows==0) { rows = 32; } myBtns[index].setIcon(mapSquares.get((index/rows)+Main.playerPosition.x-(cols/2), (index%rows)+Main.playerPosition.y-(rows/2)).getImage((int)rowSize, (int)rowSize)); } if (!onMenu) { resetMovableSquares(); } healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } layeredPane.moveToFront(hud); layeredPane.moveToFront(panel); } public void movePlayer(FinalPoint start, FinalPoint end) { //final int timing = 1000; //final long t = System.currentTimeMillis(); //long currentTime = System.currentTimeMillis(); /*while (currentTime<(t+timing)) { btnPanel.setLocation((end.x-start.x)*(int)(((double)(currentTime-t+timing))/timing), (end.y-start.y)*(int)(((double)(currentTime-t+timing))/timing)); currentTime = System.currentTimeMillis(); } btnPanel.setLocation(0, 0);*/ /*double playerX;// = start.x; double playerY;// = start.y; double distance = Math.sqrt((start.x*start.x)+(end.y*end.y)); //System.out.println(distance); long t = System.currentTimeMillis(); long currentTime = System.currentTimeMillis(); //System.out.println("got here"); final int timing = 1000; while (currentTime<(t+(distance*timing))) { //System.out.println("animating"); playerX = ((end.x-start.x)*((currentTime-t)/(distance*timing)))+start.x; playerY = ((end.y-start.y)*((currentTime-t)/(distance*timing)))+start.y; //System.out.println(playerX+", "+playerY); //boolean changingPos = false; boolean hasChanged = false; if (end.x>start.x) { while (playerX > Main.playerPosition.x) { Main.playerPosition.x++; hasChanged = true; } //for (int i = rows; i > 0; i--) { //if (i * cols > myBtns.length) break; //for (int index = 0; index < myBtns.length; index++) { //myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); //addButtonListeners(); //} //} } else { while (playerX < Main.playerPosition.x) { Main.playerPosition.x--; hasChanged = true; } //for (int i = 0; i < rows; i++) { //if (i * cols > myBtns.length) break; //for (int index = 0; index < myBtns.length; index++) { //myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); //addButtonListeners(); //} //} } if (end.y>start.y) { while (playerY > Main.playerPosition.y) { Main.playerPosition.y++; hasChanged = true; } //for (int i = cols; i > 0; i--) { //if (i * rows > myBtns.length) break; //for (int index = 0; index < myBtns.length; index++) { //myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); //addButtonListeners(); //} //} } else { while (playerY < Main.playerPosition.y) { Main.playerPosition.y--; hasChanged = true; } //for (int i = 0; i < cols; i++) { //if (i * rows > myBtns.length) break; //for (int index = 0; index < myBtns.length; index++) { //myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); //addButtonListeners(); //} //} } if (hasChanged) { for (int index = 0; index<myBtns.length; index++) { myBtns[index].setIcon(mapSquares.get((index/rows)+Main.playerPosition.x-(rows/2), (index%rows)+Main.playerPosition.y-cols/2).getImage((int)rowSize, (int)rowSize)); } addButtonListeners(); } currentTime = System.currentTimeMillis(); } System.out.println("done"); playerX = ((start.x-end.x)*((currentTime-t)/(distance*1000)))+start.x; playerY = ((start.y-end.y)*((currentTime-t)/(distance*1000)))+start.y;*/ Main.playerPosition.x = end.x; Main.playerPosition.y = end.y; //Main.player.squareOn = mapSquares.get(end.x, end.y); Main.player.move(mapSquares.get(end.x, end.y)); //mapSquares.get(end.x, end.y).occupant = Main.player; //mapSquares.get(end.x, end.y).setActor(Main.player); //mapSquares.get(start.x, start.y).occupant = null; //mapSquares.get(start.x, start.y).setActor(null); /*for (int index = 0; index<myBtns.length; index++) { int finalIndex = index; myBtns[index].setIcon(mapSquares.get((index/rows)+Main.playerPosition.x-(rows/2), (index%rows)+Main.playerPosition.y-cols/2).getImage((int)rowSize, (int)rowSize)); myBtns[index].getActionListeners()[0] = e -> { System.out.println((finalIndex/rows)+Main.playerPosition.x-(rows/2) +", "+((finalIndex%rows)+Main.playerPosition.y-(cols/2))+", "+rows); System.out.println(mapSquares.get((finalIndex/rows)+Main.playerPosition.x-(rows/2), (finalIndex%rows)+Main.playerPosition.x-(cols/2)).lowerMapSquare.name); System.out.println(Main.playerPosition.x+", "+Main.playerPosition.y); //movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint((finalIndex/rows)+Main.playerPosition.x-(rows/2), (finalIndex%rows)+Main.playerPosition.x-(cols/2))); }; }*/ for (int index = 0; index<myBtns.length; index++) { //int finalIndex = index; myBtns[index].setIcon(mapSquares.get((index/rows)+Main.playerPosition.x-(cols/2), (index%rows)+Main.playerPosition.y-(rows/2)).getImage((int)rowSize, (int)rowSize)); /*myBtns[index].removeActionListener(actionListener); actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (((JButton)e.getSource()).getBorder().equals(btnBorder)) { myBtns[finalIndex].addActionListener(actionListener); System.out.println((finalIndex / rows) + Main.playerPosition.x - (cols / 2) + ", " + ((finalIndex % rows) + Main.playerPosition.y - (rows / 2)) + ", " + rows); System.out.println(mapSquares.get((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.x - (rows / 2)).lowerMapSquare.name); movePlayer(new FinalPoint(Main.playerPosition.x, Main.playerPosition.y), new FinalPoint((finalIndex / rows) + Main.playerPosition.x - (cols / 2), (finalIndex % rows) + Main.playerPosition.x - (rows / 2))); System.out.println(Main.playerPosition.x + ", " + Main.playerPosition.y); } } };*/ //myBtns[index].addActionListener(actionListener); } //addButtonListeners(); //System.out.println("done"); //boolean changingPos = false; /*if (end.x>start.x) { while (playerX > Main.playerPosition.x) { Main.playerPosition.x++; for (int i = rows; i > 0; i--) { if (i * cols > myBtns.length) break; for (int index = 0; index < myBtns.length; index++) { myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); addButtonListeners(); } } } } else { while (playerX > Main.playerPosition.x) { Main.playerPosition.x--; for (int i = 0; i < rows; i++) { if (i * cols > myBtns.length) break; for (int index = 0; index < myBtns.length; index++) { myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); addButtonListeners(); } } } } if (end.y>start.y) { while (playerY > Main.playerPosition.y) { Main.playerPosition.y++; for (int i = cols; i > 0; i--) { if (i * rows > myBtns.length) break; for (int index = 0; index < myBtns.length; index++) { myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); addButtonListeners(); } } } } else { while (playerY > Main.playerPosition.y) { Main.playerPosition.y--; for (int i = 0; i < cols; i++) { if (i * rows > myBtns.length) break; for (int index = 0; index < myBtns.length; index++) { myBtns[index].setIcon(mapSquares.get((index / rows) + Main.playerPosition.x - (rows / 2), (index % rows) + Main.playerPosition.y - (cols / 2)).getImage((int) rowSize, (int) rowSize)); addButtonListeners(); } } } }*/ } public void getMovableSquares() { //resetMovableSquares(); MapHolder<Boolean, Byte> availableSquares = Main.player.getSquaresToMoveTo(); /*for (byte x = -6; x<7; x++) { String string = ""; for (byte y = -6; y<7;y++) { string += availableSquares.get(x, y)+", "; } System.out.println(string); }*/ for (byte x = (byte)-63; x<64; x++) { for (byte y = (byte)-63; y<64; y++) { //if (availableSquares.get(x, y)!=null) { //System.out.println("got one!"); //} if (availableSquares.get(x, y)!=null && availableSquares.get(x, y)) { //System.out.println(x+", "+y); //if (x<rows && y<cols) { int theX = x+(cols/2); int theY = y+(rows/2); if (((theX*rows) + (theY%rows))<myBtns.length && ((theX*rows) + (theY%rows))>=0) { myBtns[(theX * rows) + (theY % rows)].setBorder(btnBorder); } //} } } } } public void resetMovableSquares() { for (JButton btn: myBtns) { btn.setBorder(null); } getMovableSquares(); } public void loadInventory(MapSquare square) { inventoryPanel = new JPanel(); inventoryPanel.setOpaque(false); inventoryPanel.setLayout(new GridLayout(3, 9)); inventoryPanel.setBounds(layeredPane.getWidth()/10, layeredPane.getHeight()/10, layeredPane.getWidth()-(layeredPane.getWidth()/5), layeredPane.getHeight()-(layeredPane.getHeight()/5)); JButton btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.axe!=null) { if (Main.player.inventory.axe.isUseful(square)) { btn.addActionListener(e -> { Main.player.inventory.axe.use(square); layeredPane.remove(inventoryPanel); for (Component jBtn: inventoryPanel.getComponents()) { if (jBtn!=null) { if (((JButton) jBtn).getBorder().equals(btnBorder)) { ((JButton) jBtn).setBorder(null); } } } //layeredPane.moveToFront(btnPanel); resetSizes(); Main.tickActors(); }); btn.setBorder(btnBorder); } btn.setIcon(new ImageIcon(Main.player.inventory.axe.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.meleeWeapon!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.meleeWeapon.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.rangedWeapon!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.rangedWeapon.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[0]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[0].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[1]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[1].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[2]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[2].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[3]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[3].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.pickaxe!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.pickaxe.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); for (int index = 11; index < 27; index++) { if (index == 17) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); BufferedImage image = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.BLACK); try { graphics.drawImage(ImageIO.read(new File("img/coin.png")), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 3, null); } catch (Exception ignored) {} graphics.drawString(String.valueOf(Main.player.inventory.coins), (inventoryPanel.getWidth()/9)-((inventoryPanel.getWidth()/9)/2), (inventoryPanel.getHeight()/3)-((inventoryPanel.getHeight()/3)/5)); graphics.dispose(); btn.setIcon(new ImageIcon(image)); } else if (index == 18) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.backpack!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.backpack.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } } else if (index == 19) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); } else if (index == 26) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.addActionListener(e -> { layeredPane.remove(inventoryPanel); for (Component jBtn: inventoryPanel.getComponents()) { if (jBtn!=null) { if (((JButton) jBtn).getBorder().equals(btnBorder)) { ((JButton) jBtn).setBorder(null); } } } layeredPane.moveToFront(btnPanel); layeredPane.moveToFront(hud); healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } Main.tickActors(); }); try { btn.setIcon(new ImageIcon(ImageIO.read(new File("img/bigX.png")).getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); } catch (Exception e) { System.out.println(e); } } else if (index < 16) { /*if (Main.player.inventory.storage!=null) { if (Main.player.inventory.storage[index-11]!=null) { btn = new JButton(String.valueOf(Main.player.inventory.storage[index - 11].count)); } } else { btn = new JButton(); }*/ btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.storage!=null) { if (Main.player.inventory.storage[index-11]!=null) { BufferedImage image = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.BLACK); if (Main.player.inventory.storage[index-11]!=null) { graphics.drawImage(Main.player.inventory.storage[index - 11].getImage(), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 3, null); graphics.drawString(String.valueOf(Main.player.inventory.storage[index - 11].count), (inventoryPanel.getWidth() / 9) - ((inventoryPanel.getWidth() / 9) / 5), (inventoryPanel.getHeight() / 3) - ((inventoryPanel.getHeight() / 3) / 5)); } graphics.dispose(); btn.setIcon(new ImageIcon(image)); } } } else { /*if (Main.player.inventory.storage!=null) { if (Main.player.inventory.storage[index-14]!=null) { btn = new JButton(String.valueOf(Main.player.inventory.storage[index - 14].count)); } } else { btn = new JButton(); }*/ btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); //btn.setVerticalAlignment(SwingConstants.BOTTOM); if (Main.player.inventory.storage!=null) { if (Main.player.inventory.storage[index-14]!=null) { //BufferedImage image = (BufferedImage)((Image)Main.player.inventory.storage[index-14].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); //image.getGraphics().drawString(String.valueOf(Main.player.inventory.storage[index-14].count), btn.getWidth()-(btn.getWidth()/5), btn.getHeight()-(btn.getHeight()/5)); //btn.setIcon(new ImageIcon(image)); //btn.setIcon(new ImageIcon(Main.player.inventory.storage[index-14].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST))); BufferedImage image = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.BLACK); if (Main.player.inventory.storage[index-11]!=null) { graphics.drawImage(Main.player.inventory.storage[index - 11].getImage(), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 3, null); graphics.drawString(String.valueOf(Main.player.inventory.storage[index-11].count), (inventoryPanel.getWidth()/9)-((inventoryPanel.getWidth()/9)/5), (inventoryPanel.getHeight()/3)-((inventoryPanel.getHeight()/3)/5)); } //graphics.drawString(String.valueOf(Main.player.inventory.storage[index-11].count), (inventoryPanel.getWidth()/9)-((inventoryPanel.getWidth()/9)/5), (inventoryPanel.getHeight()/3)-((inventoryPanel.getHeight()/3)/5)); graphics.dispose(); btn.setIcon(new ImageIcon(image)); } } } //btn.setIcon((Icon)Main.player.inventory.storage[index-12].getImage()); //try { //btn.setIcon(new ImageIcon(ImageIO.read(new File("img/bigX.png")))); //} catch (Exception e) { //System.out.println(e); //} } /*if (Main.player.inventory.storage!=null) { for (int index = 10; index < 24; index++) { if (index == 16 || index == 17) continue; if (index < 16) { if (Main.player.inventory.storage[index-10]!=null) { JButton btn = new JButton(); btn.setIcon((Icon)Main.player.inventory.storage[index-10].getImage()); inventoryPanel.add(btn, index); } } else { if (Main.player.inventory.storage[index-12]!=null) { JButton btn = new JButton(); btn.setIcon((Icon)Main.player.inventory.storage[index-12].getImage()); inventoryPanel.add(btn, index); } } } }*/ } public void loadInventoryTrades(MapSquare square) { inventoryPanel = new JPanel(); inventoryPanel.setOpaque(false); inventoryPanel.setLayout(new GridLayout(5, 9)); inventoryPanel.setBounds(layeredPane.getWidth()/10, layeredPane.getHeight()/10, layeredPane.getWidth()-(layeredPane.getWidth()/5), layeredPane.getHeight()-(layeredPane.getHeight()/5)); JButton btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); BufferedImage myImage = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); Graphics2D myGraphics = (Graphics2D) myImage.getGraphics(); myGraphics.setColor(Color.BLACK); myGraphics.drawImage(((Villager)square.occupant).itemToSell.getImage(), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 8, null); myGraphics.drawString(((Villager)square.occupant).cost + " coins", (int)((inventoryPanel.getWidth()/9)-((inventoryPanel.getWidth()/9)/1.5)), (inventoryPanel.getHeight()/5)-((inventoryPanel.getHeight()/5)/5)); myGraphics.dispose(); btn.setIcon(new ImageIcon(myImage)); //System.out.println(Main.player.inventory.axe + ", " + Main.player.inventory.coins + ", " + ((Villager)square.occupant).cost); if (Main.player.inventory.axe==null && Main.player.inventory.coins>=((Villager)square.occupant).cost) { btn.setBorder(btnBorder); btn.addActionListener(e -> { //System.out.println("buying"); Main.player.inventory.coins-=((Villager)square.occupant).cost; Main.player.inventory.axe = new Axe(); layeredPane.remove(inventoryPanel); loadInventoryTrades(square); layeredPane.add(inventoryPanel); layeredPane.moveToFront(inventoryPanel); }); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); myImage = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); myGraphics = (Graphics2D) myImage.getGraphics(); myGraphics.setColor(Color.BLACK); //myGraphics.drawImage(((Villager)square.occupant).itemToSell.getImage(), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 5, null); try { myGraphics.drawImage(ImageIO.read(new File("img/coin.png")), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 5, null); } catch (Exception ignored) {} myGraphics.drawString(1 + " log", (int)((inventoryPanel.getWidth()/9)-((inventoryPanel.getWidth()/9)/1.5)), (inventoryPanel.getHeight()/5)-((inventoryPanel.getHeight()/5)/5)); myGraphics.dispose(); btn.setIcon(new ImageIcon(myImage)); boolean hasWood = false; for (int i = 0; i<12; i++) { if (Main.player.inventory.storage[i] instanceof Log) { if (Main.player.inventory.storage[i].count>0) { hasWood = true; break; } } } if (hasWood) { btn.setBorder(btnBorder); btn.addActionListener(e -> { //System.out.println("buying"); for (int i = 0; i<12; i++) { if (Main.player.inventory.storage[i] instanceof Log) { Main.player.inventory.storage[i].count--; if (Main.player.inventory.storage[i].count==0) { Main.player.inventory.storage[i] = null; } Main.player.inventory.coins++; break; } } //Main.player.inventory.coins-=((Villager)square.occupant).cost; //Main.player.inventory.axe = new Axe(); layeredPane.remove(inventoryPanel); loadInventoryTrades(square); layeredPane.add(inventoryPanel); layeredPane.moveToFront(inventoryPanel); }); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); myImage = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); myGraphics = (Graphics2D) myImage.getGraphics(); myGraphics.setColor(Color.BLACK); myGraphics.drawImage(IronSword.image, 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 8, null); myGraphics.drawString(((Villager)square.occupant).swordCost + " coins", (int)((inventoryPanel.getWidth()/9)-((inventoryPanel.getWidth()/9)/1.5)), (inventoryPanel.getHeight()/5)-((inventoryPanel.getHeight()/5)/5)); myGraphics.dispose(); btn.setIcon(new ImageIcon(myImage)); //System.out.println(Main.player.inventory.axe + ", " + Main.player.inventory.coins + ", " + ((Villager)square.occupant).cost); if (Main.player.inventory.meleeWeapon==null && Main.player.inventory.coins>=((Villager)square.occupant).swordCost) { btn.setBorder(btnBorder); btn.addActionListener(e -> { //System.out.println("buying"); Main.player.inventory.coins-=((Villager)square.occupant).swordCost; Main.player.inventory.meleeWeapon = new IronSword(); layeredPane.remove(inventoryPanel); loadInventoryTrades(square); layeredPane.add(inventoryPanel); layeredPane.moveToFront(inventoryPanel); }); } for (int i = 0; i<9; i++) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.axe!=null) { /*if (Main.player.inventory.axe.isUseful(square)) { btn.addActionListener(e -> { Main.player.inventory.axe.use(square); layeredPane.remove(inventoryPanel); for (Component jBtn: inventoryPanel.getComponents()) { if (jBtn!=null) { if (((JButton) jBtn).getBorder().equals(btnBorder)) { ((JButton) jBtn).setBorder(null); } } } resetSizes(); }); btn.setBorder(btnBorder); }*/ btn.setIcon(new ImageIcon(Main.player.inventory.axe.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.meleeWeapon!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.meleeWeapon.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.rangedWeapon!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.rangedWeapon.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[0]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[0].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[1]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[1].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[2]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[2].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.armor[3]!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.armor[3].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.pickaxe!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.pickaxe.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); for (int index = 11; index < 27; index++) { if (index == 17) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); BufferedImage image = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.BLACK); try { graphics.drawImage(ImageIO.read(new File("img/coin.png")), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 5, null); } catch (Exception ignored) {} graphics.drawString(String.valueOf(Main.player.inventory.coins), (inventoryPanel.getWidth()/9)-((inventoryPanel.getWidth()/9)/2), (inventoryPanel.getHeight()/5)-((inventoryPanel.getHeight()/5)/5)); graphics.dispose(); btn.setIcon(new ImageIcon(image)); } else if (index == 18) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.backpack!=null) { btn.setIcon(new ImageIcon(Main.player.inventory.backpack.getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } } else if (index == 19) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.setVisible(false); } else if (index == 26) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); btn.addActionListener(e -> { layeredPane.remove(inventoryPanel); for (Component jBtn: inventoryPanel.getComponents()) { if (jBtn!=null) { if (((JButton) jBtn).getBorder().equals(btnBorder)) { ((JButton) jBtn).setBorder(null); } } } layeredPane.moveToFront(btnPanel); layeredPane.moveToFront(hud); healthBar.setText(Main.player.health+" health"); if (Main.player.health<=0) { hud.setOpaque(true); hud.setBackground(Color.RED); hud.add(new JLabel("YOU DIED"), BoxLayout.Y_AXIS); } Main.tickActors(); }); try { btn.setIcon(new ImageIcon(ImageIO.read(new File("img/bigX.png")).getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, Image.SCALE_FAST))); } catch (Exception e) { System.out.println(e); } } else if (index < 16) { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.storage!=null) { if (Main.player.inventory.storage[index-11]!=null) { BufferedImage image = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, BufferedImage.TYPE_INT_ARGB);//(BufferedImage)((Image)Main.player.inventory.storage[index-11].getImage().getScaledInstance(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/3, Image.SCALE_FAST)); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.BLACK); if (Main.player.inventory.storage[index-11]!=null) { graphics.drawImage(Main.player.inventory.storage[index - 11].getImage(), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 5, null); graphics.drawString(String.valueOf(Main.player.inventory.storage[index - 11].count), (inventoryPanel.getWidth() / 9) - ((inventoryPanel.getWidth() / 9) / 5), (inventoryPanel.getHeight() / 5) - ((inventoryPanel.getHeight() / 5) / 5)); } graphics.dispose(); btn.setIcon(new ImageIcon(image)); } } } else { btn = new JButton(); inventoryPanel.add(btn); btn.setOpaque(false); if (Main.player.inventory.storage!=null) { if (Main.player.inventory.storage[index-14]!=null) { BufferedImage image = new BufferedImage(inventoryPanel.getWidth()/9, inventoryPanel.getHeight()/5, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.BLACK); if (Main.player.inventory.storage[index-11]!=null) { graphics.drawImage(Main.player.inventory.storage[index - 11].getImage(), 0, 0, inventoryPanel.getWidth() / 9, inventoryPanel.getHeight() / 5, null); graphics.drawString(String.valueOf(Main.player.inventory.storage[index - 11].count), (inventoryPanel.getWidth() / 9) - ((inventoryPanel.getWidth() / 9) / 5), (inventoryPanel.getHeight() / 5) - ((inventoryPanel.getHeight() / 5) / 5)); } graphics.dispose(); btn.setIcon(new ImageIcon(image)); } } } } } public static void createAndShowGui(String name) { Gui frame = new Gui(name); frame.initComponents(); MapSquare.initalizeImages(); frame.addListeners(); frame.addComponentsToPane(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); //frame.getMovableSquares(); } }
package util; import static java.lang.Integer.max; /** * Created by SRIN on 7/19/2017. */ public class RedBlackTree<Value> { final int RED = 1; final int BLACK = 2; public class Node { Integer key; Value value; Node left, right, parent; int color; Node (Integer key, Value value) { this.key = key; this.value = value; left = right = parent = null; color = RED; } Node() { left = right = parent = null; color = BLACK; } } Node root, x, y, now; Node NIL; public RedBlackTree() { NIL = new Node(); root = NIL; } public void insert(Integer key, Value value) { now = new Node(key, value); now.left = now.right = now.parent = NIL; x = root; y = NIL; while (x != NIL) { y = x; if(now.key.compareTo(x.key) < 0) { x = x.left; } else if(now.key.compareTo(x.key) > 0) { x = x.right; } else { x.value = value; return; } } if(y == NIL) { root = now; } else if (now.key.compareTo(y.key) < 0) { y.left = now; } else { y.right = now; } now.parent = y; insert_fix(now); } public void print() { print(root); } public void clear() { clear(root); root = NIL; } public Node search (Integer key) { x = root; while (x != NIL) { if ((key - x.key) < 0) { x = x.left; } else if ((key - x.key) > 0) { x = x.right; } else break; } return x; } public Value get (Integer key) { x = root; while (x != NIL) { if ((key - x.key) < 0) { x = x.left; } else if ((key - x.key) > 0) { x = x.right; } else break; } return x.value; } public int depth() { return depth(root); } public void delete_node(Node z) { Node y = z; int y_original_color = y.color; if(z.left == NIL) { x = z.right; transplant(z, z.right); } else if (z.right == NIL) { x = z.left; transplant(z, z.left); } else { y = tree_minimum(z.right); y_original_color = y.color; x = y.right; if(y.parent == z) { x.parent = y; } else { transplant(y, y.right); y.right = z.right; y.right.parent = y; } transplant(z, y); y.left = z.left; y.left.parent = y; y.color = z.color; } if(y_original_color == BLACK) delete_fixup(x); } private Node tree_minimum(Node node) { while (node.left != NIL) { node = node.left; } return node; } private void transplant(Node u, Node v) { if(u.parent == NIL) root = v; else if (u == u.parent.left) u.parent.left = v; else u.parent.right = v; v.parent = u.parent; } private void delete_fixup(Node x) { while(x != root && x.color == BLACK) { if(x == x.parent.left) { Node w = x.parent.right; if(w.color == RED) { w.color = BLACK; x.parent.color = RED; left_rotate(x.parent); w = x.parent.right; } if(w.left.color == BLACK && w.right.color == BLACK) { w.color = RED; x = x.parent; } else if (w.right.color == BLACK) { w.left.color = BLACK; w.color = RED; right_rotate(w); w = x.parent.right; } else { w.color = x.parent.color; x.parent.color = BLACK; w.right.color = BLACK; left_rotate(x.parent); x = root; } } } x.color = BLACK; } private int depth(Node n) { if(n == NIL) return 0; return 1 + max(depth(n.left), depth(n.right)); } public void print (Node n) { if (n == NIL) return; print(n.left); System.out.println("Key: " + n.key + " value: " + n.value + " Color: " + n.color); print(n.right); } private void clear(Node n) { if(n == NIL) return; clear(n.left); clear(n.right); n = null; } private void left_rotate(Node x) { y = x.right; x.right = y.left; if(x.right != NIL) { x.right.parent = x; } y.parent = x.parent; if(x.parent == NIL) { root = y; } else if (x.parent.left == x) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; } private void right_rotate(Node y) { x = y.left; y.left = x.right; if(y.left != NIL) { y.left.parent = y; } x.parent = y.parent; if(y.parent == NIL) { root = x; } else if (y.parent.left == y) { y.parent.left = x; } else { y.parent.right = x; } x.right = y; y.parent = x; } private void insert_fix(Node x) { while (x.parent.color == RED) { if(x.parent.parent.left == x.parent) { y = x.parent.parent.right; if(y.color == RED) { y.color = BLACK; x.parent.color = BLACK; x.parent.parent.color = RED; x = x.parent.parent; } else { if(x.parent.right == x) { x = x.parent; left_rotate(x); } x.parent.color = BLACK; x.parent.parent.color = RED; right_rotate(x.parent.parent); } } else { y = x.parent.parent.left; if(y.color == RED) { y.color = BLACK; x.parent.color = BLACK; x.parent.parent.color = RED; x = x.parent.parent; } else { if(x.parent.left == x) { x = x.parent; right_rotate(x); } x.parent.color = BLACK; x.parent.parent.color = RED; left_rotate(x.parent.parent); } } } root.color = BLACK; } }
package pro.eddiecache.kits.disk.indexed; import java.io.Serializable; public class IndexedDiskElementDescriptor implements Serializable, Comparable<IndexedDiskElementDescriptor> { private static final long serialVersionUID = 1L; long pos; int len; public IndexedDiskElementDescriptor(long pos, int len) { this.pos = pos; this.len = len; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[DED: "); sb.append(" pos = " + pos); sb.append(" len = " + len); sb.append("]"); return sb.toString(); } @Override public int hashCode() { return Long.valueOf(this.pos).hashCode() ^ Integer.valueOf(len).hashCode(); } @Override public boolean equals(Object o) { if (o == null) { return false; } else if (o instanceof IndexedDiskElementDescriptor) { IndexedDiskElementDescriptor ided = (IndexedDiskElementDescriptor) o; return pos == ided.pos && len == ided.len; } return false; } /** * 重写排序规则: * 1. length: 数据的长度 * 2. position: 数据存放的起始位置 */ @Override public int compareTo(IndexedDiskElementDescriptor o) { if (o == null) { return 1; } if (o.len == len) { if (o.pos == pos) { return 0; } else if (o.pos < pos) { return -1; } else { return 1; } } else if (o.len > len) { return -1; } else { return 1; } } }
package samples.jsr305.nullness; import javax.annotation.Nullable; public class AnnotatedReturnValue { @Nullable public Object method() { return null; } }
/* * 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 com.pizzahouse.service; import com.pizzahouse.exceptions.ResourceNotFoundException; import com.pizzahouse.model.Role; import com.pizzahouse.model.User; import org.springframework.data.jpa.domain.Specifications; import java.util.List; import java.util.Map; /** * @author stargazer */ public interface UserManagementService { List<User> findAll(); List<User> findAll(Specifications specifications); Map<Long, User> asMap(); Map<Long, Role> roleAsMap(); User find(Long id); void delete(Long id) throws ResourceNotFoundException; User save(User user) throws ResourceNotFoundException; User saveNew(User user, String desiredRole) throws ResourceNotFoundException; }
package tictactoe; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static tictactoe.Square.*; public class Board { private final Map<Square, Player> takenSquares; public Board() { takenSquares = new HashMap<>(); } private Board(HashMap<Square, Player> squares) { takenSquares = squares; } public boolean alreadyTaken(Square square) { return takenSquares.containsKey(square); } public Board take(Square square, Player player) { HashMap<Square, Player> squares = new HashMap<>(takenSquares); squares.put(square, player); return new Board(squares); } public boolean isFull() { return this.takenSquares.size() == 9; } public boolean hasWon(Player currentPlayer) { Stream<Stream<Square>> winningMoves = Stream.of( Stream.of(TOP_LEFT, TOP_MIDDLE, TOP_RIGHT), Stream.of(CENTRE_LEFT, MIDDLE, CENTRE_RIGHT), Stream.of(BOTTOM_LEFT, BOTTOM_MIDDLE, BOTTOM_RIGHT), Stream.of(BOTTOM_LEFT, MIDDLE, TOP_RIGHT), Stream.of(TOP_LEFT, MIDDLE, BOTTOM_RIGHT), Stream.of(TOP_LEFT, CENTRE_LEFT,BOTTOM_LEFT), Stream.of(TOP_MIDDLE, MIDDLE, BOTTOM_MIDDLE), Stream.of(TOP_RIGHT, CENTRE_RIGHT, BOTTOM_RIGHT) ); return winningMoves.anyMatch(combo -> combo.allMatch(squaresTakenByPlayer(currentPlayer)::contains)); } private Set<Square> squaresTakenByPlayer(Player player) { return takenSquares.entrySet().stream() .filter(entry -> entry.getValue().equals(player)) .map(Map.Entry::getKey).collect(Collectors.toSet()); } }
package com.pcms.util; public interface PcmsConst { /** * 生成文件存放地址 */ String FILEPATH = "/usr/local/website/model"; //String FILEPATH = "D://model"; //String FILEPATH = "/Users/feng/html"; /** * 结果页面存放地址 */ String RESULTPATH = "/usr/local/website/result"; String EXCELPATH = "/usr/local/excel"; //String FILEPATH = "//Users/feng/html"; //String EXCELPATH = "/Users/feng/excel"; String RESPCODE = "respCode"; String RESPMSD = "respMsd"; String url = "http://www.nitethoughts.club/model/"; String REQUESTTYPE_NOTFOUNDMOIVE = "findMovie"; String REQUESTTYPE_MOIVELINKNOTUSE = "linkINvalid"; interface RequestMoive { String STATUS_INIT = "0"; String STATUS_HASHANDLE = "1"; } }
/** * @version 1.00 2003-08-10 * @author S Kannan */ package com.mycom.calculator; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; public class AboutDialog extends JDialog { private JPanel logoPanel; public AboutDialog(Frame owner, String title, boolean modal, ImageIcon icon) { super(owner, title, modal); logoPanel = new JPanel(); logoPanel.setBorder(BorderFactory.createLoweredBevelBorder()); JPanel labelPanel = new JPanel(); labelPanel.setBorder(BorderFactory.createRaisedBevelBorder()); labelPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); JPanel okPanel = new JPanel(); okPanel.setBorder(BorderFactory.createRaisedBevelBorder()); JPanel okPanel1 = new JPanel(); JLabel logoLabel = new JLabel(icon, JLabel.LEFT); //JLabel logoLabel = new JLabel(new ImageIcon("C:\\Java_Codes\\Calculator3S.ico")); JLabel nameLabel1 = new JLabel("Java2-Swing Calculator Version 4.0", JLabel.LEFT); JLabel nameLabel2 = new JLabel("Developed by S. Kannan", JLabel.LEFT); JLabel nameLabel3 = new JLabel("Copyright(C) 2001 - 2005 SK Corp.", JLabel.LEFT); JLabel nameLabel4 = new JLabel(" ", JLabel.LEFT); JLabel licenseLabel = new JLabel("This product is licensed to: ", JLabel.RIGHT); JButton okButton = new JButton("OK"); okButton.setPreferredSize(new Dimension(75, 25)); okButton.setForeground(Color.blue); okButton.setToolTipText("Click to close"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { //setVisible(false); dispose(); } }); okButton.requestFocus(); //requestFocusInWindow(); logoPanel.add(logoLabel); labelPanel.add(nameLabel1); labelPanel.add(nameLabel2); labelPanel.add(nameLabel3); labelPanel.add(nameLabel4); //okPanel.setLayout(new BorderLayout()); okPanel.setLayout(new GridLayout(3, 1, 1, 1)); okPanel.add(licenseLabel); okPanel.add(new JLabel(" ", JLabel.RIGHT)); okPanel1.add(okButton); okPanel.add(okPanel1); getContentPane().add("West", logoPanel); getContentPane().add("Center", labelPanel); getContentPane().add("South", okPanel); setResizable(false); setSize(350, 250); //setLocation(280, 100); //setVisible(true); } }
package com.wit.getaride; import com.parse.ParseUser; import android.app.Activity; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.v4.app.FragmentActivity; import android.support.v7.app.ActionBarActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.PopupWindow; import android.widget.Toast; public class Base extends FragmentActivity{ public GetArideApp app; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (GetArideApp) getApplication(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu){ super.onPrepareOptionsMenu(menu); MenuItem home = menu.findItem(R.id.menuHome); MenuItem dest = menu.findItem(R.id.menuDest); MenuItem svdest = menu.findItem(R.id.menuSvDest); MenuItem logout = menu.findItem(R.id.logout); if(this instanceof MainActivity){ home.setEnabled(false); dest.setEnabled(false); svdest.setEnabled(false); } // if(this instanceof SetDestination){ // dest.setEnabled(false); // } return true; } public void homeClicked(MenuItem item){ startActivity(new Intent(this, MainActivity.class)); } public void destClicked(MenuItem item){ // startActivity(new Intent(this, SetDestination.class)); } public void savedDests(MenuItem item){ // startActivity (new Intent(this, SavedDestinations.class)); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void openProfile(MenuItem item){ //startActivity (new Intent(this, Profile.class)); } //checkGPS checks if gps is on or not, if not show a message with link to phones settings. public void checkGPS(){ LocationManager manager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); boolean enabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER); if(!enabled) { LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE); final View popupMsg = inflater.inflate(R.layout.popup, (ViewGroup)findViewById(R.id.popup_element)); final PopupWindow window = new PopupWindow(popupMsg, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true); Button settings = (Button)popupMsg.findViewById(R.id.btnSettings); settings.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { window.dismiss(); Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); new Handler().postDelayed(new Runnable(){ public void run() { window.showAtLocation(popupMsg, Gravity.CENTER, 0, 0); } }, 100L); } } public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub } }
package buttons.characters; import buttons.multiTransitions.CharacterClick; import engine.Menu; import components.Button; public class NyxButton extends Button { public NyxButton(int x, int y, String text, int width, int height, String imagePath) { super(x, y, text, width, height, imagePath); } @Override public void onClicked() { m.nyxMovie.play(); m.children().addAll(m.movieScreen.vBox(), m.nyxDescriptionScreen.vBox(), m.nyxMovieScreen.vBox(), m.startGameScreen.vBox()); Menu.characterId = 0; } @Override public void style() { championStyle = true; } @Override public void transitions() { CharacterClick.characterTransition(); } }
package com.tencent.mm.plugin.account.security.ui; import android.os.Message; import com.tencent.mm.sdk.platformtools.ag; class MySafeDeviceListUI$3 extends ag { final /* synthetic */ MySafeDeviceListUI eOK; MySafeDeviceListUI$3(MySafeDeviceListUI mySafeDeviceListUI) { this.eOK = mySafeDeviceListUI; } public final void handleMessage(Message message) { MySafeDeviceListUI.b(this.eOK).notifyDataSetChanged(); super.handleMessage(message); } }
public class Vanne extends Branchement { public Vanne(Compteur compteur) { super(compteur); } }
package org.metaborg.sunshine; import java.util.Map; import java.util.Map.Entry; import org.metaborg.core.MetaborgException; import org.metaborg.sunshine.arguments.MainArguments; import org.metaborg.util.log.ILogger; import org.metaborg.util.log.LoggerUtils; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; import javax.inject.Inject; import javax.inject.Named; import spoofax.core.cmd.command.ICommand; public class Runner { private static final ILogger logger = LoggerUtils.logger(Runner.class); private final Map<String, ICommand> localCommands; private final Map<String, ICommand> remoteCommands; @Inject public Runner(@Named("local") Map<String, ICommand> localCommands, @Named("remote") Map<String, ICommand> remoteCommands) { this.localCommands = localCommands; this.remoteCommands = remoteCommands; } public int run(String[] args, boolean remote) { final Map<String, ICommand> commands = remote ? remoteCommands : localCommands; final MainArguments arguments = new MainArguments(); final JCommander jc = new JCommander(arguments); for(Entry<String, ICommand> entry : commands.entrySet()) { jc.addCommand(entry.getKey(), entry.getValue()); } try { jc.parse(args); } catch(ParameterException e) { logger.error(e.getMessage()); final StringBuilder sb = new StringBuilder(); jc.usage(sb); System.err.println(sb.toString()); return -1; } if(arguments.help) { final StringBuilder sb = new StringBuilder(); jc.usage(sb); System.err.println(sb.toString()); return 0; } if(arguments.exit) { logger.info("Exitting immediately for testing purposes"); return 0; } final ICommand command = commands.get(jc.getParsedCommand()); if(command == null) { logger.error("No command was specified"); final StringBuilder sb = new StringBuilder(); jc.usage(sb); System.err.println(sb.toString()); return -1; } if(!command.validate()) { final StringBuilder sb = new StringBuilder(); jc.usage(jc.getParsedCommand(), sb); System.err.println(sb.toString()); return -1; } try { return command.run(); } catch(MetaborgException e) { logger.error("Error during command execution", e); return -1; } } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BeschichtungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BeschichtungsEinheitType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BeschichtungsVerfahrenEnum; import java.io.StringWriter; import java.math.BigInteger; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; public class BeschichtungTypeBuilder { public static String marshal(BeschichtungType beschichtungType) throws JAXBException { JAXBElement<BeschichtungType> jaxbElement = new JAXBElement<>(new QName("TESTING"), BeschichtungType.class , beschichtungType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private int id; private String werkstoff; private String charge; private String materialnummer; private Double dicke; private BeschichtungsEinheitType einheitDicke; private BeschichtungsVerfahrenEnum verfahren; private String oberflaechenAusfuehrung; private Double saumbreiteRechts; private Double saumbreiteLinks; private XMLGregorianCalendar zeitpunkt; private String messmethodeBeschichtungsdicke; private Double beschichtungsdickeLinks; private Double beschichtungsdickeMitte; private Double beschichtungsdickeRechts; private Double beschichtungsdickeMaxWert; private Double beschichtungsdickeExtremMaxWert; private Double beschichtungsdickeMinWert; private Double beschichtungsdickeExtremMinWert; private Double beschichtungsdickeRand1Mittelwert; private Double beschichtungsdickeRand1StdAbw; private Double beschichtungsdickeMitteMittelwert; private Double beschichtungsdickeMitteStdAbw; private Double beschichtungsdickeRand2Mittelwert; private Double beschichtungsdickeRand2StdAbw; private Double beschichtungsdickeMittelwert; private Double beschichtungsdickeStdAbw; private Double beschichtungsdickeMaxWertStdAbw; private Double beschichtungsdickeExtremMaxWertStdAbw; private Double beschichtungsdickeMinWertStdAbw; private Double beschichtungsdickeExtremMinWertStdAbw; private BigInteger schichtNr; public BeschichtungTypeBuilder setId(int value) { this.id = value; return this; } public BeschichtungTypeBuilder setWerkstoff(String value) { this.werkstoff = value; return this; } public BeschichtungTypeBuilder setCharge(String value) { this.charge = value; return this; } public BeschichtungTypeBuilder setMaterialnummer(String value) { this.materialnummer = value; return this; } public BeschichtungTypeBuilder setDicke(Double value) { this.dicke = value; return this; } public BeschichtungTypeBuilder setEinheitDicke(BeschichtungsEinheitType value) { this.einheitDicke = value; return this; } public BeschichtungTypeBuilder setVerfahren(BeschichtungsVerfahrenEnum value) { this.verfahren = value; return this; } public BeschichtungTypeBuilder setOberflaechenAusfuehrung(String value) { this.oberflaechenAusfuehrung = value; return this; } public BeschichtungTypeBuilder setSaumbreiteRechts(Double value) { this.saumbreiteRechts = value; return this; } public BeschichtungTypeBuilder setSaumbreiteLinks(Double value) { this.saumbreiteLinks = value; return this; } public BeschichtungTypeBuilder setZeitpunkt(XMLGregorianCalendar value) { this.zeitpunkt = value; return this; } public BeschichtungTypeBuilder setMessmethodeBeschichtungsdicke(String value) { this.messmethodeBeschichtungsdicke = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeLinks(Double value) { this.beschichtungsdickeLinks = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMitte(Double value) { this.beschichtungsdickeMitte = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeRechts(Double value) { this.beschichtungsdickeRechts = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMaxWert(Double value) { this.beschichtungsdickeMaxWert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeExtremMaxWert(Double value) { this.beschichtungsdickeExtremMaxWert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMinWert(Double value) { this.beschichtungsdickeMinWert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeExtremMinWert(Double value) { this.beschichtungsdickeExtremMinWert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeRand1Mittelwert(Double value) { this.beschichtungsdickeRand1Mittelwert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeRand1StdAbw(Double value) { this.beschichtungsdickeRand1StdAbw = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMitteMittelwert(Double value) { this.beschichtungsdickeMitteMittelwert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMitteStdAbw(Double value) { this.beschichtungsdickeMitteStdAbw = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeRand2Mittelwert(Double value) { this.beschichtungsdickeRand2Mittelwert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeRand2StdAbw(Double value) { this.beschichtungsdickeRand2StdAbw = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMittelwert(Double value) { this.beschichtungsdickeMittelwert = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeStdAbw(Double value) { this.beschichtungsdickeStdAbw = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMaxWertStdAbw(Double value) { this.beschichtungsdickeMaxWertStdAbw = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeExtremMaxWertStdAbw(Double value) { this.beschichtungsdickeExtremMaxWertStdAbw = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeMinWertStdAbw(Double value) { this.beschichtungsdickeMinWertStdAbw = value; return this; } public BeschichtungTypeBuilder setBeschichtungsdickeExtremMinWertStdAbw(Double value) { this.beschichtungsdickeExtremMinWertStdAbw = value; return this; } public BeschichtungTypeBuilder setSchichtNr(BigInteger value) { this.schichtNr = value; return this; } public BeschichtungType build() { BeschichtungType result = new BeschichtungType(); result.setId(id); result.setWerkstoff(werkstoff); result.setCharge(charge); result.setMaterialnummer(materialnummer); result.setDicke(dicke); result.setEinheitDicke(einheitDicke); result.setVerfahren(verfahren); result.setOberflaechenAusfuehrung(oberflaechenAusfuehrung); result.setSaumbreiteRechts(saumbreiteRechts); result.setSaumbreiteLinks(saumbreiteLinks); result.setZeitpunkt(zeitpunkt); result.setMessmethodeBeschichtungsdicke(messmethodeBeschichtungsdicke); result.setBeschichtungsdickeLinks(beschichtungsdickeLinks); result.setBeschichtungsdickeMitte(beschichtungsdickeMitte); result.setBeschichtungsdickeRechts(beschichtungsdickeRechts); result.setBeschichtungsdickeMaxWert(beschichtungsdickeMaxWert); result.setBeschichtungsdickeExtremMaxWert(beschichtungsdickeExtremMaxWert); result.setBeschichtungsdickeMinWert(beschichtungsdickeMinWert); result.setBeschichtungsdickeExtremMinWert(beschichtungsdickeExtremMinWert); result.setBeschichtungsdickeRand1Mittelwert(beschichtungsdickeRand1Mittelwert); result.setBeschichtungsdickeRand1StdAbw(beschichtungsdickeRand1StdAbw); result.setBeschichtungsdickeMitteMittelwert(beschichtungsdickeMitteMittelwert); result.setBeschichtungsdickeMitteStdAbw(beschichtungsdickeMitteStdAbw); result.setBeschichtungsdickeRand2Mittelwert(beschichtungsdickeRand2Mittelwert); result.setBeschichtungsdickeRand2StdAbw(beschichtungsdickeRand2StdAbw); result.setBeschichtungsdickeMittelwert(beschichtungsdickeMittelwert); result.setBeschichtungsdickeStdAbw(beschichtungsdickeStdAbw); result.setBeschichtungsdickeMaxWertStdAbw(beschichtungsdickeMaxWertStdAbw); result.setBeschichtungsdickeExtremMaxWertStdAbw(beschichtungsdickeExtremMaxWertStdAbw); result.setBeschichtungsdickeMinWertStdAbw(beschichtungsdickeMinWertStdAbw); result.setBeschichtungsdickeExtremMinWertStdAbw(beschichtungsdickeExtremMinWertStdAbw); result.setSchichtNr(schichtNr); return result; } }
package com.eluniversal.test.core.petitions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; public class JsonBuilder { public static String parseJson(Object entity) { Field[] parameters = entity.getClass().getDeclaredFields(); JSONObject jsonObject = null; if (parameters != null) { try { jsonObject = new JSONObject(); for (Field param : parameters) { String name = param.getName(); param.setAccessible(true); Object value = param.get(entity); Object type = param.getType(); if (value == null) { if (type == int.class || type == long.class || type == Long.class) { jsonObject.accumulate(name, 0); } else { if (type == List.class) jsonObject.accumulate(name, new JSONArray()); else jsonObject.accumulate(name, new String()); } } else { if (type == List.class) { List<String> objs = (List<String>)value; JSONArray jsonArray = new JSONArray(); for (int i=0; i<objs.size(); i++) jsonArray.put(objs.get(i)); jsonObject.accumulate(name, jsonArray); continue; } jsonObject.accumulate(name, param.get(entity)); } } return new String(jsonObject.toString().getBytes(), "UTF-8"); } catch (JSONException e) { e.printStackTrace(); return new String(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return new String(); } catch (IllegalAccessException e) { e.printStackTrace(); return new String(); } } return new String(); } public static String convertInputStreamToString(InputStream inputStream) { String line = new String(); String result = new String(); try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); } catch(IOException e) { e.printStackTrace(); } return result; } protected static Object parseEntity(String jsonString, Object entity) { JSONObject jsonObject = null; Field[] parameters = entity.getClass().getDeclaredFields(); Method[] methods = entity.getClass().getMethods(); try { if (jsonString.startsWith("{") && jsonString.endsWith("}")) { jsonObject = new JSONObject(jsonString); if (jsonObject != null) { for (Field param : parameters) { String name = param.getName(); param.setAccessible(true); Method setter = getMethodFor(methods, name); if (setter != null) { Object value = jsonObject.opt(name); if (value != null) { if (value instanceof JSONArray) { JSONArray jsonArray = (JSONArray)value; List list = new LinkedList(); for (int i=0; i<jsonArray.length(); i++) { Object item = jsonArray.get(i); list.add(item); } value = list; } if (jsonObject.opt(name).getClass() == Integer.class && param.getType() == Long.class) value = new Long((Integer)value); if (value.equals(null)) value = null; setter.invoke(entity, value); } } } } } else { JSONArray jsonArray = new JSONArray(jsonString); List list = new LinkedList<>(); for (int i=0; i<jsonArray.length(); i++) { Object newEntity = entity.getClass().newInstance(); newEntity = parseEntity(jsonArray.get(i).toString(), newEntity); list.add(newEntity); } return list; } } catch (JSONException e) { e.printStackTrace(); return null; } catch (IllegalAccessException e) { e.printStackTrace(); return null; } catch (InvocationTargetException e) { e.printStackTrace(); return null; } catch (InstantiationException e) { e.printStackTrace(); return null; } return entity; } private static Method getMethodFor(Method[] methods, String field) { if (methods != null) { for (int i=0; i<methods.length; i++) { String nameMethod = methods[i].getName(); if (nameMethod.toLowerCase().contains(field.toLowerCase()) && nameMethod.contains("set")) return methods[i]; } } return null; } }
package com.example.userportal.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import javax.persistence.*; import java.io.Serializable; import java.util.Collection; @Data @Accessors(chain = true) @EqualsAndHashCode(callSuper = true) @Entity public class Product extends AbstractAuditingEntity implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "description", columnDefinition = "TEXT") private String description; @Column(name = "company") private String company; @Column(name = "logical_quantity_in_stock") private Integer logicalQuantityInStock; @Column(name = "physical_quantity_in_stock") private Integer physicalQuantityInStock; @Column(name = "unit_price") private Integer unitPrice; @Column(name = "image_url", length = 500) private String imageUrl; @Column(name = "available", length = 500) private Boolean available = true; @JsonIgnore @OneToMany(mappedBy = "product") private Collection<OrderPosition> orderPositions; @ManyToOne @JoinColumn(name = "subcategory_id", referencedColumnName = "id") private ProductSubcategory productSubcategory; @JsonIgnore @OneToMany(mappedBy = "product") private Collection<ShoppingCartPosition> shoppingCartPositions; @OneToMany(mappedBy = "product", cascade = CascadeType.ALL) private Collection<SpecificationPosition> specificationPositions; }
package com.chuxin.family.resource; import com.chuxin.family.R; /** * 颜色角色资源管理类 * @author wentong.men * */ public class CxResourceColor { private CxResourceColor() {} private static CxResourceColor color; /** * * @param flag true 男 , false 女 * @return */ public static CxResourceColor getInstance(){ if(color==null){ color=new CxResourceColor(); } return color; } /** * <!-- colors <color name="cx_fa_role_co_authen_new">#f0e7e0</color> <color name="cx_fa_role_co_authen_new_s">#ecdfd7</color> <color name="cx_fa_role_co_accounting_account_item_pink">#edb2b2</color> <color name="cx_fa_role_co_accounting_account_item_pink_s">#b2c8ed</color> <color name="cx_fa_role_co_accounting_account_item_blue">#b2c8ed</color> <color name="cx_fa_role_co_accounting_account_item_blue_s">#edb2b2</color> --> */ public int co_main_login_authen_new=R.color.cx_fa_role_co_authen_new; public int co_accounting_account_item_pink=R.color.cx_fa_role_co_accounting_account_item_pink; public int co_accounting_account_item_blue=R.color.cx_fa_role_co_accounting_account_item_blue; public void setColorType(boolean flag){ if(flag){ co_main_login_authen_new=R.color.cx_fa_role_co_authen_new; co_accounting_account_item_pink=R.color.cx_fa_role_co_accounting_account_item_pink; co_accounting_account_item_blue=R.color.cx_fa_role_co_accounting_account_item_blue; }else{ co_main_login_authen_new=R.color.cx_fa_role_co_authen_new_s; co_accounting_account_item_pink=R.color.cx_fa_role_co_accounting_account_item_pink_s; co_accounting_account_item_blue=R.color.cx_fa_role_co_accounting_account_item_blue_s; } } }
package com.ojcgame.warp; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import com.alibaba.fastjson.JSON; import com.ojcgame.common.EnvironmentManager; import com.ojcgame.common.OJCUtils; public class WarpDataManager { String[] filesArr; public void WarpAll(String[] files) { filesArr = files; ProgressMonitorDialog progress = new ProgressMonitorDialog(null); IRunnableWithProgress progressTask = new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("正在导出数据", IProgressMonitor.UNKNOWN); WarpAll(filesArr, monitor); } }; try { progress.run(true, false, progressTask); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { filesArr = null; } } @SuppressWarnings("deprecation") private void WarpAll(String[] files, IProgressMonitor monitor) { InputStream is = null; XSSFWorkbook xssfWorkbook = null; List<String> titles = null; Map<String, Object> oneCellData = null; List<Map<String, Object>> AllDataList = null; int fileIndex = 0; try { for (int f = 0, fLength = files.length; f < fLength; ++f) { fileIndex = f; // System.out.println("正在尝试导出:" + files[f]); monitor.subTask("尝试导出:" + files[f]); is = new FileInputStream(EnvironmentManager.getInstance() .getDataSourcesFloderPath() + "\\" + files[f]); xssfWorkbook = new XSSFWorkbook(is); // 读取sheet1 XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); if (xssfSheet == null) continue; titles = new ArrayList<String>(); AllDataList = new ArrayList<Map<String, Object>>(); // 先读取字段 XSSFRow titleRow = xssfSheet.getRow(0); for (int rowIndex = 0, mLength = titleRow.getLastCellNum() + 1; rowIndex < mLength; ++rowIndex) { if (null == titleRow.getCell(rowIndex) || titleRow.getCell(rowIndex).getCellType() == HSSFCell.CELL_TYPE_BLANK) { break; } else { try { // System.out.println(titles.get(cellNum) + "---" // + xssfCell.getStringCellValue()); titles.add(titleRow.getCell(rowIndex) .getStringCellValue()); } catch (IllegalStateException e) { // System.out.println("rowIndex number:" + rowIndex // + " ---- " + files[f]); // System.out.println(titles.get(cellNum) + "---" // + xssfCell.getNumericCellValue()); titles.add(titleRow.getCell(rowIndex) .getNumericCellValue() + ""); } } } // System.out.println(xssfSheet // .getLastRowNum() + 1); // 读取行 for (int rowNum = 2, rLength = xssfSheet.getLastRowNum() + 1; rowNum < rLength; ++rowNum) { XSSFRow xssfRow = xssfSheet.getRow(rowNum); if (xssfRow == null) { continue; } oneCellData = new HashMap<String, Object>(); // 读取列 for (int cellNum = 0; cellNum < titles.size(); ++cellNum) { XSSFCell xssfCell = xssfRow.getCell(cellNum); if (null == xssfCell) continue; if (xssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { // System.out.println(titles.get(cellNum) + "---" // + xssfCell.getNumericCellValue()); oneCellData.put(titles.get(cellNum), xssfCell.getNumericCellValue()); } else if (xssfCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { // System.out.println(titles.get(cellNum) + "---" // + xssfCell.getStringCellValue()); oneCellData.put(titles.get(cellNum), xssfCell.getStringCellValue()); } else if (xssfCell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { // System.out.println(cellNum + "--- kong=======" + // rowNum); // System.out // .println(titles.get(cellNum) + "--- kong"); oneCellData.put(titles.get(cellNum), ""); } else if (xssfCell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { try { // System.out.println(titles.get(cellNum) + // "---" // + xssfCell.getStringCellValue()); oneCellData.put(titles.get(cellNum), xssfCell.getStringCellValue()); } catch (IllegalStateException e) { // System.out.println(titles.get(cellNum) + // "---" // + xssfCell.getNumericCellValue()); oneCellData.put(titles.get(cellNum), xssfCell.getNumericCellValue()); } } } AllDataList.add(oneCellData); } if (null != xssfWorkbook) xssfWorkbook.close(); if (null != is) is.close(); ParseJson(AllDataList, OJCUtils.GetFileName(files[f], ".xlsx")); monitor.worked(f + 1); } } catch (Exception e) { e.printStackTrace(); OJCUtils.ShowDialog("导出失败:" + files[fileIndex]); } finally { monitor.done(); try { if (null != xssfWorkbook) xssfWorkbook.close(); } catch (IOException e) { e.printStackTrace(); OJCUtils.ShowDialog("导出失败:" + files[fileIndex]); } finally { try { if (null != is) is.close(); } catch (Exception e) { e.printStackTrace(); OJCUtils.ShowDialog("导出失败:" + files[fileIndex]); } } } } private void ParseJson(List<Map<String, Object>> pContents, String pFileName) { String jsonStr = JSON.toJSONString(pContents, true); if (null == jsonStr || jsonStr.isEmpty()) { return; } FileWriter writer = null; try { writer = new FileWriter(EnvironmentManager.getInstance() .getDataTargetFloderPath() + "\\" + pFileName + ".json"); writer.write(jsonStr); writer.flush(); } catch (Exception e) { e.printStackTrace(); OJCUtils.ShowDialog("导出JSON失败:" + pFileName); } finally { try { if (null != writer) { writer.flush(); writer.close(); } } catch (Exception e) { e.printStackTrace(); OJCUtils.ShowDialog("导出JSON失败:" + pFileName); } } } // public static void main(String[] args) { // ProgressMonitorDialog progress = new ProgressMonitorDialog(null); // IRunnableWithProgress progressTask = new IRunnableWithProgress() { // @Override // public void run(IProgressMonitor monitor) // throws InvocationTargetException, InterruptedException { // monitor.beginTask("正在导出数据", IProgressMonitor.UNKNOWN); // WarpDataManager wdMgr = new WarpDataManager(); // wdMgr.WarpAll(new String[] { "skill.xlsx" }, monitor); // monitor.done(); // } // }; // // try { // progress.run(true, false, progressTask); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } }
package com.google.android.gms.wearable.internal; import android.net.Uri; import android.os.IBinder; import android.os.Parcel; import android.os.ParcelFileDescriptor; import com.google.android.gms.wearable.Asset; import com.google.android.gms.wearable.ConnectionConfiguration; import com.google.android.gms.wearable.PutDataRequest; class x$a$a implements x { private IBinder aFh; x$a$a(IBinder iBinder) { this.aFh = iBinder; } public final void a(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(22, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, byte b) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeByte(b); this.aFh.transact(53, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeInt(i); this.aFh.transact(43, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, Uri uri) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (uri != null) { obtain.writeInt(1); uri.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(7, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, Uri uri, int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (uri != null) { obtain.writeInt(1); uri.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } obtain.writeInt(i); this.aFh.transact(40, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, Asset asset) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (asset != null) { obtain.writeInt(1); asset.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(13, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, ConnectionConfiguration connectionConfiguration) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (connectionConfiguration != null) { obtain.writeInt(1); connectionConfiguration.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(20, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, PutDataRequest putDataRequest) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (putDataRequest != null) { obtain.writeInt(1); putDataRequest.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(6, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, AddListenerRequest addListenerRequest) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (addListenerRequest != null) { obtain.writeInt(1); addListenerRequest.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(16, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, AncsNotificationParcelable ancsNotificationParcelable) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (ancsNotificationParcelable != null) { obtain.writeInt(1); ancsNotificationParcelable.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(27, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, RemoveListenerRequest removeListenerRequest) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (removeListenerRequest != null) { obtain.writeInt(1); removeListenerRequest.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(17, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, u uVar, String str) { IBinder iBinder = null; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (uVar != null) { iBinder = uVar.asBinder(); } obtain.writeStrongBinder(iBinder); obtain.writeString(str); this.aFh.transact(34, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, String str) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); this.aFh.transact(21, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, String str, int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); obtain.writeInt(i); this.aFh.transact(42, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, String str, ParcelFileDescriptor parcelFileDescriptor) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); if (parcelFileDescriptor != null) { obtain.writeInt(1); parcelFileDescriptor.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(38, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, String str, ParcelFileDescriptor parcelFileDescriptor, long j, long j2) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); if (parcelFileDescriptor != null) { obtain.writeInt(1); parcelFileDescriptor.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } obtain.writeLong(j); obtain.writeLong(j2); this.aFh.transact(39, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, String str, String str2) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); obtain.writeString(str2); this.aFh.transact(31, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, String str, String str2, byte[] bArr) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); obtain.writeString(str2); obtain.writeByteArray(bArr); this.aFh.transact(12, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void a(v vVar, boolean z) { int i = 0; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (z) { i = 1; } obtain.writeInt(i); this.aFh.transact(48, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final IBinder asBinder() { return this.aFh; } public final void b(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(8, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeInt(i); this.aFh.transact(28, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, Uri uri) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (uri != null) { obtain.writeInt(1); uri.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(9, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, Uri uri, int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (uri != null) { obtain.writeInt(1); uri.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } obtain.writeInt(i); this.aFh.transact(41, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, ConnectionConfiguration connectionConfiguration) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (connectionConfiguration != null) { obtain.writeInt(1); connectionConfiguration.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(2, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, u uVar, String str) { IBinder iBinder = null; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (uVar != null) { iBinder = uVar.asBinder(); } obtain.writeStrongBinder(iBinder); obtain.writeString(str); this.aFh.transact(35, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, String str) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); this.aFh.transact(23, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, String str, int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); obtain.writeInt(i); this.aFh.transact(33, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void b(v vVar, boolean z) { int i = 0; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (z) { i = 1; } obtain.writeInt(i); this.aFh.transact(50, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void c(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(14, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void c(v vVar, int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeInt(i); this.aFh.transact(29, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void c(v vVar, Uri uri) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); if (uri != null) { obtain.writeInt(1); uri.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.aFh.transact(11, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void c(v vVar, String str) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); this.aFh.transact(24, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void d(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(15, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void d(v vVar, String str) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); this.aFh.transact(46, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void e(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(18, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void e(v vVar, String str) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); this.aFh.transact(47, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void f(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(19, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void f(v vVar, String str) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); obtain.writeString(str); this.aFh.transact(32, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void g(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(25, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void h(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(26, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void i(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(30, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void j(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(37, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void k(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(49, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void l(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(51, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void m(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(52, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void n(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(3, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void o(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(4, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final void p(v vVar) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.wearable.internal.IWearableService"); obtain.writeStrongBinder(vVar != null ? vVar.asBinder() : null); this.aFh.transact(5, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } }
package com.guli.acl.service; import com.guli.acl.entity.UserRole; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author dtt * @since 2021-04-06 */ public interface UserRoleService extends IService<UserRole> { }
package unalcol.io; import unalcol.service.ServiceCore; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; /** * <p>Title: Write</p> * <p> * <p>Description: Writing methods for a given object</p> * <p> * <p>Copyright: Copyright (c) 2009</p> * <p> * <p>Company: Kunsamu</p> * * @author Jonatan Gomez Perdomo * @version 1.0 */ public abstract class Write<T> { /** * Determines if the default service has been registered in the service infra-structure */ public static Write<?> get(Object owner) { if (ServiceCore.get(Object.class, Write.class) == null) set(Object.class, new WriteWrapper()); return (Write<?>) ServiceCore.get(owner, Write.class); } public static boolean set(Object owner, Write<?> service) { return ServiceCore.set(owner, Write.class, service); } /** * Writes an object to the given writer (The object should has a write method) * * @param obj Object to write * @param writer The writer object * @throws IOException IOException */ @SuppressWarnings("unchecked") public static void apply(Object obj, Writer writer) throws Exception { Write<?> service = (Write<?>) get(obj); ((Write<Object>) service).write(obj, writer); } /** * Gets the persistent version of an object in String version. The Class which the * object belongs to should have associated a ClassPersistence object in the * Persistence class * * @param obj Object that will be stored in an string * @return String containing the persistent version of the object */ public static String toString(Object obj) { try { StringWriter sw = new StringWriter(); apply(obj, sw); sw.close(); return sw.toString(); } catch (Exception e) { } return obj.toString(); } /** * Writes an object to the given writer * * @param obj Object to write * @param writer The writer object * @throws IOException IOException */ public abstract void write(T obj, Writer writer) throws Exception; }
package com.sushichet.sushichet.fragment; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.daimajia.slider.library.SliderLayout; import com.daimajia.slider.library.SliderTypes.BaseSliderView; import com.daimajia.slider.library.SliderTypes.DefaultSliderView; import com.daimajia.slider.library.Tricks.ViewPagerEx; import com.sushichet.sushichet.R; import com.sushichet.sushichet.adapter.PlaceViewPagerAdapter; import com.sushichet.sushichet.controller.SharedPreferenceController; import com.sushichet.sushichet.model.GalleryModel; import com.sushichet.sushichet.model.MenuModel; import com.sushichet.sushichet.rest.ApiClient; import com.sushichet.sushichet.rest.callbacks.GalleryInterface; import com.sushichet.sushichet.rest.callbacks.MenuInterface; import com.sushichet.sushichet.room.database.MyDatabase; import com.sushichet.sushichet.room.entity.Category; import com.sushichet.sushichet.room.entity.Gallery; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MenuFragment extends Fragment implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener, ViewPager.OnPageChangeListener { Activity context; List<Category> menus = new ArrayList<>(); SliderLayout sliderLayout; private TabLayout mTabLayout; PagerAdapter placeViewPagerAdapter; private ViewPager mViewPager; FragmentManager fragmentManager; boolean isFirstTime = true; @Override public void onAttach(Context context) { super.onAttach(context); this.context = (Activity) context; } public MenuFragment() { } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_menu, container, false); Log.d("CHECKADapter", "onCreateveiw"); //gridView = (GridView) view.findViewById(R.id.gridview); fragmentManager = getFragmentManager(); sliderLayout = view.findViewById(R.id.placeslider); if(SharedPreferenceController.getGalleryLog(context)){ laodSlider(); }else{ List<Gallery> galleries = MyDatabase.getAppDatabase(context).getDao().getAllGallery(); for (int i = 0; i < galleries.size(); i++) { DefaultSliderView defaultSliderView = new DefaultSliderView(context); defaultSliderView.image(galleries.get(i).getImage()) .setScaleType(BaseSliderView.ScaleType.Fit) .setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() { @Override public void onSliderClick(BaseSliderView slider) { } }); sliderLayout.addSlider(defaultSliderView); } sliderLayout.startAutoCycle(); sliderLayout.addOnPageChangeListener(MenuFragment.this); sliderLayout.setPresetTransformer(SliderLayout.Transformer.Stack); sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom); sliderLayout.setDuration(4000); } /* sliderLayout.setPagerTransformer(false, new BaseTransformer() { @Override protected void onTransform(View view, float position) { } });*/ mViewPager = view.findViewById(R.id.viewpager); mTabLayout = view.findViewById(R.id.tablayout); return view; } private void laodSlider() { GalleryInterface galleryInterface = ApiClient.getApiClient().create(GalleryInterface.class); Call<List<GalleryModel>> call = galleryInterface.getSlider(); call.enqueue(new Callback<List<GalleryModel>>() { @Override public void onResponse(@NonNull Call<List<GalleryModel>> call, Response<List<GalleryModel>> response) { if (response.body() != null) { SharedPreferenceController.saveGalleryLog(context,false); for (int i = 0; i < response.body().size(); i++) { GalleryModel galleryModel = response.body().get(i); MyDatabase.getAppDatabase(context).getDao().addGallery(new Gallery(galleryModel.getTitle(),galleryModel.getImage(),galleryModel.getLink(),galleryModel.getDescription())); DefaultSliderView defaultSliderView = new DefaultSliderView(context); defaultSliderView.image(response.body().get(i).getImage()) .setScaleType(BaseSliderView.ScaleType.Fit) .setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() { @Override public void onSliderClick(BaseSliderView slider) { } }); sliderLayout.addSlider(defaultSliderView); } sliderLayout.startAutoCycle(); sliderLayout.addOnPageChangeListener(MenuFragment.this); sliderLayout.setPresetTransformer(SliderLayout.Transformer.Stack); sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom); sliderLayout.setDuration(4000); } } @Override public void onFailure(Call<List<GalleryModel>> call, Throwable t) { } }); } @Override public void onStart() { super.onStart(); Log.d("CHECKADapter", "onstart"); placeViewPagerAdapter = new PlaceViewPagerAdapter(getChildFragmentManager(), menus, context); mTabLayout.setupWithViewPager(mViewPager); mViewPager.setAdapter(placeViewPagerAdapter); if (SharedPreferenceController.getCategoryLog(context)) { setMenu(); } else { menus.clear(); menus.addAll(MyDatabase.getAppDatabase(context).getDao().getAllCategories()); placeViewPagerAdapter.notifyDataSetChanged(); } } private void setMenu() { MenuInterface menuInterface = ApiClient.getApiClient().create(MenuInterface.class); Call<List<MenuModel>> call = menuInterface.getMenu(); call.enqueue(new Callback<List<MenuModel>>() { @Override public void onResponse(@NonNull Call<List<MenuModel>> call, Response<List<MenuModel>> response) { if (response.body() != null) { menus.clear(); SharedPreferenceController.saveCategoryLog(context,false); for (int i = 0; i < response.body().size(); i++) { Category category = new Category(response.body().get(i).getId(), response.body().get(i).getName()); menus.add(category); MyDatabase.getAppDatabase(context).getDao().addCategory(category); } placeViewPagerAdapter.notifyDataSetChanged(); } } @Override public void onFailure(Call<List<MenuModel>> call, Throwable t) { } }); } @Override public void onStop() { super.onStop(); menus.clear(); placeViewPagerAdapter.notifyDataSetChanged(); sliderLayout.stopAutoCycle(); MyDatabase.destroyInstance(); Log.d("CHECKADapter", "onStop"); } @Override public void onSliderClick(BaseSliderView slider) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }
import java.awt.*; /** * Created by IntelliJ IDEA. * User: champ9 * Date: 08.Haz.2004 * Time: 16:18:06 * To change this template use File | Settings | File Templates. */ public class Opamp extends CircuitElement { private double lines[][] = { {-3, -1, -2, -1}, {-3, 1, -2, 1}, { 0,-3.5, 2, -3.5}, { 1,-4.5, 1, -2.5}, {-2, -2, 2, 0}, { 2, 0, -2, 2}, {-2, 2, -2, -2}, { 1, -1.5, 1, -0.5}, { 1, 1.5, 1, 0.5}, { 0,3.5, 2,3.5}, { 2, 0, 3, 0} }; double xRatio = 4; double yRatio = 4; double width = 24; double height = 16; int n, i, o; public Opamp(Node n, Node i, Node o) { connections.add(n); connections.add(i); connections.add(o); this.n = n.number; this.i = i.number; this.o = o.number; x = (n.getX() + i.getX() + o.getX()) / 3; y = (n.getY() + i.getY() + o.getY()) / 3; } public void draw(Graphics g) { Node n = (Node)(connections.get(0)); Node i = (Node)(connections.get(1)); Node o = (Node)(connections.get(2)); double last[][]; double sin = 0, cos = 1; if (n != null && i != null && o != null) { sin = ((n.getY() + i.getY()) / 2 - o.getY()) / Math.hypot(o.getX() - (n.getX() + i.getX()) / 2 , o.getY() - (n.getY() + i.getY()) / 2 ); cos = (o.getX() - (n.getX() + i.getX()) / 2) / Math.hypot(o.getX() - (n.getX() + i.getX()) / 2 , o.getY() - (n.getY() + i.getY()) / 2 ); last = new double[lines.length][4]; for (int j = 0; j < lines.length; j++) { last[j][0] = x + (lines[j][0] * xRatio * cos + lines[j][1] * yRatio * sin); last[j][1] = y - (lines[j][0] * xRatio * sin - lines[j][1] * yRatio * cos); last[j][2] = x + (lines[j][2] * xRatio * cos + lines[j][3] * yRatio * sin); last[j][3] = y - (lines[j][2] * xRatio * sin - lines[j][3] * yRatio * cos); g.drawLine((int)(last[j][0]), (int)(last[j][1]), (int)(last[j][2]), (int)(last[j][3])); } cos = (n.getX() - x - width / 2) / Math.hypot(x - width / 2 - n.getX(), y - height / 2 - n.getY()); sin = (y - height / 2 - n.getY()) / Math.hypot(x - width / 2 - n.getX(), y - height / 2 - n.getY()); g.drawLine((int) last[0][0], (int) last[0][1],(int) (n.getX() - n.getRadius() * cos), (int) (n.getY() + n.getRadius() * sin)); cos = (i.getX() - x - width / 2) / Math.hypot(x - width / 2 - i.getX(), y - height / 2 - i.getY()); sin = (y - height / 2 - i.getY()) / Math.hypot(x - width / 2 - i.getX(), y - height / 2 - i.getY()); g.drawLine((int) last[1][0], (int) last[1][1],(int) (i.getX() - i.getRadius() * cos), (int) (i.getY() + i.getRadius() * sin)); cos = (o.getX() - x - width / 2) / Math.hypot(x - width / 2 - o.getX(), y - height / 2 - o.getY()); sin = (y - height / 2 - o.getY()) / Math.hypot(x - width / 2 - o.getX(), y - height / 2 - o.getY()); g.drawLine((int) last[last.length - 1][2], (int) last[last.length - 1][3],(int) (o.getX() - o.getRadius() * cos), (int) (o.getY() + o.getRadius() * sin)); } } public boolean contains(double x, double y) { return (Math.abs(x - this.x) < (width / 2)) && (Math.abs(y - this.y) < (height / 2)); } }
package com.workshops.fightmode; import java.util.List; public interface PaoYingShupIntf { public PaoYingShupType takeAction(List<PaoYingShupType> actionHist); public String getEngineName(); }
package com.tencent.mm.wallet_core.f; class a$a { static a uXR = new a(); }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package com.hybris.backoffice.workflow.impl; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import de.hybris.platform.workflow.WorkflowProcessingService; import de.hybris.platform.workflow.model.WorkflowActionModel; import de.hybris.platform.workflow.model.WorkflowDecisionModel; import de.hybris.platform.workflow.model.WorkflowModel; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.hybris.backoffice.widgets.notificationarea.NotificationService; import com.hybris.backoffice.workflow.WorkflowEventPublisher; import com.hybris.cockpitng.core.util.impl.TypedSettingsMap; import com.hybris.cockpitng.dataaccess.context.impl.DefaultContext; import com.hybris.cockpitng.engine.WidgetInstanceManager; @RunWith(MockitoJUnitRunner.class) public class DefaultWorkflowDecisionMakerTest { @InjectMocks private DefaultWorkflowDecisionMaker workflowDecisionMaker; @Mock private WorkflowProcessingService workflowProcessingService; @Mock private WorkflowEventPublisher workflowEventPublisher; @Mock private NotificationService notificationService; @Mock private WorkflowModel workflow; @Mock private WorkflowActionModel workflowAction; @Mock private WorkflowDecisionModel workflowDecision; @Mock private WidgetInstanceManager widgetInstanceManager; @Mock private TypedSettingsMap widgetSetting; @Test public void shouldSendGlobalEventOnUpdatingWorkflowActions() { //given when(workflowAction.getWorkflow()).thenReturn(workflow); when(widgetInstanceManager.getWidgetSettings()).thenReturn(widgetSetting); //when workflowDecisionMaker.makeDecision(workflowAction, workflowDecision, widgetInstanceManager); //then verify(workflowDecisionMaker.getWorkflowEventPublisher()).publishWorkflowUpdatedEvent(eq(workflow), any(DefaultContext.class)); } }
package genscript.parse; import genscript.parse.exceptions.ParseException; import genscript.parse.exceptions.SyntaxExceptionEndOfBuffer; import genscript.parse.exceptions.SyntaxExceptionNotAccepted; import global.StringOps; import scriptinterface.Index; import java.io.BufferedReader; import java.io.IOException; public class NTProductions extends SearchGraph { public static final Object ACCEPTED = new Object(); @SuppressWarnings("unused") private final String syn = "Syntax"; @SuppressWarnings("unused") private final String tok = "Tokens"; private NTProductions alternativeParser; private boolean mustAccept; public NTProductions(boolean mustAccept, String name) { super(); this.name = name; alternativeParser = null; this.mustAccept = mustAccept; this.mustAccept = mustAccept; } public boolean isMustAccept() { return this.mustAccept; } @SuppressWarnings({"unchecked", "rawtypes"}) private Object subParse(IndexReader source, Node startNode, int startStackMark, int curPriority, int depth, boolean mustAccept) throws ParseException { source.switchParser(this); //Some Readers need the current reading Nonterminal source.setStackMark(startStackMark); Index curIndex = null; //Current read value int startPos = source.getPosition(); //Start parse position, remains the same for this method call int lstValuePos = startPos; //Position of the last found value/accepting state Object lstValue = null; Node curElem = startNode; while (true) { if (curElem.hasParseEvent()) { source.setIntervalPositions(startPos, source.getPosition() - 1); ((ParseAction) curElem.getParseEvent()).action(source); } if (curElem.hasValue()) { lstValue = curElem.getValue(); lstValuePos = source.getPosition(); } //Reached end of buffer? if (source.isEndOfBuffer()) { //Current state must be an accepting one if (this.mustAccept && !curElem.hasValue()) throw new SyntaxExceptionEndOfBuffer(source.getBottomLevelPosition(), null); break; } curIndex = source.read(); int index = curIndex.getIndex(); Node nextElem = curElem.getChild(index); if (nextElem != null) { //deb(depth+" key "+curIndex+" "+source.getPosition()); //Found key if (nextElem.checkPriority(curPriority)) { source.stepBack(); break; } curElem = nextElem; } else { //No key found - step back if (source.canStepBack()) { source.stepBack(); int lstPos = source.getPosition(); if (curElem.hasNonTerminal() && !(curElem == this.root)) { //Root-NonTerminals are handled // externally //deb(depth+" nt "+curIndex+" "+source.getPosition()); //Non terminal NonTerminal nonTerminal = curElem.getNonTerminal(); Object subResult = nonTerminal.getSubSearchGraph().parse(source, nonTerminal.getPriority(), depth + 1, false); source.setStackMark(startStackMark); if (subResult == null) { if (!curElem.hasValue()) { source.setErrorPosition(lstPos); if (mustAccept) throw new SyntaxExceptionNotAccepted(source.getBottomLevelPosition(lstPos), null); } break; } curElem = curElem.getNonTerminal().getNextNode(); } else { if (!curElem.hasValue()) { if (source.getErrorPosition() < lstPos) source.setErrorPosition(lstPos); if (mustAccept) throw new SyntaxExceptionNotAccepted(lstPos, null); } break; } } } } if (curElem.hasUnacceptedChildren() && curIndex != null && !source.isEndOfBuffer() && curElem .isUnacceptedChild(curIndex.getIndex())) { source.resetStack(); return null; } else { if (lstValue instanceof ParseAction<?>) { source.setIntervalPositions(startPos, source.getPosition() - 1); ((ParseAction) lstValue).action(source); } if (lstValue instanceof ContentFactory<?, ?>) { source.setPosition(lstValuePos); source.setIntervalPositions(startPos, source.getPosition() - 1); Object creation = (Object) ((ContentFactory) lstValue).createElem(source); return creation; } else { source.setPosition(lstValuePos); return lstValue; } } } private Object parse(IndexReader source, int curPriority, int depth, boolean mustAccept) throws ParseException { int prePosition = source.getPosition(); int startMark = source.getResultStackSize(); Object result = null; NonTerminal nonTerminal = root.getNonTerminal(); if (nonTerminal != null && nonTerminal.getSubSearchGraph() != this) result = (Object) nonTerminal.getSubSearchGraph().parse(source, curPriority, depth, mustAccept); if (result == null) result = subParse(source, this.root, startMark, curPriority, depth, mustAccept); if (result != null) { source.pushResult(result); if (nonTerminal != null) { Object nextResult; int prevPos = source.getPosition(); while (!source.isEndOfBuffer()) { nextResult = subParse(source, nonTerminal.getNextNode(), startMark, curPriority, depth + 1, false); if (nextResult == null || source.getPosition() == prevPos) break; result = nextResult; source.pushResult(result); prevPos = source.getPosition(); //deb(depth+" ++ "+source.resultStackToString()); } } } if (result == null && root.hasValue()) { return (Object) root.getValue(); } if (alternativeParser != null && result == null) { source.resetStack(); source.setPosition(prePosition); Object res = alternativeParser.parse(source, curPriority, depth, mustAccept); return res; } return result; } /** * Starts at buffer.position, sets position to word end + 1 or one char after WHITESPACE or LINEBREAK * * @return The value of the largest next key in sourceReader, endOfBuffer, if buffer already ends */ public Object parse(IndexReader source) throws ParseException { try { source.parseStart(this); Object result = parse(source, Integer.MIN_VALUE, 0, this.mustAccept); if (mustAccept && !source.isEndOfBuffer()) throw new SyntaxExceptionNotAccepted(source.getBottomLevelPosition(), null); //TODO rightmost position! return result; } catch (ParseException parseException) { parseException.setSource(source); if (!parseException.isPosSet()) parseException.setPos(source.getIntervalStartPos()); throw parseException; } } public boolean accepted(IndexReader key) throws ParseException { return parse(key) != null; } public void removeAlternativeParser() { this.alternativeParser = null; } public NTProductions createAlternativeParser(boolean mustAccept, String name) { NTProductions parser = new NTProductions(mustAccept, name); setAlternativeParser(parser); return parser; } public NTProductions createAlternativeParser(String name) { return createAlternativeParser(mustAccept, name); } public NTProductions getAlternativeParser() { return this.alternativeParser; } public void setAlternativeParser(NTProductions parser) { NTProductions altParser = this.alternativeParser; if (altParser == null) { this.alternativeParser = parser; return; } while (altParser.hasAlternativeParser()) { altParser = altParser.getAlternativeParser(); } altParser.alternativeParser = parser; } public boolean hasAlternativeParser() { return (this.getAlternativeParser() != null); } public Object insertWord(BufferedReader key, int keyLength, Object value, boolean connectWithAlternativeParser) { try { key.mark(keyLength + 1); Node res = root.insert(key, value); if (doOverwrite) res.overwriteValue(value); else res.setValue(value); if (connectWithAlternativeParser && alternativeParser != null) { key.reset(); Node altNode = alternativeParser.findNode(key, false); if (altNode != null) res.setUnacceptedChildren(altNode.getChildren()); } return res.getValue(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Insertion failed."); } } public Object insertWord(String key, Object value, boolean connectWithAlternativeParser) { return insertWord(StringOps.stringToBuffer(key), key.length(), value, connectWithAlternativeParser); } /* public Object insertWord(BufferedReader key,int keyLength,Object value,boolean connectWithAlternativeParser) { try { key.mark(keyLength+1); Node res = root.insert(key,value); if(doOverwrite) res.overwriteValue(value); else res.setValue(value); if(connectWithAlternativeParser) { key.reset(); Node altNode = alternativeParser.findNode(key, false); if(altNode!=null) res.copyFromNode(altNode,true); } return res.getValue(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Insertion failed."); } } public Object insertWord(String key,Object value,boolean connectWithAlternativeParser) { return insertWord(StringOps.stringToBuffer(key),key.length(),value,connectWithAlternativeParser); } */ @Override public Object insertWord(BufferedReader key, int keyLength, Object value) { return insertWord(key, keyLength, value, true); } @Override public Object insertWord(String key, Object value) { return insertWord(key, value, true); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package co.th.aten.hospital.util; import java.io.File; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; /** * * @author Aten */ public class Sound { // private boolean canPlay = true; // private boolean canPlayError = true; // private boolean playError = false; private static Sound instance; // private SwingWorker playErrorWorker; AudioInputStream soundClick = null; Clip clipClick = null; DataLine.Info infoClick = null; File soundFileClick = null; private AePlayWave player; public static Sound getInstance() { if (instance == null) { instance = new Sound(); } return instance; } public Sound() { initSounds(); } private void initSounds() { // try { // soundFileClick = new File("sounds/click.wav"); // soundClick = AudioSystem.getAudioInputStream(soundFileClick); // // load the sound into memory (a Clip) // infoClick = new DataLine.Info(Clip.class, soundClick.getFormat()); // clipClick = (Clip) AudioSystem.getLine(infoClick); // clipClick.open(soundClick); // } catch (LineUnavailableException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (UnsupportedAudioFileException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (IOException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } } public void playInfected() { new AePlayWave("sounds/infected.wav").start(); } public void playDing() { new AePlayWave("sounds/ding.wav").start(); } public void playNotify() { new AePlayWave("sounds/notify.wav").start(); } public void playSearchFail() { new AePlayWave("sounds/search_fail.wav").start(); } public void playClick() { // if (player != null && player.isAlive()) { // System.out.println("Sound is playing , ignore new one."); // return; // } // player = new AePlayWave("sounds/click.wav"); // player.start(); new AePlayWave("sounds/click.wav").start(); // new SwingWorker() { // // @Override // protected Object doInBackground() throws Exception { // if (canPlay) { // canPlay = false; //// AudioInputStream sound = null; //// Clip clip = null; //// DataLine.Info info = null; //// File soundFile = null; // try { //// soundFile = new File("sounds/click.wav"); //// sound = AudioSystem.getAudioInputStream(soundFile); //// // load the sound into memory (a Clip) //// info = new DataLine.Info(Clip.class, sound.getFormat()); //// clip = (Clip) AudioSystem.getLine(info); //// clip.open(sound); // //// FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); //// double gain = 1.0D; // number between 0 and 1 (loudest) //// float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0); //// gainControl.setValue(dB); //// clip.start(); // clipClick.start(); // //// } catch (LineUnavailableException ex) { //// Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); //// } catch (UnsupportedAudioFileException ex) { //// Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); //// } catch (IOException ex) { //// Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } finally { //// try { // clipClick.setFramePosition(0); //// clip.close(); //// sound.close(); //// clip.close(); //// clip = null; //// info = null; //// sound = null; //// soundFile = null; //// } catch (IOException ex) { //// Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); //// } // canPlay = true; //// clipClick.stop(); // } // } // return null; // } // }.execute(); } public void playError() { // if (canPlayError) { // if (player != null && player.isAlive()) { // System.out.println("Sound is playing , ignore new one."); // return; // } // player = new AePlayWave("sounds/error.wav"); // player.start(); new AePlayWave("sounds/error.wav").start(); // } // new SwingWorker() { // // @Override // protected Object doInBackground() throws Exception { // if (canPlay) { // canPlay = false; // AudioInputStream sound = null; // Clip clip = null; // DataLine.Info info = null; // File soundFile = null; // try { // soundFile = new File("sounds/error.wav"); // sound = AudioSystem.getAudioInputStream(soundFile); // // load the sound into memory (a Clip) // info = new DataLine.Info(Clip.class, sound.getFormat()); // clip = (Clip) AudioSystem.getLine(info); // clip.open(sound); // clip.start(); // } catch (LineUnavailableException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (UnsupportedAudioFileException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (IOException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } finally { // try { // clip.close(); // sound.close(); // clip = null; // info = null; // sound = null; // soundFile = null; // } catch (IOException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } // canPlay = true; // } // // } // return null; // } // }.execute(); } // public void playContError() { // if (canPlayError) { // canPlayError = false; // new AePlayWave("sounds/error.wav").start(); // playErrorWorker = new SwingWorker() { // // @Override // protected Object doInBackground() { // AudioInputStream sound = null; // Clip clip = null; // DataLine.Info info = null; // File soundFile = null; // try { // soundFile = new File("sounds/error.wav"); // sound = AudioSystem.getAudioInputStream(soundFile); // // load the sound into memory (a Clip) // info = new DataLine.Info(Clip.class, sound.getFormat()); // clip = (Clip) AudioSystem.getLine(info); // clip.open(sound); // while (!isCancelled()) { //// System.out.println("play error sound="+playError); // try { // clip.start(); // Thread.sleep(1000); // clip.stop(); // clip.setFramePosition(0); // } catch (InterruptedException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } // // } // System.out.println("***stop play error"); // } catch (LineUnavailableException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (UnsupportedAudioFileException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (IOException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } finally { // try { // clip.close(); // sound.close(); // clip = null; // info = null; // sound = null; // soundFile = null; // // } catch (IOException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // System.out.println("stop sound error"); // } // } // // return null; // } // }; // playErrorWorker.execute(); // } // } // public void stopPlayError() { // if (playErrorWorker != null) { // playErrorWorker.cancel(false); // canPlayError = true; // } // } public void playAsterisk() { // if (player != null && player.isAlive()) { // System.out.println("Sound is playing , ignore new one."); // return; // } // player = new AePlayWave("sounds/asterisk.wav"); // player.start(); new AePlayWave("sounds/asterisk.wav").start(); // new SwingWorker() { // // @Override // protected Object doInBackground() { // if (canPlay) { // canPlay = false; // AudioInputStream sound = null; // Clip clip = null; // DataLine.Info info = null; // File soundFile = null; // try { // soundFile = new File("sounds/asterisk.wav"); // sound = AudioSystem.getAudioInputStream(soundFile); // // load the sound into memory (a Clip) // info = new DataLine.Info(Clip.class, sound.getFormat()); // clip = (Clip) AudioSystem.getLine(info); // clip.open(sound); // clip.start(); // } catch (LineUnavailableException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (UnsupportedAudioFileException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } catch (IOException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } finally { // try { // clip.close(); // sound.close(); // clip = null; // info = null; // sound = null; // soundFile = null; // // } catch (IOException ex) { // Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex); // } // canPlay = true; // } // // } // return null; // } // }.execute(); } }
package application.socket; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import application.utils.CloseUtil; /** * Send Class defined the thread sending the data * @author Zetian Qin zxq876 * */ public class Send implements Runnable{ // Input Stream from console private BufferedReader console; // Output Stream from channel private DataOutputStream dos; // Thread which control the operation private boolean isRunning = true; // Username private String name; /** * Empty Constructor */ public Send() { console = new BufferedReader(new InputStreamReader(System.in)); } /** * Constructor for Send class * @param client the client socket * @param name the name of user */ public Send(Socket client,String name) { this(); try { dos = new DataOutputStream(client.getOutputStream()); this.name = name; send(this.name); } catch (IOException e) { isRunning = false; CloseUtil.closeAll(dos,console); } } /** * Receive messages from console * @return the message from console */ private String getMsgFromConsole() { try { return console.readLine(); } catch (IOException e) { //e.printStackTrace(); return ""; } } /** * Send messages to others * @param msg the message which would send to others */ public void send(String msg) { if(null!=msg && !msg.equals("")) { try { dos.writeUTF(msg); dos.flush(); // 强制刷新 } catch (IOException e) { isRunning = false; CloseUtil.closeAll(dos,console); } } } @Override public void run() { // Thread Body while(isRunning) { send(getMsgFromConsole()); } } }
package org.sbbs.app.demo.dao; import static org.junit.Assert.fail; import java.util.List; import org.hibernate.SessionFactory; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.sbbs.app.demo.model.DemoTreeNode; import org.sbbs.base.dao.BaseDaoTestCase; import org.sbbs.base.dao.BaseTreeDao; import org.springframework.beans.factory.annotation.Autowired; /** * 测试数据结构: 1 2 3 4 5 * * */ public class DemoTreeNodeNestSetDaoTest extends BaseDaoTestCase { /** * */ @Autowired private BaseTreeDao demoTreeNodeNestSetDao; /** * */ @Autowired private SessionFactory sessionFactory; /** * */ public final void test() { fail("Not yet implemented"); } /** * */ @Before public final void init() { this.demoTreeNodeNestSetDao.reBuildTree(1l, 1); this.demoTreeNodeNestSetDao.debugDisplayTree(1l); } /** * */ /** * */ @Test public final void testRebuildTree() { this.demoTreeNodeNestSetDao.reBuildTree(1l, 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt() == 10); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getLft() == 2); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getRgt() == 9); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getLft() == 3); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getRgt() == 4); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getLft() == 5); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getRgt() == 6); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getLft() == 7); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getRgt() == 8); this.demoTreeNodeNestSetDao.debugDisplayTree(1l); } /** * */ @Test public void testGet() { DemoTreeNode node = (DemoTreeNode) this.demoTreeNodeNestSetDao.get(1l); Assert.assertNotNull(node); } /** * */ @Test public void testGetAll() { List l = this.demoTreeNodeNestSetDao.getAll(); Assert.assertTrue(l.size() == 5); } /** * */ @Test public void testGetAllRoots() { List l = this.demoTreeNodeNestSetDao.getAllRoots(); Assert.assertTrue(l.size() == 1); } /** * */ @Test public void testGetImmediateDescendant() { List l = this.demoTreeNodeNestSetDao.getImmediateDescendant(1l); Assert.assertTrue(l.size() == 1); } /** * */ @Test public void testGetImmediateLeafDescendant() { List l = this.demoTreeNodeNestSetDao.getImmediateLeafDescendant(1l); Assert.assertTrue(l.size() == 0); l = this.demoTreeNodeNestSetDao.getImmediateLeafDescendant(2l); Assert.assertTrue(l.size() == 3); } /** * @author Administrator * */ @Test public void testGetAllNodeAtLevel() { List l = this.demoTreeNodeNestSetDao.getAllNodeAtLevel(2); Assert.assertTrue(l.size() == 3); } /** * */ @Test public void testGetAllNodeAtLevelUnderNode() { List l = this.demoTreeNodeNestSetDao.getAllNodeAtLevelUnderNode(1l, 2); Assert.assertTrue(l.size() == 3); } @Test public void testGetAllLeafNodeAtLevelUnderNode() { List l = this.demoTreeNodeNestSetDao.getAllLeafNodeAtLevelUnderNode(1l, 2); Assert.assertTrue(l.size() == 3); } @Test public void testGetAllUnLeafNodeAtLevelUnderNode() { List l = this.demoTreeNodeNestSetDao.getAllUnLeafNodeAtLevelUnderNode( 1l, 2); Assert.assertTrue(l.size() == 0); } @Test public void testGetImmediateUnLeafDescendant() { List l = this.demoTreeNodeNestSetDao.getImmediateUnLeafDescendant(1l); Assert.assertTrue(l.size() == 1); l = this.demoTreeNodeNestSetDao.getImmediateUnLeafDescendant(2l); Assert.assertTrue(l.size() == 0); } @Test public void testGetTree() { List tl = this.demoTreeNodeNestSetDao.getTreeByNodeId(1l); Assert.assertNotNull(tl); Assert.assertTrue(tl.size() == 5); tl = this.demoTreeNodeNestSetDao.getTreeByNodeId(2l); Assert.assertTrue(tl.size() == 4); tl = this.demoTreeNodeNestSetDao.getTreeByNodeId(3l); Assert.assertTrue(tl.size() == 1); tl = this.demoTreeNodeNestSetDao.getTreeByNodeId(4l); Assert.assertTrue(tl.size() == 1); tl = this.demoTreeNodeNestSetDao.getTreeByNodeId(5l); Assert.assertTrue(tl.size() == 1); DemoTreeNode n = (DemoTreeNode)this.demoTreeNodeNestSetDao.get( 5l ); n.setDisabled( true ); this.demoTreeNodeNestSetDao.save( n ); tl = this.demoTreeNodeNestSetDao.getTreeByNodeId(1l); Assert.assertNotNull(tl); Assert.assertTrue(tl.size() == 4); n = (DemoTreeNode) this.demoTreeNodeNestSetDao.get( 5l ); Assert.assertNotNull( n ); List all = this.demoTreeNodeNestSetDao.getAll(); Assert.assertNotNull(all); Assert.assertTrue(all.size() == 4); } @Test public void testGetPathToNode() { List pl = this.demoTreeNodeNestSetDao.getPathToNode(5l, true); Assert.assertNotNull(pl); Assert.assertTrue(pl.size() == 3); Assert.assertEquals(1l, ((DemoTreeNode) pl.get(0)).getId().longValue()); Assert.assertEquals(2l, ((DemoTreeNode) pl.get(1)).getId().longValue()); Assert.assertEquals(5l, ((DemoTreeNode) pl.get(2)).getId().longValue()); pl = this.demoTreeNodeNestSetDao.getPathToNode(4l, false); Assert.assertNotNull(pl); Assert.assertTrue(pl.size() == 2); Assert.assertEquals(1l, ((DemoTreeNode) pl.get(0)).getId().longValue()); Assert.assertEquals(2l, ((DemoTreeNode) pl.get(1)).getId().longValue()); // Assert.assertEquals(10l, // ((DemoTreeNode)pl.get(2)).getNodeId().longValue()); } @Test public void testInsertNode() { long rid = 1l; DemoTreeNode root = (DemoTreeNode) this.demoTreeNodeNestSetDao.get(rid); DemoTreeNode nnode = new DemoTreeNode(); nnode.setNodeName("testNew"); nnode.setParentNode(root); // this.demoTreeNodeNestSetDao.increaseleftAndRight(root.getLft()); nnode = (DemoTreeNode) this.demoTreeNodeNestSetDao.insertNode(nnode); List tl = this.demoTreeNodeNestSetDao.getAll(); Assert.assertNotNull(tl); Assert.assertTrue(tl.size() == 6); this.demoTreeNodeNestSetDao.debugDisplayTree(1l); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt() == 12); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getLft() == 4); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getRgt() == 11); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getLft() == 5); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getRgt() == 6); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getLft() == 7); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getRgt() == 8); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getLft() == 9); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getRgt() == 10); Assert.assertTrue(nnode.getLft() == 2); Assert.assertTrue(nnode.getRgt() == 3); } @Test public void testGetAllLeafChildren() { List ll = this.demoTreeNodeNestSetDao.getAllLeafDescendant(1l); Assert.assertNotNull(ll); Assert.assertTrue(ll.size() == 3); } @Test public void testGetAllChildren() { List tl = this.demoTreeNodeNestSetDao.getAllDescendant(1l); Assert.assertNotNull(tl); Assert.assertTrue(tl.size() == 4); tl = this.demoTreeNodeNestSetDao.getAllDescendant(2l); Assert.assertTrue(tl.size() == 3); tl = this.demoTreeNodeNestSetDao.getAllDescendant(3l); Assert.assertTrue(tl.size() == 0); } @Test public final void testDelete0() { this.demoTreeNodeNestSetDao.delete(5l); List tl = this.demoTreeNodeNestSetDao.getAll(); this.demoTreeNodeNestSetDao.debugDisplayTree(1l); Assert.assertTrue(tl.size() == 4); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt() == 8); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getLft() == 2); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getRgt() == 7); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getLft() == 3); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getRgt() == 4); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getLft() == 5); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getRgt() == 6); } @Test public void testDelete1() { /* * this.demoTreeNodeNestSetDao.delete(6l); List tl = * this.demoTreeNodeNestSetDao.getAll(); * Assert.assertTrue(tl.size()==5); */ this.demoTreeNodeNestSetDao.delete(2l); List tl = this.demoTreeNodeNestSetDao.getAll(); Assert.assertTrue(tl.size() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt() == 2); /* * this.demoTreeNodeNestSetDao.delete(1l); tl = * this.demoTreeNodeNestSetDao.getAll(); * Assert.assertTrue(tl.size()==0); */ } @Test public void testDelete2() { this.demoTreeNodeNestSetDao.delete(5l); List tl = this.demoTreeNodeNestSetDao.getAll(); this.demoTreeNodeNestSetDao.debugDisplayTree(1l); Assert.assertTrue(tl.size() == 4); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt() == 8); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getLft() == 2); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getRgt() == 7); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getLft() == 3); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getRgt() == 4); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getLft() == 5); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getRgt() == 6); this.demoTreeNodeNestSetDao.delete(3l); tl = this.demoTreeNodeNestSetDao.getAll(); this.demoTreeNodeNestSetDao.debugDisplayTree(1l); Assert.assertTrue(tl.size() == 3); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt() == 6); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getLft() == 2); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getRgt() == 5); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getLft() == 3); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getRgt() == 4); } @Test public void testDebugDisplayTree() { // this.demoTreeNodeNestSetDao.debugDisplayTree(1l); Assert.assertTrue(true); } @Test public void testMove() { this.demoTreeNodeNestSetDao.debugDisplayTree(1l); this.demoTreeNodeNestSetDao.move(5l, 4l); this.demoTreeNodeNestSetDao.debugDisplayTree(1l); List l = this.demoTreeNodeNestSetDao.getAll(); Assert.assertTrue(l.size() == 5); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft() == 1); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt() == 10); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getLft() == 2); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getRgt() == 9); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getLft() == 3); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getRgt() == 4); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getLft() == 5); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getRgt() == 8); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getLft() == 6); Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getRgt() == 7); /* * this.demoTreeNodeNestSetDao.move(2l, 7l); * this.demoTreeNodeNestSetDao.debugDisplayTree(1l); l = * this.demoTreeNodeNestSetDao.getAll(); * Assert.assertTrue(l.size()==10); */ } /* * @Test public void testIncrease(){ * this.demoTreeNodeNestSetDao.increaseleftAndRight(1); * this.demoTreeNodeNestSetDao.debugDisplayTree(1l); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getLft()==1); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(1l).getRgt()==12); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getLft()==4); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(2l).getRgt()==11); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getLft()==5); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(3l).getRgt()==6); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getLft()==7); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(4l).getRgt()==8); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getLft()==9); * Assert.assertTrue(this.demoTreeNodeNestSetDao.get(5l).getRgt()==10); * } */ }
package pe.gob.trabajo.web.rest; import pe.gob.trabajo.LiquidacionesApp; import pe.gob.trabajo.domain.Docpresate; import pe.gob.trabajo.repository.DocpresateRepository; import pe.gob.trabajo.repository.search.DocpresateSearchRepository; import pe.gob.trabajo.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the DocpresateResource REST controller. * * @see DocpresateResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = LiquidacionesApp.class) public class DocpresateResourceIntTest { private static final String DEFAULT_V_OBSDOPATE = "AAAAAAAAAA"; private static final String UPDATED_V_OBSDOPATE = "BBBBBBBBBB"; private static final Integer DEFAULT_N_USUAREG = 1; private static final Integer UPDATED_N_USUAREG = 2; private static final Instant DEFAULT_T_FECREG = Instant.ofEpochMilli(0L); private static final Instant UPDATED_T_FECREG = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Boolean DEFAULT_N_FLGACTIVO = false; private static final Boolean UPDATED_N_FLGACTIVO = true; private static final Integer DEFAULT_N_SEDEREG = 1; private static final Integer UPDATED_N_SEDEREG = 2; private static final Integer DEFAULT_N_USUAUPD = 1; private static final Integer UPDATED_N_USUAUPD = 2; private static final Instant DEFAULT_T_FECUPD = Instant.ofEpochMilli(0L); private static final Instant UPDATED_T_FECUPD = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Integer DEFAULT_N_SEDEUPD = 1; private static final Integer UPDATED_N_SEDEUPD = 2; @Autowired private DocpresateRepository docpresateRepository; @Autowired private DocpresateSearchRepository docpresateSearchRepository; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restDocpresateMockMvc; private Docpresate docpresate; @Before public void setup() { MockitoAnnotations.initMocks(this); final DocpresateResource docpresateResource = new DocpresateResource(docpresateRepository, docpresateSearchRepository); this.restDocpresateMockMvc = MockMvcBuilders.standaloneSetup(docpresateResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Docpresate createEntity(EntityManager em) { Docpresate docpresate = new Docpresate() .vObsdopate(DEFAULT_V_OBSDOPATE) .nUsuareg(DEFAULT_N_USUAREG) .tFecreg(DEFAULT_T_FECREG) .nFlgactivo(DEFAULT_N_FLGACTIVO) .nSedereg(DEFAULT_N_SEDEREG) .nUsuaupd(DEFAULT_N_USUAUPD) .tFecupd(DEFAULT_T_FECUPD) .nSedeupd(DEFAULT_N_SEDEUPD); return docpresate; } @Before public void initTest() { docpresateSearchRepository.deleteAll(); docpresate = createEntity(em); } @Test @Transactional public void createDocpresate() throws Exception { int databaseSizeBeforeCreate = docpresateRepository.findAll().size(); // Create the Docpresate restDocpresateMockMvc.perform(post("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(docpresate))) .andExpect(status().isCreated()); // Validate the Docpresate in the database List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeCreate + 1); Docpresate testDocpresate = docpresateList.get(docpresateList.size() - 1); assertThat(testDocpresate.getvObsdopate()).isEqualTo(DEFAULT_V_OBSDOPATE); assertThat(testDocpresate.getnUsuareg()).isEqualTo(DEFAULT_N_USUAREG); assertThat(testDocpresate.gettFecreg()).isEqualTo(DEFAULT_T_FECREG); assertThat(testDocpresate.isnFlgactivo()).isEqualTo(DEFAULT_N_FLGACTIVO); assertThat(testDocpresate.getnSedereg()).isEqualTo(DEFAULT_N_SEDEREG); assertThat(testDocpresate.getnUsuaupd()).isEqualTo(DEFAULT_N_USUAUPD); assertThat(testDocpresate.gettFecupd()).isEqualTo(DEFAULT_T_FECUPD); assertThat(testDocpresate.getnSedeupd()).isEqualTo(DEFAULT_N_SEDEUPD); // Validate the Docpresate in Elasticsearch Docpresate docpresateEs = docpresateSearchRepository.findOne(testDocpresate.getId()); assertThat(docpresateEs).isEqualToComparingFieldByField(testDocpresate); } @Test @Transactional public void createDocpresateWithExistingId() throws Exception { int databaseSizeBeforeCreate = docpresateRepository.findAll().size(); // Create the Docpresate with an existing ID docpresate.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail restDocpresateMockMvc.perform(post("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(docpresate))) .andExpect(status().isBadRequest()); // Validate the Docpresate in the database List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void checknUsuaregIsRequired() throws Exception { int databaseSizeBeforeTest = docpresateRepository.findAll().size(); // set the field null docpresate.setnUsuareg(null); // Create the Docpresate, which fails. restDocpresateMockMvc.perform(post("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(docpresate))) .andExpect(status().isBadRequest()); List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void checktFecregIsRequired() throws Exception { int databaseSizeBeforeTest = docpresateRepository.findAll().size(); // set the field null docpresate.settFecreg(null); // Create the Docpresate, which fails. restDocpresateMockMvc.perform(post("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(docpresate))) .andExpect(status().isBadRequest()); List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void checknFlgactivoIsRequired() throws Exception { int databaseSizeBeforeTest = docpresateRepository.findAll().size(); // set the field null docpresate.setnFlgactivo(null); // Create the Docpresate, which fails. restDocpresateMockMvc.perform(post("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(docpresate))) .andExpect(status().isBadRequest()); List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void checknSederegIsRequired() throws Exception { int databaseSizeBeforeTest = docpresateRepository.findAll().size(); // set the field null docpresate.setnSedereg(null); // Create the Docpresate, which fails. restDocpresateMockMvc.perform(post("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(docpresate))) .andExpect(status().isBadRequest()); List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void getAllDocpresates() throws Exception { // Initialize the database docpresateRepository.saveAndFlush(docpresate); // Get all the docpresateList restDocpresateMockMvc.perform(get("/api/docpresates?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(docpresate.getId().intValue()))) .andExpect(jsonPath("$.[*].vObsdopate").value(hasItem(DEFAULT_V_OBSDOPATE.toString()))) .andExpect(jsonPath("$.[*].nUsuareg").value(hasItem(DEFAULT_N_USUAREG))) .andExpect(jsonPath("$.[*].tFecreg").value(hasItem(DEFAULT_T_FECREG.toString()))) .andExpect(jsonPath("$.[*].nFlgactivo").value(hasItem(DEFAULT_N_FLGACTIVO.booleanValue()))) .andExpect(jsonPath("$.[*].nSedereg").value(hasItem(DEFAULT_N_SEDEREG))) .andExpect(jsonPath("$.[*].nUsuaupd").value(hasItem(DEFAULT_N_USUAUPD))) .andExpect(jsonPath("$.[*].tFecupd").value(hasItem(DEFAULT_T_FECUPD.toString()))) .andExpect(jsonPath("$.[*].nSedeupd").value(hasItem(DEFAULT_N_SEDEUPD))); } @Test @Transactional public void getDocpresate() throws Exception { // Initialize the database docpresateRepository.saveAndFlush(docpresate); // Get the docpresate restDocpresateMockMvc.perform(get("/api/docpresates/{id}", docpresate.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(docpresate.getId().intValue())) .andExpect(jsonPath("$.vObsdopate").value(DEFAULT_V_OBSDOPATE.toString())) .andExpect(jsonPath("$.nUsuareg").value(DEFAULT_N_USUAREG)) .andExpect(jsonPath("$.tFecreg").value(DEFAULT_T_FECREG.toString())) .andExpect(jsonPath("$.nFlgactivo").value(DEFAULT_N_FLGACTIVO.booleanValue())) .andExpect(jsonPath("$.nSedereg").value(DEFAULT_N_SEDEREG)) .andExpect(jsonPath("$.nUsuaupd").value(DEFAULT_N_USUAUPD)) .andExpect(jsonPath("$.tFecupd").value(DEFAULT_T_FECUPD.toString())) .andExpect(jsonPath("$.nSedeupd").value(DEFAULT_N_SEDEUPD)); } @Test @Transactional public void getNonExistingDocpresate() throws Exception { // Get the docpresate restDocpresateMockMvc.perform(get("/api/docpresates/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateDocpresate() throws Exception { // Initialize the database docpresateRepository.saveAndFlush(docpresate); docpresateSearchRepository.save(docpresate); int databaseSizeBeforeUpdate = docpresateRepository.findAll().size(); // Update the docpresate Docpresate updatedDocpresate = docpresateRepository.findOne(docpresate.getId()); updatedDocpresate .vObsdopate(UPDATED_V_OBSDOPATE) .nUsuareg(UPDATED_N_USUAREG) .tFecreg(UPDATED_T_FECREG) .nFlgactivo(UPDATED_N_FLGACTIVO) .nSedereg(UPDATED_N_SEDEREG) .nUsuaupd(UPDATED_N_USUAUPD) .tFecupd(UPDATED_T_FECUPD) .nSedeupd(UPDATED_N_SEDEUPD); restDocpresateMockMvc.perform(put("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(updatedDocpresate))) .andExpect(status().isOk()); // Validate the Docpresate in the database List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeUpdate); Docpresate testDocpresate = docpresateList.get(docpresateList.size() - 1); assertThat(testDocpresate.getvObsdopate()).isEqualTo(UPDATED_V_OBSDOPATE); assertThat(testDocpresate.getnUsuareg()).isEqualTo(UPDATED_N_USUAREG); assertThat(testDocpresate.gettFecreg()).isEqualTo(UPDATED_T_FECREG); assertThat(testDocpresate.isnFlgactivo()).isEqualTo(UPDATED_N_FLGACTIVO); assertThat(testDocpresate.getnSedereg()).isEqualTo(UPDATED_N_SEDEREG); assertThat(testDocpresate.getnUsuaupd()).isEqualTo(UPDATED_N_USUAUPD); assertThat(testDocpresate.gettFecupd()).isEqualTo(UPDATED_T_FECUPD); assertThat(testDocpresate.getnSedeupd()).isEqualTo(UPDATED_N_SEDEUPD); // Validate the Docpresate in Elasticsearch Docpresate docpresateEs = docpresateSearchRepository.findOne(testDocpresate.getId()); assertThat(docpresateEs).isEqualToComparingFieldByField(testDocpresate); } @Test @Transactional public void updateNonExistingDocpresate() throws Exception { int databaseSizeBeforeUpdate = docpresateRepository.findAll().size(); // Create the Docpresate // If the entity doesn't have an ID, it will be created instead of just being updated restDocpresateMockMvc.perform(put("/api/docpresates") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(docpresate))) .andExpect(status().isCreated()); // Validate the Docpresate in the database List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeUpdate + 1); } @Test @Transactional public void deleteDocpresate() throws Exception { // Initialize the database docpresateRepository.saveAndFlush(docpresate); docpresateSearchRepository.save(docpresate); int databaseSizeBeforeDelete = docpresateRepository.findAll().size(); // Get the docpresate restDocpresateMockMvc.perform(delete("/api/docpresates/{id}", docpresate.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate Elasticsearch is empty boolean docpresateExistsInEs = docpresateSearchRepository.exists(docpresate.getId()); assertThat(docpresateExistsInEs).isFalse(); // Validate the database is empty List<Docpresate> docpresateList = docpresateRepository.findAll(); assertThat(docpresateList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void searchDocpresate() throws Exception { // Initialize the database docpresateRepository.saveAndFlush(docpresate); docpresateSearchRepository.save(docpresate); // Search the docpresate restDocpresateMockMvc.perform(get("/api/_search/docpresates?query=id:" + docpresate.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(docpresate.getId().intValue()))) .andExpect(jsonPath("$.[*].vObsdopate").value(hasItem(DEFAULT_V_OBSDOPATE.toString()))) .andExpect(jsonPath("$.[*].nUsuareg").value(hasItem(DEFAULT_N_USUAREG))) .andExpect(jsonPath("$.[*].tFecreg").value(hasItem(DEFAULT_T_FECREG.toString()))) .andExpect(jsonPath("$.[*].nFlgactivo").value(hasItem(DEFAULT_N_FLGACTIVO.booleanValue()))) .andExpect(jsonPath("$.[*].nSedereg").value(hasItem(DEFAULT_N_SEDEREG))) .andExpect(jsonPath("$.[*].nUsuaupd").value(hasItem(DEFAULT_N_USUAUPD))) .andExpect(jsonPath("$.[*].tFecupd").value(hasItem(DEFAULT_T_FECUPD.toString()))) .andExpect(jsonPath("$.[*].nSedeupd").value(hasItem(DEFAULT_N_SEDEUPD))); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Docpresate.class); Docpresate docpresate1 = new Docpresate(); docpresate1.setId(1L); Docpresate docpresate2 = new Docpresate(); docpresate2.setId(docpresate1.getId()); assertThat(docpresate1).isEqualTo(docpresate2); docpresate2.setId(2L); assertThat(docpresate1).isNotEqualTo(docpresate2); docpresate1.setId(null); assertThat(docpresate1).isNotEqualTo(docpresate2); } }
package com.example.proiectdam_serbansorinaalexandra.Data; import android.os.AsyncTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class JSONReader extends AsyncTask<URL, Void, String> { @Override protected String doInBackground(URL... urls) { HttpURLConnection connection = null; try{ connection = (HttpURLConnection)urls[0].openConnection(); InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(inputStreamReader); StringBuilder result = new StringBuilder(); String line = ""; while((line = reader.readLine()) != null) { result.append(line); } reader.close(); inputStreamReader.close(); inputStream.close(); return result.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if(connection != null) { connection.disconnect(); } } return null; } protected List<Landmark> parceLandmarksJSON(String json) { List<Landmark> landmarks = new ArrayList<>(); try { JSONObject jsonObject = new JSONObject(json); JSONArray landmarkObject = jsonObject.getJSONArray("landmarks"); for (int i = 0; i < landmarkObject.length(); i++) { JSONObject currentObject = landmarkObject.getJSONObject(i); Landmark landmark = new Landmark(); landmark.setName(currentObject.getString("name")); landmark.setLocation(currentObject.getString("location")); landmark.setType(currentObject.getString("type")); landmarks.add(landmark); } } catch (JSONException e) { e.printStackTrace(); } return landmarks; } }
package LC400_600.LC450_500; import org.junit.Test; import java.util.*; public class LC472_Concatenated_Words { @Test public void test() { System.out.println(findAllConcatenatedWordsInADict(new String[] {"cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"})); } public List<String> findAllConcatenatedWordsInADict(String[] words) { List<String> result = new ArrayList<>(); if (words.length == 0 || words[0].equals("")) return result; Arrays.sort(words, (o1, o2) -> o1.length() - o2.length()); Map<String, Integer> map = new HashMap<>(); Stack<String> stack = new Stack<>(); Set<String> set = new HashSet<>(); for (String word : words) set.add(word); int min = words[0].length(); for (String s : words) { stack.add(s); while (stack.size() > 0) { String peek = stack.peek(); if (map.getOrDefault(peek, -1) >= 1) { stack.pop(); continue; } if (peek.length() < 2 * min && !set.contains(peek)) { stack.pop(); map.put(peek, 0); continue; } int count = 0; for (String word : words) { if (count >= 2) break; if (peek.startsWith(word)) { if (word.equals(peek)) { count += 1; break; } else if (peek.length() >= 2 * min) { String next = peek.substring(word.length()); int t = map.getOrDefault(next, -1); if (t != -1 && t != 0) count += t; else if (count < 2 && next.length() >= 2 * min || set.contains(next)) stack.push(next); } } } if (stack.peek().equals(peek)) { stack.pop(); map.put(peek, count); } } } for (String k : map.keySet()) if (set.contains(k) && map.get(k) > 1) result.add(k); return result; } }
package DAO; import java.util.List; import org.hibernate.Session; public class hibernateDAO { public Session getCurrentSession() { return HibernateUtil.getSessionFactory().openSession(); } public void saveObject(Object obj) { getCurrentSession().save(obj); } public void updateObject(Object obj) { getCurrentSession().update(obj); } public void deleteObject(Object obj) { getCurrentSession().delete(obj); } public Object getObject(String hsql) { return getCurrentSession().createQuery(hsql).uniqueResult(); } public <T> T getObject(Class<T> cls,String id) { Object obj = getCurrentSession().get(cls,id); return (T)obj; } public List<?> getObjects(String hsql) { return getCurrentSession().createQuery(hsql).list(); } }
package gdut.ff.mapper; import java.util.List; 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 gdut.ff.domain.File; import gdut.ff.service.FileServiceImpl; /** * 测试文件的增删改查接口 * @author bluesnail95 * */ @RunWith(SpringRunner.class) @SpringBootTest public class FileMapperTest { @Autowired private FileServiceImpl fileServiceImpl; @Test public void testFindInsertFile() { File file = new File(); file.setGroupName("group1"); file.setRemoteFileName("M00/00/00/rBAAEFrpxHiAUGPRAAAIdkgFegc18.file"); file.setFileName("photo.jpg"); file.setFileIntroduction("上传头像"); fileServiceImpl.insertFile(file); } @Test public void testFindFile() { File file = fileServiceImpl.findFileById("6ba4ecb6-5937-4f9c-817d-5a42078f693e"); System.out.println(file.toString()); List files = fileServiceImpl.findAllFile(null); files.forEach(uploadFile -> { System.out.println(uploadFile); }); } @Test public void testUpdateFile() { File file = new File(); //file.setGroupName("group1"); //file.setRemoteFileName("M00/00/00/rBAAEFrpxHiAUGPRAAAIdkgFegc18.file"); file.setFileIntroduction("上传头像测试"); fileServiceImpl.updateFile(file); } @Test public void testDeleteFile() { fileServiceImpl.deleteFileById("6ba4ecb6-5937-4f9c-817d-5a42078f693e"); } }
package ec.com.yacare.y4all.asynctask.ws; import android.os.AsyncTask; import android.provider.Settings; import ec.com.yacare.y4all.activities.LoginActivity; import ec.com.yacare.y4all.activities.SplashActivity; import ec.com.yacare.y4all.activities.DatosAplicacion; import ec.com.yacare.y4all.lib.webservice.ObtenerListaDispositivos; public class ObtenerListaDispositivoAsyncTask extends AsyncTask<String, Float, String> { private LoginActivity loginActivity; private SplashActivity splashActivity; public ObtenerListaDispositivoAsyncTask(LoginActivity loginActivity, SplashActivity splashActivity) { super(); this.loginActivity = loginActivity; this.splashActivity = splashActivity; } @Override protected String doInBackground(String... arg0) { String email = null; DatosAplicacion datosAplicacion = null; String idDispositivo = null; if(loginActivity != null){ idDispositivo= Settings.Secure.getString(loginActivity.getApplicationContext().getContentResolver(),Settings.Secure.ANDROID_ID); datosAplicacion = ((DatosAplicacion) loginActivity.getApplicationContext()); email = loginActivity.getEmailTexto(); }else{ idDispositivo= Settings.Secure.getString(splashActivity.getApplicationContext().getContentResolver(),Settings.Secure.ANDROID_ID); datosAplicacion = ((DatosAplicacion) splashActivity.getApplicationContext()); email = datosAplicacion.getCuenta().getEmail(); } String respStr = ObtenerListaDispositivos.obtenerListaDispositivo( email, datosAplicacion.getToken(),idDispositivo); //Log.d("ws: obtenerListaDispositivo",respStr); return respStr; } protected void onPostExecute(String respuesta) { // if(loginActivity != null){ // loginActivity.verificarListaDispositivos(respuesta); // }else{ // splashActivity.verificarListaDispositivos(respuesta); // } } }
package com.widera.petclinic.domain.repository; import com.widera.petclinic.domain.entities.User; /** * Created by maviek on 21.10.16. */ public interface UserRepository { User findUserByUsername(String username); void save(User user); }
package org.nyer.sns.renren; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.log4j.Logger; import org.nyer.sns.core.AbstractOAuth2Weibo; import org.nyer.sns.core.WeiboResponse; import org.nyer.sns.core.WeiboUser; import org.nyer.sns.http.PrepareHttpClient; import org.nyer.sns.oauth.OAuthDeveloperAccount; import org.nyer.sns.oauth.OAuthProvider; import org.nyer.sns.token.OAuthTokenPair; import org.nyer.sns.util.page.Page; public class RenRen extends AbstractOAuth2Weibo { private static Logger log = Logger.getLogger(LOG_NAME); public static final String URL_SERVER = "https://api.renren.com/restserver.do"; public RenRen(OAuthDeveloperAccount developerAccount, PrepareHttpClient httpClient) { super(developerAccount, httpClient, OAuthProvider.RENREN); this.protocal = new RenRenProtocal(oauth); } @Override public WeiboResponse publish(OAuthTokenPair accessTokenPair, String title, String message, String url, String clientIP) { Map<String, String> params = new HashMap<String, String>(); params.put("method", "status.set"); params.put("status", StringUtils.abbreviate(message, 200)); // description长度不超过200 return this.protocal.post(URL_SERVER, params, accessTokenPair); } @Override public WeiboResponse publishWithImage(OAuthTokenPair accessTokenPair, String title, String message, byte[] imgBytes, String imgName, String url, String clientIP) { Map<String, String> params = new HashMap<String, String>(); params.put("method", "photos.upload"); params.put("caption", StringUtils.abbreviate(message, 200)); // description长度不超过200 MultipartEntity requestEntity = new MultipartEntity(); requestEntity.addPart("upload", new ByteArrayBody(imgBytes, imgName)); return this.protocal.post(URL_SERVER, params, requestEntity, accessTokenPair); } @Override public WeiboUser fetchUser(OAuthTokenPair tokenPair) { Map<String, String> params = new HashMap<String, String>(); params.put("method", "users.getLoggedInUser"); WeiboResponse response = this.protocal.post(URL_SERVER, params, tokenPair); if (response.isStatusOK()) { String userId = null; try { JSONObject obj = JSONObject.fromObject(response.getHttpResponseText()); userId = obj.getString("uid"); params = new HashMap<String, String>(); params.put("method", "users.getProfileInfo"); params.put("uid", userId); response = this.protocal.post(URL_SERVER, params, tokenPair); if (response.isStatusOK()) { WeiboUser weiboUser = new WeiboUser(tokenPair); try { obj = JSONObject.fromObject(response.getHttpResponseText()); weiboUser.setUid(userId); weiboUser.setProfileUrl("http://www.renren.com/" + userId); weiboUser.setNickName(obj.getString("name")); weiboUser.setImgUrl(obj.getString("headurl")); return weiboUser; } catch (Exception e) { response.setLocalError(e); } } } catch (Exception e) { response.setLocalError(e); } } if (response.isStatusOK() == false) log.error("error to get user, token: " + tokenPair + ", resp: " + response); return null; } /** * 人人没有Follower的关系 */ @Override public Page<WeiboUser> getPageFollower( OAuthTokenPair accessTokenPair, int page, int pageSize) { throw new UnsupportedOperationException(); } @Override public Page<WeiboUser> getPageFriend( OAuthTokenPair accessTokenPair, int page, int pageSize) { Map<String, String> params = new HashMap<String, String>(); params.put("method", "friends.getFriends"); params.put("page", page + ""); params.put("count", pageSize + ""); WeiboResponse response = this.protocal.post(URL_SERVER, params, accessTokenPair); if (response.isStatusOK()) { try { JSONArray friends = JSONArray.fromObject(response.getHttpResponseText()); Page<WeiboUser> pageFriend = new Page<WeiboUser>(page, pageSize); List<WeiboUser> weiboFriends = new ArrayList<WeiboUser>(friends.size()); pageFriend.setContent(weiboFriends); for (int i = 0;i < friends.size();i ++) { JSONObject friend = friends.getJSONObject(i); WeiboUser weiboFriend = new WeiboUser(null); weiboFriend.setNickName(friend.getString("name")); weiboFriend.setImgUrl(friend.getString("headurl")); String userId = friend.getString("id"); weiboFriend.setUid(userId); weiboFriend.setProfileUrl("http://www.renren.com/" + userId); weiboFriends.add(weiboFriend); } return pageFriend; } catch (Exception e) { response.setLocalError(e); } } log.error("error to get followers, resp: " + response); return null; } }
//@@author A0141021H package seedu.whatnow.logic.commands; import java.io.IOException; import java.util.Optional; import java.util.logging.Logger; import seedu.whatnow.commons.core.Config; import seedu.whatnow.commons.core.LogsCenter; import seedu.whatnow.commons.exceptions.DataConversionException; import seedu.whatnow.commons.util.ConfigUtil; import seedu.whatnow.commons.util.StringUtil; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import static seedu.whatnow.commons.core.Messages.*; /** * Changes the data file location of WhatNow. */ public class ChangeCommand extends Command { public static final String COMMAND_WORD = "change"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Changes the WhatNow data file storage location. " + "Parameters: PATH\n" + "Example: " + COMMAND_WORD + " location to" + " PATH: C:" + "\\" + "Users" + "\\" + "Jim" + "\\" + "Dropbox"; public static final String MESSAGE_SUCCESS = "The data storage location has been successfully changed to: %1$s"; public static final String MESSAGE_UNDO_FAIL = "Unable to undo due to no previous location information"; public static final String MESSAGE_UNDO_SUCCESS = "Successfully able to undo to %1$s"; public static final String MESSAGE_REDO_SUCCESS = "Successfully able to redo to %1$s"; public static final String MESSAGE_REDO_FAIL = "Unable to redo due to no previous undo command"; public static final String WHATNOW_XMLFILE = "whatnow.xml"; public static final String DOUBLE_BACKSLASH = "\\"; public static final String SINGLE_FORWARDSLASH = "/"; public String newPath; public Path source; public Path destination; public Config config; private static final Logger logger = LogsCenter.getLogger(ChangeCommand.class); public ChangeCommand(String newPath) { this.newPath = newPath; } /** * Execute the ChangeCommand to change to the updated data filepath */ @Override public CommandResult execute() { Path path = FileSystems.getDefault().getPath(newPath); if (Files.exists(path)) { if (newPath.contains(DOUBLE_BACKSLASH)) { newPath = newPath + DOUBLE_BACKSLASH + WHATNOW_XMLFILE; } else if (newPath.contains(SINGLE_FORWARDSLASH)) { newPath = newPath + SINGLE_FORWARDSLASH + WHATNOW_XMLFILE; } else { newPath = newPath + SINGLE_FORWARDSLASH + WHATNOW_XMLFILE; } path = FileSystems.getDefault().getPath(newPath); String configFilePathUsed = Config.DEFAULT_CONFIG_FILE; try { Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed); config = configOptional.orElse(new Config()); model.getStackOfChangeFileLocationOld().push(config.getWhatNowFilePath()); config.setWhatNowFilePath(newPath); model.changeLocation(path, config); model.getUndoStack().push(COMMAND_WORD); model.clearRedoAll(); } catch (DataConversionException e1) { logger.warning("Config file at " + configFilePathUsed + " is not in the correct format. " + "Using default config properties"); config = new Config(); } try { ConfigUtil.saveConfig(config, configFilePathUsed); } catch (IOException e) { logger.warning("Failed to save config file : " + StringUtil.getDetails(e)); } return new CommandResult(String.format(MESSAGE_SUCCESS, newPath)); } else { return new CommandResult(String.format(MESSAGE_INVALID_PATH, newPath)); } } }