text
stringlengths 10
2.72M
|
|---|
package com.av.db.layer.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.av.db.dataobjects.Tarjeta;
import com.av.db.layer.interfaces.TarjetaLayer;
import com.av.exceptions.AvException;
/**
* Clase que contiene la implementacion de funciones para la tabla de tarjetas
* utilizando la tecnologia de Hibernate
*
* @author Victor J Morales R
*
*/
public class TarjetaLayerImpl extends HibernateDaoSupport implements
TarjetaLayer {
private static Logger log = Logger.getLogger(TarjetaLayerImpl.class);
/**
* Funcion que actualiza en la base de datos una tarjeta en especifo
*/
@Override
public void actualizar(Tarjeta tarjeta) throws AvException {
log.info("Inicio - actualizar(Tarjeta tarjeta)");
log.debug("Id : " + tarjeta.getId());
log.debug("Tarjeta : " + tarjeta.toString());
if (tarjeta == null) {
log.error("No se puede actualizar una tarjeta nula");
throw new AvException("Tarjeta nula a ser actualizada");
}
if (tarjeta.getId() < 0) {
log.error("No se puede actualizar una tarjeta con identificador "
+ "invalido");
throw new AvException("Tarjeta con identificador invalido a ser "
+ "actualizado");
}
getHibernateTemplate().update(tarjeta);
log.info("Fin - actualizar(Tarjeta tarjeta)");
}// actualizar
/**
* Funcion que agrega en la base de datos configura una nueva tarjeta
*/
@Override
public void agregar(Tarjeta tarjeta) throws AvException {
log.info("Inicio - agregar(Tarjeta tarjeta)");
log.debug("Tarjeta : " + tarjeta.toString());
if (tarjeta == null) {
log.error("No se puede agregar una tarjeta nula");
throw new AvException("Tarjeta nula a ser agregada");
}
getHibernateTemplate().save(tarjeta);
log.info("Fin - agregar(Tarjeta tarjeta)");
}// agregar
/**
* Funcion que elimina una tarjeta especifica de la base de datos
* configurada
*/
@Override
public void eliminar(Tarjeta tarjeta) throws AvException {
log.info("Inicio - eliminar(Tarjeta tarjeta)");
log.debug("Tarjeta : " + tarjeta.toString());
if (tarjeta == null) {
log.error("No se puede eliminar una tarjeta nula");
throw new AvException("Tarjeta nula a ser eliminada");
}
if (tarjeta.getId() < 0) {
log
.error("No se puede eliminar una tarjeta con identificador negativo");
throw new AvException("Identificador negativo");
}
getHibernateTemplate().delete(tarjeta);
log.info("Fin - eliminar(Tarjeta tarjeta)");
}// eliminar
/**
* Funcion que obtiene una tarjeta de la base de datos configurada a partir
* de su identificador
*/
@Override
public Tarjeta obtener(int id) {
log.info("Inicio - obtener(int id)");
log.debug("Id : " + id);
if (id < 0) {
log
.warn("No se puede obtener una tarjeta con identificador negativo");
return null;
}
Tarjeta tmp = getHibernateTemplate().get(Tarjeta.class, id);
if (tmp != null) {
log.debug("Tarjeta : " + tmp.toString());
} else {
log.debug("Tarjeta no encontrada");
}
log.info("Fin - obtener(int id)");
return tmp;
}// obtener
/**
* Funcion que obtiene el conjunto de todas las tarjetas registradas en la
* base de datos configurada
*/
@Override
public Tarjeta[] obtener() {
log.info("Inicio - obtener()");
List<?> l = getSession().createCriteria(Tarjeta.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).addOrder(
Order.asc(Tarjeta.ID)).list();
Tarjeta[] tmp = null;
if (l != null && l.size() > 0) {
log.debug("Cantidad obtenida : " + l.size());
tmp = new Tarjeta[l.size()];
l.toArray(tmp);
}
log.info("Fin - obtener()");
return tmp;
}// obtener
/**
* Funcion que obtiene todos las tarjetas activas del sistema
*/
@Override
public Tarjeta[] obtenerActivos() {
log.info("Inicio - obtenerActivos()");
List<?> l = getSession().createCriteria(Tarjeta.class).add(
Restrictions.eq(Tarjeta.ACTIVO, true)).setResultTransformer(
Criteria.DISTINCT_ROOT_ENTITY).addOrder(Order.asc(Tarjeta.ID))
.list();
Tarjeta[] tmp = null;
if (l != null && l.size() > 0) {
log.debug("Cantidad obtenida : " + l.size());
tmp = new Tarjeta[l.size()];
l.toArray(tmp);
}
log.info("Fin - obtenerActivos()");
return tmp;
}// obtenerActivos
/**
* Funcion que obtiene todas las tarjetas inactivas registradas en el
* sistema
*/
@Override
public Tarjeta[] obtenerInactivos() {
log.info("Inicio - obtenerActivos()");
List<?> l = getSession().createCriteria(Tarjeta.class).add(
Restrictions.eq(Tarjeta.ACTIVO, false)).setResultTransformer(
Criteria.DISTINCT_ROOT_ENTITY).addOrder(Order.asc(Tarjeta.ID))
.list();
Tarjeta[] tmp = null;
if (l != null && l.size() > 0) {
log.debug("Cantidad obtenida : " + l.size());
tmp = new Tarjeta[l.size()];
l.toArray(tmp);
}
log.info("Fin - obtenerActivos()");
return tmp;
}// obtenerInactivos
/**
* Funcion que obtiene la primera tarjeta activa a partir de su codigo o
* numero de placa
*/
@Override
public Tarjeta obtenerPorCodigoONumPlaca(String codigo, String numPlaca) {
log
.info("Inicio - obtenerPorCodigoONumPlaca(String codigo, String numPlaca)");
log.debug("Codigo : " + codigo);
log.debug("Num. de placa : " + numPlaca);
if ((codigo == null || codigo.trim().length() < 0)
&& (numPlaca == null || numPlaca.trim().length() < 0)) {
log
.error("El codigo y el num. de placa no pueden ser vacios o nulos");
return null;
}
Criteria c = getSession().createCriteria(Tarjeta.class);
if (codigo != null && codigo.trim().length() > 0) {
c.add(Restrictions.eq(Tarjeta.CODIGO, codigo.trim()));
}
if (numPlaca != null && numPlaca.trim().length() > 0) {
c.add(Restrictions.eq(Tarjeta.NUM_PLACA, numPlaca.trim()));
}
List<?> l = c.add(Restrictions.eq(Tarjeta.ACTIVO, true)).addOrder(
Order.asc(Tarjeta.ID)).setResultTransformer(
Criteria.DISTINCT_ROOT_ENTITY).setMaxResults(1).list();
Tarjeta tmp = null;
if (l != null && l.size() > 0) {
log.debug("Cantidad obtenida : " + l.size());
tmp = (Tarjeta) l.get(0);
if (tmp != null) {
log.debug("Tarjeta : " + tmp.toString());
} else {
log.debug("Tarjeta no encontrada");
}
}
log
.info("Fin - obtenerPorCodigoONumPlaca(String codigo, String numPlaca)");
return tmp;
}
}// TarjetaLayerImpl
|
package com.beans.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.beans.EnggStudent;
import com.beans.Student;
public class TestStudent {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
EnggStudent student_old = (EnggStudent) context.getBean("engg_old");
System.out.println("with old configuration");
System.out.println(student_old);
EnggStudent student_new = (EnggStudent) context.getBean("engg_new");
System.out.println("with new configuration");
System.out.println(student_new);
System.out.println("with new configuration with overridding roll number");
EnggStudent student_new1 = (EnggStudent) context.getBean("engg_new1");
System.out.println(student_new1);
System.out.println("try to obtain Student instance");
Student student = (Student) context.getBean("student");
}
}
|
/**
*
*/
package ru.andreychapliuk;
/**
* @author Andrey
*
*/
public interface EepromIC {
public static enum TypeI2C {
// int PageSizeToWrite, int PageSizeToRead, int QuantityPageToWrite, int QuantityPagesToRead
IC24C16(16, 128, 128, 16),
IC24C32(32, 128, 128, 32),
IC24C64(32, 128, 256, 64),
IC24C128(64, 128, 256, 128),
IC24C256(64, 128, 512, 256),
IC24C512(128, 128, 512, 512),
IC24C1024(128, 128, 1024, 1024);
private final int pageSizeToWrite;
/**
* @return the quantityPageToWrite
*/
public int getQuantityPageToWrite() {
return quantityPageToWrite;
}
/**
* @return the quantityPagesToRead
*/
public int getQuantityPagesToRead() {
return quantityPagesToRead;
}
private final int pageSizeToRead;
private final int quantityPageToWrite;
private final int quantityPagesToRead;
TypeI2C(int PageSizeToWrite, int PageSizeToRead,
int QuantityPageToWrite, int QuantityPagesToRead) {
pageSizeToWrite = PageSizeToWrite;
pageSizeToRead = PageSizeToRead;
quantityPageToWrite = QuantityPageToWrite;
quantityPagesToRead = QuantityPagesToRead;
}
public void getTypeI2C(short[] mas) {
if (mas.length < 4)
{
System.out.println("Неверный входной массив");
return;
}
mas[0] = (short) getPageSizeToWrite();
mas[1] = (short) getPageSizeToRead();
mas[2] = (short) quantityPageToWrite;
mas[3] = (short) quantityPagesToRead;
}
/**
* @return the pageSizeToRead
*/
public int getPageSizeToRead() {
return pageSizeToRead;
}
/**
* @return the pageSizeToWrite
*/
public int getPageSizeToWrite() {
return pageSizeToWrite;
}
}
}
|
package basic;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Exercise06Test {
@Test
public void test_calSumDigitsOfNumber() {
assertEquals(new Exercise06().sumSequenceOfNum(3), 20);
}
}
|
package com.hesoyam.pharmacy.pharmacy.repository;
import com.hesoyam.pharmacy.pharmacy.model.Pharmacy;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface PharmacyRepository extends JpaRepository<Pharmacy, Long> {
@Query("select p from Pharmacy p join p.inventory i join i.inventoryItems it join it.medicine m where m.id = :medicine_id and it.available>0")
List<Pharmacy> getPharmacyByMedicineAvailability(@Param("medicine_id") Long medicineId);
@Query("select p from Pharmacy p join p.administrator a where a.id = :administrator_id")
Pharmacy getPharmacyByAdministrator(@Param("administrator_id") Long administratorId);
@Query("SELECT pharmacy " +
"FROM Pharmacy pharmacy join pharmacy.inventory inventory join inventory.inventoryItems invItems join invItems.medicine medicine " +
"WHERE medicine.id IN (:medicineIds) " +
"GROUP BY pharmacy.id " +
"HAVING COUNT(pharmacy) = :listSize")
List<Pharmacy> getPharmaciesByMedicineAvailability(@Param("medicineIds")List<Long> medicineIds, @Param("listSize") Long size);
@Query("SELECT ( count(pharmacy) > 0 ) " +
"FROM Pharmacy pharmacy join pharmacy.inventory inventory join inventory.inventoryItems invItems " +
"WHERE pharmacy.id = :pharmacyId AND invItems.medicine.id = :medicineId AND invItems.available >= :quantity ")
Boolean canPharmacyOfferMedicineQuantity(@Param("pharmacyId") Long pharmacyId, @Param("medicineId") Long medicineId, @Param("quantity") int quantity);
Pharmacy findById(long pharmacyId);
}
|
package ru.itis.javalab.servlets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* MediaServlet
* created: 22-01-2021 - 21:19
* project: 07. Fremarker
*
* @author dinar
* @version v0.1
*/
@WebServlet("/media")
public class MediaServlet extends HttpServlet {
private final String imagesPath = "C:\\Users\\dinar\\Documents\\1-All Projects" +
"\\#Java\\JavaLab\\JavaLab\\07. Fremarker\\store\\images\\";
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
String path = request.getParameter("path");
File file = new File(imagesPath + path + ".jpg");
InputStream inputStream = new FileInputStream(file);
response.getOutputStream().write(inputStream.readAllBytes());
}
}
|
package org.maven.ide.eclipse.io;
import java.io.IOException;
/**
* http response 403
* @author mkleint
*
*/
public class ForbiddenException
extends IOException
{
private static final long serialVersionUID = -3931433246316614538L;
public ForbiddenException( String message )
{
super( message );
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.platformtools.x;
class SettingsUI$2 implements OnClickListener {
final /* synthetic */ SettingsUI mUx;
SettingsUI$2(SettingsUI settingsUI) {
this.mUx = settingsUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
h.mEJ.h(11545, Integer.valueOf(3));
x.i("MicroMsg.SettingsUI", "reprot: MM_LightPushCloseWechat == OP_LogoutConfirm");
h.mEJ.a(99, 145, 1, false);
if (!(g.DF() == null || g.DF().dJs == null)) {
g.DF().dJs.bD(false);
}
if (SettingsUI.g(this.mUx) != null) {
SettingsUI.g(this.mUx).dismiss();
}
SettingsUI.h(this.mUx);
}
}
|
package com.tantransh.workshopapp.jobbooking.data;
import java.io.Serializable;
import java.util.ArrayList;
public class JobServiceList implements Serializable{
private ArrayList<ServiceInfo> serviceList;
private static JobServiceList instance;
private JobServiceList (){
serviceList = new ArrayList<>();
}
public static JobServiceList getInstance(){
if(instance == null){
instance = new JobServiceList();
}
return instance;
}
public ServiceInfo getService(int pos){
return serviceList.get(pos);
}
public void addService(ServiceInfo serviceInfo){
serviceList.add(serviceInfo);
}
public void remove(int pos){
serviceList.remove(pos);
}
public void clear(){
serviceList.clear();
}
public int getSize(){
return serviceList.size();
}
public ServiceInfo getService(String serviceId){
for(int i = 0; i<getSize(); i++){
if(getService(i).getServiceId().equals(serviceId)){
return getService(i);
}
}
return null;
}
public boolean searchService(String serviceId){
return getService(serviceId) != null;
}
public boolean comparePrice(String serviceId, String price){
return getService(serviceId).getAmount().equals(price);
}
public void updateAmount(String serviceId, String amount){
getService(serviceId).setAmount(amount);
}
}
|
/**
*
* @author 141638
*/
public class main {
public static void main(String[] args) {
CheckInput ci = new CheckInput();
BubbleSort bs = new BubbleSort();
int ar[] = null;
int n = 0;
int check = 0;
do{
System.out.println("======== BubbleSort ========");
System.out.println("1. Input Elements");
System.out.println("2. Display Array");
System.out.println("3. Sort In Ascending Order");
System.out.println("4. Sort In Descending Order");
System.out.println("0. Exit");
n = ci.CheckInput(0,0,4);
switch(n){
case 1:{
System.out.println("--------- Input Elements ---------");
System.out.println("Enter size of array: ");
int x = ci.CheckInput(3,0,0);
ar = new int[x];
for(int i = 0;i<ar.length;i++){
System.out.print("Element "+(i+1)+" :");
ar[i] = ci.CheckInput(2,0,0);
}
System.err.println("Add Completed!");
check = 0;
break;
}
case 2:{
if(ar == null)
System.err.println("List is empty!");
else{
System.out.println("--------- Display ---------");
System.out.print("Array: ");
if(check == 2){
for(int i = ar.length-1;i>=0;i--)
System.out.printf(" [%d] ",ar[i]);
}
else{
for(int i = 0;i<ar.length;i++)
System.out.printf(" [%d] ",ar[i]);
}
System.out.println("");
}
break;
}
case 3:{
if(ar == null)
System.err.println("List is empty!");
else{
if(check == 0){
bs.sort(ar);
System.err.println("Sort Completed!!");
check = 1;
}
else{
check = 1;
System.err.println("Sort Completed!!");
}
}
break;
}
case 4:{
if(ar == null)
System.err.println("List is empty!");
else{
if(check == 0){
bs.sort(ar);
System.err.println("Sort Completed!!");
check = 2;
}
else{
check = 2;
System.err.println("Sort Completed!!");
}
}
break;
}
}
}
while(n!=0);
}
}
|
/*
* 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 antariksa.fx;
import antariksa.fx.dbase.DBConnector;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Border;
import javafx.scene.layout.VBox;
import javafx.scene.media.AudioClip;
import javafx.stage.Stage;
/**
*
* @author ACER
*/
public class CobaFX extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Sistem Peluncuran Roket"); //Judul Tab
Parent root = FXMLLoader.load(getClass().getResource("PeluncuranRoket.fxml"));
Image gmb = new Image(getClass().getResource("Rocket_icon.png").toString());
ImageView view = new ImageView(gmb);
view.setPreserveRatio(true);
view.setFitWidth(120);
VBox tampil = new VBox();
VBox kosong = new VBox();
kosong.setBorder(Border.EMPTY);
tampil.setAlignment(Pos.CENTER);
tampil.getChildren().addAll(root,view,kosong);
Scene scene = new Scene(tampil);
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
if(null != DBConnector.getConnection("MYSQL")){
System.out.println("succes");
} else{
System.out.println("Gagal");
}
//AccountHolderDataModel ahdm = new AccountHolderDataModel("MYSQL");
//IndividualHolder ih = new IndividualHolder(20,"Abbi","Lampung","male","2002-08-21",new Account(55,5000000.0));
//ahdm.addAccountHolder(ih);
//System.out.println("succes");
launch(args);
} catch (SQLException ex) {
Logger.getLogger(CobaFX.class.getName()).log(Level.SEVERE, null, ex);
}
/*try {
AccountHolderDataModel tes = new AccountHolderDataModel("MYSQL");
System.out.println(tes.nextAccountHolderID());
} catch (SQLException ex) {
Logger.getLogger(CobaFX.class.getName()).log(Level.SEVERE, null, ex);
}*/
//launch(args);
}
}
|
/*
* Copyright (c) 2012 by Bjoern Kolbeck.
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.osd;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicReference;
import org.xtreemfs.common.statusserver.StatusServerModule;
import org.xtreemfs.osd.rwre.RWReplicationStage;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType;
import com.sun.net.httpserver.HttpExchange;
/**
* Status page showing the list of files currently open in replication mode.
* @author bjko
*/
class ReplicatedFileStatusPage extends StatusServerModule {
private OSDRequestDispatcher myDispatcher;
@Override
public String getDisplayName() {
return "OSD Replicated File Table";
}
@Override
public String getUriPath() {
return "/rft";
}
@Override
public boolean isAvailableForService(ServiceType service) {
return service == ServiceType.SERVICE_TYPE_OSD;
}
@Override
public void initialize(ServiceType service, Object serviceRequestDispatcher) {
assert (service == ServiceType.SERVICE_TYPE_OSD);
myDispatcher = (OSDRequestDispatcher) serviceRequestDispatcher;
}
@Override
public void shutdown() {
}
@Override
public void handle(HttpExchange httpExchange) throws IOException {
try {
final StringBuffer sb = new StringBuffer();
final AtomicReference<Map<String, Map<String, String>>> result
= new AtomicReference<Map<String, Map<String, String>>>();
sb.append("<HTML><HEAD><TITLE>Replicated File Status List</TITLE>");
sb.append("<STYLE type=\"text/css\">body,table,tr,td,h1 ");
sb.append("{font-family:Arial,Helvetica,sans-serif;}</STYLE></HEAD><BODY>");
sb.append("<H1>List of Open Replicated Files</H1>");
sb.append("<TABLE border=\"1\">");
sb.append("<TR><TD><B>File ID</B></TD><TD><B>Status</B></TD></TR>");
myDispatcher.getRWReplicationStage().getStatus(new RWReplicationStage.StatusCallback() {
@Override
public void statusComplete(Map<String, Map<String, String>> status) {
synchronized (result) {
result.set(status);
result.notifyAll();
}
}
});
synchronized (result) {
if (result.get() == null)
result.wait();
}
Map<String, Map<String, String>> status = result.get();
for (String fileId : status.keySet()) {
sb.append("<TR><TD>");
sb.append(fileId);
final String role = status.get(fileId).get("role");
String bgcolor = "#FFFFFF";
if (role != null && role.equals("primary")) {
bgcolor = "#A3FFA3";
} else if (role != null && role.startsWith("backup")) {
bgcolor = "#FFFF66";
}
sb.append("</TD><TD style=\"background-color:");
sb.append(bgcolor);
sb.append("\"><TABLE border=\"0\">");
for (Entry<String, String> e : status.get(fileId).entrySet()) {
sb.append("<TR><TD>");
sb.append(e.getKey());
sb.append("</TD><TD>");
sb.append(e.getValue());
sb.append("</TD></TR>\n");
}
sb.append("</TABLE></TD></TR>\n");
}
sendResponse(httpExchange, sb.toString());
} catch (Throwable ex) {
ex.printStackTrace();
httpExchange.sendResponseHeaders(500, 0);
}
}
}
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
package com.wire.bots.sdk.tools;
import com.wire.bots.sdk.exceptions.AuthException;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.math.BigInteger;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
private static Pattern pattern = Pattern.compile("(?<=@)([a-zA-Z0-9\\_]{3,})");
private static final String HMAC_SHA_1 = "HmacSHA1";
public static byte[] encrypt(byte[] key, byte[] dataToSend, byte[] iv) throws Exception {
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));
byte[] bytes = c.doFinal(dataToSend);
ByteArrayOutputStream os = new ByteArrayOutputStream();
os.write(iv);
os.write(bytes);
return os.toByteArray();
}
public static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
ByteArrayInputStream is = new ByteArrayInputStream(encrypted);
byte[] iv = new byte[16];
is.read(iv);
byte[] bytes = toByteArray(is);
IvParameterSpec vec = new IvParameterSpec(iv);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, vec);
return cipher.doFinal(bytes);
}
public static SecretKey genKey(char[] password, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), "AES");
}
public static String readLine(File file) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
return br.readLine();
}
}
public static String readFile(File f) throws IOException {
try (FileInputStream fis = new FileInputStream(f)) {
byte[] data = new byte[(int) f.length()];
fis.read(data);
return new String(data, "UTF-8");
}
}
public static void writeLine(String line, File file) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(line);
}
}
public static String calcMd5(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes, 0, bytes.length);
byte[] hash = md.digest();
byte[] byteArray = Base64.getEncoder().encode(hash);
return new String(byteArray);
}
public static String digest(MessageDigest md, byte[] bytes) {
md.update(bytes, 0, bytes.length);
byte[] hash = md.digest();
byte[] byteArray = Base64.getEncoder().encode(hash);
return new String(byteArray);
}
public static String getHmacSHA1(String payload, String secret)
throws NoSuchAlgorithmException, InvalidKeyException {
Mac hmac = Mac.getInstance(HMAC_SHA_1);
hmac.init(new SecretKeySpec(secret.getBytes(Charset.forName("UTF-8")), HMAC_SHA_1));
byte[] bytes = hmac.doFinal(payload.getBytes(Charset.forName("UTF-8")));
return String.format("%040x", new BigInteger(1, bytes));
}
public static byte[] toByteArray(InputStream input) throws IOException {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
int n;
byte[] buffer = new byte[1024 * 4];
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
}
public static boolean compareAuthorizations(String auth1, String auth2) {
if (auth1 == null || auth2 == null)
return false;
String token1 = extractToken(auth1);
String token2 = extractToken(auth2);
return token1.equals(token2);
}
private static String extractToken(String auth) {
String[] split = auth.split(" ");
return split.length == 1 ? split[0] : split[1];
}
public static String extractMimeType(byte[] imageData) throws IOException {
try (ByteArrayInputStream input = new ByteArrayInputStream(imageData)) {
String contentType = URLConnection.guessContentTypeFromStream(input);
return contentType != null ? contentType : "image/xyz";
}
}
public static byte[] getResource(String name) throws IOException {
ClassLoader classLoader = Util.class.getClassLoader();
try (InputStream resourceAsStream = classLoader.getResourceAsStream(name)) {
return toByteArray(resourceAsStream);
}
}
public static int mentionLen(String txt) {
Matcher matcher = pattern.matcher(txt);
if (matcher.find()) {
return matcher.group().length() + 1;
}
return 0;
}
public static int mentionStart(String txt) {
Matcher matcher = pattern.matcher(txt);
if (matcher.find()) {
return matcher.start() - 1;
}
return 0;
}
public static UUID extractUserId(String token) throws AuthException {
String[] pairs = token.split("\\.");
for (String pair : pairs) {
String[] vals = pair.split("=");
if (vals.length == 2 && vals[0].equals("u"))
return UUID.fromString(vals[1]);
}
throw new AuthException("Error extracting userId from token", 403);
}
}
|
package servlet.controller;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import servlet.model.MemberDAOImpl;
import servlet.model.MemberVO;
public class AllMemberController implements Controller{
@Override
public ModelAndView execute(HttpServletRequest request, HttpServletResponse response) {
String path = "";
try{
ArrayList<MemberVO> list=MemberDAOImpl.getInstance().showAllMember();
request.setAttribute("list", list);
path = "allView.jsp";
}catch(SQLException e) {
}
return new ModelAndView(path);
}
}
|
package com.baomidou.mybatisplus.samples.quickstart.domain;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class WindowTab implements Serializable {
/**
* id
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 橱窗名
*/
private String name;
/**
* 橱窗位置 1:首页
*/
private Integer location;
/**
* 排序
*/
private Integer sort;
/**
* logo图片地址
*/
private String logo;
/**
* 角标0:默认,1:最新,2:最热
*/
private Integer mark;
/**
* 角标
*/
@TableField(strategy = FieldStrategy.IGNORED)
private String markStr;
/**
* 跳转方式:1:内链、2:外链、3:产品
*/
private Integer jumpType;
/**
* 跳转地址
*/
private String jumpUrl;
private Date createTime;
private Date updateTime;
/**
* 1正常
*/
private Integer status;
/**
* 1:全部用户 2:未登录用户 3:已登录用户 4:渠道用户------>(5.2.3)5:新用户 6:老用户
*/
private Integer displayType;
/**
* 展示设备 0:全部 1:安卓 2:ios
*/
private Integer displayEquipment;
/**
* 展示包名
*/
private String platfrom;
/**
* 上线时间
*/
@TableField(strategy = FieldStrategy.IGNORED)
private Date onlineDate;
/**
* 下线时间
*/
@TableField(strategy = FieldStrategy.IGNORED)
private Date offlineDate;
private static final long serialVersionUID = 1L;
private Integer cityLimit;
@TableField(strategy = FieldStrategy.IGNORED)
private String city;
}
|
package del.group10.java_ee.repository;
import java.util.List;
import del.group10.java_ee.model.DaftarTujuan;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TujuanRepository extends JpaRepository<DaftarTujuan, Integer> {
DaftarTujuan findByTujuan(String tujuan);
List<DaftarTujuan> findAll();
}
|
/*
* 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 loc.dto;
/**
*
* @author hi
*/
public class RoomDTO {
private String roomID, hotelID, typeID, statusID, image, description;
private double price;
private int amount;
public RoomDTO() {
}
public RoomDTO(String roomID, String hotelID, String typeID, String statusID, String image, String description, double price, int amount) {
this.roomID = roomID;
this.hotelID = hotelID;
this.typeID = typeID;
this.statusID = statusID;
this.image = image;
this.description = description;
this.price = price;
this.amount = amount;
}
public RoomDTO(String roomID, String hotelID, String typeID, String image, String description, double price, int amount) {
this.roomID = roomID;
this.hotelID = hotelID;
this.typeID = typeID;
this.image = image;
this.description = description;
this.price = price;
this.amount = amount;
}
public String getRoomID() {
return roomID;
}
public void setRoomID(String roomID) {
this.roomID = roomID;
}
public String getHotelID() {
return hotelID;
}
public void setHotelID(String hotelID) {
this.hotelID = hotelID;
}
public String getTypeID() {
return typeID;
}
public void setTypeID(String typeID) {
this.typeID = typeID;
}
public String getStatusID() {
return statusID;
}
public void setStatusID(String statusID) {
this.statusID = statusID;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
|
package ibatis.services.user.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import ibatis.services.domain.User;
import ibatis.services.user.UserDAO;
/*
* Persistence Layer Component :: MyBatisUserDAOImpl10
* SqlSession을 DI 하는 컴포넌트
* 1) 필드에 SqlSession 선언
* 2) setter로 주입
*
* MyBatisUserDAOImpl10의 Persistence Layer Component가 잘 만들어졌는지를 확인하는
* Persistence Layer의 단위테스트는 MyBatisTestApp102
*/
public class MyBatisUserDAOImpl10 implements UserDAO {
private SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public int addUser(User user) throws Exception {
int result = sqlSession.insert("User10.addUser",user);
sqlSession.commit();
return result;
}
@Override
public int updateUser(User user) throws Exception {
int result = sqlSession.update("User10.updateUser",user);
sqlSession.commit();
return result;
}
@Override
public int removeUser(String userId) throws Exception {
int result = sqlSession.delete("User10.removeUser",userId);
sqlSession.commit();
return result;
}
@Override
public User getUser(String userId) throws Exception {
return sqlSession.selectOne("User10.getUser", userId);
}
@Override
public List<User> getUserList(User user) throws Exception {
return sqlSession.selectList("User10.getUserList", user);
}
}
|
package submitter;
//
//import java.io.BufferedReader;
//import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.FileReader;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.IOException;
//import java.io.OutputStreamWriter;
//import java.net.URL;
//import java.net.URLConnection;
//import java.net.URLEncoder;
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//import java.util.ArrayList;
//import java.util.Enumeration;
//import java.util.List;
//
//public class Submit {
//
// String[] partIDs = new String[] { "hvSBXixt" };
// String[] partNames = new String[] { "Part1" };
//
// String logPath = "/Users/samira_tasharofi/Documents/workspace-coursera/Test/logcat.txt";
// String runnerScriptPath = "/Users/samira_tasharofi/Documents/workspace-coursera/Submitter/src/testrunner.sh";
// String deviceScriptPath = "/Users/samira_tasharofi/Documents/workspace-coursera/Submitter/src/devicechecker.sh";
//
// public void submit(Integer partId) {
// System.out.println(String.format("==\n== Submitting Solutions"
// + " | Programming Exercise %s\n==", homework_id()));
//
// partId = promptPart();
// if (!isValidPartId(partId)) {
// System.err.println("!! Invalid homework part selected.");
// System.err
// .println(String.format(
// "!! Expected an integer from 1 to %d.",
// partIDs.length + 1));
// System.err.println("!! Submission Cancelled");
// return;
// }
//
// String[] loginPassword = loginPrompt();
// String login = loginPassword[0];
// String password = loginPassword[1];
//
// if (login == null || login.equals("")) {
// System.out.println("!! Submission Cancelled");
// return;
// }
//
// System.out.print("\n== Connecting to coursera ... ");
//
// // Setup submit list
// List<Integer> submitParts = new ArrayList<Integer>();
// if (partId == partIDs.length + 1) {
// for (int i = 0; i < partIDs.length; i++) {
// submitParts.add(new Integer(i));
// }
// } else {
// submitParts.add(new Integer(partId - 1));
// }
//
// for (Integer part : submitParts) {
// // Get Challenge
// String[] loginChSignature = getChallenge(login, part);
// if (loginChSignature == null) {
// return;
// }
// login = loginChSignature[0];
// String ch = loginChSignature[1];
// String signature = loginChSignature[2];
// String ch_aux = loginChSignature[3];
//
// // Attempt Submission with Challenge
// String ch_resp = challengeResponse(login, password, ch);
// String result = submitSolution(login, ch_resp, part.intValue(),
// output(part, ch_aux), source(part), signature);
// if (result == null) {
// result = "NULL RESPONSE";
// }
// System.out.println(String.format(
// "\n== Submitted Homework %s - Part %s ", homework_id(),
// partNames[part]));
// System.out.println("== " + result);
// if (result
// .trim()
// .equals("Exception: We could not verify your username / password, please try again. (Note that your password is case-sensitive.)")) {
// System.out
// .println("== The password is not your login, but a 10 character alphanumeric string displayed on the top of the Assignments page.");
// }
// }
// }
//
// private String homework_id() {
// return "Assignment1";
// }
//
// private List<List<String>> sources() {
// List<List<String>> srcs = new ArrayList<List<String>>();
// List<String> tmp;
//
// // Java.
// tmp = new ArrayList<String>(1);
// tmp.add("./src/submitter/Base64.java");
// srcs.add(tmp);
//
// return srcs;
// }
//
// private String challenge_url() {
// return "https://class.coursera.org/androidapps101-001/assignment/challenge";
// }
//
// private String submit_url() {
// return "https://class.coursera.org/androidapps101-001/assignment/submit";
// }
//
// // private String writeContactsToJSON(List<SpamLord.Contact> contacts) {
// // JSONArray jContact;
// // JSONArray jAll = new JSONArray();
// //
// // SpamLord.Contact c;
// // for (int i = 0; i < contacts.size(); i++) {
// // c = contacts.get(i);
// // jContact = new JSONArray();
// // jContact.add(c.getFileName());
// // jContact.add(c.getType());
// // jContact.add(c.getValue());
// // jAll.add(jContact);
// // }
// // StringWriter out = new StringWriter();
// // String jarr = new String();
// // try {
// // jAll.writeJSONString(out);
// // jarr = out.toString();
// // } catch(java.io.IOException e) {
// // System.err.println("[ERROR]\tcould not encode submission into JSON");
// // }
// // return jarr;
// // }
//
// protected String output(int partId, String ch_aux) {
//
// Runtime rt = Runtime.getRuntime();
// try {
//
// Process deviceChecker = rt.exec(deviceScriptPath);
// deviceChecker.waitFor();
// BufferedReader reader = new BufferedReader(new InputStreamReader(
// deviceChecker.getInputStream()));
//
// //this line is "List of devices attached"
// String line = reader.readLine();
//
// /*The next lines indicate the list of devices running.
// * If there is no second line, no device is attached,
// * then throw error and exit.
// */
// line = reader.readLine();
// if (line == null || !line.contains("device")) {
// System.out.println("line"+line);
// System.err.println("Error! No device is attached! Please run a device and try again.");
// return "";
// }
//
// Process testrunner = rt.exec(runnerScriptPath);
// testrunner.waitFor();
// int r = testrunner.exitValue();
// reader = new BufferedReader(new InputStreamReader(
// testrunner.getErrorStream()));
// String errorLine;
// while ((errorLine = reader.readLine()) != null) {
// System.err.println(errorLine);
// }
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// String result = parseLogFile(logPath);
//
// return result;
// }
//
// private String parseLogFile(String log) {
//
// String result = "";
// String returnedResult = "";
//
// String testCaseTag = "****** TEST CASE: ";
// String failedTag = "****** FAILED COUNT: ";
// String passTag = "****** PASSED COUNT: ";
//
// try {
// BufferedReader logReader = new BufferedReader(new FileReader(log));
// String line;
//
// try {
// while ((line = logReader.readLine()) != null) {
// if (line.contains(failedTag)) {
// result += "F:"
// + line.substring(line.indexOf(failedTag)
// + failedTag.length());
// result += ";";
// }
// if (line.contains(passTag)) {
// returnedResult = line.substring(line.indexOf(passTag)
// + passTag.length());
// result += "P:" + returnedResult;
// }
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// System.out.println("The result is " + result);
//
// // TODO Auto-generated method stub
// return returnedResult;
// }
//
// // ========================= CHALLENGE HELPERS =========================
//
// private String source(int partId) {
// StringBuffer src = new StringBuffer();
// List<List<String>> src_files = sources();
// if (partId < src_files.size()) {
// List<String> flist = src_files.get(partId);
// for (String fname : flist) {
// try {
// BufferedReader reader = new BufferedReader(new FileReader(
// fname));
// String line;
// while ((line = reader.readLine()) != null) {
// src.append(line);
// }
// reader.close();
// src.append("||||||||");
// } catch (IOException e) {
// System.err.println(String.format(
// "!! Error reading file '%s': %s", fname,
// e.getMessage()));
// return src.toString();
// }
// }
// }
// return src.toString();
// }
//
// private boolean isValidPartId(int partId) {
// return (partId >= 1 && partId <= partIDs.length + 1);
// }
//
// private int promptPart() {
// int partId = -1;
// System.out.println("== Select which part(s) to submit:");
// List<List<String>> srcFiles = sources();
// StringBuffer prompt = new StringBuffer();
// for (int i = 1; i < partIDs.length + 1; i++) {
// prompt.append(String.format("== %d) %s [", i, partNames[i - 1]));
// List<String> srcs = srcFiles.get(i - 1);
// for (String src : srcs) {
// prompt.append(String.format(" %s ", src));
// }
// prompt.append("]\n");
// }
// prompt.append(String.format("== %d) All of the above \n",
// partIDs.length + 1));
// prompt.append(String.format("==\nEnter your choice [1-%d]: ",
// partIDs.length + 1));
// System.out.println(prompt.toString());
// try {
// BufferedReader in = new BufferedReader(new InputStreamReader(
// System.in));
// String line = in.readLine();
// partId = Integer.parseInt(line);
// if (!isValidPartId(partId)) {
// partId = -1;
// }
// } catch (Exception e) {
// System.err.println("!! Error reading partId from stdin: "
// + e.getMessage());
// return -1;
// }
// return partId;
// }
//
// // Returns [email,ch,signature]
// private String[] getChallenge(String email, int partId) {
// String[] results = new String[4];
// try {
// URL url = new URL(challenge_url());
// URLConnection connection = url.openConnection();
// connection.setDoOutput(true);
// OutputStreamWriter out = new OutputStreamWriter(
// connection.getOutputStream());
// // url encode e-mail
// out.write("email_address=" + URLEncoder.encode(email, "UTF-8"));
// out.write("&assignment_part_sid=" + partIDs[partId]);
// out.write("&response_encoding=delim");
// out.close();
// BufferedReader in = new BufferedReader(new InputStreamReader(
// connection.getInputStream()));
// StringBuffer sb = new StringBuffer();
// String line;
// while ((line = in.readLine()) != null) {
// sb.append(line + "\n");
// }
// String str = sb.toString();
// in.close();
//
// String[] splits = str.split("\\|");
//
// if (splits.length < 8) {
// System.err.println("!! Error getting challenge from server.");
// for (String string : results) {
// System.err.println(string);
// }
// return null;
// } else {
// results[0] = splits[2]; // email
// results[1] = splits[4]; // ch
// results[2] = splits[6]; // signature
// if (splits.length == 9) { // if there's a challenge, use it
// results[3] = splits[8];
// } else {
// results[3] = null;
// }
// }
// } catch (Exception e) {
// System.err.println("Error getting challenge from server: "
// + e.getMessage());
// }
// return results;
// }
//
// private String submitSolution(String email, String ch_resp, int part,
// String output, String source, String state) {
// String str = null;
// try {
// StringBuffer post = new StringBuffer();
// post.append("assignment_part_sid="
// + URLEncoder.encode(partIDs[part], "UTF-8"));
// post.append("&email_address=" + URLEncoder.encode(email, "UTF-8"));
// post.append("&submission="
// + URLEncoder.encode(base64encode(output), "UTF-8"));
// post.append("&submission_aux="
// + URLEncoder.encode(base64encode(source), "UTF-8"));
// post.append("&challenge_response="
// + URLEncoder.encode(ch_resp, "UTF-8"));
// post.append("&state=" + URLEncoder.encode(state, "UTF-8"));
//
// URL url = new URL(submit_url());
// URLConnection connection = url.openConnection();
// connection.setDoOutput(true);
// OutputStreamWriter out = new OutputStreamWriter(
// connection.getOutputStream());
// out.write(post.toString());
// out.close();
//
// BufferedReader in = new BufferedReader(new InputStreamReader(
// connection.getInputStream()));
//
// String line = "";
// str = "";
// while ((line = in.readLine()) != null) {
// str += line + " ";
// }
// // str = in.readLine();
// in.close();
//
// } catch (Exception e) {
// System.err.println("!! Error submittion solution: "
// + e.getMessage());
// return null;
// }
// return str;
// }
//
// // =========================== LOGIN HELPERS ===========================
//
// // Returns [login, password]
// private String[] loginPrompt() {
// String[] results = new String[2];
// try {
// // System.out.print("Login (Email address): ");
// System.out.println("Login (Email address): ");
// BufferedReader in = new BufferedReader(new InputStreamReader(
// System.in));
// String line = in.readLine();
// results[0] = line.trim();
// results[0] = "tasharo1@illinois.edu";
//
// // System.out.print("Password: ");
// System.out.println("Password: ");
// line = in.readLine();
// results[1] = line.trim();
// results[1] = "BQjD3aRBJs";
// } catch (IOException e) {
// System.err.println("!! Error prompting for login/password: "
// + e.getMessage());
// }
// return results;
// }
//
// private String challengeResponse(String email, String passwd,
// String challenge) {
// MessageDigest md = null;
// try {
// md = MessageDigest.getInstance("SHA-1");
// } catch (NoSuchAlgorithmException e) {
// System.err.println("No such hashing algorithm: " + e.getMessage());
// }
// try {
// String message = challenge + passwd;
// md.update(message.getBytes("US-ASCII"));
// byte[] byteDigest = md.digest();
// StringBuffer buf = new StringBuffer();
// for (byte b : byteDigest) {
// buf.append(String.format("%02x", b));
// }
// return buf.toString();
// } catch (Exception e) {
// System.err.println("Error generating challenge response: "
// + e.getMessage());
// }
// return null;
// }
//
// public String base64encode(String str) {
// Base64 base = new Base64();
// byte[] strBytes = str.getBytes();
// byte[] encBytes = base.encode(strBytes);
// String encoded = new String(encBytes);
// return encoded;
// }
//
// public static void main(String[] args) {
//
// Submit submit = new Submit();
// submit.submit(0);
// }
//}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class Submit {
String[] partIDs = new String[] { "hvSBXixt" };
String[] partNames = new String[] { "Part1" };
String logPath = "/Users/samira_tasharofi/Documents/workspace-coursera/Test/logcat.txt";
String runnerScriptPath = "/Users/samira_tasharofi/Documents/workspace-coursera/Submitter/src/testrunner.sh";
String deviceScriptPath = "/Users/samira_tasharofi/Documents/workspace-coursera/Submitter/src/devicechecker.sh";
public void submit(String testResult, String resultFilePath) {
// System.out.println(String.format("==\n== Submitting Solutions"
// + " | Programming Exercise %s\n==", homework_id()));
int partId = promptPart();
if (!isValidPartId(partId)) {
System.err.println("!! Invalid homework part selected.");
System.err
.println(String.format(
"!! Expected an integer from 1 to %d.",
partIDs.length + 1));
System.err.println("!! Submission Cancelled");
return;
}
String[] loginPassword = loginPrompt();
String login = loginPassword[0];
String password = loginPassword[1];
if (login == null || login.equals("")) {
System.out.println("!! Submission Cancelled");
return;
}
System.out.print("\n== Connecting to coursera ... ");
// Setup submit list
List<Integer> submitParts = new ArrayList<Integer>();
if (partId == partIDs.length + 1) {
for (int i = 0; i < partIDs.length; i++) {
submitParts.add(new Integer(i));
}
} else {
submitParts.add(new Integer(partId - 1));
}
for (Integer part : submitParts) {
// Get Challenge
String[] loginChSignature = getChallenge(login, part);
if (loginChSignature == null) {
return;
}
login = loginChSignature[0];
String ch = loginChSignature[1];
String signature = loginChSignature[2];
String ch_aux = loginChSignature[3];
// Attempt Submission with Challenge
String ch_resp = challengeResponse(login, password, ch);
String result = submitSolution(login, ch_resp, part.intValue(),
/*output(part, ch_aux)*/testResult, /*source(part)*/"", signature);
if (result == null) {
result = "NULL RESPONSE";
}
System.out.println(String.format(
"\n== Submitted Homework %s - Part %s ", homework_id(),
partNames[part]));
System.out.println("== " + result);
if (result
.trim()
.equals("Exception: We could not verify your username / password, please try again. (Note that your password is case-sensitive.)")) {
System.out
.println("== The password is not your login, but a 10 character alphanumeric string displayed on the top of the Assignments page.");
}
// File resultFile = new File(resultFilePath);
//
// System.out.println(resultFile.getAbsolutePath());
//
//
// try {
// FileWriter writer = new FileWriter(resultFile);
// writer.write(result);
// writer.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
private String homework_id() {
return "Assignment1";
}
private List<List<String>> sources() {
List<List<String>> srcs = new ArrayList<List<String>>();
List<String> tmp;
// Java.
tmp = new ArrayList<String>(1);
tmp.add("./src/submitter/Base64.java");
srcs.add(tmp);
return srcs;
}
private String challenge_url() {
return "https://class.coursera.org/androidapps101-001/assignment/challenge";
}
private String submit_url() {
return "https://class.coursera.org/androidapps101-001/assignment/submit";
}
// protected String output(int partId, String ch_aux) {
//
// Runtime rt = Runtime.getRuntime();
// try {
//
// Process deviceChecker = rt.exec(deviceScriptPath);
// deviceChecker.waitFor();
// BufferedReader reader = new BufferedReader(new InputStreamReader(
// deviceChecker.getInputStream()));
//
// //this line is "List of devices attached"
// String line = reader.readLine();
//
// /*The next lines indicate the list of devices running.
// * If there is no second line, no device is attached,
// * then throw error and exit.
// */
// line = reader.readLine();
// if (line == null || !line.contains("device")) {
// System.out.println("line"+line);
// System.err.println("Error! No device is attached! Please run a device and try again.");
// return "";
// }
//
// Process testrunner = rt.exec(runnerScriptPath);
// testrunner.waitFor();
// int r = testrunner.exitValue();
// reader = new BufferedReader(new InputStreamReader(
// testrunner.getErrorStream()));
// String errorLine;
// while ((errorLine = reader.readLine()) != null) {
// System.err.println(errorLine);
// }
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// String result = parseLogFile(logPath);
//
// return result;
// }
// private String parseLogFile(String log) {
//
// String result = "";
// String returnedResult = "";
//
// String testCaseTag = "****** TEST CASE: ";
// String failedTag = "****** FAILED COUNT: ";
// String passTag = "****** PASSED COUNT: ";
//
// try {
// BufferedReader logReader = new BufferedReader(new FileReader(log));
// String line;
//
// try {
// while ((line = logReader.readLine()) != null) {
// if (line.contains(failedTag)) {
// result += "F:"
// + line.substring(line.indexOf(failedTag)
// + failedTag.length());
// result += ";";
// }
// if (line.contains(passTag)) {
// returnedResult = line.substring(line.indexOf(passTag)
// + passTag.length());
// result += "P:" + returnedResult;
// }
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// System.out.println("The result is " + result);
//
// // TODO Auto-generated method stub
// return returnedResult;
// }
// ========================= CHALLENGE HELPERS =========================
private String source(int partId) {
StringBuffer src = new StringBuffer();
// List<List<String>> src_files = sources();
// if (partId < src_files.size()) {
// List<String> flist = src_files.get(partId);
// for (String fname : flist) {
// try {
// BufferedReader reader = new BufferedReader(new FileReader(
// fname));
// String line;
// while ((line = reader.readLine()) != null) {
// src.append(line);
// }
// reader.close();
// src.append("||||||||");
// } catch (IOException e) {
// System.err.println(String.format(
// "!! Error reading file '%s': %s", fname,
// e.getMessage()));
// return src.toString();
// }
// }
// }
src.append("");
return src.toString();
}
private boolean isValidPartId(int partId) {
return (partId >= 1 && partId <= partIDs.length + 1);
}
private int promptPart() {
int partId = -1;
// System.out.println("== Select which part(s) to submit:");
// List<List<String>> srcFiles = sources();
// StringBuffer prompt = new StringBuffer();
// for (int i = 1; i < partIDs.length + 1; i++) {
// prompt.append(String.format("== %d) %s [", i, partNames[i - 1]));
// List<String> srcs = srcFiles.get(i - 1);
// for (String src : srcs) {
// prompt.append(String.format(" %s ", src));
// }
// prompt.append("]\n");
// }
// prompt.append(String.format("== %d) All of the above \n",
// partIDs.length + 1));
// prompt.append(String.format("==\nEnter your choice [1-%d]: ",
// partIDs.length + 1));
// System.out.println(prompt.toString());
// try {
// BufferedReader in = new BufferedReader(new InputStreamReader(
// System.in));
// String line = in.readLine();
// partId = Integer.parseInt(line);
// if (!isValidPartId(partId)) {
// partId = -1;
// }
// } catch (Exception e) {
// System.err.println("!! Error reading partId from stdin: "
// + e.getMessage());
// return -1;
// }
partId = 1;
return partId;
}
// Returns [email,ch,signature]
private String[] getChallenge(String email, int partId) {
String[] results = new String[4];
try {
URL url = new URL(challenge_url());
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
// url encode e-mail
out.write("email_address=" + URLEncoder.encode(email, "UTF-8"));
out.write("&assignment_part_sid=" + partIDs[partId]);
out.write("&response_encoding=delim");
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
String str = sb.toString();
in.close();
String[] splits = str.split("\\|");
if (splits.length < 8) {
System.err.println("!! Error getting challenge from server.");
for (String string : results) {
System.err.println(string);
}
return null;
} else {
results[0] = splits[2]; // email
results[1] = splits[4]; // ch
results[2] = splits[6]; // signature
if (splits.length == 9) { // if there's a challenge, use it
results[3] = splits[8];
} else {
results[3] = null;
}
}
} catch (Exception e) {
System.err.println("Error getting challenge from server: "
+ e.getMessage());
}
return results;
}
private String submitSolution(String email, String ch_resp, int part,
String output, String source, String state) {
String str = null;
try {
StringBuffer post = new StringBuffer();
post.append("assignment_part_sid="
+ URLEncoder.encode(partIDs[part], "UTF-8"));
post.append("&email_address=" + URLEncoder.encode(email, "UTF-8"));
post.append("&submission="
+ URLEncoder.encode(base64encode(output), "UTF-8"));
post.append("&submission_aux="
+ URLEncoder.encode(base64encode(source), "UTF-8"));
post.append("&challenge_response="
+ URLEncoder.encode(ch_resp, "UTF-8"));
post.append("&state=" + URLEncoder.encode(state, "UTF-8"));
URL url = new URL(submit_url());
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write(post.toString());
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = "";
str = "";
while ((line = in.readLine()) != null) {
str += line + " ";
}
// str = in.readLine();
in.close();
} catch (Exception e) {
System.err.println("!! Error submittion solution: "
+ e.getMessage());
return null;
}
return str;
}
// =========================== LOGIN HELPERS ===========================
// Returns [login, password]
private String[] loginPrompt() {
String[] results = new String[2];
results[0] = "tasharo1@illinois.edu";
results[1] = "BQjD3aRBJs";
// try {
// // System.out.print("Login (Email address): ");
// System.out.println("Login (Email address): ");
// BufferedReader in = new BufferedReader(new InputStreamReader(
// System.in));
// String line = in.readLine();
// results[0] = line.trim();
//
// // System.out.print("Password: ");
// System.out.println("Password: ");
// line = in.readLine();
// results[1] = line.trim();
//
// } catch (IOException e) {
// System.err.println("!! Error prompting for login/password: "
// + e.getMessage());
// }
return results;
}
private String challengeResponse(String email, String passwd,
String challenge) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
System.err.println("No such hashing algorithm: " + e.getMessage());
}
try {
String message = challenge + passwd;
md.update(message.getBytes("US-ASCII"));
byte[] byteDigest = md.digest();
StringBuffer buf = new StringBuffer();
for (byte b : byteDigest) {
buf.append(String.format("%02x", b));
}
return buf.toString();
} catch (Exception e) {
System.err.println("Error generating challenge response: "
+ e.getMessage());
}
return null;
}
public String base64encode(String str) {
Base64 base = new Base64();
byte[] strBytes = str.getBytes();
byte[] encBytes = base.encode(strBytes);
String encoded = new String(encBytes);
return encoded;
}
public static void main(String[] args) {
Submit submit = new Submit();
submit.submit("4","");
}
}
|
package com.esc.fms.service.file.impl;
import com.esc.fms.common.constant.Constants;
import com.esc.fms.entity.Dictionary;
import com.esc.fms.entity.FileOperationHistory;
import com.esc.fms.entity.SharedFile;
import com.esc.fms.entity.User;
import com.esc.fms.service.base.DictionaryService;
import com.esc.fms.service.base.FtpService;
import com.esc.fms.service.file.FileManageService;
import com.esc.fms.service.file.FileOperationHistoryService;
import com.esc.fms.service.file.FileService;
import com.esc.fms.service.right.UserService;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* Created by tangjie on 2017/9/7.
*/
@Service("fileManageService")
public class FileManageServiceImpl implements FileManageService{
private static final Logger logger = LoggerFactory.getLogger(FileManageServiceImpl.class);
@Autowired
private FileService fileService;
@Autowired
private FtpService ftpService;
@Autowired
private UserService userService;
@Autowired
private FileOperationHistoryService fileOperationHistoryService;
public boolean fileReplace(Integer fileID, MultipartFile file, String userName) throws IOException {
logger.debug("call fileReplace method!");
SharedFile sharedFile = fileService.selectByPrimaryKey(fileID);
String fileUrl = sharedFile.getFilePath();
String removedFileName = sharedFile.getFileName() + "." + sharedFile.getFileExtType();
FTPClient ftpClient = null;
try{
ftpClient = ftpService.getFtpClient();
logger.debug("file Download ... fileUrl:[{}]",fileUrl);
String[] paths = fileUrl.split("/");
for(int i=0;i<paths.length;i++){
String path = new String(paths[i].getBytes(ftpClient.getControlEncoding()), Constants.SERVER_CHARSET);
if(!ftpClient.changeWorkingDirectory(path)){
throw new IOException("为文件路径[" + fileUrl + "]切换目录[" + path + "]时,失败!");
}
}
if(!ftpClient.deleteFile(removedFileName)){
throw new IOException("删除路径[" + sharedFile.getFilePath() + "]下的文件[" + removedFileName + "]失败!");
}
logger.debug("begin upload file [{}]",file.getOriginalFilename());
if(!ftpClient.storeFile(file.getOriginalFilename(),file.getInputStream())){
throw new IOException("文件[" + file.getOriginalFilename() + "]上传失败,没有操作权限!");
}
file.getInputStream().close();
logger.debug("end upload file [{}]",file.getOriginalFilename());
User user = userService.getUserByUserName(userName);
String[] arr = file.getOriginalFilename().split("\\.");
sharedFile.setFileName(arr[0]);
sharedFile.setFileExtType(arr[1]);
sharedFile.setMimeType(file.getContentType());
sharedFile.setFileSize(file.getSize());
sharedFile.setLastUpdator(user.getUserID());
sharedFile.setUpdateTime(new Date());
fileService.updateByPrimaryKey(sharedFile);
recordFileOpHistory(sharedFile,"0501",user.getUserID());
}catch (IOException e){
logger.error(e.getMessage());
throw e;
}finally {
try{
ftpService.closeFtpConnection(ftpClient);
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}
}
return true;
}
public boolean fileDelete(List<Integer> fileIDs, String userName) throws IOException {
logger.debug("call fileDelete method!");
FTPClient ftpClient = null;
try{
for(Integer fileID : fileIDs){
SharedFile sharedFile = fileService.selectByPrimaryKey(fileID);
String fileUrl = sharedFile.getFilePath();
String removedFileName = sharedFile.getFileName() + "." + sharedFile.getFileExtType();
ftpClient = ftpService.getFtpClient();
logger.debug("file Delete ... fileUrl:[{}]",fileUrl);
String[] paths = fileUrl.split("/");
for(int i=0;i<paths.length;i++){
String path = new String(paths[i].getBytes(ftpClient.getControlEncoding()), Constants.SERVER_CHARSET);
if(!ftpClient.changeWorkingDirectory(path)){
throw new IOException("为文件路径[" + fileUrl + "]切换目录[" + path + "]时,失败!");
}
}
logger.debug("begin delete file [{}]",removedFileName);
if(!ftpClient.deleteFile(removedFileName)){
throw new IOException("删除路径[" + sharedFile.getFilePath() + "]下的文件[" + removedFileName + "]失败!");
}
if(!fileService.deleteByPrimaryKey(fileID)){
throw new IOException("删除文件[" + sharedFile.getFileName() + "]数据库中的记录失败!");
}
User user = userService.getUserByUserName(userName);
recordFileOpHistory(sharedFile,"0502",user.getUserID());
logger.debug("end delete file [{}]",removedFileName);
}
}catch (IOException e){
logger.error(e.getMessage());
throw e;
}finally {
try{
ftpService.closeFtpConnection(ftpClient);
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}
}
return true;
}
private void recordFileOpHistory(SharedFile file,String fileOpType,Integer userID){
FileOperationHistory foh = new FileOperationHistory();
foh.setFileID(file.getFileID());
foh.setFileName(file.getFileName());
foh.setFileExtType(file.getFileExtType());
foh.setFilePath(file.getFilePath());
foh.setFolderName(file.getFolderName());
foh.setFileOpType(fileOpType);
foh.setCreator(file.getCreator());
foh.setCreatTime(file.getCreateTime());
foh.setUpdateTime(new Date());
foh.setUpdator(userID);
fileOperationHistoryService.insert(foh);
}
}
|
package br.ufrgs.rmpestano.intrabundle.plugin;
import br.ufrgs.rmpestano.intrabundle.locator.OSGiProjectLocator;
import br.ufrgs.rmpestano.intrabundle.util.TestUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.forge.project.Project;
import org.jboss.forge.resources.DirectoryResource;
import org.jboss.forge.resources.FileResource;
import org.jboss.forge.test.SingletonAbstractShellTest;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
/**
* Created by rmpestano on 8/23/14.
*/
public abstract class BaseMetricsTest extends SingletonAbstractShellTest{
@Deployment
public static JavaArchive getDeployment() {
JavaArchive jar = TestUtils.getBaseDeployment();
jar.addPackages(true, OSGiProjectLocator.class.getPackage()) ;
//System.out.println(jar.toString(true));
return jar;
}
public Project initializeOSGiMavenProject() throws Exception {
DirectoryResource root = createTempFolder();
DirectoryResource main = root.getOrCreateChildDirectory("main");
TestUtils.addPom(main);
TestUtils.addMavenBundle(main, "module1");
TestUtils.addMavenBundle(main, "module2");
TestUtils.addMavenBundle(main, "module3");
getShell().setCurrentResource(main);
return getProject();
}
public Project initializeOSGiBundleWithStaleReferences() throws Exception {
DirectoryResource root = createTempFolder();
DirectoryResource mod1 = TestUtils.addMavenBundle(root,"module1");
FileResource<?> aClass = (FileResource<?>) mod1.getOrCreateChildDirectory("src").
getOrCreateChildDirectory("main").
getOrCreateChildDirectory("java").
getOrCreateChildDirectory("br").
getOrCreateChildDirectory("ufrgs").
getOrCreateChildDirectory("rmpestano").getChild("AClass.java");
if(!aClass.exists()){
aClass.setContents(TestUtils.class.getResourceAsStream("/ClassWithLotsOfLines.java"));
}
getShell().setCurrentResource(mod1);
return getProject();
}
public Project initializeMavenBundle() throws Exception {
DirectoryResource root = createTempFolder();
getShell().setCurrentResource(TestUtils.addMavenBundle(root, "module1"));
return getProject();
}
}
|
package sample.entity;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
@Entity
@Table(name = "pokazaniya", schema = "komraz", catalog = "")
public class PokazaniyaEntity {
private int id;
private double value;
private Date date;
private SchetchikEntity schetchik;
@Id
@GeneratedValue(generator="increment")
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "value")
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
@Basic
@Column(name = "date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@ManyToOne
@JoinColumn(name = "schetchik_id")
public SchetchikEntity getSchetchik() {
return schetchik;
}
public void setSchetchik(SchetchikEntity schetchik) {
this.schetchik = schetchik;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PokazaniyaEntity that = (PokazaniyaEntity) o;
if (id != that.id) return false;
if (Double.compare(that.value, value) != 0) return false;
if (schetchik != that.schetchik) return false;
if (!Objects.equals(date, that.date)) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
temp = Double.doubleToLongBits(value);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (date != null ? date.hashCode() : 0);
result = 31 * result + schetchik.hashCode();
return result;
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
final class c$gr extends g {
c$gr() {
super("reportMiniProgramPageData", "reportMiniProgramPageData", 284, false);
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import com.tencent.mm.bk.b;
public final class bzj extends a {
public long rxH;
public int svC;
public int svD;
public int svE;
public int svF;
public b svG;
public long svs;
protected final int a(int i, Object... objArr) {
int S;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.T(1, this.svs);
aVar.T(2, this.rxH);
aVar.fT(3, this.svC);
aVar.fT(4, this.svD);
aVar.fT(5, this.svE);
aVar.fT(6, this.svF);
if (this.svG != null) {
aVar.b(7, this.svG);
}
return 0;
} else if (i == 1) {
S = (((((f.a.a.a.S(1, this.svs) + 0) + f.a.a.a.S(2, this.rxH)) + f.a.a.a.fQ(3, this.svC)) + f.a.a.a.fQ(4, this.svD)) + f.a.a.a.fQ(5, this.svE)) + f.a.a.a.fQ(6, this.svF);
if (this.svG != null) {
return S + f.a.a.a.a(7, this.svG);
}
return S;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (S = a.a(aVar2); S > 0; S = a.a(aVar2)) {
if (!super.a(aVar2, this, S)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bzj bzj = (bzj) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
bzj.svs = aVar3.vHC.rZ();
return 0;
case 2:
bzj.rxH = aVar3.vHC.rZ();
return 0;
case 3:
bzj.svC = aVar3.vHC.rY();
return 0;
case 4:
bzj.svD = aVar3.vHC.rY();
return 0;
case 5:
bzj.svE = aVar3.vHC.rY();
return 0;
case 6:
bzj.svF = aVar3.vHC.rY();
return 0;
case 7:
bzj.svG = aVar3.cJR();
return 0;
default:
return -1;
}
}
}
}
|
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.KIPPENSolldatenType;
import java.io.StringWriter;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class KIPPENSolldatenTypeBuilder
{
public static String marshal(KIPPENSolldatenType kIPPENSolldatenType)
throws JAXBException
{
JAXBElement<KIPPENSolldatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), KIPPENSolldatenType.class , kIPPENSolldatenType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private Boolean geaendertKz;
private ArbeitsvorgangTypType arbeitsvorgang;
public KIPPENSolldatenTypeBuilder setGeaendertKz(Boolean value)
{
this.geaendertKz = value;
return this;
}
public KIPPENSolldatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value)
{
this.arbeitsvorgang = value;
return this;
}
public KIPPENSolldatenType build()
{
KIPPENSolldatenType result = new KIPPENSolldatenType();
result.setGeaendertKz(geaendertKz);
result.setArbeitsvorgang(arbeitsvorgang);
return result;
}
}
|
package jawale.ankita.helloworld;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import static android.graphics.Typeface.ITALIC;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView introTV = (TextView) findViewById(R.id.intro);
introTV.setText(R.string.intro);
introTV.setTypeface(Typeface.defaultFromStyle(ITALIC));
}
}
|
package com.demo.modules.sys.controller;
import com.demo.common.annotation.SysLog;
import com.demo.common.entity.Page;
import com.demo.common.entity.R;
import com.demo.modules.sys.entity.SysLogEntity;
import com.demo.modules.sys.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* 系统日志
*
* @author Centling Techonlogies
* @email xxx@demo.com
* @url www.demo.com
* @date 2017年8月14日 下午10:01:36
*/
@RestController
@RequestMapping("/sys/log")
public class SysLogController extends AbstractController {
@Autowired
private SysLogService sysLogService;
/**
* 日志列表
* @param params
* @return
*/
@RequestMapping("/list")
public Page<SysLogEntity> listLog(@RequestBody Map<String, Object> params) {
return sysLogService.listLog(params);
}
/**
* 删除日志
* @param id
* @return
*/
@SysLog("删除日志")
@RequestMapping("/remove")
public R batchRemove(@RequestBody Long[] id) {
return sysLogService.batchRemove(id);
}
/**
* 清空日志
* @return
*/
@SysLog("清空日志")
@RequestMapping("/clear")
public R batchRemoveAll() {
return sysLogService.batchRemoveAll();
}
}
|
public class staticvariable1 {
static int var1=77;
String var2;
public static void main(String args[])
{
staticvariable1 ob1 = new staticvariable1();
staticvariable1 ob2 = new staticvariable1();
ob1.var1=88;
ob1.var2="I'm Object1";
ob2.var1=99;
ob2.var2="I'm Object2";
System.out.println("ob1 integer:"+ob1.var1);
System.out.println("ob1 String:"+ob1.var2);
System.out.println("ob2 integer:"+ob2.var1);
System.out.println("ob2 STring:"+ob2.var2);
}
}
|
package com.ibm.ive.tools.japt.reduction.ita;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;
public class FieldCollection {
/*
* Because of the implementation of the Comparable interface in
* FieldInstance, the use of TreeMap here cannot include two different
* field instance for the same field (ie the same field in two separate objects)
*/
TreeMap instanceFields;
public int size() {
if(instanceFields == null) {
return 0;
}
return instanceFields.size();
}
public FieldInstance getFieldInstance(Field field, boolean generic, PropagatedObject owningObject) {
if(field.isStatic()) {
throw new IllegalArgumentException();
}
FieldInstance instance;
if(instanceFields == null) {
instanceFields = new TreeMap();
instance = createNewInstance(field, generic, owningObject);
} else {
instance = (FieldInstance) instanceFields.get(field);
if(instance == null) {
instance = createNewInstance(field, generic, owningObject);
}
}
return instance;
}
private FieldInstance createNewInstance(Field field, boolean generic,
PropagatedObject owningObject) {
FieldInstance instance;
instance = field.isShared() ? field.getDeclaringClass().getSharedFieldInstance(field) :
(generic ? field.getDeclaringClass().getGenericFieldInstance(field) :
new ObjectFieldInstance(field, owningObject));
instanceFields.put(field, instance);
return instance;
}
public ObjectSet getContainedObjects() {
if(instanceFields == null) {
return ObjectSet.EMPTY_SET;
}
Collection values = instanceFields.values();
if(values.size() == 0) {
return ObjectSet.EMPTY_SET;
}
Iterator iterator = values.iterator();
FieldInstance fieldInstance = (FieldInstance) iterator.next();
ObjectSet set = fieldInstance.getContainedObjects();
if(values.size() == 1) {
if(set == null) {
return ObjectSet.EMPTY_SET;
}
return set;
}
ObjectSet result = new ObjectSet();
if(set != null) {
result.addAll(set);
}
while(iterator.hasNext()) {
fieldInstance = (FieldInstance) iterator.next();
set = fieldInstance.getContainedObjects();
if(set != null) {
result.addAll(set);
}
}
if(result.size() == 0) {
return ObjectSet.EMPTY_SET;
}
return result;
}
}
|
package com.tb.bughub.order.demo;
import com.tb.bughub.order.demo.domain.OrderRequest;
import com.tb.bughub.order.demo.domain.OrderResponse;
import com.tb.bughub.order.demo.model.Order;
import com.tb.bughub.order.demo.repository.OrderRepository;
import com.tb.bughub.order.demo.service.OrderService;
import com.tb.bughub.order.demo.web.OrderController;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.ui.ModelExtensionsKt;
import org.springframework.util.Assert;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
@AutoConfigureMockMvc
@SpringBootTest
@EnableWebMvc
class DemoApplicationTests extends Mockito {
@Autowired
private MockMvc mvc;
@Autowired
private OrderService orderService;
@MockBean
private OrderRepository orderRepository;
@MockBean
private Order order;
@Test
void contextLoads() {
}
@Test
public void postCreateOrder() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/orders/createOrder").accept(MediaType.APPLICATION_JSON).content("test"))
.andExpect(status().isOk());
}
@Test
public void createOrder_thenReturnOrderResponse () throws Exception{
OrderRequest orderRequest = new OrderRequest();
List<String> menuItemList = new ArrayList<String>();
menuItemList.add("333-333-333-333");
orderRequest.setMenuItem(menuItemList);
orderRequest.setRestuarantId("2020");
orderRequest.setUserId("test");
orderRequest.setTip(25);
when(orderRepository.save(order)).thenReturn(any());
OrderResponse orderResponse = orderService.createOrder(orderRequest);
Assertions.assertNotNull(orderResponse.getOrderId());
Assertions.assertNotNull(orderResponse.getTotalPrice());
Assertions.assertNotNull(orderResponse.getOrderTime());
Assertions.assertNotNull(orderResponse.getExpectedDeliveryTime());
}
}
|
/**
*
*/
package excepciones;
/**
* @author susana
*
*/
@SuppressWarnings("serial")
public class ErrorNumeroCiclosIncorrecto extends Exception {
/**
*
*/
public ErrorNumeroCiclosIncorrecto() {
// TODO Auto-generated constructor stub
}
/**
* @param arg0
*/
public ErrorNumeroCiclosIncorrecto(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
/**
* @param arg0
*/
public ErrorNumeroCiclosIncorrecto(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
/**
* @param arg0
* @param arg1
*/
public ErrorNumeroCiclosIncorrecto(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
}
|
package com.lty.entity;
/**
* @Author: lty
* @Date: 2021/1/20 10:11
*/
public class ReferenceData {
private String data;
private String data2;
public ReferenceData(String data, String data2) {
this.data = data;
this.data2 = data2;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@Override
public String toString() {
return "ReferenceData{" +
"data='" + data + '\'' +
", data2='" + data2 + '\'' +
'}';
}
}
|
package com.salesianos.ModeloManyToMany.service;
import com.salesianos.ModeloManyToMany.model.Song;
import com.salesianos.ModeloManyToMany.repositories.SongRepository;
import com.salesianos.ModeloManyToMany.service.base.BaseService;
import org.springframework.stereotype.Service;
@Service
public class SongService
extends BaseService<Song, Long, SongRepository> {
}
|
package com.villcore.gis.tiles.server;
import com.villcore.gis.tiles.FilePosition;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TileFileManager {
private static final Logger LOGGER = LoggerFactory.getLogger(TileFileManager.class);
private static final byte[] ZERO_BYTES_ARRAY = new byte[0];
private static final int INDEX_BLOCK_LEN = 4 + 4 + 8 + 4;
private Path curRoot;
private int zLevel;
private Path metaPath;
private Path indexPath;
private Path mapPath;
private int xStart;
private int xEnd;
private int yStart;
private int yEnd;
private ByteBuffer indexByteBuffer;
private ByteBuffer mapByteBuffer;
private boolean indexCache = true;
private boolean mapCache = true;
public TileFileManager(int zLevel, Path curRoot) {
this.zLevel = zLevel;
this.curRoot = curRoot;
this.metaPath = Paths.get(curRoot.toString(), zLevel + ".meta");
this.indexPath = Paths.get(curRoot.toString(), zLevel + ".index");
this.mapPath = Paths.get(curRoot.toString(), zLevel + ".map");
}
public void init() throws IOException {
readMeta();
readIndex();
readMap();
}
public byte[] getTileBytes(int xLevel, int yLevel) throws IOException {
System.out.println(correct(xLevel, yLevel));
if (!correct(xLevel, yLevel)) {
return ZERO_BYTES_ARRAY;
}
FilePosition filePosition = getTilePosition(xLevel - xStart, yLevel - yStart);
return getTileToBytes(filePosition);
}
public ByteBuf getTileByteBuf(int xLevel, int yLevel) throws IOException {
if (!correct(xLevel, yLevel)) {
return Unpooled.wrappedBuffer(ZERO_BYTES_ARRAY);
}
int x = xLevel - xStart;
int y = yLevel - yStart;
FilePosition filePosition = getTilePosition(x, y);
return Unpooled.wrappedBuffer(getTileToBuffer(filePosition));
}
private byte[] getTileToBytes(FilePosition filePosition) {
byte[] bytes = new byte[filePosition.len];
mapByteBuffer.position((int) filePosition.start);
mapByteBuffer.get(bytes);
mapByteBuffer.position(0);
return bytes;
}
private ByteBuffer getTileToBuffer(FilePosition filePosition) {
int start = (int) filePosition.start;
int end = (int) (filePosition.start + filePosition.len);
ByteBuffer byteBuffer = mapByteBuffer.duplicate();
byteBuffer.position(start).limit(end);
return byteBuffer;
}
private FilePosition getTilePosition(int x, int y) throws IOException {
long indexPos = getIndexPosition(x, y, INDEX_BLOCK_LEN);
// byte[] bytes = new byte[INDEX_BLOCK_LEN];
//
// indexByteBuffer.position((int) indexPos);
// indexByteBuffer.get(bytes);
// indexByteBuffer.position(0);
//
// ByteBuffer indexBlockBuffer = ByteBuffer.wrap(bytes);
// LOGGER.debug("start = {}, len = {}", indexByteBuffer.position(), indexByteBuffer.limit());
LOGGER.debug("X = {}, Y = {}", x, y);
return new FilePosition(indexByteBuffer.getLong((int) (indexPos + 4 + 4)), indexByteBuffer.getInt((int) (indexPos + 4 + 4 + 8)));
}
private long getIndexPosition(int xPos, int yPos, int blockLen) {
return (xPos * (yEnd - yStart + 1) + yPos) * blockLen;
}
private boolean correct(int xLevel, int yLevel) {
if (!(xLevel >= xStart && xLevel <= xEnd)) {
return false;
}
if (!(yLevel >= yStart && yLevel <= yEnd)) {
return false;
}
return true;
}
private void readMeta() throws IOException {
RandomAccessFile metaFile = new RandomAccessFile(metaPath.toFile(), "r");
this.xStart = metaFile.readInt();
this.xEnd = metaFile.readInt();
this.yStart = metaFile.readInt();
this.yEnd = metaFile.readInt();
LOGGER.debug("read meta, xStart = {}, xEnd = {}, yStart = {}, yEnd = {}", new Object[]{
xStart, xEnd, yStart, yEnd
});
}
private void readIndex() throws IOException {
RandomAccessFile indexFile = new RandomAccessFile(indexPath.toFile(), "r");
FileChannel indexFileChannel = indexFile.getChannel();
this.indexByteBuffer = indexFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, indexFile.length());
LOGGER.debug("file size = {}, indexBuffer pos = {}, limit = {}", indexFile.length(), indexByteBuffer.position(), indexByteBuffer.limit());
if(indexCache) {
this.indexByteBuffer = cacheByteBuffer(this.indexByteBuffer);
}
}
private void readMap() throws IOException {
RandomAccessFile mapFile = new RandomAccessFile(mapPath.toFile(), "r");
FileChannel indexFileChannel = mapFile.getChannel();
this.mapByteBuffer = indexFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, mapFile.length());
if (mapCache) {
this.mapByteBuffer = cacheByteBuffer(this.mapByteBuffer);
}
}
private ByteBuffer cacheByteBuffer(ByteBuffer src) {
int capcity = src.capacity();
ByteBuffer memByteBuffer = ByteBuffer.allocateDirect(capcity);
memByteBuffer.put(src);
return memByteBuffer;
}
public void close() {
}
}
|
package com.facebook.yoga;
public interface YogaNodeClonedFunction {
void onNodeCloned(YogaNode paramYogaNode1, YogaNode paramYogaNode2, YogaNode paramYogaNode3, int paramInt);
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\yoga\YogaNodeClonedFunction.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.deltastuido.order.interfaces;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.deltastuido.cart.domain.Cart;
import com.deltastuido.store.Address;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class OrderCreation {
@XmlElement
private Cart cart;
@XmlElement
private Address address;
@XmlElement
private String customization;
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getCustomizations() {
return customization;
}
public void setCustomizations(String customization) {
this.customization = customization;
}
}
|
package se.magmag.oauth.properties;
/**
* Created by magnus.eriksson on 04/07/16.
*/
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
@Singleton
@Slf4j
public class PropertyFileResolver {
private Map<String, String> properties = new HashMap<String, String>();
@PostConstruct
private void init() {
//"application.properties" matches the property name as defined in the system-properties element in WildFly
String propertyFile = System.getProperty("application.properties");
File file = new File(propertyFile);
Properties properties = new Properties();
try {
properties.load(new FileInputStream(file));
} catch (IOException e) {
LOG.error("Unable to load properties file" + e);
}
HashMap <String, String> propertyMap = new HashMap<String, String>();
for(Map.Entry<Object, Object> x : properties.entrySet()) {
propertyMap.put((String)x.getKey(), (String)x.getValue());
}
this.properties.putAll(propertyMap);
}
public String getProperty(String key) {
return properties.get(key);
}
}
|
/*
* 注册时的操作类
* 更新时间:
* ZQW-2018-03-15
* ZQW-2018-03-16
*/
package controller;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import model.DataBase;
import model.FileText;
import model.JudgeTextField;
import model.Time;
public class Register
{
private Register() {}
//用于检测用户输入数据的合法性并反馈给用户的方法
public static boolean registerWIS(JTextField NicknameText, JTextField PasswordText, JTextField PasswordText2,
JTextField MailText, JLabel label_1, JLabel label_2, JLabel label_3)
{
if(!FileText.getLineText(1).equals("0"))//已注册
return false;
else
{
if(!JudgeTextField.judgeName("昵称", NicknameText.getText().length(), 2, 8).equals(""))
{//昵称有问题时
label_1.setText(JudgeTextField.judgeName("昵称", NicknameText.getText().length(), 2, 8));
label_1.setForeground(Color.red);
return false;
}
else
{
label_1.setText("正确");
label_1.setForeground(Color.green);
}
if(!JudgeTextField.judgeTwo("密码", PasswordText.getText(), PasswordText2.getText()).equals(""))
{//两次密码不一致时
label_2.setText(JudgeTextField.judgeTwo("密码", PasswordText.getText(), PasswordText2.getText()));
label_2.setForeground(Color.red);
return false;
}
else
{
if(!JudgeTextField.judgePassword("密码", PasswordText.getText(), 6, 16).equals(""))
{//密码不符合要求
label_2.setText(JudgeTextField.judgePassword("密码", PasswordText.getText(), 6, 16));
label_2.setForeground(Color.red);
return false;
}
else
{
label_2.setText("正确");
label_2.setForeground(Color.green);
}
}
if(!JudgeTextField.judgeMail("邮箱", MailText.getText()).equals(""))
{//邮箱有问题时
label_3.setText(JudgeTextField.judgeMail("邮箱", MailText.getText()));
label_3.setForeground(Color.red);
return false;
}
else
{
label_3.setText("正确");
label_3.setForeground(Color.green);
return true;
}
}
}
//注册时对数据库进行操作的方法
public static boolean addToDataBase(JTextField Nickname, JTextField Password, JTextField Mail)
{
if(!DataBase.insertDataBase(GetCode.code, Password.getText(), Nickname.getText(), Mail.getText()))
{
JOptionPane.showMessageDialog(null, "注册失败!", "无服务提示", 0);
return false;
}
else
{
int lines = 7;//文件内容的行数
String temptext = "";//临时存储文件内容
for(int i = 1; i <= lines; i++)
{
if(i == 1)//修改第一行
temptext = "1\n";
else
temptext = temptext.concat(FileText.getLineText(i).concat("\n"));//存储文件内容
}
if(!FileText.setText(temptext))//修改文件失败
{
JOptionPane.showMessageDialog(null, "信息文件异常!", "无服务提示", 0);
return false;
}
else//完成注册
{
DataBase.modifyDataBase("user", "Code", GetCode.code, "RegisterTime", Time.YMDDate);
return true;
}
}
}
}
|
package com.tencent.mm.plugin.remittance.model;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.lo;
import com.tencent.mm.protocal.c.lp;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.c.h;
import java.net.URLDecoder;
public final class m extends h {
private final String TAG = "MicroMsg.NetSceneF2fDynamicCode";
public lp mxr;
public m(int i, String str, String str2, String str3, String str4, String str5, String str6, String str7, String str8) {
a aVar = new a();
aVar.dIG = new lo();
aVar.dIH = new lp();
aVar.dIF = 2736;
aVar.uri = "/cgi-bin/mmpay-bin/f2fdynamiccode";
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
lo loVar = (lo) this.diG.dID.dIL;
loVar.amount = i;
loVar.hyG = str;
loVar.myl = str2;
loVar.rpI = URLDecoder.decode(str3);
loVar.mxX = str4;
loVar.mxY = str5;
loVar.myo = str6;
loVar.nickname = str7;
loVar.mxM = str8;
x.i("MicroMsg.NetSceneF2fDynamicCode", "amount: %s, username: %s, transfer_code_id: %s", new Object[]{Integer.valueOf(i), str, URLDecoder.decode(str3)});
}
public final int getType() {
return 2736;
}
public final void b(int i, int i2, String str, q qVar) {
x.i("MicroMsg.NetSceneF2fDynamicCode", "errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
this.mxr = (lp) ((b) qVar).dIE.dIL;
x.i("MicroMsg.NetSceneF2fDynamicCode", "retcode: %s, retmsg: %s", new Object[]{Integer.valueOf(this.mxr.hUm), this.mxr.hUn});
if (this.diJ != null) {
this.diJ.a(i, i2, str, this);
}
}
protected final void f(q qVar) {
lp lpVar = (lp) ((b) qVar).dIE.dIL;
this.uXe = lpVar.hUm;
this.uXf = lpVar.hUn;
}
}
|
package com.xindq.yilan.util;
public class UrlUtil {
public static String getHttpUrl(String address, String path) {
return "http://" + address + path;
}
public static String getWsUrl(String address, String path) {
return "ws://" + address + path;
}
}
|
package com.bsa.bsa_giphy.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Data
@AllArgsConstructor
public class UserIdDto {
@Pattern(regexp = "^[\\w\\-. ]+$")
@Size(min = 1, max = 260)
private final String userId;
}
|
// $Id: ackermann.java,v 1.5 2001/11/17 17:20:39 doug Exp $
// http://www.bagley.org/~doug/shootout/
package com.harris.mobihoc;
public class ackermann implements Runnable{
private boolean contin = false;
private int num = 10;
public ackermann(boolean contin, int num){
this.contin = contin;
this.num = num;
}
@Override
public void run(){
//int num = Integer.parseInt(args[0]);
System.out.println("Ack(3," + num + "): " + Ack(3, num));
if(contin){
try{
Thread trial = new Thread(new fibo(contin, num));
trial.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static int Ack(int m, int n) {
return (m == 0) ? (n + 1) : ((n == 0) ? Ack(m-1, 1) :
Ack(m-1, Ack(m, n - 1)));
}
}
|
package org.usfirst.frc.team346.camera;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class PiCamera extends Thread
{
boolean isValid;
double lastTargetX;
double lastTargetY;
double lastTargetZ;
double lastTargetRotX;
double lastTargetRotY;
double lastTargetRotZ;
double linearDistance;
double linearAngle;
double robotX;
double robotY;
double robotZ;
//This is the angle in which the camera is rotated up,
//we need this to determine the hypotenuse
public double cameraAngle = 0;
final double maxError = 1.5; //Degrees either way for error .... to be changed later
final double goalOpening = 16.0/12; //Calculation in feet ..
final double ballDiam = 10.0/12; //Calculation in feet ..
final double ballRad = ballDiam/2.0; //Calculation in feet ..
public void run()
{
while(true)
{
tick();
trySleep(1);
}
}
public void trySleep(long ms)
{
try
{
sleep(ms);
} catch(Exception ex)
{}
}
public void tick()
{
try
{
isValid = SmartDashboard.getBoolean("camera_isValid");
lastTargetX = SmartDashboard.getNumber("camera_last_target_x");
lastTargetY = SmartDashboard.getNumber("camera_last_target_y");
lastTargetZ = SmartDashboard.getNumber("camera_last_target_z");
lastTargetRotX = SmartDashboard.getNumber("camera_last_target_rot_x");
lastTargetRotY = SmartDashboard.getNumber("camera_last_target_rot_y");
lastTargetRotZ = SmartDashboard.getNumber("camera_last_target_rot_z");
if(isValid)
{
calculatePosition();
}
}
catch(Exception e)
{
isValid = false;
}
}
protected void calculatePosition()
{
double opp = -1*lastTargetY; //Negative is up so reverse it first
double hypo = lastTargetZ; //Z is the distance in a straight line from the lens to the center
double alpha = Math.toDegrees(Math.asin(opp/hypo));
alpha += cameraAngle;
//cos(angle) = adj/hypo
double adj = hypo*Math.cos(Math.toRadians(alpha));
linearDistance = adj;
opp = lastTargetX;
alpha = Math.toDegrees(Math.asin(opp/hypo));
linearAngle = alpha;
}
/************************************************************************************************
Getters
************************************************************************************************/
public boolean hasTarget()
{
return isValid;
}
public double getTargetCameraX()
{
return lastTargetX;
}
public double getTargetCameraY()
{
return lastTargetY;
}
public double getTargetCameraZ()
{
return lastTargetZ;
}
public double getTargetCameraRotX()
{
return lastTargetRotX;
}
public double getTargetCameraRotY()
{
return lastTargetRotY;
}
public double getTargetCameraRotZ()
{
return lastTargetRotZ;
}
//This is the distance ON THE GROUND from the robot to the BASE of where the target is
public double getLinearDistance()
{
return linearDistance;
}
//This is the rotation of the robot ON THE GROUND in relation to the target
public double getLinearAngle()
{
return linearAngle;
}
public boolean onTargetAngle()
{
return Math.abs(linearAngle) <= maxError;
}
public boolean onTargetBallInGoal()
{
//TODO: Calculate based on the target's rotational vector as well as the opening closes as it is rotated
return Math.abs(lastTargetX) <= Math.abs(Math.cos(lastTargetRotZ)*goalOpening)/2.0-ballRad;
}
}
|
package com.company.dog;
public class Sichu implements Dog{
@Override
public void introduces() {
System.out.println("츄츄츄츄츄츄츄츄");
}
}
|
package com.tbg.capture;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CAMERA = 1;
private GstAhc gstAhc;
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private SurfaceView surfaceView;
private ImageButton playButton;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
surfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private View mControlsView;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
hide();
}
};
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
new String[] { Manifest.permission.CAMERA },
PERMISSION_REQUEST_CAMERA);
return;
}
try {
gstAhc = GstAhc.init(this);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
setContentView(R.layout.activity_main);
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
playButton = (ImageButton) findViewById(R.id.play_button);
// Set up the user interaction to manually show or hide the system UI.
surfaceView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggle();
}
});
Spinner spinner = (Spinner) findViewById(R.id.white_balance_spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
gstAhc.setWhiteBalanceMode (parent.getItemAtPosition(pos).toString());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
; // do nothing
}
});
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainActivity", "clicked button");
gstAhc.togglePlay();
}
});
gstAhc.setStateChangedListener(new GstAhc.StateChangedListener(){
@Override
public void stateChanged(GstAhc gstAhc, final GstAhc.State state) {
playButton = (ImageButton) findViewById(R.id.play_button);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (state != GstAhc.State.PLAYING) {
playButton.setImageResource(android.R.drawable.ic_media_play);
}
else {
playButton.setImageResource(android.R.drawable.ic_media_pause);
}
}
});
}
});
gstAhc.setErrorListener(new GstAhc.ErrorListener(){
@Override
public void error(GstAhc gstAhc, String errorMessage) {
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
});
surfaceView.getHolder().addCallback(gstAhc);
setOrientation (this.getWindowManager().getDefaultDisplay()
.getRotation());
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
@SuppressLint("InlinedApi")
private void show() {
// Show the system bar
surfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_resolution_320:
if (checked) {
gstAhc.changeResolutionTo(320, 240);
}
break;
case R.id.radio_resolution_640:
if (checked) {
gstAhc.changeResolutionTo(640, 480);
}
break;
}
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.autofocus:
gstAhc.setAutoFocus(checked);
break;
default:
break;
}
}
private void setOrientation (int rotation)
{
GstAhc.Rotate rotate = GstAhc.Rotate.NONE;
switch (rotation) {
case Surface.ROTATION_0: rotate = GstAhc.Rotate.COUNTERCLOCKWISE; break;
case Surface.ROTATION_90: rotate = GstAhc.Rotate.ROTATE_180; break;
case Surface.ROTATION_180: rotate = GstAhc.Rotate.NONE; break;
case Surface.ROTATION_270: rotate = GstAhc.Rotate.NONE; break;
}
gstAhc.setRotateMethod(rotate);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
Toast.makeText(this,"PORTRAIT",Toast.LENGTH_LONG).show();
}
else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Toast.makeText(this,"LANDSCAPE",Toast.LENGTH_LONG).show();
}
setOrientation (this.getWindowManager().getDefaultDisplay()
.getRotation());
}
}
|
package com.youthchina.domain.Qinghong;
import java.sql.Timestamp;
/**
* @program: youthchina
* @description: 专业信息表
* @author: Qinghong Wang
* @create: 2019-04-09 09:34
**/
public class Major {
private Integer major_num;
private Integer major_level;
private String major_code;
private String major_abbre;
private String major_chn;
private String major_eng;
private Timestamp start_date;
private Integer is_delete;
private Timestamp is_delete_time;
public Integer getMajor_num() {
return major_num;
}
public void setMajor_num(Integer major_num) {
this.major_num = major_num;
}
public Integer getMajor_level() {
return major_level;
}
public void setMajor_level(Integer major_level) {
this.major_level = major_level;
}
public String getMajor_code() {
return major_code;
}
public void setMajor_code(String major_code) {
this.major_code = major_code;
}
public String getMajor_abbre() {
return major_abbre;
}
public void setMajor_abbre(String major_abbre) {
this.major_abbre = major_abbre;
}
public String getMajor_chn() {
return major_chn;
}
public void setMajor_chn(String major_chn) {
this.major_chn = major_chn;
}
public String getMajor_eng() {
return major_eng;
}
public void setMajor_eng(String major_eng) {
this.major_eng = major_eng;
}
public Timestamp getStart_date() {
return start_date;
}
public void setStart_date(Timestamp start_date) {
this.start_date = start_date;
}
public Integer getIs_delete() {
return is_delete;
}
public void setIs_delete(Integer is_delete) {
this.is_delete = is_delete;
}
public Timestamp getIs_delete_time() {
return is_delete_time;
}
public void setIs_delete_time(Timestamp is_delete_time) {
this.is_delete_time = is_delete_time;
}
}
|
package com.aplicacion.guiaplayasgalicia.resultadoinfomareas;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.aplicacion.guiaplayasgalicia.R;
public class CalendarBaseAdapter extends BaseAdapter {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
private final Context context;
private final List<String> list;
private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private int daysInMonth;
private TextView gridcell;
private Date initDate;
private Date finalDate;
private int trailingSpaces = 0; // The number of days to leave blank at the start of this month.
private String dateClicked;
// Days in Current Month
public CalendarBaseAdapter(Context context, int textViewResourceId, Date initDate, Date finalDate, int month, int year, String dateClicked) {
this.context = context;
this.list = new ArrayList<String>();
this.initDate = initDate;
this.finalDate = finalDate;
this.dateClicked = dateClicked;
printMonth(month, year);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.gridcell, parent, false);
}
gridcell = (TextView) convertView.findViewById(R.id.gridCellId);
String[] dayColorArray = list.get(position).split("-"); // dd/mm/yyyy-color
gridcell.setText(dayColorArray[0].split("/")[0]);
// Set the date that will be in the tag of the view
String date = "";
String day = dayColorArray[0].split("/")[0];
String month = dayColorArray[0].split("/")[1];
String year = dayColorArray[0].split("/")[2];
if (dayColorArray[0].split("/")[0].length() == 1) { // The day should have two characters
day = "0" + day;
}
if (dayColorArray[0].split("/")[1].length() == 1) { // The month should have two characters
month = "0" + month;
}
date = day + "/" + month + "/" + year;
gridcell.setTag(date + "-" + dayColorArray[1]);
// Set the color (or NS -Not Shown-) of the date numbers shown in the calendar
if (dayColorArray[1].equals("NS")) {
gridcell.setTextColor(context.getResources().getColor(R.color.BackgroundActivityColor));
}
if (dayColorArray[1].equals("GREY")) {
gridcell.setTextColor(Color.LTGRAY);
}
if (dayColorArray[1].equals("BLACK")) {
gridcell.setTextColor(Color.BLACK);
}
// The date clicked should have red background
if (dateClicked.equals(date) && !dayColorArray[1].equals("NS")) {
gridcell.setBackgroundColor(Color.RED);
}
return convertView;
}
/**
* Method that prints the calendar
* @param monthNumber
* @param yy
*/
private void printMonth(int monthNumber, int yy) {
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;
int currentMonth = monthNumber - 1;
daysInMonth = daysOfMonth[currentMonth];
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
if (currentMonth == 11) {
prevMonth = currentMonth - 1;
daysInPrevMonth = daysOfMonth[prevMonth];
nextMonth = 0;
prevYear = yy;
nextYear = yy + 1;
}
else {
if (currentMonth == 0) {
prevMonth = 11;
prevYear = yy - 1;
nextYear = yy;
daysInPrevMonth = daysOfMonth[prevMonth];
nextMonth = 1;
}
else {
prevMonth = currentMonth - 1;
nextMonth = currentMonth + 1;
nextYear = yy;
prevYear = yy;
daysInPrevMonth = daysOfMonth[prevMonth];
}
}
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 2;
trailingSpaces = currentWeekDay;
if (cal.isLeapYear(cal.get(Calendar.YEAR))) {
if (monthNumber == 2) {
++daysInMonth;
}
else {
if (monthNumber == 3) {
++daysInPrevMonth;
}
}
}
// Trailing Month days (Days of the previous month that will not be shown)
for (int i = 0; i < trailingSpaces; i++) {
list.add(String.valueOf((daysInPrevMonth - trailingSpaces + 1) + i) + "/" + prevMonth + "/" + prevYear + "-NS");
}
// Current Month Days (Available dates)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
for (int i = 1; i <= daysInMonth; i++) {
String dateToPrintStr = String.valueOf(i) + "/" + monthNumber + "/" + yy;
Date dateToPrintDate = null;
try {
dateToPrintDate = simpleDateFormat.parse(dateToPrintStr);
}
catch (ParseException e) {
Log.e(this.getClass().toString(), "Error parsing string date (dd/MM/yyyy): " + dateToPrintStr);
}
if (dateToPrintDate != null && (dateToPrintDate.compareTo(this.initDate) >= 0) && dateToPrintDate.compareTo(this.finalDate) <= 0) {
list.add(String.valueOf(i) + "/" + monthNumber + "/" + yy + "-BLACK");
}
else {
list.add(String.valueOf(i) + "/" + monthNumber + "/" + yy + "-GREY");
}
}
// Leading Month days (Days of the next month that will not be shown)
for (int i = 0; i < list.size() % 7; i++) {
list.add(String.valueOf(i + 1) + "/" + nextMonth + "/" + nextYear + "-NS");
}
}
}
|
package com.dvg111.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The primary key class for the ss_event database table.
*
*/
@Embeddable
public class SsEventPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="DEVICE")
private String device;
@Column(name="_ID")
private long id;
public SsEventPK(long id, String device) {
super();
this.device = device;
this.id = id;
}
public SsEventPK() {
}
public String getDevice() {
return this.device;
}
public void setDevice(String device) {
this.device = device;
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SsEventPK)) {
return false;
}
SsEventPK castOther = (SsEventPK)other;
return
this.device.equals(castOther.device)
&& (this.id == castOther.id);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.device.hashCode();
hash = hash * prime + ((int) (this.id ^ (this.id >>> 32)));
return hash;
}
}
|
package com.sky.service;
import com.sky.Student;
public class StudentService {
public Student getStudentById() {
Student student = new Student();
student.setName("张龙");
return student;
}
}
|
package cn.bs.zjzc.model.bean;
/**
* Created by yiming on 2016/6/20.
*/
public class RegisterRequestBody {
public String token;
public String acount;
public String name;
public String passwd;
public String confirmPassword;
public String code;
public RegisterRequestBody(String token, String acount, String name, String passwd, String confirmPassword, String code) {
this.token = token;
this.acount = acount;
this.name = name;
this.passwd = passwd;
this.confirmPassword = confirmPassword;
this.code = code;
}
}
|
package com.example.logins;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.rilixtech.widget.countrycodepicker.CountryCodePicker;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class Regist extends AppCompatActivity {
EditText mFullName, mEmail, mPassword, mPhone, mOTPCode;
Button mRegisterBtn;
TextView mLoginBtn, mResendOtp;
FirebaseAuth fAuth;
FirebaseFirestore fstore;
ProgressBar progressBar;
CountryCodePicker countryCodePicker;
String verificationID;
PhoneAuthProvider.ForceResendingToken token;
Boolean verificationinprogress = false;
String userOTP, email, password, fullname, phoneNum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regist);
mFullName = findViewById(R.id.FullNameTxt);
mEmail = findViewById(R.id.EmailTxt);
mPassword = findViewById(R.id.PasswordTxt);
mPhone = findViewById(R.id.PhoneTxt);
mRegisterBtn = findViewById(R.id.RegisterBtn);
mLoginBtn = findViewById(R.id.LoginBtn);
mOTPCode = findViewById(R.id.OtpTxt);
mResendOtp = findViewById(R.id.ResendOtpBtn);
countryCodePicker = findViewById(R.id.ccp);
fAuth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
progressBar = findViewById(R.id.ProgressBar);
// if(fAuth.getCurrentUser() == null){
// startActivity(new Intent(getApplicationContext(), MainActivity.class));
// finish();
// }
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!verificationinprogress){
email = mEmail.getText().toString().trim();
password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
mEmail.setError("Email is required");
return;
}
if(TextUtils.isEmpty(password)){
mPassword.setError("Password is required");
return;
}
if(password.length() <= 6){
mPassword.setError("Password must be more than 6 characther");
return;
}
// progressBar.setVisibility(View.VISIBLE);
if(!mPhone.getText().toString().isEmpty()){
phoneNum = "+" + countryCodePicker.getSelectedCountryCode() + mPhone.getText().toString();
Log.d("tag", "Phone No -> " + phoneNum);
progressBar.setVisibility(View.VISIBLE);
requestOTP(phoneNum);
}else{
mPhone.setError("Phone number is not valid !");
}
}
else{
userOTP = mOTPCode.getText().toString();
if(!userOTP.isEmpty() && userOTP.length() == 6){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationID, userOTP);
verifyAuth(credential, email, password);
}else{
mOTPCode.setError("INVALID OTP");
}
}
}
});
}
// protected void onStart() {
// super.onStart();
//
// if (fAuth.getCurrentUser() != null){
// progressBar.setVisibility(View.VISIBLE);
// AutomateLogin();
// }
// else{
// startActivity(new Intent(getApplicationContext(), Logins.class));
// }
// }
private void AutomateLogin() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
private void verifyAuth(PhoneAuthCredential credential, String email, String password) {
fAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
LoginCredential();
}else{
Toast.makeText(Regist.this, "Invalid OTP Code", Toast.LENGTH_SHORT).show();
}
}
});
}
private void LoginCredential(){
fullname = mFullName.getText().toString().trim();
email = mEmail.getText().toString().trim();
password = mPassword.getText().toString().trim();
//Register user in firebase
fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Regist.this, "User Succesfully Created", Toast.LENGTH_SHORT).show();
DocumentReference docref = fstore.collection("users").document(fAuth.getCurrentUser().getUid());
Map<String, Object> user = new HashMap<>();
user.put("FullName", fullname);
user.put("Email", email);
user.put("PhoneNumber", phoneNum);
docref.set(user).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(Regist.this, "Data Registered", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Regist.this, "Data Didnt registered", Toast.LENGTH_SHORT).show();
}
}
});
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
else{
Toast.makeText(Regist.this, "Error is occured " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void requestOTP(String phoneNum) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNum,
60L,
TimeUnit.SECONDS,
this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationinprogress = true;
progressBar.setVisibility(View.GONE);
mOTPCode.setVisibility(View.VISIBLE);
verificationID = s;
token = forceResendingToken;
mRegisterBtn.setText("VERIFY");
}
@Override
public void onCodeAutoRetrievalTimeOut(@NonNull String s) {
super.onCodeAutoRetrievalTimeOut(s);
//mResendOtp.setVisibility(View.VISIBLE);
}
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(Regist.this, "Cannot Create Account, " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void RedirectLogin(View view){
startActivity(new Intent(getApplicationContext(), Logins.class));
}
}
|
package weather.model;
/**
* Une classe pour représenter le noeud "main" retourné par l'api openweather.
*
* @author Josselin Tobelem
*
*/
public class Meteo {
private double temp;
private int humidity;
// TODO 1. ajouter les autres attributs
// TODO 2. générer un constructeur "using fields" (fonctionnalité eclipse, source/generate...)
}
|
package implementations;
import interfaces.AbstractBinarySearchTree;
public class BinarySearchTree<E extends Comparable<E>> implements AbstractBinarySearchTree<E> {
private Node<E> root;
public BinarySearchTree() {
}
public BinarySearchTree(Node<E> root) {
this.root = root;
}
@Override
public void insert(E element) {
if (this.root == null) {
this.root = new Node<>(element);
} else {
insertNode(this.root, element);
}
}
@Override
public boolean contains(E element) {
return find(element) != null;
}
@Override
public AbstractBinarySearchTree<E> search(E element) {
Node<E> node = find(element);
return node == null ? null : new BinarySearchTree<>(node);
}
@Override
public Node<E> getRoot() {
return this.root;
}
@Override
public Node<E> getLeft() {
return getRoot().leftChild;
}
@Override
public Node<E> getRight() {
return getRoot().rightChild;
}
@Override
public E getValue() {
return getRoot().value;
}
private void insertNode(Node<E> root, E element) {
if(element.compareTo(root.value) > 0) {
if(root.rightChild == null) {
root.rightChild = new Node<>(element);
} else {
insertNode(root.rightChild, element);
}
} else if (element.compareTo(root.value) < 0) {
if(root.leftChild == null) {
root.leftChild = new Node<>(element);
} else {
insertNode(root.leftChild, element);
}
}
}
private Node<E> find(E element) {
Node<E> node = this.root;
while (node != null) {
int compare = element.compareTo(node.value);
if(compare == 0) {
return node;
}
if (compare > 0) {
node = node.rightChild;
} else {
node = node.leftChild;
}
}
return null;
}
}
|
package com.tencent.mm.plugin.scanner.util;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class e$10 implements OnClickListener {
final /* synthetic */ e mMX;
e$10(e eVar) {
this.mMX = eVar;
}
public final void onClick(DialogInterface dialogInterface, int i) {
if (this.mMX.mMU != null) {
this.mMX.mMU.o(1, 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.sia.mainInterface;
import com.sia.ui.transaksi.*;
//import com.sia.ui.aruskas.HelpProduk;
import com.sia.ui.pengaman.fLogin;
import javax.swing.JFrame;
/**
*
* @author ARCH
*/
public class Transaksi extends javax.swing.JFrame {
/**
* Creates new form MainFrame
*/
public Transaksi() {
initComponents();
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setAlwaysOnTop(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenuItem1 = new javax.swing.JMenuItem();
jMenuBar2 = new javax.swing.JMenuBar();
jMenu5 = new javax.swing.JMenu();
jMenu6 = new javax.swing.JMenu();
panelGlass1 = new usu.widget.glass.PanelGlass();
panelGlass5 = new usu.widget.glass.PanelGlass();
jDate = new javax.swing.JLabel();
jTgl = new javax.swing.JLabel();
panelGlass6 = new usu.widget.glass.PanelGlass();
jRp = new javax.swing.JLabel();
jBayar = new javax.swing.JLabel();
panelGlass7 = new usu.widget.glass.PanelGlass();
total = new javax.swing.JLabel();
namabarang = new javax.swing.JLabel();
hargabarang = new javax.swing.JLabel();
kode = new javax.swing.JTextField();
qty1 = new javax.swing.JTextField();
qty2 = new javax.swing.JTextField();
qty3 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable = new javax.swing.JTable();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
panelGlass3 = new usu.widget.glass.PanelGlass();
btnDel = new usu.widget.ButtonGlass();
btnAdd = new usu.widget.ButtonGlass();
btnPending = new usu.widget.ButtonGlass();
btnRefresh1 = new usu.widget.ButtonGlass();
btnReprint = new usu.widget.ButtonGlass();
panelGlass8 = new usu.widget.glass.PanelGlass();
namabarang1 = new javax.swing.JLabel();
hargabarang1 = new javax.swing.JLabel();
hargabarang2 = new javax.swing.JLabel();
hargabarang4 = new javax.swing.JLabel();
hargabarang5 = new javax.swing.JLabel();
hargabarang6 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
user = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jSeparator2 = new javax.swing.JPopupMenu.Separator();
produk = new javax.swing.JMenuItem();
exit = new javax.swing.JMenuItem();
jMenu7 = new javax.swing.JMenu();
BayarCash = new javax.swing.JMenuItem();
BayarKartu = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
Pembelian = new javax.swing.JMenu();
Pemebelian = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
saldo = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem1.setText("jMenuItem1");
jMenu5.setText("File");
jMenuBar2.add(jMenu5);
jMenu6.setText("Edit");
jMenuBar2.add(jMenu6);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
panelGlass1.setAlpha(1.0F);
panelGlass1.setBackground(new java.awt.Color(255, 255, 255));
panelGlass1.setMinimumSize(new java.awt.Dimension(0, 0));
panelGlass1.setPreferredSize(new java.awt.Dimension(1365, 745));
panelGlass1.setRound(false);
panelGlass1.setWarna(new java.awt.Color(102, 102, 102));
panelGlass1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
panelGlass5.setRound(false);
jDate.setFont(new java.awt.Font("Segoe UI Light", 0, 36)); // NOI18N
jDate.setForeground(new java.awt.Color(255, 255, 255));
jDate.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jDate.setText("23-07-2015");
jDate.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jTgl.setFont(new java.awt.Font("Segoe UI Light", 0, 36)); // NOI18N
jTgl.setForeground(new java.awt.Color(255, 255, 255));
jTgl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jTgl.setText("23:45");
jTgl.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout panelGlass5Layout = new javax.swing.GroupLayout(panelGlass5);
panelGlass5.setLayout(panelGlass5Layout);
panelGlass5Layout.setHorizontalGroup(
panelGlass5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jDate, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, Short.MAX_VALUE)
.addComponent(jTgl, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14))
);
panelGlass5Layout.setVerticalGroup(
panelGlass5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(panelGlass5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTgl, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jDate, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelGlass1.add(panelGlass5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 370, 60));
panelGlass6.setAlpha(0.08F);
panelGlass6.setBackground(new java.awt.Color(255, 255, 255));
panelGlass6.setOpaque(true);
jRp.setBackground(new java.awt.Color(51, 51, 51));
jRp.setFont(new java.awt.Font("Bauhaus 93", 0, 36)); // NOI18N
jRp.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jRp.setText("RP");
jBayar.setBackground(new java.awt.Color(51, 51, 51));
jBayar.setFont(new java.awt.Font("Arial", 1, 80)); // NOI18N
jBayar.setText("45,234,211,980");
javax.swing.GroupLayout panelGlass6Layout = new javax.swing.GroupLayout(panelGlass6);
panelGlass6.setLayout(panelGlass6Layout);
panelGlass6Layout.setHorizontalGroup(
panelGlass6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jRp, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jBayar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(25, 25, 25))
);
panelGlass6Layout.setVerticalGroup(
panelGlass6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass6Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(panelGlass6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jBayar)
.addComponent(jRp, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(23, Short.MAX_VALUE))
);
panelGlass1.add(panelGlass6, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 60, 670, 140));
panelGlass7.setRound(false);
total.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
total.setForeground(new java.awt.Color(51, 51, 51));
total.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
total.setText("HARGA TOTAL");
total.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
total.setOpaque(true);
namabarang.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
namabarang.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
namabarang.setText("NAMA BARANG");
namabarang.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
namabarang.setOpaque(true);
hargabarang.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
hargabarang.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hargabarang.setText("HARGA BARANG");
hargabarang.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
hargabarang.setOpaque(true);
kode.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
kode.setHorizontalAlignment(javax.swing.JTextField.CENTER);
kode.setText("NMA09828687276783");
kode.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
qty1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
qty1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
qty1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
qty1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
qty1ActionPerformed(evt);
}
});
qty2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
qty2.setHorizontalAlignment(javax.swing.JTextField.CENTER);
qty2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
qty2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
qty2ActionPerformed(evt);
}
});
qty3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
qty3.setHorizontalAlignment(javax.swing.JTextField.CENTER);
qty3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
qty3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
qty3ActionPerformed(evt);
}
});
javax.swing.GroupLayout panelGlass7Layout = new javax.swing.GroupLayout(panelGlass7);
panelGlass7.setLayout(panelGlass7Layout);
panelGlass7Layout.setHorizontalGroup(
panelGlass7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass7Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(kode, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(qty2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(qty3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(qty1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(namabarang, javax.swing.GroupLayout.PREFERRED_SIZE, 510, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(hargabarang, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(total, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
);
panelGlass7Layout.setVerticalGroup(
panelGlass7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(kode, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(qty2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(qty3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(qty1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(namabarang, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hargabarang, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(total, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
);
panelGlass1.add(panelGlass7, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 210, 1350, 30));
jTable.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null}
},
new String [] {
"Kode", "Qty", "Dis", "Ukuran", "Nama Barang", "Harga Barang", "Harga Total"
}
));
jTable.setSelectionForeground(new java.awt.Color(51, 153, 255));
jTable.setShowHorizontalLines(false);
jScrollPane1.setViewportView(jTable);
panelGlass1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 240, 1340, 400));
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Ukr");
panelGlass1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 190, -1, -1));
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("KODE");
panelGlass1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 190, -1, -1));
panelGlass3.setAlpha(0.0F);
panelGlass3.setRound(false);
btnDel.setForeground(new java.awt.Color(255, 255, 255));
btnDel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/doc_delete1.png"))); // NOI18N
btnDel.setText("Hapus");
btnDel.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N
btnDel.setPreferredSize(new java.awt.Dimension(117, 41));
btnDel.setRoundRect(true);
btnDel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDelActionPerformed(evt);
}
});
btnAdd.setForeground(new java.awt.Color(255, 255, 255));
btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/doc_new1.png"))); // NOI18N
btnAdd.setText("Tambah");
btnAdd.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N
btnAdd.setRoundRect(true);
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
btnPending.setForeground(new java.awt.Color(255, 255, 255));
btnPending.setText("Pending");
btnPending.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N
btnPending.setPreferredSize(new java.awt.Dimension(117, 41));
btnPending.setRoundRect(true);
btnPending.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPendingActionPerformed(evt);
}
});
btnRefresh1.setForeground(new java.awt.Color(255, 255, 255));
btnRefresh1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/doc_refresh1.png"))); // NOI18N
btnRefresh1.setText("Refresh");
btnRefresh1.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N
btnRefresh1.setPreferredSize(new java.awt.Dimension(117, 41));
btnRefresh1.setRoundRect(true);
btnRefresh1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefresh1ActionPerformed(evt);
}
});
btnReprint.setForeground(new java.awt.Color(255, 255, 255));
btnReprint.setText("RePrint");
btnReprint.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N
btnReprint.setPreferredSize(new java.awt.Dimension(117, 41));
btnReprint.setRoundRect(true);
btnReprint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnReprintActionPerformed(evt);
}
});
javax.swing.GroupLayout panelGlass3Layout = new javax.swing.GroupLayout(panelGlass3);
panelGlass3.setLayout(panelGlass3Layout);
panelGlass3Layout.setHorizontalGroup(
panelGlass3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelGlass3Layout.createSequentialGroup()
.addContainerGap(78, Short.MAX_VALUE)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnDel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(198, 198, 198)
.addGroup(panelGlass3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnPending, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnReprint, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(35, 35, 35))
.addGroup(panelGlass3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelGlass3Layout.createSequentialGroup()
.addContainerGap(354, Short.MAX_VALUE)
.addComponent(btnRefresh1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(169, 169, 169)))
);
panelGlass3Layout.setVerticalGroup(
panelGlass3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(panelGlass3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnDel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAdd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(panelGlass3Layout.createSequentialGroup()
.addComponent(btnPending, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnReprint, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(panelGlass3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnRefresh1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
panelGlass1.add(panelGlass3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, 640, -1));
panelGlass8.setRound(false);
namabarang1.setBackground(new java.awt.Color(153, 153, 153));
namabarang1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
namabarang1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
namabarang1.setText("F1 | Produk");
namabarang1.setOpaque(true);
hargabarang1.setBackground(new java.awt.Color(153, 153, 153));
hargabarang1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
hargabarang1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hargabarang1.setText("F2 | Bayar Cash");
hargabarang1.setOpaque(true);
hargabarang2.setBackground(new java.awt.Color(153, 153, 153));
hargabarang2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
hargabarang2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hargabarang2.setText("F3 | Bayar Kartu");
hargabarang2.setOpaque(true);
hargabarang4.setBackground(new java.awt.Color(153, 153, 153));
hargabarang4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
hargabarang4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hargabarang4.setText("F4 | Pembelian");
hargabarang4.setOpaque(true);
hargabarang5.setBackground(new java.awt.Color(153, 153, 153));
hargabarang5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
hargabarang5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hargabarang5.setText("F5 | Saldo Insidentil");
hargabarang5.setOpaque(true);
hargabarang6.setBackground(new java.awt.Color(153, 153, 153));
hargabarang6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
hargabarang6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
hargabarang6.setText("Esc | Keluar");
hargabarang6.setOpaque(true);
javax.swing.GroupLayout panelGlass8Layout = new javax.swing.GroupLayout(panelGlass8);
panelGlass8.setLayout(panelGlass8Layout);
panelGlass8Layout.setHorizontalGroup(
panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass8Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(namabarang1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hargabarang1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(hargabarang2, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(hargabarang4, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(hargabarang5, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(hargabarang6, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(521, Short.MAX_VALUE))
);
panelGlass8Layout.setVerticalGroup(
panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGlass8Layout.createSequentialGroup()
.addGroup(panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(namabarang1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hargabarang1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hargabarang2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hargabarang4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hargabarang5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(hargabarang6, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 20, Short.MAX_VALUE))
);
panelGlass1.add(panelGlass8, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 650, -1, 50));
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("QTY");
panelGlass1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 190, -1, -1));
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
panelGlass1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(770, 30, -1, -1));
jButton2.setText("jButton1");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
panelGlass1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 30, -1, -1));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("DIS");
panelGlass1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 190, -1, -1));
user.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
user.setForeground(new java.awt.Color(255, 255, 255));
user.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
panelGlass1.add(user, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 0, 140, 20));
jMenuBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jMenuBar1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jMenu1.setText("Help");
jMenu1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jMenu1MouseClicked(evt);
}
});
jMenu1.add(jSeparator2);
produk.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
produk.setText("Produk");
produk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
produkActionPerformed(evt);
}
});
jMenu1.add(produk);
exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
exit.setText("Exit");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
jMenu1.add(exit);
jMenuBar1.add(jMenu1);
jMenu7.setText("Bayar");
jMenu7.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
BayarCash.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
BayarCash.setText("Bayar Cash");
BayarCash.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BayarCashActionPerformed(evt);
}
});
jMenu7.add(BayarCash);
BayarKartu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0));
BayarKartu.setText("Bayar Kartu");
BayarKartu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BayarKartuActionPerformed(evt);
}
});
jMenu7.add(BayarKartu);
jMenu7.add(jSeparator1);
jMenuBar1.add(jMenu7);
Pembelian.setText("Pembelian");
Pembelian.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
Pemebelian.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0));
Pemebelian.setText("Pembelian");
Pemebelian.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PemebelianActionPerformed(evt);
}
});
Pembelian.add(Pemebelian);
jMenuBar1.add(Pembelian);
jMenu2.setText("Saldo Insidentil");
jMenu2.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
saldo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
saldo.setText("Saldo");
saldo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saldoActionPerformed(evt);
}
});
jMenu2.add(saldo);
jMenuBar1.add(jMenu2);
jMenu3.setText("Submit Transaksi");
jMenu3.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F6, 0));
jMenuItem2.setText("Submit Transaksi");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu3.add(jMenuItem2);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1365, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(panelGlass1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 745, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(panelGlass1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_jMenu1MouseClicked
private void BayarCashActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BayarCashActionPerformed
// TODO add your handling code here:
new Bayar().setVisible(true);
}//GEN-LAST:event_BayarCashActionPerformed
private void BayarKartuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BayarKartuActionPerformed
// TODO add your handling code here:
new BayarKartu().setVisible(true);
}//GEN-LAST:event_BayarKartuActionPerformed
private void produkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_produkActionPerformed
// TODO add your handling code here:
new HelpProduk().setVisible(true);
}//GEN-LAST:event_produkActionPerformed
private void qty1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_qty1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_qty1ActionPerformed
private void qty2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_qty2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_qty2ActionPerformed
private void qty3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_qty3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_qty3ActionPerformed
private void btnDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDelActionPerformed
// TODO add your handling code here:
// try{
// String id=String.valueOf(tblpengguna.getValueAt(tblpengguna.getSelectedRow(), 0));
// if(JOptionPane.showConfirmDialog(this, "Yakin menghapus data?", "Peringatan", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION){
// con.queryDelete("tb_pengguna", "NoAnggota="+id);
// clear();
// }else{
// return;
// }
// }catch(Exception e){
// System.out.println(e);
// }
// loadTable();
}//GEN-LAST:event_btnDelActionPerformed
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
// TODO add your handling code here:
// err_msg.setVisible(true);
// createPengguna();
}//GEN-LAST:event_btnAddActionPerformed
private void btnPendingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPendingActionPerformed
// TODO add your handling code here:
// loadTable();
// clear();
}//GEN-LAST:event_btnPendingActionPerformed
private void btnRefresh1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefresh1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnRefresh1ActionPerformed
private void btnReprintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReprintActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnReprintActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
this.dispose();
new Master().setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
this.dispose();
new Akuntansi().setVisible(true);
}//GEN-LAST:event_jButton2ActionPerformed
private void saldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saldoActionPerformed
// TODO add your handling code here:
new saldoInsedintil().setVisible(true);
}//GEN-LAST:event_saldoActionPerformed
private void PemebelianActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PemebelianActionPerformed
// TODO add your handling code here:
new Pembelian().setVisible(true);
}//GEN-LAST:event_PemebelianActionPerformed
private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
// TODO add your handling code here:
this.dispose();
fLogin login = new fLogin();
login.setVisible(true);
}//GEN-LAST:event_exitActionPerformed
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jMenuItem2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Transaksi().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem BayarCash;
private javax.swing.JMenuItem BayarKartu;
private javax.swing.JMenu Pembelian;
private javax.swing.JMenuItem Pemebelian;
private usu.widget.ButtonGlass btnAdd;
private usu.widget.ButtonGlass btnDel;
private usu.widget.ButtonGlass btnPending;
private usu.widget.ButtonGlass btnRefresh1;
private usu.widget.ButtonGlass btnReprint;
private javax.swing.JMenuItem exit;
private javax.swing.JLabel hargabarang;
private javax.swing.JLabel hargabarang1;
private javax.swing.JLabel hargabarang2;
private javax.swing.JLabel hargabarang4;
private javax.swing.JLabel hargabarang5;
private javax.swing.JLabel hargabarang6;
private javax.swing.JLabel jBayar;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jDate;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu5;
private javax.swing.JMenu jMenu6;
private javax.swing.JMenu jMenu7;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JLabel jRp;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator2;
private javax.swing.JTable jTable;
private javax.swing.JLabel jTgl;
private javax.swing.JTextField kode;
private javax.swing.JLabel namabarang;
private javax.swing.JLabel namabarang1;
private usu.widget.glass.PanelGlass panelGlass1;
private usu.widget.glass.PanelGlass panelGlass3;
private usu.widget.glass.PanelGlass panelGlass5;
private usu.widget.glass.PanelGlass panelGlass6;
private usu.widget.glass.PanelGlass panelGlass7;
private usu.widget.glass.PanelGlass panelGlass8;
private javax.swing.JMenuItem produk;
private javax.swing.JTextField qty1;
private javax.swing.JTextField qty2;
private javax.swing.JTextField qty3;
private javax.swing.JMenuItem saldo;
private javax.swing.JLabel total;
private javax.swing.JLabel user;
// End of variables declaration//GEN-END:variables
public void setUser(String USER, String id) {
//To change body of generated methods, choose Tools | Templates.
user.setText(USER);
String setIdUser=id;
}
}
|
package com.tamimattafi.mydebts.ui.fragments.drawer.main;
import java.lang.System;
@kotlin.Metadata(mv = {1, 1, 16}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u001a\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u000e\n\u0002\b\u0005\n\u0002\u0018\u0002\n\u0000\u0018\u00002\u00020\u0001B\u0005\u00a2\u0006\u0002\u0010\u0002J\b\u0010\t\u001a\u00020\nH\u0016R\u001a\u0010\u0003\u001a\u00020\u0004X\u0096\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b\u0005\u0010\u0006\"\u0004\b\u0007\u0010\b\u00a8\u0006\u000b"}, d2 = {"Lcom/tamimattafi/mydebts/ui/fragments/drawer/main/MainFragment;", "Lcom/tamimattafi/mydebts/ui/fragments/drawer/base/BaseFragment;", "()V", "name", "", "getName", "()Ljava/lang/String;", "setName", "(Ljava/lang/String;)V", "prepareAdapter", "Lcom/tamimattafi/mvp/MvpBaseContract$Adapter;", "app_debug"})
public final class MainFragment extends com.tamimattafi.mydebts.ui.fragments.drawer.base.BaseFragment {
@org.jetbrains.annotations.NotNull()
private java.lang.String name;
private java.util.HashMap _$_findViewCache;
@org.jetbrains.annotations.NotNull()
@java.lang.Override()
public java.lang.String getName() {
return null;
}
@java.lang.Override()
public void setName(@org.jetbrains.annotations.NotNull()
java.lang.String p0) {
}
@org.jetbrains.annotations.NotNull()
@java.lang.Override()
public com.tamimattafi.mvp.MvpBaseContract.Adapter prepareAdapter() {
return null;
}
public MainFragment() {
super(0);
}
}
|
package com.gmail.merikbest2015.ecommerce.controller;
import com.gmail.merikbest2015.ecommerce.domain.Order;
import com.gmail.merikbest2015.ecommerce.domain.User;
import com.gmail.merikbest2015.ecommerce.service.OrderService;
import com.gmail.merikbest2015.ecommerce.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
/**
* Customer order controller class.
* This controller and related pages can be accessed by all users, regardless of their roles.
* The @Controller annotation serves to inform Spring that this class is a bean and must be
* loaded when the application starts.
*
* @author Miroslav Khotinskiy (merikbest2015@gmail.com)
* @version 1.0
* @see Order
* @see User
* @see OrderService
* @see UserService
*/
@Controller
@Slf4j
public class OrderController {
/**
* Service object for working with customer.
*/
private final UserService userService;
/**
* Service object for working orders.
*/
private final OrderService orderService;
/**
* Constructor for initializing the main variables of the cart controller.
* The @Autowired annotation will allow Spring to automatically initialize objects.
*
* @param userService service object for working with customer.
* @param orderService service object for working orders.
*/
@Autowired
public OrderController(UserService userService, OrderService orderService) {
this.userService = userService;
this.orderService = orderService;
}
/**
* Returns the checkout page.
* URL request {"/order"}, method GET.
*
* @param userSession request Authenticated customer.
* @param model class object {@link Model}.
* @return order page with model attributes.
*/
@GetMapping("/order")
public String getOrder(@AuthenticationPrincipal User userSession, Model model) {
User userFromDB = userService.findByUsername(userSession.getUsername());
model.addAttribute("perfumes", userFromDB.getPerfumeList());
return "order/order";
}
/**
* Saves the customers order and redirect to "/finalizeOrder".
* URL request {"/order"}, method POST.
*
* @param userSession requested Authenticated customer.
* @param bindingResult errors in validating http request.
* @param model class object {@link Model}.
* @return order page with model attributes.
*/
@PostMapping("/order")
public String postOrder(
@AuthenticationPrincipal User userSession,
@Valid Order validOrder,
BindingResult bindingResult,
Model model
) {
User user = userService.findByUsername(userSession.getUsername());
Order order = new Order(user);
if (bindingResult.hasErrors()) {
Map<String, String> errorsMap = ControllerUtils.getErrors(bindingResult);
model.mergeAttributes(errorsMap);
model.addAttribute("perfumes", user.getPerfumeList());
return "order/order";
} else {
order.getPerfumeList().addAll(user.getPerfumeList());
order.setTotalPrice(validOrder.getTotalPrice());
order.setFirstName(validOrder.getFirstName());
order.setLastName(validOrder.getLastName());
order.setCity(validOrder.getCity());
order.setAddress(validOrder.getAddress());
order.setPostIndex(validOrder.getPostIndex());
order.setEmail(validOrder.getEmail());
order.setPhoneNumber(validOrder.getPhoneNumber());
user.getPerfumeList().clear();
orderService.save(order);
log.debug("User {} id={} made an order: FirstName={}, LastName={}, TotalPrice={}, City={}, " +
"Address={}, PostIndex={}, Email={}, PhoneNumber={}",
user.getUsername(), user.getId(), order.getFirstName(), order.getLastName(), order.getTotalPrice(),
order.getCity(), order.getAddress(), order.getPostIndex(), order.getEmail(), order.getPhoneNumber());
}
return "redirect:/finalizeOrder";
}
/**
* Returns the finalize order page with order index.
* URL request {"/finalizeOrder"}, method GET.
*
* @param model class object {@link Model}.
* @return finalizeOrder page with model attributes.
*/
@GetMapping("/finalizeOrder")
public String finalizeOrder(Model model) {
List<Order> orderList = orderService.findAll();
Order orderIndex = orderList.get(orderList.size() - 1);
model.addAttribute("orderIndex", orderIndex.getId());
return "order/finalizeOrder";
}
/**
* Returns all customers orders.
* URL request {"/userOrders"}, method GET.
*
* @param userSession requested Authenticated customer.
* @param model class object {@link Model}.
* @return orders page with model attributes.
*/
@GetMapping("/userOrders")
public String getUserOrdersList(@AuthenticationPrincipal User userSession, Model model) {
User userFromDB = userService.findByUsername(userSession.getUsername());
List<Order> orders = orderService.findOrderByUser(userFromDB);
model.addAttribute("orders", orders);
return "order/orders";
}
/**
* Returns all orders of all customers.
* URL request {"/orders"}, method GET.
*
* @param model class object {@link Model}.
* @return orders page with model attributes.
*/
@GetMapping("/orders")
public String getAllOrdersList(Model model) {
List<Order> orders = orderService.findAll();
model.addAttribute("orders", orders);
return "order/orders";
}
}
|
package com.zilker.taxi.ui;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.zilker.taxi.bean.CabModel;
import com.zilker.taxi.bean.CabModelDetail;
import com.zilker.taxi.constant.Constants;
import com.zilker.taxi.delegate.AdminDelegate;
import com.zilker.taxi.util.RegexUtility;
/*
* Admin UI.
*/
public class Admin {
private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
private final static Scanner SCANNER = new Scanner(System.in);
public void adminConsole(String userPhone) {
int choice = 0;
Admin admin = null;
do {
try {
admin = new Admin();
LOGGER.log(Level.INFO, Constants.ADMIN_MESSAGE);
LOGGER.log(Level.INFO, "Enter your choice: ");
choice = SCANNER.nextInt();
switch (choice) {
case 1:
admin.addCabModel(userPhone);
break;
case 2:
admin.displayCabs();
break;
case 3:
admin.updateCabModel(userPhone);
break;
case 4:
admin.deleteCabModel();
break;
case 5:
return;
default:
LOGGER.log(Level.WARNING, "Invalid choice. Enter a valid one.");
break;
}
} catch (InputMismatchException e) {
LOGGER.log(Level.WARNING, "Invalid input. Please enter a valid number.");
SCANNER.next();
}
} while (choice != 6);
}
/*
* Adds cab model details.
*/
public void addCabModel(String userPhone) {
String cabModelName = "";
String cabModelDescription = "";
String licencePlate = "";
int numSeats = -1;
boolean check = false;
CabModel cabModel = null;
AdminDelegate adminDelegate = null;
RegexUtility regexUtility = null;
String response = "";
try {
regexUtility = new RegexUtility();
cabModel = new CabModel();
adminDelegate = new AdminDelegate();
SCANNER.nextLine();
LOGGER.log(Level.INFO, "Enter the name of the model: ");
cabModelName = SCANNER.nextLine();
/*
* do {
*
*
* check = regexUtility.validateRegex(Constants.VALID_STRING_REGEX,
* licencePlate); if(check == true) { break; } else { LOGGER.log(Level.WARNING,
* "Invalid input. Enter a valid one."); }
*
* }while(check!=true);
*/
check = false;
do {
LOGGER.log(Level.INFO, "Enter the licence plate number: ");
licencePlate = SCANNER.next();
check = regexUtility.validateRegex(Constants.VALID_LICENCE_PLATE_REGEX, licencePlate);
if (check == true) {
break;
} else {
LOGGER.log(Level.WARNING, "Invalid licence plate number. Enter a valid one.");
}
} while (check != true);
check = false;
LOGGER.log(Level.INFO, "Enter the description of the model: ");
cabModelDescription = SCANNER.next();
do {
LOGGER.log(Level.INFO, "Enter the number of seats in the model: ");
numSeats = SCANNER.nextInt();
if (numSeats <= 0 || numSeats == 1) {
LOGGER.log(Level.INFO, "Invalid number of seats.");
} else {
check = true;
break;
}
} while (check != true);
cabModel = new CabModel(cabModelName, cabModelDescription, licencePlate, numSeats);
response = adminDelegate.addCabModel(cabModel, userPhone);
if (response.equals(Constants.SUCCESS)) {
LOGGER.log(Level.INFO, "Cab model successfully added.");
} else {
LOGGER.log(Level.WARNING, "Error in adding cab model details.");
}
} catch (InputMismatchException e) {
LOGGER.log(Level.WARNING, "Invalid input. Please enter a valid number.");
SCANNER.next();
} catch (Exception exception) {
LOGGER.log(Level.WARNING, "Error in passing cab model details to DAO.");
}
}
/*
* Updates cab model.
*/
public void updateCabModel(String userPhone) {
String licencePlate = "";
String modelName = "";
String modelDescription = "";
int numSeats;
boolean check = false;
int modelID = -1;
AdminDelegate adminDelegate = null;
RegexUtility regexUtility = null;
CabModel cabModel = null;
String response = "";
try {
adminDelegate = new AdminDelegate();
regexUtility = new RegexUtility();
do {
LOGGER.log(Level.INFO, "Enter the licence plate number: ");
licencePlate = SCANNER.next();
check = regexUtility.validateRegex(Constants.VALID_LICENCE_PLATE_REGEX, licencePlate);
if (check == true) {
break;
} else {
LOGGER.log(Level.WARNING, "Invalid licence plate number. Enter a valid one.");
}
} while (check != true);
check = false;
modelID = adminDelegate.getModelByLicencePlate(licencePlate);
if (modelID == (-1)) {
LOGGER.log(Level.WARNING, licencePlate + " doesn't exist.");
return;
}
SCANNER.nextLine();
LOGGER.log(Level.INFO, "Enter model name: ");
modelName = SCANNER.nextLine();
LOGGER.log(Level.INFO, "Enter model description: ");
modelDescription = SCANNER.nextLine();
LOGGER.log(Level.INFO, "Enter number of seats: ");
numSeats = SCANNER.nextInt();
cabModel = new CabModel(modelName, modelDescription, licencePlate, numSeats);
response = adminDelegate.updateCabModel(cabModel, userPhone, modelID);
if (response.equals(Constants.SUCCESS)) {
LOGGER.log(Level.INFO, "Cab model successfully updated.");
} else {
LOGGER.log(Level.WARNING, "Couldn't update model.");
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error in updating cab model.");
}
}
/*
* Removes cab model and makes it unavailable for ride.
*/
public void deleteCabModel() {
boolean check = false;
String licencePlate = "";
AdminDelegate adminDelegate = null;
RegexUtility regexUtility = null;
int modelID = -1;
String response = "";
try {
adminDelegate = new AdminDelegate();
regexUtility = new RegexUtility();
do {
LOGGER.log(Level.INFO, "Enter the licence plate number: ");
licencePlate = SCANNER.next();
check = regexUtility.validateRegex(Constants.VALID_LICENCE_PLATE_REGEX, licencePlate);
if (check == true) {
break;
} else {
LOGGER.log(Level.WARNING, "Invalid licence plate number. Enter a valid one.");
}
} while (check != true);
check = false;
modelID = adminDelegate.getModelByLicencePlate(licencePlate);
if (modelID == (-1)) {
LOGGER.log(Level.WARNING, licencePlate + " doesn't exist.");
return;
}
response = adminDelegate.deleteCabModel(modelID);
if (response.equals(Constants.SUCCESS)) {
LOGGER.log(Level.INFO, "Cab model deleted successfully.");
} else {
LOGGER.log(Level.WARNING, "Couldn't delete cab model.");
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error in deleting the account.");
}
}
/*
* Displays cab model details.
*/
public void displayCabs() {
AdminDelegate adminDelegate = null;
ArrayList<CabModelDetail> cabModel = null;
CabModelDetail object = null;
int size = -1;
int i = 0;
LOGGER.log(Level.WARNING, "List of cab model details.");
try {
adminDelegate = new AdminDelegate();
object = new CabModelDetail();
cabModel = adminDelegate.displayCabModelDetails();
size = cabModel.size();
for (i = 0; i < size; i++) {
object = cabModel.get(i);
LOGGER.log(Level.INFO, object.getLicencePlate() + " " + object.getModelName() + " "
+ object.getModelDescription() + " " + object.getNumSeats());
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Error displaying cab model details.");
}
}
}
|
package com.smxknife.springdatajpa.model.user;
/**
* @author smxknife
* 2020/11/19
*/
public class Team {
}
|
package io;
import org.junit.Before;
import org.junit.Test;
import testutilities.TestUtilities;
import util.MyArrayList;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.*;
public class MyImageIOTest {
private static final double DELTA = 1e-15;
private static MyImageIO imageIO;
@Before
public void before() throws IOException {
File outputfile = new File("./src/test/resources/rgb.png");
File outputfile2 = new File("./src/test/resources/rgb2.png");
int r = (255 << 24) | (255 << 16);
int g = (255 << 24) | (255 << 8);
int b = (255 << 24) | 255;
int a = (255 << 24) | (255 << 16) | (255 << 8) | 255;
int[] pixels = new int[]{r, r, r, r, r, r, g, g, g, g, g, g, b, b, b, b, b, b, a, a, a, a, a, a};
int width = 6;
int height = 4;
BufferedImage image = new BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
BufferedImage image2 = new BufferedImage(3, height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
// Copy correct pixels to the image
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, pixels[y * width + x]);
if (x <= 2)
image2.setRGB(x, y, pixels[y * width + x]);
}
if (x == 2)
ImageIO.write(image2, "png", outputfile2);
}
ImageIO.write(image, "png", outputfile);
imageIO = new MyImageIO("./src/test/resources/");
imageIO.loadImages(new String[]{"rgb.png"}, RGB.GREEN);
}
@Test
public void construct() {
try {
MyImageIO imageIO = new MyImageIO("./src/test/resources/");
assertTrue(imageIO != null);
assertEquals("./src/test/resources/", TestUtilities.getPrivateField("resourcesRoot", imageIO));
MyImageIO imageIO2 = new MyImageIO();
assertTrue(imageIO2 != null);
assertEquals(new File(".").getCanonicalPath() + "/src/main/resources/", TestUtilities.getPrivateField("resourcesRoot", imageIO2));
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void getWidth() {
assertTrue(imageIO != null);
assertEquals(6, imageIO.getWidth());
}
@Test
public void getHeight() {
assertTrue(imageIO != null);
assertEquals(4, imageIO.getHeight());
}
@Test
public void getPixels() {
assertTrue(imageIO.getPixels() instanceof MyArrayList);
assertTrue(imageIO.getPixels().get(0) instanceof int[][]);
MyArrayList<int[][]> pixels = imageIO.getPixels();
assertEquals(1, pixels.getSize());
assertEquals(6, ((int[][]) pixels.get(0)).length);
assertEquals(4, ((int[][]) pixels.get(0))[0].length);
int r = (255 << 24) | (255 << 16);
int g = (255 << 24) | (255 << 8);
int b = (255 << 24) | 255;
int a = (255 << 24) | (255 << 16) | (255 << 8) | 255;
assertArrayEquals(new int[][]{{r, g, b, a}, {r, g, b, a}, {r, g, b, a}, {r, g, b, a}, {r, g, b, a}, {r, g, b, a}}, (int[][]) pixels.get(0));
}
@Test
public void getGreens() {
assertTrue(imageIO.getChannels() instanceof MyArrayList);
assertTrue(imageIO.getChannels().get(0) instanceof double[][]);
MyArrayList<double[][]> greens = imageIO.getChannels();
assertEquals(1, greens.getSize());
assertEquals(6, ((double[][]) greens.get(0)).length);
assertEquals(4, ((double[][]) greens.get(0))[0].length);
assertArrayEquals(new double[][]{{0, 255, 0, 255}, {0, 255, 0, 255}, {0, 255, 0, 255}, {0, 255, 0, 255}, {0, 255, 0, 255}, {0, 255, 0, 255}}, (double[][]) greens.get(0));
}
@Test
public void loadImages() throws IOException {
String path = new File(".").getCanonicalPath() + "/src/test/resources/";
MyImageIO imageIO = new MyImageIO(path);
imageIO.loadImages(new String[]{"rgb.png", "rgb.png"}, RGB.GREEN);
assertEquals(2, imageIO.getChannels().getSize());
}
@Test(expected = IllegalArgumentException.class)
public void loadImages_NotSameSizeImages() throws IllegalArgumentException, IOException {
String path = new File(".").getCanonicalPath() + "/src/test/resources/";
MyImageIO imageIO = new MyImageIO(path);
imageIO.loadImages(new String[]{"rgb.png", "rgb2.png"}, RGB.GREEN);
}
@Test(expected = IllegalArgumentException.class)
public void loadImages_NoFiles() throws IllegalArgumentException, IOException {
MyImageIO imageIO = new MyImageIO();
imageIO.loadImages(null, RGB.GREEN);
}
@Test
public void saveImage() throws IOException {
int r = (255 << 24) | (255 << 16);
int g = (255 << 24) | (255 << 8);
int b = (255 << 24) | 255;
int a = (255 << 24) | (255 << 16) | (255 << 8) | 255;
int[] pixels = new int[]{r, r, r, r, r, r, g, g, g, g, g, g, b, b, b, b, b, b, a, a, a, a, a, a};
String path = new File(".").getCanonicalPath() + "/src/test/resources/";
MyImageIO imageIO = new MyImageIO(path);
MyImageIO.saveImage(pixels, 6, 4, "../../test/resources/rgb.png");
assertTrue((new File("./src/test/resources/", "rgb.png")).exists());
}
@Test
public void getDefaultResourceRoot() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
MyImageIO imageIO = new MyImageIO();
Object value = TestUtilities.callPrivateMethod(MyImageIO.class, new Class[] { String.class }, "getDefaultResourceRoot", imageIO, new Object[] {"\u0000"});
assertEquals("./src/main/resources/", value);
}
}
|
/*
* Copyright 2016-2018 www.jeesuite.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.vakin.algorithm;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @description <br>
* @author <a href="mailto:vakinge@gmail.com">vakin</a>
* @date 2018年11月27日
*/
public class ShortMd5 {
private static final char[] saltChars = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
.toCharArray());
public static String md5Short(String orig){
if(orig == null){
return null ;
}
//先得到url的32个字符的md5码
String md5 = md5(orig) ;
//将32个字符的md5码分成4段处理,每段8个字符
//4段任意一段加密都可以,这里我们取第二段
int offset = 1 * 8 ;
String sub = md5.substring(offset, offset + 8) ;
long sub16 = Long.parseLong(sub , 16) ; //将sub当作一个16进制的数,转成long
// & 0X3FFFFFFF,去掉最前面的2位,只留下30位
sub16 &= 0X3FFFFFFF ;
StringBuilder sb = new StringBuilder() ;
//将剩下的30位分6段处理,每段5位
for (int j = 0; j < 6 ; j++) {
//得到一个 <= 61的数字
long t = sub16 & 0x0000003D ;
sb.append(saltChars[(int) t]) ;
sub16 >>= 5 ; //将sub16右移5位
}
return sb.toString() ;
}
public static String md5(Object content) {
String keys = null;
if (content == null) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bPass = String.valueOf(content).getBytes("UTF-8");
md.update(bPass);
keys = bytesToHexString(md.digest());
} catch (NoSuchAlgorithmException aex) {
System.out.println(aex);
} catch (java.io.UnsupportedEncodingException uex) {
System.out.println(uex);
}
return keys.toLowerCase();
}
private static String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(md5Short("123456"));
}
}
|
package pattern_test.factory_method;
/**
* Description:
*
* @author Baltan
* @date 2019-04-02 11:03
*/
public class Test1 {
public static void main(String[] args) {
ForeverFactory foreverFactory = new ForeverFactory();
Bicycle forever = foreverFactory.createBicycle();
System.out.println(forever.getPrice());
GiantFactory giantFactory = new GiantFactory();
Bicycle giant = giantFactory.createBicycle();
System.out.println(giant.getPrice());
MeridaFactory meridaFactory = new MeridaFactory();
Bicycle merida = meridaFactory.createBicycle();
System.out.println(merida.getPrice());
}
}
|
/*
* 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 resourcemanagementapp.tags;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextField;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import resourcemanagementapp.database.DBConnection;
/**
* FXML Controller class
*
* @author thilr_88qp6ap
*/
public class AddTagController implements Initializable {
@FXML
private AnchorPane addtagpane;
@FXML
private JFXTextField txtTagName;
@FXML
private JFXTextField txtTagCode;
@FXML
private JFXComboBox comboRelatedTag;
@FXML
private Label errLbl;
// DB Connection
Connection connection = DBConnection.DBConnector();
PreparedStatement pst = null;
ResultSet rs = null;
/**
* Initializes the controller class.
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// Radio button
relatedTagRadioBtn();
}
// Related tag combo box
public void relatedTagRadioBtn() {
comboRelatedTag.getItems().clear();
comboRelatedTag.getItems().addAll("Lecture", "Tutorial", "Practical");
}
// Load Auto Increment ID
int AID;
public int autoIncrementID() throws SQLException {
String query = "SELECT id FROM tag ORDER BY id DESC LIMIT 1";
pst = (PreparedStatement) connection.prepareStatement(query);
rs = pst.executeQuery();
if(rs.next()) {
AID = rs.getInt("id");
AID = AID + 1;
} else {
AID = 1;
}
System.out.println("Auto Increment ID : " + AID);
rs.close();
pst.close();
return AID;
}
// Validation
public boolean Validation() {
if("".equals(txtTagName.getText())) {
errLbl.setText("* Please, fill the Tag Name");
return true;
}
if("".equals(txtTagCode.getText())) {
errLbl.setText("* Please, fill the Tag Code");
return true;
}
if(comboRelatedTag.getValue() == null) {
errLbl.setText("* Please, choose the Rlated Tag");
return true;
}
return false;
}
@FXML
private void backBtnPressed() throws IOException {
// when user clicked Add Lecturer button
this.addtagpane.getScene().getWindow().hide();
Parent root = null;
root = FXMLLoader.load(getClass().getResource("ManageTags.fxml"));
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setTitle("Manage Tags - Resouce Management Application");
stage.show();
}
@FXML
private void clearBtnPressed() {
txtTagName.setText("");
txtTagCode.setText("");
comboRelatedTag.setValue(null);
errLbl.setText("");
}
@FXML
private void saveBtnPressed() throws SQLException {
if(Validation() == true) {
System.out.println("== Statement FALSE ==");
} else {
autoIncrementID();
errLbl.setText("");
// Add data to DB
String tagName = txtTagName.getText();
String tagCode = txtTagCode.getText();
String relatedTag = comboRelatedTag.getValue().toString();
String query = "INSERT INTO tag (id, tag_name, tag_code, related_tag) VALUES (?,?,?,?)";
pst = null;
try {
pst = connection.prepareStatement(query);
pst.setInt(1, AID);
pst.setString(2, tagName);
pst.setString(3, tagCode);
pst.setString(4, relatedTag);
int connectStatus = pst.executeUpdate();
pst.close();
if(connectStatus == 1) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
// Get the Stage.
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
// Add a custom icon.
alert.setTitle("Add Tag");
alert.setHeaderText("Successfully Inserted.");
alert.setContentText("Tag Add Successfully");
alert.showAndWait().ifPresent(rs -> {
if (rs == ButtonType.OK)
{
System.out.println("Pressed OK.");
clearBtnPressed();
}
});
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
// Get the Stage.
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
// Add a custom icon.
alert.setTitle("Add Tag Error");
alert.setHeaderText("Sorry, we can not add Tag at this momoment.");
alert.setContentText("Please Try Again Later");
alert.showAndWait().ifPresent(rs -> {
if (rs == ButtonType.OK)
{
System.out.println("Pressed OK.");
}
});
}
} catch(SQLException e) {
System.out.println(e);
}
finally {
pst.close();
}
}
}
}
|
package Networking.HighLevelAPIS.URLConnections;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://example.org");
URI uri = url.toURI();
/*
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(url.openStream())
);
String line = "";
while (line != null) {
line = inputStream.readLine();
System.out.println(line);
}
inputStream.close();
*/
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
BufferedReader inputStream = new BufferedReader(new InputStreamReader(in));
Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
// List<String> headers = headerFields.values().stream()
// .collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);
//
//
// headers.forEach(System.out::println);
headerFields.forEach((s, strings) -> {
System.out.println("-----Key: " + s);
strings.forEach(s1 -> {
System.out.println("\t\tValue: " + s1);
});
});
inputStream.close();
} catch (URISyntaxException | MalformedURLException e) {
if (e.getClass().equals(MalformedURLException.class)) {
System.out.println("Malformed url exception: " + e.getMessage());
} else {
System.out.println("URI Syntax exception: " + e.getMessage());
}
} catch (IOException e) {
System.out.println("IO exception: " + e.getMessage());
}
}
}
|
public class FundoRendaFixaLongoPrazo extends FundoRendaFixa{
public double getTaxaIR(Saldo saldo) {
int quantidadeDias = saldo.getQuantidadeDiasAplicacao();
if (quantidadeDias > 720) {
return 0.15;
} else if (quantidadeDias >= 361 && quantidadeDias <= 720) {
return 0.175;
} else if (quantidadeDias >= 181 && quantidadeDias <= 360) {
return 0.20;
} else {
return 0.225;
}
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.content.Intent;
import android.widget.Toast;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.kernel.a;
import com.tencent.mm.kernel.g;
import com.tencent.mm.modelsimple.q;
import com.tencent.mm.plugin.account.a.j;
import com.tencent.mm.plugin.account.ui.MobileVerifyUI.b;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.applet.SecurityImage;
import com.tencent.mm.ui.base.h;
import com.tencent.tmassistantsdk.common.TMAssistantDownloadSDKErrorCode;
public final class m implements e, b {
SecurityImage eIX = null;
f eQY = null;
private g eSA = null;
MobileVerifyUI eTG;
private int eTb;
public m(int i) {
this.eTb = i;
x.i("MicroMsg.MobileVerifyForgetPwdLogic", "forget pwd, purpose %d", new Object[]{Integer.valueOf(i)});
}
public final void a(MobileVerifyUI mobileVerifyUI) {
this.eTG = mobileVerifyUI;
}
public final void start() {
StringBuilder stringBuilder = new StringBuilder();
g.Eg();
stringBuilder = stringBuilder.append(a.DA()).append(",").append(getClass().getName()).append(",F200_300,");
g.Eg();
com.tencent.mm.plugin.c.a.d(true, stringBuilder.append(a.gd("F200_300")).append(",1").toString());
com.tencent.mm.plugin.c.a.pT("F200_300");
}
public final void stop() {
int i = 2;
if (this.eTG.eUl != -1) {
i = this.eTG.eUl;
}
StringBuilder stringBuilder = new StringBuilder();
g.Eg();
stringBuilder = stringBuilder.append(a.DA()).append(",").append(getClass().getName()).append(",F200_300,");
g.Eg();
com.tencent.mm.plugin.c.a.d(false, stringBuilder.append(a.gd("F200_300")).append(",").append(i).toString());
}
public final boolean jn(int i) {
switch (5.eTK[i - 1]) {
case 1:
YM();
break;
case 2:
StringBuilder stringBuilder = new StringBuilder();
g.Eg();
stringBuilder = stringBuilder.append(a.DA()).append(",").append(getClass().getName()).append(",R200_400,");
g.Eg();
com.tencent.mm.plugin.c.a.pV(stringBuilder.append(a.gd("R200_400")).append(",1").toString());
l lVar = null;
if (this.eTb == 3) {
lVar = new com.tencent.mm.modelfriend.a(this.eTG.bTi, 8, "", 0, "");
} else if (this.eTb == 5) {
lVar = new com.tencent.mm.plugin.account.friend.a.x(this.eTG.bTi, 20, "", 0, "");
}
if (lVar != null) {
g.DF().a(lVar, 0);
break;
}
break;
case 3:
YM();
break;
}
return false;
}
private void YM() {
StringBuilder stringBuilder = new StringBuilder();
g.Eg();
stringBuilder = stringBuilder.append(a.DA()).append(",").append(getClass().getName()).append(",R200_350_auto,");
g.Eg();
com.tencent.mm.plugin.c.a.pV(stringBuilder.append(a.gd("R200_350_auto")).append(",1").toString());
g.DF().a(145, this);
g.DF().a(132, this);
l lVar = null;
if (this.eTb == 3) {
lVar = new com.tencent.mm.modelfriend.a(this.eTG.bTi, 9, this.eTG.eGC.getText().toString().trim(), 0, "");
} else if (this.eTb == 5) {
lVar = new com.tencent.mm.plugin.account.friend.a.x(this.eTG.bTi, 21, this.eTG.eGC.getText().toString().trim(), 0, "");
}
if (lVar != null) {
g.DF().a(lVar, 0);
MobileVerifyUI mobileVerifyUI = this.eTG;
MobileVerifyUI mobileVerifyUI2 = this.eTG;
this.eTG.getString(j.app_tip);
mobileVerifyUI.eHw = h.a(mobileVerifyUI2, this.eTG.getString(j.bind_mcontact_verifing), true, new 1(this, lVar));
}
}
public final void a(int i, int i2, String str, l lVar) {
x.i("MicroMsg.MobileVerifyForgetPwdLogic", "onSceneEnd: errType = " + i + " errCode = " + i2 + " errMsg = " + str);
if (this.eTG.eHw != null) {
this.eTG.eHw.dismiss();
this.eTG.eHw = null;
}
if (this.eQY == null) {
this.eQY = new f();
}
if (lVar.getType() != TMAssistantDownloadSDKErrorCode.DownloadSDKErrorCode_RESPONSE_IS_NULL || this.eSA == null) {
com.tencent.mm.h.a eV;
if (lVar.getType() == 145) {
this.eQY.account = ((com.tencent.mm.modelfriend.a) lVar).getUsername();
this.eQY.eRP = ((com.tencent.mm.modelfriend.a) lVar).Oi();
g.DF().b(145, this);
if (i == 0 && i2 == 0) {
if (this.eTb == 3) {
g.DF().a(TMAssistantDownloadSDKErrorCode.DownloadSDKErrorCode_RESPONSE_IS_NULL, this);
this.eSA = new g(new 4(this), ((com.tencent.mm.modelfriend.a) lVar).getUsername(), ((com.tencent.mm.modelfriend.a) lVar).Oi(), this.eTG.bTi);
this.eSA.a(this.eTG);
return;
}
return;
} else if (i2 == -51) {
eV = com.tencent.mm.h.a.eV(str);
if (eV != null) {
eV.a(this.eTG, null, null);
return;
} else {
h.i(this.eTG, j.bind_mcontact_verify_err_time_out_content, j.bind_mcontact_verify_tip);
return;
}
}
}
if (lVar.getType() == 132) {
g.DF().b(132, this);
if (i == 0 && i2 == 0) {
if (this.eTb == 5) {
String Oj = ((com.tencent.mm.plugin.account.friend.a.x) lVar).Oj();
Intent intent = new Intent();
intent.putExtra("setpwd_ticket", Oj);
this.eTG.setResult(-1, intent);
this.eTG.finish();
return;
}
return;
} else if (i2 == -51) {
eV = com.tencent.mm.h.a.eV(str);
if (eV != null) {
eV.a(this.eTG, null, null);
return;
} else {
h.i(this.eTG, j.bind_mcontact_verify_err_time_out_content, j.bind_mcontact_verify_tip);
return;
}
}
}
if (!this.eTG.e(i, i2, str)) {
if (lVar.getType() == TMAssistantDownloadSDKErrorCode.DownloadSDKErrorCode_RESPONSE_IS_NULL) {
eV = com.tencent.mm.h.a.eV(str);
if (eV != null && eV.a(this.eTG, null, null)) {
return;
}
}
if (i != 0 || i2 != 0) {
Toast.makeText(this.eTG, this.eTG.getString(j.bind_mcontact_verify_err, new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}), 0).show();
return;
}
return;
}
return;
}
g.DF().b(TMAssistantDownloadSDKErrorCode.DownloadSDKErrorCode_RESPONSE_IS_NULL, this);
this.eQY.eJa = ((q) lVar).Re();
this.eQY.eIZ = ((q) lVar).Rf();
this.eQY.eJb = ((q) lVar).Rg();
this.eQY.eRQ = ((q) lVar).getSecCodeType();
if (i2 == -6 || i2 == -311 || i2 == -310) {
g.DF().a(TMAssistantDownloadSDKErrorCode.DownloadSDKErrorCode_RESPONSE_IS_NULL, this);
if (this.eIX == null) {
this.eIX = SecurityImage.a.a(this.eTG, j.regbyqq_secimg_title, this.eQY.eRQ, this.eQY.eIZ, this.eQY.eJa, this.eQY.eJb, new 2(this), null, new 3(this), this.eQY);
return;
}
x.d("MicroMsg.MobileVerifyForgetPwdLogic", "imgSid:" + this.eQY.eJa + " img len" + this.eQY.eIZ.length + " " + com.tencent.mm.compatible.util.g.Ac());
this.eIX.a(this.eQY.eRQ, this.eQY.eIZ, this.eQY.eJa, this.eQY.eJb);
return;
}
this.eSA.a(this.eTG, i, i2, str, lVar);
if (i == 0 && i2 == 0) {
boolean Rm;
if (lVar instanceof q) {
Rm = ((q) lVar).Rm();
} else {
Rm = true;
}
this.eTG.co(Rm);
}
}
}
|
package server;
/**
* Created by Portatile on 18/05/2017.
*/
public abstract class AbstractServer {
private final Server server;
/**
* Costruttore astratto del server (socket o rmi)
* @param server
*/
public AbstractServer(Server server)
{
this.server = server;
}
public server.Server getServer() {
return server;
}
public abstract void StartServer(int porta) throws Exception;
}
|
package DAL.Polish;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import DAL.DAL_Generic;
import basicas.polish.Polish;
public class DAL_Polish extends DAL_Generic<Polish> {
public DAL_Polish(EntityManager em) {
super(em);
}
@SuppressWarnings("unchecked")
public List<Polish> listAll() {
List<Polish> retorno = null;
try {
Query q = getEntityManager().createNamedQuery("Polish.findAll");
retorno = q.getResultList();
} catch (PersistenceException e) {
System.out.println(e.getMessage());
}
return retorno;
}
public Polish findByName(String name) {
Polish retorno = null;
try {
Query q = getEntityManager().createNamedQuery("Polish.findByName");
q.setParameter("name", name);
retorno = (Polish) q.getSingleResult();
} catch (PersistenceException e) {
System.out.println(e.getMessage());
}
return retorno;
}
@SuppressWarnings("unchecked")
public List<Polish> findByFilters(Polish p){
List<Polish> retorno = null;
String name = "", color = "", brand = "", finish = "";
if (p.getName() != null) {
name = p.getName();
}if (p.getColor() != null) {
color = p.getColor();
}if (p.getBrand() != null) {
if (p.getBrand().getName() != null) {
brand = p.getBrand().getName();
}
}if (p.getFinish() != null) {
if (p.getFinish().getName() != null) {
finish = p.getFinish().getName();
}
}
try {
String query = "select p from Polish p where p.name like :name and p.color like :color and p.brand.name like :brand and p.finish.name like :finish";
Query q = getEntityManager().createQuery(query, Polish.class);
q.setParameter("name", "%" + name + "%");
q.setParameter("color", "%"+ color +"%");
q.setParameter("brand", "%"+ brand +"%");
q.setParameter("finish", "%"+ finish +"%");
retorno = q.getResultList();
} catch (PersistenceException e) {
System.out.println(e.getMessage());
}
return retorno;
}
}
|
import java.awt.*;
import javax.swing.*;
//import javax.swing.border.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.lang.NumberFormatException;
import java.lang.NullPointerException;
public class ClientJPanel extends Painel implements ActionListener {
protected JButton bSaque, bDeposito, bInfo, bSenha, bLogout;
protected JLabel bemVindo;
public ClientJPanel() {
if (Banco.testInstance()) { bemVindo = new JLabel("Bem vindo(a) Sr(a). " + b.client_getNome()); } else { bemVindo = new JLabel("---"); }
bemVindo.setAlignmentX(JComponent.CENTER_ALIGNMENT);
JPanel container = new JPanel();
container.setLayout(new GridLayout(0, 1)); //Infinitas linhas, uma coluna
JPanel buttons = new JPanel(new GridLayout(5, 1, 0, 10)); //5 linhas, uma coluna, espacamento 0x10
buttons.setOpaque(true);
bSaque = new JButton("Realizar Saque");
bSaque.setActionCommand("sacar");
bSaque.setMnemonic(KeyEvent.VK_S);
bSaque.addActionListener(this);
bSaque.setAlignmentX(JComponent.CENTER_ALIGNMENT);
bDeposito = new JButton("Realizar Deposito");
bDeposito.setActionCommand("depositar");
bDeposito.setMnemonic(KeyEvent.VK_D);
bDeposito.addActionListener(this);
bDeposito.setAlignmentX(JComponent.CENTER_ALIGNMENT);
bInfo = new JButton("Visualizar Informacoes");
bInfo.setActionCommand("info");
bInfo.setMnemonic(KeyEvent.VK_I);
bInfo.addActionListener(this);
bInfo.setAlignmentX(JComponent.CENTER_ALIGNMENT);
bSenha = new JButton("Alterar Senha");
bSenha.setActionCommand("senha");
bSenha.setMnemonic(KeyEvent.VK_A);
bSenha.addActionListener(this);
bSenha.setAlignmentX(JComponent.CENTER_ALIGNMENT);
bLogout = new JButton("Desconectar");
bLogout.setActionCommand("logout");
bLogout.setMnemonic(KeyEvent.VK_D);
bLogout.addActionListener(this);
bLogout.setAlignmentX(JComponent.CENTER_ALIGNMENT);
container.add(bemVindo);
buttons.add(bSaque);
buttons.add(bDeposito);
buttons.add(bInfo);
buttons.add(bSenha);
buttons.add(bLogout);
container.add(buttons);
add(container);
}
public void actionPerformed(ActionEvent e) {
b = Banco.getInstance();
if ("sacar".equals(e.getActionCommand())) {
String input = JOptionPane.showInputDialog("Digite o valor para saque", "0.00");
double val;
try {
val = Double.parseDouble(input);
b.client_sacar(val);
JOptionPane.showMessageDialog(null, "Saque realizado com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
} catch ( NumberFormatException ne ) {
JOptionPane.showMessageDialog(null, "Favor digitar um numero!", "Erro", JOptionPane.ERROR_MESSAGE);
} catch (SaldoInvalidoException se) {
JOptionPane.showMessageDialog(null, se.to_string(), "Erro", JOptionPane.ERROR_MESSAGE);
} catch (ValorInvalidoException ve) {
JOptionPane.showMessageDialog(null, ve.to_string(), "Erro", JOptionPane.WARNING_MESSAGE);
} catch (NoActiveSessionException ns) {
JOptionPane.showMessageDialog(null, ns.to_string(), "Erro", JOptionPane.ERROR_MESSAGE);
b.reconfigContentPane(Banco.MAIN);
} catch ( NullPointerException npe ) { }
} else if ("depositar".equals(e.getActionCommand())) {
String input = JOptionPane.showInputDialog("Digite o valor para deposito", "0.00");
double val;
try {
val = Double.parseDouble(input);
b.client_depositar(val);
JOptionPane.showMessageDialog(null, "Deposito realizado com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
} catch ( NumberFormatException ne ) {
JOptionPane.showMessageDialog(null, "Favor digitar um numero!", "Erro", JOptionPane.ERROR_MESSAGE);
} catch (ValorInvalidoException ve) {
JOptionPane.showMessageDialog(null, ve.to_string(), "Erro", JOptionPane.WARNING_MESSAGE);
} catch (NoActiveSessionException ns) {
JOptionPane.showMessageDialog(null, ns.to_string(), "Erro", JOptionPane.ERROR_MESSAGE);
b.reconfigContentPane(Banco.MAIN);
} catch ( NullPointerException npe ) { }
} else if ("info".equals(e.getActionCommand())) {
try {
JOptionPane.showMessageDialog(null, b.client_to_string(), "Informacoes", JOptionPane.INFORMATION_MESSAGE);
} catch (NoActiveSessionException ns) {
JOptionPane.showMessageDialog(null, ns.to_string(), "Erro", JOptionPane.ERROR_MESSAGE);
b.reconfigContentPane(Banco.MAIN);
}
} else if ("senha".equals(e.getActionCommand())) {
String senhaAntiga = JOptionPane.showInputDialog("Digite a senha antiga", "senha antiga");
try {
if (b.client_comparaSenha(senhaAntiga)) {
String senhaNova = JOptionPane.showInputDialog("Digite a nova senha", "senha nova");
b.client_alterarSenha(senhaAntiga, senhaNova);
JOptionPane.showMessageDialog(null, "Senha atualizada com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Senha atual diferente!", "Erro", JOptionPane.ERROR_MESSAGE);
}
} catch (NoActiveSessionException ns) {
JOptionPane.showMessageDialog(null, ns.to_string(), "Erro", JOptionPane.ERROR_MESSAGE);
b.reconfigContentPane(Banco.MAIN);
} catch (NullPointerException npe) { }
} else if ("logout".equals(e.getActionCommand())) {
b.client_logOut();
b.reconfigContentPane(Banco.MAIN);
}
}
public void on_update() {
b = Banco.getInstance();
bemVindo.setText("Bem vindo(a) Sr(a). " + b.client_getNome());
}
}
|
package groupon.edanpossey.groupon1.Client.DataAccessLayer;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import groupon.edanpossey.groupon1.Entities.AccessLevel;
/**
* Created by IlayDavid on 17/05/2015.
*/
public class GrouponDBHelper extends SQLiteOpenHelper {
private static GrouponDBHelper instance;
public static final String DATABASE_NAME = "GrouponDB.db";
public static final int DATABASE_VERSION = 1;
public static final String USERS_TABLE_NAME = "Users";
public static final String USERS_COLUMN_ID = "id"; // Primary Key
public static final String USERS_COLUMN_PASSWORD = "password";
public static final String USERS_COLUMN_EMAIL = "email";
public static final String USERS_COLUMN_PHONE = "phone";
public static final String USERS_COLUMN_PERMISSION = "permission";
public static final String[] USER_COLUMNS = {USERS_COLUMN_ID, USERS_COLUMN_PASSWORD,
USERS_COLUMN_EMAIL, USERS_COLUMN_PHONE, USERS_COLUMN_PERMISSION};
public static final String BUSINESSES_TABLE_NAME = "Businesses";
public static final String BUSINESSES_COLUMN_ID = "id"; // References Users.id
public static final String BUSINESSES_COLUMN_BUSINESSNAME = "businessName"; // Primary Key
public static final String BUSINESSES_COLUMN_CITY = "city";
public static final String BUSINESSES_COLUMN_ADDRESS = "address";
public static final String BUSINESSES_COLUMN_DESCRIPTION = "description";
public static final String BUSINESSES_COLUMN_COORDINATES = "coordinates";
public static final String[] BUSINESS_COLUMNS =
{BUSINESSES_COLUMN_BUSINESSNAME, BUSINESSES_COLUMN_ID,
BUSINESSES_COLUMN_CITY, BUSINESSES_COLUMN_ADDRESS, BUSINESSES_COLUMN_DESCRIPTION, BUSINESSES_COLUMN_COORDINATES};
public static final String CATALOG_TABLE_NAME = "Catalog";
public static final String CATALOG_COLUMN_BUSINESSNAME = "businessName"; // References Businesses.businessName
public static final String CATALOG_COLUMN_CATALOGNUMBER = "catalogNumber"; // Primary Key
public static final String CATALOG_COLUMN_CATALONGITEMNAME = "catalogItemName";
public static final String CATALOG_COLUMN_CATEGORY = "category";
public static final String CATALOG_COLUMN_DESCRIPTION = "description";
public static final String CATALOG_COLUMN_STATUS = "status";
public static final String CATALOG_COLUMN_RATINGS = "ratings";
public static final String CATALOG_COLUMN_SUMOFRATINGS = "sumOfRatings";
public static final String CATALOG_COLUMN_ORIGINALPRICE = "originalPrice";
public static final String CATALOG_COLUMN_PRICEAFTERDISCOUNT = "priceAfterDiscount";
public static final String CATALOG_COLUMN_EXPIRATIONDATE = "expirationDate";
public static final String CATALOG_COLUMN_TYPE = "type";
public static final String[] CATALOG_COLUMNS = {CATALOG_COLUMN_CATALOGNUMBER, CATALOG_COLUMN_BUSINESSNAME,
CATALOG_COLUMN_CATEGORY,CATALOG_COLUMN_CATALONGITEMNAME, CATALOG_COLUMN_DESCRIPTION,
CATALOG_COLUMN_STATUS, CATALOG_COLUMN_RATINGS, CATALOG_COLUMN_SUMOFRATINGS,
CATALOG_COLUMN_ORIGINALPRICE, CATALOG_COLUMN_PRICEAFTERDISCOUNT,
CATALOG_COLUMN_EXPIRATIONDATE, CATALOG_COLUMN_TYPE};
public static final String ORDERS_TABLE_NAME = "Orders";
public static final String ORDERS_COLUMN_ID = "id"; // References Users.id
public static final String ORDERS_COLUMN_ORDERCODE = "orderCode"; // Primary Key
public static final String ORDERS_COLUMN_STATUS = "status";
public static final String ORDERS_COLUMN_CATALOGNUMBER = "catalogNumber"; // References Catalog.catalogNumber
public static final String ORDERS_COLUMN_COUPONCODE = "couponCode"; // References Coupon.couponCode
public static final String[] ORDER_COLUMNS =
{ORDERS_COLUMN_ID, ORDERS_COLUMN_ORDERCODE, ORDERS_COLUMN_STATUS,
ORDERS_COLUMN_CATALOGNUMBER, ORDERS_COLUMN_COUPONCODE};
public static final String COUPONS_TABLE_NAME = "Coupons";
public static final String COUPONS_COLUMN_CATALOGNUMBER = "catalogNumber"; // References Catalog.catalogNumber
public static final String COUPONS_COLUMN_COUPONCODE = "couponCode"; // Primary Key
public static final String COUPONS_COLUMN_STATUS = "status";
public static final String[] COUPON_COLUMNS = {COUPONS_COLUMN_CATALOGNUMBER,
COUPONS_COLUMN_COUPONCODE, COUPONS_COLUMN_STATUS};
public static GrouponDBHelper getInstance(Context context) {
if (instance == null) {
instance = new GrouponDBHelper(context);
}
return instance;
}
private GrouponDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Called when the database is created for the first time. This is where the
* creation of tables and the initial population of the tables should happen.
*
* @param db The database.
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE Users " +
"(id TEXT PRIMARY KEY, password TEXT, email TEXT, phone TEXT, permission TEXT)"
);
ContentValues cv = new ContentValues();
cv.put(USERS_COLUMN_ID, "admin");
cv.put(USERS_COLUMN_PASSWORD, "adminpass");
cv.put(USERS_COLUMN_EMAIL, "email@groupon.com");
cv.put(USERS_COLUMN_PHONE, "0504442966");
cv.put(USERS_COLUMN_PERMISSION, AccessLevel.Administrator.toString());
db.insert(USERS_TABLE_NAME, null, cv);
db.execSQL(
"CREATE TABLE Businesses " +
"(" +
"businessName TEXT PRIMARY KEY, id TEXT, city TEXT, address TEXT, description TEXT, coordinates TEXT, " +
"FOREIGN KEY(id) REFERENCES Users(id)" +
")"
);
db.execSQL(
"CREATE TABLE Catalog " +
"(" +
"catalogNumber INTEGER PRIMARY KEY, businessName TEXT, category TEXT, catalogItemName TEXT, description TEXT, status TEXT, ratings INTEGER, sumOfRatings INTEGER, originalPrice REAL, priceAfterDiscount REAL, expirationDate DATE, type TEXT" +
")"
);
db.execSQL(
"CREATE TABLE Orders " +
"(" +
"orderCode INTEGER PRIMARY KEY, id TEXT, status TEXT, catalogNumber INTEGER, couponCode INTEGER, " +
"FOREIGN KEY(id) REFERENCES Users(id), " +
"FOREIGN KEY(catalogNumber) REFERENCES Catalog(catalogNumber), " +
"FOREIGN KEY(couponCode) REFERENCES Coupons(couponCode)" +
")"
);
db.execSQL(
"CREATE TABLE Coupons " +
"(" +
"couponCode INTEGER PRIMARY KEY, catalogNumber INTEGER, status TEXT, " +
"FOREIGN KEY(catalogNumber) REFERENCES Catalog(catalogNumber)" +
")"
);
}
/**
* Called when the database needs to be upgraded. The implementation
* should use this method to drop tables, add tables, or do anything else it
* needs to upgrade to the new schema version.
* <p/>
* <p>
* The SQLite ALTER TABLE documentation can be found
* <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
* you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
* you can use ALTER TABLE to rename the old table, then create the new table and then
* populate the new table with the contents of the old table.
* </p><p>
* This method executes within a transaction. If an exception is thrown, all changes
* will automatically be rolled back.
* </p>
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
package com.ibm.esc.xml.parser.sax.samples;
import java.net.*;
import java.io.*;
import org.xml.sax.*;
import com.ibm.esc.xml.parser.sax.*;
import com.ibm.esc.xml.parser.sax.errorhandler.*;
/**
* This class implements a sample of the SAX XML parser
* generating a trace of the parsing on the Console.
*/
public class XMLTraceSample extends Object
{
/**
* XMLTraceSample constructor comment.
*/
public XMLTraceSample() {
super();
}
/**
* Starts the application.
* @param args an array of command-line arguments
*/
public static void main(java.lang.String[] args)
{
// URL url = null;
InputStream is = null;
// First, check the command-line usage.
if (args.length == 0)
{
System.err.println(com.ibm.esc.xml.parser.Messages.getString("EmbeddedXMLParser.Usage__java_<url>_1"));
System.exit(2);
}
// try
// {
// url = new URL(args[0]);
// } catch (MalformedURLException e)
// {
// e.printStackTrace();
// }
// Open a stream which supports the Locator Interface APIs
// try
// {
// is = url.openStream();
// } catch (IOException e)
// {
// e.printStackTrace();
// }
is = System.in;
Reader reader = new BufferedReader(new InputStreamReader(is));
InputSource source = new InputSource(reader);
// Create the XML Parser
Parser parser = new MicroXMLParser();
// Create the DocumentHandler
//DocumentHandler docHandler = new XMLTraceDocumentHandler();
DocumentHandler docHandler = new XMLEmptyDocumentHandler();
parser.setDocumentHandler(docHandler);
parser.setErrorHandler(new DefaultErrorHandler());
long start = System.currentTimeMillis();
try
{
parser.parse(source);
} catch (SAXException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
long stop = System.currentTimeMillis();
System.out.println(com.ibm.esc.xml.parser.Messages.getString("EmbeddedXMLParser.Time_to_run___{0}_ms", new Object[] {Long.toString(stop - start)}));
}
}
|
package q0226_binaryTree;
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class InvertBinaryTree {
/**
翻转一棵二叉树。
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
*/
//DFS深度优先
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
//BFS广度优先
public TreeNode invertTree2(TreeNode root) {
if(root == null) return root;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode cur = queue.poll();
TreeNode tmp = cur.left;
cur.left = cur.right;
cur.right = tmp;
if(cur.left != null) queue.add(cur.left);
if(cur.right != null) queue.add(cur.right);
}
return root;
}
}
|
package com.voiceman.cg.serviceImpl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.voiceman.cg.entities.CMD;
import com.voiceman.cg.repository.CmdRepository;
import com.voiceman.cg.service.ICmdService;
@Service
@Transactional
public class CmdServiceImpl implements ICmdService{
@Autowired
private CmdRepository cmdDao;
@Override
public CMD addCmd(CMD cmd) {
return cmdDao.save(cmd);
}
@Override
public boolean validerCMD(Long idCmd) {
return false;
}
@Override
public int deleteCMD(int idCMD) {
return 0;
}
@Override
public CMD getCmdById(Long idCmd) {
return cmdDao.findById(idCmd).get();
}
@Override
public List<CMD> getCmdByUser(Long idUser) {
return null;
}
@Override
public List<CMD> getAllCmds() {
return cmdDao.findAll();
}
@Override
public CMD getCmdByDate(Date dateCmd) {
return null;
}
@Override
public boolean updateCMD(CMD cmd) {
// TODO Auto-generated method stub
return false;
}
}
|
package com.rs.game.player.dialogues;
import com.rs.game.player.Skills;
public class LargeLamp extends Dialogue {
int XP = 1550;
int LAMP = 23715;
@Override
public void start() {
sendOptionsDialogue("What skill would you like to gain experience in?", "Attack", "Strength", "Defence", "Ranged", "More...");
}
@Override
public void run(int interfaceId, int componentId) {
switch(stage) {
case -1:
if(componentId == OPTION_1) {
player.getSkills().addXp(Skills.ATTACK, XP);
destroyLamp();
} else if(componentId == OPTION_2) {
player.getSkills().addXp(Skills.STRENGTH, XP);
destroyLamp();
} else if(componentId == OPTION_3) {
player.getSkills().addXp(Skills.DEFENCE, XP);
destroyLamp();
} else if(componentId == OPTION_4) {
player.getSkills().addXp(Skills.RANGE, XP);
destroyLamp();
} else {
sendOptionsDialogue("What skill would you like to gain experience in?", "Prayer", "Magic", "Constitution", "Summoning", "More...");
stage = 1;
}
break;
case 1:
if(componentId == OPTION_1) {
player.getSkills().addXp(Skills.PRAYER, XP);
destroyLamp();
} else if(componentId == OPTION_2) {
player.getSkills().addXp(Skills.MAGIC, XP);
destroyLamp();
} else if(componentId == OPTION_3) {
player.getSkills().addXp(Skills.HITPOINTS, XP);
destroyLamp();
} else if(componentId == OPTION_4) {
player.getSkills().addXp(Skills.SUMMONING, XP);
destroyLamp();
} else {
sendOptionsDialogue("What skill would you like to gain experience in?", "Agility", "Herblore", "Thieving", "Crafting", "More...");
stage = 2;
}
break;
case 2:
if(componentId == OPTION_1) {
player.getSkills().addXp(Skills.AGILITY, XP);
destroyLamp();
} else if(componentId == OPTION_2) {
player.getSkills().addXp(Skills.HERBLORE, XP);
destroyLamp();
} else if(componentId == OPTION_3) {
player.getSkills().addXp(Skills.THIEVING, XP);
destroyLamp();
} else if(componentId == OPTION_4) {
player.getSkills().addXp(Skills.CRAFTING, XP);
destroyLamp();
} else {
sendOptionsDialogue("What skill would you like to gain experience in?", "Fletching", "Runecrafting", "Construction", "Slayer", "More...");
stage = 3;
}
break;
case 3:
if(componentId == OPTION_1) {
player.getSkills().addXp(Skills.FLETCHING, XP);
destroyLamp();
} else if(componentId == OPTION_2) {
player.getSkills().addXp(Skills.RUNECRAFTING, XP);
destroyLamp();
} else if(componentId == OPTION_3) {
player.getSkills().addXp(Skills.CONSTRUCTION, XP);
destroyLamp();
} else if(componentId == OPTION_4) {
player.getSkills().addXp(Skills.SLAYER, XP);
destroyLamp();
} else {
sendOptionsDialogue("What skill would you like to gain experience in?", "Hunter", "Mining", "Smithing", "Fishing", "More...");
stage = 4;
}
break;
case 4:
if(componentId == OPTION_1) {
player.getSkills().addXp(Skills.HUNTER, XP);
destroyLamp();
} else if(componentId == OPTION_2) {
player.getSkills().addXp(Skills.MINING, XP);
destroyLamp();
} else if(componentId == OPTION_3) {
player.getSkills().addXp(Skills.SMITHING, XP);
destroyLamp();
} else if(componentId == OPTION_4) {
player.getSkills().addXp(Skills.FISHING, XP);
destroyLamp();
} else {
sendOptionsDialogue("What skill would you like to gain experience in?", "Cooking", "Firemaking", "Woodcutting", "Farming", "Back...");
stage = 5;
}
break;
case 5:
if(componentId == OPTION_1) {
player.getSkills().addXp(Skills.COOKING, XP);
destroyLamp();
} else if(componentId == OPTION_2) {
player.getSkills().addXp(Skills.FIREMAKING, XP);
destroyLamp();
} else if(componentId == OPTION_3) {
player.getSkills().addXp(Skills.WOODCUTTING, XP);
destroyLamp();
} else if(componentId == OPTION_4) {
player.getSkills().addXp(Skills.FARMING, XP);
destroyLamp();
} else {
sendOptionsDialogue("What skill would you like to gain experience in?", "Attack", "Strength", "Defence", "Ranged", "More...");
stage = -1;
}
}
}
public void destroyLamp() {
player.getInventory().deleteItem(LAMP, 1);
}
@Override
public void finish() {
}
}
|
package com.smallproject.dominicparks.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class ConfirmationPage {
WebDriver webdriver;
public ConfirmationPage(WebDriver webdriver) {
this.webdriver = webdriver;
PageFactory.initElements(webdriver, this);
}
@FindBy(xpath = "//h2/i")
private WebElement successMessage;
@FindBy(xpath = "//span[@id='layer_cart_product_title']")
private WebElement productTitle;
@FindBy(id = "layer_cart_product_time_duration")
private WebElement time;
@FindBy(id = "layer_cart_product_quantity")
private WebElement roomquantity;
@FindBy(id = "layer_cart_product_price")
private WebElement totalcartcost;
@FindBy(css = ".ajax_block_products_total")
private WebElement totalroomscost;
@FindBy(xpath = "//span[@class='ajax_block_cart_total']")
private WebElement total;
@FindBy(xpath = "//span[contains(.,'Proceed to checkout')]")
private WebElement btnCheckoutProcess;
public String getProductTitle() {
return productTitle.getText();
}
public String getRoomPrice() {
return totalcartcost.getText();
}
public String getTotalCost() {
return totalroomscost.getText();
}
public void clickProceedCheckout() {
btnCheckoutProcess.click();
}
public boolean isDisplayed() {
successMessage.isDisplayed();
time.isDisplayed();
roomquantity.isDisplayed();
total.isDisplayed();
return true;
}
}
|
/**
* Copyright 2013-present febit.org (support@febit.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.febit.web.render;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import jodd.net.MimeTypes;
import org.febit.web.ActionRequest;
import org.febit.web.util.ServletUtil;
/**
*
* @author zqq90
*/
public class Text implements Renderable {
protected final String mimetype;// = MimeTypes.MIME_TEXT_PLAIN;
protected final String data;
public Text(String data) {
this(MimeTypes.MIME_TEXT_PLAIN, data);
}
public Text(String mimetype, String data) {
this.mimetype = mimetype;
this.data = data;
}
@Override
public Object render(final ActionRequest actionRequest) throws IOException {
final HttpServletResponse response = actionRequest.response;
final String encoding = response.getCharacterEncoding();
response.setContentType(this.mimetype);
response.setCharacterEncoding(encoding);
ServletUtil.setResponseContent(response, this.data.getBytes(encoding));
return null;
}
}
|
package org.bardibardi.jruby;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* The RubyApp (via IRubyO) is meant to be the
* starting point for using JRuby from java.
* A Guice Injector is used to construct/inject
* a singleton RubyApp when creating an IRubyO.
*
* @author Bardi Einarsson, bardibardi.org
*
*/
@Singleton
public class RubyApp extends RubyO implements IRubyO {
/**
* The RubyApp constructor is designed to be called
* by a Guice Injector exactly once.
* It creates ruby, a global JRuby engine, gets nil, the ruby
* nil and gets topSelf, the JRuby engine's top level object.
* The icra parameter is used to configure the
* JRuby engines load path ($:) and to get the script
* which is run to create the wrapped IRubyObject.
*
* @param icra, IConfigureRubyApp injected by Guice
*/
@Inject
public RubyApp(IConfigureRubyApp icra) {
super(null); // Java nonsense
ruby = JavaEmbedUtils.initialize(icra.loadPathAdditions());
// script is an engine method -- does not require robj
nil = script("nil");
// script is an engine method -- does not require robj
IRubyObject ts = script("self");
// script is an engine method -- does not require robj
robj = script(icra.appScript());
// If this (java this) is wrapping the top level ruby object,
// do not create an extra IRubyO.
topSelf = ts.equals(robj) ? this : rubyO(ts);
}
} // RubyApp
|
package com.online.trip;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.online.trip.model.TripSummary;
import com.online.trip.repository.TripSummaryRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TripsummaryApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class TripsummaryApplicationTests {
@LocalServerPort
private int port;
@MockBean
private TripSummaryRepository tripSummaryRepository;
@Autowired
private TestRestTemplate restTemplate;
/*@Test
public void contextLoads() {
}
*/
@Test
public void testGetTripSummaryForRider() throws Exception {
Mockito.when(tripSummaryRepository.findByRiderId(Mockito.anyString()))
.thenReturn(TripsummaryApplicationTests.riderTrips());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("userId", "rider1");
headers.set("roles", "RIDER");
ResponseEntity<String> response = restTemplate.exchange(
new URL("http://localhost:" + port + "/trip-summary/trip").toString(), HttpMethod.GET,
new HttpEntity<>(headers), String.class);
//assertTrue(StringUtils.contains(response.getBody(), "riderId1"));
}
@Test
public void testGetTripSummaryForDriver() throws Exception {
Mockito.when(tripSummaryRepository.findByDriverId(Mockito.anyString()))
.thenReturn(TripsummaryApplicationTests.riderTrips());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("userId", "driver1");
headers.set("roles", "DRIVER");
ResponseEntity<String> response = restTemplate.exchange(
new URL("http://localhost:" + port + "/trip-query/summary").toString(), HttpMethod.GET,
new HttpEntity<>(headers), String.class);
// assertTrue(StringUtils.contains(response.getBody(), "driverId1"));
}
@Test
public void testGetTripSummaryForAdmin() throws Exception {
Mockito.when(tripSummaryRepository.findAll()).thenReturn(TripsummaryApplicationTests.riderTrips());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("userId", "admin1");
headers.set("roles", "ADMIN");
ResponseEntity<String> response = restTemplate.exchange(
new URL("http://localhost:" + port + "/trip-query/summary").toString(), HttpMethod.GET,
new HttpEntity<>(headers), String.class);
//assertTrue(StringUtils.contains(response.getBody(), "driverId1"));
}
public static List<TripSummary> riderTrips() {
List<TripSummary> trips = new ArrayList<TripSummary>();
TripSummary trip1 = new TripSummary();
trip1.setRiderId("riderId1");
trip1.setDriverId("driverId1");
trip1.setFromLocation("abc");
trip1.setToLocation("xyz");
trip1.setStartTime("01/01/2019 09:00:00");
trip1.setEndTime("01/01/2019 10:00:00");
trip1.setStatus("COMPLETE");
//trip1.setTripId("12345");
trips.add(trip1);
return trips;
}
}
|
package com.mideas.rpg.v2.game.item;
public class RequestItem {
private DragItem slotType;
private int gemSlot;
private int slot;
private int id;
public RequestItem(int id, DragItem slotType, int slot, int gemSlot) {
this.slotType = slotType;
this.gemSlot = gemSlot;
this.slot = slot;
this.id = id;
}
public RequestItem(int id, DragItem slotType, int slot) {
this(id, slotType, slot, -1);
}
public DragItem getSlotType() {
return this.slotType;
}
public int getGemSlot() {
return this.gemSlot;
}
public int getSlot() {
return this.slot;
}
public int getId() {
return this.id;
}
}
|
/*
* Copyright 2011 frdfsnlght <frdfsnlght@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.frdfsnlght.transporter;
import com.frdfsnlght.transporter.api.SpawnDirection;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
/**
*
* @author frdfsnlght <frdfsnlght@gmail.com>
*/
public final class DesignBlockDetail {
private BuildableBlock buildBlock = null;
private BuildableBlock openBlock = null;
private boolean isScreen = false;
private boolean isPortal = false;
private boolean isTrigger = false;
private boolean isSwitch = false;
private boolean isInsert = false;
private SpawnDirection spawn = null;
private LightningMode sendLightningMode = LightningMode.NONE;
private LightningMode receiveLightningMode = LightningMode.NONE;
private RedstoneMode triggerOpenMode = RedstoneMode.HIGH;
private RedstoneMode triggerCloseMode = RedstoneMode.LOW;
private RedstoneMode switchMode = RedstoneMode.HIGH;
public DesignBlockDetail(DesignBlockDetail src, BlockFace direction) {
if (src.buildBlock != null)
buildBlock = new BuildableBlock(src.buildBlock, direction);
if (src.openBlock != null)
openBlock = new BuildableBlock(src.openBlock, direction);
isScreen = src.isScreen;
isPortal = src.isPortal;
isTrigger = src.isTrigger;
isSwitch = src.isSwitch;
isInsert = src.isInsert;
if (src.spawn != null)
spawn = src.spawn.rotate(direction);
sendLightningMode = src.sendLightningMode;
receiveLightningMode = src.receiveLightningMode;
triggerOpenMode = src.triggerOpenMode;
triggerCloseMode = src.triggerCloseMode;
switchMode = src.switchMode;
}
public DesignBlockDetail(String blockType) throws BlockException {
buildBlock = new BuildableBlock(blockType);
if (! buildBlock.hasType()) buildBlock = null;
}
public DesignBlockDetail(TypeMap map) throws BlockException {
TypeMap subMap;
String str;
subMap = map.getMap("build");
if (subMap == null) {
str = map.getString("build");
if (str != null)
buildBlock = new BuildableBlock(str);
} else
buildBlock = new BuildableBlock(subMap);
if ((buildBlock != null) && (! buildBlock.hasType())) buildBlock = null;
subMap = map.getMap("open");
if (subMap == null) {
str = map.getString("open");
if (str != null)
openBlock = new BuildableBlock(str);
} else
openBlock = new BuildableBlock(subMap);
if ((openBlock != null) && (! openBlock.hasType())) openBlock = null;
isScreen = map.getBoolean("screen", false);
isPortal = map.getBoolean("portal", false);
isTrigger = map.getBoolean("trigger", false);
isSwitch = map.getBoolean("switch", false);
isInsert = map.getBoolean("insert", false);
str = map.getString("spawn");
if (str != null) {
try {
spawn = Utils.valueOf(SpawnDirection.class, str);
} catch (IllegalArgumentException iae) {
throw new BlockException(iae.getMessage() + " spawn '%s'", str);
}
}
str = map.getString("sendLightningMode", "NONE");
try {
sendLightningMode = Utils.valueOf(LightningMode.class, str);
} catch (IllegalArgumentException iae) {
throw new BlockException(iae.getMessage() + " sendLightningMode '%s'", str);
}
str = map.getString("receiveLightningMode", "NONE");
try {
receiveLightningMode = Utils.valueOf(LightningMode.class, str);
} catch (IllegalArgumentException iae) {
throw new BlockException(iae.getMessage() + " receiveLightningMode '%s'", str);
}
// backwards compatibility in v7.8, remove someday
str = map.getString("lightningMode");
if (str != null) {
str = str.toUpperCase();
if (! str.equals("NONE"))
Utils.warning("Outdated 'lightningMode' block option found! Please update to use new lightning mode options!");
if (str.equals("SEND"))
sendLightningMode = LightningMode.NORMAL;
else if (str.equals("RECEIVE"))
receiveLightningMode = LightningMode.NORMAL;
else if (str.equals("BOTH")) {
sendLightningMode = LightningMode.NORMAL;
receiveLightningMode = LightningMode.NORMAL;
}
}
str = map.getString("triggerOpenMode", "HIGH");
try {
triggerOpenMode = Utils.valueOf(RedstoneMode.class, str);
} catch (IllegalArgumentException iae) {
throw new BlockException(iae.getMessage() + " triggerOpenMode '%s'", str);
}
str = map.getString("triggerCloseMode", "LOW");
try {
triggerCloseMode = Utils.valueOf(RedstoneMode.class, str);
} catch (IllegalArgumentException iae) {
throw new BlockException(iae.getMessage() + " triggerCloseMode '%s'", str);
}
str = map.getString("switchMode", "HIGH");
try {
switchMode = Utils.valueOf(RedstoneMode.class, str);
} catch (IllegalArgumentException iae) {
throw new BlockException(iae.getMessage() + " switchMode '%s'", str);
}
if (isScreen && ((buildBlock == null) || (! buildBlock.isSign())))
throw new BlockException("screen blocks must be wall signs or sign posts");
}
public Map<String,Object> encode() {
Map<String,Object> node = new HashMap<String,Object>();
if (buildBlock != null) node.put("build", buildBlock.encode());
if (openBlock != null) node.put("open", openBlock.encode());
if (isScreen) node.put("screen", isScreen);
if (isPortal) node.put("portal", isPortal);
if (isTrigger) node.put("trigger", isTrigger);
if (isSwitch) node.put("switch", isSwitch);
if (isInsert) node.put("insert", isInsert);
if (spawn != null) node.put("spawn", spawn.toString());
if (sendLightningMode != LightningMode.NONE) node.put("sendLightningMode", sendLightningMode.toString());
if (receiveLightningMode != LightningMode.NONE) node.put("receiveLightningMode", receiveLightningMode.toString());
if (triggerOpenMode != RedstoneMode.HIGH) node.put("triggerOpenMode", triggerOpenMode.toString());
if (triggerCloseMode != RedstoneMode.LOW) node.put("triggerCloseMode", triggerCloseMode.toString());
if (switchMode != RedstoneMode.HIGH) node.put("switchMode", switchMode.toString());
return node;
}
public BuildableBlock getBuildBlock() {
return buildBlock;
}
public BuildableBlock getOpenBlock() {
return openBlock;
}
public boolean isScreen() {
return isScreen;
}
public boolean isPortal() {
return isPortal;
}
public boolean isTrigger() {
return isTrigger;
}
public boolean isSwitch() {
return isSwitch;
}
public boolean isInsert() {
return isInsert;
}
public boolean isSpawn() {
return spawn != null;
}
public SpawnDirection getSpawn() {
return spawn;
}
public RedstoneMode getTriggerOpenMode() {
return triggerOpenMode;
}
public RedstoneMode getTriggerCloseMode() {
return triggerCloseMode;
}
public RedstoneMode getSwitchMode() {
return switchMode;
}
public LightningMode getSendLightningMode() {
return sendLightningMode;
}
public LightningMode getReceiveLightningMode() {
return receiveLightningMode;
}
public boolean isInventory() {
return (buildBlock != null) && (buildBlock.getType() != Material.AIR.getId());
}
public boolean isBuildable() {
return buildBlock != null;
}
public boolean isOpenable() {
return openBlock != null;
}
public boolean isMatchable() {
return (buildBlock != null) && (buildBlock.getMaterial() != Material.AIR);
}
@Override
public int hashCode() {
return
((buildBlock != null) ? buildBlock.hashCode() : 0) +
((openBlock != null) ? openBlock.hashCode() : 0) +
(isScreen ? 10 : 0) +
(isPortal ? 100 : 0) +
(isTrigger ? 1000 : 0) +
(isSwitch ? 10000 : 0) +
(isInsert ? 100000 : 0) +
sendLightningMode.hashCode() +
receiveLightningMode.hashCode() +
((spawn != null) ? spawn.hashCode() : 0) +
triggerOpenMode.hashCode() +
triggerCloseMode.hashCode() +
switchMode.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (! (obj instanceof DesignBlockDetail)) return false;
DesignBlockDetail other = (DesignBlockDetail)obj;
if ((buildBlock == null) && (other.buildBlock != null)) return false;
if ((buildBlock != null) && (other.buildBlock == null)) return false;
if ((buildBlock != null) && (other.buildBlock != null) &&
(! buildBlock.equals(other.buildBlock))) return false;
if ((openBlock == null) && (other.openBlock != null)) return false;
if ((openBlock != null) && (other.openBlock == null)) return false;
if ((openBlock != null) && (other.openBlock != null) &&
(! openBlock.equals(other.openBlock))) return false;
if (isScreen != other.isScreen) return false;
if (isPortal != other.isPortal) return false;
if (isTrigger != other.isTrigger) return false;
if (isSwitch != other.isSwitch) return false;
if (isInsert != other.isInsert) return false;
if (spawn != other.spawn) return false;
if (sendLightningMode != other.sendLightningMode) return false;
if (receiveLightningMode != other.receiveLightningMode) return false;
if (triggerOpenMode != other.triggerOpenMode) return false;
if (triggerCloseMode != other.triggerCloseMode) return false;
if (switchMode != other.switchMode) return false;
return true;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("Detail[");
buf.append("scr=").append(isScreen).append(",");
buf.append("prt=").append(isPortal).append(",");
buf.append("trg=").append(isTrigger).append(",");
buf.append("swt=").append(isSwitch).append(",");
buf.append("ins=").append(isInsert).append(",");
buf.append("spw=").append(spawn).append(",");
buf.append("slng=").append(sendLightningMode).append(",");
buf.append("rlng=").append(receiveLightningMode).append(",");
buf.append("trgOpnMod=").append(triggerOpenMode).append(",");
buf.append("trgClsMod=").append(triggerOpenMode).append(",");
buf.append("swtMod=").append(switchMode).append(",");
buf.append(buildBlock).append(",");
buf.append(openBlock);
buf.append("]");
return buf.toString();
}
}
|
package com.gili.msmservice.untils;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public class RandomUntils {
private static final Random random=new Random();
private static final DecimalFormat fourformat=new DecimalFormat("0000");
private static final DecimalFormat sixformat=new DecimalFormat("000000");
public static String getFourFormat(){
return fourformat.format(random.nextInt(10000));
}
public static String getSixFormat(){
return sixformat.format(random.nextInt(1000000));
}
public static ArrayList getRandom(List list,int n){
Random random=new Random();
HashMap<Object, Object> hashMap=new HashMap<>();
for(int i=0; i<list.size();i++){
int number=random.nextInt(100)+1;
hashMap.put(number,i);
}
Object[] robjs=hashMap.values().toArray();
ArrayList r=new ArrayList();
for(int i=0; i<list.size();i++) {
r.add(list.get((Integer) robjs[i]));
System.out.println(list.get((Integer) robjs[i]));
}
return r;
}
}
|
package com.tencent.mm.plugin.appbrand.dynamic.a;
import android.os.Bundle;
import com.tencent.mm.ipcinvoker.a;
import com.tencent.mm.ipcinvoker.c;
import com.tencent.mm.plugin.appbrand.dynamic.h.b;
class b$a implements a<Bundle, Bundle> {
private b$a() {
}
public final /* synthetic */ void a(Object obj, c cVar) {
boolean z = false;
Bundle bundle = (Bundle) obj;
if (bundle != null && bundle.getBoolean("forceKillProcess", false)) {
z = true;
}
if (z) {
b.afu();
} else {
b.aft();
}
cVar.at(null);
}
}
|
package com.ibm.ive.tools.japt.testcase.escape;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
public class EscapeClass {
public static void main() {
Object array = new Object[] {new Object(), null}; /* arrays used to manage collections of objects often do not escape */
ArrayList sorter = new ArrayList(); /* Collections used for data management sometimes do not escape */
Collections.sort(sorter);
Set set = new HashSet();
Iterator iterator = set.iterator(); /* iterators frequently do not escape the method in which they are used */
while(iterator.hasNext()) {
System.out.println("Some object" + iterator.next()); /* StringBuffer or StringBuilder objects are frequently for temporary use and thus do not escape */
}
Vector vector = new Vector(); /* enumerations frequently do not escape the method in which they are used */
Enumeration elements = vector.elements();
while(elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
}
public static final short escapeClassInitializer[][] = {
{0, 0},
{0, 1},
};
Object object;
void escapeToThisArgument() {
object = new Object();
}
void escapeToParameterArgument(EscapeClass arg) {
arg.object = new Object();
}
static void escapeByThrow() {
throw new RuntimeException();
}
static void escapeByPropagatedThrow() {
escapeByThrow();
}
static Object escapeByReturn() {
return new Object();
}
static Object escapeByDoubleReturn() {
return escapeByReturn();
}
static Object staticObject;
static void escapeByStaticField() {
staticObject = new Object();
}
/*
* All of these escape by native examples are equivalent to escape by any method
* for which the code is unknown at the time of analysis, which incudes methods
* whose classes have not been loaded at runtime.
*/
static void escapeByNative() {
new EscapeClass().aNative();
}
native void aNative();
static void escapeByAnotherNative() {
aNative2(new EscapeClass());
}
static native void aNative2(Object arg);
static void escapeByNativeReturned() {
aNative3().object = new Object();
}
static native EscapeClass aNative3();
static void escapeByNativeThrown() {
try {
aNative4();
} catch(RuntimeExceptionSubclass e) {
e.object = new Object();
}
}
static class RuntimeExceptionSubclass extends RuntimeException {
Object object;
}
static native void aNative4();
static void escapeByThread() {
final Object object = new Object();
class ThreadSubClass extends Thread {
public void run() {
Object local = object;
}
}
Thread thread = new ThreadSubClass();
thread.start();
}
class CustomThread extends Thread {
Object object;
}
/*
* If currentThread() is a native call or if it accesses a static field, then that will cause the
* object to escape as well.
*/
static void escapeByCurrentThread() {
((CustomThread) Thread.currentThread()).object = new Object();
}
static void escapeNotLoaded() {
OtherClass object = new OtherClass();
/*
* If we have not loaded the class for an object, analysis will determine that the object escapes,
* because there is always a constructor invocation with the object, and inside
* that invocation the object can escape.
*/
}
static class OtherClass {
OtherClass() {
staticObject = this;
}
static void method(Object arg) {
staticObject = arg;
}
static EscapeClass method2() {
staticObject = new EscapeClass();
return (EscapeClass) staticObject;
}
static void method3() {
staticObject = new RuntimeExceptionSubclass();
throw (RuntimeExceptionSubclass) staticObject;
}
}
static void escapeNotLoadedArg() {
OtherClass.method(new EscapeClass());
}
static void escapeNotLoadedReturned() {
OtherClass.method2().object = new Object();
}
static void escapeNotLoadedThrown() {
try {
OtherClass.method3();
} catch(RuntimeExceptionSubclass e) {
e.object = new Object();
}
}
void escapeToArray() {
/* There are 3 object instantiated here, the base array of type int[][] assigned to object the two objects of type int[] contained within the base array */
object = new int[2][3];
}
}
|
package se.jaitco.queueticketapi.controller;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import se.jaitco.queueticketapi.model.LoginRequest;
import se.jaitco.queueticketapi.model.LoginResponse;
import se.jaitco.queueticketapi.service.AuthenticationService;
public class UserControllerTest {
@InjectMocks
private final UserController classUnderTest = new UserController();
@Mock
private AuthenticationService authenticationService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testLoginCorrect() {
LoginRequest userLogin = LoginRequest.builder().build();
Mockito.when(authenticationService.login(userLogin)).thenReturn(LoginResponse.builder().build());
LoginResponse loginResponse = classUnderTest.login(userLogin);
Mockito.verify(authenticationService, Mockito.times(1)).login(userLogin);
}
}
|
package com.espendwise.manta.service;
import com.espendwise.manta.model.data.OrderPropertyData;
import com.espendwise.manta.model.data.PropertyData;
import com.espendwise.manta.model.view.EntityPropertiesView;
import java.util.List;
public interface PropertyService {
public List<PropertyData> findEntityPropertyValues(Long entityId, String typeCode);
public void configureEntityProperty(Long entityId, String propertyType, String propertyValue);
public EntityPropertiesView findEntityProperties(Long entityId, List<String> propertyExtraTypeCds, List<String> propertyTypeCds);
public EntityPropertiesView saveEntityProperties(Long entityId, EntityPropertiesView view);
public OrderPropertyData saveOrderProperty(Long orderId, OrderPropertyData property);
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.common.service;
import java.util.Map;
/**
* This abstract class defines a Cache Manager service for
* use by runtime governance components.
*
*/
public abstract class CacheManager extends Service {
/**
* This method returns the cache associated with the
* supplied name.
*
* @param name The name of the required cache
* @return The cache, or null if not found
*
* @param <K> The key type
* @param <V> The value type
*/
public abstract <K,V> Map<K,V> getCache(String name);
/**
* This method locks the item, associated with the
* supplied key, in the named cache.
*
* @param cacheName The name of the cache
* @param key The key for the item to be locked
* @return Whether the lock could be applied
*/
public abstract boolean lock(String cacheName, Object key);
}
|
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;
public class baseChrome {
public static AndroidDriver<AndroidElement> Capabilities() throws MalformedURLException {
DesiredCapabilities cb = new DesiredCapabilities();
cb.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);
cb.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Device");
cb.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");
cb.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.google.android.apps.chrome.Main");
cb.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.android.chrome");
AndroidDriver<AndroidElement> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"),cb);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
|
/*
* Sonar GreenPepper Plugin
* Copyright (C) 2009 SonarSource
* dev@sonar.codehaus.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.greenpepper;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.io.File;
import java.net.URISyntaxException;
public class GreenPepperReportsParserTest {
@Test
public void testParseReport() throws URISyntaxException {
File xmlReport = new File(getClass().getResource("/GreenPepper Confluence-GREENPEPPER-Cell decoration.xml")
.toURI());
GreenPepperReport report = GreenPepperReportsParser.parseReport(xmlReport);
assertEquals(14, report.getTests());
assertEquals(1, report.getSkippedTests());
assertEquals(0, report.getTestErrors());
assertEquals(0, report.getTestFailures());
assertEquals(13, report.getTestsSuccess());
}
@Test
public void testParseReports() throws URISyntaxException {
File reportsDir = new File(getClass().getResource("/").toURI());
GreenPepperReport report = GreenPepperReportsParser.parseReports(reportsDir);
assertEquals(31, report.getTests());
assertEquals(5, report.getSkippedTests());
assertEquals(0, report.getTestErrors());
assertEquals(1, report.getTestFailures());
assertEquals(25, report.getTestsSuccess());
assertEquals(25.0 / 26.0, report.getTestSuccessPercentage(), 0.00001);
}
}
|
package gr.athena.innovation.fagi.exception;
/**
* Wrapper exception for wrong input related exceptions.
*
* @author nkarag
*/
public class WrongInputException extends Exception{
/**
* Empty constructor of a Wrong Input Exception.
*/
public WrongInputException() {}
/**
* Constructor of a Wrong Input Exception with the message.
* Calls the super constructor with the message (RuntimeException -> Exception -> Throwable).
*
* @param message the exception message as a string.
*/
public WrongInputException(String message){
super(message);
}
}
|
package com.timebusker.repository;
import com.timebusker.entity.UserEntity;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
* @DESC:UserRepository
* @author:timebusker
* @date:2018/9/5
*/
public interface UserRepository extends MongoRepository<UserEntity, Integer> {
/*
* MongoRepository与HibernateTemplete相似,提供一些基本的方法,
* 实现的方法有findone(),save(),count(),findAll(),findAll(Pageable),delete(),deleteAll()..etc
* 要使用Repository的功能,先继承MongoRepository<T, TD>接口
* 其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。
* 之后在spring-boot中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。
* starter-data-mongodb 支持方法命名约定查询 findBy{User的name属性名},
* findBy后面的属性名一定要在User类中存在,否则会报错
*/
UserEntity findById(Integer key);
void deleteById(Integer key);
}
|
package com.mysql.cj.protocol;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class NetworkResources {
private final Socket mysqlConnection;
private final InputStream mysqlInput;
private final OutputStream mysqlOutput;
public NetworkResources(Socket mysqlConnection, InputStream mysqlInput, OutputStream mysqlOutput) {
this.mysqlConnection = mysqlConnection;
this.mysqlInput = mysqlInput;
this.mysqlOutput = mysqlOutput;
}
public final void forceClose() {
try {
if (!ExportControlled.isSSLEstablished(this.mysqlConnection))
try {
if (this.mysqlInput != null)
this.mysqlInput.close();
} finally {
if (this.mysqlConnection != null && !this.mysqlConnection.isClosed() && !this.mysqlConnection.isInputShutdown())
try {
this.mysqlConnection.shutdownInput();
} catch (UnsupportedOperationException unsupportedOperationException) {}
}
} catch (IOException iOException) {}
try {
if (!ExportControlled.isSSLEstablished(this.mysqlConnection))
try {
if (this.mysqlOutput != null)
this.mysqlOutput.close();
} finally {
if (this.mysqlConnection != null && !this.mysqlConnection.isClosed() && !this.mysqlConnection.isOutputShutdown())
try {
this.mysqlConnection.shutdownOutput();
} catch (UnsupportedOperationException unsupportedOperationException) {}
}
} catch (IOException iOException) {}
try {
if (this.mysqlConnection != null)
this.mysqlConnection.close();
} catch (IOException iOException) {}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\NetworkResources.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.atguigu.gmall.index.service;
import com.atguigu.gmall.pms.vo.CategoryVO;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface IndexService {
public List<CategoryEntity> queryLvel1Category() ;
List<CategoryVO> queryLv2WithSubByPid(Long pid);
void testLock();
}
|
package com.tencent.magicbrush.engine;
import java.util.TimerTask;
public class AppBrandContext$a extends TimerTask {
public int bnu;
public boolean bnv;
final /* synthetic */ AppBrandContext bnw;
public AppBrandContext$a(AppBrandContext appBrandContext, int i, boolean z) {
this.bnw = appBrandContext;
this.bnu = i;
this.bnv = z;
}
public final void run() {
if (!AppBrandContext.b(this.bnw)) {
AppBrandContext.d(this.bnw).post(new 1(this));
} else if (!this.bnv) {
AppBrandContext.c(this.bnw).add(Integer.valueOf(this.bnu));
}
}
}
|
package com.tencent.mm.plugin.honey_pay.ui;
import com.tencent.mm.ab.l;
import com.tencent.mm.wallet_core.c.h.a;
class HoneyPayCheckPwdUI$6 implements a {
final /* synthetic */ HoneyPayCheckPwdUI kld;
HoneyPayCheckPwdUI$6(HoneyPayCheckPwdUI honeyPayCheckPwdUI) {
this.kld = honeyPayCheckPwdUI;
}
public final void g(int i, int i2, String str, l lVar) {
HoneyPayCheckPwdUI.d(this.kld);
}
}
|
package org.apache.giraph.worker;
import org.apache.hadoop.io.Text;
import java.util.regex.Pattern;
public class KMeansNodeWorkerContext extends DefaultWorkerContext {
private double[][] centers;
private int numberOfClusters;
private int numberOfDimensions;
private int maxIterations;
private final static Pattern commaPattern = Pattern.compile(",");
@Override
public void preApplication() throws InstantiationException,
IllegalAccessException{
numberOfClusters = 3;
numberOfDimensions = 2;
centers = new double[numberOfClusters][numberOfDimensions];
maxIterations = 80;
}
@Override
public void preSuperstep(){
Text pointsText = ((Text)getAggregatedValue("custom.center.point"));
if (pointsText != null) {
String pointsString = pointsText.toString();
if (!pointsString.isEmpty()) {
String[] points = commaPattern.split(pointsString);
int pointIndex = 0;
for (int c = 0; c < numberOfClusters; c++) {
for (int d = 0; d < numberOfDimensions; d++) {
//System.out.println("centers[" + c + "][" + d + "]=" + points[pointIndex]);
centers[c][d] = Double.parseDouble(points[pointIndex]);
pointIndex++;
}
}
}
}
}
public double[][] getCenters() {
return centers;
}
public int getNumberOfClusters() {
return numberOfClusters;
}
public int getNumberOfDimensions() {
return numberOfDimensions;
}
public int getMaxIterations() {
return maxIterations;
}
}
|
package com.team_linne.digimov.model;
import lombok.*;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.FieldType;
import org.springframework.data.mongodb.core.mapping.MongoId;
import java.util.List;
@Document
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Movie {
@MongoId(FieldType.OBJECT_ID)
private String id;
private String name;
private Integer duration;
private List<String> genreIds;
private String director;
private String description;
private String imageUrl;
private String rating;
private List<String> cast;
private String language;
public Movie(String name, Integer duration, List<String> genreIds, String director, String description, String imageUrl, String rating, List<String> cast, String language) {
this.name = name;
this.duration = duration;
this.genreIds = genreIds;
this.director = director;
this.description = description;
this.imageUrl = imageUrl;
this.rating = rating;
this.cast = cast;
this.language = language;
}
}
|
/*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID 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 net.shibboleth.idp.test;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.SocketUtils;
import net.shibboleth.utilities.java.support.annotation.constraint.NotEmpty;
import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
import net.shibboleth.utilities.java.support.logic.Constraint;
/** Start Jetty via start.jar. */
public class JettyServerProcess extends AbstractServerProcess {
/** Class logger. */
@Nonnull private final Logger log = LoggerFactory.getLogger(JettyServerProcess.class);
/** Port to use to shutdown Jetty. Defaults to 8005. */
@Nonnull private int shutdownPort = 8005;
/** Passphrase to use to shutdown Jetty. Defaults to SHUTDOWN. */
@Nonnull private String shutdownKey = "SHUTDOWN";
/** {@inheritDoc} */
@Override
protected void doInitialize() throws ComponentInitializationException {
super.doInitialize();
// Add JETTY_BASE to environment
getProcessBuilder().environment().put("JETTY_BASE", getServletContainerBasePath().toAbsolutePath().toString());
// Start Jetty via start.jar
// Prefer Java located at idp.java.home system property
final Path pathToJava = Paths.get(System.getProperty("idp.java.home", System.getProperty("java.home")), "bin", "java");
log.debug("Will use Java located at '{}'", pathToJava);
getCommands().add(pathToJava.toAbsolutePath().toString());
getCommands().add("-jar");
getCommands().add(getServletContainerHomePath().toAbsolutePath().toString() + "/start.jar");
getCommands().add("STOP.KEY=" + shutdownKey);
nextAvailableShutdownPort();
getCommands().add("STOP.PORT=" + Integer.toString(shutdownPort));
}
/**
* Set Jetty shutdown passphrase.
*
* Passed to start.jar as STOP.KEY.
*
* @param key key to use to shutdown Jetty
*/
@Nonnull
public void setShutdownKey(@Nonnull @NotEmpty final String key) {
shutdownKey = key;
}
/**
* Configure the next available port in the range 20000-30000 to shutdown Jetty.
*
* @return the next available port to use to shutdown Tomcat, by default '8005' if the '8080' system property is
* <code>true</code>
* @throws ComponentInitializationException if catalina.properties cannot be modified
*/
@Nonnull
public int nextAvailableShutdownPort() throws ComponentInitializationException {
if (Boolean.getBoolean("8080")) {
log.debug("System property '8080' is true, using default shutdown port {}", shutdownPort);
return shutdownPort;
}
shutdownPort = SocketUtils.findAvailableTcpPort(20000, 30000);
log.debug("Selecting Jetty shutdown port {}", shutdownPort);
return shutdownPort;
}
/**
* Attempt to shutdown Jetty.
*
* Send the stop command to the STOP.PORT.
*
* @param hostname the name of the remote host
* @param port the port to connect to on the remote host
* @param password the shutdown password
*/
public void shutdown(@Nonnull final String hostname, final int port, @Nonnull final String password) {
Constraint.isNotNull(hostname, "Hostname cannot be null");
Constraint.isNotNull(password, "Password cannot be null");
log.debug("Attempting to shutdown Jetty at '{}:{}'", hostname, port);
try {
try (final Socket s = new Socket(InetAddress.getByName(hostname), port)) {
try (OutputStream out = s.getOutputStream()) {
out.write((password + "\r\nstop\r\n").getBytes());
out.flush();
}
}
} catch (SocketTimeoutException e) {
log.warn("Timed out waiting for stop confirmation");
} catch (ConnectException e) {
log.warn("Server might be stopped", e);
} catch (Exception e) {
log.warn("An error occurred waiting for server to stop", e);
}
}
/** {@inheritDoc} */
@Override
public void stop() {
shutdown("127.0.0.1", shutdownPort, shutdownKey);
super.stop();
}
}
|
/*
* Copyright (C) 2021-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.importer.reader.balance;
import static com.hedera.mirror.common.domain.DigestAlgorithm.SHA_384;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.collect.Collections2;
import com.hedera.mirror.common.domain.balance.AccountBalance;
import com.hedera.mirror.common.domain.balance.AccountBalanceFile;
import com.hedera.mirror.common.util.DomainUtils;
import com.hedera.mirror.importer.MirrorProperties;
import com.hedera.mirror.importer.TestUtils;
import com.hedera.mirror.importer.domain.StreamFileData;
import com.hedera.mirror.importer.domain.StreamFilename;
import com.hedera.mirror.importer.exception.InvalidDatasetException;
import com.hedera.mirror.importer.parser.balance.BalanceParserProperties;
import com.hedera.mirror.importer.reader.balance.line.AccountBalanceLineParser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.util.StringUtils;
abstract class CsvBalanceFileReaderTest {
protected final MirrorProperties mirrorProperties;
protected final BalanceParserProperties balanceParserProperties;
protected final File balanceFile;
protected final CsvBalanceFileReader balanceFileReader;
protected final AccountBalanceLineParser parser;
protected final long expectedCount;
protected File testFile;
protected long consensusTimestamp;
@TempDir
Path tempDir;
CsvBalanceFileReaderTest(
Class<? extends CsvBalanceFileReader> balanceFileReaderClass,
Class<? extends AccountBalanceLineParser> accountBalanceLineParserClass,
String balanceFilePath,
long expectedCount) {
mirrorProperties = new MirrorProperties();
balanceParserProperties = new BalanceParserProperties();
balanceFile = TestUtils.getResource(balanceFilePath);
parser = (AccountBalanceLineParser) ReflectUtils.newInstance(
accountBalanceLineParserClass, new Class<?>[] {MirrorProperties.class}, new Object[] {mirrorProperties
});
balanceFileReader = (CsvBalanceFileReader) ReflectUtils.newInstance(
balanceFileReaderClass,
new Class<?>[] {BalanceParserProperties.class, accountBalanceLineParserClass},
new Object[] {balanceParserProperties, parser});
this.expectedCount = expectedCount;
}
protected static String getTestFilename(String version, String filename) {
return Path.of("data", "accountBalances", version, "balance0.0.3", filename)
.toString();
}
@BeforeEach
void setup() throws IOException {
Instant instant = StreamFilename.from(balanceFile.getName()).getInstant();
consensusTimestamp = DomainUtils.convertToNanosMax(instant);
testFile = tempDir.resolve(balanceFile.getName()).toFile();
assertThat(testFile.createNewFile()).isTrue();
}
@Test
void readValid() throws Exception {
StreamFileData streamFileData = StreamFileData.from(balanceFile);
AccountBalanceFile accountBalanceFile = balanceFileReader.read(streamFileData);
assertAccountBalanceFile(accountBalanceFile);
assertFileHash(balanceFile, accountBalanceFile);
verifySuccess(balanceFile, accountBalanceFile, 2);
}
@Test
void readInvalidWhenFileHasNoTimestampHeader() throws IOException {
List<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
lines.remove(0);
FileUtils.writeLines(testFile, lines);
StreamFileData streamFileData = StreamFileData.from(testFile);
assertThrows(InvalidDatasetException.class, () -> balanceFileReader.read(streamFileData));
}
@Test
void readInvalidWhenFileHasInvalidVersion() throws IOException {
List<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
lines.remove(0);
List<String> copy = new ArrayList<>();
copy.add("# 0.1.0");
copy.addAll(lines);
FileUtils.writeLines(testFile, copy);
StreamFileData streamFileData = StreamFileData.from(testFile);
assertThrows(InvalidDatasetException.class, () -> balanceFileReader.read(streamFileData));
}
@Test
void readInvalidWhenFileHasNoHeader() throws IOException {
List<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
lines.remove(0);
lines.remove(0);
FileUtils.writeLines(testFile, lines);
StreamFileData streamFileData = StreamFileData.from(testFile);
assertThrows(InvalidDatasetException.class, () -> balanceFileReader.read(streamFileData));
}
@Test
void readInvalidWhenFileHasNoColumnHeader() throws IOException {
Collection<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
Collection<String> filtered =
Collections2.filter(lines, line -> !line.contains(CsvBalanceFileReader.COLUMN_HEADER_PREFIX));
FileUtils.writeLines(testFile, filtered);
StreamFileData streamFileData = StreamFileData.from(testFile);
assertThrows(InvalidDatasetException.class, () -> balanceFileReader.read(streamFileData));
}
@Test
void readInvalidWhenFileIsEmpty() {
StreamFileData streamFileData = StreamFileData.from(balanceFile.getName(), "");
assertThrows(InvalidDatasetException.class, () -> balanceFileReader.read(streamFileData));
}
@Test
void readInvalidWhenFileDoesNotExist() {
StreamFileData streamFileData = StreamFileData.from(testFile);
assertThrows(InvalidDatasetException.class, () -> balanceFileReader.read(streamFileData));
}
@Test
void readInvalidWhenFileHasMalformedTimestamp() throws IOException {
String prefix = balanceFileReader.getTimestampHeaderPrefix();
Collection<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
Collection<String> filtered =
Collections2.transform(lines, line -> StringUtils.startsWithIgnoreCase(line, prefix) ? prefix : line);
FileUtils.writeLines(testFile, filtered);
StreamFileData streamFileData = StreamFileData.from(testFile);
assertThrows(InvalidDatasetException.class, () -> balanceFileReader.read(streamFileData));
}
@Test
void readValidWhenFileHasTrailingEmptyLines() throws IOException {
List<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
FileUtils.writeLines(testFile, lines);
FileUtils.writeStringToFile(testFile, "\n\n\n", CsvBalanceFileReader.CHARSET, true);
StreamFileData streamFileData = StreamFileData.from(testFile);
AccountBalanceFile accountBalanceFile = balanceFileReader.read(streamFileData);
assertAccountBalanceFile(accountBalanceFile);
verifySuccess(testFile, accountBalanceFile, 2);
}
@Test
void readValidWhenFileHasBadTrailingLines() throws IOException {
List<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
FileUtils.writeLines(testFile, lines);
FileUtils.writeStringToFile(testFile, "\n0.0.3.20340\nfoobar\n", CsvBalanceFileReader.CHARSET, true);
StreamFileData streamFileData = StreamFileData.from(testFile);
AccountBalanceFile accountBalanceFile = balanceFileReader.read(streamFileData);
assertAccountBalanceFile(accountBalanceFile);
verifySuccess(testFile, accountBalanceFile, 2);
}
@Test
void readValidWhenFileHasLinesWithDifferentShardNum() throws IOException {
List<String> lines = FileUtils.readLines(balanceFile, CsvBalanceFileReader.CHARSET);
FileUtils.writeLines(testFile, lines);
long otherShard = mirrorProperties.getShard() + 1;
FileUtils.writeStringToFile(
testFile,
String.format("\n%d,0,3,340\n%d,0,4,340\n", otherShard, otherShard),
CsvBalanceFileReader.CHARSET,
true);
StreamFileData streamFileData = StreamFileData.from(testFile);
AccountBalanceFile accountBalanceFile = balanceFileReader.read(streamFileData);
assertAccountBalanceFile(accountBalanceFile);
verifySuccess(testFile, accountBalanceFile, 2);
}
@Test
void supports() {
StreamFileData streamFileData = StreamFileData.from(balanceFile);
assertThat(balanceFileReader.supports(streamFileData)).isTrue();
}
@Test
void supportsInvalidWhenWrongExtension() {
StreamFileData streamFileData = StreamFileData.from("2021-03-10T16:00:00Z_Balances.csv", "");
assertThat(balanceFileReader.supports(streamFileData)).isFalse();
}
@Test
void supportsInvalidWhenEmpty() {
StreamFileData streamFileData = StreamFileData.from(balanceFile.getName(), "");
assertThat(balanceFileReader.supports(streamFileData)).isFalse();
}
@Test
void supportsInvalidWhenEmptyFirstLine() {
String versionPrefix = balanceFileReader.getVersionHeaderPrefix();
StreamFileData streamFileData = StreamFileData.from(balanceFile.getName(), '\n' + versionPrefix);
assertThat(balanceFileReader.supports(streamFileData)).isFalse();
}
@Test
void supportsInvalidWhenExceedsLineSize() {
String versionPrefix = balanceFileReader.getVersionHeaderPrefix();
String prefix = " ".repeat(CsvBalanceFileReader.BUFFER_SIZE + 1);
StreamFileData streamFileData = StreamFileData.from(balanceFile.getName(), prefix + versionPrefix);
assertThat(balanceFileReader.supports(streamFileData)).isFalse();
}
@Test
void supportsInvalidWhenInvalidFirstLine() {
StreamFileData streamFileData = StreamFileData.from(balanceFile.getName(), "junk");
assertThat(balanceFileReader.supports(streamFileData)).isFalse();
}
protected void assertAccountBalanceFile(AccountBalanceFile accountBalanceFile) {
assertThat(accountBalanceFile).isNotNull();
assertThat(accountBalanceFile.getBytes()).isNotEmpty();
assertThat(accountBalanceFile.getCount()).isEqualTo(expectedCount);
assertThat(accountBalanceFile.getConsensusTimestamp()).isEqualTo(consensusTimestamp);
assertThat(accountBalanceFile.getLoadStart()).isNotNull().isPositive();
assertThat(accountBalanceFile.getName()).isEqualTo(balanceFile.getName());
}
protected void assertFileHash(File file, AccountBalanceFile accountBalanceFile) throws Exception {
MessageDigest md = MessageDigest.getInstance(SHA_384.getName());
byte[] array = Files.readAllBytes(file.toPath());
String fileHash = DomainUtils.bytesToHex(md.digest(array));
assertThat(accountBalanceFile.getFileHash()).isEqualTo(fileHash);
}
protected void verifySuccess(File file, AccountBalanceFile accountBalanceFile, int skipLines) throws IOException {
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(new FileInputStream(file), CsvBalanceFileReader.CHARSET))) {
while (skipLines > 0) {
reader.readLine();
skipLines--;
}
List<AccountBalance> accountBalances =
accountBalanceFile.getItems().collectList().block();
var lineIter = reader.lines().iterator();
var accountBalanceIter = accountBalances.iterator();
while (lineIter.hasNext()) {
String line = lineIter.next();
line = line.trim();
if (line.isEmpty()) {
continue;
}
try {
AccountBalance expectedItem = parser.parse(line, consensusTimestamp);
AccountBalance actualItem = accountBalanceIter.next();
assertThat(actualItem).isEqualTo(expectedItem);
} catch (InvalidDatasetException ex) {
}
}
assertThat(accountBalanceIter.hasNext()).isFalse();
}
}
}
|
package com.slort.model.security;
// Application imports
import com.slort.model.EntityBase;
// Java imports
import java.util.Set;
public class OpcionMenu extends EntityBase implements Comparable {
public OpcionMenu() {
}
public OpcionMenu(Long id) {
setIdOpcionMenu(id);
}
public Long getIdOpcionMenu() {
return idOpcionmenu;
}
public String getLongDesc() {
return longDesc;
}
public String getShortDesc() {
return shortDesc;
}
public void setIdOpcionMenu(Long i) {
idOpcionmenu = i;
}
public void setLongDesc(String string) {
longDesc = string;
}
public void setShortDesc(String string) {
shortDesc = string;
}
public Set getGrupos() {
return grupos;
}
public void setGrupos(Set set) {
grupos = set;
}
private Long idOpcionmenu;
private String shortDesc;
private String longDesc;
private Set grupos;
private String link;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
@Override
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
OpcionMenu otraOpcion=(OpcionMenu)arg0;
return this.longDesc.compareToIgnoreCase(otraOpcion.longDesc);
}
}
|
package baekjoon.priority_queue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test_11286 {
//절댓값 힙
//Value 클래스 만들고 Comparator의 compare 메소드 구현해서 해결
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
PriorityQueue<Value> queue = new PriorityQueue<>(new Comparator<Value>() {
@Override
public int compare(Value o1, Value o2) {
if (o1.absoluteValue == o2.absoluteValue) {
return o1.realValue - o2.realValue;
}
return o1.absoluteValue - o2.absoluteValue;
}
});
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
int tempNumber = Integer.parseInt(br.readLine());
if (tempNumber == 0) {
if (queue.isEmpty()) {
sb.append(0+"\n");
} else {
sb.append(queue.poll().realValue+"\n");
}
} else {
queue.add(new Value(tempNumber, Math.abs(tempNumber)));
}
}
System.out.println(sb.toString());
}
static class Value {
int realValue;
int absoluteValue;
Value(int realValue, int absoluteValue) {
this.realValue = realValue;
this.absoluteValue = absoluteValue;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.