text stringlengths 10 2.72M |
|---|
package com.learn.leetcode.week4;
import com.learn.leetcode.week1.struct.ListNode;
public class SolutionReverseList {
public static ListNode reverseList(ListNode head) {
if(head == null)
return null;
ListNode before = null;
ListNode current = head;
ListNode next = current.next;
while(current.next!= null){
current.next = before;
before = current;
current = next;
next = next.next;
}
current.next = before;
return current;
}
}
|
package com.tuyenmonkey.stackoverflowmvvm.api;
import com.tuyenmonkey.stackoverflowmvvm.entity.QuestionList;
import retrofit.http.GET;
import retrofit.http.Query;
import rx.Observable;
/**
* Created by Tuyen on 2/22/16.
*/
public interface StackOverflowApi {
@GET("2.2/questions?order=desc&sort=creation&site=stackoverflow")
Observable<QuestionList> getQuestions(@Query("tagged") String tags);
}
|
/**
* Class to represent a graph
* Methods to find EC, LC, indegree and outdegree
* @author : pgr150030- Panchami Rudrakshi
reference : critical_shortest_paths_in _DAG (lecture 24 rbk notes)
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Graph implements Iterable<Vertex> {
List<Vertex> v; // vertices of graph
int size; // number of vertices in the graph
boolean directed; // true if graph is directed, false otherwise
/**
* Constructor for Graph
*
* @param size
* : int - number of vertices
*/
Graph(int size) {
this.size = size;
this.v = new ArrayList<>(size + 1);
this.v.add(0, null); // Vertex at index 0 is not used
this.directed = true; // default is undirected graph
// create an array of Vertex objects
for (int i = 1; i <= size; i++)
this.v.add(i, new Vertex(i));
}
/**
* Find vertex no. n
*
* @param n
* : int
*/
Vertex getVertex(int n) {
return this.v.get(n);
}
/**
* Method to add an edge to the graph
*
* @param a
* : int - one end of edge
* @param b
* : int - other end of edge
* @param weight
* : int - the weight of the edge
*/
void addEdge(Vertex from, Vertex to, int weight) {
Edge e = new Edge(from, to, weight);
if (this.directed) {
from.adj.add(e);
to.revAdj.add(e);
} else {
from.adj.add(e);
to.adj.add(e);
}
}
/**
* Method to create iterator for vertices of graph
*/
public Iterator<Vertex> iterator() {
Iterator<Vertex> it = this.v.iterator();
it.next(); // Index 0 is not used. Skip it.
return it;
}
// Run BFS from a given source node
// Precondition: nodes have already been marked unseen
public void bfs(Vertex src) {
src.seen = true;
src.d = 0;
Queue<Vertex> q = new LinkedList<>();
q.add(src);
System.out.println(src);
while (!q.isEmpty()) {
Vertex u = q.remove();
for (Edge e : u.adj) {
Vertex v = e.otherEnd(u);
if (!v.seen) {
v.seen = true;
v.d = u.d + 1;
q.add(v);
System.out.print(v);
}
// System.out.println(v);
}
}
}
// Check if graph is bipartite, using BFS
public boolean isBipartite() {
for (Vertex u : this) {
u.seen = false;
}
for (Vertex u : this) {
if (!u.seen) {
bfs(u);
}
}
for (Vertex u : this) {
for (Edge e : u.adj) {
Vertex v = e.otherEnd(u);
if (u.d == v.d) {
return false;
}
}
}
return true;
}
// read a directed graph using the Scanner interface
public static Graph readDirectedGraph(Scanner in) {
return readGraph(in, true);
}
// read an undirected graph using the Scanner interface
public static Graph readGraph(Scanner in) {
return readGraph(in, false);
}
public static Graph readGraph(Scanner in, boolean directed) {
// read the graph related parameters
int n = in.nextInt(); // number of vertices in the graph
int m = in.nextInt(); // number of edges in the graph
// create a graph instance
Graph g = new Graph(n);
g.directed = directed;
for (int i = 0; i < m; i++) {
int u = in.nextInt();
int v = in.nextInt();
int w = in.nextInt();
g.addEdge(g.getVertex(u), g.getVertex(v), w);
}
return g;
}
void calcIndegree(Graph g) {
for (Vertex u : g) {
u.indegree = 0;
}
for (Vertex u : g) {
for (Edge e : u.adj) {
Vertex v = e.otherEnd(u);
v.indegree = v.indegree + 1;
}
}
}
void calcOutdegree(Graph g) {
for (Vertex u : g) {
u.outdegree = 0;
}
for (Vertex u : g) {
for (Edge e : u.revAdj) {
Vertex v = e.otherEnd(u);
v.outdegree = v.outdegree + 1;
}
}
}
void CalcEc(List<Vertex> lst, Graph g) {
int num = g.size;
int s = num - 1;
Vertex s1 = this.getVertex(s);
s1.ec = 0;
for (Vertex u : g) {
u.ec = 0;
}
for (Vertex u : lst) {
for (Edge e : u.adj) {
Vertex v = e.otherEnd(u);
v.ec = Math.max(v.ec, (u.ec + v.d));
}
}
}
void CalcLc(List<Vertex> lst, Graph g) {
int num = g.size;
int t = num;
Vertex t1 = g.getVertex(t);
t1.lc = t1.ec;
for (Vertex u : g) {
u.lc = t1.lc;
}
for (Vertex u : lst) {
for (Edge e : u.revAdj) {
Vertex p = e.otherEnd(u);
p.lc = Math.min(p.lc, (u.lc - u.d));
p.slack = p.lc - p.ec;
}
}
}
static List<Vertex> DFSTop(Graph g) {
List<Vertex> stack = new LinkedList<>();
for (Vertex v : g) {
v.parent = null;
v.seen = false;
v.cno = 0;
}
int cno = 0;
for (Vertex v : g) {
if (!v.seen) {
v.cno = ++cno;
DFSVisit(v, stack);
}
}
if (stack.size() == g.size)
return stack;
else
return null;
}
/**
* Private method for DFS
*
* @param u:
* Vertex - DFS on this vertex
* @param stack:
* ArrayDeque<Vertex> - to store the topological order of
* vertices
* @throws CyclicGraphException
* exception to be thrown when cycle is encountered in the graph
*/
public static void DFSVisit(Vertex u, List<Vertex> stack) {
u.seen = true;
for (Edge e : u.adj) {
Vertex v = e.otherEnd(u);
if (!v.seen) {
v.parent = u;
v.cno = u.cno;
DFSVisit(v, stack);
}
}
stack.add(u);
}
/**
* Method for BFS - calls another method that implements BFS from first
* vertex
*
* @param g:
* Graph
*/
public static void BFS(Graph g) {
for (Vertex v : g)
v.seen = false;
for (Vertex v : g)
if (!v.seen)
BFS(g, v);
}
/**
* Method to implement the BFS
*
* @param g:
* Graph
* @param v:
* vertex - start of BFS
*/
public static void BFS(Graph g, Vertex v) {
Queue<Vertex> vertexVisited = new LinkedList<>();// visited vertices
v.seen = true;
v.d = 0;
vertexVisited.add(v);
/*
* Remove vertex from the queue and check its adjacent vertices. Mark
* the adjacent vertices and add it to the queue. Repeat till the queue
* is empty i.e all the vertices are visited.
*
* Distance of the vertices is the distance starting vertex v
*/
while (!vertexVisited.isEmpty()) {
Vertex u = vertexVisited.remove();
for (Edge e : u.adj) {
Vertex w = e.otherEnd(u);
if (!w.seen) {
w.seen = true;
w.parent = u;
w.d = u.d + 1;
vertexVisited.add(w);
}
}
}
}
}
|
package com.rhino.mailParser.betterParser;
import com.rhino.mailParser.data.UserData;
public interface WordParserInterface {
public void parse(String word,UserData data);
}
|
package kiemtra;
public class Main {
public static void main(String[] args) {
Quanlynhanvien qlnv = new Quanlynhanvien(null, null, 0);
qlnv.menu();
}
}
|
import java.awt.*;
import java.awt.geom.*;
// class that handles the rendering of wires!
public class RenderWire extends Line2D implements Visitable {
// edges of the line segment
private final Point2D a;
private final Point2D b;
public RenderWire(final Point2D a, final Point2D b) {
this.a = a;
this.b = b;
}
public double getX1() { return a.getX(); }
public double getY1() { return a.getY(); }
public double getX2() { return b.getX(); }
public double getY2() { return b.getY(); }
public void setLine(Point2D a, Point2D b) {
a.setLocation(a.getX(), a.getY());
b.setLocation(b.getX(), b.getY());
}
public void setLine(double x1, double y1, double x2, double y2) {
a.setLocation(x1, y1);
b.setLocation(x2, y2);
}
public Rectangle2D getBounds2D() {
return new Rectangle2D.Double(
a.getX() < b.getX()? a.getX() : b.getX(),
a.getY() < b.getY()? a.getY() : b.getY(),
a.getX() < b.getX()? b.getX() - a.getX() : a.getX() - b.getX(),
a.getY() < b.getY()? b.getY() - a.getY() : a.getY() - b.getY());
}
public final Point2D getP1() { return a; }
public final Point2D getP2() { return b; }
public void render(Graphics2D g) {
g.draw(this);
g.fillOval((int)getX1() - 3, (int)getY1() - 3, 6, 6);
g.fillOval((int)getX2() - 3, (int)getY2() - 3, 6, 6);
}
public boolean intersectsLine(RenderWire rw) {
return super.intersectsLine(rw) &&
!getP1().equals(rw.getP1()) && !getP1().equals(rw.getP2()) &&
!getP2().equals(rw.getP1()) && !getP2().equals(rw.getP2());
}
public String accept(Visitor visitor){
return visitor.visit(this);
}
}
|
package com.springJWT_Trksh.model;
import javax.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name="roller")
public class KisiRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
private ERoller name;
public KisiRole(ERoller name) {
this.name = name;
}
}
|
package net.droidlabs.viking.bindings.map.listeners;
import com.google.android.gms.maps.model.Marker;
import net.droidlabs.viking.bindings.map.managers.MarkerManager;
import net.droidlabs.viking.bindings.map.models.BindableMarker;
import net.droidlabs.viking.bindings.map.adapters.MarkerClickAdapter;
public class MarkerClickListener<T> extends MarkerClickAdapter<BindableMarker<T>> {
private final MarkerManager<T> markerManager;
public MarkerClickListener(OnMarkerClickListener<BindableMarker<T>> markerClickListener,
MarkerManager<T> markerManager) {
super(markerClickListener);
this.markerManager = markerManager;
}
@Override
public BindableMarker<T> getModel(Marker marker) {
return markerManager.retrieveBindableMarker(marker);
}
}
|
package ir.madreseplus.ui.view.weekly;
import java.util.List;
import ir.madreseplus.data.model.req.Event;
import ir.madreseplus.utilities.BaseNavigator;
public interface WeeklyScheduleNavigator<T> extends BaseNavigator {
void error(Throwable throwable);
void events(List<Event> events);
}
|
package com.gaoshin.onsalelocal.osl.entity;
public enum BookmarkType {
Offer,
Search,
Store,
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Employe extends UnicastRemoteObject implements EmployeInterface {
public Employe() throws RemoteException {
super();
}
public String AddEmploye(String institut, String nom, String prenom, String cin, String tel) throws RemoteException {
String FILENAME = "C:\\Users\\Attia\\Desktop\\sar\\" + institut + ".txt";
System.out.print(FILENAME);
FileWriter fw = null;
try {
String content = "nom = " + nom + " ; prénom = " + prenom + " ; cin = " + cin + " ; téléphone = " + tel;
fw = new FileWriter(FILENAME, true);
fw.write(content + "\r\n");
fw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return "1";
}
}
public Vector SearchEmploye(String institut, String cin) throws RemoteException {
Vector<String> V = new Vector<String>();
try {
File f = new File("C:\\Users\\Attia\\Desktop\\sar\\" + institut + ".txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
String line = null;
int i = -1;
while ((line = reader.readLine()) != null) {
i++;
if (line.contains(cin)) {
System.out.println(line);
String[] parts = line.split(" ; ");
String nom1 = parts[0];
String prenom1 = parts[1];
String cin1 = parts[2];
String tel1 = parts[3];
String[] partn = nom1.split(" = ");
String[] partp = prenom1.split(" = ");
String[] partc = cin1.split(" = ");
String[] partt = tel1.split(" = ");
System.out.println(partn[1] + partp[1] + partc[1] + partt[1]);
System.out.println(i);
V.add(partn[1]);
V.add(partp[1]);
V.add(partc[1]);
V.add(partt[1]);
V.add(line);
}
}
reader.close();
} catch (IOException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
return V;
}
public String DeleteEmploye(String institut, String cin) throws RemoteException {
try {
String x = null;
Vector<String> V = new Vector<>();
V = SearchEmploye(institut, cin);
String lineToRemove = V.elementAt(4);
if (!V.isEmpty())
{
x="sucess";
String ch = institut + ".txt";
File inputFile = new File("C:\\Users\\Attia\\Desktop\\sar\\" + institut + ".txt");
File tempFile = new File("C:\\Users\\Attia\\Desktop\\sar\\tempfile.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(inputFile));
} catch (FileNotFoundException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
System.out.println("hello curent" + currentLine);
if (!trimmedLine.equals(lineToRemove)) {
System.out.println(currentLine);
writer.write(currentLine + System.getProperty("line.separator"));
}
}
} catch (IOException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
writer.close();
} catch (IOException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
reader.close();
inputFile.delete();
tempFile.renameTo(new File("C:\\Users\\Attia\\Desktop\\sar\\" + institut + ".txt"));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return "0";
}
}
catch(Exception ex) {
System.out.println(ex.getMessage()) ;
}
return "1";
}
public Vector SearchName(String institut, String nom) throws RemoteException {
Vector<String> V = new Vector<String>();
try {
File f = new File("C:\\Users\\Attia\\Desktop\\sar\\" + institut + ".txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
String line = null;
int i = -1;
while ((line = reader.readLine()) != null) {
i++;
String ch="nom = "+nom+" ;";
if (line.contains(ch)) {
System.out.println(line);
String[] splits = line.split(" ; ");
String nom1 = splits[0];
String prenom1 = splits[1];
String cin1 = splits[2];
String tel1 = splits[3];
String[] splitn = nom1.split(" = ");
String[] splitp = prenom1.split(" = ");
String[] splitc = cin1.split(" = ");
String[] splitt = tel1.split(" = ");
System.out.println(splitn[1] + splitp[1] + splitc[1] + splitt[1]);
System.out.println(i);
V.add(splitn[1]);
V.add(splitp[1]);
V.add(splitc[1]);
V.add(splitt[1]);
V.add(line);
}
}
reader.close();
} catch (IOException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
return V;
}
public String ModifEmploye(String institut,String cin,String nom,String prenom,String tel) throws RemoteException {
String ch1=DeleteEmploye(institut,cin);
String ch2=AddEmploye(institut,nom,prenom,cin,tel);
return null;
}
}
|
package Day4.UnitTesting;
/**
* Created by student on 06-May-16.
*/
public enum CoffeeType {
Expresso(10,0), LATTE(5,300),CAPPUCINO(7,100),FILTERCOFFEE(10,0);
private final int requiredBeans;
private final int requiredMilk;
CoffeeType(int requiredBeans, int requiredMilk) {
this.requiredBeans = requiredBeans;
this.requiredMilk = requiredMilk;
}
public int getRequiredBeans() {
return requiredBeans;
}
public int getRequiredMilk() {
return requiredMilk;
}
}
|
package com.itheima;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("输入一个数字");
int week=in.nextInt();
if(week<1||week>7){
System.out.println("你输入的数值范围有误");
}else if(week==1){
System.out.println("星期一");
}else if(week==2){
System.out.println("星期二");
}else if(week==3){
System.out.println("星期三");
}else if(week==4){
System.out.println("星期四");
}else if(week==5){
System.out.println("星期五");
}else if(week==6){
System.out.println("星期六");
}else if(week==7){
System.out.println("星期日");
}
}
}
|
package com.stk123.task;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class TaskRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("TaskRunner......");
}
}
|
public class transaksi {
public double saldo, saldoAwal, saldoAkhir;
public String tanggalTransaksi,type;
void transaksi (double a, double b, double c, String d, String e){
saldo = a;
saldoAwal = b;
saldoAkhir = c;
tanggalTransaksi = d;
type = e;
}
void tampil(){
System.out.println("saldo = " + saldo);
System.out.println("saldo awal = " + saldoAwal);
System.out.println("saldo akhir = " + saldoAkhir);
System.out.println("tanggal transaksi = " + tanggalTransaksi);
System.out.println("type = " + type);
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.util;
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* ZLib压缩工具
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public class ZlibUtils {
/**
* 压缩字节数组.
*
* @param array 将要压缩字节数组
* @return 压缩后的字节数组
*/
public static byte[] compress(byte[] array) {
final Deflater deflater = new Deflater();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length)) {
deflater.setInput(array);
deflater.finish();
byte[] buf = new byte[1024];
while (!deflater.finished()) {
baos.write(buf, 0, deflater.deflate(buf));
}
return baos.toByteArray();
} catch (Exception e) {
// 压缩失败,那就不压了嘛...
return array;
} finally {
deflater.end();
}
}
/**
* 解压缩.
*
* @param data 待解压的数据
* @return 解压缩后的数据
*/
public static byte[] uncompress(byte[] data) {
final Inflater decompresser = new Inflater();
try (ByteArrayOutputStream o = new ByteArrayOutputStream(data.length)) {
decompresser.reset();
decompresser.setInput(data);
byte[] buf = new byte[1024];
while (!decompresser.finished()) {
o.write(buf, 0, decompresser.inflate(buf));
}
return o.toByteArray();
} catch (Exception e) {
// 解不开那就不解了...
return data;
} finally {
decompresser.end();
}
}
}
|
package com.example.selfhelpcity.adapter;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.selfhelpcity.R;
import com.example.selfhelpcity.base.Api;
import com.example.selfhelpcity.bean.db.CommuityBean;
import java.util.List;
import comenjoy.com.imageloadlibrary.GlideUtil;
public class ReleaseAdapter extends BaseQuickAdapter<CommuityBean, BaseViewHolder> {
private Context context;
private List<String> list;
public ReleaseAdapter() {
super(R.layout.items_release);
}
@Override
protected void convert(BaseViewHolder helper, CommuityBean item) {
GlideUtil.getInstance().loadImage(mContext, Api.BASE_URL + "/images/" + item.getPicture(), R.mipmap.bsd, helper.getView(R.id.items_release_img));
helper.setText(R.id.items_community_address, item.getAddress());
helper.setText(R.id.items_roommate_standard, item.getJianjie());
helper.addOnClickListener(R.id.items_collection);
helper.setChecked(R.id.items_collection, item.isCollection());
}
}
|
package com.example.railway_lab_department.Service;
import com.example.railway_lab_department.Repository.DepartmentRepository;
import com.example.railway_lab_department.entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Transactional
public class DepartmentService {
@Autowired
private DepartmentRepository deprepo;
public DepartmentService(DepartmentRepository repository) {
deprepo = repository;
}
public List<Department> listAll() {
return deprepo.findAll();
}
public void save(Department dep) {
deprepo.save(dep);
}
public Department get(long ID) {
return deprepo.findById(ID).get();
}
public void delete(long ID) {
deprepo.deleteById(ID);
}
}
|
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
*
* 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.frostwire.gui.components.slides;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import jd.http.Browser;
import jd.http.Request;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.parser.html.Form;
import jd.parser.html.Form.MethodType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.limewire.util.FileUtils;
/**
*
* @author gubatron
* @author aldenml
*
*/
class YouTubeStreamURLExtractor {
private static Log LOG = LogFactory.getLog(YouTubeStreamURLExtractor.class);
static public final Pattern YT_FILENAME_PATTERN = Pattern.compile("<meta name=\"title\" content=\"(.*?)\">", Pattern.CASE_INSENSITIVE);
private HashMap<DestinationFormat, ArrayList<Info>> possibleconverts;
private final String youtubePageUrl;
public YouTubeStreamURLExtractor(String youtubePageUrl) {
this.youtubePageUrl = youtubePageUrl;
}
private HashMap<Integer, String[]> getLinks(final String video, final boolean prem, Browser br, int retrycount) throws Exception {
if (retrycount > 2) {
// do not retry more often than 2 time
return null;
}
// if (br == null) {
// br = this.br;
// }
br.setFollowRedirects(true);
/* this cookie makes html5 available and skip controversy check */
br.setCookie("youtube.com", "PREF", "f2=40100000");
br.getHeaders().put("User-Agent", "Wget/1.12");
br.getPage(video);
if (br.containsHTML("id=\"unavailable-submessage\" class=\"watch-unavailable-submessage\"")) {
return null;
}
final String VIDEOID = new Regex(video, "watch\\?v=([\\w_\\-]+)").getMatch(0);
boolean fileNameFound = false;
String YT_FILENAME = VIDEOID;
if (br.containsHTML("&title=")) {
YT_FILENAME = Encoding.htmlDecode(br.getRegex("&title=([^&$]+)").getMatch(0).replaceAll("\\+", " ").trim());
fileNameFound = true;
}
final String url = br.getURL();
boolean ythack = false;
if (url != null && !url.equals(video)) {
/* age verify with activated premium? */
// if (url.toLowerCase(Locale.ENGLISH).indexOf("youtube.com/verify_age?next_url=") != -1) {
// verifyAge = true;
// }
if (url.toLowerCase(Locale.ENGLISH).indexOf("youtube.com/verify_age?next_url=") != -1 && prem) {
final String session_token = br.getRegex("onLoadFunc.*?gXSRF_token = '(.*?)'").getMatch(0);
final LinkedHashMap<String, String> p = Request.parseQuery(url);
final String next = p.get("next_url");
final Form form = new Form();
form.setAction(url);
form.setMethod(MethodType.POST);
form.put("next_url", "%2F" + next.substring(1));
form.put("action_confirm", "Confirm+Birth+Date");
form.put("session_token", Encoding.urlEncode(session_token));
br.submitForm(form);
if (br.getCookie("http://www.youtube.com", "is_adult") == null) {
return null;
}
} else if (url.toLowerCase(Locale.ENGLISH).indexOf("youtube.com/index?ytsession=") != -1 || url.toLowerCase(Locale.ENGLISH).indexOf("youtube.com/verify_age?next_url=") != -1 && !prem) {
ythack = true;
br.getPage("http://www.youtube.com/get_video_info?video_id=" + VIDEOID);
if (br.containsHTML("&title=") && fileNameFound == false) {
YT_FILENAME = Encoding.htmlDecode(br.getRegex("&title=([^&$]+)").getMatch(0).replaceAll("\\+", " ").trim());
fileNameFound = true;
}
} else if (url.toLowerCase(Locale.ENGLISH).indexOf("google.com/accounts/servicelogin?") != -1) {
// private videos
return null;
}
}
/* html5_fmt_map */
if (br.getRegex(YT_FILENAME_PATTERN).count() != 0 && fileNameFound == false) {
YT_FILENAME = Encoding.htmlDecode(br.getRegex(YT_FILENAME_PATTERN).getMatch(0).trim());
fileNameFound = true;
}
final HashMap<Integer, String[]> links = new HashMap<Integer, String[]>();
String html5_fmt_map = br.getRegex("\"html5_fmt_map\": \\[(.*?)\\]").getMatch(0);
if (html5_fmt_map != null) {
String[] html5_hits = new Regex(html5_fmt_map, "\\{(.*?)\\}").getColumn(0);
if (html5_hits != null) {
for (String hit : html5_hits) {
String hitUrl = new Regex(hit, "url\": \"(http:.*?)\"").getMatch(0);
String hitFmt = new Regex(hit, "itag\": (\\d+)").getMatch(0);
String hitQ = new Regex(hit, "quality\": \"(.*?)\"").getMatch(0);
if (hitUrl != null && hitFmt != null && hitQ != null) {
hitUrl = unescape(hitUrl.replaceAll("\\\\/", "/"));
links.put(Integer.parseInt(hitFmt), new String[] { Encoding.htmlDecode(Encoding.urlDecode(hitUrl, true)), hitQ });
}
}
}
} else {
/* new format since ca. 1.8.2011 */
html5_fmt_map = br.getRegex("\"url_encoded_fmt_stream_map\": \"(.*?)\"").getMatch(0);
if (html5_fmt_map == null) {
html5_fmt_map = br.getRegex("url_encoded_fmt_stream_map=(.*?)(&|$)").getMatch(0);
if (html5_fmt_map != null) {
html5_fmt_map = html5_fmt_map.replaceAll("%2C", ",");
if (!html5_fmt_map.contains("url=")) {
html5_fmt_map = html5_fmt_map.replaceAll("%3D", "=");
html5_fmt_map = html5_fmt_map.replaceAll("%26", "&");
}
}
}
if (html5_fmt_map != null && !html5_fmt_map.contains("signature") && !html5_fmt_map.contains("sig")) {
Thread.sleep(5000);
br.clearCookies("youtube.com");
return getLinks(video, prem, br, retrycount + 1);
}
if (html5_fmt_map != null) {
String[] html5_hits = new Regex(html5_fmt_map, "(.*?)(,|$)").getColumn(0);
if (html5_hits != null) {
for (String hit : html5_hits) {
hit = unescape(hit);
String hitUrl = new Regex(hit, "url=(http.*?)(\\&|$)").getMatch(0);
String sig = new Regex(hit, "url=http.*?(\\&|$)(sig|signature)=(.*?)(\\&|$)").getMatch(2);
String hitFmt = new Regex(hit, "itag=(\\d+)").getMatch(0);
String hitQ = new Regex(hit, "quality=(.*?)(\\&|$)").getMatch(0);
if (hitUrl != null && hitFmt != null && hitQ != null) {
hitUrl = unescape(hitUrl.replaceAll("\\\\/", "/"));
if (hitUrl.startsWith("http%253A")) {
hitUrl = Encoding.htmlDecode(hitUrl);
}
String[] inst = null;
if (hitUrl.contains("sig")) {
inst = new String[] { Encoding.htmlDecode(Encoding.urlDecode(hitUrl, true)), hitQ };
} else {
inst = new String[] { Encoding.htmlDecode(Encoding.urlDecode(hitUrl, true) + "&signature=" + sig), hitQ };
}
links.put(Integer.parseInt(hitFmt), inst);
}
}
}
}
}
/* normal links */
final HashMap<String, String> fmt_list = new HashMap<String, String>();
String fmt_list_str = "";
if (ythack) {
fmt_list_str = (br.getMatch("&fmt_list=(.+?)&") + ",").replaceAll("%2F", "/").replaceAll("%2C", ",");
} else {
fmt_list_str = (br.getMatch("\"fmt_list\":\\s+\"(.+?)\",") + ",").replaceAll("\\\\/", "/");
}
final String fmt_list_map[][] = new Regex(fmt_list_str, "(\\d+)/(\\d+x\\d+)/\\d+/\\d+/\\d+,").getMatches();
for (final String[] fmt : fmt_list_map) {
fmt_list.put(fmt[0], fmt[1]);
}
if (links.size() == 0 && ythack) {
/* try to find fallback links */
String urls[] = br.getRegex("url%3D(.*?)($|%2C)").getColumn(0);
int index = 0;
for (String vurl : urls) {
String hitUrl = new Regex(vurl, "(.*?)%26").getMatch(0);
String hitQ = new Regex(vurl, "%26quality%3D(.*?)%").getMatch(0);
if (hitUrl != null && hitQ != null) {
hitUrl = unescape(hitUrl.replaceAll("\\\\/", "/"));
if (fmt_list_map.length >= index) {
links.put(Integer.parseInt(fmt_list_map[index][0]), new String[] { Encoding.htmlDecode(Encoding.urlDecode(hitUrl, false)), hitQ });
index++;
}
}
}
}
for (Integer fmt : links.keySet()) {
String fmt2 = fmt + "";
if (fmt_list.containsKey(fmt2)) {
String Videoq = links.get(fmt)[1];
final Integer q = Integer.parseInt(fmt_list.get(fmt2).split("x")[1]);
if (fmt == 40) {
Videoq = "240p Light";
} else if (q > 1080) {
Videoq = "Original";
} else if (q > 720) {
Videoq = "1080p";
} else if (q > 576) {
Videoq = "720p";
} else if (q > 360) {
Videoq = "480p";
} else if (q > 240) {
Videoq = "360p";
} else {
Videoq = "240p";
}
links.get(fmt)[1] = Videoq;
}
}
if (YT_FILENAME != null) {
links.put(-1, new String[] { YT_FILENAME });
}
return links;
}
public String getYoutubeStreamURL() throws Exception {
this.possibleconverts = new HashMap<DestinationFormat, ArrayList<Info>>();
String decryptedLink = null;
String param = youtubePageUrl;
String parameter = param.toString().replace("watch#!v", "watch?v");
parameter = parameter.replaceFirst("(verify_age\\?next_url=\\/?)", "");
parameter = parameter.replaceFirst("(%3Fv%3D)", "?v=");
parameter = parameter.replaceFirst("(watch\\?.*?v)", "watch?v");
parameter = parameter.replaceFirst("/embed/", "/watch?v=");
parameter = parameter.replaceFirst("https", "http");
Browser br = new Browser();
br.setFollowRedirects(true);
br.setCookiesExclusive(true);
br.clearCookies("youtube.com");
if (parameter.contains("watch#")) {
parameter = parameter.replace("watch#", "watch?");
}
if (parameter.contains("v/")) {
String id = new Regex(parameter, "v/([a-z\\-_A-Z0-9]+)").getMatch(0);
if (id != null)
parameter = "http://www.youtube.com/watch?v=" + id;
}
boolean prem = false;
try {
final HashMap<Integer, String[]> LinksFound = this.getLinks(parameter, prem, br, 0);
String error = br.getRegex("<div id=\"unavailable\\-message\" class=\"\">[\t\n\r ]+<span class=\"yt\\-alert\\-vertical\\-trick\"></span>[\t\n\r ]+<div class=\"yt\\-alert\\-message\">([^<>\"]*?)</div>").getMatch(0);
if (error == null)
error = br.getRegex("<div class=\"yt\\-alert\\-message\">(.*?)</div>").getMatch(0);
if ((LinksFound == null || LinksFound.isEmpty()) && error != null) {
//logger.info("Video unavailable: " + parameter);
//logger.info("Reason: " + error.trim());
return decryptedLink;
}
if (LinksFound == null || LinksFound.isEmpty()) {
if (br.getURL().toLowerCase(Locale.getDefault()).indexOf("youtube.com/get_video_info?") != -1 && !prem) {
throw new IOException("DecrypterException.ACCOUNT");
}
throw new IOException("Video no longer available");
}
/* First get the filename */
String YT_FILENAME = "";
if (LinksFound.containsKey(-1)) {
YT_FILENAME = LinksFound.get(-1)[0];
LinksFound.remove(-1);
}
final boolean fast = false;//cfg.getBooleanProperty("FAST_CHECK2", false);
//final boolean mp3 = cfg.getBooleanProperty("ALLOW_MP3", true);
final boolean mp4 = true;//cfg.getBooleanProperty("ALLOW_MP4", true);
//final boolean webm = cfg.getBooleanProperty("ALLOW_WEBM", true);
//final boolean flv = cfg.getBooleanProperty("ALLOW_FLV", true);
//final boolean threegp = cfg.getBooleanProperty("ALLOW_3GP", true);
/* http://en.wikipedia.org/wiki/YouTube */
final HashMap<Integer, Object[]> ytVideo = new HashMap<Integer, Object[]>() {
/**
*
*/
private static final long serialVersionUID = -3028718522449785181L;
{
// **** FLV *****
// if (mp3) {
// this.put(0, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Mono" });
// this.put(5, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Stereo" });
// this.put(6, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Mono" });
// }
// if (flv) {
// this.put(34, new Object[] { DestinationFormat.VIDEOFLV, "H.264", "AAC", "Stereo" });
// this.put(35, new Object[] { DestinationFormat.VIDEOFLV, "H.264", "AAC", "Stereo" });
// }
// **** 3GP *****
// if (threegp) {
// this.put(13, new Object[] { DestinationFormat.VIDEO3GP, "H.263", "AMR", "Mono" });
// this.put(17, new Object[] { DestinationFormat.VIDEO3GP, "H.264", "AAC", "Stereo" });
// }
// **** MP4 *****
if (mp4) {
this.put(18, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
this.put(22, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
this.put(37, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
//this.put(38, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" });
}
// **** WebM *****
// if (webm) {
// this.put(43, new Object[] { DestinationFormat.VIDEOWEBM, "VP8", "Vorbis", "Stereo" });
// this.put(45, new Object[] { DestinationFormat.VIDEOWEBM, "VP8", "Vorbis", "Stereo" });
// }
}
};
/* check for wished formats first */
String dlLink = "";
String vQuality = "";
DestinationFormat cMode = null;
for (final Integer format : LinksFound.keySet()) {
if (ytVideo.containsKey(format)) {
cMode = (DestinationFormat) ytVideo.get(format)[0];
vQuality = "(" + LinksFound.get(format)[1] + "_" + ytVideo.get(format)[1] + "-" + ytVideo.get(format)[2] + ")";
} else {
cMode = DestinationFormat.UNKNOWN;
vQuality = "(" + LinksFound.get(format)[1] + "_" + format + ")";
/*
* we do not want to download unknown formats at the
* moment
*/
continue;
}
dlLink = LinksFound.get(format)[0];
try {
if (fast) {
this.addtopos(cMode, dlLink, 0, vQuality, format);
} else if (br.openGetConnection(dlLink).getResponseCode() == 200) {
this.addtopos(cMode, dlLink, br.getHttpConnection().getLongContentLength(), vQuality, format);
}
} catch (final Throwable e) {
LOG.error("Error in youtube decrypt logic", e);
} finally {
try {
br.getHttpConnection().disconnect();
} catch (final Throwable e) {
}
}
}
int lastFmt = 0;
for (final Entry<DestinationFormat, ArrayList<Info>> next : this.possibleconverts.entrySet()) {
final DestinationFormat convertTo = next.getKey();
for (final Info info : next.getValue()) {
final HttpDownloadLink thislink = new HttpDownloadLink(info.link);
//thislink.setBrowserUrl(parameter);
//thislink.setFinalFileName(YT_FILENAME + info.desc + convertTo.getExtFirst());
thislink.setSize(info.size);
String name = null;
if (convertTo != DestinationFormat.AUDIOMP3) {
name = YT_FILENAME + info.desc + convertTo.getExtFirst();
name = FileUtils.getValidFileName(name);
thislink.setFileName(name);
} else {
/*
* because demuxer will fail when mp3 file already
* exists
*/
//name = YT_FILENAME + info.desc + ".tmp";
//thislink.setProperty("name", name);
}
//thislink.setProperty("convertto", convertTo.name());
//thislink.setProperty("videolink", parameter);
//thislink.setProperty("valid", true);
//thislink.setProperty("fmtNew", info.fmt);
//thislink.setProperty("LINKDUPEID", name);
if (lastFmt < info.fmt) {
decryptedLink = thislink.getUrl();
}
}
}
} catch (final IOException e) {
br.getHttpConnection().disconnect();
//logger.log(java.util.logging.Level.SEVERE, "Exception occurred", e);
return null;
}
return decryptedLink;
}
private static String unescape(final String s) {
char ch;
char ch2;
final StringBuilder sb = new StringBuilder();
int ii;
int i;
for (i = 0; i < s.length(); i++) {
ch = s.charAt(i);
switch (ch) {
case '%':
case '\\':
ch2 = ch;
ch = s.charAt(++i);
StringBuilder sb2 = null;
switch (ch) {
case 'u':
/* unicode */
sb2 = new StringBuilder();
i++;
ii = i + 4;
for (; i < ii; i++) {
ch = s.charAt(i);
if (sb2.length() > 0 || ch != '0') {
sb2.append(ch);
}
}
i--;
sb.append((char) Long.parseLong(sb2.toString(), 16));
continue;
case 'x':
/* normal hex coding */
sb2 = new StringBuilder();
i++;
ii = i + 2;
for (; i < ii; i++) {
ch = s.charAt(i);
sb2.append(ch);
}
i--;
sb.append((char) Long.parseLong(sb2.toString(), 16));
continue;
default:
if (ch2 == '%') {
sb.append(ch2);
}
sb.append(ch);
continue;
}
}
sb.append(ch);
}
return sb.toString();
}
private void addtopos(final DestinationFormat mode, final String link, final long size, final String desc, final int fmt) {
ArrayList<Info> info = this.possibleconverts.get(mode);
if (info == null) {
info = new ArrayList<Info>();
this.possibleconverts.put(mode, info);
}
final Info tmp = new Info();
tmp.link = link;
tmp.size = size;
tmp.desc = desc;
tmp.fmt = fmt;
info.add(tmp);
}
public class HttpDownloadLink {
private String url;
private long size;
private String filename;
private String displayName;
private boolean compressed;
public HttpDownloadLink(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getFileName() {
return filename;
}
public void setFileName(String name) {
this.filename = name;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isCompressed() {
return compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
}
static class Info {
public String link;
public long size;
public int fmt;
public String desc;
}
public static enum DestinationFormat {
AUDIOMP3("Audio (MP3)", new String[] { ".mp3" }), VIDEOFLV("Video (FLV)", new String[] { ".flv" }), VIDEOMP4("Video (MP4)", new String[] { ".mp4" }), VIDEOWEBM("Video (Webm)", new String[] { ".webm" }), VIDEO3GP("Video (3GP)", new String[] { ".3gp" }), UNKNOWN("Unknown (unk)",
new String[] { ".unk" }),
VIDEOIPHONE("Video (IPhone)", new String[] { ".mp4" });
private String text;
private String[] ext;
DestinationFormat(final String text, final String[] ext) {
this.text = text;
this.ext = ext;
}
public String getExtFirst() {
return this.ext[0];
}
public String getText() {
return this.text;
}
@Override
public String toString() {
return this.text;
}
}
}
|
package common.web;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
public class ResourceTester {
protected static EmbeddedJetty server = null;
protected static final String contextPath = "/bdserver";
protected static WebResource resource = null;
protected static final String Password = "password";
private static int serverRefCount = 0;
@BeforeClass
public synchronized static void setup() throws Exception {
if (server != null) {
serverRefCount++;
return;
}
server = new EmbeddedJetty();
JettyWebAppContext jwac = new JettyWebAppContext();
jwac.setResourceBase("./src/test/webapp");
jwac.setContextPath(contextPath);
jwac.setExtraClassPath("./src/test/resources,./src/main/resources");
server.addWebAppContext(jwac.getWebAppContext());
server.start();
System.out.println("Started embedded Jetty. " + server);
// Configure Logging
String logging = "org.apache.commons.logging";
System.setProperty(logging + ".Log", logging + ".impl.SimpleLog");
// System.setProperty(logging + ".logging.simplelog.showdatetime", "true");
System.setProperty(logging + ".simplelog.log.httpclient.wire", "debug");
// System.setProperty(logging + ".simplelog.log.org.apache.commons.httpclient", "debug");
DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
config.getProperties().put(
DefaultApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
Client client = ApacheHttpClient.create(config);
String uri = server.getBaseUri(contextPath);
resource = client.resource(uri);
serverRefCount++;
}
@AfterClass
public synchronized static void shutdown() throws Exception {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
serverRefCount--;
if (serverRefCount <= 0) {
try {
server.stop();
} catch (Exception e) {
e.printStackTrace();
}
server = null;
serverRefCount = 0;
}
}
});
thread.start();
}
protected void print(String msg) {
System.out.println("====================" + msg);
}
protected Builder getBuilder(String path, Object... queryParameters) {
WebResource webResource = resource.path(path);
if(queryParameters != null) {
for(int i=0; i<queryParameters.length; i=i+2) {
webResource = webResource.queryParam(queryParameters[i].toString(), queryParameters[i + 1].toString());
}
}
return webResource.header("Content-type", "text/xml;charset=utf-8").accept("text/xml;charset=utf-8");
}
protected Builder getBuilder(String path, String... queryParameters) {
WebResource webResource = resource.path(path);
if (queryParameters != null) {
for (int i = 0; i < queryParameters.length; i = i + 2) {
webResource = webResource.queryParam(queryParameters[i], queryParameters[i + 1]);
}
}
return webResource.header("Content-type", "application/json;charset=utf-8").accept("application/json;charset=utf-8");
}
protected Builder getBuilder(String path) {
WebResource webResource = resource.path(path);
return webResource.header("Content-type", "application/json;charset=utf-8").accept("application/json;charset=utf-8");
}
protected void post(String path) {
getBuilder(path).post(" ");
}
protected <T> T post(String path, Class<T> respClass) {
return getBuilder(path).post(respClass, " ");
}
protected String getCurrentTimeMillisString() {
return System.currentTimeMillis() + "";
}
} |
package com.cmm.pay.base;
public abstract class BaseAbstractAgent {
public abstract Integer getCurrentAgentId();
}
|
/*
* 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.pmm.sdgc.ws.funcional;
import com.pmm.sdgc.dao.BiometriaCadastradaDao;
import com.pmm.sdgc.dao.EscalaDao;
import com.pmm.sdgc.dao.EscalaTipoDao;
import com.pmm.sdgc.dao.EspecialidadeDao;
import com.pmm.sdgc.dao.EspecialidadeTipoDao;
import com.pmm.sdgc.dao.FuncionalDao;
import com.pmm.sdgc.dao.LotacaoDao;
import com.pmm.sdgc.dao.LotacaoSubDao;
import com.pmm.sdgc.dao.MensagemDao;
import com.pmm.sdgc.dao.OcorrenciaDescDao;
import com.pmm.sdgc.dao.SolicitacaoDao;
import com.pmm.sdgc.dao.SolicitacaoSubDao;
import com.pmm.sdgc.dao.UserLogDao;
import com.pmm.sdgc.dao.UserLoginDao;
import com.pmm.sdgc.dao.UserPermissaoAcessoDao;
import com.pmm.sdgc.model.BiometriaCadastrada;
import com.pmm.sdgc.model.EscalaTipo;
import com.pmm.sdgc.model.EspecialidadeTipo;
import com.pmm.sdgc.model.Funcional;
import com.pmm.sdgc.model.Lotacao;
import com.pmm.sdgc.model.LotacaoSub;
import com.pmm.sdgc.model.SolicitacaoSub;
import com.pmm.sdgc.model.UserLogin;
import com.pmm.sdgc.model.UserPermissaoAcesso;
import com.pmm.sdgc.ws.model.ModelBiometriaCadastradaWs;
import com.pmm.sdgc.ws.model.ModelBuscaServidorWs;
import com.pmm.sdgc.ws.model.ModelEscalaWs;
import com.pmm.sdgc.ws.model.ModelEspecialidadeWs;
import com.pmm.sdgc.ws.model.ModelFuncionalWs;
import com.pmm.sdgc.ws.model.ModelSetorWs;
import com.pmm.sdgc.ws.model.ModelLotacaoWs;
import com.pmm.sdgc.ws.model.ModelOcorrenciaDescWs;
import com.pmm.sdgc.ws.model.ModelPodeAlterarRegime;
import com.pmm.sdgc.ws.model.ModelRegimeWs;
import com.pmm.sdgc.ws.model.ModelSolicitacaoSubWs;
import com.pmm.sdgc.ws.model.ModelUserTemplatePermissaoAcessoWs;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* @author acg
*/
@Named
@Path("funcionalws")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class FuncionalWs {
@EJB
FuncionalDao daoFuncional;
@EJB
EspecialidadeTipoDao daoEspecialidadeTipo;
@EJB
EspecialidadeDao daoEspecialidade;
@EJB
LotacaoDao daoLotacao;
@EJB
LotacaoSubDao daoLotacaoSub;
@EJB
EscalaDao daoEscala;
@EJB
EscalaTipoDao daoEscalaTipo;
@EJB
SolicitacaoDao daoSolicitacao;
@EJB
SolicitacaoSubDao daoSolicitacaoSub;
@EJB
OcorrenciaDescDao daoOcoDesc;
@EJB
MensagemDao daoMensagem;
@EJB
UserLogDao daoUserLog;
@EJB
UserPermissaoAcessoDao daoUserPermissaoAcesso;
@EJB
BiometriaCadastradaDao daoBiometriaCadastrada;
@GET
@Path("getListaFuncional")
public List<Funcional> getListaFuncional(@Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("ListaFuncional", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
return daoFuncional.getFuncionais();
} catch (Exception exception) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build());
}
}
@GET
@Path("getUmFuncionalPorMatricula/{matricula}")
public Funcional getUmFuncionalPorMatricula(@PathParam("matricula") String matricula, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("UmFuncionalPorMatricula", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
Funcional funcional = daoFuncional.getUmFuncionalPorMatricula(matricula);
funcional.setPodeCriarUsuario(daoUserPermissaoAcesso.getUsuarioPodeCriarUsuario(headers.getRequestHeader("chave").get(0)));
return funcional;
} catch (Exception ex) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build());
}
}
@GET
@Path("getUmFuncionalPorId/{id}")
public ModelFuncionalWs getUmFuncionalPorId(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("UmFuncionalPorId", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
ModelFuncionalWs mfws = new ModelFuncionalWs();
mfws.setId(id);
mfws.setEspecialidades(getListaEspecialidadePorId(id, headers, request));
mfws.setLotacoes(getListaLotacaoPorId(id, headers, request));
mfws.setLotacoesSub(getListaSetorPorId(id, headers, request));
mfws.setRegimes(getListaRegimePorId(id, headers, request));
mfws.setOcorrenciaDesc(getListaOcorrenciaDesc(headers, request));
mfws.setSetoresAtivos(getListaSetorAtivoPorId(id, headers, request));
mfws.setTemUsuario(getListaFuncionalTemUsuarioPorId(id, headers, request));
mfws.setPermissoes(getListaPermissaoAcesso(id, headers, request));
//mfws.setBiometria(getBiometriaCadastrada(id, headers,request));
return mfws;
} catch (Exception ex) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build());
}
}
// @GET
// @Path("getBiometriaCadastrada/{id}")
// public BiometriaCadastrada getBiometriaCadastrada(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request){
// try {
// daoUserLog.criarLog("GetBiometriaCadastrada", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
// return daoBiometriaCadastrada.getBiometriaCadastrada(id);
// } catch (Exception ex) {
// throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build());
// }
// }
@EJB
UserLoginDao daoUserLogin;
@GET
@Path("getListaFuncionalTemUsuarioPorId/{id}")
public Boolean getListaFuncionalTemUsuarioPorId(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
Funcional funcional;
try {
daoUserLog.criarLog("ListaFuncionalTemUsuarioPorId", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
funcional = daoFuncional.getUmFuncionalPorIdFuncional(id);
UserLogin ul = daoUserLogin.getUserLoginPorCPf(funcional.getPessoa().getCpf());
if (ul == null) {
return false;
}
} catch (Exception ex) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build());
}
return true;
}
@GET
@Path("getListaSetorAtivoPorIdLotacao/{id}")
public List<ModelSetorWs> getListaSetorAtivoPorIdLotacao(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("ListaSetorAtivoPorIdLotacao", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
List<LotacaoSub> ss = daoLotacaoSub.getSetores(id);
if (ss == null) {
return null;
}
List<ModelSetorWs> lotacoesSub = ModelSetorWs.toModelLotacaoSubAtivoWs(ss);
return lotacoesSub;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
@GET
@Path("getListaFuncionalPorIdSetor/{id}")
public List<ModelSolicitacaoSubWs> getListaFuncionalPorIdSetor(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("Lista Um Funcional", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
List<SolicitacaoSub> ss = daoSolicitacaoSub.getFuncionalPorIdSetor(id);
if (ss == null) {
return null;
}
List<ModelSolicitacaoSubWs> lotacoesSub = ModelSolicitacaoSubWs.toModelSolicitacaoSubFuncionalWs(ss);
return lotacoesSub;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
@GET
@Path("getListaEspecialidadePorId/{id}")
public List<ModelEspecialidadeWs> getListaEspecialidadePorId(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
//Parte 1 - buscando as especialidades
try {
daoUserLog.criarLog("Lista Um Funcional", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
List<ModelEspecialidadeWs> especialidades = ModelEspecialidadeWs.toModelEspecialidadeWs(daoEspecialidadeTipo.getEspecialidadeTipo(id));
List<EspecialidadeTipo> especialidadeAtivas = daoEspecialidade.getEspecialidadePorId(id);
for (EspecialidadeTipo et : especialidadeAtivas) {
for (ModelEspecialidadeWs mw : especialidades) {
if (mw.getIdEspecialidade().equals(et.getId())) {
mw.setAtivo(true);
break;
}
}
}
return especialidades;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
@GET
@Path("getListaLotacaoPorId/{id}")
public List<ModelLotacaoWs> getListaLotacaoPorId(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("ListaLotacaoPorId", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
Funcional func = daoFuncional.getUmFuncionalPorIdFuncional(id);
if (func == null) {
return null;
}
//Parte 2 - Lotacao
//List<ModelLotacaoWs> lotacoes = ModelLotacaoWs.toModelLotacaoWs(daoLotacao.getLotacao());
List<ModelLotacaoWs> lotacoes = ModelLotacaoWs.toModelLotacaoWs(daoUserPermissaoAcesso.getListLotacaoUsuario(headers.getRequestHeader("chave").get(0)));
List<Lotacao> lotacaoAtivas = daoSolicitacao.getLotacaoPorId(id);
for (Lotacao l : lotacaoAtivas) {
for (ModelLotacaoWs mw : lotacoes) {
if (mw.getIdLotacao().equals(l.getId())) {
mw.setAtivo(true);
break;
}
}
}
return lotacoes;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
@GET
@Path("getListaSetorAtivoPorId/{id}")
public List<ModelSetorWs> getListaSetorAtivoPorId(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("Lista Setor Ativo Por Id", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
List<SolicitacaoSub> ss = daoSolicitacaoSub.getSolicitacaoSubPorIdAtivo(id);
if (ss == null) {
return null;
}
List<ModelSetorWs> lotacoesSub = ModelSetorWs.toModelSetorAtivoSemAtivoWs(ss);
return lotacoesSub;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
@GET
@Path("getListaPermissaoAcesso/{id}")
public List<ModelUserTemplatePermissaoAcessoWs> getListaPermissaoAcesso(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("Lista de Permissao Acesso", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
List<UserPermissaoAcesso> permissoes = daoUserPermissaoAcesso.getPermissaoAcessoDeUmFuncional(id, headers.getRequestHeader("chave").get(0));
List<ModelUserTemplatePermissaoAcessoWs> pws = new ArrayList();
for (UserPermissaoAcesso permissao : permissoes) {
ModelUserTemplatePermissaoAcessoWs mu = new ModelUserTemplatePermissaoAcessoWs();
mu.setAlterar(permissao.getAlterar());
mu.setArquivo(permissao.getUserMenu().getArquivo());
mu.setBuscar(permissao.getBuscar());
mu.setDirecao(permissao.getUserMenu().getDirecao());
mu.setExcluir(permissao.getExcluir());
mu.setIcon(permissao.getUserMenu().getIcon());
mu.setIdUserMenu(permissao.getUserMenu().getId());
mu.setIdUserTemplate(permissao.getUserTemplate().getId());
mu.setIncluir(permissao.getIncluir());
mu.setLink(permissao.getUserMenu().getLink());
mu.setListar(permissao.getListar());
mu.setMenuN1(permissao.getUserMenu().getMenuN1());
mu.setMenuN2(permissao.getUserMenu().getMenuN2());
mu.setMenuN3(permissao.getUserMenu().getMenuN3());
mu.setOrdenar(permissao.getUserMenu().getOrdenar());
mu.setPasta(permissao.getUserMenu().getPasta());
mu.setUserMenuativo(permissao.getUserMenu().getAtivo());
pws.add(mu);
}
return pws;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
@GET
@Path("getListaSetorPorId/{id}")
public List<ModelSetorWs> getListaSetorPorId(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("ListaSetorPorId", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
Funcional func = daoFuncional.getUmFuncionalPorIdFuncional(id);
if (func == null) {
return null;
}
List<LotacaoSub> lsupa = daoUserPermissaoAcesso.getListLotacaoSubUsuario(headers.getRequestHeader("chave").get(0));
//Parte 3 - Setor (SolicitacaoSub)
List<LotacaoSub> lotacoes = daoLotacaoSub.getLotacaoSub(func);
List<LotacaoSub> lsfinal = new ArrayList();
if (lsupa.isEmpty()) {
lsfinal = lotacoes;
} else {
for (LotacaoSub lsf : lotacoes) {
for (LotacaoSub lsp : lsupa) {
if (lsf.getId().equals(lsp.getId())) {
lsfinal.add(lsf);
}
}
}
}
List<ModelSetorWs> lotacoesSub = new ArrayList();
if (!(lotacoes.isEmpty())) {
//lotacoesSub= ModelSetorWs.toModelLotacaoSubWs(lotacoes);
lotacoesSub = ModelSetorWs.toModelLotacaoSubWs(lsfinal);
}
List<LotacaoSub> lotacaoSubAtivas = daoSolicitacaoSub.getLotacaoSubPorId(id);
for (LotacaoSub ls : lotacaoSubAtivas) {
for (ModelSetorWs mw : lotacoesSub) {
if (mw.getIdSetor().equals(ls.getId())) {
mw.setAtivo(true);
break;
}
}
}
return lotacoesSub;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
@GET
@Path("getListaRegimePorId/{id}")
public List<ModelRegimeWs> getListaRegimePorId(@PathParam("id") String id, @Context HttpHeaders headers, @Context HttpServletRequest request) {
Boolean naoDeuCerto = true;
try {
daoUserLog.criarLog("ListaRegimePorId", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
Funcional func = daoFuncional.getUmFuncionalPorIdFuncional(id);
if (func == null) {
return null;
}
//Parte 4 - Regime
List<ModelRegimeWs> regimes = ModelRegimeWs.toModelRegimeWs(daoEscalaTipo.getEscalaTipo(id));
List<EscalaTipo> escalaAtivas = daoEscala.getEscalaPorId(id);
for (EscalaTipo e : escalaAtivas) {
for (ModelRegimeWs mrw : regimes) {
if (mrw.getIdRegime().equals(e.getId())) {
mrw.setAtivo(true);
naoDeuCerto = false;
break;
}
}
}
//TEIIIII
if(!(escalaAtivas.isEmpty())){
if(naoDeuCerto){
regimes.add(new ModelRegimeWs(
escalaAtivas.get(0).getNomeEscalaTipo(),
"NAOPODE",
true
));
}
}
return regimes;
} catch (Exception e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());
}
}
//Lista todos tipos de Ocorrências Ativas
@GET
@Path("getListaOcorrenciaDesc")
//Parte 5 - OcorrenciaDesc
public List<ModelOcorrenciaDescWs> getListaOcorrenciaDesc(@Context HttpHeaders headers, @Context HttpServletRequest request) {
List<ModelOcorrenciaDescWs> ocorrenciasDesc = ModelOcorrenciaDescWs.toModelOcorrenciaDescWs(daoOcoDesc.getOcorrenciaDescAtivo());
try {
daoUserLog.criarLog("ListaOcorrenciaDesc", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
return ocorrenciasDesc;
} catch (Exception exception) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build());
}
}
/**
* Esse webservice altera as Lotacoes de um funcionário removendo as não
* listadas e adicionando as que nao estao no banco de dados
*
*
* @param headers
* @param lotacoes
* @return Response
* @autor Raphael
*/
@POST
@Path("postAlterarLotacao")
public Response postAlterarLotacao(@Context HttpHeaders headers, @Context HttpServletRequest request, List<ModelLotacaoWs> lotacoes) {
try {
daoUserLog.criarLog("AlterarLotacao", "Alterar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
daoFuncional.alterarLotacao(lotacoes, headers.getRequestHeader("chave").get(0));
return Response.ok().build();
} catch (Exception ex) {
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
}
}
/**
* Esse webservice altera as especialidades de um funcionário removendo as
* não listadas e adicionando as que nao estao no banco de dados
*
*
* @param headers
* @param especialidades
* @return Response
* @autor Alan
*/
@POST
@Path("postAlterarEspecialidade")
public Response postAlterarEspecialidade(@Context HttpHeaders headers, @Context HttpServletRequest request, List<ModelEspecialidadeWs> especialidades) {
try {
daoUserLog.criarLog("AlterarEspecialidade", "Alterar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
daoFuncional.alterarEspecialidade(especialidades, headers.getRequestHeader("chave").get(0));
return Response.ok().build();
} catch (Exception ex) {
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
}
}
/**
* Esse webservice altera as SolicitacoesSub de um funcionário removendo as
* não listadas e adicionando as que nao estao no banco de dados
*
*
* @param headers
* @param setores
* @return Response
* @autor Alan
*/
@POST
@Path("postAlterarSetor")
public Response postAlterarSetor(@Context HttpHeaders headers, List<ModelSetorWs> setores, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("AlterarSetor", "Alterar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
daoFuncional.alterarSetor(setores, headers.getRequestHeader("chave").get(0));
return Response.ok().build();
} catch (Exception ex) {
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
}
}
/**
* Esse webservice altera as Escalas de um funcionário removendo as não
* listadas e adicionando as que nao estao no banco de dados
*
*
* @param headers
* @param escalas
* @return Response
* @autor Raphael
*/
@POST
@Path("postAlterarRegime")
public Response postAlterarRegime(@Context HttpHeaders headers, List<ModelEscalaWs> escalas, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("AlterarRegime", "Alterar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
daoFuncional.alterarRegime(escalas, headers.getRequestHeader("chave").get(0));
return Response.ok().build();
} catch (Exception ex) {
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
}
}
@GET
@Path("getPodeAlterarRegime/{idEscala}/{idFuncional}")
public ModelPodeAlterarRegime getPodeAlterarRegime(@PathParam("idEscala") String idEscala, @PathParam("idFuncional") String idFuncional, @Context HttpHeaders headers, @Context HttpServletRequest request){
try {
daoUserLog.criarLog("getPodeAlterarRegime", "Consultar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
return daoFuncional.podeAlterarRegime(idEscala, idFuncional);
} catch (Exception ex) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build());
}
}
@GET
@Path("getListarFuncionalPorNomeMatriculaCpf/{nome: [^/]*?}/{matricula: [^/]*?}/{cpf: [^/]*?}")
public List<ModelBuscaServidorWs> getListarFuncionalPorNomeMatriculaCpf(@PathParam("nome") String nome, @PathParam("matricula") String matricula, @PathParam("cpf") String cpf, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("ListarFuncionalPorNomeMatriculaCpf", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
List<ModelBuscaServidorWs> bf = daoFuncional.getFuncionalMult(nome, matricula, cpf, headers.getRequestHeader("chave").get(0));
return bf;
} catch (Exception ex) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build());
}
}
@GET
@Path("getBiometriaCadastrada/{cpf}")
public ModelBiometriaCadastradaWs getBiometriaCadastrada(@PathParam("cpf") String cpf, @Context HttpHeaders headers, @Context HttpServletRequest request) {
try {
daoUserLog.criarLog("ListaMarcacaoPonto", "Listar", headers.getRequestHeader("chave").get(0), request.getPathInfo(), headers.getRequestHeader("appv").get(0), request.getRemoteAddr());
return ModelBiometriaCadastradaWs.toModelBiometriaCadastradaWs(daoBiometriaCadastrada.getBiometriaCadastrada(cpf));
} catch (Exception exception) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build());
}
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE file for licensing information.
*/
package pl.edu.icm.unity.saml.idp;
import pl.edu.icm.unity.types.basic.Attribute;
import xmlbeans.org.oasis.saml2.assertion.AttributeType;
/**
* Defines mappings of Unity attributes to and from SAML attributes.
* TODO - only Unity->SAML is supported for now. In future the whole attribute mapping must be refactored and enhanced.
* @author K. Benedyczak
*/
public interface SamlAttributeMapper
{
public boolean isHandled(Attribute<?> unityAttribute);
public AttributeType convertToSaml(Attribute<?> unityAttribute);
/*
public boolean isHandled(AttributeType samlAttribute);
public Attribute<?> convertToUnity(AttributeType samlAttribute);
*/
}
|
package gov.nih.nci.ctrp.importtrials.studyprotocolenum;
import com.fasterxml.jackson.annotation.JsonValue;
import gov.nih.nci.ctrp.importtrials.exception.ImportTrialException;
import org.apache.commons.lang3.StringUtils;
/**
* Created by chandrasekaranp on 3/20/17.
*/
public enum SamplingMethodCode {
/**
* Probability Sample.
*/
PROBABILITY_SAMPLE("Probability Sample"),
/**
* Non-Probability Sample.
*/
NON_PROBABILITY_SAMPLE("Non-Probability Sample");
private String code;
/**
* Constructor for SamplingMethodCode.
* @param code
*/
private SamplingMethodCode(String code) {
this.code = code;
}
/**
* @return code coded value of enum
*/
@JsonValue
public String getCode() {
return code;
}
/**
*
* @param code code
* @return SamplingMethodCode
*/
public static SamplingMethodCode getByCode(String code) throws ImportTrialException {
if (StringUtils.isNotBlank(code)) {
SamplingMethodCode[] codes = SamplingMethodCode.values();
for (SamplingMethodCode samplingMethodCode : codes)
if (StringUtils.equalsIgnoreCase(code, samplingMethodCode.getCode()))
return samplingMethodCode;
throw new ImportTrialException("The ClinicalTrials.gov sampling method code value does not correspond to a valid CTRP code: "
+ code);
}
return null;
}
}
|
package mistaomega.jahoot.gui;
import mistaomega.jahoot.client.Client;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* This is the gameplay UI
* The user will select a button within the allotted time
* This controller will send the answer selected back to the client class, which then processes the response
*
* @author Jack Nash
* @version 1.0
*/
public class ClientMainUI extends UserInterfaceControllerClass {
private final Client client;
private ArrayList<String> colorList;
private ArrayList<JPanel> panels;
private JPanel mainPanel;
private JPanel answerPane1;
private JPanel answerPane2;
private JPanel answerPane3;
private JPanel answerPane4;
private JTextField tfQuestion;
private JButton btnAnswer2;
private JButton btnAnswer1;
private JButton btnAnswer3;
private JButton btnAnswer4;
private JTextField tfTimeLeft;
/**
* constructor
*
* @param client Instance of the Client
*/
public ClientMainUI(Client client) {
super(new JFrame("Game Interface"));
this.client = client;
initListeners();
btnAnswer1.addActionListener(e -> client.answerQuestion(0));
}
/**
* listeners set here
*/
public void initListeners() {
btnAnswer1.addActionListener(e -> client.answerQuestion(0));
btnAnswer2.addActionListener(e -> client.answerQuestion(1));
btnAnswer3.addActionListener(e -> client.answerQuestion(2));
btnAnswer4.addActionListener(e -> client.answerQuestion(3));
}
/**
* Entry function
*/
public void run() {
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(800, 800);
frame.setVisible(true);
}
/**
* Randomly sets the button panel colours
*/
public void setPanelColors() {
Random rnd = new Random();
for (JPanel panel : panels) {
int index = rnd.nextInt(colorList.size());
panel.setBackground(Color.decode(colorList.get(index)));
colorList.remove(index);
}
}
/**
* Adds information to the question buttons
*
* @param questionTitle Title of the Question
* @param answers List of answers to the question
*/
public void addQuestion(String questionTitle, List<String> answers) {
SwingUtilities.invokeLater(() -> {
tfQuestion.setText(questionTitle);
btnAnswer1.setText(answers.get(0));
btnAnswer2.setText(answers.get(1));
btnAnswer3.setText(answers.get(2));
btnAnswer4.setText(answers.get(3));
});
}
/**
* Sets remaining time left
*
* @param timeLeft How much time is left
*/
public void setTfTimeLeft(String timeLeft) {
tfTimeLeft.setText("Time left: " + timeLeft);
}
private void createUIComponents() {
// TODO: place custom component creation code here
colorList = new ArrayList<>(Arrays.asList(JahootColors.JAHOOTBLUE.getHex(), JahootColors.JAHOOTLIME.getHex(), JahootColors.JAHOOTORANGE.getHex(), JahootColors.JAHOOTPINK.getHex()));
panels = new ArrayList<>();
answerPane1 = new JPanel();
answerPane2 = new JPanel();
answerPane3 = new JPanel();
answerPane4 = new JPanel();
panels.add(answerPane1);
panels.add(answerPane2);
panels.add(answerPane3);
panels.add(answerPane4);
setPanelColors();
}
}
|
package io.github.ihongs.serv.matrix;
import io.github.ihongs.Cnst;
import io.github.ihongs.Core;
import io.github.ihongs.HongsException;
import io.github.ihongs.HongsExemption;
import io.github.ihongs.action.ActionHelper;
import io.github.ihongs.action.FormSet;
import io.github.ihongs.db.DB;
import io.github.ihongs.db.Model;
import io.github.ihongs.db.Table;
import io.github.ihongs.dh.search.SearchEntity;
import io.github.ihongs.util.Dawn;
import io.github.ihongs.util.Dict;
import io.github.ihongs.util.Syno;
import io.github.ihongs.util.Synt;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BooleanClause;
/**
* 数据存储模型
*
* <pre>
* 错误代码:
* matrix.form.not.exists=表单配置文件不存在
* matrix.wait.one.second=等会儿, 不要急
* matrix.item.is.removed=记录已被删除了
* matrix.node.not.exists=找不到恢复起源
* matrix.node.is.current=这已是最终记录
* matrix.rev.unsupported=资源不支持恢复
* </pre>
*
* @author Hongs
*/
public class Data extends SearchEntity {
/**
* 分区字段名
*/
public static final String PART_ID_KEY = "pd";
protected final String conf ;
protected final String form ;
private String userId = null;
private Set<String> nmCols = null;
private Set<String> wdCols = null;
private Set<String> skCols = null;
/**
* 数据实例基础构造方法
* @param conf 当前配置文件
* @param form 当前表单名称
*/
protected Data(String conf, String form) {
super(null, null, null);
this.conf = conf;
this.form = form;
}
/**
* 获取实例
*
* <pre>
* 配置如指定 db-class 则调用类的:
* getInstance(conf, form)
* getInstance()
* new Xxxx ()
* 此类必须是 Data 的子类.
* 存在以上任一方法即返回,
* 首个需自行维护生命周期,
* 后两个交由 Core 作存取.
* </pre>
*
* <pre>
* 错误代码:
* 821 找不到对应的类
* 822 构建方法不可用
* 823 构建实例不成功
* 910 配置文件不存在
* 912 表单信息不存在
* </pre>
*
* @param conf
* @param form
* @return
* @throws HongsException 表单获取失败
* @throws HongsExemption 实例构建失败
* @throws ClassCastException 不是 Data 的子类
*/
public static Data getInstance(String conf , String form) throws HongsException {
// 外部指定
Map dict = FormSet.getInstance(conf).getForm(form);
String name = ( String ) Dict.get(dict, null, "@", "db-class");
if (name != null && !name.isEmpty() && !name.equals(Data.class.getName( ))) {
Class klass ;
try {
klass = Class.forName (name);
} catch (ClassNotFoundException e) {
throw new HongsExemption(821,"Can not find class by name '"+name+"'.");
}
try {
return (Data) klass
.getMethod("getInstance", new Class [] {String.class, String.class})
.invoke ( null , new Object[] { conf , form });
} catch (NoSuchMethodException ex) {
return (Data) Core.getInstance(klass);
} catch (InvocationTargetException ex) {
Throwable ta = ex.getCause( );
// 调用层级过多, 最好直接抛出
if (ta instanceof StackOverflowError) {
throw (StackOverflowError) ta;
}
throw new HongsExemption(823,"Can not call '"+name+".getInstance'",ta);
} catch ( IllegalArgumentException ex) {
throw new HongsExemption(823,"Can not call '"+name+".getInstance'",ex);
} catch ( IllegalAccessException ex) {
throw new HongsExemption(823,"Can not call '"+name+".getInstance'",ex);
} catch ( SecurityException se) {
throw new HongsExemption(822,"Can not call '"+name+".getInstance'",se);
}
}
// 默认构造
Data inst;
Core core = Core.getInstance();
name = Data.class.getName() +":"+ conf +"."+ form;
if (core.containsKey(name)) {
inst = (Data) core.got(name);
} else {
inst = new Data (conf, form);
core.put ( name, inst );
}
return inst;
}
public Model getModel() throws HongsException {
String tn = Synt.declare(getParams().get("db-model"), "matrix.data");
if ("".equals(tn) || "none".equals(tn)) {
return null;
}
return DB.getInstance("matrix").getModel(tn);
}
public Table getTable() throws HongsException {
String tn = Synt.declare(getParams().get("db-table"), "matrix.data");
if ("".equals(tn) || "none".equals(tn)) {
return null;
}
return DB.getInstance("matrix").getTable(tn);
}
/**
* 获取参数
* 另一方法非常可能需要覆盖,
* 故提供此方法以便从基类调,
* 未设时抛出 NullPointerException
* @return
*/
protected final Map gotParams() {
return super . getParams();
}
/**
* 获取字段
* 另一方法非常可能需要覆盖,
* 故提供此方法以便从基类调,
* 未设时抛出 NullPointerException
* @return
*/
protected final Map gotFields() {
return super . getFields();
}
/**
* 获取参数
* 取不到则会尝试先获取字段.
* @return
*/
@Override
public Map getParams() {
try {
return gotParams();
}
catch (NullPointerException ex) {
getFields();
return gotParams();
}
}
/**
* 获取字段
* 当前表单不在管理区之内时,
* 会用当前表单覆盖管理表单,
* 配置文件不存在则抛出异常 404
* @return
*/
@Override
public Map getFields() {
try {
return gotFields();
}
catch (NullPointerException ex) {
// 使用超类管理字段
// 拿不到就进行填充
}
/**
* 字段以 centra/data 的字段为基础
* 但可在 centre/data 重设部分字段
*
* 配置文件不得放在资源包里面
* 此处会校验表单文件是否存在
*/
Map fields = null;
Map fieldx = null;
String cnf = conf;
do {
try {
fields = FormSet.getInstance(cnf).getForm(form);
} catch (HongsException ex) {
if (ex.getErrno() != 910
&& ex.getErrno() != 912) { // 非表单缺失
throw ex.toExemption();
}
break;
}
if (fields == null) {
break;
}
cnf = getBgConf( );
if ( cnf == null) {
break;
}
try {
fieldx = FormSet.getInstance(cnf).getForm(form);
} catch (HongsException ex) {
if (ex.getErrno() != 910
&& ex.getErrno() != 912) { // 非表单缺失
throw ex.toExemption();
}
break;
}
/**
* 注意:
* 1. 不可破坏原始配置
* 2. 当前的覆盖后台的
*/
Map fieldz = new LinkedHashMap(fieldx);
fieldz.putAll (fields);
fields = /**/ fieldz ;
// 3. 表单参数可被重写, 2019/08/10
Map params = (Map) fields .get( "@" );
Map paramx = (Map) fieldx .get( "@" );
if ( null != params && null != paramx) {
paramx = new LinkedHashMap(paramx);
paramx.putAll (params);
fields.put("@",paramx);
}
} while ( false );
if ( null == fields) {
throw new HongsExemption(910, "Data form '"+conf+"."+form+"' is not exists")
.setLocalizedContent("matrix.form.not.exists")
.setLocalizedContext("matrix");
}
setFields(fields);
return fields ;
}
/**
* 获取背景
* 当前表单不在管理区之内时,
* 会用当前表单覆盖管理表单,
* 此可获取对内配置, 用于 getFields
* @return
*/
protected String getBgConf() {
if ( ! conf.startsWith("centre/") ) {
return null;
}
return "centra/"+ conf.substring(7);
}
@Override
public String getDbPath() {
try {
return super.getDbPath();
}
catch (NullPointerException ex) {
// Will build the path.
}
String path = Synt.asString(getParams().get("db-path"));
// 按配置构建路径
if (path == null || path.isEmpty()) {
if (conf.startsWith("centra/")
|| conf.startsWith("centre/")) {
path = "matrix/"+ conf.substring(7) +"/"+ form ;
} else {
path = conf +"/"+ form;
}
}
// 进一步处理路径
Map m = new HashMap();
m.put("SERVER_ID", Core.SERVER_ID);
m.put("CORE_PATH", Core.CORE_PATH);
m.put("DATA_PATH", Core.DATA_PATH);
path = Syno.inject(path, m);
if ( ! new File(path).isAbsolute())
path = Core.DATA_PATH +"/lucene/"+ path;
setDbPath(path);
return path;
}
@Override
public String getDbName() {
try {
return super.getDbName();
}
catch (NullPointerException ex) {
// Will build the name.
}
String name = Synt.asString(getParams().get("db-name"));
// 按配置构建路径
if (name == null || name.isEmpty()) {
if (conf.startsWith("centra/")
|| conf.startsWith("centre/")) {
name = "matrix/"+ conf.substring(7) +"."+ form ;
} else {
name = conf +"."+ form;
}
}
setDbName(name);
return name;
}
public String getFormId() {
String code = Synt.asString(getParams().get("form_id"));
// 默认同表单名称
if (code == null || code.isEmpty()) {
code = form;
}
return code;
}
public String getPartId() {
String code = Synt.asString(getParams().get("part_id"));
return code;
}
public String getUserId() {
if ( null == userId ) {
try {
userId = (String) ActionHelper.getInstance()
. getSessibute(Cnst.UID_SES);
} catch (UnsupportedOperationException e ) {
throw new NullPointerException("Call setUserId first");
}
if ( null == userId ) {
throw new NullPointerException("Call setUserId first");
}
}
return userId;
}
public void setUserId(String cuId) {
userId = cuId;
}
/**
* 删除记录
* @param rd
* @return
* @throws HongsException
*/
@Override
public int delete(Map rd) throws HongsException {
Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet());
permit(rd , ids , 1096);
int c = 0;
for(String id : ids) {
c+= del(id , rd );
}
return c;
}
/**
* 恢复记录
* @param rd
* @return
* @throws HongsException
*/
public int revert(Map rd) throws HongsException {
Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet());
// permit(rd , ids , 1096);
int c = 0;
for(String id : ids) {
c+= rev(id , rd );
}
return c;
}
/**
* 添加记录
* @param rd
* @return
* @throws HongsException
*/
@Override
public String add(Map rd) throws HongsException {
String id = Core.newIdentity();
Map dd = rd;
// 构建文档对象, 会重组 name,word 的取值, 用于下方记录
dd.put(Cnst.ID_KEY , id);
Document dc = padDoc(dd);
// 保存到数据库
Table table = getTable();
if (table != null) {
String fid = getFormId();
String uid = getUserId();
long ctime = System.currentTimeMillis() / 1000;
Map nd = new HashMap();
nd.put("ctime", ctime);
nd.put("etime", 0 );
nd.put("state", 1 );
nd.put( "id", id );
nd.put("form_id", fid);
nd.put("user_id", uid);
// 数据快照和日志标题
nd.put("data", Dawn.toString(dd, true));
nd.put("name", cutText(dd, "name"));
// 操作备注和终端代码
if (rd.containsKey("memo")) {
nd.put("memo", cutText(rd, "memo"));
}
if (rd.containsKey("meno")) {
nd.put("meno", cutText(rd, "meno"));
}
table.insert(nd);
}
// 保存到索引库
setDoc(id, dc);
return id;
}
/**
* 保存记录
*
* 注意:
* 更新不产生新节点,
* 仅供内部持续补充.
*
* @param id
* @param rd
* @return
* @throws HongsException
*/
@Override
public int set(String id, Map rd) throws HongsException {
// 合并新旧数据
int i = 0;
// int t = 2;
Map dd = get(id);
// if (dd.isEmpty()) t = 1;
Map<String,Map> fs = getFields();
for(String fn : fs . keySet( ) ) {
if ( "id". equals(fn)) {
dd.put(fn , id);
} else
if (rd.containsKey(fn)) {
Object fr = rd.get(fn);
Object fo = dd.get(fn);
dd.put(fn , fr);
// 跳过环境字段, 比如修改时间
if (! canSkip(fn,fr,fo)) {
i ++;
}
}
}
// 无更新不存储
if (i == 0) {
return 0;
}
// 构建文档对象, 会重组 name,word 的取值, 用于下方记录
dd.put(Cnst.ID_KEY , id);
Document dc = padDoc(dd);
// 保存到数据库
Table table = getTable();
if (table != null) {
String fid = getFormId();
String uid = getUserId();
long ctime = System.currentTimeMillis() / 1000;
Object[] param = new String[] {id, fid, "0"};
String where = "`id`=? AND `form_id`=? AND `etime`=?";
/**
* 此类里的提交方法并不会将对应的操作记录数据进行提交,
* 好在关系数据库事务内可查到前面插入但还未提交的记录.
*/
Map nd = table.fetchCase()
.filter( where,param )
.select("ctime,state")
.getOne( );
if (nd.isEmpty()) {
nd.put("ctime", ctime);
nd.put("etime", 0 );
nd.put("state", 1 );
nd.put( "id", id );
nd.put("form_id", fid);
nd.put("user_id", uid);
} else {
if (Synt.declare(nd.get("state"), 0 ) == 0 ) {
throw new HongsException(404, "Data item '"+id+"' is removed in "+getDbName())
.setLocalizedContent("matrix.item.is.removed")
.setLocalizedContext("matrix");
}
}
// 数据快照和日志标题
nd.put("data", Dawn.toString(dd, true));
nd.put("name", cutText(dd, "name"));
// 操作备注和终端代码
if (rd.containsKey("memo")) {
nd.put("memo", cutText(rd, "memo"));
}
if (rd.containsKey("meno")) {
nd.put("meno", cutText(rd, "meno"));
}
if (nd.containsKey("etime") == false ) {
table.update(nd, where, param);
} else {
table.insert(nd);
}
}
// 保存到索引库
setDoc(id, dc);
return 1;
}
/**
* 保存记录
*
* 注意:
* 每次都产生新节点,
* 有则更新无则添加.
*
* @param id
* @param rd
* @return 有更新为 1, 无更新为 0
* @throws HongsException
*/
@Override
public int put(String id, Map rd) throws HongsException {
// 合并新旧数据
int i = 0;
int t = 2;
Map dd = get(id);
if (dd.isEmpty()) t = 1;
Map<String,Map> fs = getFields();
for(String fn : fs . keySet( ) ) {
if ( "id". equals(fn)) {
dd.put(fn , id);
} else
if (rd.containsKey(fn)) {
Object fr = rd.get(fn);
Object fo = dd.get(fn);
dd.put(fn , fr);
// 跳过环境字段, 比如修改时间
if (! canSkip(fn,fr,fo)) {
i ++;
}
}
}
// 无更新不存储
if (i == 0) {
return 0;
}
// 构建文档对象, 会重组 name,word 的取值, 用于下方记录
dd.put(Cnst.ID_KEY , id);
Document dc = padDoc(dd);
// 保存到数据库
Table table = getTable();
if (table != null) {
String fid = getFormId();
String uid = getUserId();
long ctime = System.currentTimeMillis() / 1000;
Object[] param = new String[] {id, fid, "0"};
String where = "`id`=? AND `form_id`=? AND `etime`=?";
//** 检查记录状态 **/
if (t == 2) {
Map od = table.fetchCase()
.filter( where,param )
.select("ctime,state")
.getOne( );
if (! od.isEmpty()) {
if (Synt.declare(od.get("state"), 0 ) == 0 ) {
throw new HongsException(404, "Data item '"+id+"' is removed in "+getDbName())
.setLocalizedContent("matrix.item.is.removed")
.setLocalizedContext("matrix");
}
if (Synt.declare(od.get("ctime"), 0L ) >= ctime) {
throw new HongsException(400, "Wait 1 second to put '"+id+"' in "+getDbName())
.setLocalizedContent("matrix.wait.one.second")
.setLocalizedContext("matrix");
}
}
} else {
Map od = table.fetchCase()
.filter( where,param )
.select("ctime,state,data")
.getOne( );
if (! od.isEmpty()) {
if (Synt.declare(od.get("state"), 0 ) == 0 ) {
throw new HongsException(404, "Data item '"+id+"' is removed in "+getDbName())
.setLocalizedContent("matrix.item.is.removed")
.setLocalizedContext("matrix");
}
if (Synt.declare(od.get("ctime"), 0L ) >= ctime) {
throw new HongsException(400, "Wait 1 second to put '"+id+"' in "+getDbName())
.setLocalizedContent("matrix.wait.one.second")
.setLocalizedContext("matrix");
}
// 用快照补全数据
Map<Object, Object> bd = (Map) Dawn.toObject( (String) od.get("data"));
for (Map.Entry et : bd.entrySet()) {
Object k = et.getKey( );
if (dd.containsKey(k)
|| !fs.containsKey(k) ) {
continue;
}
dd.put(k,et.getValue());
}
t = 2 ;
}
}
//** 保存到数据库 **/
Map ud = new HashMap();
Map nd = new HashMap();
ud.put("etime", ctime);
nd.put("ctime", ctime);
nd.put("etime", 0 );
nd.put("state", t );
nd.put( "id", id );
nd.put("form_id", fid);
nd.put("user_id", uid);
// 数据快照和日志标题
nd.put("data", Dawn.toString(dd, true));
nd.put("name", cutText(dd, "name"));
// 操作备注和终端代码
if (rd.containsKey("memo")) {
nd.put("memo", cutText(rd, "memo"));
}
if (rd.containsKey("meno")) {
nd.put("meno", cutText(rd, "meno"));
}
table.update(ud, where, param);
table.insert(nd);
}
// 保存到索引库
setDoc(id, dc);
return 1;
}
/**
* 删除记录
*
* 注意:
* 此方法不被 delete 调用,
* 重写请覆盖 del(id, rd).
*
* @param id
* @return 有更新为 1, 无更新为 0
* @throws HongsException
*/
@Override
public int del(String id) throws HongsException {
Map rd = /**/ new HashMap();
return del(id, rd);
}
/**
* 删除记录
* @param id
* @param rd
* @return 有更新为 1, 无更新为 0
* @throws HongsException
*/
public int del(String id, Map rd) throws HongsException {
Table table = getTable();
if (table == null) {
delDoc(id); return 1;
}
String fid = getFormId();
String uid = getUserId();
long ctime = System.currentTimeMillis() / 1000;
Object[] param = new String[] {id, fid, "0"};
String where = "`id`=? AND `form_id`=? AND `etime`=?";
//** 检查记录状态 **/
Map od = table.fetchCase()
.filter( where,param )
.select("ctime,state,data,name")
.getOne( );
if (od.isEmpty()) {
delDoc( id ); return 0; // 规避关系库无而搜索库有
}
if (Synt.declare(od.get("state"), 0 ) == 0 ) {
delDoc( id ); return 0; // 删除是幂等的可重复调用
}
if (Synt.declare(od.get("ctime"), 0L ) >= ctime) {
throw new HongsException(400, "Wait 1 second to del '"+id+"' in "+getDbName())
.setLocalizedContent("matrix.wait.one.second")
.setLocalizedContext("matrix");
}
//** 保存到数据库 **/
Map ud = new HashMap();
Map nd = new HashMap();
ud.put("etime", ctime);
nd.put("ctime", ctime);
nd.put("etime", 0 );
nd.put("state", 0 );
nd.put( "id", id );
nd.put("form_id", fid);
nd.put("user_id", uid);
// 拷贝快照和日志标题
nd.put("data", od.get("data"));
nd.put("name", od.get("name"));
// 操作备注和终端代码
if (rd.containsKey("memo")) {
nd.put("memo", cutText(rd, "memo"));
}
if (rd.containsKey("meno")) {
nd.put("meno", cutText(rd, "meno"));
}
table.update(ud, where, param);
table.insert(nd);
//** 从索引库删除 **/
delDoc(id);
return 1;
}
/**
* 恢复记录
* @param id
* @param rd
* @return 有更新为 1, 无更新为 0
* @throws HongsException
*/
public int rev(String id, Map rd) throws HongsException {
Table table = getTable();
if (table == null) {
throw new HongsException(405, "Data table for '"+getDbName()+"' is not exists")
.setLocalizedContent("matrix.rev.unsupported")
.setLocalizedContext("matrix");
}
String fid = getFormId();
String uid = getUserId();
long ctime = System.currentTimeMillis() / 1000 ;
long rtime = Synt.declare (rd.get("rtime"), 0L);
Object[] param = new String[] {id, fid, "0" };
String where = "`id`=? AND `form_id`=? AND `etime`=?";
Object[] para2 = new Object[] {id, fid,rtime};
String wher2 = "`id`=? AND `form_id`=? AND `ctime`=?";
//** 获取旧的数据 **/
Map od = table.fetchCase()
.filter( where, param)
.select("ctime")
.getOne( );
if (od.isEmpty()) {
// throw new HongsException(404, "Can not find current '"+id+"' in "+getDbName())
// .setLocalizedContent("matrix.wait.one.second")
// .setLocalizedContext("matrix");
} else
if (Synt.declare(od.get("ctime"), 0L ) >= ctime) {
throw new HongsException(400, "Wait 1 second to del '"+id+"' in "+getDbName())
.setLocalizedContent("matrix.wait.one.second")
.setLocalizedContext("matrix");
}
Map nd = table.fetchCase()
.filter( wher2, para2)
// .assort("ctime DESC")
.getOne( );
if (nd.isEmpty()) {
throw new HongsException(404, "Empty '"+id+"' at '"+ctime+"' in "+getDbName())
.setLocalizedContent("matrix.node.not.exists")
.setLocalizedContext("matrix");
}
// 删除时保留的是删除前的快照, 即使为最终记录仍然可以恢复
if (Synt.declare(nd.get("state"), 0 ) != 0 ) {
if (Synt.declare(nd.get("etime"), 0L ) == 0L ) {
throw new HongsException(400, "Alive '"+id+"' at '"+ctime+"' in "+getDbName())
.setLocalizedContent("matrix.node.is.current")
.setLocalizedContext("matrix");
}}
//** 保存到数据库 **/
Map ud = new HashMap();
ud.put("etime", ctime);
nd.put("ctime", ctime);
nd.put("rtime", rtime);
nd.put("etime", 0 );
nd.put("state", 3 );
nd.put("form_id", fid);
nd.put("user_id", uid);
// 操作备注和终端代码
if (rd.containsKey("memo")) {
nd.put("memo", cutText(rd, "memo"));
}
if (rd.containsKey("meno")) {
nd.put("meno", cutText(rd, "meno"));
}
table.update(ud, where, param);
table.insert(nd);
//** 保存到索引库 **/
Map dd = (Map) Dawn.toObject((String) nd.get("data"));
dd.put(Cnst.ID_KEY , id);
Document dc = padDoc(dd);
setDoc(id, dc);
return 1;
}
@Override
protected void padQry(BooleanQuery.Builder qr, Map rd) throws HongsException {
// 限定分区范围
String pd = getPartId();
if (null != pd && ! pd.isEmpty( )) {
qr.add(new TermQuery(new Term("@"+PART_ID_KEY, pd)), BooleanClause.Occur.MUST);
}
super.padQry ( qr, rd );
}
@Override
protected void padDoc(Document doc, Map map, Set rep) {
// 写入分区标识
String pd = getPartId();
if (null != pd && ! pd.isEmpty( )) {
doc.add(new StringField("@"+PART_ID_KEY, pd, Field.Store.NO));
doc.add(new StoredField(/**/PART_ID_KEY, pd));
}
/**
* 补充:
* 需写入名称和关键词
* 2019/03/23
* 存在外部只读才拼接
*/
Map<String, Map> fields = getFields();
if (fields.containsKey("name")) {
Map m = fields.get("name");
if (Synt.declare(m.get("disabled"), false)) {
map.put("name", getName(map));
}
}
if (fields.containsKey("word")) {
Map m = fields.get("word");
if (Synt.declare(m.get("disabled"), false)) {
map.put("word", getWord(map));
}
}
super.padDoc(doc, map, rep);
}
/**
* 保存中跳过的字段或取值
* 当返回 true 时跳过检查,
* 如都是 true 则不做更新.
* @param fn
* @param fr 新值
* @param fo 旧值
* @return
*/
protected boolean canSkip(String fn, Object fr, Object fo) {
if (getSkipable().contains(fn)) {
return true ;
}
if (fr == null && fo == null) {
return true ;
}
if (fr == null || fo == null) {
return false;
}
// 数字类则转为字符串进行对比
if (fr instanceof Number
|| fo instanceof Number ) {
fr = Synt.asString(fr);
fo = Synt.asString(fo);
} else
// 复杂对象用 JSON 串进行对比
if (fr instanceof Map
|| fr instanceof Collection
|| fr instanceof Object [ ]) {
fr = Dawn.toString(fr, true);
fo = Dawn.toString(fo, true);
}
return fr.equals(fo);
}
/**
* 切割字段值, 防止数据库报错
* @param dd
* @param fn
* @return
* @throws HongsException
*/
protected String cutText(Map dd, String fn)
throws HongsException {
String s = Synt.asString(dd.get(fn));
if (s == null) return null;
Map m = (Map) getTable().getFields().get(fn);
if (m == null) return null;
int k = Synt.defxult((Integer) m.get("size"), 255); // 默认字段宽 255
if (k >= s.length()) return s;
// 宽字符按长度为 2 进行切割
int l = 0, i , c;
for(i = 0; i < s.length( ); i ++ )
{
c = Character.codePointAt(s,i);
if (c >= 0 && c <= 255) {
l += 1;
} else {
l += 2;
}
if (l > k) {
s = s.substring(0 , i - 1) + "…";
break ;
}
}
return s ;
}
/**
* 获取名称串
* @param dd
* @return
*/
protected String getName(Map dd) {
StringBuilder nn = new StringBuilder();
Set < String> ns = getNameable( );
for ( String fn : ns ) {
Object fv = dd.get(fn);
if (fv == null) continue ;
if (fv instanceof Collection)
for (Object fw : (Collection) fv ) {
nn.append(fw).append(' ');
} else {
nn.append(fv).append(' ');
}
}
String nm = nn.toString().trim( );
if (! ns.contains("name")
&& 255 < nm.length( ) ) {
return nm.substring( 0, 254 ) + "…";
} else {
return nm;
}
}
/**
* 获取关键词
* @param dd
* @return
*/
protected String getWord(Map dd) {
StringBuilder nn = new StringBuilder();
Set < String> ns = getWordable( );
for ( String fn : ns ) {
Object fv = dd.get(fn);
if (fv == null) continue ;
if (fv instanceof Collection)
for (Object fw : (Collection) fv ) {
nn.append(fw).append(' ');
} else {
nn.append(fv).append(' ');
}
}
String nm = nn.toString().trim( );
if (! ns.contains("word")
&& ! ns.contains("id") ) {
return dd.get("id") +" "+ nm ;
} else {
return nm;
}
}
/**
* 增加搜索和命名未明确指定时的后备类型
* @param t
* @return
*/
@Override
public Set<String> getCaseTypes(String t) {
if ("wordable".equals(t)) {
return Synt.setOf("string", "search", "text", "textarea", "textview");
} else
if ("nameable".equals(t)) {
return Synt.setOf("string", "search", "text");
} else {
return super.getCaseTypes(t);
}
}
/**
* 存在 word 字段则为 word, 否则调 getWordable
* @return
*/
@Override
public Set<String> getRschable() {
Map fs = (Map) getFields().get("word");
if (fs != null) {
return Synt.setOf ("word");
} else {
return getWordable( /**/ );
}
}
public Set<String> getWordable() {
if (null != wdCols) {
return wdCols;
}
Map fs = (Map) getFields().get("word");
if (fs != null && !Synt.declare(fs.get("readonly"), false)) {
wdCols = Synt.setOf("word");
} else {
wdCols = getCaseNames("wordable");
if (wdCols == null
|| wdCols.isEmpty()) {
wdCols = getSrchable( );
}
wdCols.remove("word");
}
return wdCols;
}
public Set<String> getNameable() {
if (null != nmCols) {
return nmCols;
}
Map fs = (Map) getFields().get("name");
if (fs != null && !Synt.declare(fs.get("readonly"), false)) {
nmCols = Synt.setOf("name");
} else {
nmCols = getCaseNames("nameable");
// if (nmCols == null
// || nmCols.isEmpty()) {
// nmCols = getListable( );
// }
nmCols.remove("name");
}
return nmCols;
}
public Set<String> getSkipable() {
if (null != skCols) {
return skCols;
}
skCols = getCaseNames("skipable");
if (skCols == null
|| skCols.isEmpty( ) ) {
skCols = new HashSet();
skCols.add("mtime");
skCols.add("muser");
skCols.add("memo" );
skCols.add("meno" );
}
return skCols;
}
}
|
package cn.hellohao.dao;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface NoticeMapper {
String getNotice();
}
|
package com.example.activitatmvc.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.example.activitatmvc.dao.PerfilDAO;
import com.example.activitatmvc.model.Perfil;
@Controller
public class HomeController {
@Autowired
private PerfilDAO PerfilDAO;
@RequestMapping(value="/")
public ModelAndView listPerfil(ModelAndView model) throws IOException{
List<Perfil> listPerfil = PerfilDAO.list();
model.addObject("listPerfil", listPerfil);
model.setViewName("home");
return model;
}
@RequestMapping(value = "/newPerfil", method = RequestMethod.GET)
public ModelAndView newPerfil(ModelAndView model) {
Perfil newPerfil = new Perfil();
model.addObject("perfil", newPerfil);
model.setViewName("PerfilForm");
return model;
}
@RequestMapping(value = "/savePerfil", method = RequestMethod.POST)
public ModelAndView savePerfil(@ModelAttribute Perfil perfil) {
PerfilDAO.saveOrUpdate(perfil);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/deletePerfil", method = RequestMethod.GET)
public ModelAndView deletePerfil(HttpServletRequest request) {
int perfilId = Integer.parseInt(request.getParameter("id"));
PerfilDAO.delete(perfilId);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/editPerfil", method = RequestMethod.GET)
public ModelAndView editPerfil(HttpServletRequest request) {
int perfilId = Integer.parseInt(request.getParameter("id"));
Perfil perfil = PerfilDAO.get(perfilId);
ModelAndView model = new ModelAndView("PerfilForm");
model.addObject("perfil", perfil);
return model;
}
}
|
public class tempf {
}
|
package com.example.gtraderprototype.entity;
import android.util.Log;
/**
* player class that initializes the user
*/
public class Player extends Character {
public static volatile Player player = null;
/**
* initializing a player that has a default Gnatt ship
* @param name name of the player
* @param pilotPoints skill points of piloting
* @param engineerPoints skill points of engineering
* @param fighterPoints skill points of fighting
* @param traderPoints skill points of trading
*/
public Player(String name, int pilotPoints, int engineerPoints, int fighterPoints, int traderPoints){
super(name, pilotPoints, engineerPoints, fighterPoints, traderPoints, Ship.ShipType.GNATT);
player = this;
}
public Player(){
}
/**
* getting the statistics of the player
* @return player's information
*/
public static Player getPlayer(){
if (player == null){
synchronized (Player.class){
if(player == null){
player = new Player("NoName", 0, 0, 0, 0);
}
}
}
return player;
}
/**
* getting information of whether this character is a pirate or not
* @return boolean indicating this character is a pirate or not
*/
public void setPirate(boolean pirate) {
getPlayer().isPirate = pirate;
}
public String toString(){return "Player Name: " + name + ", Pilot Skill Points: " + pilotSkillPoints +
", Engineer Skill Points: " + engineerSkillPoints + ", Fighter Skill Points: " + fighterSkillPoints +
", Trader Skill Points: " + traderSkillPoints +
", Money: " + money + ", SpaceShip: "+ spaceShip.getName();}
}
|
package com.jfronny.raut.api;
import com.google.common.collect.Multimap;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.attribute.EntityAttribute;
import net.minecraft.entity.attribute.EntityAttributeModifier;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import org.apache.commons.lang3.tuple.Triple;
import java.util.HashMap;
import java.util.UUID;
public class BaseArmor extends ArmorItem {
private static final UUID[] MODIFIERS = new UUID[]{UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"),
UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"),
UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"),
UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")};
HashMap<EquipmentSlot, HashMap<EntityAttribute, Triple<String, Double, EntityAttributeModifier.Operation>>> attributes;
public BaseArmor(AttributeArmorMat material, EquipmentSlot slot) {
super(material, slot, new Item.Settings().group(ItemGroup.COMBAT));
this.attributes = material.getAttributes();
}
@Override
public Multimap<String, EntityAttributeModifier> getModifiers(EquipmentSlot slot) {
Multimap<String, EntityAttributeModifier> map = super.getModifiers(slot);
if (this.slot == slot && attributes.containsKey(this.slot)) {
HashMap<EntityAttribute, Triple<String, Double, EntityAttributeModifier.Operation>> tmp = attributes.get(slot);
for (EntityAttribute attribute : tmp.keySet()) {
Triple<String, Double, EntityAttributeModifier.Operation> mod = tmp.get(attribute);
map.put(attribute.getId(), new EntityAttributeModifier(MODIFIERS[slot.getEntitySlotId()], mod.getLeft(), mod.getMiddle(), mod.getRight()));
}
}
return map;
}
}
|
package com.alibaba.druid.bvt.support.spring;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import junit.framework.TestCase;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.spring.DruidLobCreator;
public class DruidLobCreatorTest extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setTestOnBorrow(false);
dataSource.setInitialSize(1);
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_lobCreator() throws Exception {
DruidLobCreator lobCreator = new DruidLobCreator();
Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("select 1");
lobCreator.setBlobAsBytes(ps, 1, new byte[0]);
lobCreator.setBlobAsBinaryStream(ps, 2, new ByteArrayInputStream(new byte[0]), 0);
lobCreator.setClobAsAsciiStream(ps, 3, new ByteArrayInputStream(new byte[0]), 0);
lobCreator.setClobAsCharacterStream(ps, 4, new StringReader(""), 0);
lobCreator.setClobAsString(ps, 5, "");
ps.close();
conn.close();
}
}
|
package com.chenyuwei.requestmaker;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by vivi on 2016/8/31.
*/
public abstract class RequestMaker {
public static String BASE_URl = "";
protected Context context;
private String tag;
private int failedTime = 30000;
private static RequestQueue queue;
private HashMap<String,String> map = new HashMap<>();
private ProgressDialog dialog;
public RequestMaker(Context context, Method method, String url) {
this.context = context;
setParams(map);
switch(method) {
case GET:
requestGet(url);
break;
case POST:
requestPost(url);
break;
}
}
public RequestMaker(Context context, Method method, String url, String tag) {
this.context = context;
this.tag = tag;
setParams(map);
switch(method) {
case GET:
requestGet(url);
break;
case POST:
requestPost(url);
break;
}
}
public RequestMaker(Context context, Method method, String url, boolean enableDialog) {
if (enableDialog && dialog == null){
dialog = new ProgressDialog(context);
dialog.setTitle("加载中,请稍等");
dialog.setCancelable(false);
dialog.show();
}
this.context = context;
setParams(map);
switch(method) {
case GET:
requestGet(url);
break;
case POST:
requestPost(url);
break;
}
}
public RequestMaker(Context context, Method method, String url, boolean enableDialog, String tag) {
if (enableDialog && dialog == null){
dialog = new ProgressDialog(context);
dialog.setTitle("加载中,请稍等");
dialog.setCancelable(false);
dialog.show();
}
this.context = context;
this.tag = tag;
setParams(map);
switch(method) {
case GET:
requestGet(url);
break;
case POST:
requestPost(url);
break;
}
}
public enum Method {
GET, POST
}
public static void init(Context context){
queue = Volley.newRequestQueue(context);
}
private void requestGet(String url){
final StringBuilder builderUrl = new StringBuilder();
builderUrl.append(url);
if (map.size() != 0){
for (Object object : map.entrySet()) {
Map.Entry entry = (Map.Entry) object;
String key = (String) entry.getKey();
String val = (String) entry.getValue();
builderUrl.append("&");
builderUrl.append(key);
builderUrl.append("=");
builderUrl.append(val);
if (tag != null){
Log.e("response", tag + "=>" + "param: " + key + "=" + val);
}
}
}
queue.add(new StringRequest(Request.Method.GET, BASE_URl + builderUrl.toString(), new Response.Listener<String>() {
@Override
public void onResponse(String s) {
if (dialog != null){
dialog.dismiss();
}
int state = 0;
String data = null;
try {
JSONObject response= new JSONObject(s);
state = response.getInt("state");
if (state == 0){
onError(response.getInt("code"),response.getString("error_msg"));
}
else if (state == 1){
data = response.getString("data");
onSuccess(data);
}
else {
Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
onJsonAnalysisError();
}
finally {
if (tag != null){
Log.e("response",tag + "=>"+ "url=" + BASE_URl + builderUrl.toString());
Log.e("response",tag + "=>"+ "response=" + s);
Log.e("response",tag + "=>"+ "state=" + state);
if (data != null){
Log.e("response",tag + "=>"+ "data=" + data);
}
else {
Log.e("response",tag + "=>"+ "data=" + "no data in response");
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (dialog != null){
dialog.dismiss();
}
onFail();
}
}){
@Override
public void setRetryPolicy(RetryPolicy retryPolicy) {
super.setRetryPolicy(new DefaultRetryPolicy(failedTime,0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
});
}
private void requestPost(final String url){
queue.add(new StringRequest(Request.Method.POST, BASE_URl +url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
if (dialog != null){
dialog.dismiss();
}
int state = 0;
String data = null;
try {
JSONObject response= new JSONObject(s);
state = response.getInt("state");
if (state == 0){
onError(response.getInt("code"),response.getString("error_msg"));
}
else if (state == 1){
data = response.getString("data");
onSuccess(data);
}
else {
toast("网络连接失败");
}
} catch (JSONException e) {
e.printStackTrace();
onJsonAnalysisError();
}
finally {
if (tag != null){
StringBuilder builderUrl = new StringBuilder();
builderUrl.append(url);
if (map.size() != 0){
builderUrl.append("?");
for (Object object : map.entrySet()) {
Map.Entry entry = (Map.Entry) object;
String key = (String) entry.getKey();
String val = (String) entry.getValue();
builderUrl.append(key);
builderUrl.append("=");
builderUrl.append(val);
builderUrl.append("&");
Log.e("response", tag + "=>" + "param: " + key + "=" + val);
}
builderUrl.deleteCharAt(builderUrl.length()-1);
}
Log.e("response",tag + "=>"+ "url=" + BASE_URl + builderUrl.toString());
Log.e("response",tag + "=>"+ "response=" + s);
Log.e("response",tag + "=>"+ "state=" + state);
if (data != null){
Log.e("response",tag + "=>"+ "data=" + data);
}
else {
Log.e("response",tag + "=>"+ "data=" + "no data in response");
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (dialog != null){
dialog.dismiss();
}
onFail();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return map;
}
@Override
public void setRetryPolicy(RetryPolicy retryPolicy) {
super.setRetryPolicy(new DefaultRetryPolicy(failedTime,0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
});
}
protected abstract void onSuccess(String response) throws JSONException;
protected void onJsonAnalysisError(){
if (tag != null){
toast("解析错误");
Log.e("response",tag + "=>json解析失败,onSuccuss()中的程序可能没有完全执行,请核对data中的json数据");
}
}
protected void onFail(){
toast("网络连接失败");
}
protected void onError(int code,String message){
toast(message);
}
protected void setParams(HashMap<String,String> map){
}
protected void setFailedTime(int failedTime) {
this.failedTime = failedTime;
}
private void toast(String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
private void toast(int id) {
Toast.makeText(context, context.getResources().getString(id), Toast.LENGTH_SHORT).show();
}
} |
package controllers.machineLearning.linear_logistic;
import controllers.machineLearning.all.Matrix;
import controllers.machineLearning.logistic.LogisticCost;
/**
* Created by shrestha on 11/18/2015.
*/
public class RegularizedGradient {
private double regularizedCost;
public double[][] getGradient(double[][] theta, double[][] X, double[][] y, double lambda, String algorithm){
// int col = theta[0].length;
// double thetaSum = 0;
// double[][] thetaFiltered = new double[1][col];
// for(int i=1; i<col; i++){
// thetaFiltered[0][i] = (lambda/row)*theta[0][i];
// theta[0][i] = theta[0][i] + thetaFiltered[0][i];
// }
// return theta;
Matrix matrix = new Matrix();
int thetarow = theta.length;
int row = y.length;
double cost;
double[][] grad = theta;
if(algorithm== "machineLearning/logistic"){
double[][] thetaFiltered = new double[thetarow][1];
thetaFiltered = theta;
thetaFiltered[0][0] = 0;
LogisticCost logisticCost = new LogisticCost();
cost = logisticCost.getCost(X, y, theta);
grad = logisticCost.getGrad();
double[][] costmult = matrix.multMatrix(matrix.transpose(thetaFiltered),thetaFiltered);
double a = (double) lambda/(2*row);
double[][] costmultAndlambda = matrix.matrixDivideorMultBy(costmult, a, "*");
cost = cost+costmultAndlambda[0][0];
this.regularizedCost = cost;
//calculate gradient descent
double x = (double) lambda/row;
double[][] mult = matrix.matrixDivideorMultBy(thetaFiltered, x, "*");
grad = matrix.elementwiseOp(grad, mult, "+");
}
return grad;
}
public double getRegularizedCost() {
return regularizedCost;
}
public void setRegularizedCost(double regularizedCost) {
this.regularizedCost = regularizedCost;
}
}
|
package com.contus.keerthi.myapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.contus.keerthi.myapp.Contract.MyApp;
/**
* Created by user on 24/2/17.
*/
public class NewsFragment extends Fragment {
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
public static int items = 2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_fragment,container,false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
mViewPager = (ViewPager)view.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout)view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
return view;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position)
{
case 0:
FetchNews top =new FetchNews();
Bundle args = new Bundle();
args.putString("newsType","top");
top.setArguments(args);
return top;
case 1:
FetchNews latest =new FetchNews();
Bundle bundle = new Bundle();
bundle.putString("newsType","latest");
latest.setArguments(bundle);
return latest;
case 2:
FetchNews tech =new FetchNews();
Bundle tech_args = new Bundle();
tech_args.putString("newsType","tech");
tech.setArguments(tech_args);
return tech;
}
return null;
}
@Override
public int getCount() {
return MyApp.PagerNames.NEWS_PAGER.length;
}
@Override
public CharSequence getPageTitle(int position) {
return MyApp.PagerNames.NEWS_PAGER[position];
}
}
}
|
package com.lenovohit.hcp.base.web.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.hcp.base.model.HcpRole;
import com.lenovohit.hcp.base.model.HcpRoleMenuRela;
import com.lenovohit.hcp.base.model.HcpUser;
import com.lenovohit.hcp.base.model.HcpUserRoleRela;
import com.lenovohit.hcp.base.model.Menu;
/**
* 授权管理
*
*/
@RestController
@RequestMapping("/hcp/base/auth")
public class HcpAuthRestController extends HcpBaseRestController {
@Autowired
private GenericManager<HcpUserRoleRela, String> hcpUserRoleRelaManager;
@Autowired
private GenericManager<HcpRoleMenuRela, String> hcpRoleMenuRelaManager;
/***************************** 权限-user *******************************************/
/**
* 根据角色id取关联用户
*
* @param roleId
* @return
*/
@RequestMapping(value = "/user/list/{roleId}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forUserPage(@PathVariable("roleId") String roleId) {
// HcpUser current = this.getCurrentUser();
List<?> users = hcpUserRoleRelaManager
.find("select rela.user.id from HcpUserRoleRela rela " + " where rela.role.id = ? ", roleId);
return ResultUtils.renderPageResult(users);
}
/**
* 为用户授权角色
*
* @param roleId
* @param userId
* @return
*/
@RequestMapping(value = "/user/assign/{roleId}/{userId}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forAssignUser(@PathVariable("roleId") String roleId, @PathVariable("userId") String userId) {
List<HcpUserRoleRela> relas = hcpUserRoleRelaManager
.find("from HcpUserRoleRela rela where rela.role.id = ? and rela.user.id = ? ", roleId, userId);
if (relas.size() == 1) {
return ResultUtils.renderSuccessResult();
} else if (relas.size() > 1) {
return ResultUtils.renderFailureResult();
} else {
HcpUser user = new HcpUser();
HcpRole role = new HcpRole();
user.setId(userId);
role.setId(roleId);
HcpUserRoleRela rela = new HcpUserRoleRela();
rela.setUser(user);
rela.setRole(role);
this.hcpUserRoleRelaManager.save(rela);
}
return ResultUtils.renderSuccessResult();
}
/**
* 为用户解除角色授权
*
* @param roleId
* @param userId
* @return
*/
@RequestMapping(value = "/user/unassign/{roleId}/{userId}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forUnAssignUser(@PathVariable("roleId") String roleId, @PathVariable("userId") String userId) {
List<HcpUserRoleRela> relas = hcpUserRoleRelaManager
.find("from HcpUserRoleRela rela where rela.role.id = ? and rela.user.id = ? ", roleId, userId);
if (relas.size() == 1) {
hcpUserRoleRelaManager.delete(relas.get(0));
return ResultUtils.renderSuccessResult();
} else if (relas.size() > 1) {
return ResultUtils.renderFailureResult();
}
return ResultUtils.renderSuccessResult();
}
/***************************** 权限-menu *******************************************/
/**
* 根据角色id取对应菜单
*
* @param roleId
* @return
*/
@RequestMapping(value = "/menu/list/{roleId}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forMenuList(@PathVariable("roleId") String roleId) {
List<?> users = hcpRoleMenuRelaManager
.find("select rela.menu.id from HcpRoleMenuRela rela " + " where rela.role.id = ? ", roleId);
return ResultUtils.renderPageResult(users);
}
/**
* 为角色分配菜单权限
*
* @param roleId
* @param data
* @return
*/
@RequestMapping(value = "/menu/assign/{roleId}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forAssignMenu(@PathVariable("roleId") String roleId, @RequestBody String data) {
List<?> ids = JSONUtils.deserialize(data, List.class);
List<?> relas = hcpRoleMenuRelaManager
.findBySql("SELECT ROLE_ID,MENU_ID FROM HCP_ROLE_MENU_RELA WHERE ROLE_ID = ? ", roleId);
System.out.println("新ids " + ids);
List<String> deleteIds = new ArrayList<String>();
StringBuilder deleteSql = new StringBuilder();
deleteSql.append("DELETE FROM HCP_ROLE_MENU_RELA WHERE MENU_ID IN (");
Map<String, Object> addMap = new HashMap<String, Object>();
Map<String, Object> existMap = new HashMap<String, Object>();
for (Object id : ids) {
addMap.put(id.toString(), new byte[0]);
}
for (Object obj : relas) {
Object[] rela = (Object[]) obj;
Object value = addMap.get(rela[1]);
if (value == null) {
if (deleteIds.size() > 0)
deleteSql.append(",");
deleteSql.append("'").append(rela[1]).append("'");
deleteIds.add(rela[1].toString());
}
existMap.put(rela[1].toString(), new byte[0]);
}
deleteSql.append(")");
if (deleteIds.size() > 0) {
deleteSql.append(" AND ROLE_ID = ? ");
System.out.println(deleteSql);
this.hcpRoleMenuRelaManager.executeSql(deleteSql.toString(), roleId);
}
List<HcpRoleMenuRela> creates = new ArrayList<HcpRoleMenuRela>();
for (Object id : ids) {
Object value = existMap.get(id.toString());
if (value == null) {// 新id数据库不存在
Menu menu = new Menu();
HcpRole role = new HcpRole();
menu.setId(id.toString());
role.setId(roleId);
HcpRoleMenuRela rela = new HcpRoleMenuRela();
rela.setMenu(menu);
rela.setRole(role);
creates.add(rela);
System.out.println("add " + id);
}
}
this.hcpRoleMenuRelaManager.batchSave(creates);
return ResultUtils.renderSuccessResult();
}
/**
* 为角色解除菜单授权
*
* @param roleId
* @param menuId
* @return
*/
@RequestMapping(value = "/menu/unassign/{roleId}/{menuId}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forUnAssignMenu(@PathVariable("roleId") String roleId, @PathVariable("menuId") String menuId) {
List<HcpRoleMenuRela> relas = hcpRoleMenuRelaManager
.find("from HcpRoleMenuRela rela where rela.role.id = ? and rela.menu.id = ? ", roleId, menuId);
if (relas.size() == 1) {
hcpRoleMenuRelaManager.delete(relas.get(0));
return ResultUtils.renderSuccessResult();
} else if (relas.size() > 1) {
return ResultUtils.renderFailureResult();
}
return ResultUtils.renderSuccessResult();
}
/***************************** 权限-reource *******************************************/
/**
* 根据角色id取已授权的资源
*
* @param roleId
* @return
*/
@RequestMapping(value = "/resource/list/{roleId}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forResourceList(@PathVariable("roleId") String roleId) {
List<?> users = hcpRoleMenuRelaManager
.find("select rela.menu.id from HcpRoleMenuRela rela " + " where rela.role.id = ? ", roleId);
return ResultUtils.renderPageResult(users);
}
/**
* 为角色授权资源
*
* @param roleId
* @param resourceId
* @return
*/
@RequestMapping(value = "/resource/assign/{roleId}/{resourceId}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forAssignResource(@PathVariable("roleId") String roleId,
@PathVariable("resourceId") String resourceId) {
List<HcpRoleMenuRela> relas = hcpRoleMenuRelaManager
.find("from HcpRoleMenuRela rela where rela.role.id = ? and rela.menu.id = ? ", roleId, resourceId);
if (relas.size() == 1) {
return ResultUtils.renderSuccessResult();
} else if (relas.size() > 1) {
return ResultUtils.renderFailureResult();
} else {
Menu menu = new Menu();
HcpRole role = new HcpRole();
menu.setId(resourceId);
role.setId(roleId);
HcpRoleMenuRela rela = new HcpRoleMenuRela();
rela.setMenu(menu);
rela.setRole(role);
this.hcpRoleMenuRelaManager.save(rela);
}
return ResultUtils.renderSuccessResult();
}
/**
* 解除角色资源授权
*
* @param roleId
* @param reourceId
* @return
*/
@RequestMapping(value = "/reource/unassign/{roleId}/{reourceId}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forUnAssignResource(@PathVariable("roleId") String roleId,
@PathVariable("reourceId") String reourceId) {
List<HcpRoleMenuRela> relas = hcpRoleMenuRelaManager
.find("from HcpRoleMenuRela rela where rela.role.id = ? and rela.menu.id = ? ", roleId, reourceId);
if (relas.size() == 1) {
hcpRoleMenuRelaManager.delete(relas.get(0));
return ResultUtils.renderSuccessResult();
} else if (relas.size() > 1) {
return ResultUtils.renderFailureResult();
}
return ResultUtils.renderSuccessResult();
}
public String ObjectIsNull(Object obj) {
if (obj == null)
return "";
return obj.toString();
}
}
|
package com.example.jdktest.advice;
import com.example.jdktest.common.CommonResult;
import com.example.jdktest.constant.ServiceExceptionEnum;
import com.example.jdktest.execption.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@RestControllerAdvice(basePackages = "com.example.jdktest.controller")
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 服务器类型异常,
* @param request
* @param ex
* @return
*/
@ExceptionHandler(value = ServiceException.class)
public CommonResult ServiceExceptionHandler(HttpServletRequest request , ServiceException ex){
logger.debug("[ServiceException]",ex);
return CommonResult.error(ex.getCode(),ex.getMessage());
}
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(HttpServletRequest request , Exception ex){
logger.debug("[Exception]",ex);
return CommonResult.error(ServiceExceptionEnum.SYS_ERROR.getCode(),
ServiceExceptionEnum.SYS_ERROR.getMessage());
}
}
|
public class Gold implements Membership {
private static Gold instance = new Gold();
public static Gold getInstance() {
return instance;
}
@Override
public double getDiscount() {
return 0.90;
}
public String toString() {
return "Gold";
}
}
|
package hua;
public class Storage {
private String variety;
private int packages_number;
public String getVariety() {
return variety;
}
public void setVariety(String variety) {
this.variety = variety;
}
public int getPackages_number() {
return packages_number;
}
public void setPackages_number(int packages_number) {
this.packages_number = packages_number;
}
}
|
package Operacional;
public class Mostrador {
private String display;
public boolean mostrarMensagem(String str, int tempo)
{
this.display = str;
//Thread.currentThread().sleep(temp*1000);
return true;
}
public boolean mostrarMensagem(String str)
{
this.display = str;
return true;
}
}
|
package com.eegeo.mapapi.services.routing;
import java.util.List;
/**
* A response to a routing query. Returned when a routing query completes via callback.
*/
public class RoutingQueryResponse {
boolean m_succeeded;
List<Route> m_results;
RoutingQueryResponse(boolean succeeded, List<Route> results) {
this.m_succeeded = succeeded;
this.m_results = results;
}
/**
* @return A boolean indicating whether the search succeeded or not.
*/
public boolean succeeded() {
return m_succeeded;
}
/**
* Get the results of the query as a List of Route objects. Each route passes through all given waypoints with the first route being the shortest.
* @return The query results.
*/
public List<Route> getResults() {
return m_results;
}
}
|
package pers.mrxiexie.card.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@NoArgsConstructor
@Data
public class GoodsShelves {
/**
* banner : http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7h icFN
* page_title : 惠城优惠大派送
* can_share : true
* scene : SCENE_NEAR_BY
* card_list : [{"card_id":"pXch-jnOlGtbuWwIO2NDftZeynRE","thumb_url":"www.qq.com/a.jpg"},{"card_id":"pXch-jnAN-ZBoRbiwgqBZ1RV60fI","thumb_url":"www.qq.com/b.jpg"}]
*/
private String banner;
private String page_title;
private boolean can_share;
private String scene;
private List<CardListBean> card_list;
@AllArgsConstructor
@NoArgsConstructor
@Data
public static class CardListBean {
/**
* card_id : pXch-jnOlGtbuWwIO2NDftZeynRE
* thumb_url : www.qq.com/a.jpg
*/
private String card_id;
private String thumb_url;
}
}
|
package unb.beacon.beacon_project;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Intent;
import android.os.Bundle;;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import unb.beacon.beacon_project.Utilidades.Beacon;
import unb.beacon.beacon_project.Utilidades.Utilidades;
public class Locator_actv extends Activity {
private BluetoothLeScanner mBluetoothScanner;
//private Handler mHandler = new Handler();
private ScanCallback scanCallback;
private boolean hasBT;
private TextView Locator_text;
private ListView List_view;
private int i = 0;
private ArrayList<Beacon> lista_beacons;
private ListView lv;
private ArrayAdapter<Beacon> arrayAdapter;
//private boolean isScan = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_locator);
init();
}
@Override
public void onDestroy()
{
super.onDestroy();
stopDiscovery();
}
private void init()
{
hasBT = request_bluetooth();
if(hasBT)
{
Interface();
}
}
private void Interface()
{
Locator_text = (TextView) findViewById(R.id.locator_text);
lista_beacons = new ArrayList<Beacon>();
List_view = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<Beacon>(this,android.R.layout.simple_list_item_1, lista_beacons);
List_view.setAdapter(arrayAdapter);
startDiscovery();
}
private boolean request_bluetooth()
{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean ok = false;
if (mBluetoothAdapter == null) {
Utilidades.showAlert("Erro", "Bluetooth não existe!",this);
} else {
if (!mBluetoothAdapter.isEnabled())
{
Intent enablebt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
this.startActivityForResult(enablebt, Utilidades.REQUEST_ENABLE_BLUETOOTH);
}
else {
mBluetoothScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
scanCallback = createScanCallback();
ok = true;
}
}
return ok;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Utilidades.REQUEST_ENABLE_BLUETOOTH:
if (resultCode == Activity.RESULT_OK) {
init();
} else {
finish();
}
break;
default:
break;
}
}
private ScanCallback createScanCallback () {
return new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
if (result == null
|| result.getDevice() == null){
if(result == null){ Locator_text.setText("NADA RESULT"); }
if(result.getDevice() == null){ Locator_text.setText("NADA GETDEVICE"); }
return;}
byte[] data = result.getScanRecord().getServiceData(Utilidades.SERVICE_UUID);
byte frametype = data[0];
switch(frametype) {
case Utilidades.FRAME_TYPE_UID:
Integer power = new Byte(data[1]).intValue();
String name;
String id;
name = Beacon.getInstanceNSpace(data);
id = Beacon.getInstanceId(data);
Integer rssi = new Integer(result.getRssi());
Double distance = Utilidades.getDistance(rssi, power);
boolean achou = false;
for (Beacon b : lista_beacons) {
if (id.equals(b.id)) {
b.update(rssi, power, -1, distance);
arrayAdapter.notifyDataSetChanged();
achou = true;
}
}
if (!achou) {
lista_beacons.add(new Beacon(name, id, rssi.intValue(), power.intValue(), -1, distance));
arrayAdapter.notifyDataSetChanged();
}
break;
}
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
}
};
}
private void startDiscovery()
{
Locator_text.setText("Scanning");
List<ScanFilter> filters = new ArrayList<>();
ScanFilter filter = new ScanFilter.Builder()
.setServiceUuid(Utilidades.SERVICE_UUID)
.build();
filters.add(filter);
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
mBluetoothScanner.startScan(filters,settings,scanCallback);
}
private void stopDiscovery()
{
mBluetoothScanner.stopScan(scanCallback);
}
public void onBackPressed()
{
finish();
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
/**
* <a href="http://oj.leetcode.com/problems/sort-colors/">Sort Colors</a>
* Copyright 2013 LeetCode
* <p/>
* Given an array with n objects colored red, white or blue, sort them so that
* objects of the same color are adjacent, with the colors in the order red,
* white and blue.
* <p/>
* Here, we will use the integers 0, 1, and 2 to represent the color red,
* white, and blue respectively.
* <p/>
* Note:
* You are not suppose to use the library's sort function for this problem.
* <p/>
* Follow up:
* A rather straight forward solution is a two-pass algorithm using counting
* sort.
* First, iterate the array counting number of 0's, 1's, and 2's, then
* overwrite array with total number of 0's, then 1's and followed by 2's.
* <p/>
* Could you come up with an one-pass algorithm using only constant space?
* <p/>
*
* @see <a href="http://discuss.leetcode.com/questions/251/sort-colors">Leetcode discussion</a>
* @see <a href="http://blog.csdn.net/zxzxy1988/article/details/8596144">zxzxy1988's blog</a>
* @see <a href="http://en.wikipedia.org/wiki/Dutch_national_flag_problem">Dutch national flag problem on Wikipedia</a>
* @see <a href="http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/">lloyd's page</a>
*/
public interface SortColors {
void sortColors(int[] A);
}
|
package com.lenovohit.hwe.pay.support.acctpay.balance.transfer;
import java.util.List;
public class RestListResponse<T> extends RestResponse {
public RestListResponse(){
super();
}
public RestListResponse(RestResponse reponse){
super();
if(null == reponse){
return;
}
this.setSuccess(reponse.getSuccess());
this.setMsg(reponse.getMsg());
this.setResult(reponse.getResult());
this.setList(null);
}
public RestListResponse(RestResponse reponse, List<T> list){
super();
if(null == reponse){
return;
}
this.setSuccess(reponse.getSuccess());
this.setMsg(reponse.getMsg());
this.setResult(reponse.getResult());
this.setList(list);
}
private List<T> list;
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
|
package com.codigo.smartstore.database.domain.domain;
import java.util.regex.Pattern;
public class DNSHelpers {
private static Pattern pDomainName;
private static final String DOMAIN_NAME_PATTERN = "^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$";
static {
DNSHelpers.pDomainName = Pattern.compile(DNSHelpers.DOMAIN_NAME_PATTERN);
}
// is this a valid domain name?
public static boolean isValidDomainName(final String domainName) {
return DNSHelpers.pDomainName.matcher(domainName)
.find();
}
}
|
package org.wildfly.issues.jbeap11984;
import javax.jws.WebMethod;
import javax.jws.WebService;
import org.apache.cxf.interceptor.InInterceptors;
@InInterceptors(classes = { org.wildfly.issues.jbeap11984.EventHandlerInjector.class })
@WebService
public class Hello {
@WebMethod
public String hello(String msg, long times) {
return "Hello " + msg + " " + times + " times";
}
}
|
package com.alibaba.druid.bvt.sql.mysql.show;
import com.alibaba.druid.sql.MysqlTest;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.parser.SQLParserFeature;
import java.util.List;
/**
* @author chenmo.cm
* @date 2018/8/27 上午11:41
*/
public class MySqlShowTest_39_stc extends MysqlTest {
public void test_0() throws Exception {
String sql = "SHOW STC";
MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.TDDLHint);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
assertEquals(0, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertEquals(0, visitor.getOrderByColumns().size());
assertEquals("SHOW STC", stmt.toString());
}
public void test_1() throws Exception {
String sql = "SHOW STC his";
MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.TDDLHint);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
assertEquals(0, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
assertEquals(0, visitor.getOrderByColumns().size());
assertEquals("SHOW STC HIS", stmt.toString());
}
}
|
package cit360mvcSimple;
import java.util.Vector;
public class Controller {
public void startApplication() {
RunwayModel = new Model();
RunwayModel.initialize();
View view = new View();
for (int i = 10; i > 0; i--) {
String movement = view.newView(currentRunway(), i);
switch (movement) {
case "left":
moveLeft();
break;
case "right":
moveRight();
break;
default:
break;
}
}
}
public String currentRunway() {
Vector curRun;
Vector modRun;
modRun = (Vector)RunwayModel.current().clone();
curRun = (Vector)modRun.clone();
String stringRunway = curRun.toString();
return stringRunway;
}
public void moveLeft() {
Vector curRun = RunwayModel.current();
int spot;
spot = curRun.indexOf("X");
if (spot > 0) { spot--; }
curRun.clear();
for (int i = 0; i < 10; i++) {
curRun.add(i," ");
}
curRun.add(spot,"X");
RunwayModel.update(curRun);
}
public void moveRight() {
Vector curRun = RunwayModel.current();
int spot;
spot = curRun.indexOf("X");
if (spot < 9) { spot++; }
curRun.clear();
for (int i = 0; i < 10; i++) {
curRun.add(i," ");
}
curRun.add(spot,"X");
RunwayModel.update(curRun);
}
private Model RunwayModel;
}
|
package uk.kainos.seleniumframework.driver.producer.desktop.ie;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import uk.kainos.seleniumframework.driver.GridUtils;
import uk.kainos.seleniumframework.driver.producer.WebDriverProducer;
import uk.kainos.seleniumframework.properties.CommonProperties;
import uk.kainos.seleniumframework.properties.PropertyLoader;
import java.util.HashMap;
public class IENativeEventsRemoteWebDriverProducer implements WebDriverProducer {
private final static String platform = PropertyLoader.getProperty(CommonProperties.BROWSER_PLATFORM);
private final static String platformVersion = PropertyLoader.getProperty(CommonProperties.BROWSER_PLATFORM_VERSION);
@Override
public WebDriver produce() {
InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions();
internetExplorerOptions.ignoreZoomSettings();
internetExplorerOptions.requireWindowFocus();
internetExplorerOptions.destructivelyEnsureCleanSession();
internetExplorerOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
if (platform != null || platformVersion != null) {
HashMap<String, Object> browserstackOptions = new HashMap<>();
if (platform != null) {
browserstackOptions.put("os", platform);
}
if (platformVersion != null) {
browserstackOptions.put("osVersion", platformVersion);
}
browserstackOptions.put("local", "false");
internetExplorerOptions.setCapability("bstack:options", browserstackOptions);
}
RemoteWebDriver remoteWebDriver = new RemoteWebDriver(GridUtils.getSeleniumGridURL(), internetExplorerOptions);
remoteWebDriver.setFileDetector(new LocalFileDetector());
return remoteWebDriver;
}
}
|
package com.example.bookspace.settings;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.content.SharedPreferences;
import com.example.bookspace.R;
import com.example.bookspace.model.RetrofitClient;
import com.example.bookspace.model.profile.ProfileResponse;
import com.example.bookspace.model.profile.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.Context.MODE_PRIVATE;
public class SetTargetsFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settarget, container, false);
final EditText weekTarget = view.findViewById(R.id.editTextTargetForAWeek);
final EditText monthTarget = view.findViewById(R.id.editTextTargetForAMonth);
final EditText yearTarget = view.findViewById(R.id.editTextTargetForAYear);
final String token = this.getContext().getSharedPreferences("AppPreferences", MODE_PRIVATE).getString("token", "");
Call<ProfileResponse> getProfileInfo = RetrofitClient
.getInstance()
.getBookSpaceAPI()
.getProfileInfo("Bearer " + token);
getProfileInfo.enqueue(new Callback<ProfileResponse>() {
@Override
public void onResponse(Call<ProfileResponse> call, Response<ProfileResponse> response) {
ProfileResponse resp = response.body();
User user = resp.getUser();
weekTarget.setText(user.getWeek().toString());
monthTarget.setText(user.getMonth().toString());
yearTarget.setText(user.getYear().toString());
}
@Override
public void onFailure(Call<ProfileResponse> call, Throwable t) {
t.printStackTrace();
}
});
return view;
}
}
|
package com.wrathOfLoD.Models.Ability.Abilities;
import com.wrathOfLoD.Models.Entity.Character.Character;
import com.wrathOfLoD.Models.Skill.SneakSkillManager;
/**
* Created by luluding on 4/13/16.
*/
public class PickPocketAbility extends UntimedAbility{
private SneakSkillManager ssm;
public PickPocketAbility(Character character, int manaCost) {
super(character, manaCost);
ssm = (SneakSkillManager)getCharacter().getSkillManager();
setName("Pickpocket");
}
public PickPocketAbility(int unlockLevel, Character character, int manaCost){
super(unlockLevel, character, manaCost);
ssm = (SneakSkillManager)getCharacter().getSkillManager();
setName("Pickpocket");
}
@Override
public boolean shouldDoAbility() {
return checkCanCastAbility(ssm.getPickPocketLevel());
}
@Override
public void doAbilityHook() {
//TODO: write the do ability logic for pick poket here
}
}
|
package graphs.maxflow;
import java.util.ArrayList;
import java.util.List;
public class FlowNetwork {
private int vertices;
private int edges;
private List<List<Edge>> adjacencies;
public FlowNetwork(int vertices) {
this.vertices = vertices;
adjacencies = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
List<Edge> edges = new ArrayList<>();
adjacencies.add(edges);
}
}
public void addEdge(Edge e) {
Vertex u = e.getU();
Vertex v = e.getV();
adjacencies.get(u.getId()).add(e);
adjacencies.get(v.getId()).add(e);
edges++;
}
public List<Edge> getAdjacencies(Vertex v) {
return adjacencies.get(v.getId());
}
public int getVertices() {
return vertices;
}
public int getEdges() {
return edges;
}
}
|
package com.redsun.platf.web.controller.system.account;
import com.redsun.platf.dao.base.IPagedDao;
import com.redsun.platf.entity.account.AccountRole;
import com.redsun.platf.entity.account.UserAccount;
import com.redsun.platf.entity.sys.Department;
import com.redsun.platf.service.account.AccountManager;
import com.redsun.platf.util.PasswordUtil;
import com.redsun.platf.util.string.StringUtils;
import com.redsun.platf.web.controller.AbstractStandardController;
import com.redsun.platf.web.validator.UserAccountValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 增加spring valdator 支持
*
* @see com.redsun.platf.web.validator.UserAccountValidator
*/
@Controller
@RequestMapping("/system/account")
@Transactional
public class UserController
extends AbstractStandardController<UserAccount> {
Log logger = LogFactory.getLog(this.getClass());
@Resource
AccountManager userManager;
@Override
public String getUrl() {
return "system/account";
}
@Override
public IPagedDao<UserAccount, Long> getDao() {
return userManager.getUserDao(); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
protected void prepareModel() throws Exception {
}
// @InitBinder
// public void initBinder(WebDataBinder binder){
@Override
protected void initValidator(WebDataBinder binder, HttpServletRequest request) {
binder.setValidator(new UserAccountValidator());
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception {
System.out.println(model);
model.addAttribute("aa", "111");
// System.out.println(model);
// System.out.println(userManager.getUserDao());
System.out.println("user getDao");
System.out.println(getDao());
List<?> l = userManager.getUserDao().getAll();
System.out.println(l);
// model.addAttribute("userList", userManager.getUserDao().getAll());
return "account/list-user";
}
/**
* 查询所有
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/queryAll", method = RequestMethod.GET)
@ResponseBody
public ModelAndView queryAll() throws
Exception {
Map<String, Object> map = new HashMap<String, Object>();
// List<UserAccount> results = userManager.getUserDao().getAll();
List<UserAccount> results = getDao().getAll();
// System.out.println("結果:");
// System.out.println(results.size());
for (UserAccount u : results) {
System.out.println("name:" + u.getLoginName());
List<AccountRole> rs = u.getRoleList();
for (Iterator<AccountRole> iterator = rs.iterator(); iterator.hasNext(); ) {
AccountRole r = (AccountRole) iterator.next();
System.out.println(r);
}
}
map.put("results", results);
// String json = mapper.writeValueAsString(results);
ModelAndView mav = new ModelAndView();
mav.addObject("success", map);
return mav;
}
// /**
// * 將部門顯示給用戶選擇,顯示增加畫面
// *
// * @return
// * @throws Exception
// * @ModelAttribute Map<String, List<Department>> listDept,
// * ModelMap model, BindingResult result
// */
// @RequestMapping(value = "/addUI", method = RequestMethod.GET)
//// 直接放在視圖裡,不用json @ResponseBody
// public ModelAndView addUI() throws Exception {
// // spring会利用jackson自动将返回值封装成JSON对象
//
// List<Department> deptList = userManager.getDepartmentDao().getAll();
// logger.info("current dept:" + deptList);
//
// Map<String, List<Department>> model = new HashMap<String, List<Department>>();
//
// model.put("listDept", deptList);
//
// return new ModelAndView("account/add", model);
// }
private void reigster(HttpServletRequest request, HttpServletResponse response,
@Validated UserAccount entity, BindingResult result) throws ServletException, IOException {
Map<String, String> errors = new HashMap<String, String>();
if (StringUtils.isEmptyOrNull(entity.getLoginName())) {
errors.put("userName", "用户名不能为空!");
} else if (getDao().findBy("loginName", entity.getLoginName()).size() > 0) {
errors.put("userName", "该用户已注册!");
}
// if (password == null || "".equals(password)) {
// errors.put("password","密码不能为空!");
// } else if (password != null && password.length() < 3) {
// errors.put("password","密码长度不能低于3位!");
// }
//
// if (password2 == null || "".equals(password2)) {
// errors.put("password2", "确认密码不能为空!");
// } else if (password2 != null && !password2.equals(password)) {
// errors.put("password2", "两次输入的密码不一致!");
// }
//
// if (email == null || "".equals(email)) {
// errors.put("email", "email不能为空!");
//
// } else if (email != null && !email.matches("[0-9a-zA-Z_-]+@[0-9a-zA-Z_-]+\\.[0-9a-zA-Z_-]+(\\.[0-9a-zA-Z_-])*")) {
// errors.put("email", "email格式不正确!");
// }
//
if (!errors.isEmpty()) {
request.setAttribute("errors", errors);
request.getRequestDispatcher("/registerUI").forward(request, response);
return;
}
// User user = new User();
// user.setUserName(userName);
// user.setPassword(password);
// user.setEmail(email);
// user.setActivated(false);
// userDao.addUser(user);
getDao().save(entity);
// 注册成功后,发送帐户激活链接
EmailUtils.sendAccountActivateEmail(entity);
// 注册成功直接将当前用户保存到session中
request.getSession().setAttribute("user", entity);
request.getRequestDispatcher("/WEB-INF/pages/registerSuccess.jsp").forward(request, response);
}
public void activeUser(HttpServletRequest request, HttpServletResponse response) {
String idValue = request.getParameter("id");
int id = -1;
try {
id = Integer.parseInt(idValue);
} catch (NumberFormatException e) {
throw new RuntimeException("无效的用户!");
}
UserAccount user = getDao().findUniqueBy("id", id);
// UserDao userDao = UserDaoImpl.getInstance();
// User user = userDao.findUserById(id);// 得到要激活的帐户
// user.setActivated(GenerateLinkUtils.verifyCheckcode(user, request));// 校验验证码是否和注册时发送的一致,以此设置是否激活该帐户
// userDao.updateUser(user);
getDao().update(user);
request.getSession().setAttribute("user", user);
// request.getRequestDispatcher("/accountActivateUI").forward(request, response);
}
@Override
protected boolean beforeSave() {
/*將password 進行encode */
if (!this.isUpdate()) {
String oriPassword = getModel().getPassword();
getModel().setPassword(encodePassword(oriPassword));
System.out.println(oriPassword + "->" + getModel().getPassword());
return true;
} else {
return false;
}
}
//蜜碼加密處理
public String encodePassword(String password) {
return PasswordUtil.enCoderSHA(password);
}
}
|
public class Matrix {
public static void main(String[] args) {
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
matrixAddition(a,b);
matrixSubtraction(a,b);
matrixMultiplication(a,b);
matrixTranspose(a);
}
private static void matrixAddition(int[][] a,int[][] b) {
int c[][]=new int[3][3];
System.out.println("Addition :");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
private static void matrixTranspose(int[][] a) {
System.out.println("Transpose: :");
int c[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[j][i];
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
private static void matrixMultiplication(int[][] a,int[][] b) {
int c[][]=new int[3][3];
System.out.println("Multiplication :");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
private static void matrixSubtraction(int[][] a, int[][] b) {
int c[][]=new int[3][3];
System.out.println("Subtraction:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]-b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
|
package com.turios.modules.utils;
public class AssetFiles {
public static final String PICKLIST = "picklist.txt";
public static final String TKP = "TKP.pdf";
}
|
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.AdvertPosition;
@Repository("advertPositionDAO")
public class AdvertPositionDAO extends GenericDAO<AdvertPosition> {
} |
package com.pda.pda_android.db.dao;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import com.pda.pda_android.db.Entry.AssayBean;
import com.pda.pda_android.db.Entry.AssayDetailBean;
import com.pda.pda_android.db.Entry.CheckBean;
import com.pda.pda_android.db.Entry.PostCacheBean;
import com.pda.pda_android.db.Entry.SsxxBean;
import com.pda.pda_android.db.Entry.UserBean;
import com.pda.pda_android.db.dao.AssayBeanDao;
import com.pda.pda_android.db.dao.AssayDetailBeanDao;
import com.pda.pda_android.db.dao.CheckBeanDao;
import com.pda.pda_android.db.dao.PostCacheBeanDao;
import com.pda.pda_android.db.dao.SsxxBeanDao;
import com.pda.pda_android.db.dao.UserBeanDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig assayBeanDaoConfig;
private final DaoConfig assayDetailBeanDaoConfig;
private final DaoConfig checkBeanDaoConfig;
private final DaoConfig postCacheBeanDaoConfig;
private final DaoConfig ssxxBeanDaoConfig;
private final DaoConfig userBeanDaoConfig;
private final AssayBeanDao assayBeanDao;
private final AssayDetailBeanDao assayDetailBeanDao;
private final CheckBeanDao checkBeanDao;
private final PostCacheBeanDao postCacheBeanDao;
private final SsxxBeanDao ssxxBeanDao;
private final UserBeanDao userBeanDao;
public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
assayBeanDaoConfig = daoConfigMap.get(AssayBeanDao.class).clone();
assayBeanDaoConfig.initIdentityScope(type);
assayDetailBeanDaoConfig = daoConfigMap.get(AssayDetailBeanDao.class).clone();
assayDetailBeanDaoConfig.initIdentityScope(type);
checkBeanDaoConfig = daoConfigMap.get(CheckBeanDao.class).clone();
checkBeanDaoConfig.initIdentityScope(type);
postCacheBeanDaoConfig = daoConfigMap.get(PostCacheBeanDao.class).clone();
postCacheBeanDaoConfig.initIdentityScope(type);
ssxxBeanDaoConfig = daoConfigMap.get(SsxxBeanDao.class).clone();
ssxxBeanDaoConfig.initIdentityScope(type);
userBeanDaoConfig = daoConfigMap.get(UserBeanDao.class).clone();
userBeanDaoConfig.initIdentityScope(type);
assayBeanDao = new AssayBeanDao(assayBeanDaoConfig, this);
assayDetailBeanDao = new AssayDetailBeanDao(assayDetailBeanDaoConfig, this);
checkBeanDao = new CheckBeanDao(checkBeanDaoConfig, this);
postCacheBeanDao = new PostCacheBeanDao(postCacheBeanDaoConfig, this);
ssxxBeanDao = new SsxxBeanDao(ssxxBeanDaoConfig, this);
userBeanDao = new UserBeanDao(userBeanDaoConfig, this);
registerDao(AssayBean.class, assayBeanDao);
registerDao(AssayDetailBean.class, assayDetailBeanDao);
registerDao(CheckBean.class, checkBeanDao);
registerDao(PostCacheBean.class, postCacheBeanDao);
registerDao(SsxxBean.class, ssxxBeanDao);
registerDao(UserBean.class, userBeanDao);
}
public void clear() {
assayBeanDaoConfig.clearIdentityScope();
assayDetailBeanDaoConfig.clearIdentityScope();
checkBeanDaoConfig.clearIdentityScope();
postCacheBeanDaoConfig.clearIdentityScope();
ssxxBeanDaoConfig.clearIdentityScope();
userBeanDaoConfig.clearIdentityScope();
}
public AssayBeanDao getAssayBeanDao() {
return assayBeanDao;
}
public AssayDetailBeanDao getAssayDetailBeanDao() {
return assayDetailBeanDao;
}
public CheckBeanDao getCheckBeanDao() {
return checkBeanDao;
}
public PostCacheBeanDao getPostCacheBeanDao() {
return postCacheBeanDao;
}
public SsxxBeanDao getSsxxBeanDao() {
return ssxxBeanDao;
}
public UserBeanDao getUserBeanDao() {
return userBeanDao;
}
}
|
/**
*/
package iso20022.impl;
import java.lang.String;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.InternalEList;
import iso20022.BusinessTransaction;
import iso20022.Iso20022Package;
import iso20022.MessageDefinition;
import iso20022.MessageTransmission;
import iso20022.Receive;
import iso20022.Send;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Message Transmission</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iso20022.impl.MessageTransmissionImpl#getBusinessTransaction <em>Business Transaction</em>}</li>
* <li>{@link iso20022.impl.MessageTransmissionImpl#getDerivation <em>Derivation</em>}</li>
* <li>{@link iso20022.impl.MessageTransmissionImpl#getMessageTypeDescription <em>Message Type Description</em>}</li>
* <li>{@link iso20022.impl.MessageTransmissionImpl#getSend <em>Send</em>}</li>
* <li>{@link iso20022.impl.MessageTransmissionImpl#getReceive <em>Receive</em>}</li>
* </ul>
*
* @generated
*/
public class MessageTransmissionImpl extends RepositoryConceptImpl implements MessageTransmission {
/**
* The cached value of the '{@link #getDerivation() <em>Derivation</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDerivation()
* @generated
* @ordered
*/
protected EList<MessageDefinition> derivation;
/**
* The default value of the '{@link #getMessageTypeDescription() <em>Message Type Description</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMessageTypeDescription()
* @generated
* @ordered
*/
protected static final String MESSAGE_TYPE_DESCRIPTION_EDEFAULT = null;
/**
* The cached value of the '{@link #getMessageTypeDescription() <em>Message Type Description</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMessageTypeDescription()
* @generated
* @ordered
*/
protected String messageTypeDescription = MESSAGE_TYPE_DESCRIPTION_EDEFAULT;
/**
* The cached value of the '{@link #getSend() <em>Send</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSend()
* @generated
* @ordered
*/
protected Send send;
/**
* The cached value of the '{@link #getReceive() <em>Receive</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReceive()
* @generated
* @ordered
*/
protected EList<Receive> receive;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MessageTransmissionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getMessageTransmission();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BusinessTransaction getBusinessTransaction() {
if (eContainerFeatureID() != Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION) return null;
return (BusinessTransaction)eInternalContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetBusinessTransaction(BusinessTransaction newBusinessTransaction, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newBusinessTransaction, Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBusinessTransaction(BusinessTransaction newBusinessTransaction) {
if (newBusinessTransaction != eInternalContainer() || (eContainerFeatureID() != Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION && newBusinessTransaction != null)) {
if (EcoreUtil.isAncestor(this, newBusinessTransaction))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newBusinessTransaction != null)
msgs = ((InternalEObject)newBusinessTransaction).eInverseAdd(this, Iso20022Package.BUSINESS_TRANSACTION__TRANSMISSION, BusinessTransaction.class, msgs);
msgs = basicSetBusinessTransaction(newBusinessTransaction, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION, newBusinessTransaction, newBusinessTransaction));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<MessageDefinition> getDerivation() {
if (derivation == null) {
derivation = new EObjectWithInverseResolvingEList.ManyInverse<MessageDefinition>(MessageDefinition.class, this, Iso20022Package.MESSAGE_TRANSMISSION__DERIVATION, Iso20022Package.MESSAGE_DEFINITION__TRACE);
}
return derivation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getMessageTypeDescription() {
return messageTypeDescription;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMessageTypeDescription(String newMessageTypeDescription) {
String oldMessageTypeDescription = messageTypeDescription;
messageTypeDescription = newMessageTypeDescription;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.MESSAGE_TRANSMISSION__MESSAGE_TYPE_DESCRIPTION, oldMessageTypeDescription, messageTypeDescription));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Send getSend() {
return send;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetSend(Send newSend, NotificationChain msgs) {
Send oldSend = send;
send = newSend;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Iso20022Package.MESSAGE_TRANSMISSION__SEND, oldSend, newSend);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSend(Send newSend) {
if (newSend != send) {
NotificationChain msgs = null;
if (send != null)
msgs = ((InternalEObject)send).eInverseRemove(this, Iso20022Package.SEND__MESSAGE_TRANSMISSION, Send.class, msgs);
if (newSend != null)
msgs = ((InternalEObject)newSend).eInverseAdd(this, Iso20022Package.SEND__MESSAGE_TRANSMISSION, Send.class, msgs);
msgs = basicSetSend(newSend, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.MESSAGE_TRANSMISSION__SEND, newSend, newSend));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Receive> getReceive() {
if (receive == null) {
receive = new EObjectContainmentWithInverseEList<Receive>(Receive.class, this, Iso20022Package.MESSAGE_TRANSMISSION__RECEIVE, Iso20022Package.RECEIVE__MESSAGE_TRANSMISSION);
}
return receive;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetBusinessTransaction((BusinessTransaction)otherEnd, msgs);
case Iso20022Package.MESSAGE_TRANSMISSION__DERIVATION:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getDerivation()).basicAdd(otherEnd, msgs);
case Iso20022Package.MESSAGE_TRANSMISSION__SEND:
if (send != null)
msgs = ((InternalEObject)send).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Iso20022Package.MESSAGE_TRANSMISSION__SEND, null, msgs);
return basicSetSend((Send)otherEnd, msgs);
case Iso20022Package.MESSAGE_TRANSMISSION__RECEIVE:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getReceive()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION:
return basicSetBusinessTransaction(null, msgs);
case Iso20022Package.MESSAGE_TRANSMISSION__DERIVATION:
return ((InternalEList<?>)getDerivation()).basicRemove(otherEnd, msgs);
case Iso20022Package.MESSAGE_TRANSMISSION__SEND:
return basicSetSend(null, msgs);
case Iso20022Package.MESSAGE_TRANSMISSION__RECEIVE:
return ((InternalEList<?>)getReceive()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION:
return eInternalContainer().eInverseRemove(this, Iso20022Package.BUSINESS_TRANSACTION__TRANSMISSION, BusinessTransaction.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION:
return getBusinessTransaction();
case Iso20022Package.MESSAGE_TRANSMISSION__DERIVATION:
return getDerivation();
case Iso20022Package.MESSAGE_TRANSMISSION__MESSAGE_TYPE_DESCRIPTION:
return getMessageTypeDescription();
case Iso20022Package.MESSAGE_TRANSMISSION__SEND:
return getSend();
case Iso20022Package.MESSAGE_TRANSMISSION__RECEIVE:
return getReceive();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION:
setBusinessTransaction((BusinessTransaction)newValue);
return;
case Iso20022Package.MESSAGE_TRANSMISSION__DERIVATION:
getDerivation().clear();
getDerivation().addAll((Collection<? extends MessageDefinition>)newValue);
return;
case Iso20022Package.MESSAGE_TRANSMISSION__MESSAGE_TYPE_DESCRIPTION:
setMessageTypeDescription((String)newValue);
return;
case Iso20022Package.MESSAGE_TRANSMISSION__SEND:
setSend((Send)newValue);
return;
case Iso20022Package.MESSAGE_TRANSMISSION__RECEIVE:
getReceive().clear();
getReceive().addAll((Collection<? extends Receive>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION:
setBusinessTransaction((BusinessTransaction)null);
return;
case Iso20022Package.MESSAGE_TRANSMISSION__DERIVATION:
getDerivation().clear();
return;
case Iso20022Package.MESSAGE_TRANSMISSION__MESSAGE_TYPE_DESCRIPTION:
setMessageTypeDescription(MESSAGE_TYPE_DESCRIPTION_EDEFAULT);
return;
case Iso20022Package.MESSAGE_TRANSMISSION__SEND:
setSend((Send)null);
return;
case Iso20022Package.MESSAGE_TRANSMISSION__RECEIVE:
getReceive().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Iso20022Package.MESSAGE_TRANSMISSION__BUSINESS_TRANSACTION:
return getBusinessTransaction() != null;
case Iso20022Package.MESSAGE_TRANSMISSION__DERIVATION:
return derivation != null && !derivation.isEmpty();
case Iso20022Package.MESSAGE_TRANSMISSION__MESSAGE_TYPE_DESCRIPTION:
return MESSAGE_TYPE_DESCRIPTION_EDEFAULT == null ? messageTypeDescription != null : !MESSAGE_TYPE_DESCRIPTION_EDEFAULT.equals(messageTypeDescription);
case Iso20022Package.MESSAGE_TRANSMISSION__SEND:
return send != null;
case Iso20022Package.MESSAGE_TRANSMISSION__RECEIVE:
return receive != null && !receive.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (messageTypeDescription: ");
result.append(messageTypeDescription);
result.append(')');
return result.toString();
}
} //MessageTransmissionImpl
|
package javapackage;
public class Customer1 implements Comparable<Customer1> {
private final String name;
private final String address;
Customer1(String name, String address) {
this.name = name;
this.address = address;
}
@Override
public int compareTo(Customer1 other) {
return name.compareTo(other.name);
}
public String toString() {
return name + " " + address;
}
}
|
package com.tmontovaneli.engine;
import java.io.Serializable;
public class Palavra implements Serializable, Comparable<Palavra> {
/**
*
*/
private static final long serialVersionUID = 658021962229211967L;
String word;
int nrOccur;
int nrOccurComoProx;
public Palavra(String word) {
this.word = word;
}
@Override
public boolean equals(Object arg0) {
if (!(arg0 instanceof Palavra))
return false;
Palavra p = (Palavra) arg0;
return this.word.equals(p.word);
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
return this.word;
}
public double getFreq() {
return nrOccur / CarregaBase.getQtPalavras();
}
public int getNrOccurComoProx() {
return nrOccurComoProx;
}
@Override
public int compareTo(Palavra arg0) {
return this.word.compareTo(arg0.word);
}
} |
package org.squonk.api;
import org.apache.camel.spi.TypeConverterRegistry;
/**
* Created by timbo on 23/03/2016.
*/
public interface GenericHandler<P,G> {
void setGenericType(Class<G> genericType);
Class<G> getGenericType();
default boolean canConvertGeneric(Class<? extends Object> otherGenericType, TypeConverterRegistry registry) {
return false;
}
default P convertGeneric(P from, Class<? extends Object> otherGenericType, TypeConverterRegistry registry) {
throw new RuntimeException("There is no default way to handle generic conversions. Implementations must handle this.");
}
}
|
import java.util.*;
public class Ch18_03 {
//takes O(nlogn) time complexity and O(1) space complexity
public static int minimumTotalWaitingTime(List<Integer> serviceTimes) {
Collections.sort(serviceTimes);
int totalWaitingTime = 0;
int waitingTime = 0;
for (int i = 1; i < serviceTimes.size(); i++) {
waitingTime += serviceTimes.get(i - 1);
totalWaitingTime += waitingTime;
}
return totalWaitingTime;
}
public static void main(String []args) {
List<Integer> serviceTimes = new ArrayList<Integer>(Arrays.asList(5, 4, 3, 2, 1));
System.out.println(minimumTotalWaitingTime(serviceTimes));
}
}
|
package uz.otash.shop.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import uz.otash.shop.entity.template.AbsEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class ProductWithAmount extends AbsEntity {
@ManyToOne(fetch = FetchType.LAZY)
private Product product;
@Column(nullable = false)
private Integer amount;
private Double soldPrice;
@ManyToOne(fetch = FetchType.LAZY)
private Transfer transfer;
@ManyToOne(fetch = FetchType.LAZY)
private Sale sale;
@ManyToOne(fetch = FetchType.LAZY)
private Reject reject;
@ManyToOne(fetch = FetchType.LAZY)
private Defect defect;
public ProductWithAmount(Product product, Integer amount, Transfer transfer) {
this.product = product;
this.amount = amount;
this.transfer = transfer;
}
public ProductWithAmount(Product product, Integer amount, Sale sale) {
this.product = product;
this.amount = amount;
this.sale = sale;
}
public ProductWithAmount(Product product, Integer amount, Reject reject) {
this.product = product;
this.amount = amount;
this.reject = reject;
}
public ProductWithAmount(Product product, Integer amount, Defect defect) {
this.product = product;
this.amount = amount;
this.defect = defect;
}
}
|
package enums;
public enum BlackJackMove {
STICK,
TWIST
}
|
package com.thomasdedinsky.fydp.fydpweb.auth;
import org.springframework.stereotype.Service;
@Service
public class ConfirmationTokenService {
private final ConfirmationTokenRepository confirmationTokenRepository;
public ConfirmationTokenService(ConfirmationTokenRepository confirmationTokenRepository) {
super();
this.confirmationTokenRepository = confirmationTokenRepository;
}
public void saveConfirmationToken(ConfirmationToken confirmationToken) {
confirmationTokenRepository.save(confirmationToken);
}
public void deleteConfirmationToken(int id){
confirmationTokenRepository.deleteById(id);
}
public ConfirmationToken findConfirmationTokenByToken(String token) {
return confirmationTokenRepository.findConfirmationTokenByConfirmationToken(token);
}
} |
package com.zantong.mobilecttx.user.activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import com.zantong.mobilecttx.common.PublicData;
import com.zantong.mobilecttx.R;
import com.zantong.mobilecttx.api.CallBack;
import com.zantong.mobilecttx.api.CarApiClient;
import com.zantong.mobilecttx.base.activity.BaseMvpActivity;
import com.zantong.mobilecttx.base.interf.IBaseView;
import com.zantong.mobilecttx.base.bean.BaseResult;
import com.zantong.mobilecttx.daijia.bean.DaiJiaOrderDetailResult;
import com.zantong.mobilecttx.daijia.dto.DaiJiaOrderDetailDTO;
import com.zantong.mobilecttx.presenter.HelpPresenter;
import com.zantong.mobilecttx.utils.rsa.RSAUtils;
import com.zantong.mobilecttx.utils.DialogUtils;
import com.zantong.mobilecttx.utils.HashUtils;
import com.zantong.mobilecttx.utils.PullToRefreshLayout;
import com.zantong.mobilecttx.utils.StringUtils;
import com.zantong.mobilecttx.utils.jumptools.Act;
import com.zantong.mobilecttx.daijia.activity.DrivingOrderActivity;
import java.util.HashMap;
import butterknife.Bind;
import butterknife.OnClick;
/**
* 代驾派单中详情页面
* Created by zhoujie on 2017/2/21.
*/
public class DODetailBeingActivity extends BaseMvpActivity<IBaseView, HelpPresenter> {
@Bind(R.id.order_detail_date_being)
TextView mDate;
@Bind(R.id.order_detail_address_being)
TextView mAddress;
@Bind(R.id.order_detail_clean_being)
TextView mClean;
@Bind(R.id.daijia_order_detail_state)
TextView mState;
@Bind(R.id.driving_order_layout)
PullToRefreshLayout mDrivingOrderLayout;
@Bind(R.id.order_detail_driver_layout)
View mDriverLayout;
@Bind(R.id.order_detail_mileage_layout)
View mMileageLayout;
@Bind(R.id.order_detail_price_layout)
View mPriceLayout;
@Bind(R.id.order_detail_driver_phone)
TextView mDriverPhone;
@Bind(R.id.order_detail_price)
TextView mPrice;
@Bind(R.id.order_detail_mileage)
TextView mMileage;
@Override
public void initView() {
setTitleText("当前代驾订单");
}
@Override
public void initData() {
initRefreshView();
}
@Override
protected void onResume() {
super.onResume();
getOrderDetail();
}
@OnClick(R.id.order_detail_clean_being)
public void onClick(View view) {
switch (view.getId()) {
case R.id.order_detail_clean_being:
cleanOrderDialog();
break;
}
}
/**
* 取消订单dialog
*/
private void cleanOrderDialog() {
DialogUtils.telDialog(this, "提示", "您确定取消订单吗?", new View.OnClickListener() {
@Override
public void onClick(View v) {
DaiJiaOrderDetailDTO dto = new DaiJiaOrderDetailDTO();
String time = "1488253689";
try {
time = StringUtils.getTimeToStr();
} catch (Exception e) {
}
dto.setTime(time);
Intent intent = getIntent();
String orderId = intent.getStringExtra("param");
dto.setOrderId(orderId);
dto.setUsrId(RSAUtils.strByEncryptionLiYing(PublicData.getInstance().userID, true));
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("time",time);
hashMap.put("orderId",orderId);
hashMap.put("usrId",PublicData.getInstance().userID);
dto.setHash(HashUtils.getSignature(hashMap));
CarApiClient.cancelDaiJiaOrderDetail(DODetailBeingActivity.this, dto, new CallBack<BaseResult>() {
@Override
public void onSuccess(BaseResult result) {
if (result.getResponseCode() == 2000) {
mState.setText("已取消");
mState.setTextColor(R.color.gray_cc);
mClean.setVisibility(View.GONE);
}
}
});
}
});
}
@Override
public HelpPresenter initPresenter() {
return new HelpPresenter();
}
@Override
protected int getContentResId() {
return R.layout.activity_d_o_detail_being;
}
/**
* 获取代驾中的订单详情
*/
private void getOrderDetail() {
String time = "1488253689";
try {
time = StringUtils.getTimeToStr();
} catch (Exception e) {
}
DaiJiaOrderDetailDTO dto = new DaiJiaOrderDetailDTO();
Intent intent = getIntent();
String orderId = intent.getStringExtra(Act.ACT_PARAM);
dto.setOrderId(orderId);
dto.setTime(time);
dto.setUsrId(RSAUtils.strByEncryptionLiYing(PublicData.getInstance().userID, true));
CarApiClient.getDaiJiaOrderDetail(this, dto, new CallBack<DaiJiaOrderDetailResult>() {
@Override
public void onSuccess(DaiJiaOrderDetailResult result) {
mDrivingOrderLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
if (result.getResponseCode() == 2000) {
String state = result.getData().getOrderStatus();
mState.setText(state);
if (state.contains("派单中")) {
mMileageLayout.setVisibility(View.GONE);
mPriceLayout.setVisibility(View.GONE);
mDriverLayout.setVisibility(View.GONE);
mState.setTextColor(R.color.red);
} else if (state.contains("司机途中")) {
mMileageLayout.setVisibility(View.GONE);
mPriceLayout.setVisibility(View.GONE);
mDriverLayout.setVisibility(View.GONE);
mState.setTextColor(R.color.red);
} else if (state.contains("司机等待")) {
mMileageLayout.setVisibility(View.GONE);
mPriceLayout.setVisibility(View.GONE);
mDriverLayout.setVisibility(View.GONE);
mState.setTextColor(R.color.red);
} else if (state.contains("代驾中")) {
mMileageLayout.setVisibility(View.GONE);
mPriceLayout.setVisibility(View.GONE);
mDriverLayout.setVisibility(View.GONE);
mClean.setVisibility(View.GONE);
mState.setTextColor(R.color.red);
} else if (state.contains("代驾完成")) {
mMileageLayout.setVisibility(View.GONE);
mPriceLayout.setVisibility(View.GONE);
mDriverLayout.setVisibility(View.GONE);
mClean.setVisibility(View.GONE);
mState.setTextColor(R.color.gray_cc);
} else if (state.contains("已预约")) {
mMileageLayout.setVisibility(View.GONE);
mPriceLayout.setVisibility(View.GONE);
mDriverLayout.setVisibility(View.GONE);
mClean.setVisibility(View.GONE);
mState.setTextColor(R.color.red);
}else if (state.contains("支付完成")) {
mMileageLayout.setVisibility(View.VISIBLE);
mPriceLayout.setVisibility(View.VISIBLE);
mDriverLayout.setVisibility(View.VISIBLE);
mPrice.setText(result.getData().getAmount());
mMileage.setText(result.getData().getDistance());
mDriverPhone.setText(result.getData().getDriverMobile());
mClean.setVisibility(View.GONE);
mState.setTextColor(R.color.gray_cc);
}else if (state.contains("已取消")) {
mMileageLayout.setVisibility(View.GONE);
mPriceLayout.setVisibility(View.GONE);
mDriverLayout.setVisibility(View.GONE);
mClean.setVisibility(View.GONE);
mState.setTextColor(R.color.gray_cc);
}
mDate.setText(result.getData().getCreateTime());
mAddress.setText(result.getData().getAddress());
}
}
@Override
public void onError(String errorCode, String msg) {
super.onError(errorCode, msg);
}
});
}
/**
* 初始化下拉刷新界面控件
*/
private void initRefreshView() {
mDrivingOrderLayout.setPullUpEnable(false);
mDrivingOrderLayout.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
@Override
public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
getOrderDetail();
}
@Override
public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
}
});
}
@Override
protected void baseGoBack() {
Act.getInstance().gotoIntent(this, DrivingOrderActivity.class);
finish();
}
} |
/*
* 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 Lambda;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
/**
*
* @author YNZ
*/
class Worker implements Runnable {
private Random r = new Random();
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(r.nextInt(100));
}
}
}
class Person implements Comparable<Person> {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public int compareTo(Person o) {
return this.name.compareToIgnoreCase(o.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
class Car {
private String brand;
public Car() {
}
public Car(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
@Override
public String toString() {
return this.brand;
}
}
class CarComparator implements Comparator<Car> {
@Override
public int compare(Car o1, Car o2) {
return o1.getBrand().compareToIgnoreCase(o2.getBrand());
}
}
class User {
private String name;
public User(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return this.name;
}
}
public class LambadaFunctionDemo {
public static void main(String[] args) {
new Thread(new Worker()).start();
List<Person> list = new ArrayList<>();
list.add(new Person("Yichun"));
list.add(new Person("Mike"));
System.out.println("" + list.toString());
Collections.sort(list);
System.out.println("" + list.toString());
List<Car> cars = new ArrayList<>();
cars.add(new Car("Ford"));
cars.add(new Car("Benz"));
cars.add(new Car("Audi"));
Collections.sort(cars, new CarComparator());
System.out.println("" + cars.toString());
List<User> users = new ArrayList<>();
users.add(new User("Yichun"));
users.add(new User("Bose"));
users.add(new User("Mia"));
//functional interface
//lambda expression
// Comparator<User> comparator = (o1, o2) -> o1.getName().compareTo(o2.getName());
// Collections.sort(users, comparator);
System.out.println(""+users.toString());
Collections.sort(users,(o1, o2) -> o1.getName().compareTo(o2.getName()));
System.out.println(""+users.toString());
}
}
|
package controller;
import controller.cliente.TelaClienteController;
import controller.funcionario.TelaFuncionarioController;
import entity.Carrinho;
import entity.Produto;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import petshop.Principal;
public class TelaBrinquedosController implements Initializable {
@FXML
private AnchorPane parent;
@FXML
TableColumn tableColumnBrinquedos;
@FXML
TableColumn tableColumnPreco;
@FXML
TableView<Produto> tableBrinquedos;
@FXML
TextField txtQuantidade;
@FXML AnchorPane telaBrinquedos;
private Carrinho carrinho;
private TelaPrincipalController telaPrincipalController;
private TelaClienteController telaClienteController;
private TelaFuncionarioController telaFuncionarioController;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void adicionarCarrinho() {
try {
Produto p = tableBrinquedos.getSelectionModel().getSelectedItem();
int quantidade = Integer.parseInt(txtQuantidade.getText().trim());
//verifica se tem a quantidade de produtos desejados no estoque
if (quantidade <= p.getQuantidade()) {
Produto pCarrinho = new Produto(p.getNome(), p.getPreco(),quantidade,
p.getCategoria(), p.getPrecoFornecedor(), p.getFornecedor());
carrinho.adicionarProduto(pCarrinho);
//checar se é isso mesmo
p.vender(quantidade);
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("OK");
alert.setHeaderText(null);
alert.setContentText("Produto adiciona no carrinho!");
alert.showAndWait();
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Erro");
alert.setHeaderText(null);
alert.setContentText("Quantidade de itens indisponível!\nAtualmente possuímos apenas "+p.getQuantidade()+" itens desse produto.");
alert.showAndWait();
}
} catch (Exception ex) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Erro");
alert.setHeaderText(null);
alert.setContentText("Por favor, selecione um item!");
alert.showAndWait();
}
}
public void irMenu(ActionEvent event) {
if (telaClienteController != null) {
telaClienteController.irTelaInicialCliente();
}else
if (telaFuncionarioController !=null){
telaFuncionarioController.irTelaInicialFuncionario();
}
}//fim do metodo
public void sair() {
telaPrincipalController.retornar();
}
public void irCarrinho(ActionEvent event) {
try {
FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaCarrinho.fxml"));
AnchorPane telaCarrinho = loader.load();
TelaCarrinhoController controller = loader.getController();
controller.setCarrinho(carrinho);
controller.setTelaPrincipalController(telaPrincipalController);
controller.atualizar();
telaBrinquedos.getChildren().clear();
telaBrinquedos.getChildren().add(telaCarrinho);
} catch (IOException ex) {
ex.printStackTrace();
}//fim do catch
}//fim do metodo
public void setParent(AnchorPane a) {
this.parent = a;
}
public void setCarrinho(Carrinho carrinho) {
this.carrinho = carrinho;
}
public void setTelaPrincipalController(TelaPrincipalController telaPrincipalController) {
this.telaPrincipalController = telaPrincipalController;
}
public void atualizar() {
List<Produto> brinquedos = new ArrayList<>();
//percorre a lista de produtos do estoque e pega apenas os do tipo acessorio
for (Produto produto : Principal.estoque.getProdutos().values()) {
if (produto.getCategoria().equals(Produto.Categoria.BRINQUEDOS)) {
brinquedos.add(produto);
}
}
tableColumnBrinquedos.setCellValueFactory(new PropertyValueFactory<>("nome"));
tableColumnPreco.setCellValueFactory(new PropertyValueFactory<>("preco"));
tableBrinquedos.setItems(FXCollections.observableArrayList(brinquedos));
}
public void setTelaClienteController(TelaClienteController telaClienteController) {
this.telaClienteController = telaClienteController;
}
public void setTelaFuncionarioController(TelaFuncionarioController telaFuncionarioController) {
this.telaFuncionarioController = telaFuncionarioController;
}
}
|
package net.edzard.kinetic;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.Image;
/**
* A fill style using an image as a pattern.
* @author Ed
*/
public class PatternFillStyle implements FillStyle {
/** The image to use */
private Image image;
/** How to repeat the image */
private RepetitionType repetition;
/** Offset of the image in relation to the encapsulating shape */
private Vector2d offset;
/**
* Parametrized Ctor for pattern fills.
* Beware: underlying library does not allow the use of inlining of image data. Always use pictures constructed from straight URLs!
* @param image The image to use as a pattern.
*/
public PatternFillStyle(Image image) {
super();
this.image = image;
this.repetition = RepetitionType.NO_REPEAT;
this.offset = new Vector2d(0, 0);
}
/**
* Parametrized Ctor for pattern fills.
* Beware: underlying library does not allow the use of inlining of image data. Always use pictures constructed from straight URLs!
* @param image The image to use as a pattern.
* @param repetition Defines how the image should be repeated
*/
public PatternFillStyle(Image image, RepetitionType repetition) {
super();
this.image = image;
this.repetition = repetition;
this.offset = new Vector2d(0, 0);
}
/**
* Parametrized Ctor for pattern fills.
* Beware: underlying library does not allow the use of inlining of image data. Always use pictures constructed from straight URLs!
* @param image The image to use as a pattern.
* @param repetition Defines how the image should be repeated
* @param offset Offset of the image in relation to encapsulating shape
*/
public PatternFillStyle(Image image, RepetitionType repetition, Vector2d offset) {
super();
this.image = image;
this.repetition = repetition;
this.offset = offset;
}
/**
* Parametrized Ctor for pattern fills.
* @param res The image resource to use as a pattern.
*/
public PatternFillStyle(ImageResource res) {
this(new Image(res.getSafeUri()));
}
/**
* Parametrized Ctor for pattern fills.
* @param res The image resource to use as a pattern.
* @param repetition Defines how the image should be repeated
*/
public PatternFillStyle(ImageResource res, RepetitionType repetition) {
this(new Image(res.getSafeUri()), repetition);
}
/**
* Parametrized Ctor for pattern fills.
* @param src The image resource to use as a pattern.
* @param repetition Defines how the image should be repeated
* @param offset Offset of the image in relation to encapsulating shape
*/
public PatternFillStyle(ImageResource res, RepetitionType repetition, Vector2d offset) {
this(new Image(res.getSafeUri()), repetition, offset);
}
/**
* Retrieve the employed image.
* @return The image
*/
public Image getImage() {
return image;
}
/**
* Assign an image.
* @param image The image to use
*/
public void setImage(Image image) {
this.image = image;
}
/**
* Assign an image resource.
* @param res The image resource to use
*/
public void setImage(ImageResource res) {
this.image = new Image(res.getSafeUri());
}
/**
* Retrieve the repetition type.
* The repetition type controls how an image is repeated.
* @return The repetition type
*/
public RepetitionType getRepetition() {
return repetition;
}
/**
* Assign a repetition type.
* The repetition type controls how an image is repeated.
* @param repetition A repetition type
*/
public void setRepetition(RepetitionType repetition) {
this.repetition = repetition;
}
/**
* Retrieve the image offset.
* @return The image offset relative to encapsulating shape coordinates
*/
public Vector2d getOffset() {
return offset;
}
/**
* Assign an image offset.
* @param offset An image offset relative to encapsulating shape coordinates
*/
public void setOffset(Vector2d offset) {
this.offset = offset;
}
}
|
/*
* Created on Apr 16, 2007
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.entity.pl;
import com.citibank.ods.common.entity.BaseODSEntity;
import com.citibank.ods.entity.pl.valueobject.BaseTplIpDocCallbackEntityVO;
/**
* @author gerson.a.rodrigues
*
*
* Preferences - Java - Code Style - Code Templates
*/
public class BaseTplIpDocCallbackEntity extends BaseODSEntity
{
public static final int C_CUST_NBR_SIZE = 11;
public static final int C_IP_DOC_CODE_SIZE = 6;
public static final int C_IP_DOC_TEXT_SIZE = 40;
public static final int C_IP_INVST_CUR_ACCT_IND_SIZE = 1;
/**
* Entity VO da categoria de risco
*/
protected BaseTplIpDocCallbackEntityVO m_data;
private String m_fullNameText;
/**
* Retorna o entity VO do agregador de produtos
* @return
*/
public BaseTplIpDocCallbackEntityVO getData()
{
return m_data;
}
public boolean equals( Object obj_ )
{
BaseTplIpDocCallbackEntity baseTplIpDocCallbackEntity = ( BaseTplIpDocCallbackEntity ) obj_;
boolean isCtcNbrEqual = baseTplIpDocCallbackEntity.getData().getCtcNbr().equals(
this.getData().getCtcNbr() );
return isCtcNbrEqual;
}
/**
* @return Returns fullNameText.
*/
public String getFullNameText()
{
return m_fullNameText;
}
/**
* @param fullNameText_ Field fullNameText to be setted.
*/
public void setFullNameText( String fullNameText_ )
{
m_fullNameText = fullNameText_;
}
} |
package com.gxtc.huchuan.ui.mine.classroom.profitList;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUserView;
import com.gxtc.commlibrary.data.BaseSource;
import com.gxtc.huchuan.bean.DistributionBean;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.List;
/**
* Describe:
* Created by ALing on 2017/5/4 .
*/
public class DistributionContract {
public interface View extends BaseUserView<Presenter> {
void showDistributionList(List<DistributionBean> datas);
void showRefreshFinish(List<DistributionBean> datas);
void showLoadMoreClass(List<DistributionBean> datas);
void showLoadMoreCircle(List<DistributionBean> datas);
void showNoMore();
}
public interface Presenter extends BasePresenter {
void getDistributionList(String type,String dateType, boolean isRefresh);
void loadMore(String type,String dateType);
}
public interface Source extends BaseSource {
void getDistributionList(String token, String start, String type,String dateType, ApiCallBack<List<DistributionBean>> callBack);
}
}
|
/*
Copyright 2017 Stratumn SAS. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.stratumn.sdk.model.client;
/***
* The secret abstract class
*
*/
public abstract class Secret
{
public static Secret newCredentialSecret(String email, String password)
{
return new CredentialSecret(email, password) ;
}
public static Secret newPrivateKeySecret(String privateKey)
{
return new PrivateKeySecret(privateKey) ;
}
public static Secret newProtectedKeySecret(String publicKey, String password)
{
return new ProtectedKeySecret(publicKey, password) ;
}
/**
* Helper method to test that an object is of type CredentialSecret
* @param secret
* @return
*/
public static boolean isCredentialSecret(Secret secret)
{
return (secret instanceof CredentialSecret);
}
/***
* Helper method to test that an object is of type PrivateKeySecret
* @param secret
* @return
*/
public static boolean isPrivateKeySecret(Secret secret)
{
return secret instanceof PrivateKeySecret;
}
/***
* Helper method to test that an object is of type ProtectedKeySecret
* @param secret
* @return
*/
public static Boolean isProtectedKeySecret(Secret secret)
{
return secret instanceof ProtectedKeySecret;
}
}
|
package mekfarm.containers;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.items.IItemHandler;
/**
* Created by CF on 2016-11-16.
*/
public class CropClonerContainer extends FarmContainer {
public CropClonerContainer(IInventory playerInventory, TileEntity te) {
super(playerInventory, te);
}
@Override
protected void addInputSlots(IItemHandler itemHandler, int inputs) {
if (inputs != 1) {
super.addInputSlots(itemHandler, inputs);
}
else {
addSlotToContainer(this.createInputSlot(itemHandler, 0, 118 + 18, 6));
}
}
@Override
protected Slot createInputSlot(IItemHandler itemHandler, int slotIndex, int xPosition, int yPosition) {
return new TexturedSlot(itemHandler, slotIndex, xPosition, yPosition, 135, 226, 4);
}
}
|
/**
* This code calculates the minimum edit required to convert one string to another and
* prints the changes required to convert string to another string
* References:
* 1. https://www.geeksforgeeks.org/print-all-possible-ways-to-convert-one-string-into-another-string-edit-distance/
* 2. https://www.youtube.com/watch?time_continue=1466&v=b6AGUjqIPsA
*/
import java.util.Scanner;
public class MinEditDisToConvertStr {
static int dp[][];
// Calculate DP Matrix to count minimum edit distance to convert one string to another
public static void calculateDPMatrix(String str1, String str2) {
if(str1 == null || str2 == null) {
return;
}
int len1 = str1.length();
int len2 = str2.length();
// intialize matrix with +1 to conside null also
int[][] DP = new int[len1 + 1][len2 + 1];
// initilize by the maximum edits possible
for (int i = 0; i <= len1; i++)
DP[i][0] = i;
for (int j = 0; j <= len2; j++)
DP[0][j] = j;
for(int i = 1; i <= len1 ; i++) {
for(int j = 1; j <= len2; j++) {
if(str1.charAt(i-1) == str2.charAt(j-1)) { //Simply copy from diagonal
DP[i][j] = DP[i - 1][j - 1];
} else {
DP[i][j] = min(DP[i][j - 1], DP[i - 1][j - 1], DP[i - 1][j]) + 1;
}
}
}
// initialize to global array
dp = DP;
}
// Function to find the minimum of three
static int min(int a, int b, int c)
{
int z = Math.min(a, b);
return Math.min(z, c);
}
// function to print changes requred to convert str1 to str2 based on DP Matrix
public static void printChanges(String s1, String s2) {
int i = s1.length();
int j = s2.length();
//check till the end
while(i != 0 && j != 0) {
if(s1.charAt(i - 1) == s2.charAt(j - 1)) {
i--;
j--;
} //replace
else if(dp[i][j] == dp[i - 1][j - 1] + 1) {
System.out.println("Replace " + s1.charAt(i - 1) + " with " +s2.charAt(j - 1));
i--;
j--;
} //remove
else if (dp[i][j] == dp[i - 1][j] + 1) {
System.out.println("Remove " + s1.charAt(i - 1));
i--;
} //add
else if(dp[i][j] == dp[i][j-1] + 1) {
System.out.println("Add " + s2.charAt(j - 1));
j--;
}
}
while(i != 0) {
System.out.println("Remove " + s1.charAt(i - 1));
i--;
}
while(j != 0) {
System.out.println("Add " + s2.charAt(j - 1));
j--;
}
}
// main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter string that needs to be change");
String str1 = sc.nextLine();
System.out.println("Enter string to compare with string");
String str2 = sc.nextLine();
calculateDPMatrix(str1, str2);
System.out.println("Minimum changes required: " + dp[str1.length()][str2.length()]);
printChanges(str1, str2);
sc.close();
}
} |
package com.frontlinerlzx.tmall_lzx.web;
import com.frontlinerlzx.tmall_lzx.pojo.Product;
import com.frontlinerlzx.tmall_lzx.pojo.ProductImage;
import com.frontlinerlzx.tmall_lzx.service.ProductImageService;
import com.frontlinerlzx.tmall_lzx.service.ProductService;
import com.frontlinerlzx.tmall_lzx.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author lzx
* @create 2019-08-30-12:02
*/
@RestController
public class ProductImageController {
@Autowired
ProductImageService productImageService;
@Autowired
ProductService productService;
/**
* 查询
*
* @param type
* @param pid
* @return
*/
@GetMapping("/products/{pid}/productImages")
public List<ProductImage> list(@RequestParam("type") String type, @PathVariable("pid") int pid) throws Exception {
Product product = productService.get(pid);
if (type.equals(productImageService.type_single))
return productImageService.listSingleProductImages(product);
else if (type.equals(productImageService.type_detail))
return productImageService.listDetailProductImages(product);
return new ArrayList<ProductImage>();
}
@PostMapping("/productImages")
public Object add(@RequestParam("pid") int pid, @RequestParam("type") String type, MultipartFile image, HttpServletRequest request) throws Exception {
Product product = productService.get(pid);
ProductImage bean = new ProductImage();
bean.setProduct(product);
bean.setType(type);
productImageService.add(bean);
StringBuffer path = new StringBuffer("img/");
if (type.equals(productImageService.type_single))
path.append("productSingle");
else if (type.equals(productImageService.type_detail))
path.append("productDetail");
File file = new File(request.getServletContext().getRealPath(path.toString()), bean.getId() + ".jpg");
String filename = file.getName();
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
try {
image.transferTo(file);
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
} catch (IOException e) {
e.printStackTrace();
}
if (type.equals(productImageService.type_single)) {
String smallFilePath = request.getServletContext().getRealPath("img/productSingle_small/" + filename);
String middleFilePath = request.getServletContext().getRealPath("img/productSingle_middle/" + filename);
File smallFile = new File(smallFilePath);
File middleFile = new File(middleFilePath);
if (!smallFile.getParentFile().exists()) smallFile.getParentFile().mkdirs();
if (!middleFile.getParentFile().exists()) middleFile.getParentFile().mkdirs();
ImageUtil.resizeImage(file, 56, 56, smallFile);
ImageUtil.resizeImage(file, 217, 190, middleFile);
}
return bean;
}
@DeleteMapping("/productImages/{id}")
public String delete(@PathVariable("id") int id, HttpServletRequest request) throws Exception {
ProductImage bean = productImageService.get(id);
productImageService.delete(id);
String path = "img/";
if (bean.getType().equals(productImageService.type_single))
path = path + "productSingle/";
else if (bean.getType().equals(productImageService.type_detail))
path = path + "productDetail/";
File file = new File(request.getServletContext().getRealPath(path + bean.getId() + ".jpg"));
String filename = file.getName();
file.delete();
if (bean.getType().equals(productImageService.type_single)) {
String smallFilePath = request.getServletContext().getRealPath("img/productSingle_small/" + filename);
String middleFilePath = request.getServletContext().getRealPath("img/productSingle_middle/" + filename);
File smallFile = new File(smallFilePath);
File middleFile = new File(middleFilePath);
smallFile.delete();
middleFile.delete();
}
return null;
}
}
|
/*
* @Title: MemcacheException.java
* @Package: com.scf.core.context.spring.memcache.exception
* @author wubin
* @date 2016年8月2日 上午11:17:23
* @version 1.3.1
*/
package com.scf.core.context.spring.memcache.exception;
import com.scf.core.exception.ExCode;
import com.scf.core.exception.sys.SystemException;
/**
* @author wubin
* @date 2016年8月2日 上午11:17:23
* @version V1.1.0
*/
public class MemcacheException extends SystemException {
/** @Fields serialVersionUID: */
private static final long serialVersionUID = 3123363884205879412L;
public MemcacheException(int code,String message, Throwable cause) {
super(code,message,cause);
}
public MemcacheException(int code,String message) {
super(code,message);
}
/**
* 默认配置异常
* @author wubin
* @param message 后台日志shortmessage
* @param cause
* @return
*/
public static MemcacheException defaultException(Throwable cause){
MemcacheException memcacheException = new MemcacheException(ExCode.MEMCACHED_001,ExCode.MEMCACHED_001+"",cause);
return memcacheException;
}
/**
* memcache未开启异常
* @author wubin
* @param message
* @param cause
* @return
*/
public static MemcacheException notOpenException(){
MemcacheException memcacheException = new MemcacheException(ExCode.MEMCACHED_002,"memcache未开启");
return memcacheException;
}
}
|
public class ShowStatus implements Command {
@Override
public void execute(String[] cmdParts) {
try {
ShopSystem shopSystem = ShopSystem.getInstance();
shopSystem.showStatus();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
package com.example.obroshi.alarmclock.view;
import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.obroshi.alarmclock.R;
import com.example.obroshi.alarmclock.controller.Controller;
import com.example.obroshi.alarmclock.model.AlertReceiver;
import com.example.obroshi.alarmclock.model.Constants;
import com.example.obroshi.alarmclock.model.MyAlarm;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.orm.query.Select;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final String TAG = MainActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private Controller.LocationCallback mLocationCallback;
final int REQUEST_CODE_ASK_LOCATION_PERMISSIONS = 111;
final int REQUEST_CODE_ASK_READ_CALENDAR_PERMISSIONS = 123;
final int ADD_ALARM_ACTIVITY_REQUEST_CODE = 123;
private RecyclerView mRecyclerView;
private AlarmsAdapter mAdapter;
private List<MyAlarm> myAlarmList = new ArrayList<>();
private TextView mEmptyMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences sharedPref = getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
boolean hasTimes = sharedPref.getBoolean(Constants.HAS_USER_TIMES, false);
if (!hasTimes) {
Log.d(TAG, "This is not 1st launch, continuing to alarms list activity");
Intent intent = new Intent(MainActivity.this, WelcomeActivity.class);
// Toast.makeText(this, "Has times: " + sharedPref.contains(Constants.HAS_USER_TIMES), Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
return;
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.alarmsRecyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.hasFixedSize();
mAdapter = new AlarmsAdapter(MainActivity.this, myAlarmList);
mRecyclerView.setAdapter(mAdapter);
mEmptyMsg = (TextView) findViewById(R.id.noAlarmsMsg);
FloatingActionButton mFab = (FloatingActionButton) findViewById(R.id.addAlarmFab);
mFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddAlarmActivity.class);
startActivityForResult(intent, ADD_ALARM_ACTIVITY_REQUEST_CODE);
}
});
if (mGoogleApiClient == null) {
// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addOnConnectionFailedListener(this)
.build();
}
mLocationCallback = new Controller.LocationCallback() {
@Override
public void onCurrentLocationReceived(double lat, double lng) {
Controller.getInstance().setCurrentLat(lat);
Controller.getInstance().setCurrentLng(lng);
showCalendarPermissionsPopUp();
}
};
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_ALARM_ACTIVITY_REQUEST_CODE
&& resultCode == RESULT_OK) {
String eventId = data.getStringExtra(AddAlarmActivity.EVENT_ID);
long rawAlarmTime = data.getLongExtra(AddAlarmActivity.KEY_RAW_ALARM_TIME, 0L);
String label = data.getStringExtra(AddAlarmActivity.KEY_ALARM_LABEL);
MyAlarm alarm;
if (!label.isEmpty()) {
alarm = new MyAlarm(eventId, rawAlarmTime, label);
} else {
alarm = new MyAlarm(eventId, rawAlarmTime);
}
myAlarmList.add(alarm);
alarm.save(); // save to DB : http://satyan.github.io/sugar/getting-started.html
mAdapter.notifyDataSetChanged();
}
}
@Override
protected void onStart() {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
loadAlarmsFromDb();
super.onStart();
setAlarm();
}
/* Get all the items from the alarms.db
Source: https://guides.codepath.com/android/Clean-Persistence-with-Sugar-ORM
*/
private void loadAlarmsFromDb() {
if (myAlarmList == null) {
myAlarmList = new ArrayList<>();
} else {
myAlarmList.clear();
}
// long count = MyAlarm.count(MyAlarm.class);
// get all alarms, sorted my Raw Alarm Time;
List<MyAlarm> list = MyAlarm.listAll(MyAlarm.class, "m_raw_alarm_time");
for (int i = 0; i < list.size(); i++) {
myAlarmList.add(list.get(i));
}
Log.d(TAG, list.size() + " alarms found");
if (myAlarmList.size() > 0) {
mEmptyMsg.setVisibility(View.GONE);
} else {
mEmptyMsg.setVisibility(View.VISIBLE);
}
mAdapter.notifyDataSetChanged();
}
public void showLocationPermissionsPopUp() {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_ASK_LOCATION_PERMISSIONS);
}
private void showCalendarPermissionsPopUp() {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CALENDAR},
REQUEST_CODE_ASK_READ_CALENDAR_PERMISSIONS);
}
@Override
protected void onStop() {
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
Log.d(TAG, "Successfully disconnected from Google Play Services");
}
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "Successfully Connected to Google Play Services");
if (mGoogleApiClient.isConnected()) {
showLocationPermissionsPopUp();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_ASK_READ_CALENDAR_PERMISSIONS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Calendar permissions granted");
// FragmentManager fragmentManager = getSupportFragmentManager();
// mFragment = new EventsListFragment();
// if (fragmentManager.findFragmentByTag("EventsListFragment") == null)
// fragmentManager.beginTransaction().add(R.id.container, mFragment, "EventsListFragment").commitAllowingStateLoss();
} else {
Log.d(TAG, "Calendar permissions denied, request popup is shown");
showCalendarPermissionsPopUp();
}
return;
case REQUEST_CODE_ASK_LOCATION_PERMISSIONS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Location permissions granted");
Controller.getInstance().getCurrentLocation(getBaseContext(), mGoogleApiClient, mLocationCallback);
} else {
Log.d(TAG, "Location permissions denied, request popup is shown");
showLocationPermissionsPopUp();
}
return;
default:
}
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Connection to Google Play Services suspended");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "Failed to Connected to Google Play Services");
}
public void setAlarm() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.add(Calendar.SECOND, 5);
Intent alertIntent = new Intent(this, AlertReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), PendingIntent.getBroadcast(this, 1,
alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
|
package Utility;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
public class TestConfig{
static monitoringMail mail = new monitoringMail();
public static void mailSender() throws AddressException, MessagingException{
mail.sendMail(server, from, to, subject, messageBody, attachmentPath, attachmentName);
}
public static String server="smtp.gmail.com";
public static String from = "shareid02@gmail.com";
public static String password = "share123";
public static String[] to ={"amanmehndiratt@gmail.com"};
public static String subject = "Clove Dental PRM - Automation Scheduled Report";
public static String messageBody ="PFA";
public static String attachmentPath=System.getProperty("user.dir")+"\\Reports.zip";
public static String attachmentName="reports.zip";
//SQL DATABASE DETAILS
public static String driver="net.sourceforge.jtds.jdbc.Driver";
public static String dbConnectionUrl="jdbc:jtds:sqlserver://192.101.44.22;DatabaseName=monitor_eval";
public static String dbUserName="sa";
public static String dbPassword="$ql$!!1";
//MYSQL DATABASE DETAILS
public static String mysqldriver="com.mysql.jdbc.Driver";
public static String mysqluserName = "root";
public static String mysqlpassword = "selenium";
public static String mysqlurl = "jdbc:mysql://localhost:3306/8thmay2016";
}
|
package com.practice;
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
System.out.println("---Welcome to Rock Paper Scissors Game---");
System.out.println("Notations:");
System.out.println("(a) Rock = 0");
System.out.println("(b) Paper = 1");
System.out.println("(c) Scissor = 2");
System.out.println("Lets start the game:-)");
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int i = 1;
int player = 0;
int comp = 0;
while (i<=5) {
System.out.println("\nRound " +i+":");
System.out.print("Enter your choice: ");
byte choice = sc.nextByte();
int c_choice = rand.nextInt(3);
System.out.println("Computer chooses: " + c_choice);
if (choice == c_choice)
System.out.println("Match Draws");
else {
if (choice == 0) {
if (c_choice == 1) {
System.out.println("Computer Wins!");
comp++;
}
else if (c_choice == 2) {
System.out.println("You Win!!!");
player++;
}
}
if (choice == 1) {
if (c_choice == 2){
System.out.println("Computer Wins!");
comp++;
}
else if (c_choice == 0) {
System.out.println("You Win!!!");
player++;
}
}
if (choice == 2) {
if (c_choice == 0) {
System.out.println("Computer Wins!");
comp++;
}
else if (c_choice == 1) {
System.out.println("You Win!!!");
player++;
}
}
}
i++;
}
if(player > comp)
System.out.println("\nPlayer wins by " + player + "-" + comp);
else
System.out.println("\nComputer wins by " + comp + "-" + player);
}
}
|
package service.listados;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import com.google.gson.Gson;
import dao.ConfigDAO;
import dao.empleado.EmpleadoDAO;
import dao.empleadoHorario.EmpleadoHorarioDAO;
import dao.horario.HorarioDAO;
import dao.item.ItemDAO;
import dao.listados.ListadosDAO;
import dao.listados.ListadosDAOInsertUpdate;
import dao.listados.TipoEstatusDAO;
import dao.movimientos.MovimientosDAO;
import dao.movimientos.ordenes.OrdenesDAO;
import dao.partners.PartnerDAO;
import dao.user.UserDAO;
import dao.user.perfil.PerfilDAO;
import dto.empleado.EmpleadoDTO;
import dto.empleado.EmpleadoHorarioDTO;
import dto.empleado.EspecialidadDTO;
import dto.empleado.NivelAcademicoDTO;
import dto.horario.HorarioDTO;
import dto.listados.ColoniaDTO;
import dto.listados.ConfigCamposTipoItemDTO;
import dto.listados.EntidadFederativaDTO;
import dto.listados.EstadoCivilDTO;
import dto.listados.GeneroDTO;
import dto.listados.GradoEscolarDTO;
import dto.listados.GrupoSanguineoDTO;
import dto.listados.MunicipioDTO;
import dto.listados.PeriodoEscolarDTO;
import dto.listados.TipoEstatusDTO;
import dto.listados.TotalTiposLlamadasDTO;
import dto.listados.items.ItemDTO;
import dto.listados.items.LineaItemDTO;
import dto.listados.items.MarcaItemDTO;
import dto.listados.items.ModeloItemDTO;
import dto.listados.items.TipoItemDTO;
import dto.logs.ErroresDTO;
import dto.ordenes.DepartamentoDTO;
import dto.ordenes.LugarDTO;
import dto.ordenes.RadioDTO;
import dto.ordenes.TecnicoDTO;
import dto.ordenes.VehiculoDTO;
import dto.partner.PartnerDTO;
import dto.user.UserConfigDTO;
import dto.user.UserDTO;
import dto.user.UserSimpleDTO;
import dto.user.perfil.PerfilDTO;
import herramientas.FechaDTO;
import herramientas.herrramientasrs.HerramientasResultSet;
import herramientas.imagenes.ProcesarImagen;
public class ListadosService {
private EmpleadoDAO empleadoDAO;
private ListadosDAO listadosDAO;
private HorarioDAO horarioDAO;
private UserDAO userDAO;
private ItemDAO itemDAO;
private ConfigDAO configDAO;
private TipoEstatusDAO tipoEstatusDAO;
private PerfilDAO perfilDAO;
private ProcesarImagen procesarImagen;
private MovimientosDAO movimientosDAO;
private ListadosDAOInsertUpdate listadoDAOIU;
private OrdenesDAO ordenesDAO;
private PartnerDAO partnerDAO;
/**
* INICIALIZA LOS COMPONENTES DE LA CLASE
*/
public ListadosService(){
if(this.getEmpleadoDAO() == null){
setEmpleadoDAO(new EmpleadoDAO());
}
if(this.getListadosDAO() == null){
setListadosDAO(new ListadosDAO());
}
if(this.getHorarioDAO() == null){
setHorarioDAO(new HorarioDAO());
}
if(this.getUserDAO() == null){
setUserDAO(new UserDAO());
}
if(this.getItemDAO() == null){
this.setItemDAO(new ItemDAO());
}
if(this.getConfigDAO() == null){
this.setConfigDAO(new ConfigDAO());
}
if(this.getTipoEstatusDAO() == null){
this.setTipoEstatusDAO(new TipoEstatusDAO());
}
if(this.getPerfilDAO() == null){
this.setPerfilDAO(new PerfilDAO());
}
if(this.getProcesarImagen() == null){
this.setProcesarImagen(new ProcesarImagen());
}
if(this.getMovimientosDAO() == null){
this.setMovimientosDAO(new MovimientosDAO());
}
if(this.getListadoDAOIU() == null){
this.setListadoDAOIU(new ListadosDAOInsertUpdate());
}
if(this.getOrdenesDAO() == null){
this.setOrdenesDAO(new OrdenesDAO());
}
if(this.getPartnerDAO() == null){
this.setPartnerDAO(new PartnerDAO());
}
}
/**
* INICIALIZA LOS COMPONENTES DE LA CLASE
*/
public ListadosService(int conexion){
if(this.getEmpleadoDAO() == null && conexion == 1){
setEmpleadoDAO(new EmpleadoDAO());
}
if(this.getListadosDAO() == null && conexion == 2){
setListadosDAO(new ListadosDAO());
}
if(this.getHorarioDAO() == null && conexion == 3){
setHorarioDAO(new HorarioDAO());
}
if(this.getUserDAO() == null && conexion == 4){
setUserDAO(new UserDAO());
}
if(this.getItemDAO() == null && conexion == 5){
this.setItemDAO(new ItemDAO());
}
if(this.getConfigDAO() == null && conexion == 6){
this.setConfigDAO(new ConfigDAO());
}
if(this.getTipoEstatusDAO() == null && conexion == 7){
this.setTipoEstatusDAO(new TipoEstatusDAO());
}
if(this.getPerfilDAO() == null && conexion == 8){
this.setPerfilDAO(new PerfilDAO());
}
if(this.getProcesarImagen() == null && conexion == 9){
this.setProcesarImagen(new ProcesarImagen());
}
if(this.getMovimientosDAO() == null && conexion == 10){
this.setMovimientosDAO(new MovimientosDAO());
}
if(this.getListadoDAOIU() == null && conexion == 11){
this.setListadoDAOIU(new ListadosDAOInsertUpdate());
}
if(this.getOrdenesDAO() == null && conexion == 12){
this.setOrdenesDAO(new OrdenesDAO());
}
}
/**
* @return the empleadoDAO
*/
public EmpleadoDAO getEmpleadoDAO() {
return empleadoDAO;
}
/**
* @param empleadoDAO the empleadoDAO to set
*/
public void setEmpleadoDAO(EmpleadoDAO empleadoDAO) {
this.empleadoDAO = empleadoDAO;
}
/**
* @return the listadosDAO
*/
public ListadosDAO getListadosDAO() {
return listadosDAO;
}
/**
* @param listadosDAO the listadosDAO to set
*/
public void setListadosDAO(ListadosDAO listadosDAO) {
this.listadosDAO = listadosDAO;
}
/**
* @return the horarioDAO
*/
public HorarioDAO getHorarioDAO() {
return horarioDAO;
}
/**
* @param horarioDAO the horarioDAO to set
*/
public void setHorarioDAO(HorarioDAO horarioDAO) {
this.horarioDAO = horarioDAO;
}
/**
* @return the userDAO
*/
public UserDAO getUserDAO() {
return userDAO;
}
/**
* @param userDAO the userDAO to set
*/
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
/**
* @return the itemDAO
*/
public ItemDAO getItemDAO() {
return itemDAO;
}
/**
* @param itemDAO the itemDAO to set
*/
public void setItemDAO(ItemDAO itemDAO) {
this.itemDAO = itemDAO;
}
/**
* @return the configDAO
*/
public ConfigDAO getConfigDAO() {
return configDAO;
}
/**
* @param configDAO the configDAO to set
*/
public void setConfigDAO(ConfigDAO configDAO) {
this.configDAO = configDAO;
}
/**
* @return the tipoEstatusDAO
*/
public TipoEstatusDAO getTipoEstatusDAO() {
return tipoEstatusDAO;
}
/**
* @param tipoEstatusDAO the tipoEstatusDAO to set
*/
public void setTipoEstatusDAO(TipoEstatusDAO tipoEstatusDAO) {
this.tipoEstatusDAO = tipoEstatusDAO;
}
/**
* @return the perfilDAO
*/
public PerfilDAO getPerfilDAO() {
return perfilDAO;
}
/**
* @param perfilDAO the perfilDAO to set
*/
public void setPerfilDAO(PerfilDAO perfilDAO) {
this.perfilDAO = perfilDAO;
}
/**
* @return the procesarImagen
*/
public ProcesarImagen getProcesarImagen() {
return procesarImagen;
}
/**
* @param procesarImagen the procesarImagen to set
*/
public void setProcesarImagen(ProcesarImagen procesarImagen) {
this.procesarImagen = procesarImagen;
}
public MovimientosDAO getMovimientosDAO() {
return movimientosDAO;
}
public void setMovimientosDAO(MovimientosDAO movimientosDAO) {
this.movimientosDAO = movimientosDAO;
}
/**
* @return the listadoDAOIU
*/
public ListadosDAOInsertUpdate getListadoDAOIU() {
return listadoDAOIU;
}
/**
* @param listadoDAOIU the listadoDAOIU to set
*/
public void setListadoDAOIU(ListadosDAOInsertUpdate listadoDAOIU) {
this.listadoDAOIU = listadoDAOIU;
}
/**
*
* @param request
* @param response
*/
public void selectUsersService(HttpServletRequest request, HttpServletResponse response){
Vector<UserDTO> usuarios = getUserDAO().selectUsers();
if(usuarios != null && usuarios.size() > 0){
request.setAttribute("elementos", usuarios);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
Vector<UserConfigDTO> userConfigs = new Vector<>();
userConfigs = getUserDAO().selectUserConfigDTO(true);
if(userConfigs != null && userConfigs.size() > 0){
request.setAttribute("initServices", userConfigs);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
Vector<PerfilDTO> perfiles = new Vector<>();
perfiles = getPerfilDAO().selectPerfilesPorStatus(1);
if(perfiles != null && perfiles.size() > 0){
request.setAttribute("perfiles", perfiles);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
Vector<EmpleadoDTO> empleados = new Vector<>();
empleados = getEmpleadoDAO().selectNombreIdEmpleados(0);
if(empleados != null && empleados.size() > 0){
request.setAttribute("empleados", empleados);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
/*if(usuarios != null){
String json = new Gson().toJson(usuarios);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
/**
*
* @param request
* @param response
*/
public void selectDeptosOrdenesService(HttpServletRequest request, HttpServletResponse response){
Vector<DepartamentoDTO> deptos = getOrdenesDAO().selectDeptosDTO();
if(deptos != null && deptos.size() > 0){
request.setAttribute("items", deptos);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void selectDeptosComoboTecnicosOrdenesService(HttpServletRequest request, HttpServletResponse response){
Vector<DepartamentoDTO> deptos = getOrdenesDAO().selectDeptosDTO();
if(deptos != null && deptos.size() > 0){
request.setAttribute("departamentos", deptos);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void selectLugaresOrdenesService(HttpServletRequest request, HttpServletResponse response){
Vector<LugarDTO> lugares = getOrdenesDAO().selectLugaresDTO();
if(lugares != null && lugares.size() > 0){
request.setAttribute("items", lugares);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void selectRadiosOrdenesService(HttpServletRequest request, HttpServletResponse response){
selectTecnicosComboRadioOrdenesService(request, response);
Vector<RadioDTO> radiosDTO = getOrdenesDAO().selectRadiosDTO();
if(radiosDTO != null && radiosDTO.size() > 0){
request.setAttribute("items", radiosDTO);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void selectTecnicosComboRadioOrdenesService(HttpServletRequest request, HttpServletResponse response){
Vector<TecnicoDTO> tecnicosDTO = getOrdenesDAO().selectTecnicosDTO();
if(tecnicosDTO != null && tecnicosDTO.size() > 0){
request.setAttribute("tecnicos", tecnicosDTO);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void selectTecnicosOrdenesService(HttpServletRequest request, HttpServletResponse response){
selectDeptosComoboTecnicosOrdenesService(request, response);
Vector<TecnicoDTO> tecnicosDTO = getOrdenesDAO().selectTecnicosDTO();
if(tecnicosDTO != null && tecnicosDTO.size() > 0){
request.setAttribute("items", tecnicosDTO);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void selectVehiculosOrdenesService(HttpServletRequest request, HttpServletResponse response){
Vector<VehiculoDTO> vehiculoDTOs = getOrdenesDAO().selectVehiculosDTO();
if(vehiculoDTOs != null && vehiculoDTOs.size() > 0){
request.setAttribute("items", vehiculoDTOs);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void procesaFormItemOrdenesService(HttpServletRequest request, HttpServletResponse response){
String tipoItem = request.getParameter("itemDesc") + "DTO";
switch (tipoItem) {//EN SIGULAR
case "DepartamentoDTO":
procesaFormItemDeptoOrdenesDTO(request, response);
break;
case "LugarDTO":
procesaFormItemLugarOrdenesDTO(request, response);
break;
case "RadioDTO":
procesaFormItemRadioOrdenesDTO(request, response);
break;
case "TecnicoDTO":
procesaFormItemTecnicoOrdenesDTO(request, response);
break;
case "VehiculoDTO":
procesaFormItemVehiculoOrdenesDTO(request, response);
break;
default:
break;
}
}
/**
*
* @param request
* @param response
*/
public void procesaFormItemDeptoOrdenesDTO(HttpServletRequest request, HttpServletResponse response){
DepartamentoDTO depto = new DepartamentoDTO();
String campo = "";
String missingFields = "";
campo = "field1";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
depto.setDepartamentoId(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
campo = "field2";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
depto.setNombre(request.getParameter(campo));
}else{
missingFields += "missing: "+campo;
}
campo = "field3";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
depto.setSiglas(request.getParameter(campo));
}else{
missingFields += "missing: "+campo;
}
if(missingFields.length() > 0){
System.out.println(missingFields);
}
int res = -1;
if(depto.getDepartamentoId() == 0){
res = getOrdenesDAO().insertNewDepto(depto);
}else{
if(depto.getDepartamentoId() > 0){
res = getOrdenesDAO().updateDeptoDTO(depto);
}else{
System.out.println("error depto.getDepartamentoId() < 0");
}
}
if(res > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Faltantes: " + missingFields);
depto = null;
}
/**
*
* @param request
* @param response
*/
public void procesaFormItemLugarOrdenesDTO(HttpServletRequest request, HttpServletResponse response){
LugarDTO lugarDTO = new LugarDTO();
String campo = "";
String missingFields = "";
campo = "field1";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
lugarDTO.setLugarId(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
campo = "field2";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
lugarDTO.setNombre(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field3";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
lugarDTO.setUbicacion(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field4";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
lugarDTO.setTipo(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
if(missingFields.length() > 0){
System.out.println(missingFields);
}
int res = -1;
if(lugarDTO.getLugarId() == 0){
res = getOrdenesDAO().insertNewLugar(lugarDTO);
}else{
if(lugarDTO.getLugarId() > 0){
res = getOrdenesDAO().updateLugarDTO(lugarDTO);
}else{
System.out.println("error depto.getDepartamentoId() < 0");
}
}
if(res > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Faltantes: " + missingFields);
lugarDTO = null;
}
/**
*
* @param request
* @param response
*/
public void procesaFormItemRadioOrdenesDTO(HttpServletRequest request, HttpServletResponse response){
RadioDTO radioDTO = new RadioDTO();
String campo = "";
String missingFields = "";
campo = "field1";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
radioDTO.setRadioId(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
campo = "field2";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
radioDTO.setRfsi(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field3";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
radioDTO.setTipo(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field4";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
radioDTO.setMarca(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field5";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
radioDTO.setModelo(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field6";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
radioDTO.setSerie(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field7";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
radioDTO.getTecnicoDTO().setTecnicoId(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
if(missingFields.length() > 0){
System.out.println(missingFields);
}
int res = -1;
if(radioDTO.getRadioId() == 0){
res = getOrdenesDAO().insertNewRadioDTO(radioDTO);
}else{
if(radioDTO.getRadioId() > 0){
res = getOrdenesDAO().updateRadioDTO(radioDTO);
}else{
System.out.println("error depto.getDepartamentoId() < 0");
}
}
if(res > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Faltantes: " + missingFields);
radioDTO = null;
}
/**
*
* @param request
* @param response
*/
public void procesaFormItemTecnicoOrdenesDTO(HttpServletRequest request, HttpServletResponse response){
TecnicoDTO tecnicoDTO = new TecnicoDTO();
String campo = "";
String missingFields = "";
campo = "field1";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.setTecnicoId(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
campo = "field2";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.setIniciales(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field3";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.setTitulo(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field4";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.setNombre(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field5";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.setPuesto(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field6";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.getDepartamentoDTO().setDepartamentoId(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
campo = "field7";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.setMando(request.getParameter(campo).toUpperCase());
}else{
tecnicoDTO.setMando("N/D");
missingFields += "missing: "+campo;
}
campo = "field8";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
tecnicoDTO.setLicencia(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
if(missingFields.length() > 0){
System.out.println(missingFields);
}else{
System.out.println("Sin campos faltantes");
}
int res = -1;
if(tecnicoDTO.getTecnicoId() == 0){
res = getOrdenesDAO().insertNewTecnicoDTO(tecnicoDTO);
}else{
if(tecnicoDTO.getTecnicoId() > 0){
res = getOrdenesDAO().updateTecnicoDTO(tecnicoDTO);
}else{
System.out.println("error depto.getDepartamentoId() < 0");
}
}
if(res > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Faltantes: " + missingFields);
tecnicoDTO = null;
}
/**
*
* @param request
* @param response
*/
public void procesaFormItemVehiculoOrdenesDTO(HttpServletRequest request, HttpServletResponse response){
VehiculoDTO vehiculoDTO = new VehiculoDTO();
String campo = "";
String missingFields = "";
campo = "field1";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setVehiculoId(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
campo = "field2";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setNombre(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field3";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setTipo(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field4";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setMarca(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field5";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setLinea(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field6";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setModelo(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field7";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setPlacas(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}campo = "field8";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setInventario(request.getParameter(campo).toUpperCase());
}else{
vehiculoDTO.setInventario("N/D");
missingFields += "missing: "+campo;
}
campo = "field9";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setNumPolizaSeguro(request.getParameter(campo).toUpperCase());
}else{
missingFields += "missing: "+campo;
}
campo = "field10";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
vehiculoDTO.setActivo(String.valueOf(request.getParameter(campo)).charAt(0));
}else{
missingFields += "missing: "+campo;
}
if(missingFields.length() > 0){
System.out.println(missingFields);
}
int res = -1;
if(vehiculoDTO.getVehiculoId() == 0){
res = getOrdenesDAO().insertNewVehiculoDTO(vehiculoDTO);
}else{
if(vehiculoDTO.getVehiculoId() > 0){
res = getOrdenesDAO().updateVehiculoDTO(vehiculoDTO);
}else{
System.out.println("error depto.getDepartamentoId() < 0");
}
}
if(res > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Faltantes: " + missingFields);
vehiculoDTO = null;
}
/**
*
* @param request
* @param response
*/
public void selectPerfilUserService(HttpServletRequest request, HttpServletResponse response){
Vector<PerfilDTO> perfiles = getPerfilDAO().selectPerfiles();
if(perfiles != null && perfiles.size() > 0){
request.setAttribute("elementos", perfiles);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void selectEmpleadoService(HttpServletRequest request, HttpServletResponse response){
String empleadoSku = request.getParameter("skuEmpleado");
if(empleadoSku != null && !empleadoSku.isEmpty()){
EmpleadoDTO empleado = getEmpleadoDAO().selectEmpleadoPorSku(empleadoSku, 1);
if(empleado != null){
String json = new Gson().toJson(empleado);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
try {
response.getWriter().append("-2");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void selectEmpleadosConSinUsario(HttpServletRequest request, HttpServletResponse response){
String conSinUsuario = request.getParameter("usuario");
if(conSinUsuario != null && !conSinUsuario.isEmpty()){
Vector<EmpleadoDTO> empleados = null;
if(conSinUsuario.equals("si")){
empleados = getEmpleadoDAO().selectNombreIdEmpleadosSinUsuario(0);
}else{
empleados = getEmpleadoDAO().selectNombreIdEmpleados(0);
}
if(empleados != null && empleados.size() > 0){
String json = new Gson().toJson(empleados);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
}
}
/**
*
* @param request
* @param response
*/
public void nuevoModeloService(HttpServletRequest request, HttpServletResponse response){
ModeloItemDTO modelo = new ModeloItemDTO();
modelo.setNombreModeloItem(request.getParameter("nombreModelo") != null ? request.getParameter("nombreModelo") : "");
modelo.setSkuModeloItem(request.getParameter("sku") != null ? Integer.parseInt(request.getParameter("sku")) : 0);
modelo.getTipoItem().setIdTipoItem(request.getParameter("tiposItems") != null ? Integer.parseInt(request.getParameter("tiposItems")) : 0);
modelo.setStatusModelo(request.getParameter("statusModelo") != null ? Integer.parseInt(request.getParameter("statusModelo")) : 0);
int res = getListadoDAOIU().insertModeloItemDTO(modelo);
try {
response.getWriter().append(String.valueOf(res));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param request
* @param response
*/
public void nuevoUsuarioService(HttpServletRequest request, HttpServletResponse response){
UserSimpleDTO userSimpleDTO = verificaFormUsuario(request, response);
if(userSimpleDTO != null){
if(userSimpleDTO.getIdUser() > 0) {
//actualiza
userSimpleDTO = getUserDAO().actualizaUserSimpleDTO(userSimpleDTO);
}else{
//crea
userSimpleDTO = getUserDAO().insertUserSimpleDTO(userSimpleDTO);
}
if(userSimpleDTO.getIdUser() > 0){
//actualiza la foto en base a un usuario creado
if(userSimpleDTO.getUserAvatar().getImgPart() != null){
int res = actualizaImagenUsuario(userSimpleDTO);
if (res > 0) {
System.out.println("foto procesada correctamente");
System.out.println("usuario con foto insertado correctamente");
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else{
// erroresString += "Foto,";
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
System.out.println("avatar2 == null");
System.out.println("usuario insertado correctamente");
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public int actualizaImagenUsuario(UserSimpleDTO userSimpleDTO){
int res = -1;
UserDTO userDTO = new UserDTO();
userDTO.setUserId(userSimpleDTO.getIdUser());
res = getUserDAO().actualizarAvatarUsuario(userDTO, userSimpleDTO.getUserAvatar().getImgPart());
return res;
}
/**
*
* @param request
* @param response
*/
public void selectEmpleadoParaRegistroAsistenciaService(HttpServletRequest request, HttpServletResponse response){
String empleadoSku = request.getParameter("skuEmpleado");
if(empleadoSku != null && !empleadoSku.isEmpty()){
EmpleadoDTO empleado = getEmpleadoDAO().selectEmpleadoPorSku(empleadoSku, 1);
if(empleado != null){
String json = new Gson().toJson(empleado);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
try {
response.getWriter().append("-2");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public UserSimpleDTO verificaFormUsuario(HttpServletRequest request, HttpServletResponse response){
UserSimpleDTO userDTO = null;
String errores = null;
System.out.println(request.getParameter("login"));
if(request.getParameter("login") != null && !request.getParameter("login").isEmpty()){
userDTO = new UserSimpleDTO();
if(request.getParameter("idUserHidden") != null && !request.getParameter("idUserHidden").isEmpty()){
userDTO.setIdUser(Integer.parseInt(request.getParameter("idUserHidden")));
}else{
// errores = ", idUserHidden";
}
userDTO.setLogin(request.getParameter("login"));
if(request.getParameter("perfil") != null && !request.getParameter("perfil").isEmpty()){
userDTO.getUserProfile().setIdPerfil(Integer.parseInt(request.getParameter("perfil")));
}else{
errores = "perfil";
}
if(request.getParameter("initService") != null && !request.getParameter("initService").isEmpty()){
userDTO.setFkIdUserConfig(Integer.parseInt(request.getParameter("initService")));
}else{
errores = ", initService";
}
if(request.getParameter("name") != null && !request.getParameter("name").isEmpty()){
userDTO.setName(request.getParameter("name"));
}else{
errores = ", name";
}
if(request.getParameter("email") != null && !request.getParameter("email").isEmpty()){
userDTO.setEmail(request.getParameter("email"));
}else{
errores = ", email";
}
if(request.getParameter("timeOut") != null && !request.getParameter("timeOut").isEmpty()){
userDTO.setSessionTimeOut(Integer.parseInt(request.getParameter("timeOut")));
}else{
errores = ", timeOut";
}
if(request.getParameter("activo") != null && !request.getParameter("activo").isEmpty()){
userDTO.setActive(request.getParameter("activo").charAt(0));
}else{
userDTO.setActive('N');
}
try {
if(request.getPart("userAvatar") != null && request.getPart("userAvatar").getSize() > 0){
userDTO.getUserAvatar().setImgPart(getProcesarImagen().procesarImagenRequest(request, response, "userAvatar"));
}else{
errores = ", userAvatar";
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
if(request.getParameter("idEmpleado") != null && !request.getParameter("idEmpleado").isEmpty()){
userDTO.setFkIdEmpleado(Integer.parseInt(request.getParameter("idEmpleado")));
}else{
errores = ", idEmpleado";
}
}else{
errores = ", login";
}
if(errores != null && !errores.isEmpty()){
System.err.println(errores);
}
return userDTO;
}
/**
*
* @param request
* @param response
*/
public void buscarEmpleado(HttpServletRequest request, HttpServletResponse response){
int numLimit = (request.getParameter("numLimit") != null && !request.getParameter("numLimit").equals("") && request.getParameter("numLimit").length() > 0 ? Integer.parseInt( request.getParameter("numLimit")): 30);
int ultimoE = 0;
String skuEmpleado = request.getParameter("skuEmpleado") != null && !request.getParameter("skuEmpleado").equals("") && request.getParameter("skuEmpleado").length() > 0 ? (String) request.getParameter("skuEmpleado") : null ;
EmpleadoDTO persona = null;
if(skuEmpleado != null) {
persona = getEmpleadoDAO().selectEmpleadoPorSku(skuEmpleado,numLimit);
if (persona != null){
System.out.println("datos bd " + persona.getNombreEmpleado() );
Vector <EmpleadoDTO> v = new Vector<EmpleadoDTO>();
v.add(persona);
request.setAttribute("empleados", v);
request.setAttribute("filtroLimit", numLimit);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
request.setAttribute("filtroId",skuEmpleado);
}else{
String nombre = request.getParameter("nombre") != null && !request.getParameter("nombre").equals("") && request.getParameter("nombre").length() > 0 ? (String) request.getParameter("nombre"): null;
if(nombre != null){
Vector<EmpleadoDTO> v = null;
v = getEmpleadoDAO().selectEmpleadoPorNombre(nombre,numLimit,ultimoE);
if (v.size() > 0){
//System.out.println("datos bd " + v.getNombreEmpleado() );
EmpleadoDTO ultimoEmpleado = v.lastElement();
int idUltimoEmpleado = ultimoEmpleado.getIdEmpleado();
request.setAttribute("empleados", v);
request.setAttribute("filtroLimit", numLimit);
request.setAttribute("ultEmpleado", idUltimoEmpleado);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
request.setAttribute("filtroNombre", nombre);
}else {
Vector<EmpleadoDTO> vtodos = null;
vtodos = getEmpleadoDAO().selectEmpleadoTodos(numLimit);
if(vtodos.size() > 0){
EmpleadoDTO ultimoEmpleado = vtodos.lastElement();
int idUltimoEmpleado = ultimoEmpleado.getIdEmpleado();
int skuUltimoEmpleado = ultimoEmpleado.getSkuEmpleado();
int ultSkuEmpleado = skuUltimoEmpleado+1;
request.setAttribute("empleados",vtodos);
request.setAttribute("filtroLimit", numLimit);
request.setAttribute("ultEmpleado", idUltimoEmpleado);
request.setAttribute("ultimoSkuEmpleado", ultSkuEmpleado);
}
}
}
}
/**
*
* @param request
* @param response
*/
public void obtenerGeneros(HttpServletRequest request, HttpServletResponse response){
Vector<GeneroDTO> vgeneros = new Vector<GeneroDTO>();
vgeneros = getListadosDAO().selectGeneros();
if(vgeneros.size() > 0){
request.setAttribute("listadoGeneros", vgeneros);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void nuevoSkuEmpleado(HttpServletRequest request, HttpServletResponse response){
int nuevoSku = -1;
nuevoSku = getEmpleadoDAO().nuevoSkuEmpleado();
if(nuevoSku > 0){
System.out.println(nuevoSku);
try {
response.getWriter().append(String.valueOf(nuevoSku));
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().write("No se encontro registro");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void selectGeneros(HttpServletRequest request, HttpServletResponse response){
Vector<GeneroDTO> vgeneros = new Vector<GeneroDTO>();
vgeneros = getListadosDAO().selectGeneros();
if(vgeneros.size() > 0){
String json = new Gson().toJson(vgeneros);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("VECTOR VACIO DE GENEROS");
GeneroDTO genero = new GeneroDTO();
genero.setNombreGenero("Sin generos!");
vgeneros.add(genero);
String json = new Gson().toJson(vgeneros);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void selectEstadosCiviles(HttpServletRequest request, HttpServletResponse response){
Vector<EstadoCivilDTO> vEstCiviles = new Vector<EstadoCivilDTO>();
int idGenero = (request.getParameter("idGenero") != null ? Integer.parseInt(request.getParameter("idGenero")) : 0);
//System.out.println("idGenero "+idGenero);
vEstCiviles = getListadosDAO().selectEstadosCivilesPorGenero(idGenero);
if(vEstCiviles.size() > 0){
for (EstadoCivilDTO estadoCivilDTO : vEstCiviles) {
System.out.println(estadoCivilDTO.getNombreEstadoCivil());
}
}else{
System.out.println("VECTOR VACIO DE ESTADOS CIVILES");
EstadoCivilDTO estCiv = new EstadoCivilDTO();
estCiv.setNombreEstadoCivil("Sin Estado Civil");
vEstCiviles.add(estCiv);
}
String json = new Gson().toJson(vEstCiviles);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param request
* @param response
*/
public void obtenerEstados(HttpServletRequest request, HttpServletResponse response){
Vector<EntidadFederativaDTO> ventidades = new Vector<EntidadFederativaDTO>();
ventidades = getListadosDAO().selectEntidadFederativa();
if(ventidades.size() > 0){
request.setAttribute("listadoEntidades", ventidades);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void consultarllamadasService(HttpServletRequest request, HttpServletResponse response){
Vector<TotalTiposLlamadasDTO> llamadasTotales = new Vector<TotalTiposLlamadasDTO>();
llamadasTotales = getListadosDAO().selectTotalesTiposDeLlamadasDTO();
if(llamadasTotales.size() > 0){
request.setAttribute("llamadas", llamadasTotales);
}else{
request.setAttribute("mensaje", "No se encontro llamadasTotales");
}
}
/**
*
* @param request
* @param response
*/
public void consultarllamadasFiltrosService(HttpServletRequest request, HttpServletResponse response){
Vector<TotalTiposLlamadasDTO> llamadasTotales = new Vector<TotalTiposLlamadasDTO>();
LocalDate ldi = LocalDate.now();
LocalDate ldf = LocalDate.now();
FechaDTO fechaInicialDTO = new FechaDTO();
FechaDTO fechaFinalDTO = new FechaDTO();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// DateTimeFormatter formatterT = DateTimeFormatter.ofPattern("HH:mm:ss");
formatter = formatter.withLocale(Locale.US);//01/01/2017
if(request.getParameter("inputFechaInicial") != null && !request.getParameter("inputFechaInicial").isEmpty()){
ldi = LocalDate.parse(request.getParameter("inputFechaInicial"), formatter);
fechaInicialDTO.setFechaString(request.getParameter("inputFechaInicial"));
}
if(request.getParameter("inputFechaFinal") != null && !request.getParameter("inputFechaFinal").isEmpty()){
ldf = LocalDate.parse(request.getParameter("inputFechaFinal"), formatter);
fechaFinalDTO.setFechaString(request.getParameter("inputFechaFinal"));
}
fechaInicialDTO.setFechaLD(ldi);
fechaFinalDTO.setFechaLD(ldf);
request.setAttribute("fechaInicial", fechaInicialDTO);
request.setAttribute("fechaFinal", fechaFinalDTO);
llamadasTotales = getListadosDAO().selectTotalesTiposDeLlamadasDTOFiltros(ldi, ldf);
if(llamadasTotales != null && llamadasTotales.size() > 0){
request.setAttribute("llamadas", llamadasTotales);
String array = "";
String totales = "";
for (int i = 0; i < llamadasTotales.size(); i++) {
if(i == 0){
array = "['"+ llamadasTotales.get(i).getTipoLlamada().getNombreTipoLlamada()+"'";
totales = "["+llamadasTotales.get(i).getTotalLlamadas();
}else if(i > 0){
array += ", '"+ llamadasTotales.get(i).getTipoLlamada().getNombreTipoLlamada()+"'";
totales += ", "+llamadasTotales.get(i).getTotalLlamadas();
}else{
System.out.println("llamadasTotales error !?");
}
}
array += "]";
totales += "]";
request.setAttribute("lblLlamadas", array);
request.setAttribute("totalesLlamadas", totales);
}else{
request.setAttribute("mensaje", "No se encontro llamadasTotales");
}
}
/**
*
* @param request
* @param response
*/
public void selectEntidadesFederativas(HttpServletRequest request, HttpServletResponse response){
Vector<EntidadFederativaDTO> ventidades = new Vector<EntidadFederativaDTO>();
ventidades = getListadosDAO().selectEntidadFederativa();
if(ventidades.size() > 0){
String json = new Gson().toJson(ventidades);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("VECTOR VACIO DE ESTADOS");
EntidadFederativaDTO edo = new EntidadFederativaDTO();
edo.setNombreEntidadFederativa("Sin estados!");
ventidades.add(edo);
String json = new Gson().toJson(ventidades);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void selectMunicipios(HttpServletRequest request, HttpServletResponse response){
Vector<MunicipioDTO> vmunicipios = new Vector<MunicipioDTO>();
int idEstado = (request.getParameter("idEstado") != null ? Integer.parseInt(request.getParameter("idEstado")) : 0);
vmunicipios = getListadosDAO().selectMunicipiosPorEntidadFederativa(idEstado);
if(vmunicipios.size() > 0){
String json = new Gson().toJson(vmunicipios);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("VECTOR VACIO DE MUNICIPIOS");
MunicipioDTO mun = new MunicipioDTO();
mun.setNombreMunicipio("Sin municipios");
vmunicipios.add(mun);
String json = new Gson().toJson(vmunicipios);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void selectColonias(HttpServletRequest request, HttpServletResponse response){
Vector<ColoniaDTO> vcolonias = new Vector<ColoniaDTO>();
int idMunicipio = (request.getParameter("idMunicipio") != null ? Integer.parseInt(request.getParameter("idMunicipio")) : 0);
vcolonias = getListadosDAO().selectColoniasPorMunicipios(idMunicipio);
if(vcolonias.size() > 0){
String json = new Gson().toJson(vcolonias);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("VECTOR VACIO DE COLONIAS");
ColoniaDTO col = new ColoniaDTO();
col.setNombreColonia("Sin colonias");
vcolonias.add(col);
String json = new Gson().toJson(vcolonias);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void obtenerGruposSanguineos(HttpServletRequest request, HttpServletResponse response){
Vector<GrupoSanguineoDTO> vgposanguineos = new Vector<GrupoSanguineoDTO>();
vgposanguineos = getListadosDAO().selectGruposSanguineos();
if(vgposanguineos.size() > 0){
request.setAttribute("listadoGruposSanguineos", vgposanguineos);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
/**
*
* @param request
* @param response
*/
public void obtenerPeriodosEscolares(HttpServletRequest request, HttpServletResponse response){
Vector<PeriodoEscolarDTO> vPerEscolcares = new Vector<PeriodoEscolarDTO>();
vPerEscolcares = getListadosDAO().selectPeriodosEscolares();
if(vPerEscolcares.size() > 0){
request.setAttribute("listadoPeriodosEscolares", vPerEscolcares);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
public void selectGradosEscolares(HttpServletRequest request, HttpServletResponse response){
Vector<GradoEscolarDTO> vGdosEscolares = new Vector<GradoEscolarDTO>();
int idPeriodoEscolar = (request.getParameter("idPeriodoEscolar") != null ? Integer.parseInt(request.getParameter("idPeriodoEscolar")) : 0);
vGdosEscolares = getListadosDAO().selectGradosEscolaresPorPeriodoEscolar(idPeriodoEscolar);
if(vGdosEscolares.size() > 0){
for (GradoEscolarDTO gradoEscolarDTO : vGdosEscolares) {
System.out.println(gradoEscolarDTO.getNombreGradoAcademico());
}
}else{
System.out.println("VECTOR VACIO DE GRADOS ESCOLARES");
GradoEscolarDTO gdoEsc = new GradoEscolarDTO();
gdoEsc.setNombreGradoAcademico("Sin grados escolares");
vGdosEscolares.add(gdoEsc);
}
String json = new Gson().toJson(vGdosEscolares);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
public void obtenerNivelesAcademicos(HttpServletRequest request, HttpServletResponse response){
Vector<NivelAcademicoDTO> vNvelAcademicos = new Vector<NivelAcademicoDTO>();
vNvelAcademicos = getListadosDAO().selectNivelesAcademicos();
if(vNvelAcademicos.size() > 0){
request.setAttribute("listadoNivelesAcademicos", vNvelAcademicos);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
public void selectEspecialidadesAcademicas(HttpServletRequest request, HttpServletResponse response){
Vector<EspecialidadDTO> vEspAcademicas = new Vector<EspecialidadDTO>();
int idNivelAcademico = (request.getParameter("idNivelAcademico") != null ? Integer.parseInt(request.getParameter("idNivelAcademico")) : 0);
vEspAcademicas = getListadosDAO().selectEspecialidadesAcademicasPorNivel(idNivelAcademico);
if(vEspAcademicas.size() > 0){
}else{
System.out.println("VECTOR VACIO DE ESPECIALIDADES");
EspecialidadDTO espAcad = new EspecialidadDTO();
espAcad.setNombreEspecialidad("Sin especialidades academicas");
vEspAcademicas.add(espAcad);
}
String json = new Gson().toJson(vEspAcademicas);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
public void nuevoEmpleadoService(HttpServletRequest request, HttpServletResponse response){
EmpleadoDTO empleadoNuevo = new EmpleadoDTO();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
formatter = formatter.withLocale(Locale.US);//01/01/2017
try{
if(request.getParameter("idEmpleadoHidden") != null && request.getParameter("idEmpleadoHidden").length() > 0){
if(HerramientasResultSet.tryParse(request.getParameter("skuEmpleadoHidden")) != null){
empleadoNuevo.setIdEmpleado(Integer.parseInt(request.getParameter("idEmpleadoHidden")));
}else{
//TODO add error
}
}
if(request.getParameter("nombreEmpleado") != null){
empleadoNuevo.setNombreEmpleado(request.getParameter("nombreEmpleado"));
}
if(request.getParameter("apPaterno") != null){
empleadoNuevo.setApPaternoEmpleado(request.getParameter("apPaterno"));
}
if(request.getParameter("apMaterno") != null){
empleadoNuevo.setApMaternoEmpleado(request.getParameter("apMaterno"));
}
if(request.getParameter("skuEmpleadoHidden") != null && request.getParameter("skuEmpleadoHidden").length() > 0){
if(HerramientasResultSet.tryParse(request.getParameter("skuEmpleadoHidden")) != null){
empleadoNuevo.setSkuEmpleado(Integer.parseInt(request.getParameter("skuEmpleadoHidden")));
}else{
//TODO add error
}
}
if(request.getParameter("cuip") != null){
empleadoNuevo.setCuipEmpleado(request.getParameter("cuip").toUpperCase());
}
if(request.getParameter("curp") != null){
empleadoNuevo.setCurpEmpleado(request.getParameter("curp").toUpperCase());
}
if(request.getParameter("rfcEmpleado") != null){
empleadoNuevo.setRfcEmpleado(request.getParameter("rfcEmpleado").toUpperCase());
}
if(request.getParameter("fechaNac") != null && request.getParameter("fechaNac").length() > 0){
empleadoNuevo.setFechaNacimientoEmpleado(LocalDate.parse(request.getParameter("fechaNac"), formatter));
}
if(request.getParameter("inputGenero") != null && request.getParameter("inputGenero").length() > 0){
empleadoNuevo.getGeneroEmpleadoDTO().setIdGenero(Integer.parseInt(request.getParameter("inputGenero")));
}
if(request.getParameter("estadoCivil") != null && request.getParameter("estadoCivil").length() > 0){
empleadoNuevo.getEdoCivilEmpladoDTO().setIdEstadoCivil(Integer.parseInt(request.getParameter("estadoCivil")));
}
if(request.getParameter("grupoSanguineo") != null && request.getParameter("estadoDomicilio").length() > 0){
empleadoNuevo.getGrupoSanguineoEmpleadoDTO().setIdGrupoSanguineo(Integer.parseInt(request.getParameter("grupoSanguineo")));
}
if(request.getParameter("estadoDomicilio") != null && request.getParameter("estadoDomicilio").length() > 0){
empleadoNuevo.getEntidadFederativaDomicilioEmpleadoDTO().setIdEntidadFederativa(Integer.parseInt(request.getParameter("estadoDomicilio")));
}
if(request.getParameter("municipioDomicilio") != null && request.getParameter("municipioDomicilio").length() > 0){
empleadoNuevo.getMunicipioDomicilioEmpleadoDTO().setIdMunicipio(Integer.parseInt(request.getParameter("municipioDomicilio")));
}
if(request.getParameter("coloniaDomicilio") != null && request.getParameter("coloniaDomicilio").length() > 0){
empleadoNuevo.getColoniaDomicilioEmpleadoDTO().setIdColonia(Integer.parseInt(request.getParameter("coloniaDomicilio")));
}
if(request.getParameter("cpDomicilio") != null && request.getParameter("cpDomicilio").length() > 0){
empleadoNuevo.setCodigoPostalDomicilioEmpleado(Integer.parseInt(request.getParameter("cpDomicilio")));
}
if(request.getParameter("calleDomicilio") != null ){
empleadoNuevo.getCalleDomicilioEmpleadoDTO().setNombreCalle(request.getParameter("calleDomicilio"));
}
/*if(request.getParameter("fkCalle") != null){
empleadoNuevo.getCalleDomicilioEmpleadoDTO().setIdCalle(Integer.parseInt(request.getParameter("fkCalle")));
}*/
if(request.getParameter("numExtDomicilio") != null){
empleadoNuevo.setNoExtDomicilioEmpleado(request.getParameter("numExtDomicilio"));
}
if(request.getParameter("numIntDomicilio") != null){
empleadoNuevo.setNoIntDomicilioEmpleado(request.getParameter("numIntDomicilio"));
}
if(request.getParameter("numTelFijo") != null){
empleadoNuevo.setTelFijoEmpleado(request.getParameter("numTelFijo"));
}
if(request.getParameter("numTelMovil") != null){
empleadoNuevo.setTelMovilEmpleado(request.getParameter("numTelMovil"));
}
if(request.getParameter("correoe") != null){
empleadoNuevo.setCorreoElectronicoEmpleado(request.getParameter("correoe"));
}
if(request.getParameter("nivelAcademicoEmpleado") != null && request.getParameter("nivelAcademicoEmpleado").length() > 0){
empleadoNuevo.getNivelAcademicoEmpleadoDTO().setIdNivelAcademico(Integer.parseInt(request.getParameter("nivelAcademicoEmpleado")));
}
if(request.getParameter("especialidadEmpleado") != null && request.getParameter("especialidadEmpleado").length() > 0){
empleadoNuevo.setEspecialidadDTO(new EspecialidadDTO());
empleadoNuevo.getEspecialidadDTO().setIdEspecialidad(Integer.parseInt(request.getParameter("especialidadEmpleado")));
}
//System.out.println(1);
if(request.getParameter("carreraTrunca") != null){
if(request.getParameter("carreraTrunca").equals("on")){
empleadoNuevo.getCarreraTruncaEmpleado().setEstatusInt(1);
}else{
empleadoNuevo.getCarreraTruncaEmpleado().setEstatusInt(0);
}
}
//System.out.println(2);
if(empleadoNuevo.getCarreraTruncaEmpleado().getEstatusInt() == 1){
if(request.getParameter("tipoPeriodoEscolar") != null && request.getParameter("tipoPeriodoEscolar").length() > 0){
empleadoNuevo.getPeridoEscolarEmpleadoDTO().setIdPeriodoEscolar(Integer.parseInt(request.getParameter("tipoPeriodoEscolar")));
}else{
System.out.println("Error tipoPeriodo");
}
if(request.getParameter("ultimoGradoEmpleado") != null && request.getParameter("ultimoGradoEmpleado").length() > 0){
empleadoNuevo.getGradoPeridoEscolarEmpleadoDTO().getGradoDTO().setIdGradoEscolar(Integer.parseInt(request.getParameter("ultimoGradoEmpleado")));
}else{
System.out.println("Error ultimoGrado");
}
}else{
empleadoNuevo.getPeridoEscolarEmpleadoDTO().setIdPeriodoEscolar(4);
empleadoNuevo.getGradoPeridoEscolarEmpleadoDTO().getGradoDTO().setIdGradoEscolar(37);
}
//System.out.println(3);
if(request.getParameter("tipoComprobanteEmpleado") != null){
// empleadoNuevo.setNombreEmpleado(request.getParameter("tipoComprobanteEmpleado"));
}
if(request.getParameter("documentoComprobanteEmpleado") != null){
//empleadoNuevo.setDocumentoComprobanteInfoEmpleado(request.getParameter("documentoComprobanteEmpleado"));
}
if(request.getParameter("fechaAltaEmpleado") != null && request.getParameter("fechaAltaEmpleado").length() > 0){
empleadoNuevo.setFechaAltaEmpleado(LocalDate.parse(request.getParameter("fechaAltaEmpleado"), formatter));
}
if(request.getParameter("fotoeEmpleado") != null){
//empleadoNuevo.setFotoEmpleado(request.getParameter("fotoeEmpleado")));
}
}catch(Exception error){
System.out.println(error);
try {
response.getWriter().append("-2");
} catch (IOException e) {
e.printStackTrace();
}
}
// int editarGlobal = -1;
//System.out.println("Nombre y sku empleado nuevo" + empleadoNuevo.getNombreEmpleado() + " , " + empleadoNuevo.getSkuEmpleado() + " , " + empleadoNuevo.getApPaternoEmpleado() + " , " + empleadoNuevo.getApMaternoEmpleado() );
if (empleadoNuevo.getIdEmpleado() > 0){
int editar = getEmpleadoDAO().actualizarEmpleado(empleadoNuevo);
if(editar > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else if(editar == 0){
System.out.println("Error en databasegateway, nuevoEmpleadoService: editaEmpleado");
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("Error en ListadosDAO, nuevoEmpleadoService: editaEmpleado");
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
int res = getEmpleadoDAO().insertaNuevoEmpleado(empleadoNuevo);
if(res > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else if(res == 0){
System.out.println("Error en databasegateway, nuevoEmpleadoService: insertaNuevoEmpleado");
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("Error en ListadosDAO, nuevoEmpleadoService: insertaNuevoEmpleado");
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*if(request.getParameter("existeCalle") != null){
boolean existeCalle = false;
existeCalle = Boolean.parseBoolean(request.getParameter("existeCalle"));
if(!existeCalle){
listadosDAO.insertaCalleNueva(calleDTO);
}
}*/
}
public void buscaCurpEmpleado(HttpServletRequest request, HttpServletResponse response){
String curp = request.getParameter("curpEmpleado");
Vector<EmpleadoDTO> v = new Vector<EmpleadoDTO>();
EmpleadoDTO emp = getEmpleadoDAO().selectEmpleadoPorCurp(curp, 1);
if(emp != null){
v.addElement(emp);
String json = new Gson().toJson(v);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void prepararVistaEmpleado (HttpServletRequest request, HttpServletResponse response){
}
public void consultarHorarios(HttpServletRequest request, HttpServletResponse response){
Vector<HorarioDTO> vHorarios = new Vector<HorarioDTO>();
vHorarios = getHorarioDAO().selectHorariosTodos();
if (vHorarios.size()>0){
request.setAttribute("horarios", vHorarios);
}else{
request.setAttribute("mensaje", "No se encontro registro");
}
}
public void buscarHorarios(HttpServletRequest request, HttpServletResponse response){
Vector<ErroresDTO> vErrores = new Vector<ErroresDTO>();
HashMap<String, String> hash = new HashMap<String, String>();
String claveHorario = request.getParameter("claveHorario") != null && !request.getParameter("claveHorario").equals("") && request.getParameter("claveHorario").length() > 0 ? (String) request.getParameter("claveHorario") : "-1" ;
if(!claveHorario.equals("-1")){
hash.put("claveHorario", claveHorario);
}
Vector<HorarioDTO> Lista = getHorarioDAO().selectRegistrosHorariosFiltros(hash);
if (Lista.size()>0){
request.setAttribute("horarios", Lista);
}else{
ErroresDTO error = new ErroresDTO();
error.setTituloError("Sin registros!");
error.setMensajeError("No se encontraron registros con los filtros especificados");
vErrores.add(error);
// System.out.println("Error " + vErrores.size());
request.setAttribute("errores", vErrores);
}
}
public void nuevoHorario(HttpServletRequest request, HttpServletResponse response, UserDTO usuario){
HorarioDTO horarioNuevo = new HorarioDTO();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter formatterT = DateTimeFormatter.ofPattern("HH:mm:ss");
formatter = formatter.withLocale(Locale.US);//01/01/2017
try{
if(request.getParameter("idHorarioHidden") != null && !request.getParameter("idHorarioHidden").isEmpty()){
horarioNuevo.setIdHorario(Integer.parseInt(request.getParameter("idHorarioHidden")));
}
if(request.getParameter("noLaboral") != null && !request.getParameter("noLaboral").isEmpty()){
if(request.getParameter("noLaboral").equals("1")){
horarioNuevo.setHorarioNoLaboral(true);
}else{
horarioNuevo.setHorarioNoLaboral(false);
}
}else{
horarioNuevo.setHorarioNoLaboral(false);
}
if(!horarioNuevo.isHorarioNoLaboral()){
if(request.getParameter("cveHorarioHidden") != null && !request.getParameter("cveHorarioHidden").isEmpty()){
System.out.println("cve: " + request.getParameter("cveHorarioHidden"));
horarioNuevo.setClaveHorario(request.getParameter("cveHorarioHidden"));
if(horarioNuevo.getClaveHorario() != null && horarioNuevo.getClaveHorario().length() > 0){
if(horarioNuevo.getClaveHorario().startsWith("T")){
horarioNuevo.setPrefix(String.valueOf(horarioNuevo.getClaveHorario().charAt(0)));
String[] a = horarioNuevo.getClaveHorario().split("T");
if(a != null){
if(a.length > 0){
for(String s : a){
if(s != null && !s.isEmpty()){
System.out.println(s);
horarioNuevo.setSkuHorario(Integer.parseInt(s));
}else{
System.out.println("S ESTA VACIO!");
}
}//Termina ciclo for
}else{
System.out.println("a es < 0!");
}
}else{
System.out.println("a == null!");
}
}else{
System.out.println("Prefix de clave del horario diferente a T!");
}
}else{
System.out.println("horarioNuevo.getClaveHorario() == null || horarioNuevo.getClaveHorario().lenght() <= 0! en " + this.getClass().getSimpleName() );
}
}
}else{
if(request.getParameter("cveHorario") != null && !request.getParameter("cveHorario").isEmpty()){
horarioNuevo.setClaveHorario(request.getParameter("cveHorario"));
}else{
horarioNuevo.setClaveHorario("N/A");
}
}
System.out.println("cve: " + horarioNuevo.getClaveHorario());
if(request.getParameter("nombreHorario") != null && !request.getParameter("nombreHorario").isEmpty()){
horarioNuevo.setNombreHorario(request.getParameter("nombreHorario"));
}
System.out.println("name: " + request.getParameter("nombreHorario"));
if(request.getParameter("e1Horario") != null && !request.getParameter("e1Horario").isEmpty()){
horarioNuevo.getHoraEntrada().setHoraLT(LocalTime.parse(request.getParameter("e1Horario"), formatterT));
horarioNuevo.getHoraEntrada().setHoraString(horarioNuevo.getHoraEntrada().getHoraLT().format(formatterT));
}
if(request.getParameter("s1Horario") != null && !request.getParameter("s1Horario").isEmpty()){
horarioNuevo.setHoraSalida(LocalTime.parse(request.getParameter("s1Horario"), formatterT));
horarioNuevo.setHoraSalidaString(horarioNuevo.getHoraSalida().format(formatterT));
}
if(request.getParameter("hr1Horario") != null && !request.getParameter("hr1Horario").isEmpty()){
horarioNuevo.setHoraRetardo(LocalTime.parse(request.getParameter("hr1Horario"), formatterT));
horarioNuevo.setHoraRetardoString(horarioNuevo.getHoraRetardo().format(formatterT));
}
if(request.getParameter("horarioQuebrado") != null && !request.getParameter("horarioQuebrado").isEmpty()){
System.out.println(request.getParameter("horarioQuebrado"));
if(request.getParameter("horarioQuebrado").equals("3")){
horarioNuevo.setHorarioQuebrado(true);
horarioNuevo.getHorarioQuebradoEstatusDTO().setEstatusInt(3);
}else{
horarioNuevo.setHorarioQuebrado(false);
horarioNuevo.getHorarioQuebradoEstatusDTO().setEstatusInt(4);
}
}else{
horarioNuevo.setHorarioQuebrado(false);
horarioNuevo.getHorarioQuebradoEstatusDTO().setEstatusInt(4);
}
if(horarioNuevo.isHorarioQuebrado()){
if(request.getParameter("e2Horario") != null && !request.getParameter("e2Horario").isEmpty()){
horarioNuevo.setHoraEntrada2(LocalTime.parse(request.getParameter("e2Horario"), formatterT));
horarioNuevo.setHoraEntrada2String(horarioNuevo.getHoraEntrada2().format(formatterT));
}
if(request.getParameter("s2Horario") != null && !request.getParameter("s2Horario").isEmpty()){
horarioNuevo.setHoraSalida2(LocalTime.parse(request.getParameter("s2Horario"), formatterT));
horarioNuevo.setHoraSalida2String(horarioNuevo.getHoraSalida2().format(formatterT));
}
if(request.getParameter("hr2Horario") != null && !request.getParameter("hr2Horario").isEmpty()){
horarioNuevo.setHoraRetardo2(LocalTime.parse(request.getParameter("hr2Horario"), formatterT));
horarioNuevo.setHoraRetardo2String(horarioNuevo.getHoraRetardo2().format(formatterT));
}
}else{
horarioNuevo.setHoraEntrada2(LocalTime.parse("00:00:00", formatterT));
horarioNuevo.setHoraEntrada2String(horarioNuevo.getHoraEntrada2().format(formatterT));
horarioNuevo.setHoraSalida2(LocalTime.parse("00:00:00", formatterT));
horarioNuevo.setHoraSalida2String(horarioNuevo.getHoraSalida2().format(formatterT));
horarioNuevo.setHoraRetardo2(LocalTime.parse("00:00:00", formatterT));
horarioNuevo.setHoraRetardo2String(horarioNuevo.getHoraRetardo2().format(formatterT));
}
if(request.getParameter("statusHorario") != null && !request.getParameter("statusHorario").isEmpty()){
horarioNuevo.getTipoEstatusDTO().setEstatusInt(Integer.parseInt(request.getParameter("statusHorario")));
}else{
horarioNuevo.getTipoEstatusDTO().setEstatusInt(5);
}
}catch(Exception error){
System.out.println(error);
try {
response.getWriter().append("-2");
} catch (IOException e) {
e.printStackTrace();
}
}
// int editarGlobal = -1;
//System.out.println("Nombre y sku empleado nuevo" + empleadoNuevo.getNombreEmpleado() + " , " + empleadoNuevo.getSkuEmpleado() + " , " + empleadoNuevo.getApPaternoEmpleado() + " , " + empleadoNuevo.getApMaternoEmpleado() );
if (horarioNuevo.getIdHorario() > 0){
horarioNuevo.getFechaHoraActualizacion().getFecha().setFechaLD(LocalDate.now());
horarioNuevo.getFechaHoraActualizacion().getHora().setHoraLT(LocalTime.now());
horarioNuevo.getUsuarioActualizacion().setIdUser(usuario.getUserId());
int editar = getHorarioDAO().actualizarHorario(horarioNuevo);
if(editar > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else if(editar == 0){
System.out.println("Error en databasegateway, nuevoEmpleadoService: editaEmpleado");
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("Error en ListadosDAO, nuevoEmpleadoService: editaEmpleado");
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
horarioNuevo.getFechaHoraCreacion().getFecha().setFechaLD(LocalDate.now());
horarioNuevo.getFechaHoraCreacion().getHora().setHoraLT(LocalTime.now());
horarioNuevo.getFechaHoraActualizacion().getFecha().setFechaLD(LocalDate.now());
horarioNuevo.getUsuarioCreacion().setIdUser(usuario.getUserId());
int res = getHorarioDAO().insertaNuevoHorario(horarioNuevo);
if(res > 0){
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}else if(res == 0){
System.out.println("Error en databasegateway, nuevoEmpleadoService: insertaNuevoEmpleado");
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("Error en ListadosDAO, nuevoEmpleadoService: insertaNuevoEmpleado");
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* @param request
* @param response
*/
public void consultaSkuNuevoHorario(HttpServletRequest request, HttpServletResponse response){
String skuNuevoHorario = "";
String prefix = request.getParameter("prefix");
if(prefix != null){
skuNuevoHorario = getHorarioDAO().selectSkuNuevoHorario(prefix);
if (skuNuevoHorario.length()>0){
try {
response.getWriter().append(skuNuevoHorario);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void actualizarDatosUsuario(HttpServletRequest request, HttpServletResponse response){
int res = -1;
HttpSession session = request.getSession();
UserDTO user = (UserDTO)session.getAttribute("user");
String erroresString = "";
// String mensajesEstring = "";
if(user != null){
String pswd = request.getParameter("passwordField2");
if(pswd != null && pswd.length() > 0 && !pswd.equals("1111112")){
user.setPassword(pswd);
}else{
System.out.println("pswd == null");
}
if(user.getPassword() != null && user.getPassword().length() > 0){
res = getUserDAO().actualizarPswdUsuario(user);
if (res>0){
}else{
erroresString += "Password,";
}
}
ProcesarImagen pi = new ProcesarImagen();
Part imgAvatar = pi.procesarImagenRequest(request, response, "userAvatar");
if(imgAvatar != null){
int row = -1;
row = getUserDAO().actualizarAvatarUsuario(user, imgAvatar);
if (row > 0) {
}else{
erroresString += "Foto,";
}
}else{
System.out.println("avatar == null");
}
if(erroresString.length() > 0){
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("1");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("unused")
private String getFileName(final Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
/**
*
* @param request
* @param response
*/
public void selectTiposEstatus(HttpServletRequest request, HttpServletResponse response){
String app = request.getParameter("app");
if(app != null && !app.equals("") && app.length() > 0){
Vector<TipoEstatusDTO> vTpermisos = new Vector<TipoEstatusDTO>();
vTpermisos = getTipoEstatusDAO().selectTiposEstatusDTO(app);
if(vTpermisos.size() > 0){
String json = new Gson().toJson(vTpermisos);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
try {
response.getWriter().append("-1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param request
* @param response
*/
public void selectHorariosEmpleados(HttpServletRequest request, HttpServletResponse response){
EmpleadoHorarioDAO empleadoHorarioDAO = new EmpleadoHorarioDAO();
Vector<EmpleadoHorarioDTO> empleadosHorarios = empleadoHorarioDAO.selectEmpleadosHorariosDTO();
if(empleadosHorarios != null && empleadosHorarios.size() > 0){
request.setAttribute("empleadosHorarios", empleadosHorarios);
}else{
System.out.println("MENOR A 0");
}
}
/**
*
* @param request
* @param response
*/
public void selectHorariosEmpleadosFiltros(HttpServletRequest request, HttpServletResponse response){
EmpleadoHorarioDAO empleadoHorarioDAO = new EmpleadoHorarioDAO();
HashMap<String, String> map = new HashMap<String, String>();
map.put("fechaDe", request.getParameter("fechaDe"));
map.put("idEmpleado", request.getParameter("idEmpleado"));
map.put("nombreEmpleado", request.getParameter("nombreEmpleado"));
Vector<EmpleadoHorarioDTO> empleadosHorarios = empleadoHorarioDAO.selectEmpleadosHorariosDTO(map);
if(empleadosHorarios != null && empleadosHorarios.size() > 0){
request.setAttribute("empleadosHorarios", empleadosHorarios);
}else{
System.out.println("MENOR A 0");
}
}
/**
*
* @param request
* @param response
*/
public ConfigCamposTipoItemDTO inicializaJSPItems(HttpServletRequest request, HttpServletResponse response){
ConfigCamposTipoItemDTO configCamposItem = null;
int idTipoItem = Integer.parseInt(request.getParameter("tipoItem"));
if(idTipoItem > 0){
TipoItemDTO tipoItem = getItemDAO().selectTipoItem(idTipoItem);
if(tipoItem != null){
HttpSession session = request.getSession();
session.setAttribute("tipoItem", tipoItem);
configCamposItem = getConfigDAO().selectConfigCamposItem(tipoItem.getIdTipoItem());
if(configCamposItem != null){
request.setAttribute("configCampos", configCamposItem);
selectTipoEstatusPorTipoItem(idTipoItem, configCamposItem, request);
if(configCamposItem.getConfigCampoMarcaItem().isMostrar()){
selectMarcasItemPorTipoItem(request, response, tipoItem);
}
if(configCamposItem.getConfigCampoModeloItem().isMostrar()){
selectModelosItemsPorTipoItem(request, response, tipoItem);
}
if(configCamposItem.getConfigCampoLineaItem().isMostrar()){
selectLineasItemPorTipoItem(request, response, tipoItem);
}
if(configCamposItem.getConfigCampoStatusItem().isMostrar()){
selectStatusPorTipoItem(request, response, tipoItem, "items_status");
}
if(configCamposItem.getConfigCampoStatusItem().isMostrar()){
selectStatusPorTipoItem(request, response, tipoItem, "items_situacion");
}
if(configCamposItem.getConfigCampoStatusItem().isMostrar()){
selectStatusPorTipoItem(request, response, tipoItem, "items_ubicacion");
}
}else{
System.out.println("SIN CONFIGURACION DE CAMPOS PARA EL TIPO DE ITEM");
}
}else{
System.out.println("SIN tipo de item encontrado en la bd: tipoItem == null");
}
}else{
System.out.println("SIN tipo de item definido");
}
return configCamposItem;
}
/**
* TIENE QUE ESTAR INICIALIZADO EL configCamposItem
* @param request
* @param response
*/
public void selectItems(HttpServletRequest request, HttpServletResponse response, ConfigCamposTipoItemDTO configCamposItem){
int idTipoItem = -1;
if(configCamposItem != null){
if(configCamposItem.getIdTipoItem() > 0){
idTipoItem = configCamposItem.getIdTipoItem() ;
}else{
idTipoItem = Integer.parseInt(request.getParameter("tipoItem"));
}
}else{
idTipoItem = Integer.parseInt(request.getParameter("tipoItem"));
System.out.println("SIN CONFIGURACION DE CAMPOS PARA EL TIPO DE ITEM 0");
}
if(idTipoItem > 0){
HttpSession session = request.getSession();
TipoItemDTO tipoItem = (TipoItemDTO) session.getAttribute("tipoItem");
if(tipoItem != null){
if(configCamposItem != null){
Vector<ItemDTO> items = getItemDAO().selectItems(tipoItem.getIdTipoItem(), configCamposItem);
if(items != null && items.size() > 0){
request.setAttribute("items", items);
}else{
System.out.println("resultado de vector por tipo de item MENOR A 0");
}
}else{
System.out.println("SIN CONFIGURACION DE CAMPOS PARA EL TIPO DE ITEM 1");
}
}else{
System.out.println("SIN tipo de item encontrado en la bd: tipoItem == null");
}
}else{
System.out.println("SIN tipo de item definido");
}
}
/**
* TIENE SELECCIONA LOS PARTNERS EN BASE AL TIOPO DE PARTNERS
* @param request
* @param response
*/
public void selectPartnersPorTipo(HttpServletRequest request, HttpServletResponse response){
int tipoPartner = -1;
tipoPartner = Integer.parseInt(request.getParameter("tipoPartner"));
if(tipoPartner > 0){
Vector<PartnerDTO> partners = getPartnerDAO().selectPartnersPorTipo(tipoPartner);
if(partners != null && partners.size() > 0){
request.setAttribute("partners", partners);
}else{
System.out.println("resultado de vector por tipo de item MENOR A 0");
}
}else{
System.out.println("SIN tipo de item definido");
}
}
/**
*
* @param request
* @param response
*/
public void selectItems(HttpServletRequest request, HttpServletResponse response){
int idTipoItem = Integer.parseInt(request.getParameter("tipoItem"));
if(idTipoItem > 0){
TipoItemDTO tipoItem = getItemDAO().selectTipoItem(idTipoItem);
if(tipoItem != null){
HttpSession session = request.getSession();
session.setAttribute("tipoItem", tipoItem);
ConfigCamposTipoItemDTO configCamposItem = getConfigDAO().selectConfigCamposItem(tipoItem.getIdTipoItem());
if(configCamposItem != null){
request.setAttribute("configCampos", configCamposItem);
Vector<ItemDTO> items = getItemDAO().selectItems(tipoItem.getIdTipoItem(), configCamposItem);
// selectTipoEstatusPorTipoItem(idTipoItem, configCamposItem, request);
if(items != null && items.size() > 0){
request.setAttribute("items", items);
}else{
System.out.println("resultado de vector por tipo de item MENOR A 0");
}
}else{
System.out.println("SIN CONFIGURACION DE CAMPOS PARA EL TIPO DE ITEM");
}
}else{
System.out.println("SIN tipo de item encontrado en la bd: tipoItem == null");
}
}else{
System.out.println("SIN tipo de item definido");
}
}
/**
*
* @param request
* @param response
*/
public void selectItemsTipos(HttpServletRequest request, HttpServletResponse response){
Vector<TipoItemDTO> tiposItems = getItemDAO().selectTiposItems();
if(tiposItems != null && tiposItems.size() > 0){
HttpSession session = request.getSession();
session.setAttribute("itemsTipos", tiposItems);
}else{
System.out.println("SIN tipos de items encontrados en la bd: tiposItems == null");
}
}
/**
*
* @param request
* @param response
*/
public void selectModelosItems(HttpServletRequest request, HttpServletResponse response){
Vector<ModeloItemDTO> modelosItems = getItemDAO().selectModelosItems();
if(modelosItems != null){
if(modelosItems.size() > 0){
request.setAttribute("modelosItems", modelosItems);
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}
/**
*
* @param request
* @param response
*/
public void selectModelosItemsPorTipoItem(HttpServletRequest request, HttpServletResponse response, TipoItemDTO tipoItem){
Vector<ModeloItemDTO> modelosItems = getItemDAO().selectModelosItemsPorTipoItem(tipoItem);
if(modelosItems != null){
if(modelosItems.size() > 0){
request.setAttribute("modelosItems", modelosItems);
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}
/**
*
* @param request
* @param response
*/
public void selectLineasItemPorTipoItem(HttpServletRequest request, HttpServletResponse response, TipoItemDTO tipoItem){
Vector<LineaItemDTO> lineasItem = getItemDAO().selectLineasItemPorTipoItem(tipoItem);
if(lineasItem != null){
if(lineasItem.size() > 0){
request.setAttribute("lineasItem", lineasItem);
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}
/**
*
* @param request
* @param response
*/
public void selectStatusPorTipoItem(HttpServletRequest request, HttpServletResponse response, TipoItemDTO tipoItem, String aplicacion){
Vector<TipoEstatusDTO> tiposEstatuses = getItemDAO().selectStatusesPorTipoItem(tipoItem, aplicacion);
if(tiposEstatuses != null){
if(tiposEstatuses.size() > 0){
request.setAttribute(aplicacion, tiposEstatuses);
}else{
System.out.println("el vector de statusesItem es menor o igual a 0");
}
}else{
System.out.println("el vector de statusesItem es menor o igual a 0");
}
}
/**
*
* @param request
* @param response
*/
public void selectMarcasItemPorTipoItem(HttpServletRequest request, HttpServletResponse response, TipoItemDTO tipoItem){
Vector<MarcaItemDTO> marcasItem = getItemDAO().selectMarcasItemDTOPorTipoItem(tipoItem);
if(marcasItem != null){
if(marcasItem.size() > 0){
request.setAttribute("marcasItem", marcasItem);
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}else{
System.out.println("el vector de modelosItem es menor o igual a 0");
}
}
/**
*
* @param request
* @param response
*/
public void selectMarcasItems(HttpServletRequest request, HttpServletResponse response){
Vector<MarcaItemDTO> marcasItems = getItemDAO().selectMarcasItems();
if(marcasItems != null){
if(marcasItems.size() > 0){
request.setAttribute("marcasItems", marcasItems);
}else{
System.out.println("el vector de marcasItem es menor o igual a 0");
}
}else{
System.out.println("el vector de marcasItem es menor o igual a 0");
}
}
/**
*
* @param request
* @param response
*/
public void selectMaxIdItem(HttpServletRequest request, HttpServletResponse response){
if(request.getParameter("typeId") != null && !request.getParameter("typeId").isEmpty()){
int idTipoItem = Integer.parseInt(request.getParameter("typeId"));
if(idTipoItem > 0){
TipoItemDTO tipoItem = getItemDAO().selectTipoItem(idTipoItem);
if(tipoItem != null){
HttpSession session = request.getSession();
session.setAttribute("tipoItem", tipoItem);
// ConfigCamposTipoItemDTO configCamposItem = getConfigDAO().selectConfigCamposItem(tipoItem.getIdTipoItem());
int max_id = getItemDAO().selectMaxIdTipoItem(tipoItem.getIdTipoItem());
// selectTipoEstatusPorTipoItem(idTipoItem, configCamposItem, request);
if(max_id != 0 && max_id > 0){
int newId = max_id + 1;
try {
response.getWriter().append(String.valueOf(newId));
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("resultado de vector por tipo de item MENOR A 0");
try {
response.getWriter().append("0");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
System.out.println("SIN tipo de item encontrado en la bd: tipoItem == null");
}
}else{
System.out.println("SIN tipo de item definido");
}
}else{
System.out.println("SIN tipo de item encontrado en la url: tipoItem == null");
}
}
/**
*
* @param request
* @param response
*/
public void selectTipoEstatusPorTipoItem(HttpServletRequest request, HttpServletResponse response){
int idTipoItem = Integer.parseInt(request.getParameter("tipoItem"));
if(idTipoItem > 0){
Vector <TipoEstatusDTO> tiposEstatusesDTOSituacion = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_situacion");
Vector <TipoEstatusDTO> tiposEstatusesDTOUbicacion = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_ubicacion");
Vector <TipoEstatusDTO> tiposEstatusesDTOStatus = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_status");
Vector <TipoEstatusDTO> tiposEstatusesDTOPropietario = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_propietario");
TipoEstatusDTO tipoError = new TipoEstatusDTO();
tipoError.setEstatusString("Sin datos!");
if(tiposEstatusesDTOSituacion != null && tiposEstatusesDTOSituacion.size() > 0){
request.setAttribute("items_situacion", tiposEstatusesDTOSituacion);
}else{
request.setAttribute("items_situacion", tipoError);
}
if(tiposEstatusesDTOUbicacion != null && tiposEstatusesDTOUbicacion.size() > 0){
request.setAttribute("items_ubicacion", tiposEstatusesDTOUbicacion);
}else{
request.setAttribute("items_situacion", tipoError);
}
if(tiposEstatusesDTOStatus != null && tiposEstatusesDTOStatus.size() > 0){
request.setAttribute("items_status", tiposEstatusesDTOStatus);
}else{
request.setAttribute("items_situacion", tipoError);
}
if(tiposEstatusesDTOPropietario != null && tiposEstatusesDTOPropietario.size() > 0){
request.setAttribute("items_propietario", tiposEstatusesDTOPropietario);
}else{
request.setAttribute("items_situacion", tipoError);
}
}else{
System.out.println("SIN tipo de item definido");
}
}
public void selectTipoEstatusPorTipoItem(int tipoItem, ConfigCamposTipoItemDTO configCampos, HttpServletRequest request){
int idTipoItem = tipoItem;
if(idTipoItem > 0){
TipoEstatusDTO tipoError = new TipoEstatusDTO();
tipoError.setEstatusString("Sin datos!");
TipoEstatusDTO tipoDesha = new TipoEstatusDTO();
tipoError.setEstatusString("Deshabilitado!");
if(configCampos.getConfigCampoSituacionItem().isMostrar()){
Vector <TipoEstatusDTO> tiposEstatusesDTOSituacion = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_situacion");
if(tiposEstatusesDTOSituacion != null && tiposEstatusesDTOSituacion.size() > 0){
request.setAttribute("items_situacion", tiposEstatusesDTOSituacion);
}else{
tiposEstatusesDTOSituacion = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOSituacion.add(tipoError);
request.setAttribute("items_situacion", tiposEstatusesDTOSituacion);
}
}else{
Vector <TipoEstatusDTO> tiposEstatusesDTOSituacion = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOSituacion.add(tipoDesha);
request.setAttribute("items_situacion", tiposEstatusesDTOSituacion);
}
if(configCampos.getConfigCampoSituacionItem().isMostrar()){
Vector <TipoEstatusDTO> tiposEstatusesDTOUbicacion = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_ubicacion");
if(tiposEstatusesDTOUbicacion != null && tiposEstatusesDTOUbicacion.size() > 0){
request.setAttribute("items_ubicacion", tiposEstatusesDTOUbicacion);
}else{
tiposEstatusesDTOUbicacion = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOUbicacion.add(tipoError);
request.setAttribute("items_ubicacion", tiposEstatusesDTOUbicacion);
}
}else{
Vector <TipoEstatusDTO> tiposEstatusesDTOUbicacion = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOUbicacion.add(tipoDesha);
request.setAttribute("items_ubicacion", tiposEstatusesDTOUbicacion);
}
if(configCampos.getConfigCampoSituacionItem().isMostrar()){
Vector <TipoEstatusDTO> tiposEstatusesDTOStatus = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_status");
if(tiposEstatusesDTOStatus != null && tiposEstatusesDTOStatus.size() > 0){
request.setAttribute("items_status", tiposEstatusesDTOStatus);
}else{
tiposEstatusesDTOStatus = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOStatus.add(tipoError);
request.setAttribute("items_status", tiposEstatusesDTOStatus);
}
}else{
Vector <TipoEstatusDTO> tiposEstatusesDTOUbicacion = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOUbicacion.add(tipoDesha);
request.setAttribute("items_status", tiposEstatusesDTOUbicacion);
}
if(configCampos.getConfigCampoSituacionItem().isMostrar()){
Vector <TipoEstatusDTO> tiposEstatusesDTOPropietario = getTipoEstatusDAO().selectTiposEstatusesDTO(idTipoItem, "items_propietario");
if(tiposEstatusesDTOPropietario != null && tiposEstatusesDTOPropietario.size() > 0){
request.setAttribute("items_propietario", tiposEstatusesDTOPropietario);
}else{
tiposEstatusesDTOPropietario = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOPropietario.add(tipoError);
request.setAttribute("items_propietario", tiposEstatusesDTOPropietario);
}
}else{
Vector <TipoEstatusDTO> tiposEstatusesDTOPropietario = new Vector<TipoEstatusDTO>();
tiposEstatusesDTOPropietario.add(tipoDesha);
request.setAttribute("items_propietario", tiposEstatusesDTOPropietario);
}
}else{
System.out.println("SIN tipo de item definido");
}
}
/**
*
* @param request
* @param response
*/
public void guardarItemService(HttpServletRequest request, HttpServletResponse response){
String typeId = request.getParameter("typeId");
if(typeId != null && !typeId.isEmpty() && typeId.length() > 0){
int idTipoItem = Integer.parseInt(typeId);
if(idTipoItem > 0){
HttpSession session = request.getSession();
TipoItemDTO tipoSession = (TipoItemDTO) session.getAttribute("tipoItem");
UserDTO usuarioCompleto = (UserDTO) session.getAttribute("user");
UserSimpleDTO usuarioSimple = new UserSimpleDTO();
usuarioSimple.setIdUser(usuarioCompleto.getUserId());
TipoItemDTO tipoItem = null;
if(idTipoItem == tipoSession.getIdTipoItem()){
tipoItem = tipoSession;
}else{
tipoItem = getItemDAO().selectTipoItem(idTipoItem);
session.setAttribute("tipoItem", tipoItem);
}
if(tipoItem != null){
ItemDTO itemGuardar = new ItemDTO();
Locale local = new Locale("es", "MX");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withLocale(local);
formatter = formatter.withLocale(Locale.US);//01/01/2017
try{
String campo = "";
String missingFields = "";
campo = "idItemHidden";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setIdItem(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += "missing: "+campo;
}
itemGuardar.setTipoItem(tipoItem);
campo = "skuItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setSkuItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "nombreItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setNombreItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "noSerieItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setNoSerieItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "placasItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setPlacasItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "categoriaItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setCategoriaItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "modeloItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getModeloItem().setIdModeloItem(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "colorItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setColorItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "tamanoItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setTamanoItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "marcaItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getMarcaItem().setIdMarcaItem(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "formaItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setFormaItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "lineaItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getLineaItem().setIdLinea(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "itemAsignadoItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setItemAsignadoItem(Boolean.parseBoolean(request.getParameter(campo)));
}else{
itemGuardar.setItemAsignadoItem(false);
missingFields += ", missing: "+campo;
}
campo = "asignacionItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setAsignacionItem(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "string1Item";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setString1Item(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "fechaActualizacionItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getFechaHoraActualizacion().getFecha().setFechaLD(LocalDate.parse(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "comentariosItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setComentariosItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "situacionItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getSituacionItemDTO().setEstatusInt(Integer.parseInt(request.getParameter(campo)));;
}else{
missingFields += ", missing: "+campo;
}
campo = "ubicacionItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getUbicacionItemDTO().setEstatusInt(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "contabilidadRecursoItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setIdContabilidadRecursoItem(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "fechaRecepcionItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getFechaHoraRecepcionItem().getFecha().setFechaLD(LocalDate.parse(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
campo = "contratoItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setContratoItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "proyectoItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.setProyectoItem(request.getParameter(campo));
}else{
missingFields += ", missing: "+campo;
}
campo = "statusItem";
if(request.getParameter(campo) != null && request.getParameter(campo).length() > 0){
itemGuardar.getStatusItem().setEstatusInt(Integer.parseInt(request.getParameter(campo)));
}else{
missingFields += ", missing: "+campo;
}
if(missingFields.length() > 0){
System.out.println(missingFields);
}
int res = -1;
if(itemGuardar.getIdItem() == 0){
itemGuardar.getFechaHoraCreacion().getFecha().setFechaLD(LocalDate.now());
itemGuardar.getFechaHoraCreacion().getHora().setHoraLT(LocalTime.now());
itemGuardar.setUsuarioCreacion(usuarioSimple);
res = getItemDAO().insertNewItem(itemGuardar);
}else{
if(itemGuardar.getIdItem() > 0){
itemGuardar.setUsuarioActualizacion(usuarioSimple);
itemGuardar.getFechaHoraActualizacion().getFecha().setFechaLD(LocalDate.now());
itemGuardar.getFechaHoraActualizacion().getHora().setHoraLT(LocalTime.now());
res = getItemDAO().updateItemDTO(itemGuardar);
}else{
System.out.println("error idItemGuardar < 0");
}
}
if(res > 0){
response.getWriter().append("1");
}else{
response.getWriter().append("0");
}
}
catch (Exception e) {
System.out.println(e);
}
}else{
System.out.println("SIN tipo de item encontrado en la bd: tipoItem == null");
}
}else{
System.out.println("SIN tipo desde int, de item definido");
}
}else{
System.out.println("SIN tipo desde string, de item definido");
}
}
/**
* @return the ordenesDAO
*/
public OrdenesDAO getOrdenesDAO() {
return ordenesDAO;
}
/**
* @param ordenesDAO the ordenesDAO to set
*/
public void setOrdenesDAO(OrdenesDAO ordenesDAO) {
this.ordenesDAO = ordenesDAO;
}
/**
* @return the partnerDAO
*/
public PartnerDAO getPartnerDAO() {
return partnerDAO;
}
/**
* @param partnerDAO the partnerDAO to set
*/
public void setPartnerDAO(PartnerDAO partnerDAO) {
this.partnerDAO = partnerDAO;
}
}//Termina clase
|
package org.giveback.problems.readcsvsaveremote;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
public final class ReadCsv implements Runnable {
private final LinkedBlockingQueue<String> csvPathQ;
private final LinkedBlockingQueue<CsvContent> csvContentQ;
public ReadCsv(LinkedBlockingQueue<String> inputQ,
LinkedBlockingQueue<CsvContent> outputQ) {
this.csvPathQ = inputQ;
this.csvContentQ = outputQ;
}
@Override
public void run() {
try {
while (true) {
var path = csvPathQ.take();
var csv = FileFactory.getFile("linux", path);
var reader = csv.readFile();
var stringBuilder = new StringBuilder();
int character = 0;
while ((character = reader.read()) != 0) {
stringBuilder.append((char) character);
}
csvContentQ.offer(new CsvContent(stringBuilder.toString(),
path));
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}
|
package com.gestion.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
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 javax.servlet.http.HttpSession;
import org.hibernate.Session;
import com.gestion.entity.Fournisseur;
import com.gestion.service.ServiceFournisseur;
import fr.cortex2i.utils.HibernateUtils;
/**
* Servlet implementation class ServletListeFournisseurSupp
*/
@WebServlet("/ServletListeFournisseurSupp")
public class ServletListeFournisseurSupp extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletListeFournisseurSupp() {
super();
// TODO Auto-generated constructor stub
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Session s = HibernateUtils.getSession();
@SuppressWarnings("rawtypes")
Enumeration lf = request.getParameterNames();
Fournisseur f = new Fournisseur();
while(lf.hasMoreElements())
{
String nom = (String) lf.nextElement();
f.setNom(nom);
ServiceFournisseur.removeFournisseur(s, f);
}
request.setAttribute("message", "Supression faite avec succès...");
request.getServletContext().getRequestDispatcher("/ServletGestionFournisseur").forward(request, response);
s.close();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.sendRedirect("style/test.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
package com.eussi._01_jca_jce.securitypkg;
import java.io.FileInputStream;
import java.security.*;
import java.security.cert.CertPath;
import java.security.cert.CertificateFactory;
import java.util.Date;
/**
* demo待完善,后面看到Https时在完善
* Created by wangxueming on 2019/4/1.
*/
public class _13_Timestamp {//主要用于常见实际运行时对象的类
public static void main(String[] args) {
try {
//构建certificateFactory对象,并指定证书类型为X.509
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
//生成CertPath对象
//java.security.cert.CertificateException: Could not parse certificate: java.io.IOException: Empty input
//待解决问题
CertPath certPath = certificateFactory.generateCertPath(new FileInputStream("src/test/resources/aliyun.cer"));
//实例化数字时间戳
Timestamp t = new Timestamp(new Date(), certPath);
System.out.println(t.toString());
}catch(Exception e) {
e.printStackTrace();
}
}
}
|
/*
* Ara - Capture Species and Specimen Data
*
* Copyright © 2009 INBio (Instituto Nacional de Biodiversidad).
* Heredia, Costa Rica.
*
* 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 org.inbio.ara.dto.agent;
import org.inbio.ara.dto.BaseDTOFactory;
import org.inbio.ara.persistence.institution.Institution;
/**
*
* @author esmata
*/
public class InstitutionDTOFactory extends BaseDTOFactory<Institution,InstitutionDTO>{
public InstitutionDTO createDTO(Institution entity) {
if(entity==null){
return null;
}
InstitutionDTO result = new InstitutionDTO();
result.setInstitutionId(entity.getInstitutionId());
result.setInstitutionName(entity.getName());
result.setInstitutionCode(entity.getInstitutionCode());
result.setAcronym(entity.getAcronym());
result.setCity(entity.getCity());
result.setCountry(entity.getCountry());
result.setFax(entity.getFax());
result.setMultimediaId(entity.getMultimediaId());
result.setStateProvince(entity.getStateProvince());
result.setStreetAddress(entity.getStreetAddress());
result.setTelephone(entity.getTelephone());
result.setUrl(entity.getUrl());
//seleted is used in the Graphical Interface, should be set in false
result.setSelected(false);
return result;
}
public Institution createEntity(InstitutionDTO dto) {
if(dto==null){
return null;
}
Institution result = new Institution();
result.setInstitutionId(dto.getInstitutionId());
result.setName(dto.getInstitutionName());
result.setInstitutionCode(dto.getInstitutionCode());
result.setAcronym(dto.getAcronym());
result.setCity(dto.getCity());
result.setCountry(dto.getCountry());
result.setFax(dto.getFax());
result.setMultimediaId(dto.getMultimediaId());
result.setStateProvince(dto.getStateProvince());
result.setStreetAddress(dto.getStreetAddress());
result.setTelephone(dto.getTelephone());
result.setUrl(dto.getUrl());
return result;
}
}
|
package com.hotdog.petcam.Controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hotdog.petcam.DTO.JSONResult;
import com.hotdog.petcam.Security.Auth;
import com.hotdog.petcam.Security.AuthUser;
import com.hotdog.petcam.Security.Secret;
import com.hotdog.petcam.Service.UserService;
import com.hotdog.petcam.VO.PetVo;
import com.hotdog.petcam.VO.UserVo;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired private UserService userService;
// 유저 테스트용 페이지
@RequestMapping("/test")
public String test(){
return "user/joinform2";
}
// ************************************* 회원 가입 및 로그인/아웃 **************
@RequestMapping("/login")
public String login(){
return "redirect:/";
}
@RequestMapping(value = "/join")
public String join(@RequestParam( value="nickname", required=true, defaultValue="" ) String nickname,
@ModelAttribute UserVo userVo,HttpServletRequest request){
int users_no = userService.join(userVo);
userVo.setUsers_no(users_no);
userService.insert(userVo);
return "redirect:/";
}
@Auth
@RequestMapping("/logout")
public String logout() {
return "main/index";
}
// 코드 체크
@ResponseBody
@RequestMapping("/checkcode")
public Object test2(@RequestParam( value="code", required=true, defaultValue="" ) int inputCode,
HttpServletRequest request){
int code=(int)request.getSession().getAttribute("code");
return JSONResult.success(userService.checkCode(inputCode,code)? "yes":"no");
}
//닉네임체크
@ResponseBody
@RequestMapping("/nickCheck")
public Object nickCheck(@RequestParam( value="nickname", required=true, defaultValue="" ) String nickname,
HttpServletRequest request){
Boolean result = userService.nicknameCheck(nickname);
return JSONResult.success(result? "yes":"no");
}
// *******************************************************************************************************
// **************************************** My Account ***************************************************
// *******************************************************************************************************
// 1. 기본 정보 수정
@Auth
@Secret
@RequestMapping(value="/account/basicmodifyform", method=RequestMethod.POST)
public String basicModifyForm(@AuthUser UserVo authUser,Model model){
// model에 담아보내는 UserVo에 기본정보 다있으니 jsp 에서 뽑아 써야함..
model.addAttribute("userVo", authUser);
return "개인정보 수정 메인 페이지";
}
@Auth
@Secret
@RequestMapping(value="/account/basicmodify", method= RequestMethod.POST)
public String basicModify(@ModelAttribute UserVo userVo){
userService.basicModify(userVo);
return "redirect:/";
}
@Auth
@Secret
@RequestMapping(value="/account/profilemodifyform", method= RequestMethod.POST)
public String profileModifyForm(@AuthUser UserVo authUser,Model model,@RequestParam(value="category",required=true,defaultValue="user")String category){
if(category == "pet"){
return "펫 프로필 페이지";
}
return "유저 프로필 페이지";
}
@Auth
@Secret
@RequestMapping(value="/account/userprofilemodify", method=RequestMethod.POST)
public String userProfileModify(@ModelAttribute UserVo userVo){
userService.userProfileModify(userVo);
return "redirect:/";
}
@Auth
@Secret
@RequestMapping(value="/account/petprofilemodify", method=RequestMethod.POST)
public String petProfileModify(@ModelAttribute PetVo petVo){
userService.petProfileModify(petVo);
return "redirect:/";
}
}
|
package com.xiaomi.common.tools;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TradingFlowUtil {
/**
* 18位交易流水号 前14位为年月时分秒 后四位为随机数 保证不会重复
*/
public static String get(){
Date date = new Date();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
int randomNum = (int)((Math.random()*9+1)*1000);
String tradingFlowNum = sdf2.format(date).toString()+String.valueOf(randomNum);
return tradingFlowNum;
}
}
|
package com.imthe.god.handlers;
import com.imthe.god.base.APIConfig;
import com.imthe.god.base.Configurations;
import com.imthe.god.base.DBConfig;
import com.imthe.god.interfaces.data.IAggregator;
import com.imthe.god.util.ConfigReader;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by mavilla on 18/07/16.
*/
public class AggregatorHandler implements IAggregator {
public Map<String, String> getData(String key) {
Map<String, String> data = new HashMap<String, String>();
Configurations configurations = (Configurations) ConfigReader.configs.get(key);
List<APIConfig> apiConfigs = configurations.getApiConfigs();
List<DBConfig> dbConfigs = configurations.getDbConfigs();
for (APIConfig apiConfig : apiConfigs) {
try {
data.putAll(APIHandler.getDataFromAPI(apiConfig, new HashMap<String, String>()));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
for (DBConfig dbConfig : dbConfigs) {
data.putAll(DBHandler.getDatafromDB(dbConfig));
}
return data;
}
}
|
package gui.db;
import java.awt.Color;
import javax.swing.JTable;
public interface CellDecorator
{
Color getBackgroundColor (final JTable table, final int row, final int col,
final Object value);
Color getBorderColor (final JTable table, final int row, final int col,
final Object value);
String getToolTipText (final JTable table, final int row, final int col,
final Object value);
}
|
package PA165.language_school_manager.Dao;
import PA165.language_school_manager.Entities.Lecturer;
import PA165.language_school_manager.Entities.Person;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import javax.persistence.NoResultException;
/**
* @author Viktor Slaný
*/
@Repository
public class PersonDaoImpl implements PersonDao {
@PersistenceContext
private EntityManager entityManager;
@Override
public Person findById(Long id) {
return entityManager.find(Person.class, id);
}
@Override
public Person findByUserName(String userName){
try {
return entityManager.createQuery("select p from Person p where p.userName = :userName", Person.class)
.setParameter("userName", userName).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
@Override
public List<Person> findByLastName(String lastName) {
try {
return entityManager.createQuery("select p from Person p where p.lastName = :lastName", Person.class)
.setParameter("lastName", lastName).getResultList();
} catch (NoResultException e) {
return null;
}
}
@Override
public Person create(Person person) {
entityManager.persist(person);
return person;
}
@Override
public Person update(Person person) {
entityManager.merge(person);
return person;
}
@Override
public Person delete(Person person) {
entityManager.remove(entityManager.merge(person));
return person;
}
@Override
public List<Person> findAll() {
return entityManager.createQuery("select person from Person person", Person.class).getResultList();
}
}
|
import java.util.Scanner;
public class UsaMultiplicacion{
public static void main(String[]args){
Multiplicacion m = new Multiplicacion();
Scanner Lee=new Scanner(System.in);
System.out.print("Ingresa un numero para X: ");
m.setNumero1(Lee.nextInt());
System.out.print("Ingresa un numero para Y: ");
m.setNumero2(Lee.nextInt());
System.out.println("El resultado de la multiplicacion es: "+m.multiplicacion());
System.out.println("La multiplicacion de X*Y es igual a la suma de X,Y veces: ");
System.out.println("El resultado de la suma de X, Y veces es: "+m.suma());
}
} |
package ch.mitti.exceptions;
public class ArrayAccessException extends Exception{
private static int counter = 0;
public ArrayAccessException(String message){
super(message);
counter++;
}
public int getExceptionCount(){
return counter;
}
}
|
package com.example.chordnote.ui.main.compose;
import com.example.chordnote.ui.base.MvpView;
public interface ComposeView extends MvpView {
}
|
// https://www.youtube.com/watch?reload=9&v=Ds4Kvd_xn4w
class Solution {
public char findTheDifference(String s, String t) {
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
for (char c: s.toCharArray())
map.put(c, map.getOrDefault(c, 0) + 1);
for (char c: t.toCharArray()) {
if (map.containsKey(c) && map.get(c) == 0 || !map.containsKey(c))
return c;
else
map.put(c, map.get(c) - 1);
}
return '!';
}
} |
package a3.test;
import a3.ai.JT_Destroyer;
import aiantwars.EAntType;
import aiantwars.IAntInfo;
import aiantwars.ILocationInfo;
import aiantwars.IOnGameFinished;
import aiantwars.ITeamInfo;
import aiantwars.graphicsinterface.IGraphicsAntWarsGUI;
import aiantwars.impl.AntWarsGameCtrl;
import aiantwars.impl.Board;
import aiantwars.impl.DummyGraphicsAntWarsGUI;
import aiantwars.impl.Location;
import aiantwars.impl.LogicAnt;
import aiantwars.impl.TeamInfo;
import a3.algorithm.ShortestPath;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import a3.memory.CollectiveMemory;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import a3.test.model.OnGameFinished;
import static a3.utility.Debug.isDebug;
/**
*
* @author Tobias Jacobsen
*/
public class ShortestPathTest {
private final IOnGameFinished onFinished;
Map<String, ILocationInfo> visibleLocations;
private Board board;
private IGraphicsAntWarsGUI antwarsGUI;
private AntWarsGameCtrl factory;
private ITeamInfo teamInfo;
private JT_Destroyer ai;
CollectiveMemory cm = new CollectiveMemory();
public ShortestPathTest() {
onFinished = new OnGameFinished();
isDebug = false;
visibleLocations = new HashMap();
cm.saveWorldSizeX(10);
cm.saveWorldSizeY(10);
}
/**
* Tests shortest path with an ordinary scenario
*/
@Test
public void testScenario1() {
Map<String, ILocationInfo> locations = getLocationsMap();
Location loc41 = (Location) locations.get("4,1");
loc41.setRock(true);
Location loc42 = (Location) locations.get("4,2");
loc42.setRock(true);
Location loc43 = (Location) locations.get("4,3");
loc43.setRock(true);
Location loc44 = (Location) locations.get("4,4");
loc44.setRock(true);
Location loc45 = (Location) locations.get("4,5");
loc45.setRock(true);
Location loc46 = (Location) locations.get("4,6");
loc46.setRock(true);
Location loc36 = (Location) locations.get("3,6");
loc36.setRock(true);
Location loc26 = (Location) locations.get("2,6");
loc26.setRock(true);
Location loc16 = (Location) locations.get("1,6");
loc16.setRock(true);
Location loc64 = (Location) locations.get("6,4");
loc64.setRock(true);
Location loc74 = (Location) locations.get("7,4");
loc74.setRock(true);
Location loc84 = (Location) locations.get("8,4");
loc84.setRock(true);
cm.addTiles(getLocationsList());
board = new Board(cm.getWorldSizeX(), cm.getWorldSizeY());
antwarsGUI = new DummyGraphicsAntWarsGUI(false);
factory = new AntWarsGameCtrl(antwarsGUI, board, onFinished);
ai = new JT_Destroyer();
teamInfo = new TeamInfo(1, "Test team");
IAntInfo ant = new LogicAnt(factory, board, loc84, 0/*direction*/, 1, teamInfo, EAntType.SCOUT, ai);
ILocationInfo start = new Location(2, 3);
ILocationInfo goal = new Location(2, 7);
ShortestPath sp = new ShortestPath(ant, start, goal, cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
assertEquals("2,4", shortestPath.get(0).getX() + "," + shortestPath.get(0).getY());
assertEquals("2,5", shortestPath.get(1).getX() + "," + shortestPath.get(1).getY());
assertEquals("1,5", shortestPath.get(2).getX() + "," + shortestPath.get(2).getY());
assertEquals("0,5", shortestPath.get(3).getX() + "," + shortestPath.get(3).getY());
assertEquals("0,6", shortestPath.get(4).getX() + "," + shortestPath.get(4).getY());
assertEquals("0,7", shortestPath.get(5).getX() + "," + shortestPath.get(5).getY());
assertEquals("1,7", shortestPath.get(6).getX() + "," + shortestPath.get(6).getY());
assertEquals("2,7", shortestPath.get(7).getX() + "," + shortestPath.get(7).getY());
}
/**
* Tests shortest path with an ordinary scenario
*/
@Test
public void testScenario2() {
Map<String, ILocationInfo> locations = getLocationsMap();
Location loc11 = (Location) locations.get("1,1");
loc11.setRock(true);
Location loc21 = (Location) locations.get("2,1");
loc21.setRock(true);
Location loc41 = (Location) locations.get("4,1");
loc41.setRock(true);
Location loc42 = (Location) locations.get("4,2");
loc42.setRock(true);
Location loc33 = (Location) locations.get("3,3");
loc33.setRock(true);
Location loc43 = (Location) locations.get("4,3");
loc43.setRock(true);
Location loc54 = (Location) locations.get("5,4");
loc54.setRock(true);
Location loc64 = (Location) locations.get("6,4");
loc64.setRock(true);
Location loc74 = (Location) locations.get("7,4");
loc74.setRock(true);
Location loc84 = (Location) locations.get("8,4");
loc84.setRock(true);
Location loc15 = (Location) locations.get("1,5");
loc15.setRock(true);
Location loc25 = (Location) locations.get("2,5");
loc25.setRock(true);
Location loc35 = (Location) locations.get("3,5");
loc35.setRock(true);
Location loc55 = (Location) locations.get("5,5");
loc55.setRock(true);
Location loc26 = (Location) locations.get("2,6");
loc26.setRock(true);
Location loc56 = (Location) locations.get("5,6");
loc56.setRock(true);
Location loc27 = (Location) locations.get("2,7");
loc27.setRock(true);
Location loc57 = (Location) locations.get("5,7");
loc57.setRock(true);
Location loc28 = (Location) locations.get("2,8");
loc28.setRock(true);
Location loc29 = (Location) locations.get("2,9");
loc29.setRock(true);
cm.addTiles(getLocationsList());
board = new Board(cm.getWorldSizeX(), cm.getWorldSizeY());
antwarsGUI = new DummyGraphicsAntWarsGUI(false);
factory = new AntWarsGameCtrl(antwarsGUI, board, onFinished);
ai = new JT_Destroyer();
teamInfo = new TeamInfo(1, "Test team");
ILocationInfo start = new Location(6, 3);
ILocationInfo goal = new Location(0, 9);
IAntInfo ant = new LogicAnt(factory, board, (Location) start, 2/*direction*/, 1, teamInfo, EAntType.SCOUT, ai);
ShortestPath sp = new ShortestPath(ant, start, goal, cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
assertEquals("5,3", shortestPath.get(0).getX() + "," + shortestPath.get(0).getY());
assertEquals("5,2", shortestPath.get(1).getX() + "," + shortestPath.get(1).getY());
assertEquals("5,1", shortestPath.get(2).getX() + "," + shortestPath.get(2).getY());
assertEquals("5,0", shortestPath.get(3).getX() + "," + shortestPath.get(3).getY());
assertEquals("4,0", shortestPath.get(4).getX() + "," + shortestPath.get(4).getY());
assertEquals("3,0", shortestPath.get(5).getX() + "," + shortestPath.get(5).getY());
assertEquals("2,0", shortestPath.get(6).getX() + "," + shortestPath.get(6).getY());
assertEquals("1,0", shortestPath.get(7).getX() + "," + shortestPath.get(7).getY());
assertEquals("0,0", shortestPath.get(8).getX() + "," + shortestPath.get(8).getY());
assertEquals("0,1", shortestPath.get(8).getX() + "," + shortestPath.get(9).getY());
assertEquals("0,2", shortestPath.get(9).getX() + "," + shortestPath.get(10).getY());
assertEquals("0,3", shortestPath.get(10).getX() + "," + shortestPath.get(11).getY());
assertEquals("0,4", shortestPath.get(11).getX() + "," + shortestPath.get(12).getY());
assertEquals("0,5", shortestPath.get(12).getX() + "," + shortestPath.get(13).getY());
assertEquals("0,6", shortestPath.get(13).getX() + "," + shortestPath.get(14).getY());
assertEquals("0,7", shortestPath.get(14).getX() + "," + shortestPath.get(15).getY());
assertEquals("0,8", shortestPath.get(15).getX() + "," + shortestPath.get(16).getY());
assertEquals("0,9", shortestPath.get(16).getX() + "," + shortestPath.get(17).getY());
}
/**
* Tests shortest path with an ordinary scenario
*/
@Test
public void testScenario3() {
Map<String, ILocationInfo> locations = getLocationsMap();
Location loc40 = (Location) locations.get("4,0");
loc40.setRock(true);
Location loc01 = (Location) locations.get("0,1");
loc01.setRock(true);
Location loc11 = (Location) locations.get("1,1");
loc11.setRock(true);
Location loc21 = (Location) locations.get("2,1");
loc21.setRock(true);
Location loc41 = (Location) locations.get("4,1");
loc41.setRock(true);
Location loc42 = (Location) locations.get("4,2");
loc42.setRock(true);
Location loc33 = (Location) locations.get("3,3");
loc33.setRock(true);
Location loc43 = (Location) locations.get("4,3");
loc43.setRock(true);
Location loc54 = (Location) locations.get("5,4");
loc54.setRock(true);
Location loc64 = (Location) locations.get("6,4");
loc64.setRock(true);
Location loc74 = (Location) locations.get("7,4");
loc74.setRock(true);
Location loc15 = (Location) locations.get("1,5");
loc15.setRock(true);
Location loc25 = (Location) locations.get("2,5");
loc25.setRock(true);
Location loc35 = (Location) locations.get("3,5");
loc35.setRock(true);
Location loc55 = (Location) locations.get("5,5");
loc55.setRock(true);
Location loc26 = (Location) locations.get("2,6");
loc26.setRock(true);
Location loc56 = (Location) locations.get("5,6");
loc56.setRock(true);
Location loc27 = (Location) locations.get("2,7");
loc27.setRock(true);
Location loc57 = (Location) locations.get("5,7");
loc57.setRock(true);
Location loc28 = (Location) locations.get("2,8");
loc28.setRock(true);
Location loc29 = (Location) locations.get("2,9");
loc29.setRock(true);
cm.addTiles(getLocationsList());
board = new Board(cm.getWorldSizeX(), cm.getWorldSizeY());
antwarsGUI = new DummyGraphicsAntWarsGUI(false);
factory = new AntWarsGameCtrl(antwarsGUI, board, onFinished);
ai = new JT_Destroyer();
teamInfo = new TeamInfo(1, "Test team");
ILocationInfo start = new Location(6, 3);
ILocationInfo goal = new Location(0, 9);
IAntInfo ant = new LogicAnt(factory, board, (Location) start, 3/*direction*/, 1, teamInfo, EAntType.SCOUT, ai);
ShortestPath sp = new ShortestPath(ant, start, goal, cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
assertEquals("7,3", shortestPath.get(0).getX() + "," + shortestPath.get(0).getY());
assertEquals("8,3", shortestPath.get(1).getX() + "," + shortestPath.get(1).getY());
assertEquals("8,4", shortestPath.get(2).getX() + "," + shortestPath.get(2).getY());
assertEquals("8,5", shortestPath.get(3).getX() + "," + shortestPath.get(3).getY());
assertEquals("8,6", shortestPath.get(4).getX() + "," + shortestPath.get(4).getY());
assertEquals("8,7", shortestPath.get(5).getX() + "," + shortestPath.get(5).getY());
assertEquals("8,8", shortestPath.get(6).getX() + "," + shortestPath.get(6).getY());
assertEquals("8,9", shortestPath.get(7).getX() + "," + shortestPath.get(7).getY());
assertEquals("7,9", shortestPath.get(8).getX() + "," + shortestPath.get(8).getY());
assertEquals("6,9", shortestPath.get(9).getX() + "," + shortestPath.get(9).getY());
assertEquals("5,9", shortestPath.get(10).getX() + "," + shortestPath.get(10).getY());
assertEquals("4,9", shortestPath.get(11).getX() + "," + shortestPath.get(11).getY());
assertEquals("4,8", shortestPath.get(12).getX() + "," + shortestPath.get(12).getY());
assertEquals("4,7", shortestPath.get(13).getX() + "," + shortestPath.get(13).getY());
assertEquals("4,6", shortestPath.get(14).getX() + "," + shortestPath.get(14).getY());
assertEquals("4,5", shortestPath.get(15).getX() + "," + shortestPath.get(15).getY());
assertEquals("4,4", shortestPath.get(16).getX() + "," + shortestPath.get(16).getY());
assertEquals("3,4", shortestPath.get(17).getX() + "," + shortestPath.get(17).getY());
assertEquals("2,4", shortestPath.get(18).getX() + "," + shortestPath.get(18).getY());
assertEquals("1,4", shortestPath.get(19).getX() + "," + shortestPath.get(19).getY());
assertEquals("0,4", shortestPath.get(20).getX() + "," + shortestPath.get(20).getY());
assertEquals("0,5", shortestPath.get(21).getX() + "," + shortestPath.get(21).getY());
assertEquals("0,6", shortestPath.get(22).getX() + "," + shortestPath.get(22).getY());
assertEquals("0,7", shortestPath.get(23).getX() + "," + shortestPath.get(23).getY());
assertEquals("0,8", shortestPath.get(24).getX() + "," + shortestPath.get(24).getY());
assertEquals("0,9", shortestPath.get(25).getX() + "," + shortestPath.get(25).getY());
}
/**
* Tests shortest path with an ordinary scenario
*/
@Test
public void testScenario4() {
Map<String, ILocationInfo> locations = getLocationsMap();
Location loc40 = (Location) locations.get("4,0");
loc40.setRock(true);
Location loc21 = (Location) locations.get("2,1");
loc21.setRock(true);
Location loc41 = (Location) locations.get("4,1");
loc41.setRock(true);
Location loc02 = (Location) locations.get("0,2");
loc02.setRock(true);
Location loc12 = (Location) locations.get("1,2");
loc12.setRock(true);
Location loc22 = (Location) locations.get("2,2");
loc22.setRock(true);
Location loc42 = (Location) locations.get("4,2");
loc42.setRock(true);
Location loc62 = (Location) locations.get("6,2");
loc62.setRock(true);
Location loc72 = (Location) locations.get("7,2");
loc72.setRock(true);
Location loc92 = (Location) locations.get("9,2");
loc92.setRock(true);
Location loc43 = (Location) locations.get("4,3");
loc43.setRock(true);
Location loc63 = (Location) locations.get("6,3");
loc63.setRock(true);
Location loc14 = (Location) locations.get("1,4");
loc14.setRock(true);
Location loc24 = (Location) locations.get("2,4");
loc24.setRock(true);
Location loc34 = (Location) locations.get("3,4");
loc34.setRock(true);
Location loc44 = (Location) locations.get("4,4");
loc44.setRock(true);
Location loc64 = (Location) locations.get("6,4");
loc64.setRock(true);
Location loc84 = (Location) locations.get("8,4");
loc84.setRock(true);
Location loc65 = (Location) locations.get("6,5");
loc65.setRock(true);
Location loc06 = (Location) locations.get("0,6");
loc06.setRock(true);
Location loc16 = (Location) locations.get("1,6");
loc16.setRock(true);
Location loc26 = (Location) locations.get("2,6");
loc26.setRock(true);
Location loc36 = (Location) locations.get("3,6");
loc36.setRock(true);
Location loc46 = (Location) locations.get("4,6");
loc46.setRock(true);
Location loc56 = (Location) locations.get("5,6");
loc56.setRock(true);
Location loc66 = (Location) locations.get("6,6");
loc66.setRock(true);
Location loc76 = (Location) locations.get("7,6");
loc76.setRock(true);
Location loc86 = (Location) locations.get("8,6");
loc86.setRock(true);
Location loc27 = (Location) locations.get("2,7");
loc27.setRock(true);
Location loc47 = (Location) locations.get("4,7");
loc47.setRock(true);
Location loc28 = (Location) locations.get("2,8");
loc28.setRock(true);
Location loc48 = (Location) locations.get("4,8");
loc48.setRock(true);
Location loc68 = (Location) locations.get("6,8");
loc68.setRock(true);
Location loc69 = (Location) locations.get("6,9");
loc69.setRock(true);
cm.addTiles(getLocationsList());
board = new Board(cm.getWorldSizeX(), cm.getWorldSizeY());
antwarsGUI = new DummyGraphicsAntWarsGUI(false);
factory = new AntWarsGameCtrl(antwarsGUI, board, onFinished);
ai = new JT_Destroyer();
teamInfo = new TeamInfo(1, "Test team");
ILocationInfo start = new Location(1, 1);
ILocationInfo goal = new Location(0, 7);
IAntInfo ant = new LogicAnt(factory, board, (Location) start, 3/*direction*/, 1, teamInfo, EAntType.SCOUT, ai);
ShortestPath sp = new ShortestPath(ant, start, goal, cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
assertEquals("1,0", shortestPath.get(0).getX() + "," + shortestPath.get(0).getY());
assertEquals("2,0", shortestPath.get(1).getX() + "," + shortestPath.get(1).getY());
assertEquals("3,0", shortestPath.get(2).getX() + "," + shortestPath.get(2).getY());
assertEquals("3,1", shortestPath.get(3).getX() + "," + shortestPath.get(3).getY());
assertEquals("3,2", shortestPath.get(4).getX() + "," + shortestPath.get(4).getY());
assertEquals("3,3", shortestPath.get(5).getX() + "," + shortestPath.get(5).getY());
assertEquals("2,3", shortestPath.get(6).getX() + "," + shortestPath.get(6).getY());
assertEquals("1,3", shortestPath.get(7).getX() + "," + shortestPath.get(7).getY());
assertEquals("0,3", shortestPath.get(8).getX() + "," + shortestPath.get(8).getY());
assertEquals("0,4", shortestPath.get(9).getX() + "," + shortestPath.get(9).getY());
assertEquals("0,5", shortestPath.get(10).getX() + "," + shortestPath.get(10).getY());
assertEquals("1,5", shortestPath.get(11).getX() + "," + shortestPath.get(11).getY());
assertEquals("2,5", shortestPath.get(12).getX() + "," + shortestPath.get(12).getY());
assertEquals("3,5", shortestPath.get(13).getX() + "," + shortestPath.get(13).getY());
assertEquals("4,5", shortestPath.get(14).getX() + "," + shortestPath.get(14).getY());
assertEquals("5,5", shortestPath.get(15).getX() + "," + shortestPath.get(15).getY());
assertEquals("5,4", shortestPath.get(16).getX() + "," + shortestPath.get(16).getY());
assertEquals("5,3", shortestPath.get(17).getX() + "," + shortestPath.get(17).getY());
assertEquals("5,2", shortestPath.get(18).getX() + "," + shortestPath.get(18).getY());
assertEquals("5,1", shortestPath.get(19).getX() + "," + shortestPath.get(19).getY());
assertEquals("6,1", shortestPath.get(20).getX() + "," + shortestPath.get(20).getY());
assertEquals("7,1", shortestPath.get(21).getX() + "," + shortestPath.get(21).getY());
assertEquals("8,1", shortestPath.get(22).getX() + "," + shortestPath.get(22).getY());
assertEquals("8,2", shortestPath.get(23).getX() + "," + shortestPath.get(23).getY());
assertEquals("8,3", shortestPath.get(24).getX() + "," + shortestPath.get(24).getY());
assertEquals("9,3", shortestPath.get(25).getX() + "," + shortestPath.get(25).getY());
assertEquals("9,4", shortestPath.get(26).getX() + "," + shortestPath.get(26).getY());
assertEquals("9,5", shortestPath.get(27).getX() + "," + shortestPath.get(27).getY());
assertEquals("9,6", shortestPath.get(28).getX() + "," + shortestPath.get(28).getY());
assertEquals("9,7", shortestPath.get(29).getX() + "," + shortestPath.get(29).getY());
assertEquals("8,7", shortestPath.get(30).getX() + "," + shortestPath.get(30).getY());
assertEquals("7,7", shortestPath.get(31).getX() + "," + shortestPath.get(31).getY());
assertEquals("6,7", shortestPath.get(32).getX() + "," + shortestPath.get(32).getY());
assertEquals("5,7", shortestPath.get(33).getX() + "," + shortestPath.get(33).getY());
assertEquals("5,8", shortestPath.get(34).getX() + "," + shortestPath.get(34).getY());
assertEquals("5,9", shortestPath.get(35).getX() + "," + shortestPath.get(35).getY());
assertEquals("4,9", shortestPath.get(36).getX() + "," + shortestPath.get(36).getY());
assertEquals("3,9", shortestPath.get(37).getX() + "," + shortestPath.get(37).getY());
assertEquals("2,9", shortestPath.get(38).getX() + "," + shortestPath.get(38).getY());
assertEquals("1,9", shortestPath.get(39).getX() + "," + shortestPath.get(39).getY());
assertEquals("0,9", shortestPath.get(40).getX() + "," + shortestPath.get(40).getY());
assertEquals("0,8", shortestPath.get(41).getX() + "," + shortestPath.get(41).getY());
assertEquals("0,7", shortestPath.get(42).getX() + "," + shortestPath.get(42).getY());
}
/**
* Tests shortest path with an ordinary scenario
*/
@Test
public void testScenario5() {
Map<String, ILocationInfo> locations = getLocationsMap();
Location loc33 = (Location) locations.get("3,3");
loc33.setRock(true);
Location loc34 = (Location) locations.get("3,4");
loc34.setRock(true);
Location loc35 = (Location) locations.get("3,5");
loc35.setRock(true);
Location loc36 = (Location) locations.get("3,6");
loc36.setRock(true);
Location loc37 = (Location) locations.get("3,7");
loc37.setRock(true);
cm.addTiles(getLocationsList());
board = new Board(cm.getWorldSizeX(), cm.getWorldSizeY());
antwarsGUI = new DummyGraphicsAntWarsGUI(false);
factory = new AntWarsGameCtrl(antwarsGUI, board, onFinished);
ai = new JT_Destroyer();
teamInfo = new TeamInfo(1, "Test team");
ILocationInfo start = new Location(1, 5);
ILocationInfo goal = new Location(6, 5);
IAntInfo ant = new LogicAnt(factory, board, (Location) start, 3/*direction*/, 1, teamInfo, EAntType.SCOUT, ai);
ShortestPath sp = new ShortestPath(ant, start, goal, cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
assertEquals("2,5", shortestPath.get(0).getX() + "," + shortestPath.get(0).getY());
assertEquals("2,4", shortestPath.get(1).getX() + "," + shortestPath.get(1).getY());
assertEquals("2,3", shortestPath.get(2).getX() + "," + shortestPath.get(2).getY());
assertEquals("2,2", shortestPath.get(3).getX() + "," + shortestPath.get(3).getY());
assertEquals("3,2", shortestPath.get(4).getX() + "," + shortestPath.get(4).getY());
assertEquals("4,2", shortestPath.get(5).getX() + "," + shortestPath.get(5).getY());
assertEquals("5,2", shortestPath.get(6).getX() + "," + shortestPath.get(6).getY());
assertEquals("6,2", shortestPath.get(7).getX() + "," + shortestPath.get(7).getY());
assertEquals("6,3", shortestPath.get(8).getX() + "," + shortestPath.get(8).getY());
assertEquals("6,4", shortestPath.get(9).getX() + "," + shortestPath.get(9).getY());
assertEquals("6,5", shortestPath.get(10).getX() + "," + shortestPath.get(10).getY());
}
/**
* Tests shortest path with an ordinary scenario and when there is an ant on goal (which is allowed)
*/
@Test
public void testScenario6() {
Map<String, ILocationInfo> locations = getLocationsMap();
Location loc33 = (Location) locations.get("3,3");
LogicAnt queen = new LogicAnt(factory, board, loc33, 0, 0, teamInfo, EAntType.QUEEN, ai);
loc33.setAnt(queen);
cm.addTiles(getLocationsList());
board = new Board(cm.getWorldSizeX(), cm.getWorldSizeY());
antwarsGUI = new DummyGraphicsAntWarsGUI(false);
factory = new AntWarsGameCtrl(antwarsGUI, board, onFinished);
ai = new JT_Destroyer();
teamInfo = new TeamInfo(1, "Test team");
ILocationInfo start = new Location(1, 5);
ILocationInfo goal = new Location(3, 3);
IAntInfo ant = new LogicAnt(factory, board, (Location) start, 3/*direction*/, 1, teamInfo, EAntType.SCOUT, ai);
ShortestPath sp = new ShortestPath(ant, start, goal, cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
assertEquals("2,5", shortestPath.get(0).getX() + "," + shortestPath.get(0).getY());
assertEquals("3,5", shortestPath.get(1).getX() + "," + shortestPath.get(1).getY());
assertEquals("3,4", shortestPath.get(2).getX() + "," + shortestPath.get(2).getY());
assertEquals("3,3", shortestPath.get(3).getX() + "," + shortestPath.get(3).getY());
}
/**
* Tests shortest path when no path could be found
*/
@Test(expected = NullPointerException.class)
public void testScenario7() {
Map<String, ILocationInfo> locations = getLocationsMap();
Location loc23 = (Location) locations.get("2,3");
loc23.setRock(true);
Location loc33 = (Location) locations.get("3,3");
loc33.setRock(true);
Location loc43 = (Location) locations.get("4,3");
loc43.setRock(true);
Location loc53 = (Location) locations.get("5,3");
loc53.setRock(true);
Location loc63 = (Location) locations.get("6,3");
loc63.setRock(true);
Location loc24 = (Location) locations.get("2,4");
loc24.setRock(true);
Location loc25 = (Location) locations.get("2,5");
loc25.setRock(true);
Location loc26 = (Location) locations.get("2,6");
loc26.setRock(true);
Location loc27 = (Location) locations.get("2,7");
loc27.setRock(true);
Location loc37 = (Location) locations.get("3,7");
loc37.setRock(true);
Location loc47 = (Location) locations.get("4,7");
loc47.setRock(true);
Location loc57 = (Location) locations.get("5,7");
loc57.setRock(true);
Location loc67 = (Location) locations.get("6,7");
loc67.setRock(true);
Location loc66 = (Location) locations.get("6,6");
loc66.setRock(true);
Location loc65 = (Location) locations.get("6,5");
loc65.setRock(true);
Location loc64 = (Location) locations.get("6,4");
loc64.setRock(true);
cm.addTiles(getLocationsList());
board = new Board(cm.getWorldSizeX(), cm.getWorldSizeY());
antwarsGUI = new DummyGraphicsAntWarsGUI(false);
factory = new AntWarsGameCtrl(antwarsGUI, board, onFinished);
ai = new JT_Destroyer();
teamInfo = new TeamInfo(1, "Test team");
ILocationInfo start = new Location(4, 5);
ILocationInfo goal = new Location(8, 8);
IAntInfo ant = new LogicAnt(factory, board, (Location) start, 0/*direction*/, 1, teamInfo, EAntType.SCOUT, ai);
ShortestPath sp = new ShortestPath(ant, start, goal, cm);
List<ILocationInfo> shortestPath = sp.getShortestPath();
assertEquals("exception", shortestPath.get(0).getX() + "," + shortestPath.get(0).getY());
}
private Map getLocationsMap() {
visibleLocations = new HashMap();
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
ILocationInfo loc = new Location(x, y);
visibleLocations.put(x + "," + y, loc);
}
}
return visibleLocations;
}
private List getLocationsList() {
List<ILocationInfo> list = new ArrayList(visibleLocations.values());
return list;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package java2plant.builder;
import java.io.File;
import java.io.InputStream;
import java2plant.describer.ContextDescriber;
/**
*
* @author arthur
*/
public abstract class AbstractBuilder {
protected InputStream is;
protected ContextDescriber context;
public abstract ContextDescriber buildFromFile(File in);
/**
* This method does the same as String.split but also removes the empty
* strings from the result array.
*
* @param str
* A String to split
* @param regex
* A regular expression corresponding to a separator
* @return array of splited String
*/
public static String[] splitString(String str, String regex) {
// TODO: clean up that mess
String buffer = null;
if (str.contains("<") && str.indexOf(">") > str.indexOf("<")) {
buffer = str.substring(str.indexOf("<"), str.indexOf(">") + 1);
str = str.replaceAll("<[^>]*>", "!!----!!");
}
String[] split = str.split(regex);
int count = 0;
for (String s : split) {
if (!s.isEmpty()) {
count++;
}
}
String[] result = new String[count];
count = 0;
for (String s : split) {
if (!s.isEmpty()) {
result[count] = s;
count++;
}
}
if (buffer != null) {
for (int i = 0; i < result.length; i++) {
result[i] = result[i].replaceAll("!!----!!", buffer);
}
}
return result;
}
public static String[] splitString(String str) {
return splitString(str, "[ \n\t;{}]");
}
}
|
package official;
import okhttp3.*;
import java.io.IOException;
public class Overview {
private OkHttpClient client = new OkHttpClient();
/**
* GET A URL
*/
public String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
/**
* POST TO A SERVER
*/
public static final MediaType JSON = MediaType.get("application/json;charset=utf-8");
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try(Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
|
package com.testFileUpload.common;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
/**
* 返回结果类
*
* @author CAIFUCHENG3
*/
public class ResultObject<T> {
/**
* 成功代码
*/
public static final String SUCCESS = "S1A00000";
/**
* 失败代码
*/
public static final String FAILURE = "E0B00001";
/**
* 返回结果代码
*/
@ApiModelProperty(value = "返回结果代码", example = "S1A00000:成功;E0B00001:失败;")
private String code;
/**
* 返回结果
*/
@ApiModelProperty(value = "返回结果提示消息", example = "成功提示消息或异常提示消息")
private String msg;
@ApiModelProperty(value = "返回结果", example = "不同业务返回字段不同,可能为空")
private T data;
/**
* 返回错误异常堆栈(原始异常)
*/
@ApiModelProperty(value = "返回错误异常堆栈", example = "返回错误异常堆栈")
private String error;
/**
* 构造函数
*/
public ResultObject() {
this(SUCCESS, "");
}
/**
* 构造函数,执行成功
*
* @param msg
* 成功结果
*/
public ResultObject(String msg) {
this(SUCCESS, msg);
}
public ResultObject(String code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 构造函数
*
* @param code
* 成功或失败代码
* @param msg
* 成功或失败结果
* @param data
* 结果集
*/
public ResultObject(String code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static ResultObject makeSuccess() {
return new ResultObject();
}
/**
* 封装只有msg返回的成功查询
* @param msg
* @return
*/
public static ResultObject makeSuccess(String msg) {
return new ResultObject(msg);
}
/**
* 封装含对象和msg的成功返回查询
* @param data
* @param msg
* @param <R>
* @return
*/
public static<R> ResultObject<R> makeSuccess(R data,String msg){
return new ResultObject(SUCCESS,msg,data);
}
/**
* 只有失败信息的查询返回
* @param msg
* @return
*/
public static ResultObject makeFail(String msg) {
return new ResultObject(FAILURE, msg);
}
/**
* 含返回对象和失败信息的查询返回
* @param data
* @param msg
* @param <R>
* @return
*/
public static<R> ResultObject<R> makeFail(R data,String msg){
return new ResultObject(FAILURE,msg,data);
}
public Boolean isSuccess() {
return Objects.equals(SUCCESS, this.code);
}
public Boolean isFail() {
return !isSuccess();
}
/**
* @param code
* the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the code
*/
public String getCode() {
return code;
}
public Object getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString(){
return "code="+code+",msg= "+msg+",error "+error;
}
}
|
package pl.olart.pmsuite.services;
import pl.olart.pmsuite.model.Metadane;
import pl.olart.pmsuite.model.RozliczenieRFPBean;
import pl.olart.pmsuite.model.TypKosztuBean;
import pl.olart.pmsuite.model.Wynik;
import java.util.*;
/**
* User: grp
* Date: 16.06.16
* Time: 02:17
*/
public class RozliczenieService {
public static List<TypKosztuBean> wyodrebnijTypyKosztow(List<RozliczenieRFPBean> lista) {
HashSet<String> listaTypow = new HashSet<String>();
for(RozliczenieRFPBean rozliczenie : lista) {
listaTypow.add(rozliczenie.getTypElementuKosztu());
}
List<TypKosztuBean> typy = new ArrayList<TypKosztuBean>();
for(String typ : listaTypow) {
typy.add(new TypKosztuBean(typ));
}
przypiszOsobyDoTypu(typy, lista);
Collections.sort(typy);
return typy;
}
private static void przypiszOsobyDoTypu(List<TypKosztuBean> typy, List<RozliczenieRFPBean> lista) {
for(TypKosztuBean typ : typy) {
for(RozliczenieRFPBean rozliczenie : lista) {
if(rozliczenie.getTypElementuKosztu().equals(typ.getNazwa())) {
if(typ.getKtoPrzypisany() == null) {
typ.setKtoPrzypisany(rozliczenie.getWygenerowanyPrzez());
} else if (!typ.getKtoPrzypisany().contains(rozliczenie.getWygenerowanyPrzez())) {
typ.setKtoPrzypisany(typ.getKtoPrzypisany() + ", " + rozliczenie.getWygenerowanyPrzez());
}
}
}
}
}
public static void sklasyfikujWstepnieTypyKosztow(List<TypKosztuBean> nieprzydzielone, List<TypKosztuBean> etatIdzielo, List<TypKosztuBean> kontraktowcy, List<TypKosztuBean> zewnetrzni, List<TypKosztuBean> nieosobowe) {
List<TypKosztuBean> nieprzydzieloneCopy = (List<TypKosztuBean>) ((ArrayList<TypKosztuBean>) nieprzydzielone).clone();
for(TypKosztuBean typBean : nieprzydzieloneCopy) {
String typ = typBean.getNazwa();
//reguly
if(typ.toLowerCase().contains("kontr".toLowerCase())) {
kontraktowcy.add(typBean);
nieprzydzielone.remove(typBean);
} else if(typ.toLowerCase().contains("zus".toLowerCase())) {
etatIdzielo.add(typBean);
nieprzydzielone.remove(typBean);
} else if(typ.toLowerCase().contains("prac".toLowerCase())) {
etatIdzielo.add(typBean);
nieprzydzielone.remove(typBean);
} else if(typ.toLowerCase().contains("zewn".toLowerCase())) {
zewnetrzni.add(typBean);
nieprzydzielone.remove(typBean);
// } else if(typ.toLowerCase().contains("obc".toLowerCase())) {
// zewnetrzni.add(typBean);
// nieprzydzielone.remove(typBean); //nie zawsze to dobrze dziala, mozna to przywrocic jesli umozliwie przenoszenie typow kosztow pomiedzy wszystkimi sekcjami
} else if(typ.toLowerCase().contains("pozos".toLowerCase())) {
nieosobowe.add(typBean);
nieprzydzielone.remove(typBean);
}
}
}
public static void wyliczWartosci(List<Wynik> wyniki, List<RozliczenieRFPBean> listaPierwotnaZCSV, List<TypKosztuBean> etatIdzielo, List<TypKosztuBean> kontraktowcy, List<TypKosztuBean> zewnetrzni,List<TypKosztuBean> nieosobowe, Metadane metadane) {
String rok = wyliczRok(listaPierwotnaZCSV);
metadane.setRok(rok);
if(wyniki.size() == 0) { //pierwszy wrzucony plik
Wynik wynikEtat = new Wynik("Rzeczywiste koszty bezpośrednie pracowników etatowych lub o dzieło");
Wynik wynikKontrakt = new Wynik("Rzeczywiste koszty bezpośrednie współpracowników kontraktowych");
Wynik wynikZewnetrzni = new Wynik("Rzeczywiste koszty bezpośrednie współpracowników zewnętrznych");
Wynik wynikNieosobowe = new Wynik("Rzeczywiste koszty nieosobowe");
Wynik wynikLacznieOsobowe = new Wynik("Koszty osobowe lacznie");
wyniki.add(wynikEtat);
wyniki.add(wynikKontrakt);
wyniki.add(wynikZewnetrzni);
wyniki.add(wynikNieosobowe);
wyniki.add(wynikLacznieOsobowe);
}
Wynik wynikEtat = wyniki.get(0);
Wynik wynikKontrakt = wyniki.get(1);
Wynik wynikZewnetrzni = wyniki.get(2);
Wynik wynikNieosobowe = wyniki.get(3);
Wynik wynikLacznieOsobowe = wyniki.get(4);
wyliczWartosci(listaPierwotnaZCSV, etatIdzielo, wynikEtat, metadane);
wyliczWartosci(listaPierwotnaZCSV, kontraktowcy, wynikKontrakt, metadane);
wyliczWartosci(listaPierwotnaZCSV, zewnetrzni, wynikZewnetrzni, metadane);
wyliczWartosci(listaPierwotnaZCSV, nieosobowe, wynikNieosobowe, metadane);
wyliczLacznieOsobowe(wynikLacznieOsobowe, wynikEtat, wynikKontrakt, wynikZewnetrzni);
}
private static void wyliczLacznieOsobowe(Wynik wynikLacznieOsobowe, Wynik wynikEtat, Wynik wynikKontrakt, Wynik wynikZewnetrzni) {
wynikLacznieOsobowe.przyjmijWartosci(wynikEtat);
wynikLacznieOsobowe.dodaj(wynikKontrakt);
wynikLacznieOsobowe.dodaj(wynikZewnetrzni);
}
private static void wyliczWartosci(List<RozliczenieRFPBean> listaPierwotnaZCSV, List<TypKosztuBean> etatIdzielo, Wynik wynik, Metadane metadane) {
Map<Integer, Double> wynikMap = new HashMap<Integer, Double>();
inicjujMape(wynikMap, wynik);
for(TypKosztuBean typKosztuBean : etatIdzielo) {
wypelnijMape(listaPierwotnaZCSV, wynikMap, typKosztuBean, metadane);
}
przypiszElementyMapyDoWyniku(wynikMap, wynik);
}
private static void wypelnijMape(List<RozliczenieRFPBean> listaPierwotnaZCSV, Map<Integer, Double> wynikMap, TypKosztuBean typKosztuBean, Metadane metadane) {
for(RozliczenieRFPBean rozliczenie : listaPierwotnaZCSV) {
if(typKosztuBean.getNazwa().equals(rozliczenie.getTypElementuKosztu())) {
Date dataDostawy = rozliczenie.getDataDostawy();
Calendar cal = Calendar.getInstance();
cal.setTime(dataDostawy);
Integer miesiac = cal.get(Calendar.MONTH);
wynikMap.put(miesiac, wynikMap.get(miesiac) + rozliczenie.getKwotaNetto());
metadane.setLacznie(metadane.getLacznie() + rozliczenie.getKwotaNetto());
}
}
}
private static Double getWynikDlaMiesiaca(Wynik wynik, Integer miesiac) {
if(miesiac == 0 && wynik.getWynik1() != null) {
return wynik.getWynik1();
} else if(miesiac == 1 && wynik.getWynik2() != null) {
return wynik.getWynik2();
} else if(miesiac == 2 && wynik.getWynik3() != null) {
return wynik.getWynik3();
} else if(miesiac == 3 && wynik.getWynik4() != null) {
return wynik.getWynik4();
} else if(miesiac == 4 && wynik.getWynik5() != null) {
return wynik.getWynik5();
} else if(miesiac == 5 && wynik.getWynik6() != null) {
return wynik.getWynik6();
} else if(miesiac == 6 && wynik.getWynik7() != null) {
return wynik.getWynik7();
} else if(miesiac == 7 && wynik.getWynik8() != null) {
return wynik.getWynik8();
} else if(miesiac == 8 && wynik.getWynik9() != null) {
return wynik.getWynik9();
} else if(miesiac == 9 && wynik.getWynik10() != null) {
return wynik.getWynik10();
} else if(miesiac == 10 && wynik.getWynik11() != null) {
return wynik.getWynik11();
} else if(miesiac == 11 && wynik.getWynik12() != null) {
return wynik.getWynik12();
}
return 0d;
}
private static String wyliczRok(List<RozliczenieRFPBean> listaPierwotnaZCSV) {
if(listaPierwotnaZCSV != null && listaPierwotnaZCSV.size() > 0) {
RozliczenieRFPBean rozliczenie = listaPierwotnaZCSV.get(0);
Calendar cal = Calendar.getInstance();
cal.setTime(rozliczenie.getDataDostawy());
int year = cal.get(Calendar.YEAR);
return year + "";
}
return null;
}
private static void przypiszElementyMapyDoWyniku(Map<Integer, Double> wynikMap, Wynik wynik) {
for(Map.Entry<Integer, Double> entry : wynikMap.entrySet()) {
if(entry.getKey() == 0) {
wynik.setWynik1(entry.getValue());
} else if(entry.getKey() == 1) {
wynik.setWynik2(entry.getValue());
} else if(entry.getKey() == 2) {
wynik.setWynik3(entry.getValue());
} else if(entry.getKey() == 3) {
wynik.setWynik4(entry.getValue());
} else if(entry.getKey() == 4) {
wynik.setWynik5(entry.getValue());
} else if(entry.getKey() == 5) {
wynik.setWynik6(entry.getValue());
} else if(entry.getKey() == 6) {
wynik.setWynik7(entry.getValue());
} else if(entry.getKey() == 7) {
wynik.setWynik8(entry.getValue());
} else if(entry.getKey() == 8) {
wynik.setWynik9(entry.getValue());
} else if(entry.getKey() == 9) {
wynik.setWynik10(entry.getValue());
} else if(entry.getKey() == 10) {
wynik.setWynik11(entry.getValue());
} else if(entry.getKey() == 11) {
wynik.setWynik12(entry.getValue());
}
}
}
private static void inicjujMape(Map<Integer, Double> wynikMap, Wynik wynik) {
for (int i = 0; i < 12; i++) {
wynikMap.put(i, getWynikDlaMiesiaca(wynik, i));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.