text stringlengths 10 2.72M |
|---|
package com.example.snapup_android.service;
import com.example.snapup_android.dao.TrainRunMapper;
import com.example.snapup_android.dao.TrainSerialMapper;
import com.example.snapup_android.pojo.TrainInfo;
import com.example.snapup_android.pojo.TrainRun;
import com.example.snapup_android.pojo.TrainSerial;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class TrainSerialServiceImpl implements TrainSerialService{
private TrainSerialMapper trainSerialMapper;
private TrainRunMapper trainRunMapper;
public void setTrainRunMapper(TrainRunMapper trainRunMapper) {
this.trainRunMapper = trainRunMapper;
}
private StationOnLineService stationOnLineService;
private StationService stationService;
private TimeTableService timeTableService;
public void setTimeTableService(TimeTableService timeTableService) {
this.timeTableService = timeTableService;
}
public void setStationService(StationService stationService) {
this.stationService = stationService;
}
public void setStationOnLineService(StationOnLineService stationOnLineService) {
this.stationOnLineService = stationOnLineService;
}
public void setTrainSerialMapper(TrainSerialMapper trainSerialMapper) {
this.trainSerialMapper = trainSerialMapper;
}
public void createTrainSerial(Date date, String run_num) {
if(trainSerialMapper.findTrainSerial(new TrainSerial(0, date, run_num)) == null){
trainSerialMapper.createTrainSerial(new TrainSerial(0, date, run_num));
}
}
public List<TrainSerial> getAllTrainSerial() {
return trainSerialMapper.findAllTrainSerial();
}
public TrainInfo getTrainInfo(int run_serial) {
TrainSerial trainSerial = trainSerialMapper.findTrainSerialBySerialNum(run_serial);
String run_code = trainSerial.getRun_code();
String start_station_code = stationOnLineService.getStartStation(run_code);
String end_station_code = stationOnLineService.getEndStation(run_code);
String start_station_name = stationService.getStationByCode(start_station_code).getName();
String end_station_name = stationService.getStationByCode(end_station_code).getName();
Time startTime = timeTableService.getDepartTime(run_code, start_station_code);
Time endTime = timeTableService.getArrivalTime(run_code, end_station_code);
return new TrainInfo(run_code, startTime, endTime, start_station_name, end_station_name);
}
public void generateTrainSerial(List<String> run_codes, int days, Date startDay) {
for(String run_code: run_codes){
Date day = startDay;
for(int i=0;i<days;i++){
createTrainSerial(day, run_code);
Calendar c = Calendar.getInstance();
c.setTime(day);
c.add(Calendar.DAY_OF_MONTH, 1);
day = c.getTime();
}
}
}
public List<TrainRun> getAllTrainRun(){
List<String> run_codes = trainSerialMapper.getAllTrainRunCode();
List<TrainRun> trainRuns = new ArrayList<TrainRun>();
for(String run_code:run_codes){
trainRuns.add(trainRunMapper.findTrainRunByCode(run_code));
}
return trainRuns;
}
}
|
package Revise.threads;
import java.io.*;
import java.net.URL;
import java.util.Comparator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.Semaphore;
class QueueTurnstile {
Semaphore queueSemaphore = new Semaphore(1);
volatile boolean lowPriorityTaskPaused = false;
private Object notifyWait = new Object();
public void highPriorityTaskStarts() {
lowPriorityTaskPaused = true;
queueSemaphore.acquireUninterruptibly();
}
public void highPriorityTaskEnds() {
queueSemaphore.release();
if (lowPriorityTaskPaused == true) {
lowPriorityTaskPaused = false;
notifyTasks();
}
}
public void lowPriorityTaskStarts() {
while (true) {
if (!lowPriorityTaskPaused) break;
waitTasks();
}
queueSemaphore.acquireUninterruptibly();
lowPriorityTaskPaused = false;
}
public void lowPriorityTaskEnds() {
lowPriorityTaskPaused = false;
queueSemaphore.release();
}
private void waitTasks() {
synchronized (notifyWait) {
try {
notifyWait.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void notifyTasks() {
synchronized (notifyWait) {
notifyWait.notify();
}
}
}
class Job implements Runnable {
String jobName;
String URL = "";
int priority; //1 being the highest
QueueTurnstile queueTurnstile;
Job(String jobName, String url, int priority, QueueTurnstile queueTurnstile) {
this.jobName = jobName;
this.URL = url;
this.priority = priority;
this.queueTurnstile = queueTurnstile;
}
@Override
public void run() {
System.out.println("Job: " + jobName + " Priority: " + priority);
try {
download();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void download() throws Exception {
URL url = new URL(URL);
InputStream is = url.openStream();
FileOutputStream fos = new FileOutputStream("C:\\" + jobName + ".pdf");
byte[] buffer = new byte[4096];
int bytesRead = 0;
if (this.priority == 1) {
queueTurnstile.highPriorityTaskStarts();
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
queueTurnstile.highPriorityTaskEnds();
} else {
queueTurnstile.lowPriorityTaskStarts();
while ((bytesRead = is.read(buffer)) != -1) {
while (true) {
if (!queueTurnstile.lowPriorityTaskPaused) {
fos.write(buffer, 0, bytesRead);
} else if ((bytesRead = is.read(buffer)) == -1) {
break;
}
}
}
queueTurnstile.lowPriorityTaskEnds();
}
fos.close();
is.close();
}
}
class QueueExecutor {
private int QUEUE_SIZE = 10;
private int POOL_SIZE = 5;
private ExecutorService priorityJobPoolExecutor;
private PriorityBlockingQueue<Job> priorityQueue = new PriorityBlockingQueue<Job>(
QUEUE_SIZE,
new Comparator<Job>() {
@Override
public int compare(Job o1, Job o2) {
return o1.priority - o2.priority;
}
});
public void addJob(Job job) {
priorityQueue.add(job);
}
public void executeQueue() {
priorityJobPoolExecutor = Executors.newFixedThreadPool(POOL_SIZE);
while (!priorityQueue.isEmpty()) {
try {
priorityJobPoolExecutor.execute(priorityQueue.take());
} catch (InterruptedException e) {
break;
}
}
}
}
public class QueueSchedulerMain {
QueueTurnstile queueTurnstile = new QueueTurnstile();
QueueExecutor queueExecutor = new QueueExecutor();
public static void main(String a[]) {
new QueueSchedulerMain().execute();
}
public void execute() {
String url = "http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf";
url = "http://stackoverflow.com/";
Job job1 = new Job("J1", url, 3, queueTurnstile);
Job job2 = new Job("J2", url, 1, queueTurnstile);
Job job3 = new Job("J3", url, 2, queueTurnstile);
Job job4 = new Job("J4", url, 5, queueTurnstile);
Job job5 = new Job("J5", url, 3, queueTurnstile);
Job job6 = new Job("J6", url, 1, queueTurnstile);
Job job7 = new Job("J7", url, 4, queueTurnstile);
queueExecutor.addJob(job1);
queueExecutor.addJob(job2);
queueExecutor.addJob(job3);
queueExecutor.addJob(job4);
queueExecutor.addJob(job5);
queueExecutor.executeQueue();
}
} |
package TST_teamproject.Board.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import TST_teamproject.Board.dao.BoardReplyMapper;
import TST_teamproject.Board.model.BoardReplyVo;
@Service
public class BoardReplyServiceImp implements BoardReplyService {
@Autowired
private BoardReplyMapper mapper;
@Override
public List<BoardReplyVo> boardReplyList(int tst_board_no) throws Exception {
return mapper.boardReplyList(tst_board_no);
}
@Override
public void boardReplyInsert(BoardReplyVo vo) throws Exception {
mapper.boardReplyInsert(vo);
}
@Override
public int boardReplyCount(int tst_board_no) throws Exception {
return mapper.boardReplyCount(tst_board_no);
}
@Override
public int boardReplyDelete(int tst_board_reply_no) throws Exception {
return mapper.boardReplyDelete(tst_board_reply_no);
}
}
|
package cn.tedu.shoot_wy;
import java.awt.image.BufferedImage;
public class BigAirplane extends FlyingObject implements Award{
int step;
static BufferedImage[] images = new BufferedImage[5];
static{
for (int i =0;i<images.length;i++)
images[i] = loadImage("bigplane"+i+".png");
}
public BigAirplane(){
width=69;
height=99;
x=(int)(Math.random()*(World.WIDTH+1-width));
y= -height;
step =2;
}
public BufferedImage getImage() {
if(STATE==LIFE)
return images[0];
else if(STATE==REMOVE)
return null;
else return images[0];
}
@Override
public void step() {
y+=step;
}
@Override
public int getScores() {
return 50;
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Gunter Zeilinger, Huetteldorferstr. 24/10, 1150 Vienna/Austria/Europe.
* Portions created by the Initial Developer are Copyright (C) 2002-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunterze@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package be.openclinic.archiving;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomElement;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.data.UIDDictionary;
import org.dcm4che2.data.VR;
import org.dcm4che2.io.DicomInputStream;
import org.dcm4che2.io.DicomOutputStream;
import org.dcm4che2.io.StopTagInputHandler;
import org.dcm4che2.io.TranscoderInputHandler;
import org.dcm4che2.net.Association;
import org.dcm4che2.net.CommandUtils;
import org.dcm4che2.net.ConfigurationException;
import org.dcm4che2.net.Device;
import org.dcm4che2.net.DimseRSP;
import org.dcm4che2.net.DimseRSPHandler;
import org.dcm4che2.net.NetworkApplicationEntity;
import org.dcm4che2.net.NetworkConnection;
import org.dcm4che2.net.NewThreadExecutor;
import org.dcm4che2.net.NoPresentationContextException;
import org.dcm4che2.net.PDVOutputStream;
import org.dcm4che2.net.TransferCapability;
import org.dcm4che2.net.UserIdentity;
import org.dcm4che2.net.service.StorageCommitmentService;
import org.dcm4che2.util.CloseUtils;
import org.dcm4che2.util.StringUtils;
import org.dcm4che2.util.UIDUtils;
import be.mxs.common.util.system.Debug;
/**
* @author gunter zeilinger(gunterze@gmail.com)
* @version $Revision: 14702 $ $Date:: 2011-01-14#$
* @since Oct 13, 2005
*/
public class DcmSnd extends StorageCommitmentService {
private static final int KB = 1024;
private static final int MB = KB * KB;
private static final int PEEK_LEN = 1024;
private static final String USAGE =
"dcmsnd <aet>[@<host>[:<port>]] <file>|<directory>... [Options]";
private static final String DESCRIPTION =
"\nLoad composite DICOM Object(s) from specified DICOM file(s) and send it "
+ "to the specified remote Application Entity. If a directory is specified,"
+ "DICOM Object in files under that directory and further sub-directories "
+ "are sent. If <port> is not specified, DICOM default port 104 is assumed. "
+ "If also no <host> is specified, localhost is assumed. Optionally, a "
+ "Storage Commitment Request for successfully tranferred objects is sent "
+ "to the remote Application Entity after the storage. The Storage Commitment "
+ "result is accepted on the same association or - if a local port is "
+ "specified by option -L - in a separate association initiated by the "
+ "remote Application Entity\n"
+ "OPTIONS:";
private static final String EXAMPLE =
"\nExample: dcmsnd STORESCP@localhost:11112 image.dcm -stgcmt -L DCMSND:11113 \n"
+ "=> Start listening on local port 11113 for receiving Storage Commitment "
+ "results, send DICOM object image.dcm to Application Entity STORESCP, "
+ "listening on local port 11112, and request Storage Commitment in same association.";
private static String[] TLS1 = { "TLSv1" };
private static String[] SSL3 = { "SSLv3" };
private static String[] NO_TLS1 = { "SSLv3", "SSLv2Hello" };
private static String[] NO_SSL2 = { "TLSv1", "SSLv3" };
private static String[] NO_SSL3 = { "TLSv1", "SSLv2Hello" };
private static char[] SECRET = { 's', 'e', 'c', 'r', 'e', 't' };
private static final String[] ONLY_IVLE_TS = {
UID.ImplicitVRLittleEndian
};
private static final String[] IVLE_TS = {
UID.ImplicitVRLittleEndian,
UID.ExplicitVRLittleEndian,
UID.ExplicitVRBigEndian,
};
private static final String[] EVLE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian,
UID.ExplicitVRBigEndian,
};
private static final String[] EVBE_TS = {
UID.ExplicitVRBigEndian,
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian,
};
private static final int STG_CMT_ACTION_TYPE = 1;
/** TransferSyntax: DCM4CHE URI Referenced */
private static final String DCM4CHEE_URI_REFERENCED_TS_UID =
"1.2.40.0.13.1.1.2.4.94";
private final Executor executor;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private NetworkApplicationEntity remoteStgcmtAE;
private final NetworkConnection remoteConn = new NetworkConnection();
private final NetworkConnection remoteStgcmtConn = new NetworkConnection();
private final Device device;
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private final Map<String, Set<String>> as2ts = new HashMap<String, Set<String>>();
private final ArrayList<FileInfo> files = new ArrayList<FileInfo>();
private Association assoc;
private int priority = 0;
private int transcoderBufferSize = 1024;
private int filesSent = 0;
private long totalSize = 0L;
private boolean fileref = false;
private boolean stgcmt = false;
private long shutdownDelay = 1000L;
private DicomObject stgCmtResult;
private DicomObject coerceAttrs;
private String[] suffixUID;
private String keyStoreURL = "resource:tls/test_sys_1.p12";
private char[] keyStorePassword = SECRET;
private char[] keyPassword;
private String trustStoreURL = "resource:tls/mesa_certs.jks";
private char[] trustStorePassword = SECRET;
public DcmSnd() {
this("DCMSND");
}
public DcmSnd(String name) {
device = new Device(name);
executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAssociationAcceptor(true);
ae.register(this);
ae.setAETitle(name);
}
public final void setLocalHost(String hostname) {
conn.setHostname(hostname);
}
public final void setLocalPort(int port) {
conn.setPort(port);
}
public final void setRemoteHost(String hostname) {
remoteConn.setHostname(hostname);
}
public final void setRemotePort(int port) {
remoteConn.setPort(port);
}
public final void setRemoteStgcmtHost(String hostname) {
remoteStgcmtConn.setHostname(hostname);
}
public final void setRemoteStgcmtPort(int port) {
remoteStgcmtConn.setPort(port);
}
public final void setTlsProtocol(String[] tlsProtocol) {
conn.setTlsProtocol(tlsProtocol);
}
public final void setTlsWithoutEncyrption() {
conn.setTlsWithoutEncyrption();
remoteConn.setTlsWithoutEncyrption();
remoteStgcmtConn.setTlsWithoutEncyrption();
}
public final void setTls3DES_EDE_CBC() {
conn.setTls3DES_EDE_CBC();
remoteConn.setTls3DES_EDE_CBC();
remoteStgcmtConn.setTls3DES_EDE_CBC();
}
public final void setTlsAES_128_CBC() {
conn.setTlsAES_128_CBC();
remoteConn.setTlsAES_128_CBC();
remoteStgcmtConn.setTlsAES_128_CBC();
}
public final void setTlsNeedClientAuth(boolean needClientAuth) {
conn.setTlsNeedClientAuth(needClientAuth);
}
public final void setKeyStoreURL(String url) {
keyStoreURL = url;
}
public final void setKeyStorePassword(String pw) {
keyStorePassword = pw.toCharArray();
}
public final void setKeyPassword(String pw) {
keyPassword = pw.toCharArray();
}
public final void setTrustStorePassword(String pw) {
trustStorePassword = pw.toCharArray();
}
public final void setTrustStoreURL(String url) {
trustStoreURL = url;
}
public final void setCalledAET(String called) {
remoteAE.setAETitle(called);
}
public final void setCalling(String calling) {
ae.setAETitle(calling);
}
public final void setUserIdentity(UserIdentity userIdentity) {
ae.setUserIdentity(userIdentity);
}
public final void setOfferDefaultTransferSyntaxInSeparatePresentationContext(
boolean enable) {
ae.setOfferDefaultTransferSyntaxInSeparatePresentationContext(enable);
}
public final void setSendFileRef(boolean fileref) {
this.fileref = fileref;
}
public final void setStorageCommitment(boolean stgcmt) {
this.stgcmt = stgcmt;
}
public final boolean isStorageCommitment() {
return stgcmt;
}
public final void setStgcmtCalledAET(String called) {
remoteStgcmtAE = new NetworkApplicationEntity();
remoteStgcmtAE.setInstalled(true);
remoteStgcmtAE.setAssociationAcceptor(true);
remoteStgcmtAE.setNetworkConnection(
new NetworkConnection[] { remoteStgcmtConn });
remoteStgcmtAE.setAETitle(called);
}
public final void setShutdownDelay(int shutdownDelay) {
this.shutdownDelay = shutdownDelay;
}
public final void setConnectTimeout(int connectTimeout) {
conn.setConnectTimeout(connectTimeout);
}
public final void setMaxPDULengthReceive(int maxPDULength) {
ae.setMaxPDULengthReceive(maxPDULength);
}
public final void setMaxOpsInvoked(int maxOpsInvoked) {
ae.setMaxOpsInvoked(maxOpsInvoked);
}
public final void setPackPDV(boolean packPDV) {
ae.setPackPDV(packPDV);
}
public final void setAssociationReaperPeriod(int period) {
device.setAssociationReaperPeriod(period);
}
public final void setDimseRspTimeout(int timeout) {
ae.setDimseRspTimeout(timeout);
}
public final void setPriority(int priority) {
this.priority = priority;
}
public final void setTcpNoDelay(boolean tcpNoDelay) {
conn.setTcpNoDelay(tcpNoDelay);
}
public final void setAcceptTimeout(int timeout) {
conn.setAcceptTimeout(timeout);
}
public final void setReleaseTimeout(int timeout) {
conn.setReleaseTimeout(timeout);
}
public final void setSocketCloseDelay(int timeout) {
conn.setSocketCloseDelay(timeout);
}
public final void setMaxPDULengthSend(int maxPDULength) {
ae.setMaxPDULengthSend(maxPDULength);
}
public final void setReceiveBufferSize(int bufferSize) {
conn.setReceiveBufferSize(bufferSize);
}
public final void setSendBufferSize(int bufferSize) {
conn.setSendBufferSize(bufferSize);
}
public final void setTranscoderBufferSize(int transcoderBufferSize) {
this.transcoderBufferSize = transcoderBufferSize;
}
public final int getNumberOfFilesToSend() {
return files.size();
}
public final int getNumberOfFilesSent() {
return filesSent;
}
public final long getTotalSizeSent() {
return totalSize;
}
public List<FileInfo> getFileInfos() {
return files;
}
private static CommandLine parse(String[] args) {
Options opts = new Options();
OptionBuilder.withArgName("name");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"set device name, use DCMSND by default");
opts.addOption(OptionBuilder.create("device"));
OptionBuilder.withArgName("aet[@host][:port]");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"set AET, local address and listening port of local "
+ "Application Entity, use device name and pick up any valid "
+ "local address to bind the socket by default");
opts.addOption(OptionBuilder.create("L"));
opts.addOption("ts1", false, "offer Default Transfer Syntax in " +
"separate Presentation Context. By default offered with " +
"Explicit VR Little Endian TS in one PC.");
opts.addOption("fileref", false,
"send objects without pixel data, but with a reference to " +
"the DICOM file using DCM4CHE URI Referenced Transfer Syntax " +
"to import DICOM objects on a given file system to a DCM4CHEE " +
"archive.");
OptionBuilder.withArgName("username");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"enable User Identity Negotiation with specified username and "
+ " optional passcode");
opts.addOption(OptionBuilder.create("username"));
OptionBuilder.withArgName("passcode");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"optional passcode for User Identity Negotiation, "
+ "only effective with option -username");
opts.addOption(OptionBuilder.create("passcode"));
opts.addOption("uidnegrsp", false,
"request positive User Identity Negotation response, "
+ "only effective with option -username");
OptionBuilder.withArgName("NULL|3DES|AES");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"enable TLS connection without, 3DES or AES encryption");
opts.addOption(OptionBuilder.create("tls"));
OptionGroup tlsProtocol = new OptionGroup();
tlsProtocol.addOption(new Option("tls1",
"disable the use of SSLv3 and SSLv2 for TLS connections"));
tlsProtocol.addOption(new Option("ssl3",
"disable the use of TLSv1 and SSLv2 for TLS connections"));
tlsProtocol.addOption(new Option("no_tls1",
"disable the use of TLSv1 for TLS connections"));
tlsProtocol.addOption(new Option("no_ssl3",
"disable the use of SSLv3 for TLS connections"));
tlsProtocol.addOption(new Option("no_ssl2",
"disable the use of SSLv2 for TLS connections"));
opts.addOptionGroup(tlsProtocol);
opts.addOption("noclientauth", false,
"disable client authentification for TLS");
OptionBuilder.withArgName("file|url");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path or URL of P12 or JKS keystore, resource:tls/test_sys_2.p12 by default");
opts.addOption(OptionBuilder.create("keystore"));
OptionBuilder.withArgName("password");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"password for keystore file, 'secret' by default");
opts.addOption(OptionBuilder.create("keystorepw"));
OptionBuilder.withArgName("password");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"password for accessing the key in the keystore, keystore password by default");
opts.addOption(OptionBuilder.create("keypw"));
OptionBuilder.withArgName("file|url");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path or URL of JKS truststore, resource:tls/mesa_certs.jks by default");
opts.addOption(OptionBuilder.create("truststore"));
OptionBuilder.withArgName("password");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"password for truststore file, 'secret' by default");
opts.addOption(OptionBuilder.create("truststorepw"));
OptionBuilder.withArgName("aet@host:port");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"request storage commitment of (successfully) sent objects " +
"afterwards in new association to specified remote " +
"Application Entity");
opts.addOption(OptionBuilder.create("stgcmtae"));
opts.addOption("stgcmt", false,
"request storage commitment of (successfully) sent objects " +
"afterwards in same association");
OptionBuilder.withArgName("attr=value");
OptionBuilder.hasArgs();
OptionBuilder.withValueSeparator('=');
OptionBuilder.withDescription("Replace value of specified attribute " +
"with specified value in transmitted objects. attr can be " +
"specified by name or tag value (in hex), e.g. PatientName " +
"or 00100010.");
opts.addOption(OptionBuilder.create("set"));
OptionBuilder.withArgName("sx1[:sx2[:sx3]");
OptionBuilder.hasArgs();
OptionBuilder.withValueSeparator(':');
OptionBuilder.withDescription("Suffix SOP [,Series [,Study]] " +
"Instance UID with specified value[s] in transmitted objects.");
opts.addOption(OptionBuilder.create("setuid"));
OptionBuilder.withArgName("maxops");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"maximum number of outstanding operations it may invoke " +
"asynchronously, unlimited by default.");
opts.addOption(OptionBuilder.create("async"));
opts.addOption("pdv1", false,
"send only one PDV in one P-Data-TF PDU, " +
"pack command and data PDV in one P-DATA-TF PDU by default.");
opts.addOption("tcpdelay", false,
"set TCP_NODELAY socket option to false, true by default");
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"timeout in ms for TCP connect, no timeout by default");
opts.addOption(OptionBuilder.create("connectTO"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"delay in ms for Socket close after sending A-ABORT, " +
"50ms by default");
opts.addOption(OptionBuilder.create("soclosedelay"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"delay in ms for closing the listening socket, " +
"1000ms by default");
opts.addOption(OptionBuilder.create("shutdowndelay"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"period in ms to check for outstanding DIMSE-RSP, " +
"10s by default");
opts.addOption(OptionBuilder.create("reaper"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"timeout in ms for receiving DIMSE-RSP, 10s by default");
opts.addOption(OptionBuilder.create("rspTO"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"timeout in ms for receiving A-ASSOCIATE-AC, 5s by default");
opts.addOption(OptionBuilder.create("acceptTO"));
OptionBuilder.withArgName("ms");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"timeout in ms for receiving A-RELEASE-RP, 5s by default");
opts.addOption(OptionBuilder.create("releaseTO"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"maximal length in KB of received P-DATA-TF PDUs, 16KB by default");
opts.addOption(OptionBuilder.create("rcvpdulen"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"maximal length in KB of sent P-DATA-TF PDUs, 16KB by default");
opts.addOption(OptionBuilder.create("sndpdulen"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"set SO_RCVBUF socket option to specified value in KB");
opts.addOption(OptionBuilder.create("sorcvbuf"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"set SO_SNDBUF socket option to specified value in KB");
opts.addOption(OptionBuilder.create("sosndbuf"));
OptionBuilder.withArgName("KB");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"transcoder buffer size in KB, 1KB by default");
opts.addOption(OptionBuilder.create("bufsize"));
opts.addOption("lowprior", false,
"LOW priority of the C-STORE operation, MEDIUM by default");
opts.addOption("highprior", false,
"HIGH priority of the C-STORE operation, MEDIUM by default");
opts.addOption("h", "help", false, "print this message");
opts.addOption("V", "version", false,
"print the version information and exit");
CommandLine cl = null;
try {
cl = new GnuParser().parse(opts, args);
} catch (ParseException e) {
exit("dcmsnd: " + e.getMessage());
throw new RuntimeException("unreachable");
}
if (cl.hasOption('V')) {
Package p = DcmSnd.class.getPackage();
Debug.println("dcmsnd v" + p.getImplementationVersion());
//System.exit(0);
}
if (cl.hasOption('h') || cl.getArgList().size() < 2) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
//System.exit(0);
}
return cl;
}
public static void sendTest(String aet, String host, int port, String filename){
String[] args = new String[2];
args[0]=aet+"@"+host+":"+port;
args[1]=filename;
main(args);
}
public static boolean isSendTest(String aet, String host, int port, String filename){
String[] args = new String[2];
args[0]=aet+"@"+host+":"+port;
args[1]=filename;
return dosend(args);
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
CommandLine cl = parse(args);
DcmSnd dcmsnd = new DcmSnd(cl.hasOption("device")
? cl.getOptionValue("device") : "DCMSND");
final List<String> argList = cl.getArgList();
String remoteAE = argList.get(0);
String[] calledAETAddress = split(remoteAE, '@');
dcmsnd.setCalledAET(calledAETAddress[0]);
if (calledAETAddress[1] == null) {
dcmsnd.setRemoteHost("127.0.0.1");
dcmsnd.setRemotePort(104);
} else {
String[] hostPort = split(calledAETAddress[1], ':');
dcmsnd.setRemoteHost(hostPort[0]);
dcmsnd.setRemotePort(toPort(hostPort[1]));
}
if (cl.hasOption("L")) {
String localAE = cl.getOptionValue("L");
String[] localPort = split(localAE, ':');
if (localPort[1] != null) {
dcmsnd.setLocalPort(toPort(localPort[1]));
}
String[] callingAETHost = split(localPort[0], '@');
dcmsnd.setCalling(callingAETHost[0]);
if (callingAETHost[1] != null) {
dcmsnd.setLocalHost(callingAETHost[1]);
}
}
dcmsnd.setOfferDefaultTransferSyntaxInSeparatePresentationContext(
cl.hasOption("ts1"));
dcmsnd.setSendFileRef(cl.hasOption("fileref"));
if (cl.hasOption("username")) {
String username = cl.getOptionValue("username");
UserIdentity userId;
if (cl.hasOption("passcode")) {
String passcode = cl.getOptionValue("passcode");
userId = new UserIdentity.UsernamePasscode(username,
passcode.toCharArray());
} else {
userId = new UserIdentity.Username(username);
}
userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
dcmsnd.setUserIdentity(userId);
}
dcmsnd.setStorageCommitment(cl.hasOption("stgcmt"));
String remoteStgCmtAE = null;
if (cl.hasOption("stgcmtae")) {
try {
remoteStgCmtAE = cl.getOptionValue("stgcmtae");
String[] aet_hostport = split(remoteStgCmtAE, '@');
String[] host_port = split(aet_hostport[1], ':');
dcmsnd.setStgcmtCalledAET(aet_hostport[0]);
dcmsnd.setRemoteStgcmtHost(host_port[0]);
dcmsnd.setRemoteStgcmtPort(toPort(host_port[1]));
} catch (Exception e) {
exit("illegal argument of option -stgcmtae");
}
}
if (cl.hasOption("set")) {
String[] vals = cl.getOptionValues("set");
for (int i = 0; i < vals.length; i++, i++) {
dcmsnd.addCoerceAttr(Tag.toTag(vals[i]), vals[i+1]);
}
}
if (cl.hasOption("setuid")) {
dcmsnd.setSuffixUID(cl.getOptionValues("setuid"));
}
if (cl.hasOption("connectTO"))
dcmsnd.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
"illegal argument of option -connectTO", 1,
Integer.MAX_VALUE));
if (cl.hasOption("reaper"))
dcmsnd.setAssociationReaperPeriod(
parseInt(cl.getOptionValue("reaper"),
"illegal argument of option -reaper",
1, Integer.MAX_VALUE));
if (cl.hasOption("rspTO"))
dcmsnd.setDimseRspTimeout(parseInt(cl.getOptionValue("rspTO"),
"illegal argument of option -rspTO",
1, Integer.MAX_VALUE));
if (cl.hasOption("acceptTO"))
dcmsnd.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"),
"illegal argument of option -acceptTO",
1, Integer.MAX_VALUE));
if (cl.hasOption("releaseTO"))
dcmsnd.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
"illegal argument of option -releaseTO",
1, Integer.MAX_VALUE));
if (cl.hasOption("soclosedelay"))
dcmsnd.setSocketCloseDelay(
parseInt(cl.getOptionValue("soclosedelay"),
"illegal argument of option -soclosedelay", 1, 10000));
if (cl.hasOption("shutdowndelay"))
dcmsnd.setShutdownDelay(
parseInt(cl.getOptionValue("shutdowndelay"),
"illegal argument of option -shutdowndelay", 1, 10000));
if (cl.hasOption("rcvpdulen"))
dcmsnd.setMaxPDULengthReceive(
parseInt(cl.getOptionValue("rcvpdulen"),
"illegal argument of option -rcvpdulen", 1, 10000) * KB);
if (cl.hasOption("sndpdulen"))
dcmsnd.setMaxPDULengthSend(parseInt(cl.getOptionValue("sndpdulen"),
"illegal argument of option -sndpdulen", 1, 10000) * KB);
if (cl.hasOption("sosndbuf"))
dcmsnd.setSendBufferSize(parseInt(cl.getOptionValue("sosndbuf"),
"illegal argument of option -sosndbuf", 1, 10000) * KB);
if (cl.hasOption("sorcvbuf"))
dcmsnd.setReceiveBufferSize(parseInt(cl.getOptionValue("sorcvbuf"),
"illegal argument of option -sorcvbuf", 1, 10000) * KB);
if (cl.hasOption("bufsize"))
dcmsnd.setTranscoderBufferSize(
parseInt(cl.getOptionValue("bufsize"),
"illegal argument of option -bufsize", 1, 10000) * KB);
dcmsnd.setPackPDV(!cl.hasOption("pdv1"));
dcmsnd.setTcpNoDelay(!cl.hasOption("tcpdelay"));
if (cl.hasOption("async"))
dcmsnd.setMaxOpsInvoked(parseInt(cl.getOptionValue("async"),
"illegal argument of option -async", 0, 0xffff));
if (cl.hasOption("lowprior"))
dcmsnd.setPriority(CommandUtils.LOW);
if (cl.hasOption("highprior"))
dcmsnd.setPriority(CommandUtils.HIGH);
Debug.println("Scanning files to send");
long t1 = System.currentTimeMillis();
for (int i = 1, n = argList.size(); i < n; ++i)
dcmsnd.addFile(new File(argList.get(i)));
long t2 = System.currentTimeMillis();
if (dcmsnd.getNumberOfFilesToSend() == 0) {
//System.exit(2);
}
Debug.println("\nScanned " + dcmsnd.getNumberOfFilesToSend()
+ " files in " + ((t2 - t1) / 1000F) + "s (="
+ ((t2 - t1) / dcmsnd.getNumberOfFilesToSend()) + "ms/file)");
dcmsnd.configureTransferCapability();
if (cl.hasOption("tls")) {
String cipher = cl.getOptionValue("tls");
if ("NULL".equalsIgnoreCase(cipher)) {
dcmsnd.setTlsWithoutEncyrption();
} else if ("3DES".equalsIgnoreCase(cipher)) {
dcmsnd.setTls3DES_EDE_CBC();
} else if ("AES".equalsIgnoreCase(cipher)) {
dcmsnd.setTlsAES_128_CBC();
} else {
exit("Invalid parameter for option -tls: " + cipher);
}
if (cl.hasOption("tls1")) {
dcmsnd.setTlsProtocol(TLS1);
} else if (cl.hasOption("ssl3")) {
dcmsnd.setTlsProtocol(SSL3);
} else if (cl.hasOption("no_tls1")) {
dcmsnd.setTlsProtocol(NO_TLS1);
} else if (cl.hasOption("no_ssl3")) {
dcmsnd.setTlsProtocol(NO_SSL3);
} else if (cl.hasOption("no_ssl2")) {
dcmsnd.setTlsProtocol(NO_SSL2);
}
dcmsnd.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));
if (cl.hasOption("keystore")) {
dcmsnd.setKeyStoreURL(cl.getOptionValue("keystore"));
}
if (cl.hasOption("keystorepw")) {
dcmsnd.setKeyStorePassword(
cl.getOptionValue("keystorepw"));
}
if (cl.hasOption("keypw")) {
dcmsnd.setKeyPassword(cl.getOptionValue("keypw"));
}
if (cl.hasOption("truststore")) {
dcmsnd.setTrustStoreURL(
cl.getOptionValue("truststore"));
}
if (cl.hasOption("truststorepw")) {
dcmsnd.setTrustStorePassword(
cl.getOptionValue("truststorepw"));
}
try {
dcmsnd.initTLS();
} catch (Exception e) {
System.err.println("ERROR: Failed to initialize TLS context:"
+ e.getMessage());
//System.exit(2);
}
}
try {
dcmsnd.start();
} catch (Exception e) {
System.err.println("ERROR: Failed to start server for receiving " +
"Storage Commitment results:" + e.getMessage());
//System.exit(2);
}
try {
t1 = System.currentTimeMillis();
try {
dcmsnd.open();
} catch (Exception e) {
System.err.println("ERROR: Failed to establish association:"
+ e.getMessage());
//System.exit(2);
}
t2 = System.currentTimeMillis();
Debug.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
t1 = System.currentTimeMillis();
dcmsnd.send();
t2 = System.currentTimeMillis();
prompt(dcmsnd, (t2 - t1) / 1000F);
if (dcmsnd.isStorageCommitment()) {
t1 = System.currentTimeMillis();
if (dcmsnd.commit()) {
t2 = System.currentTimeMillis();
Debug.println("Request Storage Commitment from "
+ remoteAE + " in " + ((t2 - t1) / 1000F) + "s");
Debug.println("Waiting for Storage Commitment Result..");
try {
DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
t1 = System.currentTimeMillis();
promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
} catch (InterruptedException e) {
System.err.println("ERROR:" + e.getMessage());
}
}
}
dcmsnd.close();
Debug.println("Released connection to " + remoteAE);
if (remoteStgCmtAE != null) {
t1 = System.currentTimeMillis();
try {
dcmsnd.openToStgcmtAE();
} catch (Exception e) {
System.err.println("ERROR: Failed to establish association:"
+ e.getMessage());
//System.exit(2);
}
t2 = System.currentTimeMillis();
Debug.println("Connected to " + remoteStgCmtAE + " in "
+ ((t2 - t1) / 1000F) + "s");
t1 = System.currentTimeMillis();
if (dcmsnd.commit()) {
t2 = System.currentTimeMillis();
Debug.println("Request Storage Commitment from "
+ remoteStgCmtAE + " in " + ((t2 - t1) / 1000F) + "s");
Debug.println("Waiting for Storage Commitment Result..");
try {
DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
t1 = System.currentTimeMillis();
promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
} catch (InterruptedException e) {
System.err.println("ERROR:" + e.getMessage());
}
}
dcmsnd.close();
Debug.println("Released connection to " + remoteStgCmtAE);
}
} finally {
dcmsnd.stop();
}
}
@SuppressWarnings("unchecked")
public static boolean dosend(String[] args) {
boolean bOk=false;
CommandLine cl = parse(args);
DcmSnd dcmsnd = new DcmSnd(cl.hasOption("device")
? cl.getOptionValue("device") : "DCMSND");
final List<String> argList = cl.getArgList();
String remoteAE = argList.get(0);
String[] calledAETAddress = split(remoteAE, '@');
dcmsnd.setCalledAET(calledAETAddress[0]);
if (calledAETAddress[1] == null) {
dcmsnd.setRemoteHost("127.0.0.1");
dcmsnd.setRemotePort(104);
} else {
String[] hostPort = split(calledAETAddress[1], ':');
dcmsnd.setRemoteHost(hostPort[0]);
dcmsnd.setRemotePort(toPort(hostPort[1]));
}
if (cl.hasOption("L")) {
String localAE = cl.getOptionValue("L");
String[] localPort = split(localAE, ':');
if (localPort[1] != null) {
dcmsnd.setLocalPort(toPort(localPort[1]));
}
String[] callingAETHost = split(localPort[0], '@');
dcmsnd.setCalling(callingAETHost[0]);
if (callingAETHost[1] != null) {
dcmsnd.setLocalHost(callingAETHost[1]);
}
}
dcmsnd.setOfferDefaultTransferSyntaxInSeparatePresentationContext(
cl.hasOption("ts1"));
dcmsnd.setSendFileRef(cl.hasOption("fileref"));
if (cl.hasOption("username")) {
String username = cl.getOptionValue("username");
UserIdentity userId;
if (cl.hasOption("passcode")) {
String passcode = cl.getOptionValue("passcode");
userId = new UserIdentity.UsernamePasscode(username,
passcode.toCharArray());
} else {
userId = new UserIdentity.Username(username);
}
userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
dcmsnd.setUserIdentity(userId);
}
dcmsnd.setStorageCommitment(cl.hasOption("stgcmt"));
String remoteStgCmtAE = null;
if (cl.hasOption("stgcmtae")) {
try {
remoteStgCmtAE = cl.getOptionValue("stgcmtae");
String[] aet_hostport = split(remoteStgCmtAE, '@');
String[] host_port = split(aet_hostport[1], ':');
dcmsnd.setStgcmtCalledAET(aet_hostport[0]);
dcmsnd.setRemoteStgcmtHost(host_port[0]);
dcmsnd.setRemoteStgcmtPort(toPort(host_port[1]));
} catch (Exception e) {
exit("illegal argument of option -stgcmtae");
}
}
if (cl.hasOption("set")) {
String[] vals = cl.getOptionValues("set");
for (int i = 0; i < vals.length; i++, i++) {
dcmsnd.addCoerceAttr(Tag.toTag(vals[i]), vals[i+1]);
}
}
if (cl.hasOption("setuid")) {
dcmsnd.setSuffixUID(cl.getOptionValues("setuid"));
}
if (cl.hasOption("connectTO"))
dcmsnd.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
"illegal argument of option -connectTO", 1,
Integer.MAX_VALUE));
if (cl.hasOption("reaper"))
dcmsnd.setAssociationReaperPeriod(
parseInt(cl.getOptionValue("reaper"),
"illegal argument of option -reaper",
1, Integer.MAX_VALUE));
if (cl.hasOption("rspTO"))
dcmsnd.setDimseRspTimeout(parseInt(cl.getOptionValue("rspTO"),
"illegal argument of option -rspTO",
1, Integer.MAX_VALUE));
if (cl.hasOption("acceptTO"))
dcmsnd.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"),
"illegal argument of option -acceptTO",
1, Integer.MAX_VALUE));
if (cl.hasOption("releaseTO"))
dcmsnd.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
"illegal argument of option -releaseTO",
1, Integer.MAX_VALUE));
if (cl.hasOption("soclosedelay"))
dcmsnd.setSocketCloseDelay(
parseInt(cl.getOptionValue("soclosedelay"),
"illegal argument of option -soclosedelay", 1, 10000));
if (cl.hasOption("shutdowndelay"))
dcmsnd.setShutdownDelay(
parseInt(cl.getOptionValue("shutdowndelay"),
"illegal argument of option -shutdowndelay", 1, 10000));
if (cl.hasOption("rcvpdulen"))
dcmsnd.setMaxPDULengthReceive(
parseInt(cl.getOptionValue("rcvpdulen"),
"illegal argument of option -rcvpdulen", 1, 10000) * KB);
if (cl.hasOption("sndpdulen"))
dcmsnd.setMaxPDULengthSend(parseInt(cl.getOptionValue("sndpdulen"),
"illegal argument of option -sndpdulen", 1, 10000) * KB);
if (cl.hasOption("sosndbuf"))
dcmsnd.setSendBufferSize(parseInt(cl.getOptionValue("sosndbuf"),
"illegal argument of option -sosndbuf", 1, 10000) * KB);
if (cl.hasOption("sorcvbuf"))
dcmsnd.setReceiveBufferSize(parseInt(cl.getOptionValue("sorcvbuf"),
"illegal argument of option -sorcvbuf", 1, 10000) * KB);
if (cl.hasOption("bufsize"))
dcmsnd.setTranscoderBufferSize(
parseInt(cl.getOptionValue("bufsize"),
"illegal argument of option -bufsize", 1, 10000) * KB);
dcmsnd.setPackPDV(!cl.hasOption("pdv1"));
dcmsnd.setTcpNoDelay(!cl.hasOption("tcpdelay"));
if (cl.hasOption("async"))
dcmsnd.setMaxOpsInvoked(parseInt(cl.getOptionValue("async"),
"illegal argument of option -async", 0, 0xffff));
if (cl.hasOption("lowprior"))
dcmsnd.setPriority(CommandUtils.LOW);
if (cl.hasOption("highprior"))
dcmsnd.setPriority(CommandUtils.HIGH);
Debug.println("Scanning files to send");
long t1 = System.currentTimeMillis();
for (int i = 1, n = argList.size(); i < n; ++i)
dcmsnd.addFile(new File(argList.get(i)));
long t2 = System.currentTimeMillis();
if (dcmsnd.getNumberOfFilesToSend() == 0) {
//System.exit(2);
}
Debug.println("\nScanned " + dcmsnd.getNumberOfFilesToSend()
+ " files in " + ((t2 - t1) / 1000F) + "s (="
+ ((t2 - t1) / dcmsnd.getNumberOfFilesToSend()) + "ms/file)");
dcmsnd.configureTransferCapability();
if (cl.hasOption("tls")) {
String cipher = cl.getOptionValue("tls");
if ("NULL".equalsIgnoreCase(cipher)) {
dcmsnd.setTlsWithoutEncyrption();
} else if ("3DES".equalsIgnoreCase(cipher)) {
dcmsnd.setTls3DES_EDE_CBC();
} else if ("AES".equalsIgnoreCase(cipher)) {
dcmsnd.setTlsAES_128_CBC();
} else {
exit("Invalid parameter for option -tls: " + cipher);
}
if (cl.hasOption("tls1")) {
dcmsnd.setTlsProtocol(TLS1);
} else if (cl.hasOption("ssl3")) {
dcmsnd.setTlsProtocol(SSL3);
} else if (cl.hasOption("no_tls1")) {
dcmsnd.setTlsProtocol(NO_TLS1);
} else if (cl.hasOption("no_ssl3")) {
dcmsnd.setTlsProtocol(NO_SSL3);
} else if (cl.hasOption("no_ssl2")) {
dcmsnd.setTlsProtocol(NO_SSL2);
}
dcmsnd.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));
if (cl.hasOption("keystore")) {
dcmsnd.setKeyStoreURL(cl.getOptionValue("keystore"));
}
if (cl.hasOption("keystorepw")) {
dcmsnd.setKeyStorePassword(
cl.getOptionValue("keystorepw"));
}
if (cl.hasOption("keypw")) {
dcmsnd.setKeyPassword(cl.getOptionValue("keypw"));
}
if (cl.hasOption("truststore")) {
dcmsnd.setTrustStoreURL(
cl.getOptionValue("truststore"));
}
if (cl.hasOption("truststorepw")) {
dcmsnd.setTrustStorePassword(
cl.getOptionValue("truststorepw"));
}
try {
dcmsnd.initTLS();
} catch (Exception e) {
System.err.println("ERROR: Failed to initialize TLS context:"
+ e.getMessage());
//System.exit(2);
}
}
try {
dcmsnd.start();
} catch (Exception e) {
System.err.println("ERROR: Failed to start server for receiving " +
"Storage Commitment results:" + e.getMessage());
//System.exit(2);
}
try {
t1 = System.currentTimeMillis();
try {
dcmsnd.open();
} catch (Exception e) {
System.err.println("ERROR: Failed to establish association:"
+ e.getMessage());
//System.exit(2);
}
t2 = System.currentTimeMillis();
Debug.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
t1 = System.currentTimeMillis();
if(dcmsnd.isSend()) {
t2 = System.currentTimeMillis();
prompt(dcmsnd, (t2 - t1) / 1000F);
if (dcmsnd.isStorageCommitment()) {
t1 = System.currentTimeMillis();
if (dcmsnd.commit()) {
t2 = System.currentTimeMillis();
Debug.println("Request Storage Commitment from "
+ remoteAE + " in " + ((t2 - t1) / 1000F) + "s");
Debug.println("Waiting for Storage Commitment Result..");
try {
DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
t1 = System.currentTimeMillis();
promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
} catch (InterruptedException e) {
System.err.println("ERROR:" + e.getMessage());
}
}
}
dcmsnd.close();
Debug.println("Released connection to " + remoteAE);
if (remoteStgCmtAE != null) {
t1 = System.currentTimeMillis();
try {
dcmsnd.openToStgcmtAE();
} catch (Exception e) {
System.err.println("ERROR: Failed to establish association:"
+ e.getMessage());
//System.exit(2);
}
t2 = System.currentTimeMillis();
Debug.println("Connected to " + remoteStgCmtAE + " in "
+ ((t2 - t1) / 1000F) + "s");
t1 = System.currentTimeMillis();
if (dcmsnd.commit()) {
t2 = System.currentTimeMillis();
Debug.println("Request Storage Commitment from "
+ remoteStgCmtAE + " in " + ((t2 - t1) / 1000F) + "s");
Debug.println("Waiting for Storage Commitment Result..");
try {
DicomObject cmtrslt = dcmsnd.waitForStgCmtResult();
t1 = System.currentTimeMillis();
promptStgCmt(cmtrslt, ((t1 - t2) / 1000F));
} catch (InterruptedException e) {
System.err.println("ERROR:" + e.getMessage());
}
}
dcmsnd.close();
Debug.println("Released connection to " + remoteStgCmtAE);
}
bOk=true;
}
} finally {
dcmsnd.stop();
}
return bOk;
}
public void addCoerceAttr(int tag, String val) {
if (coerceAttrs == null)
coerceAttrs = new BasicDicomObject();
if (val.length() == 0)
coerceAttrs.putNull(tag, null);
else
coerceAttrs.putString(tag, null, val);
}
public void setSuffixUID(String[] suffix) {
if (suffix.length > 3)
throw new IllegalArgumentException(
"suffix.length: " + suffix.length);
this.suffixUID = suffix.length > 0 ? suffix.clone() : null;
}
protected static void promptStgCmt(DicomObject cmtrslt, float seconds) {
Debug.println("Received Storage Commitment Result after "
+ seconds + "s:");
DicomElement refSOPSq = cmtrslt.get(Tag.ReferencedSOPSequence);
Debug.print(refSOPSq.countItems());
Debug.println(" successful");
DicomElement failedSOPSq = cmtrslt.get(Tag.FailedSOPSequence);
if (failedSOPSq != null) {
Debug.print(failedSOPSq.countItems());
Debug.println(" FAILED!");
}
}
protected synchronized DicomObject waitForStgCmtResult() throws InterruptedException {
while (stgCmtResult == null) wait();
return stgCmtResult;
}
protected static void prompt(DcmSnd dcmsnd, float seconds) {
Debug.print("\nSent ");
Debug.print(dcmsnd.getNumberOfFilesSent());
Debug.print(" objects (=");
promptBytes(dcmsnd.getTotalSizeSent());
Debug.print(") in ");
Debug.print(seconds);
Debug.print("s (=");
promptBytes(dcmsnd.getTotalSizeSent() / seconds);
Debug.println("/s)");
}
private static void promptBytes(float totalSizeSent) {
if (totalSizeSent > MB) {
Debug.print(totalSizeSent / MB);
Debug.print("MB");
} else {
Debug.print(totalSizeSent / KB);
Debug.print("KB");
}
}
private static int toPort(String port) {
return port != null ? parseInt(port, "illegal port number", 1, 0xffff)
: 104;
}
private static String[] split(String s, char delim) {
String[] s2 = { s, null };
int pos = s.indexOf(delim);
if (pos != -1) {
s2[0] = s.substring(0, pos);
s2[1] = s.substring(pos + 1);
}
return s2;
}
private static void exit(String msg) {
System.err.println(msg);
System.err.println("Try 'dcmsnd -h' for more information.");
//System.exit(1);
}
private static int parseInt(String s, String errPrompt, int min, int max) {
try {
int i = Integer.parseInt(s);
if (i >= min && i <= max)
return i;
} catch (NumberFormatException e) {
// parameter is not a valid integer; fall through to exit
}
exit(errPrompt);
throw new RuntimeException();
}
public void addFile(File f) {
if (f.isDirectory()) {
File[] fs = f.listFiles();
if (fs == null || fs.length == 0)
return;
for (int i = 0; i < fs.length; i++)
addFile(fs[i]);
return;
}
if(f.isHidden())
return;
FileInfo info = new FileInfo(f);
DicomObject dcmObj = new BasicDicomObject();
DicomInputStream in = null;
try {
in = new DicomInputStream(f);
in.setHandler(new StopTagInputHandler(Tag.StudyDate));
in.readDicomObject(dcmObj, PEEK_LEN);
info.tsuid = in.getTransferSyntax().uid();
info.fmiEndPos = in.getEndOfFileMetaInfoPosition();
} catch (IOException e) {
e.printStackTrace();
System.err.println("WARNING: Failed to parse " + f + " - skipped.");
Debug.print('F');
return;
} finally {
CloseUtils.safeClose(in);
}
info.cuid = dcmObj.getString(Tag.MediaStorageSOPClassUID,
dcmObj.getString(Tag.SOPClassUID));
if (info.cuid == null) {
System.err.println("WARNING: Missing SOP Class UID in " + f
+ " - skipped.");
Debug.print('F');
return;
}
info.iuid = dcmObj.getString(Tag.MediaStorageSOPInstanceUID,
dcmObj.getString(Tag.SOPInstanceUID));
if (info.iuid == null) {
System.err.println("WARNING: Missing SOP Instance UID in " + f
+ " - skipped.");
Debug.print('F');
return;
}
if (suffixUID != null)
info.iuid = info.iuid + suffixUID[0];
addTransferCapability(info.cuid, info.tsuid);
files.add(info);
Debug.print('.');
}
public void addTransferCapability(String cuid, String tsuid) {
Set<String> ts = as2ts.get(cuid);
if (fileref) {
if (ts == null) {
as2ts.put(cuid,
Collections.singleton(DCM4CHEE_URI_REFERENCED_TS_UID));
}
} else {
if (ts == null) {
ts = new HashSet<String>();
ts.add(UID.ImplicitVRLittleEndian);
as2ts.put(cuid, ts);
}
ts.add(tsuid);
}
}
public void configureTransferCapability() {
int off = stgcmt || remoteStgcmtAE != null ? 1 : 0;
TransferCapability[] tc = new TransferCapability[off + as2ts.size()];
if (off > 0) {
tc[0] = new TransferCapability(
UID.StorageCommitmentPushModelSOPClass,
ONLY_IVLE_TS,
TransferCapability.SCU);
}
Iterator<Map.Entry<String, Set<String>>> iter = as2ts.entrySet().iterator();
for (int i = off; i < tc.length; i++) {
Map.Entry<String, Set<String>> e = iter.next();
String cuid = e.getKey();
Set<String> ts = e.getValue();
tc[i] = new TransferCapability(cuid,
ts.toArray(new String[ts.size()]),
TransferCapability.SCU);
}
ae.setTransferCapability(tc);
}
public void start() throws IOException {
if (conn.isListening()) {
conn.bind(executor );
Debug.println("Start Server listening on port " + conn.getPort());
}
}
public void stop() {
if (conn.isListening()) {
try {
Thread.sleep(shutdownDelay);
} catch (InterruptedException e) {
// Should not happen
e.printStackTrace();
}
conn.unbind();
}
}
public void open() throws IOException, ConfigurationException,
InterruptedException {
assoc = ae.connect(remoteAE, executor);
}
public void openToStgcmtAE() throws IOException, ConfigurationException,
InterruptedException {
assoc = ae.connect(remoteStgcmtAE, executor);
}
public void send() {
for (int i = 0, n = files.size(); i < n; ++i) {
FileInfo info = files.get(i);
TransferCapability tc = assoc.getTransferCapabilityAsSCU(info.cuid);
if (tc == null) {
Debug.println(UIDDictionary.getDictionary().prompt(
info.cuid)
+ " not supported by " + remoteAE.getAETitle());
Debug.println("skip file " + info.f);
continue;
}
String tsuid = selectTransferSyntax(tc.getTransferSyntax(),
fileref ? DCM4CHEE_URI_REFERENCED_TS_UID : info.tsuid);
if (tsuid == null) {
Debug.println();
Debug.println(UIDDictionary.getDictionary().prompt(
info.cuid)
+ " with "
+ UIDDictionary.getDictionary().prompt(
fileref ? DCM4CHEE_URI_REFERENCED_TS_UID
: info.tsuid)
+ " not supported by " + remoteAE.getAETitle());
Debug.println("skip file " + info.f);
continue;
}
try {
DimseRSPHandler rspHandler = new DimseRSPHandler() {
@Override
public void onDimseRSP(Association as, DicomObject cmd,
DicomObject data) {
DcmSnd.this.onDimseRSP(cmd);
}
};
assoc.cstore(info.cuid, info.iuid, priority,
new DataWriter(info), tsuid, rspHandler);
} catch (NoPresentationContextException e) {
System.err.println("WARNING: " + e.getMessage()
+ " - cannot send " + info.f);
Debug.print('F');
} catch (IOException e) {
e.printStackTrace();
System.err.println("ERROR: Failed to send - " + info.f + ": "
+ e.getMessage());
Debug.print('F');
} catch (InterruptedException e) {
// should not happen
e.printStackTrace();
}
}
try {
assoc.waitForDimseRSP();
} catch (InterruptedException e) {
// should not happen
e.printStackTrace();
}
}
public boolean isSend() {
boolean bOk=false;
for (int i = 0, n = files.size(); i < n; ++i) {
FileInfo info = files.get(i);
TransferCapability tc = assoc.getTransferCapabilityAsSCU(info.cuid);
if (tc == null) {
Debug.println(UIDDictionary.getDictionary().prompt(
info.cuid)
+ " not supported by " + remoteAE.getAETitle());
Debug.println("skip file " + info.f);
continue;
}
String tsuid = selectTransferSyntax(tc.getTransferSyntax(),
fileref ? DCM4CHEE_URI_REFERENCED_TS_UID : info.tsuid);
if (tsuid == null) {
Debug.println();
Debug.println(UIDDictionary.getDictionary().prompt(
info.cuid)
+ " with "
+ UIDDictionary.getDictionary().prompt(
fileref ? DCM4CHEE_URI_REFERENCED_TS_UID
: info.tsuid)
+ " not supported by " + remoteAE.getAETitle());
Debug.println("skip file " + info.f);
continue;
}
try {
DimseRSPHandler rspHandler = new DimseRSPHandler() {
@Override
public void onDimseRSP(Association as, DicomObject cmd,
DicomObject data) {
DcmSnd.this.onDimseRSP(cmd);
}
};
assoc.cstore(info.cuid, info.iuid, priority,
new DataWriter(info), tsuid, rspHandler);
bOk=true;
} catch (NoPresentationContextException e) {
System.err.println("WARNING: " + e.getMessage()
+ " - cannot send " + info.f);
Debug.print('F');
} catch (IOException e) {
e.printStackTrace();
System.err.println("ERROR: Failed to send - " + info.f + ": "
+ e.getMessage());
Debug.print('F');
} catch (InterruptedException e) {
// should not happen
e.printStackTrace();
}
}
try {
assoc.waitForDimseRSP();
} catch (InterruptedException e) {
// should not happen
e.printStackTrace();
}
return bOk;
}
public boolean commit() {
DicomObject actionInfo = new BasicDicomObject();
actionInfo.putString(Tag.TransactionUID, VR.UI, UIDUtils.createUID());
DicomElement refSOPSq = actionInfo.putSequence(Tag.ReferencedSOPSequence);
for (int i = 0, n = files.size(); i < n; ++i) {
FileInfo info = files.get(i);
if (info.transferred) {
BasicDicomObject refSOP = new BasicDicomObject();
refSOP.putString(Tag.ReferencedSOPClassUID, VR.UI, info.cuid);
refSOP.putString(Tag.ReferencedSOPInstanceUID, VR.UI, info.iuid);
refSOPSq.addDicomObject(refSOP);
}
}
try {
stgCmtResult = null;
DimseRSP rsp = assoc.naction(UID.StorageCommitmentPushModelSOPClass,
UID.StorageCommitmentPushModelSOPInstance, STG_CMT_ACTION_TYPE,
actionInfo, UID.ImplicitVRLittleEndian);
rsp.next();
DicomObject cmd = rsp.getCommand();
int status = cmd.getInt(Tag.Status);
if (status == 0) {
return true;
}
System.err.println(
"WARNING: Storage Commitment request failed with status: "
+ StringUtils.shortToHex(status) + "H");
System.err.println(cmd.toString());
} catch (NoPresentationContextException e) {
System.err.println("WARNING: " + e.getMessage()
+ " - cannot request Storage Commitment");
} catch (IOException e) {
e.printStackTrace();
System.err.println(
"ERROR: Failed to send Storage Commitment request: "
+ e.getMessage());
} catch (InterruptedException e) {
// should not happen
e.printStackTrace();
}
return false;
}
private String selectTransferSyntax(String[] available, String tsuid) {
if (tsuid.equals(UID.ImplicitVRLittleEndian))
return selectTransferSyntax(available, IVLE_TS);
if (tsuid.equals(UID.ExplicitVRLittleEndian))
return selectTransferSyntax(available, EVLE_TS);
if (tsuid.equals(UID.ExplicitVRBigEndian))
return selectTransferSyntax(available, EVBE_TS);
for (int j = 0; j < available.length; j++)
if (available[j].equals(tsuid))
return tsuid;
return null;
}
private String selectTransferSyntax(String[] available, String[] tsuids) {
for (int i = 0; i < tsuids.length; i++)
for (int j = 0; j < available.length; j++)
if (available[j].equals(tsuids[i]))
return available[j];
return null;
}
public void close() {
try {
assoc.release(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static final class FileInfo {
File f;
String cuid;
String iuid;
String tsuid;
long fmiEndPos;
long length;
boolean transferred;
int status;
public FileInfo(File f) {
this.f = f;
this.length = f.length();
}
}
private class DataWriter implements org.dcm4che2.net.DataWriter {
private FileInfo info;
public DataWriter(FileInfo info) {
this.info = info;
}
public void writeTo(PDVOutputStream out, String tsuid)
throws IOException {
if (coerceAttrs != null || suffixUID != null) {
DicomObject attrs;
DicomInputStream dis = new DicomInputStream(info.f);
try {
dis.setHandler(new StopTagInputHandler(Tag.PixelData));
attrs = dis.readDicomObject();
suffixUIDs(attrs);
coerceAttrs(attrs);
DicomOutputStream dos = new DicomOutputStream(out);
dos.writeDataset(attrs, tsuid);
if (dis.tag() >= Tag.PixelData) {
copyPixelData(dis, dos, out);
// copy attrs after PixelData
dis.setHandler(dis);
attrs = dis.readDicomObject();
dos.writeDataset(attrs, tsuid);
}
} finally {
dis.close();
}
} else if (tsuid.equals(info.tsuid)) {
FileInputStream fis = new FileInputStream(info.f);
try {
long skip = info.fmiEndPos;
while (skip > 0)
skip -= fis.skip(skip);
out.copyFrom(fis);
} finally {
fis.close();
}
} else if (tsuid.equals(DCM4CHEE_URI_REFERENCED_TS_UID)) {
DicomObject attrs;
DicomInputStream dis = new DicomInputStream(info.f);
try {
dis.setHandler(new StopTagInputHandler(Tag.PixelData));
attrs = dis.readDicomObject();
} finally {
dis.close();
}
DicomOutputStream dos = new DicomOutputStream(out);
attrs.putString(Tag.RetrieveURI, VR.UT, info.f.toURI().toString());
dos.writeDataset(attrs, tsuid);
} else {
DicomInputStream dis = new DicomInputStream(info.f);
try {
DicomOutputStream dos = new DicomOutputStream(out);
dos.setTransferSyntax(tsuid);
TranscoderInputHandler h = new TranscoderInputHandler(dos,
transcoderBufferSize);
dis.setHandler(h);
dis.readDicomObject();
} finally {
dis.close();
}
}
}
}
private void suffixUIDs(DicomObject attrs) {
if (suffixUID != null) {
int[] uidTags = { Tag.SOPInstanceUID,
Tag.SeriesInstanceUID, Tag.StudyInstanceUID };
for (int i = 0; i < suffixUID.length; i++)
attrs.putString(uidTags[i], VR.UI,
attrs.getString(uidTags[i]) + suffixUID[i]);
}
}
private void coerceAttrs(DicomObject attrs) {
if (coerceAttrs != null)
coerceAttrs.copyTo(attrs);
}
private void copyPixelData(DicomInputStream dis, DicomOutputStream dos,
PDVOutputStream out) throws IOException {
int vallen = dis.valueLength();
dos.writeHeader(dis.tag(), dis.vr(), vallen);
if (vallen == -1) {
int tag;
do {
tag = dis.readHeader();
vallen = dis.valueLength();
dos.writeHeader(tag, null, vallen);
out.copyFrom(dis, vallen);
} while (tag == Tag.Item);
} else {
out.copyFrom(dis, vallen);
}
}
private void promptErrRSP(String prefix, int status, FileInfo info,
DicomObject cmd) {
System.err.println(prefix + StringUtils.shortToHex(status) + "H for "
+ info.f + ", cuid=" + info.cuid + ", tsuid=" + info.tsuid);
System.err.println(cmd.toString());
}
private void onDimseRSP(DicomObject cmd) {
int status = cmd.getInt(Tag.Status);
int msgId = cmd.getInt(Tag.MessageIDBeingRespondedTo);
FileInfo info = files.get(msgId - 1);
info.status = status;
switch (status) {
case 0:
info.transferred = true;
totalSize += info.length;
++filesSent;
Debug.print('.');
break;
case 0xB000:
case 0xB006:
case 0xB007:
info.transferred = true;
totalSize += info.length;
++filesSent;
promptErrRSP("WARNING: Received RSP with Status ", status, info,
cmd);
Debug.print('W');
break;
default:
promptErrRSP("ERROR: Received RSP with Status ", status, info, cmd);
Debug.print('F');
}
}
@Override
protected synchronized void onNEventReportRSP(Association as, int pcid,
DicomObject rq, DicomObject info, DicomObject rsp) {
stgCmtResult = info;
notifyAll();
}
public void initTLS() throws GeneralSecurityException, IOException {
KeyStore keyStore = loadKeyStore(keyStoreURL, keyStorePassword);
KeyStore trustStore = loadKeyStore(trustStoreURL, trustStorePassword);
device.initTLS(keyStore,
keyPassword != null ? keyPassword : keyStorePassword,
trustStore);
}
private static KeyStore loadKeyStore(String url, char[] password)
throws GeneralSecurityException, IOException {
KeyStore key = KeyStore.getInstance(toKeyStoreType(url));
InputStream in = openFileOrURL(url);
try {
key.load(in, password);
} finally {
in.close();
}
return key;
}
private static InputStream openFileOrURL(String url) throws IOException {
if (url.startsWith("resource:")) {
return DcmSnd.class.getClassLoader().getResourceAsStream(
url.substring(9));
}
try {
return new URL(url).openStream();
} catch (MalformedURLException e) {
return new FileInputStream(url);
}
}
private static String toKeyStoreType(String fname) {
return fname.endsWith(".p12") || fname.endsWith(".P12")
? "PKCS12" : "JKS";
}
}
|
package se.ade.autoproxywrapper.gui.controller;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;
import se.ade.autoproxywrapper.config.Config;
import se.ade.autoproxywrapper.ProxyMode;
import se.ade.autoproxywrapper.events.EventBus;
import se.ade.autoproxywrapper.events.GenericLogEvent;
import se.ade.autoproxywrapper.events.RestartEvent;
import se.ade.autoproxywrapper.events.SetEnabledEvent;
import static se.ade.autoproxywrapper.config.Config.getConfig;
public class PropertiesController {
@FXML
public TextField listeningPort;
@FXML
public CheckBox enabled;
@FXML
public CheckBox verboseLogging;
@FXML
public CheckBox minimizeOnStartup;
@FXML
public CheckBox useBlockedHosts;
@FXML
public CheckBox useDirectModeHosts;
private Stage propertiesWindow;
@FXML
public void initialize() {
listeningPort.setText(Integer.toString(getConfig().getLocalPort()));
enabled.setSelected(getConfig().isEnabled());
minimizeOnStartup.setSelected(getConfig().isStartMinimized());
verboseLogging.setSelected(getConfig().isVerboseLogging());
useBlockedHosts.setSelected(getConfig().isBlockedHostsEnabled());
useDirectModeHosts.setSelected(getConfig().isDirectModeHostsEnabled());
}
@FXML
public void save() {
if (!validateInput()) {
return;
}
int newLocalPort = Integer.parseInt(listeningPort.getText());
if(getConfig().getLocalPort() != newLocalPort) {
getConfig().setLocalPort(newLocalPort);
EventBus.get().post(GenericLogEvent.info("Restarting..."));
EventBus.get().post(new RestartEvent());
}
getConfig().setStartMinimized(minimizeOnStartup.isSelected());
getConfig().setVerboseLogging(verboseLogging.isSelected());
getConfig().setBlockedHostsEnabled(useBlockedHosts.isSelected());
getConfig().setDirectModeHostsEnabled(useDirectModeHosts.isSelected());
Config.save();
if(enabled.isSelected() != getConfig().isEnabled()) {
EventBus.get().post(new SetEnabledEvent(enabled.isSelected()));
}
propertiesWindow.close();
}
@FXML
public void cancel() {
propertiesWindow.close();
}
private boolean validateInput() {
if (listeningPort.getText().equals("") || !StringUtils.isNumeric(listeningPort.getText()) || Integer.parseInt(listeningPort.getText()) > Short.MAX_VALUE) {
if (!listeningPort.getStyleClass().contains("invalid-field")) {
listeningPort.getStyleClass().add("invalid-field");
}
return false;
}
listeningPort.getStyleClass().remove("invalid-field");
return true;
}
public void setWindow(Stage window) {
this.propertiesWindow = window;
}
}
|
// modcommon/module.info.java
module modcommon {
exports pkgcommon;
}
|
package ggboy.study.java.spring_mybatis;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.alibaba.fastjson.JSON;
import ggboy.java.common.exception.CommonUtilException;
import ggboy.java.common.utils.sql.mysql.Select;
public class Main {
public static void main(String[] args) throws CommonUtilException {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:ggboy/study/java/spring_mybatis/spring.xml");
BaseDao dao = (BaseDao) context.getBean("baseDao");
Select sql = new Select("select * from invite limit 0,1", true);
List<Map<String,Object>> users = dao.select(sql);
System.out.println(JSON.toJSONString(users.get(0)));
}
}
|
package com.yc.education.mapper.account;
import com.yc.education.model.account.AccountReceivableFee;
import com.yc.education.util.MyMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface AccountReceivableFeeMapper extends MyMapper<AccountReceivableFee> {
/**
* 根据 应收账款冲账id 查询
* @param otherid
* @return
*/
List<AccountReceivableFee> listAccountReceivableFee(@Param("otherid") String otherid);
/**
* 通过外键删除
* @param otherid
* @return
*/
int deleteAccountReceivableFeeByParentId(@Param("otherid") String otherid);
} |
package com.moviee.moviee.services;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import com.moviee.moviee.models.Movie;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Thomas on 01/08/2016.
*/
public class FilmSharedIO {
private SharedPreferences prefs;
public FilmSharedIO(Context context)
{
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public boolean isMovieLiked(String MovieId)
{
Boolean liked = false;
int index = 0;
while (prefs.contains("film" + index)) {
String actualValue = prefs.getString("film" + index, "");
if (actualValue.contains("\"id\":\"" + MovieId + "\"")) {
liked = true;
index = 10000;
}
index++;
}
return liked;
}
public void likeOrDislikeMovie(Movie actualMovie)
{
if(isMovieLiked(actualMovie.id))
{
// dislike
int i = 0;
while(!(prefs.getString("film" + i, "").contains("\"id\":\"" + actualMovie.id + "\"")))
i++;
// now we have the position of the film to delete
// removing it:
prefs.edit().remove("film" + i).apply();
while(prefs.contains("film" + ++i))
{
prefs.edit().putString("film" + (i-1), prefs.getString("film" + i, "")).apply();
}
prefs.edit().remove("film" + (i-1)).apply();
}
else
{
int count = getLikedFilmCount();
// will add the film at position count
// value: un json {id: rating: releaseDate: genre: generalInfo: name: urlImage: }
String json = "{";
json += "\"id\":\"" + actualMovie.id + "\",";
json += "\"rating\":\"" + actualMovie.rating + "\",";
json += "\"releaseDate\":\"" + actualMovie.releaseDate + "\",";
json += "\"genre\":\"" + Uri.encode(actualMovie.genre) + "\",";
json += "\"generalInfo\":\"" + Uri.encode(actualMovie.generalInfo) + "\",";
json += "\"name\":\"" + Uri.encode(actualMovie.name) + "\",";
json += "\"urlImage\":\"" + actualMovie.urlImage + "\"";
prefs.edit().putString("film" + count, json + "}").apply();
}
}
public int getLikedFilmCount()
{
int i = -1;
while(prefs.contains("film" + (i + 1)))
i++;
return i+1;
}
public String getGenreById(String id, Context context)
{
try {
if(!"0123456789".contains(id.charAt(0) + ""))
return id;
JSONArray arr = new JSONObject( prefs.getString("genres", "")).getJSONArray("genres");
String finalString = "";
int j = -1;
id = id.replace(" ", "") + ",";
String currentOne = "";
while(++j<id.length()) {
if((id.charAt(j) + "").equals(",")) {
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
if (obj.getString("id").equals(currentOne))
finalString += obj.getString("name") + ", ";
}
currentOne = "";
}
else
currentOne += id.charAt(j);
}
return finalString.substring(0, finalString.length()-2);
}
catch (Exception exd) { exd.printStackTrace(); return "";}
}
public List<Movie> loadListFromLiked()
{
List<Movie> list = new ArrayList<>();
int i = getLikedFilmCount();
for(; i >= 0; i--)
{
try
{
String json = prefs.getString("film" + i, "");
JSONObject obj = new JSONObject(json);
String title = Uri.decode(obj.getString("name"));
String urlImage = obj.getString("urlImage");
String generalInfo = Uri.decode(obj.getString("generalInfo")) ;
String genre = Uri.decode(obj.getString("genre"));
String releaseDate = obj.getString("releaseDate");
String id = obj.getString("id");
String rating = obj.getString("rating");
list.add(new Movie(title, urlImage, generalInfo, genre, releaseDate, id, rating));
}
catch (Exception exd) {exd.printStackTrace();}
}
return list;
}
}
|
package info.fandroid.mindmap.controller.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import info.fandroid.mindmap.R;
import info.fandroid.mindmap.database.DBManager;
import info.fandroid.mindmap.model.ModelMap;
import info.fandroid.mindmap.model.ModelPlanet;
import info.fandroid.mindmap.ui.activity.OpenedMapActivity;
import info.fandroid.mindmap.ui.dialog.SupportingDialog;
import info.fandroid.mindmap.ui.fragment.EditMindMapFragment;
import info.fandroid.mindmap.util.FragmentManagerHelper;
import info.fandroid.mindmap.util.Utils;
/**
* Created by Vitaly on 26.12.2015.
*/
public class MindMapListAdapter extends RecyclerView.Adapter<MindMapListAdapter.ViewHolder> {
private List<ModelMap> mindMapList;
private Context mContext;
private DBManager mDbManager;
private FragmentManagerHelper fragmentManagerHelper;
public MindMapListAdapter() {
mindMapList = new ArrayList<>();
mDbManager = DBManager.getInstance();
fragmentManagerHelper = FragmentManagerHelper.getInstance();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView descriptionView;
public TextView description;
public TextView lastChanged;
public CircleImageView circle;
public TextView planetsCount;
public ImageView subject;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.tv_model_list_element_name);
descriptionView = (TextView) v.findViewById(R.id.tv_model_list_element_description);
description = (TextView) v.findViewById(R.id.tv_model_list_element_last_description_text);
lastChanged = (TextView) v.findViewById(R.id.tv_model_list_element_last_changed_date);
circle = (CircleImageView) v.findViewById(R.id.cv_model_list_element_circle);
planetsCount = (TextView) v.findViewById(R.id.tv_model_list_element_last_count_number);
subject = (ImageView) v.findViewById(R.id.iv_model_list_element_subject);
}
}
@Override
public MindMapListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext = parent.getContext();
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.model_mind_map_list_element, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final ModelMap model = mindMapList.get(position);
holder.name.setText(model.getName());
holder.description.setText(model.getDescription());
holder.lastChanged.setText(Utils.getDateWithCurrentLocale(model.getLastModified(),
mContext));
holder.planetsCount.setText(String.valueOf(model.getPlanetsCount()));
holder.subject.setImageDrawable(model.getSubject().getBigIcon(mContext));
if (model.getDescription().equals("") && holder.descriptionView
.getVisibility() == View.VISIBLE) {
holder.descriptionView.setVisibility(View.INVISIBLE);
} else if (holder.descriptionView.getVisibility() != View.VISIBLE) {
holder.descriptionView.setVisibility(View.VISIBLE);
}
holder.circle.setColorFilter(model.getColor());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, OpenedMapActivity.class);
intent.putExtras(ModelPlanet.mapToBundle(model));
mContext.startActivity(intent);
((AppCompatActivity) mContext).overridePendingTransition(0, 0);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
SupportingDialog.longClickDialog(mContext, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
EditMindMapFragment editMindMapFragment = new EditMindMapFragment();
editMindMapFragment.setArguments(ModelMap.toBundle(mindMapList.get(holder.getLayoutPosition())));
fragmentManagerHelper.setFragment(R.id.relative_container, editMindMapFragment, true);
editMindMapFragment.setOnFragmentListener(new EditMindMapFragment.OnEditFragmentListener() {
@Override
public void onBackFromEdit(ModelMap model) {
ModelMap old = mindMapList.get(holder.getAdapterPosition());
old.setName(model.getName());
old.setDescription(model.getDescription());
old.setColor(model.getColor());
old.setLastModified(model.getLastModified());
old.setSubject(model.getSubject());
notifyItemChanged(holder.getAdapterPosition());
((AppCompatActivity) mContext).onBackPressed();
}
});
} else if (which == 1) {
SupportingDialog.removeDialog(mContext, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int removedPosition = holder.getLayoutPosition();
mDbManager.delete().map(mindMapList.get(removedPosition).getId());
mindMapList.remove(removedPosition);
notifyItemRemoved(removedPosition);
dialog.dismiss();
}
});
}
}
});
return true;
}
});
}
@Override
public int getItemCount() {
return mindMapList.size();
}
public void addMindMap(ModelMap mindMapListElement) {
mindMapList.add(mindMapListElement);
notifyItemInserted(mindMapList.size());
}
public void addMapList(List<ModelMap> maps) {
mindMapList.addAll(maps);
notifyItemRangeInserted(0, maps.size());
}
}
|
package com.git.cloud.cloudservice.service.impl;
import com.git.cloud.cloudservice.dao.ICloudServiceFlowRefDao;
import com.git.cloud.cloudservice.model.po.CloudServiceFlowRefPo;
import com.git.cloud.cloudservice.service.ICloudServiceFlowRefService;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.common.model.IsActiveEnum;
import com.git.cloud.common.support.Pagination;
import com.git.cloud.common.support.PaginationParam;
import com.git.cloud.foundation.util.UUIDGenerator;
public class CloudServiceFlowRefServiceImpl implements ICloudServiceFlowRefService {
private ICloudServiceFlowRefDao cloudServiceFlowRefDao;
@Override
public CloudServiceFlowRefPo save(CloudServiceFlowRefPo cloudService) throws RollbackableBizException {
cloudService.setServiceFlowId(UUIDGenerator.getUUID());
cloudService.setIsActive(IsActiveEnum.YES.getValue());
cloudServiceFlowRefDao.save(cloudService);
return cloudService;
}
@Override
public void update(CloudServiceFlowRefPo cloudService) throws RollbackableBizException {
cloudServiceFlowRefDao.update(cloudService);
}
@Override
public CloudServiceFlowRefPo findById(String id) throws RollbackableBizException {
return cloudServiceFlowRefDao.findById(id);
}
@Override
public Pagination<CloudServiceFlowRefPo> queryPagination(PaginationParam paginationParam) {
return cloudServiceFlowRefDao.queryPagination(paginationParam);
}
@Override
public void deleteById(String[] ids) throws RollbackableBizException {
cloudServiceFlowRefDao.deleteById(ids);
}
public ICloudServiceFlowRefDao getCloudServiceFlowRefDao() {
return cloudServiceFlowRefDao;
}
public void setCloudServiceFlowRefDao(ICloudServiceFlowRefDao cloudServiceFlowRefDao) {
this.cloudServiceFlowRefDao = cloudServiceFlowRefDao;
}
@Override
public boolean checkCloudServiceFlowRefs(
CloudServiceFlowRefPo cloudServiceFlowRefPo)
throws RollbackableBizException {
int count = cloudServiceFlowRefDao.findCloudServiceFlowRefPoCount(cloudServiceFlowRefPo);
if(count > 0){
return false;
}else{
return true;
}
}
}
|
package pass1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
class SymLit{
//class for Symbols and Literals
int addr;
String name;
SymLit(String n,int a){
name = n;
addr = a;
}
SymLit(String n){
name = n;
}
String getName(){
return name;
}
void setAddr(int a){
addr = a;
}
static int Search(SymLit []obj,String key,int ptr){
for(int i = 1;i<ptr;i++){
if(obj[i].getName().equals(key))
return i;
}
return 0;
}
}
public class Pass1 {
public static void main(String args[]) throws IOException{
SymLit [] SYMTAB = new SymLit[50];//Symbol Table
SymLit [] LITTAB = new SymLit[50];//Literal Table
int [] POOLTAB = new int[10]; //Pool Table
//Imperative statement
HashMap<String , Integer> IS = new HashMap<>();
IS.put("STOP",0);
IS.put("ADD",1);
IS.put("SUB",2);
IS.put("MULT",3);
IS.put("MOVER",4);
IS.put("MOVEM",5);
IS.put("COMP",6);
IS.put("BC",7);
IS.put("DIV",8);
IS.put("READ",9);
IS.put("PRINT",10);
//Registers
HashMap<String, Integer> REG = new HashMap<>();
REG.put("AREG",1);
REG.put("BREG",2);
REG.put("CREG",3);
REG.put("DREG",4);
//Conditional Codes
HashMap<String,Integer> CC = new HashMap<>();
CC.put("LT", 1);
CC.put("LE", 2);
CC.put("EQ", 3);
CC.put("GT", 4);
CC.put("GE", 5);
CC.put("ANY", 6);
//Assembly Directives
HashMap<String, Integer> AD = new HashMap<>();
AD.put("START",1);
AD.put("END",2);
AD.put("ORIGIN",3);
AD.put("EQU",4);
AD.put("LTORG",5);
//Declarative
HashMap<String, Integer> DL = new HashMap<>();
DL.put("DS",2);
DL.put("DC",1);
//initialize all pointers
int loc_cntr = 0, pool_ptr = 1,lit_ptr = 1,sym_ptr = 1;
POOLTAB[1] = 1;
int newloc_cntr = 0;
//Read code from file
FileReader fr=new FileReader("code2.txt");
BufferedReader br=new BufferedReader(fr);
//store intermediate code in ic.txt
OutputStream os = new FileOutputStream(new File("/home/TE/SPOSL/3171/A1/ic.txt"));
String CurrentLine;
outerloop:
while((CurrentLine = br.readLine()) != null){
//read all lines till end of file
String line = "";
//initialize all values which are a part of every line in intermediate code
int val =0 , regval = 0 , cval = 0 , cextra = 0;
String key="";
char csl='\0',csign = '\0';
String s[]=CurrentLine.split(" ");//s[] contains all the words in current line of code
/*for(int i = 0 ;i< s.length;i++){
System.out.print(s[i] + " ");
}
System.out.println();*/
String temp = s[0];
int flag = 0;
boolean lflag = true;//flag to check if label is present on current line or not
while(flag == 0){
if(AD.containsKey(temp)){
//Assembly Directive is present
key = "AD";
val = AD.get(temp);
if(temp.equals("START")){
newloc_cntr = Integer.parseInt(s[1]);
cval = Integer.parseInt(s[1]);
csl = 'C';
if(cextra == 0)
line = "("+ key + "," + val + ") (" + csl + "," + cval + ")";
else
line = "("+ key + "," + val + ") (" + csl + "," + cval + ")" + csign + cextra + " ";
}
else if(temp.equals("EQU")){
csl = 'S';
String sym[];
//find symbol in symbol table
int index = SymLit.Search(SYMTAB, s[0],sym_ptr);
if(s[2].contains("+"))
{
sym = s[2].split("\\+");
csign = '+';
cextra = Integer.parseInt(sym[1]);
SYMTAB[index].setAddr(SYMTAB[SymLit.Search(SYMTAB, sym[0],sym_ptr)].addr + cextra);
}
else if(s[2].contains("-"))
{
sym = s[2].split("\\-");
csign = '-';
cextra = Integer.parseInt(sym[1]);
SYMTAB[index].setAddr(SYMTAB[SymLit.Search(SYMTAB, sym[0],sym_ptr)].addr - cextra);
}
else{
sym = new String[1];
sym[0]= s[2];
SYMTAB[index].setAddr(SYMTAB[SymLit.Search(SYMTAB, sym[0],sym_ptr)].addr);
}
cval = SymLit.Search(SYMTAB, sym[0],sym_ptr);
//System.out.print(sym[0]+" ");
if(cextra == 0)
line = ("("+ key + "," + val + ") (" + csl + "," + cval + ")");
else
line = ("("+ key + "," + val + ") (" + csl + "," + cval + ")" + csign + cextra + " ");
}else if(temp.equals("ORIGIN")){
csl = 'S';
String sym[];
if(lflag == false){
s[1]=s[2];
}
if(s[1].contains("+"))
{
sym = s[1].split("\\+");
csign = '+';
cextra = Integer.parseInt(sym[1]);
}
else if(s[1].contains("-"))
{
sym = s[1].split("\\-");
csign = '-';
cextra = Integer.parseInt(sym[1]);
}
else{
sym = new String[1];
sym[0] = s[1];
}
cval = SymLit.Search(SYMTAB, sym[0],sym_ptr);
newloc_cntr = SYMTAB[cval].addr ;
if(csign == '+'){
newloc_cntr +=cextra;
}
else if(csign == '-'){
newloc_cntr -= cextra;
}
if(cextra == 0)
line = ("("+ key + "," + val + ") (" + csl + "," + cval + ")");
else
line = ("("+ key + "," + val + ") (" + csl + "," + cval + ")" + csign + cextra + " ");
}else if(temp.equals("LTORG")){
line = ("("+ key + "," + val + ")");
for(int i=POOLTAB[pool_ptr];i<lit_ptr;i++){
LITTAB[i].addr = newloc_cntr;
newloc_cntr++;
}
pool_ptr++;
POOLTAB[pool_ptr] = lit_ptr;
//System.out.println(loc_cntr);
}
else if(temp.equals("END")){
line = ("("+ key + "," + val + ")");
break outerloop;
}
flag = 1;
}
else if(IS.containsKey(temp)){
key = "IS";
//Imperative Statement is present
String symlit="";
val=IS.get(temp);
if(val == 7){
//BC statement code
if(lflag){
regval=CC.get(s[1]);
}
else{
regval=REG.get(s[2]);
s[2] = s[3];
}
symlit = s[2];
csl='S';
cval = SymLit.Search(SYMTAB, symlit,sym_ptr);
if(cval == 0)
{
SYMTAB[sym_ptr]=new SymLit(symlit);
cval=sym_ptr;
sym_ptr++;
}
}
else if(val == 0){
//stop statement code do nothing
}
else{
if(lflag){
if(REG.containsKey(s[1]))
{
regval=REG.get(s[1]);
symlit = s[2];
}else{
symlit = s[1];
}
}
else{
if(REG.containsKey(s[2]))
{
regval=REG.get(s[2]);
s[2] = s[3];
}
symlit = s[2];
}
if(symlit.charAt(0)=='=')
{
csl='L';
LITTAB[lit_ptr]=new SymLit(symlit.substring(1));
cval = lit_ptr;
lit_ptr++;
}
else
{
csl='S';
cval = SymLit.Search(SYMTAB, symlit,sym_ptr);
if(cval == 0)
{
SYMTAB[sym_ptr]=new SymLit(symlit);
cval=sym_ptr;
sym_ptr++;
}
}
}
newloc_cntr++;
flag = 1;
if(csl != '\0'){
if (regval == 0)
line = ("("+ key + "," + val + ") (" + csl + "," + cval + ") " + loc_cntr);
else
line = ("("+ key + "," + val + ") (" + regval + ") (" + csl + "," +cval + ") " + loc_cntr );
}
else{
line = ("("+ key + "," + val + ") " + loc_cntr );
}
}
else if(DL.containsKey(temp)){
val=DL.get(temp);
key = "DL";
csl = 'C';
if(val == 2){
int length = Integer.parseInt(s[2]);
newloc_cntr += length;
cval = SymLit.Search(SYMTAB, s[0], sym_ptr);
if(cval == 0)
{
SYMTAB[sym_ptr]=new SymLit(s[0]);
sym_ptr++;
}
else
SYMTAB[cval].setAddr(loc_cntr);
cval = length;
}if(val ==1){
cval = SymLit.Search(SYMTAB, s[0], sym_ptr);
SYMTAB[cval].addr = loc_cntr;
newloc_cntr++;
cval = Integer.parseInt(s[2]);
}
line = ("("+ key + "," + val + ") (" + csl + "," +cval + ") " + loc_cntr );
flag = 1;
}
else{
//label is present
String lable = temp ;
cval = SymLit.Search(SYMTAB, temp, sym_ptr);
if(cval == 0){
SYMTAB[sym_ptr] = new SymLit(lable,loc_cntr);
sym_ptr++;
}else if(SYMTAB[cval].addr==0){
SYMTAB[cval].setAddr(loc_cntr);
}
temp = s[1];
lflag = false;
//System.out.println(SYMTAB[sym_ptr-1].name);
}
}
loc_cntr = newloc_cntr;
line = line+'\n';
os.write(line.getBytes(), 0, line.length());//write line in ic.txt
}
//store all literals after end statement just like LTORG
for(int i=POOLTAB[pool_ptr];i<lit_ptr;i++){
LITTAB[i].addr = loc_cntr;
loc_cntr++;
}
pool_ptr++;
POOLTAB[pool_ptr] = lit_ptr;
OutputStream os1 = new FileOutputStream(new File("/home/TE/SPOSL/3171/A1/SymbolTable.txt"));
OutputStream os2 = new FileOutputStream(new File("/home/TE/SPOSL/3171/A1/LiteralTable.txt"));
OutputStream os3 = new FileOutputStream(new File("/home/TE/SPOSL/3171/A1/PoolTable.txt"));
String line = "";
//Symbol table
for(int i=1;i < sym_ptr;i++)
{
line =(i+"\t"+SYMTAB[i].name+"\t"+SYMTAB[i].addr+"\t\n");
os1.write(line.getBytes(), 0, line.length());
}
//Literal table
for(int i=1;i<lit_ptr;i++){
line = (i+"\t"+LITTAB[i].name+"\t"+LITTAB[i].addr + "\n");
os2.write(line.getBytes(), 0, line.length());
}
//Pool Table
for(int i=1;i<pool_ptr;i++){
line = (i+"\t"+POOLTAB[i] + "\n");
os3.write(line.getBytes(), 0, line.length());
}
os1.close();
os.close();
os2.close();
os3.close();
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.types.basic;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import pl.edu.icm.unity.exceptions.IllegalIdentityValueException;
import pl.edu.icm.unity.types.confirmation.ConfirmationInfo;
/**
* Represents an identity with full information as returned from the engine.
*
* @author K. Benedyczak
*/
public class Identity extends IdentityParam
{
private Long entityId;
@JsonIgnore
private IdentityType type;
private Date creationTs;
private Date updateTs;
private String comparableValue;
private String prettyString;
private String prettyStringNoPfx;
private String ordinaryString;
public Identity()
{
}
public Identity(IdentityType type, String value, Long entityId, String realm, String target, String remoteIdp,
String translationProfile, Date creationTs, Date updateTs, ConfirmationInfo ci) throws IllegalIdentityValueException
{
super(type.getIdentityTypeProvider().getId(), value);
this.entityId = entityId;
this.type = type;
this.type.getIdentityTypeProvider().validate(value);
this.target = target;
this.realm = realm;
if (type.getIdentityTypeProvider().isTargeted() && (target == null || realm == null))
throw new IllegalIdentityValueException("The target and realm must be set for targeted identity");
setRemoteIdp(remoteIdp);
setTranslationProfile(translationProfile);
setCreationTs(creationTs);
setUpdateTs(updateTs);
setConfirmationInfo(ci);
}
public Long getEntityId()
{
return entityId;
}
public IdentityType getType()
{
return type;
}
public void setEntityId(Long entityId)
{
this.entityId = entityId;
}
public void setType(IdentityType type)
{
this.type = type;
}
public Date getCreationTs()
{
return creationTs;
}
public void setCreationTs(Date creationTs)
{
this.creationTs = creationTs;
}
public Date getUpdateTs()
{
return updateTs;
}
public void setUpdateTs(Date updateTs)
{
this.updateTs = updateTs;
}
public List<Attribute<?>> extractAttributes()
{
return type.getIdentityTypeProvider().extractAttributes(getValue(), type.getExtractedAttributes());
}
public String getComparableValue()
{
if (comparableValue == null)
try
{
comparableValue = type.getIdentityTypeProvider().getComparableValue(value,
realm, target);
} catch (IllegalIdentityValueException e)
{
//shouldn't happen, unless somebody made a buggy code
throw new IllegalStateException("The identity is not initialized properly", e);
}
return comparableValue;
}
public List<Attribute<?>> extractAllAttributes()
{
return type.getIdentityTypeProvider().extractAttributes(value, null);
}
/**
* Similar to {@link #toString()}, but allows for less verbose
* and more user-friendly output.
* @return
*/
public String toPrettyString()
{
if (prettyString == null)
prettyString = type.getIdentityTypeProvider().toPrettyString(this);
return prettyString;
}
/**
* Similar to {@link #toPrettyString()}, but doesn't return id type prefix.
* @return
*/
public String toPrettyStringNoPrefix()
{
if (prettyStringNoPfx == null)
prettyStringNoPfx = type.getIdentityTypeProvider().toPrettyStringNoPrefix(this);
return prettyStringNoPfx;
}
/**
* @return full String representation
*/
public String toString()
{
if (ordinaryString == null)
ordinaryString = type.getIdentityTypeProvider().toString(this);
return ordinaryString;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result
+ ((getComparableValue() == null) ? 0 : getComparableValue().hashCode());
result = prime * result + ((entityId == null) ? 0 : entityId.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Identity other = (Identity) obj;
if (getComparableValue() == null)
{
if (other.getComparableValue() != null)
return false;
} else if (!getComparableValue().equals(other.getComparableValue()))
return false;
if (entityId == null)
{
if (other.entityId != null)
return false;
} else if (!entityId.equals(other.entityId))
return false;
if (type == null)
{
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
|
package com.heihei.fragment.live.logic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.base.http.ErrorCode;
import com.base.http.JSONResponse;
import com.heihei.logic.present.LivePresent;
import com.heihei.model.Gift;
public class GiftController {
private static GiftController mIns;
private GiftController() {}
private HashMap<Integer, Gift> mGifts = new HashMap<>();
public static GiftController getInstance() {
if (mIns == null) {
synchronized (GiftController.class) {
if (mIns == null) {
mIns = new GiftController();
}
}
}
return mIns;
}
/**
* 通过礼物id获取礼物信息
*
* @param id
*/
public Gift getGiftById(int id) {
return mGifts.get(id);
}
private LivePresent mLivePresent = new LivePresent();
/**
* 请求礼物列表
*/
public void requestGiftList(final OnGiftListGetListener mListener) {
mLivePresent.getGiftList(new JSONResponse() {
@Override
public void onJsonResponse(JSONObject json, int errCode, String msg, boolean cached) {
if (errCode == ErrorCode.ERROR_OK) {
mGifts.clear();
List<Gift> gifts = new ArrayList<>();
JSONArray giftArr = json.optJSONArray("gifts");
if (giftArr != null && giftArr.length() > 0) {
for (int i = 0; i < giftArr.length(); i++) {
Gift gift = new Gift(giftArr.optJSONObject(i));
gifts.add(gift);
mGifts.put(gift.id, gift);
}
}
if (mListener != null) {
mListener.onGiftGet(gifts);
}
}
}
}, true);
}
public static interface OnGiftListGetListener {
public void onGiftGet(List<Gift> mGifts);
}
}
|
package com.xiniunet.tutorial.tutorial.module.screen.leave;
import com.alibaba.citrus.turbine.Context;
import com.xiniunet.framework.security.Passport;
import com.xiniunet.framework.util.auth.LocalData;
import com.xiniunet.workflow.domain.Process;
import com.xiniunet.workflow.domain.ProcessApproveRule;
import com.xiniunet.workflow.request.ProcessApproveRuleGetRequest;
import com.xiniunet.workflow.request.ProcessGetFromTemplateRequest;
import com.xiniunet.workflow.response.ProcessApproveRuleGetResponse;
import com.xiniunet.workflow.response.ProcessGetFromTemplateResponse;
import com.xiniunet.workflow.service.WorkflowService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created on 2017-08-29.
*
* @author 吕浩
* @since 1.0.0
*/
public class Submit {
@Autowired
private WorkflowService workflowService;
public String getProcess() {
return "system.tutorial.leave";
}
public void execute(Context context) {
Passport passport = LocalData.getCurrentPassport();
// 查询流程实例对象
ProcessGetFromTemplateRequest request = new ProcessGetFromTemplateRequest();
request.setCode(getProcess());
ProcessGetFromTemplateResponse response = workflowService.getProcessFromTemplate(request, passport);
Process process = response.getProcess();
// 获取流程审批规则
ProcessApproveRuleGetRequest ruleGetRequest = new ProcessApproveRuleGetRequest();
ruleGetRequest.setId(process.getId());
ProcessApproveRuleGetResponse ruleGetResponse = workflowService.getProcessApproveRule(ruleGetRequest, passport);
ProcessApproveRule approveRule = ruleGetResponse.getProcessApproveRule();
context.put("approveRule", approveRule);
}
}
|
package com.esum.ebms.v2.packages.util;
import java.util.Calendar;
/**
*
* @author Yeonho Chung <yhchung@esumtech.com>
* @since 2004-06-08
*
*/
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2002-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Axis" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* Implementation of the XML Schema type duration
*
* @author Wes Moulder <wes@themindelectric.com>
* @see <a href="http://www.w3.org/TR/xmlschema-2/#duration">XML Schema 3.2.6</a>
*/
public class Duration implements java.io.Serializable {
boolean isNegative = false;
int years;
int months;
int days;
int hours;
int minutes;
double seconds;
/**
* Default no-arg constructor
*/
public Duration() {
}
/**
* @param negative
* @param aYears
* @param aMonths
* @param aDays
* @param aHours
* @param aMinutes
* @param aSeconds
*/
public Duration(boolean negative, int aYears, int aMonths, int aDays, int aHours, int aMinutes, double aSeconds) {
isNegative = negative;
years = aYears;
months = aMonths;
days = aDays;
hours = aHours;
minutes = aMinutes;
seconds = aSeconds;
}
/**
* This method takes a string that represents an xsd:duration and parses it.
*
* @param duration
* @throws SchemaException if the string doesn't parse correctly.
*/
public Duration(String duration) throws IllegalArgumentException {
int position = 1;
int timePosition = duration.indexOf("T");
if (duration.indexOf("P") == -1)
throw new IllegalArgumentException("Bad Duration");
if (duration.startsWith("-")) {
isNegative = true;
position++;
}
if (timePosition != -1)
parseTime(duration.substring(timePosition + 1));
else
timePosition = duration.length();
parseDate(duration.substring(position, timePosition));
}
/**
* This method parses the time portion of a duration.
*
* @param time
*/
public void parseTime(String time) {
int start = 0;
int end = time.indexOf("H");
if (end != -1) {
hours = Integer.parseInt(time.substring(0, end));
start = end + 1;
}
end = time.indexOf("M");
if (end != -1) {
minutes = Integer.parseInt(time.substring(start, end));
start = end + 1;
}
end = time.indexOf("S");
if (end != -1)
seconds = Double.parseDouble(time.substring(start, end));
}
/**
* This method parses the date portion of a duration.
*
* @param date
*/
public void parseDate(String date) {
int start = 0;
int end = date.indexOf("Y");
if (end != -1) {
years = Integer.parseInt(date.substring(0, end));
start = end + 1;
}
end = date.indexOf("M");
if (end != -1) {
months = Integer.parseInt(date.substring(start, end));
start = end + 1;
}
end = date.indexOf("D");
if (end != -1)
days = Integer.parseInt(date.substring(start, end));
}
/**
*
*/
public boolean isNegative() {
return isNegative;
}
/**
*
*/
public int getYears() {
return years;
}
/**
*
*/
public int getMonths() {
return months;
}
/**
*
*/
public int getDays() {
return days;
}
/**
*
*/
public int getHours() {
return hours;
}
/**
*
*/
public int getMinutes() {
return minutes;
}
/**
*
*/
public double getSeconds() {
return seconds;
}
/**
* @param negative
*/
public void setNegative(boolean negative) {
isNegative = negative;
}
/**
* @param years
*/
public void setYears(int years) {
this.years = years;
}
/**
* @param months
*/
public void setMonths(int months) {
this.months = months;
}
/**
* @param days
*/
public void setDays(int days) {
this.days = days;
}
/**
* @param hours
*/
public void setHours(int hours) {
this.hours = hours;
}
/**
* @param minutes
*/
public void setMinutes(int minutes) {
this.minutes = minutes;
}
/**
* @param seconds
*/
public void setSeconds(int seconds) {
this.seconds = seconds;
}
/**
* This returns the xml representation of an xsd:duration object.
*/
public String toString() {
StringBuffer duration = new StringBuffer();
duration.append("P");
if (years != 0)
duration.append(years + "Y");
if (months != 0)
duration.append(months + "M");
if (days != 0)
duration.append(days + "D");
if (hours != 0 || minutes != 0 || seconds != 0.0) {
duration.append("T");
if (hours != 0)
duration.append(hours + "H");
if (minutes != 0)
duration.append(minutes + "M");
if (seconds != 0) {
if (seconds == (int) seconds)
duration.append((int) seconds + "S");
else
duration.append(seconds + "S");
}
}
if (duration.length() == 1)
duration.append("T0S");
if (isNegative)
duration.insert(0, "-");
return duration.toString();
}
/** Multiple */
public void multiple(int factor)
{
years *= factor;
months *= factor;
days *= factor;
hours *= factor;
minutes *= factor;
seconds *= factor;
}
/** Add Duration to Calendar */
public Calendar addToCalendar(Calendar cal) throws Exception
{
int plusMinus = isNegative == false ? 1 : -1;
int iyears,imonths,idays,ihours,imins,isecs,millis;
if (years > 0)
{
iyears = (int)years;
imonths = 0;
idays = (int)(365.254*(years
-iyears));
ihours = (int)(24.0*365.254*(years
-iyears
-idays/365.254));
imins = (int)(60.0*24.0*365.254*(years
-iyears
-idays/365.254
-ihours/24.0/365.254));
isecs = (int)(60.0*60.0*24.0*365.254*(years
-iyears
-idays/365.254
-ihours/24.0/365.254
-imins/60.0/24.0/365.254));
millis = (int)(1000.0*60.0*60.0*24.0*365.254*(years
-iyears
-idays/365.254
-ihours/24.0/365.254
-imins/60.0/24.0/365.254
-isecs/60.0/60.0/24.0/365.254));
cal.add(Calendar.YEAR, plusMinus*iyears);
cal.add(Calendar.DAY_OF_YEAR, plusMinus*idays);
cal.add(Calendar.HOUR, plusMinus*ihours);
cal.add(Calendar.MINUTE, plusMinus*imins);
cal.add(Calendar.SECOND, plusMinus*isecs);
cal.add(Calendar.MILLISECOND, plusMinus*millis);
}
if (months > 0)
{
imonths = (int)months;
if (months != (double)imonths)
throw new Exception("Cannot add decimal months!");
cal.add(Calendar.MONTH, plusMinus*imonths);
}
if (days > 0)
{
idays = (int)days;
ihours = (int)(24.0*(days
-idays));
imins = (int)(60.0*24.0*(days
-idays
-ihours/24.0));
isecs = (int)(60.0*60.0*24.0*(days
-idays
-ihours/24.0
-imins/24.0/60.0));
millis = (int)(1000.0*60.0*60.0*24.0*(days
-idays
-ihours/24.0
-imins/60.0/24.0
-isecs/60.0/60.0/24.0));
cal.add(Calendar.DAY_OF_YEAR, plusMinus*idays);
cal.add(Calendar.HOUR, plusMinus*ihours);
cal.add(Calendar.MINUTE, plusMinus*imins);
cal.add(Calendar.SECOND, plusMinus*isecs);
cal.add(Calendar.MILLISECOND, plusMinus*millis);
}
if (hours > 0)
{
ihours = (int)hours;
imins = (int)(60.0*(hours
-ihours));
isecs = (int)(60.0*60.0*(hours
-ihours
-imins/60.0));
millis = (int)(1000.0*60.0*60.0*(hours
-ihours
-imins/60.0
-isecs/60.0/60.0));
cal.add(Calendar.HOUR, plusMinus*ihours);
cal.add(Calendar.MINUTE, plusMinus*imins);
cal.add(Calendar.SECOND, plusMinus*isecs);
cal.add(Calendar.MILLISECOND, plusMinus*millis);
}
if (minutes > 0)
{
imins = (int)minutes;
isecs = (int)(60.0*(minutes
-imins));
millis = (int)(1000.0*60.0*(minutes
-imins
-isecs/60.0));
cal.add(Calendar.MINUTE, plusMinus*imins);
cal.add(Calendar.SECOND, plusMinus*isecs);
cal.add(Calendar.MILLISECOND, plusMinus*millis);
}
if (seconds > 0)
{
isecs = (int)seconds;
millis = (int)(1000.0*(seconds
-isecs));
cal.add(Calendar.SECOND, plusMinus*isecs);
cal.add(Calendar.MILLISECOND, plusMinus*millis);
}
return cal;
}
} |
package com.yea.loadbalancer;
import com.netflix.config.ChainedDynamicProperty;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.yea.core.loadbalancer.IRule;
import com.yea.loadbalancer.config.IClientConfig;
/**
* Predicate with the logic of filtering out circuit breaker tripped servers and servers
* with too many concurrent connections from this client.
*
* @author awang
*
*/
public class AvailabilityPredicate extends AbstractNodePredicate {
private static final DynamicBooleanProperty CIRCUIT_BREAKER_FILTERING =
DynamicPropertyFactory.getInstance().getBooleanProperty("niws.loadbalancer.availabilityFilteringRule.filterCircuitTripped", true);
private static final DynamicIntProperty ACTIVE_CONNECTIONS_LIMIT =
DynamicPropertyFactory.getInstance().getIntProperty("niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit", Integer.MAX_VALUE);
private ChainedDynamicProperty.IntProperty activeConnectionsLimit = new ChainedDynamicProperty.IntProperty(ACTIVE_CONNECTIONS_LIMIT);
public AvailabilityPredicate(IRule rule, IClientConfig clientConfig) {
super(rule, clientConfig);
initDynamicProperty(clientConfig);
}
public AvailabilityPredicate(LoadBalancerStats lbStats, IClientConfig clientConfig) {
super(lbStats, clientConfig);
initDynamicProperty(clientConfig);
}
public AvailabilityPredicate(IRule rule) {
super(rule);
}
private void initDynamicProperty(IClientConfig clientConfig) {
String id = "default";
if (clientConfig != null) {
id = clientConfig.getClientName();
activeConnectionsLimit = new ChainedDynamicProperty.IntProperty(id + "." + clientConfig.getNameSpace() + ".ActiveConnectionsLimit", ACTIVE_CONNECTIONS_LIMIT);
}
}
@Override
public boolean apply(PredicateKey input) {
LoadBalancerStats stats = getLBStats();
if (stats == null) {
return true;
}
return !shouldSkipServer(stats.getSingleServerStat(input.getServer()));
}
private boolean shouldSkipServer(ServerStats stats) {
if ((CIRCUIT_BREAKER_FILTERING.get() && stats.isCircuitBreakerTripped())
|| stats.getActiveRequestsCount() >= activeConnectionsLimit.get()) {
return true;
}
return false;
}
}
|
package com.zc.pivas.wardgroup.controller;
import com.google.gson.Gson;
import com.zc.base.common.controller.SdBaseController;
import com.zc.base.orm.mybatis.paging.JqueryStylePaging;
import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults;
import com.zc.base.sys.common.constant.AmiLogConstant;
import com.zc.pivas.common.entity.ResultData;
import com.zc.pivas.common.util.DataFormat;
import com.zc.pivas.common.util.SysConstant.operLogRecord;
import com.zc.pivas.wardgroup.bean.WardGroupBean;
import com.zc.pivas.wardgroup.service.WardGroupService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 病区分组Controller类
*
* @author kunkka
* @version 1.0
*/
@Controller
@RequestMapping(value = "/wardRegionGroup")
public class WardGroupController extends SdBaseController {
/**
* 日志类
*/
private static final Logger log = LoggerFactory.getLogger(WardGroupController.class);
@Resource
private WardGroupService wardGroupService;
/**
* 主页面
*
* @param model
* @param request
* @return
*/
@RequestMapping(value = "/init")
@RequiresPermissions(value = {"PIVAS_MENU_924"})
public String init(Model model, HttpServletRequest request) {
return "pivas/wardGroup";
}
/**
* 查询分组
*
* @param jquryStylePaging
* @return
* @throws Exception
*/
@RequestMapping(value = "/qryList")
@ResponseBody
//@RequiresPermissions(value = {"PIVAS_BTN_274"})
public String getCheckTypeList(JqueryStylePaging jquryStylePaging)
throws Exception {
JqueryStylePagingResults<WardGroupBean> pagingResults =
wardGroupService.getGroupLsit(jquryStylePaging);
return new Gson().toJson(pagingResults);
}
/**
* 初始化病区
*
* @param model
* @param request
* @param wardId
* @return
*/
@RequestMapping(value = "/initSelWard")
public String initPatient(Model model, HttpServletRequest request, String wardId) throws Exception {
List<WardGroupBean> wardList = wardGroupService.getWardList(wardId);
model.addAttribute("wardList", wardList);
return "pivas/wardGroupSelect";
}
/**
* 保存分组
*
* @param groupName
* @param groupOrder
* @param idStrs
* @return
* @throws Exception
*/
@RequestMapping(value = "/saveWardGroup")
@ResponseBody
@RequiresPermissions(value = {"PIVAS_BTN_981"})
public ResultData saveWard(String groupName, String groupOrder, String idStrs)
throws Exception {
String id = null;
if (StringUtils.isNotBlank(groupName) && StringUtils.isNotBlank(groupOrder)) {
int num = 0;
num = wardGroupService.checkParam("name", groupName);
if (num >= 1) {
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "添加分组失败,组名重复", false);
return DataFormat.formatFail("组名重复", null);
}
num = wardGroupService.checkParam("order", groupOrder);
if (num >= 1) {
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "添加分组失败,优先级重复", false);
return DataFormat.formatFail("优先级重复", null);
}
WardGroupBean ward = new WardGroupBean();
ward.setDeptname(groupName);
ward.setOrdernum(groupOrder);
//保存创建的分组
wardGroupService.saveGroup(ward);
id = ward.getId();
if (id == null || StringUtil.isBlank(id)) {
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "保存分组失败", false);
return DataFormat.formatFail("保存分组失败", null);
}
} else {
log.error("分组功能保存分组获取信息失败");
return DataFormat.formatFail("数据错误", null);
}
if (StringUtils.isNotBlank(idStrs)) {
//保存分组的子病区
String[] wardIdArray = idStrs.split(",");
wardGroupService.saveSubWard(id, wardIdArray);
}
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "保存分组成功", true);
return DataFormat.formatSucc();
}
/**
* 更新分组
*
* @param groupOrder
* @param idStrs
* @param parentid
* @param checkOrder
* @return
* @throws Exception
*/
@RequestMapping(value = "/updateGroup")
@ResponseBody
@RequiresPermissions(value = {"PIVAS_BTN_982"})
public ResultData updateWardGroup(String groupOrder, String idStrs, String parentid, Boolean checkOrder)
throws Exception {
if (StringUtils.isNotBlank(groupOrder)) {
//判断是否修改了优先级,并且修改后的优先级是否重复
if (checkOrder) {
int num = 0;
num = wardGroupService.checkParam("order", groupOrder);
if (num >= 1) {
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "更新分组失败,优先级重复", false);
return DataFormat.formatFail("优先级重复", null);
}
}
} else {
log.error("分组功能更新分组获取信息失败");
return DataFormat.formatFail("数据错误", null);
}
String[] wardIdArray = idStrs.split(",");
//更新分组
wardGroupService.updateWardGroup(parentid, wardIdArray, groupOrder);
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "更新分组成功", true);
return DataFormat.formatSucc();
}
/**
* 删除分组
*
* @param idStrs
* @return
* @throws Exception
*/
@RequestMapping(value = "/delGroup")
@ResponseBody
@RequiresPermissions(value = {"PIVAS_BTN_983"})
public ResultData delWardGroup(String idStrs) throws Exception {
if (StringUtils.isBlank(idStrs)) {
log.error("分组功能删除分组获取信息失败");
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "删除分组失败", false);
return DataFormat.formatFail("数据错误", null);
}
String[] idArray = idStrs.split(",");
wardGroupService.delWardGroup(idArray);
addOperLog(operLogRecord.wardGroup, AmiLogConstant.BRANCH_SYSTEM.CF, "删除分组成功", true);
return DataFormat.formatSucc();
}
}
|
package revolt.backend.entity;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
import javax.persistence.*;
@Getter
@Setter
@Entity
@Table(name = "mechmod")
@FieldDefaults(level = AccessLevel.PRIVATE)
public class Mechmod {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Column(name = "mechmod_name")
String name;
@Column(name = "mechmod_batteryType")
Integer batteryType;
@Column(name = "mechmod_color")
String color;
@Column(name = "mechmod_diameter")
Double diameter;
@Column(name = "mechmod_price")
Integer price;
@Column(name = "mechmod_description", length = 1000)
String description;
@Column(name = "mechmod_picture")
String picture;
@ManyToOne
@JoinColumn(name = "countryId")
Country country;
@ManyToOne
@JoinColumn(name = "brandId")
Brand brand;
} |
package org.androware.androbeans;
import android.app.Activity;
import android.content.ContextWrapper;
import org.androware.androbeans.utils.ResourceUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by jkirkley on 6/24/16.
*/
public class ObjectReaderFactory {
private static ObjectReaderFactory ourInstance = null;
public ContextWrapper contextWrapper;
public static ObjectReaderFactory getInstance() {
return getInstance(null);
}
public static ObjectReaderFactory getInstance(ContextWrapper contextWrapper) {
if(ourInstance == null){
if(contextWrapper == null) {
throw new IllegalArgumentException("Must intialize ObjectReaderFactory with an contextWrapper reference. ");
}
ourInstance = new ObjectReaderFactory(contextWrapper);
}
return ourInstance;
}
private ObjectReaderFactory(ContextWrapper contextWrapper) {
this.contextWrapper = contextWrapper;
}
public MapObjectReader makeMapReader(Map map, Class type, List<ObjectReadListener> objectReadListeners) throws ObjectReadException {
MapObjectReader mapObjectReader = new MapObjectReader(map, type);
if( objectReadListeners != null) {
mapObjectReader.setObjectReadListeners(objectReadListeners);
}
return mapObjectReader;
}
public MapObjectReader makeMapReader(Map map, Class type) throws ObjectReadException {
return makeMapReader(map, type, null);
}
public Object makeAndRunMapReader(Map map, Class type, List<ObjectReadListener> objectReadListeners) throws ObjectReadException {
MapObjectReader mapObjectReader = makeMapReader(map, type, objectReadListeners);
return mapObjectReader.read();
}
public Object makeAndRunMapReader(Map map, Class type) throws ObjectReadException {
return makeAndRunMapReader(map, type, null);
}
public Object makeAndRunInitializingMapReader(Map map, Class type) throws ObjectReadException {
List<ObjectReadListener> objectReadListeners = new ArrayList<>();
objectReadListeners.add(new InitializingReadListener());
return makeAndRunMapReader(map, type, objectReadListeners);
}
public JsonObjectReader makeJsonReader(String resourceName, String resourceGroup, Class type, List<ObjectReadListener> objectReadListeners) throws ObjectReadException {
JsonObjectReader jsonObjectReader = null;
try {
jsonObjectReader = new JsonObjectReader(ResourceUtils.getResourceInputStream(contextWrapper, resourceName, resourceGroup), type, null, objectReadListeners);
return jsonObjectReader;
} catch (IOException e) {
throw new ObjectReadException(e);
}
}
public JsonObjectReader makeJsonReader(String resourceName, Class type, List<ObjectReadListener> objectReadListeners) throws ObjectReadException {
return makeJsonReader(resourceName, "raw", type, objectReadListeners);
}
public Object makeAndRunJsonReader(String resourceName, Class type, List<ObjectReadListener> objectReadListeners) throws ObjectReadException {
JsonObjectReader JsonObjectReader = makeJsonReader(resourceName, type, objectReadListeners);
return JsonObjectReader.read();
}
public Object makeAndRunLinkedJsonReader(String resourceName, Class type) throws ObjectReadException {
List<ObjectReadListener> readListeners = new ArrayList<>();
readListeners.add(new LinkObjectReadListener());
return makeAndRunJsonReader(resourceName, type, readListeners);
}
public JsonObjectReader makeJsonReader(InputStream inputStream, Class type, List<ObjectReadListener> objectReadListeners) throws ObjectReadException {
JsonObjectReader jsonObjectReader = null;
try {
jsonObjectReader = new JsonObjectReader(inputStream, type, null, objectReadListeners);
return jsonObjectReader;
} catch (IOException e) {
throw new ObjectReadException(e);
}
}
public Object makeAndRunJsonReader(InputStream inputStream, Class type, List<ObjectReadListener> objectReadListeners) throws ObjectReadException {
JsonObjectReader JsonObjectReader = makeJsonReader(inputStream, type, objectReadListeners);
return JsonObjectReader.read();
}
public Object makeAndRunLinkedJsonReader(InputStream inputStream, Class type) throws ObjectReadException {
List<ObjectReadListener> readListeners = new ArrayList<>();
readListeners.add(new LinkObjectReadListener());
return makeAndRunJsonReader(inputStream, type, readListeners);
}
}
|
package f.star.iota.milk.ui.jdlingyu.jd;
import android.os.Bundle;
import f.star.iota.milk.base.MoreScrollImageFragment;
public class JDLINGYUFragment extends MoreScrollImageFragment<JDLINGYUPresenter, JDLINGYUAdapter> {
public static JDLINGYUFragment newInstance(String url) {
JDLINGYUFragment fragment = new JDLINGYUFragment();
Bundle bundle = new Bundle();
bundle.putString("base_url", url);
bundle.putString("page_suffix", "/");
fragment.setArguments(bundle);
return fragment;
}
@Override
protected JDLINGYUPresenter getPresenter() {
return new JDLINGYUPresenter(this);
}
@Override
protected JDLINGYUAdapter getAdapter() {
return new JDLINGYUAdapter();
}
}
|
package com.reservation.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.reservation.model.Traveler;
import com.reservation.service.TravelerService;
@RestController
@RequestMapping("/traveler")
public class TravelerController {
@Autowired
private TravelerService service;
@PreAuthorize("hasRole('ADMIN')")
@GetMapping(value = "/getAll")
public ResponseEntity<List<Traveler>> getAllTraveler() {
List<Traveler> list = service.getTraveler();
return ResponseEntity.ok(list);
}
@PreAuthorize("hasRole('ADMIN')")
@PostMapping(value = "/insertTraveler")
public ResponseEntity<Traveler> insertTraveler(@RequestBody Traveler request) {
Traveler trav = service.insertTraveler(request);
return ResponseEntity.ok(trav);
}
@PreAuthorize("hasRole('ADMIN')")
@GetMapping(value = "/getTravelerById")
public ResponseEntity<Optional<Traveler>> getTravelerById(@RequestBody Traveler request) {
Optional<Traveler> stock = service.getById(request);
if (stock.isPresent()) {
return ResponseEntity.ok(stock);
} else {
return ResponseEntity.ok(null);
}
}
@PreAuthorize("hasRole('ADMIN')")
@PostMapping(value = "updateTraveler")
public ResponseEntity<Traveler> updateTraveler( @RequestBody Traveler request) {
Optional<Traveler> stock = service.getById(request);
if (stock.isPresent()) {
Traveler traveler = service.insertTraveler(request);
traveler.setTravelerName(request.getTravelerName());
traveler.setTravelerSurname(request.getTravelerSurname());
traveler.setTravelerBirthdate(request.getTravelerBirthdate());
traveler.setTravelerEmail(request.getTravelerEmail());
traveler.setPhoneNr(request.getPhoneNr());
return ResponseEntity.ok(traveler);
}
return ResponseEntity.ok(null);
}
@PreAuthorize("hasRole('ADMIN')")
@PostMapping(value = "deleteTraveler")
public ResponseEntity<?> deleteTraveler(@RequestBody Traveler request){
Optional<Traveler> stock = service.getById(request);
if(stock.isPresent()) {
service.deleteTraveler(request);
return ResponseEntity.ok("Traveler deleted!");
}
else {
return ResponseEntity.ok("Record doesn't exist !");
}
}
/* Pagination */
@PreAuthorize("hasRole('ADMIN')")
@GetMapping(value = "/getPaged")
public ResponseEntity<List<Traveler>> getPagedTravelers(
@RequestParam(defaultValue = "0") Integer pageNo,
@RequestParam(defaultValue = "10") Integer pageSize) {
List<Traveler> list = service.getPagedTravelers(pageNo, pageSize);
return new ResponseEntity<List<Traveler>>(list, new HttpHeaders(), HttpStatus.OK);
}
/* Pagination with order*/
@PreAuthorize("hasRole('ADMIN')")
@GetMapping(value = "/getPagedWithOrder")
public ResponseEntity<List<Traveler>> getPagedTravelers(
@RequestParam(defaultValue = "0") Integer pageNo,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(defaultValue = "id") String sortBy) {
List<Traveler> list = service.getPagedTravelersWithOrder(pageNo, pageSize, sortBy);
return new ResponseEntity<List<Traveler>>(list, new HttpHeaders(), HttpStatus.OK);
}
}
|
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FormatadorUtil {
public static <T> T parseJSON(String json, Class clazz) {
ObjectMapper mapper = new ObjectMapper();
try {
return (T) mapper.readValue(json, clazz);
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException("parseJSON: " + ex.getMessage());
}
}
public static String encryptMD5(String text) {
if (text == null) {
return null;
}
return encryptMD5(text.getBytes());
}
public static String encryptMD5(byte[] text) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text);
BigInteger hash = new BigInteger(1, md.digest());
return org.apache.commons.lang.StringUtils.leftPad(hash.toString(16), 32, '0');
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
public static String encryptDES(String texto, String chave) {
try {
Cipher ecipher;
SecretKey key;
key = new SecretKeySpec(chave.getBytes("UTF-8"), 0, 8, "DES");
ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] utf8 = texto.getBytes("UTF8");
byte[] crip = ecipher.doFinal(utf8);
return new String(Hex.encodeHex(crip));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
throw new RuntimeException(ex);
}
}
public static String decryptDES(String texto, String chave) {
try {
Cipher dcipher;
SecretKey key;
key = new SecretKeySpec(chave.getBytes(), 0, 8, "DES");
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] dec = Hex.decodeHex(texto.toCharArray());
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (NoSuchAlgorithmException | NoSuchPaddingException | DecoderException | UnsupportedEncodingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
throw new RuntimeException(ex);
}
}
public static String convertToBase64(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
public static byte[] decodeBase64(String base64) {
return Base64.decodeBase64(base64);
}
public static String readResourceFile(String filename) throws IOException {
InputStream in = FormatadorUtil.class.getResourceAsStream(filename);
if (in == null) {
throw new FileNotFoundException("Arquivo '" + filename + "' inexistente em '/class/resources/'.");
}
return IOUtils.toString(in, Charset.forName("UTF-8"));
}
public static void addLogInfo(String s) {
System.out.println(s); //TODO: mudar para log4j ou equivalente.
}
public static void addLogError(String s, Exception... e) {
System.out.println(s); //TODO: mudar para log4j ou equivalente.
}
public static void addLogDebug(String s) {
System.out.println(s); //TODO: mudar para log4j ou equivalente.
}
}
|
package com.huangfu.assembly.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户类
*
* @author huangfu
* @date 2021年2月20日13:48:36
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String sex;
}
|
package zlk.cnm.view;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class InputView extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(this.getClass().getResource("/view/Input.fxml"));
Scene scene = new Scene(root,496,173);
primaryStage.initStyle(StageStyle.DECORATED);
primaryStage.setScene(scene);
primaryStage.setTitle("输入卡号");
primaryStage.show();
}
/**
* 显示输入界面
*/
public void showView(){
Application.launch(InputView.class);
}
}
|
package carnero.movement.ui;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import carnero.movement.common.graph.SplineGraph;
import carnero.movement.common.graph.SplinePath;
import carnero.movement.common.model.XY;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
import carnero.movement.R;
import carnero.movement.data.ModelDataContainer;
public abstract class AbstractGraphActivity extends AbstractBaseActivity {
protected ModelDataContainer mContainer;
protected SplinePath mYesterdayPath;
protected SplinePath mTodayPath;
protected final ArrayList<SplinePath> mPaths = new ArrayList<SplinePath>();
//
@InjectView(R.id.label)
TextView vLabel;
@InjectView(R.id.graph)
SplineGraph vGraph;
public void onCreate(Bundle state) {
super.onCreate(state);
final Intent intent = getIntent();
if (intent != null) {
mContainer = intent.getParcelableExtra("data");
}
setContentView(R.layout.notification_activity);
ButterKnife.inject(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null) {
mContainer = intent.getParcelableExtra("data");
}
}
protected void initGraph() {
mPaths.clear();
mPaths.add(mYesterdayPath);
mPaths.add(mTodayPath);
}
protected ArrayList<XY> getValues(ArrayList<Double> values) {
final ArrayList<XY> xys = new ArrayList<XY>();
for (int i = 0; i < values.size(); i ++) {
Double value = values.get(i);
XY point = new XY(
i,
value.floatValue()
);
xys.add(point);
}
return xys;
}
}
|
package com.scut.service;
import com.scut.entity.Book;
import com.scut.entity.Category;
import java.util.List;
import java.util.Map;
public interface BookService {
Book get(int id);
int getUserId(int id);
void add(Book book);
int count();
void delete(int id);
List<Book> list();
/**
* 用于myBookshelf页面,展示当前用户的图书
*
* @param uid 用户Id
* @param bookType 书的类型(图书信息1/求书信息0)
* @return 图书List
*/
List<Book> listByUserId(int uid, int bookType);
/**
* 用于展示具体某类图书
*
* @param bookType 书的类型(图书信息1/求书信息0)
* @param cid CategoryId
* @return 图书List
*/
List<Book> listByCategoryId(int bookType, int cid);
List<Book> listByBookType(int bookType);
/**
* @return 获取一个Key为Category,Value为对应当前Category的存放Book的List
*/
Map<Category, List<Book>> listByCategory();
void update(Book book);
List<Category> listCategory();
Category getCategory(int id);
void update(Category category);
//获取一个Key为CategoryId,Value为CategoryName的Map
Map<Integer, String> listByMap();
List<Book> getByKeyword(String keyword);
}
|
package testing.framework.generator;
import org.json.simple.JSONObject;
import testing.framework.Pair;
import testing.framework.TestCase;
import testing.framework.TestSuite;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* Created by mhotan_dev on 2/13/14.
*/
public class PairwiseTestSuiteGenerator extends TestSuiteGenerator {
public PairwiseTestSuiteGenerator() {
super();
}
public PairwiseTestSuiteGenerator(int arraySize, int rangeSize) {
super(arraySize, rangeSize);
}
@Override
protected Path getPath() {
try {
Path p = Paths.get(getClass().getClassLoader().getResource(".").toURI());
p = p.resolve("Pairwise-Test-Cases.txt");
return p;
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to find path for Random-Test-Cases.txt: "
+ e.getMessage());
}
}
@Override
protected TestSuite generateTestCases() {
List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < getArraySize(); ++i)
indexes.add(i);
// Create a pair of all indexes.
Collection<Pair<Integer>> pairs = getPairs(indexes);
// Random number generator
Random random = new Random();
// Set the default values.
Integer[] defaults = new Integer[getArraySize()];
for (int i = 0; i < defaults.length; ++i)
defaults[i] = random.nextInt(getIntRange());
// Set the default key.
Integer defaultKey = random.nextInt(getIntRange());
// Using a set ensures unique test cases.
Set<TestCase> cases = new HashSet<TestCase>();
for (Pair<Integer> p: pairs) {
// Create a collection of test cases varying
// the typical values of the elements assigned for the index determined by the pair.
cases.addAll(generateTestCase(defaults, defaultKey, p));
}
return new TestSuite(cases);
}
private static Integer[] copy(Integer[] original) {
Integer[] copy = new Integer[original.length];
for (int i = 0; i < copy.length; ++i)
copy[i] = original[i];
return copy;
}
/**
*
* @param defaults
* @param defaultKey
* @param pair
* @return
*/
private List<TestCase> generateTestCase(Integer[] defaults, Integer defaultKey,
Pair<Integer> pair) {
List<TestCase> cases = new ArrayList<TestCase>();
for (int i = 0; i < getIntRange(); ++i) {
for (int j = 0; j < getIntRange(); ++j) {
Integer[] defCopy = copy(defaults);
Integer key = defaultKey;
if (pair.getFirst() == getArraySize()) {
// If the first is the key
// Then use the second value as the index in the array.
key = i;
defCopy[pair.getSecond()] = j;
} else if (pair.getSecond() == getArraySize()) {
// If the second is the key
// Then use the first value as the index in the array.
defCopy[pair.getFirst()] = i;
key = j;
} else {
// The key is not used.
defCopy[pair.getFirst()] = i;
defCopy[pair.getSecond()] = j;
}
cases.add(new TestCase(defCopy, key));
}
}
return cases;
}
@Override
protected TestSuite load(JSONObject object) {
return new TestSuite(object);
}
private static <T> Collection<Pair<T>> getPairs(List<T> values) {
if (values == null)
throw new NullPointerException();
if (values.size() <= 1) // There can be no pairs.
return new ArrayList<Pair<T>>();
// Creating a set of pairs ensures uniqueness.
Set<Pair<T>> pairs = new HashSet<Pair<T>>();
for (int i = 0; i < values.size() - 1; ++i) {
for (int j = i + 1; j < values.size(); ++j) {
Pair<T> p = new Pair<T>(values.get(i), values.get(j));
if (pairs.contains(p))
throw new IllegalArgumentException("Attempting to add the same pair twice");
pairs.add(p);
}
}
// assert pairs.size() == numCombinations(values.size(), 2):
// "Number of combinations is incorrect";
return pairs;
}
private static long numCombinations(long n, long r) {
return factorial(n) / (factorial(r) * (factorial(n) - factorial(r)));
}
private static long factorial(long val) {
if (val <= 0) return 1;
long result = 1;
for (int i = 1; i <= val; i++) {
result = result * i;
}
return result;
}
}
|
package GroceryList;
import java.util.ArrayList;
public class GroceryList {
private ArrayList<String> groceryList = new ArrayList<>();
public void printGroceryList (){
System.out.println("You have " + groceryList.size() + " item(s) in the list:");
for (int i=0; i<groceryList.size(); i++){
System.out.println((i+1)+". " + groceryList.get(i));
}
System.out.println("=====================");
}
public void addItem (String item){
groceryList.add(item);
}
public void removeItem(int position){
System.out.print(groceryList.get(position-1) + " ");
groceryList.remove(position-1);
}
public void replaceItem(int position, String itemName){
groceryList.set(position,itemName);
}
public int getSize (){
return groceryList.size();
}
public String searchForItem (String itemName){
int position = groceryList.indexOf(itemName);
if(position >=0){
System.out.println("Item found on position: "+ (position+1));
return groceryList.get(position);
}
else return null;
}
}
|
package com.sinodynamic.hkgta.service.fms;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.sinodynamic.hkgta.dao.fms.FacilityTimeslotLogDao;
import com.sinodynamic.hkgta.dto.fms.FacilityTimeslotLogDto;
import com.sinodynamic.hkgta.entity.fms.FacilityTimeslotLog;
import com.sinodynamic.hkgta.service.ServiceBase;
@Service
public class FacilityTimeslotLogServiceImpl extends ServiceBase<FacilityTimeslotLog> implements
FacilityTimeslotLogService {
@Autowired
private FacilityTimeslotLogDao dao;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<FacilityTimeslotLogDto> getLogsByFacilityNo(String facilityType, Long facilityNo) {
List<FacilityTimeslotLog> entityList = dao.getByFacilityNo(facilityType, facilityNo);
return FacilityTimeslotLogDto.parseEntities(entityList);
}
}
|
package com.choco.rpc.service;
import com.choco.common.entity.Admin;
import com.choco.common.result.BaseResult;
import com.choco.rpc.vo.CartResult;
import com.choco.rpc.vo.CartVo;
/**
* Created by choco on 2021/1/7 14:11
*/
public interface CartService {
/**
* 添加购物车
* @param cartVo
* @param admin
* @return
*/
BaseResult addCart(CartVo cartVo, Admin admin);
/**
* 查询购物车数量
* @param admin
* @return
*/
Integer getCartNums(Admin admin);
/**
* 获取购物车list<cartVo>,计算总价
*/
CartResult getCartList(Admin admin);
/**
* 清除购物车
* @param admin
* @return
*/
BaseResult clearCart(Admin admin);
}
|
package com.nucpoop.covserver.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import com.nucpoop.covserver.model.covdata.CovData;
import com.nucpoop.covserver.model.covdata.CovDataLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nucpoop.covserver.model.SearchCondition;
public class Utils {
private final static Logger logger = LoggerFactory.getLogger(Utils.class);
private static CovData covData;
private static CovDataLocal covDataLocal;
public static CovData getResponseXML(StringBuilder sb) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(CovData.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
CovData covResponse;
covResponse = (CovData) unmarshaller.unmarshal(new StringReader(sb.toString()));
covResponse.toString();
return covResponse;
} catch (Exception e) {
return null;
}
}
public static CovDataLocal getLocalResponseXML(StringBuilder sb) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(CovDataLocal.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
CovDataLocal covResponse;
covResponse = (CovDataLocal) unmarshaller.unmarshal(new StringReader(sb.toString()));
covResponse.toString();
return covResponse;
} catch (Exception e) {
return null;
}
}
public static StringBuilder getCovData(SearchCondition condition) throws IOException {
final String SERVICE_KEY = "In700GpDhOczBBTNPW9EKqfV2XwqE5ff7638azwe2D9uetiEFgIRLsnK%2FIwzUVJc0xorUJOma6aR4bKJYRu7uQ%3D%3D";
final String ENCODING = "UTF-8";
StringBuilder urlBuilder = new StringBuilder(
"http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson");
urlBuilder.append("?" + URLEncoder.encode("ServiceKey", ENCODING) + "=" + SERVICE_KEY); /* Service Key */
urlBuilder.append("&" + URLEncoder.encode(condition.getPageNo() + "", ENCODING) + "="
+ URLEncoder.encode("1", ENCODING)); /* 페이지번호 */
urlBuilder.append("&" + URLEncoder.encode("numOfRows", ENCODING) + "="
+ URLEncoder.encode(condition.getNumberOfRows() + "", ENCODING)); /* 한 페이지 결과 수 */
urlBuilder.append("&" + URLEncoder.encode("startCreateDt", ENCODING) + "="
+ URLEncoder.encode(condition.getStartCreateDt(), ENCODING)); /* 검색할 생성일 범위의 시작 */
urlBuilder.append("&" + URLEncoder.encode("endCreateDt", ENCODING) + "="
+ URLEncoder.encode(condition.getEndCreateDt(), ENCODING)); /* 검색할 생성일 범위의 종료 */
URL url = new URL(urlBuilder.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
logger.info("Response code: " + conn.getResponseCode());
//System.out.println("Response code: " + conn.getResponseCode());
BufferedReader rd;
if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
//System.out.println("Response data: " + sb.toString());
logger.info("Response data: " + sb.toString());
covData = getResponseXML(sb);
return sb;
}
public static StringBuilder getCovDataLocal(SearchCondition condition) throws IOException {
final String SERVICE_KEY = "In700GpDhOczBBTNPW9EKqfV2XwqE5ff7638azwe2D9uetiEFgIRLsnK%2FIwzUVJc0xorUJOma6aR4bKJYRu7uQ%3D%3D";
final String ENCODING = "UTF-8";
StringBuilder urlBuilder = new StringBuilder(
"http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19SidoInfStateJson"); /* URL */
urlBuilder.append("?" + URLEncoder.encode("ServiceKey", ENCODING) + "=" + SERVICE_KEY); /* Service Key */
urlBuilder.append("&" + URLEncoder.encode("ServiceKey", ENCODING) + "="
+ URLEncoder.encode("-", ENCODING)); /* 공공데이터포털에서 받은 인증키 */
urlBuilder.append("&" + URLEncoder.encode(condition.getPageNo() + "", ENCODING) + "="
+ URLEncoder.encode("1", ENCODING)); /* 페이지번호 */
urlBuilder.append("&" + URLEncoder.encode("numOfRows", ENCODING) + "="
+ URLEncoder.encode(condition.getNumberOfRows() + "", ENCODING)); /* 한 페이지 결과 수 */
urlBuilder.append("&" + URLEncoder.encode("startCreateDt", ENCODING) + "="
+ URLEncoder.encode(condition.getStartCreateDt(), ENCODING)); /* 검색할 생성일 범위의 시작 */
urlBuilder.append("&" + URLEncoder.encode("endCreateDt", ENCODING) + "="
+ URLEncoder.encode(condition.getEndCreateDt(), ENCODING)); /* 검색할 생성일 범위의 종료 */
URL url = new URL(urlBuilder.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
logger.info("Response code: " + conn.getResponseCode());
//System.out.println("Response code: " + conn.getResponseCode());
BufferedReader rd;
if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
} else {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
//System.out.println("Response data: " + sb.toString());
logger.info("Response data: " + sb.toString());
covDataLocal = getLocalResponseXML(sb);
return sb;
}
public static CovData getCovData(){
return covData;
}
public static CovDataLocal getCovDataLocal(){
return covDataLocal;
}
}
|
package com.zuoqing.web.service;
import com.alibaba.dubbo.config.annotation.Reference;
import com.zuoqing.base.LoginService;
import com.zuoqing.base.entity.User;
import org.springframework.stereotype.Component;
/**
* Created by zuoqing on 2017/11/23.
*/
@Component("LoginConsumerService")
public class LoginConsumerService implements LoginService {
@Reference(version = "1.0.0")
LoginService loginService;
@Override
public String login() {
loginService.login();
return null;
}
@Override
public User findUser() {
return loginService.findUser();
}
}
|
/*
* LcmsManiseqController.java 1.00 2011-09-14
*
* Copyright (c) 2011 ???? Co. All Rights Reserved.
*
* This software is the confidential and proprietary information
* of um2m. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the license agreement
* you entered into with um2m.
*/
package egovframework.adm.lcms.cts.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.pag.controller.PagingManageController;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.com.utl.fcc.service.EgovStringUtil;
import egovframework.adm.lcms.cts.service.LcmsManiseqService;
import egovframework.adm.lcms.cts.domain.LcmsManiseq;
/**
* <pre>
* system :
* menu :
* source : LcmsManiseqController.java
* description :
* </pre>
* @version
* <pre>
* 1.0 2011-09-14 created by ?
* 1.1
* </pre>
*/
@Controller
public class LcmsManiseqController {
/** log */
protected static final Log LOG = LogFactory.getLog( LcmsManiseqController.class);
/** EgovPropertyService */
@Resource(name = "propertiesService")
protected EgovPropertyService propertiesService;
/** EgovMessageSource */
@Resource(name="egovMessageSource")
EgovMessageSource egovMessageSource;
/** PagingManageController */
@Resource(name = "pagingManageController")
private PagingManageController pagingManageController;
/** LcmsManiseq */
@Resource(name = "lcmsManiseqService")
private LcmsManiseqService lcmsManiseqService;
@RequestMapping(value="/adm/cts/LcmsManiseqPageList.do")
public String pageList(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
int totCnt = lcmsManiseqService.selectLcmsManiseqPageListTotCnt(commandMap);
pagingManageController.PagingManage(commandMap, model, totCnt);
List list = lcmsManiseqService.selectLcmsManiseqPageList(commandMap);
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "/adm/cts/LcmsManiseqPageList";
}
@RequestMapping(value="/adm/cts/LcmsManiseqList.do")
public String list(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
List list = lcmsManiseqService.selectLcmsManiseqList(commandMap);
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "/adm/cts/LcmsManiseqList";
}
@RequestMapping(value="/adm/cts/LcmsManiseqView.do")
public String view(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
Map output = new HashMap();
output.putAll((Map)lcmsManiseqService.selectLcmsManiseq(commandMap));
model.addAttribute("output",output);
model.addAllAttributes(commandMap);
return "/adm/cts/LcmsManiseqView";
}
@RequestMapping(value="/adm/cts/LcmsManiseqInsertForm.do")
public String insertForm(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
model.addAllAttributes(commandMap);
return "/adm/cts/LcmsManiseqInsert";
}
@RequestMapping(value="/adm/cts/LcmsManiseqInsert.do")
public String insert(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
String resultMsg = ""; String forwardUrl = "";
Object output = lcmsManiseqService.insertLcmsManiseq( commandMap);
commandMap.put("output"," output");
resultMsg = egovMessageSource.getMessage("success.common.insert");
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
forwardUrl = "forward:/adm/cts/LcmsManiseqPageList.do";
return forwardUrl;
}
@RequestMapping(value="/adm/cts/LcmsManiseqUdateForm.do")
public String updateForm(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
Map output = new HashMap(); output.putAll((Map)lcmsManiseqService.selectLcmsManiseq(commandMap));
model.addAttribute("output",output);
model.addAllAttributes(commandMap);
return "/adm/cts/LcmsManiseqUpdate";
}
@RequestMapping(value="/adm/cts/LcmsManiseqUpdate.do")
public String update(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
String resultMsg = "";
String forwardUrl = "";
int result = lcmsManiseqService.updateLcmsManiseq( commandMap);
if(result > 0){
resultMsg = egovMessageSource.getMessage("success.common.update");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.update");
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
forwardUrl = "forward:/adm/cts/LcmsManiseqUdateForm.do";
return forwardUrl;
}
@RequestMapping(value="/adm/cts/LcmsManiseqDelete.do")
public String delete(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
String resultMsg = "";
String forwardUrl = "";
int result = lcmsManiseqService.deleteLcmsManiseq( commandMap);
if(result > 0){
resultMsg = egovMessageSource.getMessage("success.common.delete");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.delete");
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
forwardUrl = "forward:/adm/cts/LcmsManiseqPageListForm.do";
return forwardUrl;
}
@RequestMapping(value="/adm/cts/LcmsManiseqDelete.do")
public String deleteAll(
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> commandMap, ModelMap model) throws Exception {
String resultMsg = "";
String forwardUrl = "";
commandMap.put("seq", EgovStringUtil.getStringSequence(commandMap, "chk"));
int result = lcmsManiseqService.deleteLcmsManiseqAll( commandMap);
if(result > 0){
resultMsg = egovMessageSource.getMessage("success.common.delete");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.delete");
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
forwardUrl = "forward:/adm/cts/LcmsManiseqPageListForm.do";
return forwardUrl;
}
}
|
/*
CIS 331 Section 2
Group Project Part 1.
Authors: Zach Beatty, Eric Carter, Mercy Clemente, Michael Corcoran & Troy Goddard
*/
package Project331;
public class Contractor extends Customer
{
private int contractorID = 2000;
public String contractorName;
public long contractorNumber;
public String contractorAddress;
Customer firstName;
public Contractor (String firstName, String lastName, String city, String street,
String state, int zip, String contractorName, long contractorNumber,
String contractorAddress)
{
super(firstName, lastName, city, state, street, zip, contractorNumber);
this.contractorName = contractorName;
this.contractorNumber = contractorNumber;
this.contractorAddress = contractorAddress;
this.contractorID++;
}
//setting the contractor company name
public void setContractorName (String contractorName)
{
this.contractorName = contractorName;
}
public String setContractorAddress( String contractingAddress)
{
contractingAddress ="";
contractingAddress += this.street + ", ";
contractingAddress += this.city + ", ";
contractingAddress += this.state + ", ";
contractingAddress += this.zip;
return contractingAddress;
}
//setting contractor company number
public void setContractorNumber (long contractorNumber)
{
this.contractorNumber = contractorNumber;
}
}
|
package com.jic.libin.leaderus.study005;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;
/**
* Created by andylee on 17/1/8.
*/
public class BinleeStudy00503 {
private static final int CPU_CORE_SIZE = 10;
private static final int INRC_COUNT = 10_000_000;
public static void main(String[] args) throws InterruptedException {
NormalCounter normalCounter = new NormalCounter();
CountDownLatch latch1 = new CountDownLatch(CPU_CORE_SIZE);
Runnable normalRunnable = () -> {
IntStream.range(0, INRC_COUNT).forEach(i -> {
normalCounter.incr();
});
System.out.println("NormalCounter:" + Thread.currentThread().getName() + ":" + normalCounter.getCurValue());
latch1.countDown();
};
long st1 = System.currentTimeMillis();
IntStream.range(0, CPU_CORE_SIZE).forEach(i -> {
new Thread(normalRunnable).start();
});
latch1.await();
System.out.println("NormalCounter 花费时间:" + (System.currentTimeMillis() - st1) + "ms");
SynchCounter synchCounter = new SynchCounter();
CountDownLatch latch2 = new CountDownLatch(CPU_CORE_SIZE);
Runnable synchRunnable = () -> {
IntStream.range(0, INRC_COUNT).forEach(i -> {
synchCounter.incr();
});
System.out.println("SynchCounter:" + Thread.currentThread().getName() + ":" + synchCounter.getCurValue());
latch2.countDown();
};
long st2 = System.currentTimeMillis();
IntStream.range(0, CPU_CORE_SIZE).forEach(i -> {
new Thread(synchRunnable).start();
});
latch2.await();
System.out.println("SynchCounter 花费时间:" + (System.currentTimeMillis() - st2) + "ms");
VolatileCounter volatileCounter = new VolatileCounter();
CountDownLatch latch3 = new CountDownLatch(CPU_CORE_SIZE);
Runnable volatileRunnable = () -> {
IntStream.range(0, INRC_COUNT).forEach(i -> {
volatileCounter.incr();
});
System.out.println("VolatileCounter:" + Thread.currentThread().getName() + ":" + volatileCounter.getCurValue());
latch3.countDown();
};
long st3 = System.currentTimeMillis();
IntStream.range(0, CPU_CORE_SIZE).forEach(i -> {
new Thread(volatileRunnable).start();
});
latch3.await();
System.out.println("VolatileCounter 花费时间:" + (System.currentTimeMillis() - st3) + "ms");
AtomicCounter atomicCounter = new AtomicCounter();
CountDownLatch latch4 = new CountDownLatch(CPU_CORE_SIZE);
Runnable atomicRunnable = () -> {
IntStream.range(0, INRC_COUNT).forEach(i -> {
atomicCounter.incr();
});
System.out.println("AtomicCounter:" + Thread.currentThread().getName() + ":" + atomicCounter.getCurValue());
latch4.countDown();
};
long st4 = System.currentTimeMillis();
IntStream.range(0, CPU_CORE_SIZE).forEach(i -> {
new Thread(atomicRunnable).start();
});
latch4.await();
System.out.println("AtomicCounter 花费时间:" + (System.currentTimeMillis() - st4) + "ms");
AdderCounter adderCounter = new AdderCounter();
CountDownLatch latch5 = new CountDownLatch(CPU_CORE_SIZE);
Runnable adderRunnable = () -> {
IntStream.range(0, INRC_COUNT).forEach(i -> {
adderCounter.incr();
});
System.out.println("AdderCounter:" + Thread.currentThread().getName() + ":" + adderCounter.getCurValue());
latch5.countDown();
};
long st5 = System.currentTimeMillis();
IntStream.range(0, CPU_CORE_SIZE).forEach(i -> {
new Thread(adderRunnable).start();
});
latch5.await();
System.out.println("AdderCounter 花费时间:" + (System.currentTimeMillis() - st5) + "ms");
int sum = 0;
long st6 = System.currentTimeMillis();
for (int i = 0; i < 100_000_000; i++) {
sum += 1;
}
System.out.println(sum);
System.out.println("AdderCounter 花费时间:" + (System.currentTimeMillis() - st6) + "ms");
}
}
|
package com.planet.husini;
import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import javax.inject.Inject;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
Thread tmp = null;
String xml = "";
@Inject
Retrofit mRetrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testPermission();
// tmp = new ReadLog(this);
// tmp.start();
//尝试调用logcat去监听去电时的电话状态
// new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(2000);
// readLog();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }).start();
}
private void showDialogTest() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("呼死你")
.setMessage("赶紧点")
.setPositiveButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showDialogTest();
}
});
builder.show();
}
private void testPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
Log.e("============", "shouldShowRequestPermissionRationale");
// showDialogTest();
} else
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 100);
} else {
callPhone();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callPhone();
} else {
testPermission();
Log.e("============", "else");
// ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// tmp.interrupt();
// tmp = null;
isRuning = false;
}
/**
* 拨打电话
*/
private void callPhone() {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "**"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// // TODO: Consider calling
// // ActivityCompat#requestPermissions
// // here to request the missing permissions, and then overriding
// // public void onRequestPermissionsResult(int requestCode, String[] permissions,
// // int[] grantResults)
// // to handle the case where the user grants the permission. See the documentation
// // for ActivityCompat#requestPermissions for more details.
// return;
// }
startActivity(intent);
}
private static final int WHAT_NEXT_LOG = 778;
boolean isRuning = true;
/**
* 读取logcat信息,尝试筛选打电话的log
*/
private void readLog() {
// new Thread(new Runnable() {
// @Override
// public void run() {
Process logcatProcess = null;
BufferedReader bufferedReader = null;
StringBuilder log = new StringBuilder();
String line;
String[] catchParams = {"logcat", "-b system", "-b events", "-b main", "-b radio", "Telecom:I *:S"};
try {
while (isRuning) {
logcatProcess = Runtime.getRuntime().exec(catchParams);
bufferedReader = new BufferedReader(new InputStreamReader(logcatProcess.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
Message message = mHandler.obtainMessage();
message.what = WHAT_NEXT_LOG;
message.obj = line;
mHandler.sendMessage(message);
}
}
if(log.toString().contains("MiuiCallsManager"))
Log.e("===MiuiCallsManager===", "111");
// ArrayList commandLine = new ArrayList();
// commandLine.add( "logcat");
// String[] catchParams = {"logcat", "Telecom:I *:S"};
// ShellUtils.CommandResult result = ShellUtils.execCommand(catchParams, false, true);
// if(result.successMsg.contains("MiuiCallsManager"))
// Log.e("===============", result.successMsg);
} catch (Exception e) {
e.printStackTrace();
}
// }
// }).start();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case WHAT_NEXT_LOG:
String line = (String) msg.obj;
// if(line.contains("MiuiCallsManager"))
Log.e("===============", line);
// else
break;
}
}
};
/**
*显示RAM的可用和总容量
*/
private void showRAMInfo(){
ActivityManager am=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mi=new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
String[] available=fileSize(mi.availMem);
String[] total=fileSize(mi.totalMem);
// Log.e("========", "RAM "+available[0]+available[1]+"/"+total[0]+total[1]);
Log.e("========", Formatter.formatFileSize(MainActivity.this, mi.totalMem));
}
/**
*显示ROM的可用和总容量 获取手机内部存储空间
*/
private void showROMInfo(){
File file= Environment.getDataDirectory();
StatFs statFs=new StatFs(file.getPath());
long blockSize=statFs.getBlockSize();
long totalBlocks=statFs.getBlockCount();
long availableBlocks=statFs.getAvailableBlocks();
String[] total=fileSize(totalBlocks*blockSize);
String[] available=fileSize(availableBlocks*blockSize);
// Log.e("========", "ROM "+available[0]+available[1]+"/"+total[0]+total[1]);
Log.e("========", Formatter.formatFileSize(MainActivity.this, blockSize * totalBlocks));
}
/**
*显示SD卡的可用和总容量,获取手机外部存储空间
*/
private void showSDInfo(){
if(Environment.getExternalStorageState().equals
(Environment.MEDIA_MOUNTED)){//sd卡是否可用
File file=Environment.getExternalStorageDirectory();
StatFs statFs=new StatFs(file.getPath());
long blockSize=statFs.getBlockSize();
long totalBlocks=statFs.getBlockCount();
long availableBlocks=statFs.getAvailableBlocks();
String[] total=fileSize(totalBlocks*blockSize);
String[] available=fileSize(availableBlocks*blockSize);
// Log.e("===========", "SD "+available[0]+available[1]+"/"+total[0]+total[1]);
Log.e("===========", Formatter.formatFileSize(MainActivity.this, blockSize * totalBlocks));
}else {
Log.e("============", "SD CARD 已删除");
}
}
/*返回为字符串数组[0]为大小[1]为单位KB或者MB*/
private String[] fileSize(long size){
float sizef = size;
int kmg = 1024;
String str="";
if(sizef>=kmg ){
str="KB";
sizef/=kmg ;
if(sizef>=kmg ){
str="MB";
sizef/=kmg ;
if(sizef>=kmg){
str="G";
sizef/=kmg;
}
}
}
/*将每3个数字用,分隔如:1,000*/
DecimalFormat formatter=new DecimalFormat();
formatter.setGroupingSize(3);
String result[]=new String[2];
result[0]=formatter.format(size);
result[1]=str;
return result;
}
}
|
package oo.heranca.visibilidade;
import oo.heranca.desafio.Carro;
import oo.heranca.desafio.Ferrari;
import oo.heranca.desafio.Fusca;
public class CarroTeste {
public static void main(String[] args) {
Carro f1 = new Fusca();
Carro f2 = new Fusca();
Ferrari c1 = new Ferrari();
Carro c2 = new Ferrari();
f1.acelerar();
f1.acelerar();
System.out.println(f1.toString());
f2.freiar();
System.out.println(f2.toString());
c1.acelerar();
c1.desligarAr();
c1.ligarTurbo();
System.out.println(c1.velocidadeDoAr());
System.out.println(c1.toString());
c2.freiar();
c2.freiar();
c2.freiar();
c2.freiar();
System.out.println(c2.toString());
}
}
|
package com.esum.comp.ws.inbound;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.apache.cxf.jaxws.support.JaxWsEndpointImpl;
import org.apache.cxf.transport.servlet.CXFNonSpringServlet;
import org.apache.cxf.ws.addressing.WSAddressingFeature;
import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.framework.net.http.server.tomcat.security.HTTPAuthValidator;
/**
* WebService Service Servlet.
*/
public class WsInboundServlet extends CXFNonSpringServlet {
private Logger logger = LoggerFactory.getLogger(WsInboundServlet.class);
private String traceId;
private boolean useHttpAuth = false;
private String serviceName;
private Class<?> serviceClass;
private Object serviceBean;
private WsInboundHandler inboundHandler;
private boolean useWSAddressing = false;
private Map<String, Object> inProps;
private Map<String, Object> outProps;
protected void invoke(HttpServletRequest request, HttpServletResponse response) throws ServletException {
String httpMethod = (String)request.getMethod();
if(logger.isDebugEnabled())
logger.debug(traceId+"Request({}), Request method is {}", request.getRemoteAddr(), httpMethod);
if(isUseHttpAuth()) {
try {
String authResult = HTTPAuthValidator.getInstance().validate(request, response);
if(authResult.equals(HTTPAuthValidator.STATUS_UNAUTHORIZED)) {
logger.debug(traceId+"Http request authentication validation result : "+false);
return;
}
} catch (Exception e) {
logger.error(traceId+"Http Authorization error.", e);
throw new ServletException(e);
}
}
super.invoke(request, response);
}
protected void loadBus(ServletConfig sc) {
super.loadBus(sc);
logger.debug(traceId+"Creating WebService.");
JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
try {
factory.setBus(getBus());
factory.setServiceClass(serviceClass);
factory.setServiceBean(serviceBean);
BeanUtils.setProperty(serviceBean, "inboundHandler", this.getInboundHandler());
if(logger.isDebugEnabled()) {
logger.debug(traceId+"Set the Logging In/Out Interceptor.");
getBus().getInInterceptors().add(new LoggingInInterceptor());
getBus().getOutInterceptors().add(new LoggingOutInterceptor());
}
} catch (Exception e) {
logger.error(traceId+"'"+serviceClass+"' class not found", e);
return;
}
factory.setAddress("/" + serviceName);
factory.create();
if(isUseWSAddressing()) {
logger.debug(traceId+"Set the WS-Addressing Feature.");
((JaxWsEndpointImpl)factory.getServer().getEndpoint()).getFeatures().add(new WSAddressingFeature());
}
if(this.inProps!=null) {
logger.debug(traceId+"Set the IN WS-Security.");
WSS4JInInterceptor inhandler = new WSS4JInInterceptor(inProps);
factory.getServer().getEndpoint().getInInterceptors().add(inhandler);
}
if(this.outProps!=null) {
logger.debug(traceId+"Set the OUT WS-Security");
WSS4JOutInterceptor outhandler = new WSS4JOutInterceptor(outProps);
factory.getServer().getEndpoint().getOutInterceptors().add(outhandler);
}
logger.debug(traceId+"WebService Provider creating completed.");
}
public String getTraceId() {
return traceId;
}
public void setTraceId(String traceId) {
this.traceId = traceId;
}
public Class<?> getServiceClass() {
return serviceClass;
}
public void setServiceClass(Class<?> serviceClass) {
this.serviceClass = serviceClass;
}
public Object getServiceBean() {
return serviceBean;
}
public void setServiceBean(Object serviceBean) {
this.serviceBean = serviceBean;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public boolean isUseHttpAuth() {
return useHttpAuth;
}
public void setUseHttpAuth(boolean useHttpAuth) {
this.useHttpAuth = useHttpAuth;
}
public Map<String, Object> getInProps() {
return inProps;
}
public void setInProps(Map<String, Object> inProps) {
this.inProps = inProps;
}
public Map<String, Object> getOutProps() {
return outProps;
}
public void setOutProps(Map<String, Object> outProps) {
this.outProps = outProps;
}
public boolean isUseWSAddressing() {
return useWSAddressing;
}
public void setUseWSAddressing(boolean useWSAddressing) {
this.useWSAddressing = useWSAddressing;
}
public WsInboundHandler getInboundHandler() {
return inboundHandler;
}
public void setInboundHandler(WsInboundHandler inboundHandler) {
this.inboundHandler = inboundHandler;
}
}
|
package com.design.FactoryVSStrategy.strategy;
/*
* 来源: https://www.jianshu.com/p/78c4d93fab87 https://github.com/nezha/DesignPatterns
* 重点祥述: https://www.imooc.com/article/11675#comment
* 策略模式UML图.png:
* Strategy(抽象策略角色):封装了 每个算法必须有的算法和属性,由Context来调度。
* StrategyA(具体策略角色):实现了抽象策略定义的接口。
* Context(封装角色):将策略封装起来,屏蔽了调用者直接访问具体策略。
* 意图:定义一系列算法,把他们一个个封装起来,并且使他们相互可以替换。本模式使得算法可以独立于使用它的客户而变化
*
* 拓展:https://nicky-chen.github.io/2018/05/06/strategy/
*/
public class ClientStrategy {
public static void main(String args[]) {
ContextFactory add = new ContextFactory(new AddStrategy());
int addvalue = add.calculate(1, 1);
System.out.println(addvalue);
ContextFactory sub = new ContextFactory(new SubStrategy());
int subvalue = sub.calculate(1, 1);
System.out.println(subvalue);
}
}
|
package com.show.comm.utils;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Josn工具类
*
* <pre>
* fasterxml.jackson
* 对象转为json时:
* 属性忽略:@JsonIgnore
* 属性命名:@JsonProperty("alias")
* </pre>
*
* @author heyuhua
* @date 2018年2月26日
*/
public final class JsonUtils {
/** Mapper */
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.setDateFormat(DateUtils.DF_TIME);
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY, false);
MAPPER.configure(DeserializationFeature.WRAP_EXCEPTIONS, false);
MAPPER.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
// MAPPER.setVisibility(MAPPER.getVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE));
}
/**
* 对象转换为json String
*
* @param obj
* 对象
* @return json/null
*/
public static String to(Object obj) {
return toJson(obj);
}
/**
* 对象转换为json String
*
* @param obj
* 对象
* @return json/null
*/
public static String toJson(Object obj) {
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
}
return null;
}
/**
* 对象转换为json byte
*
* @param obj
* 对象
* @return json byte[]/null
*/
public static byte[] toJsonBytes(Object obj) {
try {
return MAPPER.writeValueAsBytes(obj);
} catch (JsonProcessingException e) {
}
return null;
}
/**
* json解析为Object
*
* @param json
* json
* @param valueType
* Object
* @return Object/null
*/
public static <T> T parse(byte[] json, Class<T> valueType) {
if (null != json) {
try {
return MAPPER.readValue(json, valueType);
} catch (IOException e) {
}
}
return null;
}
/**
* json解析为Object
*
* @param json
* json
* @param valueType
* Object
* @return Object/null
*/
public static <T> T parse(String json, Class<T> valueType) {
if (null != json) {
try {
return MAPPER.readValue(json, valueType);
} catch (IOException e) {
}
}
return null;
}
/**
* json解析为Object
*
* @param json
* json
* @param valueType
* Object
* @return Object/null
*/
public static <T> List<T> parseArray(byte[] json, Class<T> valueType) {
if (null != json) {
try {
JavaType t = MAPPER.getTypeFactory().constructParametricType(List.class, valueType);
return MAPPER.readValue(json, t);
} catch (IOException e) {
}
}
return null;
}
/**
* json解析为Object
*
* @param json
* json
* @param valueType
* Object
* @return Object/null
*/
public static <T> List<T> parseArray(String json, Class<T> valueType) {
if (null != json) {
try {
JavaType t = MAPPER.getTypeFactory().constructParametricType(List.class, valueType);
return MAPPER.readValue(json, t);
} catch (IOException e) {
}
}
return null;
}
/**
* json解析为Map
*
* @param json
* json
* @return Map<String,Object>/null
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> parseMap(byte[] json) {
if (null != json) {
try {
return MAPPER.readValue(json, Map.class);
} catch (IOException e) {
}
}
return null;
}
/**
* json解析为Map
*
* @param json
* json
* @return Map<String,Object>/null
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> parseMap(String json) {
if (null != json) {
try {
return MAPPER.readValue(json, Map.class);
} catch (IOException e) {
}
}
return null;
}
}
|
package cz.metacentrum.perun.spRegistration.common.models;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class LinkCode {
private final String randomString = UUID.randomUUID().toString();
private String hash;
private String recipientEmail;
private String senderName;
private String senderEmail;
private Timestamp expiresAt;
private Long facilityId;
private Long requestId;
public void setExpiresAt(Timestamp expiresAt) {
this.expiresAt = expiresAt;
}
public void setExpiresAt(int plusDays, int plusHours) {
this.expiresAt = new Timestamp(LocalDateTime.now()
.plusDays(plusDays)
.plusHours(plusHours)
.toInstant(ZoneOffset.UTC).toEpochMilli());
}
}
|
package com.kacperwozniak.credit.service;
import com.kacperwozniak.credit.model.Credit;
import com.kacperwozniak.credit.model.Customer;
import com.kacperwozniak.credit.model.Product;
import com.kacperwozniak.credit.repository.CreditRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Service implementation ICreditService
*/
@Service
public class CreditService implements ICreditService{
@Autowired
CreditRepository creditRepository;
@Autowired
RestTemplate restTemplate;
List<Credit> creditList;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Override
public List<Credit> getCreditsList(){
creditList = creditRepository.findAll();
for (Credit credit : creditList){
credit.setCustomer(restTemplate.getForObject("http://localhost:8070/restapi/customer/getCustomer/" + credit.getCreditId(), Customer.class));
credit.setProduct(restTemplate.getForObject("http://localhost:8090/restapi/product/getProduct/" + credit.getCreditId(),Product.class));
}
return creditList;
}
@Override
public void createCredit(Credit credit){
int generatedCreditID = createCreditNumber();
credit.setCreditId(generatedCreditID);
credit.getCustomer().setCreditId(generatedCreditID);
credit.getProduct().setCreditId(generatedCreditID);
creditRepository.save(credit);
restTemplate.postForObject("http://localhost:8070/restapi/customer/createCustomer",credit.getCustomer(), Customer.class);
restTemplate.postForObject("http://localhost:8090/restapi/product/createProduct", credit.getProduct(), Product.class);
}
/**
* Method finds max ID from List of all Credits and creates new ID from max value +1
* @return new creditID
*/
private int createCreditNumber(){
creditList = creditRepository.findAll();
if (creditList.isEmpty())
return 1;
else
return Collections.max(creditList, Comparator.comparing(c->c.getCreditId())).getCreditId() + 1;
}
}
|
package com.xnarum.thonline.recon;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.persistence.Column;
import javax.persistence.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xnarum.bi.common.QueryInfo;
import com.xnarum.thonline.recon.entity.THIJARI_RECON_SUMMARY;
public class ReconSummaryLoader extends ReconTransactionHandler {
private static Logger logger = LoggerFactory.getLogger(ReconSummaryLoader.class);
public void insert(THIJARI_RECON_SUMMARY summary) throws Exception {
Connection con = null;
PreparedStatement pstmt = null;
Field [] flds = THIJARI_RECON_SUMMARY.class.getDeclaredFields();
try {
Table table = THIJARI_RECON_SUMMARY.class.getAnnotation(Table.class);
QueryInfo qi2 =
QueryGenerator.generateQueryInfo(new THIJARI_RECON_SUMMARY(), THIJARI_RECON_SUMMARY.class, table.name(), QueryInfo.QUERY_INSERT, null, null, null);
con = getMysqlConnection();
pstmt = con.prepareStatement(qi2.getQuery());
int current = 0;
int columnIndex = 0;
for ( Field f : flds ) {
if ( f.getModifiers() == (Modifier.STATIC & Modifier.FINAL) ) {
continue;
}
Column c = f.getAnnotation(Column.class);
if ( c == null ) {
continue;
}
if ( !f.isAccessible() ) {
f.setAccessible(true);
}
logger.debug("Set value for {} {} {}", columnIndex, c.name(), f.get(summary));
pstmt.setObject(++columnIndex, f.get(summary));
}
int count = pstmt.executeUpdate();
if ( count < 1 ) {
throw new Exception( "Insert count is less than 1 - " + summary.getBusinessDate());
}
con.commit();
}catch( Exception ex ) {
logger.error("Failed to save audit log", ex);
try {
con.rollback();
}catch( Exception exx ) {
}
throw ex;
}finally {
if ( pstmt != null ) {
try{ pstmt.close(); }catch( Exception e ) {}
}
if ( con != null ) {
try {con.close();}catch( Exception ex ) {
}
}
}
}
}
|
package practicas2parcial;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class MergeSortForkJoin {
public void sort(Integer[] a) {
Integer[] helper = new Integer[a.length];
ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.invoke(new MergeSortTask (a, helper, 0, a.length-1));
}
private class MergeSortTask extends RecursiveAction{
private static final long serialVersionUID = -749935388568367268L;
private final Integer[] a;
private final Integer[] helper;
private final int lo;
private final int hi;
public MergeSortTask(Integer[] a, Integer[] helper, int lo, int hi){
this.a = a;
this.helper = helper;
this.lo = lo;
this.hi = hi;
}
@Override
protected void compute() {
if (lo < hi) {
int mid = lo + (hi-lo)/2;
MergeSortTask left = new MergeSortTask (a, helper, lo, mid);
MergeSortTask right = new MergeSortTask (a, helper, mid+1, hi);
invokeAll(left, right);
merge(this.a, this.helper, this.lo, mid, this.hi);
}
}
private void merge(Integer[] a, Integer[] helper, int lo, int mid, int hi) {
for (int i = lo; i <= hi; i++) {
helper[i] = a[i];
}
int i = lo;
int j = mid + 1;
int k = lo;
while (i <= mid && j <= hi) {
if (helper[i] <= helper[j]) {
a[k] = helper[i];
i++;
} else {
a[k] = helper[j];
j++;
}
k++;
}
while (i <= mid) {
a[k] = helper[i];
k++;
i++;
}
}
}
}
|
/*
*
* * Copyright 2020. Huawei Technologies Co., Ltd. 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.huawei.myhealth.java.ui.fragments;
import android.app.DatePickerDialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import com.huawei.myhealth.R;
import com.huawei.myhealth.databinding.FragmentInsightsBinding;
import com.huawei.myhealth.java.database.entity.FoodNutrientsInsight;
import com.huawei.myhealth.java.database.viewmodel.FoodNutrientsViewModel;
import com.huawei.myhealth.java.utils.DefaultValues;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* @since 2020
* @author Huawei DTSE India
*/
public class InsightsFragment extends Fragment {
private FragmentInsightsBinding binding;
private FoodNutrientsViewModel foodNutrientsViewModel;
private String selectedDateStr = null;
private List<String> calorieTakenTodayList = new ArrayList();
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentInsightsBinding.inflate(inflater, container, false);
View view = binding.getRoot();
foodNutrientsViewModel = new ViewModelProvider(this).get(FoodNutrientsViewModel.class);
// initialize
init(view);
// Receiving Data Via Observer
foodNutrientsViewModel.allFoodList().observe(getViewLifecycleOwner(), foodNutrientsInsights -> {
for (FoodNutrientsInsight calorieInEachFood : foodNutrientsInsights) {
calorieTakenTodayList.add(calorieInEachFood.getProtein());
calorieTakenTodayList.add(calorieInEachFood.getTotalLipidFat());
calorieTakenTodayList.add(calorieInEachFood.getCarbohydrate());
calorieTakenTodayList.add(calorieInEachFood.getFiberTotalDietary());
updateUI();
}
});
return view;
}
private void init(View view) {
//set current date to calendar
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(getResources().getString(R.string.date_pattern));
String currentDateAndTime = simpleDateFormat.format(new Date());
binding.tvDate.setText(currentDateAndTime);
binding.rlCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int y = cal.get(Calendar.YEAR);
int m = cal.get(Calendar.MONTH);
int d = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String myFormat = getResources().getString(R.string.date_pattern); // mention the format you need
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
// Display Selected date in textbox
binding.tvDate.setText("" + sdf.format(cal.getTime()));
selectedDateStr = "" + sdf.format(cal.getTime());
String selectedDateStr1 = sdf.format(new Date());
if (selectedDateStr1.equals(selectedDateStr)) {
// Receiving Data Via Observer
foodNutrientsViewModel.allFoodList().observe(getViewLifecycleOwner(), foodNutrientsInsights -> {
for (FoodNutrientsInsight calorieInEachFood : foodNutrientsInsights) {
calorieTakenTodayList.add(calorieInEachFood.getProtein());
calorieTakenTodayList.add(calorieInEachFood.getTotalLipidFat());
calorieTakenTodayList.add(calorieInEachFood.getCarbohydrate());
calorieTakenTodayList.add(calorieInEachFood.getFiberTotalDietary());
}
//update the UI
updateUI();
});
} else {
calorieTakenTodayList.clear();
//update the UI
updateUI();
}
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
});
}
private void updateUI() {
if ((calorieTakenTodayList != null) && (calorieTakenTodayList.size() > 0)) {
binding.tvProteinQ.setText("" + calorieTakenTodayList.get(0) + getResources().getString(R.string.g));
binding.tvFatQ.setText("" + calorieTakenTodayList.get(1) + getResources().getString(R.string.g));
binding.tvCarbsQ.setText("" + calorieTakenTodayList.get(2) + getResources().getString(R.string.g));
binding.tvFiberQ.setText("" + calorieTakenTodayList.get(3) + getResources().getString(R.string.g));
// set percentage
int protein_percentage = 0;
protein_percentage = (int) (((Double.parseDouble(calorieTakenTodayList.get(0))) * DefaultValues.VALUE_10) / DefaultValues.VALUE_2);
protein_percentage = protein_percentage;
binding.tvProteinPercentage.setText(String.valueOf(protein_percentage) + getResources().getString(R.string.percentage));
binding.pbProtein.setProgress(protein_percentage);
int fat_percentage = 0;
fat_percentage = (int) (((Double.parseDouble(calorieTakenTodayList.get(1))) * DefaultValues.VALUE_16) / DefaultValues.VALUE_2);
binding.tvFatPercentage.setText(String.valueOf(fat_percentage) + getResources().getString(R.string.percentage));
binding.pbFat.setProgress(fat_percentage);
int carbs_percentage = 0;
carbs_percentage = (int) (((Double.parseDouble(calorieTakenTodayList.get(2))) * DefaultValues.VALUE_7) / DefaultValues.VALUE_2);
binding.tvCarbsPercentage.setText(String.valueOf(carbs_percentage) + getResources().getString(R.string.percentage));
binding.pbCarbs.setProgress(carbs_percentage);
int fiber_percentage = 0;
fiber_percentage = (int) (((Double.parseDouble(calorieTakenTodayList.get(3))) * DefaultValues.VALUE_69) / DefaultValues.VALUE_2);
binding.tvFiberPercentage.setText(fat_percentage + getResources().getString(R.string.percentage));
binding.pbFiber.setProgress(fiber_percentage);
} else {
binding.tvProteinQ.setText(getResources().getString(R.string.zerog));
binding.tvFatQ.setText(getResources().getString(R.string.zerog));
binding.tvCarbsQ.setText(getResources().getString(R.string.zerog));
binding.tvFiberQ.setText(getResources().getString(R.string.zerog));
binding.tvProteinPercentage.setText(getResources().getString(R.string.zeropercentage));
binding.pbProtein.setProgress(DefaultValues.DEFAULT_VALUE);
binding.tvFatPercentage.setText(getResources().getString(R.string.zeropercentage));
binding.pbFat.setProgress(DefaultValues.DEFAULT_VALUE);
binding.tvCarbsPercentage.setText(getResources().getString(R.string.zeropercentage));
binding.pbCarbs.setProgress(DefaultValues.DEFAULT_VALUE);
binding.tvFiberPercentage.setText(getResources().getString(R.string.zeropercentage));
binding.pbFiber.setProgress(DefaultValues.DEFAULT_VALUE);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
} |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.util;
import jakarta.servlet.ServletException;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.lang.Nullable;
/**
* Legacy subclass of {@link ServletException} that handles a root cause in terms
* of message and stacktrace.
*
* @author Juergen Hoeller
* @since 1.2.5
* @deprecated as of 6.0, in favor of standard {@link ServletException} nesting
*/
@Deprecated(since = "6.0")
public class NestedServletException extends ServletException {
/** Use serialVersionUID from Spring 1.2 for interoperability. */
private static final long serialVersionUID = -5292377985529381145L;
static {
// Eagerly load the NestedExceptionUtils class to avoid classloader deadlock
// issues on OSGi when calling getMessage(). Reported by Don Brown; SPR-5607.
NestedExceptionUtils.class.getName();
}
/**
* Construct a {@code NestedServletException} with the specified detail message.
* @param msg the detail message
*/
public NestedServletException(String msg) {
super(msg);
}
/**
* Construct a {@code NestedServletException} with the specified detail message
* and nested exception.
* @param msg the detail message
* @param cause the nested exception
*/
public NestedServletException(@Nullable String msg, @Nullable Throwable cause) {
super(NestedExceptionUtils.buildMessage(msg, cause), cause);
}
}
|
package net.yustinus.crud.backend.tests;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import net.yustinus.crud.backend.beans.MenuBean;
import net.yustinus.crud.backend.beans.MenuItemBean;
import net.yustinus.crud.backend.dto.MenuDto;
import net.yustinus.crud.backend.services.MenuService;
import net.yustinus.crud.backend.testutils.BasicTest;
//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = { "classpath:applicationContext-backend-test.xml" })
public class MenuTest extends BasicTest {
@Autowired
private MenuService menuService;
@Test
public void getAllMenu() {
List<MenuBean> menus = menuService.getAllMenus();
for (MenuBean mb : menus) {
System.out.println("Header ID : "+mb.getHeaderMenu().getMenuId());
System.out.println("Header Name : "+mb.getHeaderMenu().getMenuName());
for(MenuItemBean mainMenu : mb.getMenus()) {
System.out.println("\t main menu ID : "+mainMenu.getParentMenu().getMenuId());
System.out.println("\t main menu Name : "+mainMenu.getParentMenu().getMenuName());
for (MenuDto cm : mainMenu.getChildMenu()) {
System.out.println("\t \t child menu ID : "+cm.getMenuId());
System.out.println("\t \t child menu Name : "+cm.getMenuName());
}
}
}
Assert.assertEquals(2, menus.size());
}
@Test
public void getBreadcrumb() {
List<MenuDto> menus = menuService.getBreadcrumb(12);
Assert.assertEquals(3, menus.size());
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.expression.spel.standard;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.asm.ClassWriter;
import org.springframework.asm.MethodVisitor;
import org.springframework.asm.Opcodes;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.CompiledExpression;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.ast.SpelNodeImpl;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* A SpelCompiler will take a regular parsed expression and create (and load) a class
* containing byte code that does the same thing as that expression. The compiled form of
* an expression will evaluate far faster than the interpreted form.
*
* <p>The SpelCompiler is not currently handling all expression types but covers many of
* the common cases. The framework is extensible to cover more cases in the future. For
* absolute maximum speed there is *no checking* in the compiled code. The compiled
* version of the expression uses information learned during interpreted runs of the
* expression when it generates the byte code. For example if it knows that a particular
* property dereference always seems to return a Map then it will generate byte code that
* expects the result of the property dereference to be a Map. This ensures maximal
* performance but should the dereference result in something other than a map, the
* compiled expression will fail - like a ClassCastException would occur if passing data
* of an unexpected type in a regular Java program.
*
* <p>Due to the lack of checking there are likely some expressions that should never be
* compiled, for example if an expression is continuously dealing with different types of
* data. Due to these cases the compiler is something that must be selectively turned on
* for an associated SpelExpressionParser (through the {@link SpelParserConfiguration}
* object), it is not on by default.
*
* <p>Individual expressions can be compiled by calling {@code SpelCompiler.compile(expression)}.
*
* @author Andy Clement
* @author Juergen Hoeller
* @since 4.1
*/
public final class SpelCompiler implements Opcodes {
private static final int CLASSES_DEFINED_LIMIT = 100;
private static final Log logger = LogFactory.getLog(SpelCompiler.class);
// A compiler is created for each classloader, it manages a child class loader of that
// classloader and the child is used to load the compiled expressions.
private static final Map<ClassLoader, SpelCompiler> compilers = new ConcurrentReferenceHashMap<>();
// The child ClassLoader used to load the compiled expression classes
private volatile ChildClassLoader childClassLoader;
// Counter suffix for generated classes within this SpelCompiler instance
private final AtomicInteger suffixId = new AtomicInteger(1);
private SpelCompiler(@Nullable ClassLoader classloader) {
this.childClassLoader = new ChildClassLoader(classloader);
}
/**
* Attempt compilation of the supplied expression. A check is made to see
* if it is compilable before compilation proceeds. The check involves
* visiting all the nodes in the expression AST and ensuring enough state
* is known about them that bytecode can be generated for them.
* @param expression the expression to compile
* @return an instance of the class implementing the compiled expression,
* or {@code null} if compilation is not possible
*/
@Nullable
public CompiledExpression compile(SpelNodeImpl expression) {
if (expression.isCompilable()) {
if (logger.isDebugEnabled()) {
logger.debug("SpEL: compiling " + expression.toStringAST());
}
Class<? extends CompiledExpression> clazz = createExpressionClass(expression);
if (clazz != null) {
try {
return ReflectionUtils.accessibleConstructor(clazz).newInstance();
}
catch (Throwable ex) {
throw new IllegalStateException("Failed to instantiate CompiledExpression for expression: " +
expression.toStringAST(), ex);
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("SpEL: unable to compile " + expression.toStringAST());
}
return null;
}
private int getNextSuffix() {
return this.suffixId.incrementAndGet();
}
/**
* Generate the class that encapsulates the compiled expression and define it.
* The generated class will be a subtype of CompiledExpression.
* @param expressionToCompile the expression to be compiled
* @return the expression call, or {@code null} if the decision was to opt out of
* compilation during code generation
*/
@Nullable
private Class<? extends CompiledExpression> createExpressionClass(SpelNodeImpl expressionToCompile) {
// Create class outline 'spel/ExNNN extends org.springframework.expression.spel.CompiledExpression'
String className = "spel/Ex" + getNextSuffix();
String evaluationContextClass = "org/springframework/expression/EvaluationContext";
ClassWriter cw = new ExpressionClassWriter();
cw.visit(V1_8, ACC_PUBLIC, className, null, "org/springframework/expression/spel/CompiledExpression", null);
// Create default constructor
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "org/springframework/expression/spel/CompiledExpression",
"<init>", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// Create getValue() method
mv = cw.visitMethod(ACC_PUBLIC, "getValue",
"(Ljava/lang/Object;L" + evaluationContextClass + ";)Ljava/lang/Object;", null,
new String[] {"org/springframework/expression/EvaluationException"});
mv.visitCode();
CodeFlow cf = new CodeFlow(className, cw);
// Ask the expression AST to generate the body of the method
try {
expressionToCompile.generateCode(mv, cf);
}
catch (IllegalStateException ex) {
if (logger.isDebugEnabled()) {
logger.debug(expressionToCompile.getClass().getSimpleName() +
".generateCode opted out of compilation: " + ex.getMessage());
}
return null;
}
CodeFlow.insertBoxIfNecessary(mv, cf.lastDescriptor());
if ("V".equals(cf.lastDescriptor())) {
mv.visitInsn(ACONST_NULL);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(0, 0); // not supplied due to COMPUTE_MAXS
mv.visitEnd();
cw.visitEnd();
cf.finish();
byte[] data = cw.toByteArray();
// TODO need to make this conditionally occur based on a debug flag
// dump(expressionToCompile.toStringAST(), clazzName, data);
return loadClass(StringUtils.replace(className, "/", "."), data);
}
/**
* Load a compiled expression class. Makes sure the classloaders aren't used too much
* because they anchor compiled classes in memory and prevent GC. If you have expressions
* continually recompiling over time then by replacing the classloader periodically
* at least some of the older variants can be garbage collected.
* @param name the name of the class
* @param bytes the bytecode for the class
* @return the Class object for the compiled expression
*/
@SuppressWarnings("unchecked")
private Class<? extends CompiledExpression> loadClass(String name, byte[] bytes) {
ChildClassLoader ccl = this.childClassLoader;
if (ccl.getClassesDefinedCount() >= CLASSES_DEFINED_LIMIT) {
synchronized (this) {
ChildClassLoader currentCcl = this.childClassLoader;
if (ccl == currentCcl) {
// Still the same ClassLoader that needs to be replaced...
ccl = new ChildClassLoader(ccl.getParent());
this.childClassLoader = ccl;
}
else {
// Already replaced by some other thread, let's pick it up.
ccl = currentCcl;
}
}
}
return (Class<? extends CompiledExpression>) ccl.defineClass(name, bytes);
}
/**
* Factory method for compiler instances. The returned SpelCompiler will
* attach a class loader as the child of the given class loader and this
* child will be used to load compiled expressions.
* @param classLoader the ClassLoader to use as the basis for compilation
* @return a corresponding SpelCompiler instance
*/
public static SpelCompiler getCompiler(@Nullable ClassLoader classLoader) {
ClassLoader clToUse = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
// Quick check for existing compiler without lock contention
SpelCompiler compiler = compilers.get(clToUse);
if (compiler == null) {
// Full lock now since we're creating a child ClassLoader
synchronized (compilers) {
return compilers.computeIfAbsent(clToUse, SpelCompiler::new);
}
}
return compiler;
}
/**
* Request that an attempt is made to compile the specified expression.
* It may fail if components of the expression are not suitable for compilation
* or the data types involved are not suitable for compilation. Used for testing.
* @param expression the expression to compile
* @return {@code true} if the expression was successfully compiled,
* {@code false} otherwise
*/
public static boolean compile(Expression expression) {
return (expression instanceof SpelExpression spelExpression && spelExpression.compileExpression());
}
/**
* Request to revert to the interpreter for expression evaluation.
* Any compiled form is discarded but can be recreated by later recompiling again.
* @param expression the expression
*/
public static void revertToInterpreted(Expression expression) {
if (expression instanceof SpelExpression spelExpression) {
spelExpression.revertToInterpreted();
}
}
/**
* A ChildClassLoader will load the generated compiled expression classes.
*/
private static class ChildClassLoader extends URLClassLoader {
private static final URL[] NO_URLS = new URL[0];
private final AtomicInteger classesDefinedCount = new AtomicInteger();
public ChildClassLoader(@Nullable ClassLoader classLoader) {
super(NO_URLS, classLoader);
}
public Class<?> defineClass(String name, byte[] bytes) {
Class<?> clazz = super.defineClass(name, bytes, 0, bytes.length);
this.classesDefinedCount.incrementAndGet();
return clazz;
}
public int getClassesDefinedCount() {
return this.classesDefinedCount.get();
}
}
/**
* An ASM ClassWriter extension bound to the SpelCompiler's ClassLoader.
*/
private class ExpressionClassWriter extends ClassWriter {
public ExpressionClassWriter() {
super(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
}
@Override
protected ClassLoader getClassLoader() {
return childClassLoader;
}
}
}
|
public class FoodItem {
private String dishName;
private Integer price;
public String getDishName() {
return dishName;
}
public void setDishName(String dishName) {
this.dishName = dishName;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "FoodItem [dishName=" + dishName + ", price=" + price + "]";
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.CertificatesCertificategenerationhistoryRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class CertificatesCertificategenerationhistory extends TableImpl<CertificatesCertificategenerationhistoryRecord> {
private static final long serialVersionUID = -404106256;
/**
* The reference instance of <code>bitnami_edx.certificates_certificategenerationhistory</code>
*/
public static final CertificatesCertificategenerationhistory CERTIFICATES_CERTIFICATEGENERATIONHISTORY = new CertificatesCertificategenerationhistory();
/**
* The class holding records for this type
*/
@Override
public Class<CertificatesCertificategenerationhistoryRecord> getRecordType() {
return CertificatesCertificategenerationhistoryRecord.class;
}
/**
* The column <code>bitnami_edx.certificates_certificategenerationhistory.id</code>.
*/
public final TableField<CertificatesCertificategenerationhistoryRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.certificates_certificategenerationhistory.created</code>.
*/
public final TableField<CertificatesCertificategenerationhistoryRecord, Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.certificates_certificategenerationhistory.modified</code>.
*/
public final TableField<CertificatesCertificategenerationhistoryRecord, Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.certificates_certificategenerationhistory.course_id</code>.
*/
public final TableField<CertificatesCertificategenerationhistoryRecord, String> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>bitnami_edx.certificates_certificategenerationhistory.is_regeneration</code>.
*/
public final TableField<CertificatesCertificategenerationhistoryRecord, Byte> IS_REGENERATION = createField("is_regeneration", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, "");
/**
* The column <code>bitnami_edx.certificates_certificategenerationhistory.generated_by_id</code>.
*/
public final TableField<CertificatesCertificategenerationhistoryRecord, Integer> GENERATED_BY_ID = createField("generated_by_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.certificates_certificategenerationhistory.instructor_task_id</code>.
*/
public final TableField<CertificatesCertificategenerationhistoryRecord, Integer> INSTRUCTOR_TASK_ID = createField("instructor_task_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* Create a <code>bitnami_edx.certificates_certificategenerationhistory</code> table reference
*/
public CertificatesCertificategenerationhistory() {
this("certificates_certificategenerationhistory", null);
}
/**
* Create an aliased <code>bitnami_edx.certificates_certificategenerationhistory</code> table reference
*/
public CertificatesCertificategenerationhistory(String alias) {
this(alias, CERTIFICATES_CERTIFICATEGENERATIONHISTORY);
}
private CertificatesCertificategenerationhistory(String alias, Table<CertificatesCertificategenerationhistoryRecord> aliased) {
this(alias, aliased, null);
}
private CertificatesCertificategenerationhistory(String alias, Table<CertificatesCertificategenerationhistoryRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<CertificatesCertificategenerationhistoryRecord, Integer> getIdentity() {
return Keys.IDENTITY_CERTIFICATES_CERTIFICATEGENERATIONHISTORY;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<CertificatesCertificategenerationhistoryRecord> getPrimaryKey() {
return Keys.KEY_CERTIFICATES_CERTIFICATEGENERATIONHISTORY_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<CertificatesCertificategenerationhistoryRecord>> getKeys() {
return Arrays.<UniqueKey<CertificatesCertificategenerationhistoryRecord>>asList(Keys.KEY_CERTIFICATES_CERTIFICATEGENERATIONHISTORY_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<CertificatesCertificategenerationhistoryRecord, ?>> getReferences() {
return Arrays.<ForeignKey<CertificatesCertificategenerationhistoryRecord, ?>>asList(Keys.CERTIFICATES_CE_GENERATED_BY_ID_4679598E2D7D6E10_FK_AUTH_USER_ID, Keys.D794923145B81064C232A4D0BFE79880);
}
/**
* {@inheritDoc}
*/
@Override
public CertificatesCertificategenerationhistory as(String alias) {
return new CertificatesCertificategenerationhistory(alias, this);
}
/**
* Rename this table
*/
public CertificatesCertificategenerationhistory rename(String name) {
return new CertificatesCertificategenerationhistory(name, null);
}
}
|
package com.andrewsales.tools.dtd2xml;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
public class ContentHander implements ContentHandler {
@Override
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endPrefixMapping(String arg0) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void ignorableWhitespace(char[] arg0, int arg1, int arg2)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void processingInstruction(String arg0, String arg1)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void setDocumentLocator(Locator arg0) {
// TODO Auto-generated method stub
}
@Override
public void skippedEntity(String s) throws SAXException {
System.err.println(s);
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startElement(String arg0, String arg1, String arg2,
Attributes arg3) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startPrefixMapping(String arg0, String arg1)
throws SAXException {
// TODO Auto-generated method stub
}
}
|
package benchmark.java.metrics.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.io.OutputStream;
import benchmark.java.Config;
import benchmark.java.entities.PersonCollection;
import benchmark.java.metrics.AMetric;
import benchmark.java.metrics.Info;
public class JacksonMetric extends AMetric {
private ObjectMapper mapper;
private final Info info = new Info(Config.Format.JSON, "Jackson", "https://github.com/FasterXML/jackson", "2.8.5");
@Override
public Info getInfo() {
return info;
}
@Override
protected void prepareBenchmark() {
mapper = new ObjectMapper();
}
@Override
public boolean serialize(Object data, OutputStream output) throws Exception {
mapper.writeValue(output, data);
return true;
}
@Override
public Object deserialize(InputStream input, byte[] bytes) throws Exception {
PersonCollection personCollection = mapper.readValue(input, PersonCollection.class);
return personCollection;
}
}
|
package com.esum.framework.core.management.resource;
import java.util.Set;
import javax.management.ObjectName;
import org.apache.catalina.mbeans.ConnectorMBean;
import org.apache.catalina.mbeans.ContextMBean;
import org.apache.catalina.mbeans.ServiceMBean;
import org.apache.tomcat.util.modeler.BaseModelMBean;
import com.esum.framework.core.management.ManagementException;
import com.esum.framework.jmx.JmxClientTemplate;
/**
* Tomcat을 MBean으로 관리하기 위한 기능을 제공한다.
*/
public class TomcatControl extends AbstractJmxControl {
/**
* 특정 ipAddress, port정보를 통해 JMX로 연결된 TomcatManager객체를 리턴한다.
*/
public static TomcatControl getControl(String ipAddress, int port) throws ManagementException {
return new TomcatControl(ipAddress, port);
}
private TomcatControl(String ipAddress, int port) throws ManagementException {
setJmxClient(JmxClientTemplate.createJmxClient(ipAddress, port));
}
public Set<ObjectName> getConnectors() throws ManagementException {
String jmxNameFilter = "Tomcat:type=Connector,port=*";
return getObjectNames(jmxNameFilter);
}
/**
* 특정 context에 대한 BaseModelMBean객체를 리턴한다.
* 리턴한 객체를 통해 해당 context에 대한 설정을 변경할 수 있다.
*
* @param contextName 가져온 객체에 대한 context(http, status, update, ebms, as2 등)
* @return
* @throws ManagementException
*/
public ContextMBean getContextMBean(String contextName) throws ManagementException {
// String jmxName = "Tomcat:type=Manager,context=/"+contextName+",host=localhost";
String jmxName = "Tomcat:j2eeType=WebModule,name=//localhost"+contextName+",J2EEApplication=none,J2EEServer=none";
return findMBean(jmxName, ContextMBean.class);
}
/**
* Tomcat에서 listen하고 있는 포트에 대한 ConnectorMBean을 리턴한다. 9080, 9443등에 대한 정보를 사용할 수 있다.
*/
public ConnectorMBean getConnectorMBean(int port) throws ManagementException {
String jmxName = "Tomcat:type=Connector,port="+port;
return findMBean(jmxName, ConnectorMBean.class);
}
public BaseModelMBean getGlobalRequestProcessor(int port) throws ManagementException {
String jmxName = "Tomcat:type=GlobalRequestProcessor,name=\"http-bio-"+port+"\"";
return findMBean(jmxName, BaseModelMBean.class);
}
public long getBytesSent(int port) throws ManagementException {
String jmxName = "Tomcat:type=GlobalRequestProcessor,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "bytesSent").toString());
} catch (Exception e) {
throw new ManagementException("getBytesSent()", e.getMessage(), e);
}
}
public long getErrorCount(int port) throws ManagementException {
String jmxName = "Tomcat:type=GlobalRequestProcessor,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "errorCount").toString());
} catch (Exception e) {
throw new ManagementException("getErrorCount()", e.getMessage(), e);
}
}
public long getMaxTime(int port) throws ManagementException {
String jmxName = "Tomcat:type=GlobalRequestProcessor,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "maxTime").toString());
} catch (Exception e) {
throw new ManagementException("getMaxTime()", e.getMessage(), e);
}
}
public long getProcessingTime(int port) throws ManagementException {
String jmxName = "Tomcat:type=GlobalRequestProcessor,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "processingTime").toString());
} catch (Exception e) {
throw new ManagementException("getProcessingTime()", e.getMessage(), e);
}
}
public long getRequestCount(int port) throws ManagementException {
String jmxName = "Tomcat:type=GlobalRequestProcessor,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "requestCount").toString());
} catch (Exception e) {
throw new ManagementException("getRequestCount()", e.getMessage(), e);
}
}
/**
* Tomcat의 서버 MBean을 가져온다, 서버에 대한 Start, Shutdown을 실행할 수 있다.
*/
public BaseModelMBean getThreadPool(int port) throws ManagementException {
String jmxName = "Tomcat:type=ThreadPool,name=\"http-bio-"+port+"\"";
return findMBean(jmxName, BaseModelMBean.class);
}
public long getConnectionCount(int port) throws ManagementException {
String jmxName = "Tomcat:type=ThreadPool,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "connectionCount").toString());
} catch (Exception e) {
throw new ManagementException("getConnectionCount()", e.getMessage(), e);
}
}
public long getCurrentThreadCount(int port) throws ManagementException {
String jmxName = "Tomcat:type=ThreadPool,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "currentThreadCount").toString());
} catch (Exception e) {
throw new ManagementException("getCurrentThreadCount()", e.getMessage(), e);
}
}
public long getCurrentThreadsBusyCount(int port) throws ManagementException {
String jmxName = "Tomcat:type=ThreadPool,name=\"http-bio-"+port+"\"";
try {
return Long.parseLong(findAttribute(jmxName, "currentThreadsBusy").toString());
} catch (Exception e) {
throw new ManagementException("getCurrentThreadsBusyCount()", e.getMessage(), e);
}
}
/**
* Tomcat에서 실행중인 서비스들에 대한 정보를 관리한다. 서비스들은 9080, 9443과 같은 Connector들에 대한 서비스들을 말한다.
*/
public ServiceMBean getSrviceMBean() throws ManagementException {
String jmxName = "Tomcat:type=Service";
return findMBean(jmxName, ServiceMBean.class);
}
}
|
package com.bofsoft.laio.customerservice.DataClass;
import com.bofsoft.laio.data.BaseData;
import java.util.ArrayList;
import java.util.List;
/**
* Created by szw on 2017/2/23.
*/
public class GPSInfoList extends BaseData {
public List<GPSInfoData> InfoList = new ArrayList<GPSInfoData>();
}
|
import static org.junit.Assert.*;
import org.junit.Test;
public class GrafoTest {
public Grafo grafo(){
return new Grafo(5);
}
@Test
public void testCrearArista() {
Grafo aTestear = grafo();
//arista posible
aTestear.crearArista(0, 1);
assertTrue(aTestear.existeArista(0, 1));
assertEquals(1, aTestear.getCantAristas());
}
@Test
public void testCrearAristaRepetidaTest(){
Grafo aTestear=grafo();
//agrego la misma arista varias veces
aTestear.crearArista(2, 3);
aTestear.crearArista(2, 3);
aTestear.crearArista(2, 3);
aTestear.crearArista(2, 3);
assertEquals(1,aTestear.getCantAristas());
}
@Test(expected=IllegalArgumentException.class)
public void crearAristaFueraDeRangoTest(){
Grafo aTestear=grafo();
//arista fuera de rango
aTestear.crearArista(3, 6);
}
@Test(expected=IllegalArgumentException.class)
public void crearAristaNegativaTest(){
Grafo aTestear= grafo();
aTestear.crearArista(-1, 4);
aTestear.crearArista(2, -1);
}
@Test
public void existeAristaTest(){
Grafo aTestear= grafo();
//creo una arista pero chequeo esa y otra inexistente
aTestear.crearArista(1, 0);
assertTrue(aTestear.existeArista(1, 0));
assertTrue(aTestear.existeArista(0, 1));
assertFalse(aTestear.existeArista(2,0));
}
@Test
public void eliminarAristaTest(){
Grafo aTestear= grafo();
//creo una arista y luegp la elimino
aTestear.crearArista(1, 2);
assertEquals(1,aTestear.getCantAristas());
aTestear.eliminarArista(1, 2);
assertEquals(0,aTestear.getCantAristas());
//elimino una arista que no existe
aTestear.eliminarArista(1, 2);
assertEquals(0, aTestear.getCantAristas());
}
}
|
package com.giora.climasale.features.weatherDetails.module;
import com.giora.climasale.features.weatherDetails.domain.GetForecastsUseCase;
import com.giora.climasale.features.weatherDetails.domain.IGetForecastsUseCase;
import com.giora.climasale.features.weatherDetails.presentation.DayOfTheWeekImageProvider;
import com.giora.climasale.features.weatherDetails.presentation.IDayOfTheWeekImageProvider;
import com.giora.climasale.features.weatherDetails.presentation.IWeatherDetailsViewModelFactory;
import com.giora.climasale.features.weatherDetails.presentation.WeatherDetailsViewModelFactory;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class WeatherDetailsModule {
@Provides
IDayOfTheWeekImageProvider provideDayOfTheWeekImageProvider() {
return new DayOfTheWeekImageProvider();
}
@Provides
IGetForecastsUseCase provideGetForecastsUseCase() {
return new GetForecastsUseCase();
}
@Singleton
@Provides
IWeatherDetailsViewModelFactory provideWeatherDetailsViewModelFactory(IGetForecastsUseCase getForecastsUseCase,
IDayOfTheWeekImageProvider dayOfTheWeekImageProvider) {
return new WeatherDetailsViewModelFactory(getForecastsUseCase, dayOfTheWeekImageProvider);
}
}
|
package io.github.yizhiru.thulac4j.process;
import io.github.yizhiru.thulac4j.model.SegItem;
import java.io.Serializable;
import java.util.List;
/**
* 词黏结.
*/
public interface Cementer extends Serializable {
/**
* 黏结分词结果.
*
* @param segItems 序列标注结果.
*/
void cement(List<SegItem> segItems);
}
|
package ua.kteam.pocketmonsters;
import java.util.*;
import ua.kteam.pocketmonsters.R;
import android.app.*;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.*;
public class AuthorizationActivity extends Activity {
ViewPager pager;
FragmentPagerAdapter pagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_authorization);
pager = (ViewPager) findViewById(R.id.pager);
List<Fragment> list = new Vector<Fragment>();
list.add(new LoginFragment());
list.add(new RegistrationFragment());
List<String> titles = new Vector<String>();
titles.add(getString(R.string.signInTitle));
titles.add(getString(R.string.signUpTitle));
pagerAdapter = new UniversalPagerAdapter(getFragmentManager(), list, titles);
pager.setAdapter(pagerAdapter);
}
}
|
package com.example.android.spunk;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.SQLException;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.io.IOException;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity {
public static final String TAG = PostActivity.class.getSimpleName();
DatabaseHelper myDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
initialiseDatabase();
// getActionBar().setDisplayHomeAsUpEnabled(true);
Button btnPost = (Button) findViewById(R.id.button_post);
btnPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//startActivity(new Intent(HomeActivity.this,PostActivity.class));
Log.d(TAG, "Clicked Post");
EditText title = (EditText) findViewById(R.id.editTopic);
EditText desc = (EditText) findViewById(R.id.editDesc);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
int selectedId = radioGroup.getCheckedRadioButtonId();
String type = null;
if(selectedId == 0)
type = "Q";
else
type = "B";
// if(quesRadioButton.ge)
// mCursor.requery();
//mAdapter.notifyDataSetChanged();
// mText.setText(null);
myDBHelper.setPost(type, title.getText().toString(), desc.getText().toString(), 1);
/* Log.d(TAG, "After Set Post");
ArrayList<String> titles = myDBHelper.getPostTitles("B");
String title2 = myDBHelper.getPost(1);
Log.d(TAG, "After get Post Titles Post");
Log.d(TAG, title2);
if(titles == null)
Log.d(TAG, "NUll output");
else {
for (int i=0;i<titles.size();i++)
Log.d(TAG, titles.get(i));
}*/
Intent upIntent = NavUtils.getParentActivityIntent(PostActivity.this);
upIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(upIntent);
finish();
// NavUtils.navigateUpFromSameTask(PostActivity.this);
}
});
Button btnDiscard = (Button) findViewById(R.id.button_discard);
btnDiscard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//startActivity(new Intent(HomeActivity.this,PostActivity.class));
NavUtils.navigateUpFromSameTask(PostActivity.this);
}
});
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.8),(int)(height*0.6));
}
public void initialiseDatabase(){
myDBHelper = new DatabaseHelper(this);
//myDBHelper = new DatabaseHelper(this);
try{
myDBHelper.createDataBase();
}
catch(IOException e){
throw new Error("Unable to create database");
}
try{
myDBHelper.openDataBase();
}
catch(SQLException e){
throw e;
}
}
}
|
package by.bytechs.ndcParser.response.commands;
/**
* @author Romanovich Andrei
*/
public class NumberCashToDispense {
private Integer cassetteNumber;
private Integer cashNumber;
public NumberCashToDispense() {
}
public NumberCashToDispense(Integer cassetteNumber, Integer cashNumber) {
this.cassetteNumber = cassetteNumber;
this.cashNumber = cashNumber;
}
public Integer getCassetteNumber() {
return cassetteNumber;
}
public void setCassetteNumber(Integer cassetteNumber) {
this.cassetteNumber = cassetteNumber;
}
public Integer getCashNumber() {
return cashNumber;
}
public void setCashNumber(Integer cashNumber) {
this.cashNumber = cashNumber;
}
@Override
public String toString() {
return "NumberCashToDispense{" +
"cassetteNumber=" + cassetteNumber +
", cashNumber=" + cashNumber +
'}';
}
} |
package ru.mstoyan.shiko.testtask.Views;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import java.util.Random;
/**
* Created by shiko on 08.02.2017.
*/
public class PathDrawer extends View implements GestureDetector.OnGestureListener{
private Path path;
private Paint paint;
private GestureDetector gestureDetector;
private Region region;
Random rnd = new Random();
public PathDrawer(Context context) {
super(context);
init();
}
public PathDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PathDrawer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public PathDrawer(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init(){
path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(0,0,0));
paint.setStyle(Paint.Style.FILL);
region = new Region();
gestureDetector = new GestureDetector(getContext(), this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint);
}
public void setPath(Path newPath){
path = newPath;
region.setPath(newPath, new Region(0,0,getHeight(),getWidth()));
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
@Override
public void setOnTouchListener(OnTouchListener l) {
super.setOnTouchListener(l);
}
@Override
public boolean onDown(MotionEvent e) {
if (region.contains((int)e.getX(),(int)e.getY()))
paint.setColor(Color.rgb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
invalidate();
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
|
package org.juxtasoftware.dao.impl;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.juxtasoftware.Constants;
import org.juxtasoftware.dao.CacheDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class CacheDaoImpl implements CacheDao {
@Autowired private JdbcTemplate jdbcTemplate;
@Autowired private Integer cacheLifespan;
protected static final Logger LOG = LoggerFactory.getLogger( Constants.WS_LOGGER_NAME );
private final String TABLE = "juxta_collation_cache";
@Override
public void deleteAll(Long setId) {
try {
final String sql = "delete from "+TABLE+" where set_id=?";
jdbcTemplate.update(sql, setId );
} catch (Exception e) {
LOG.error("Clear cache failed for set "+setId, e);
}
}
@Override
public boolean heatmapExists(final Long setId, final Long key, boolean condensed ) {
try {
final String sql = "select count(*) as cnt from "
+TABLE+" where set_id=? and config=? and data_type=?";
String type = "HEATMAP";
if ( condensed ) {
type = "CONDENSED_HEATMAP";
}
long cnt = jdbcTemplate.queryForLong(sql, setId, key.toString(), type);
return cnt > 0;
} catch (Exception e) {
LOG.error("Cached heatmap exists failed for set "+setId, e);
return false;
}
}
@Override
public void deleteHeatmap(final Long setId) {
try {
final String sql = "delete from "+TABLE+" where set_id=? and data_type=? || data_type=?";
jdbcTemplate.update(sql, setId, "HEATMAP", "CONDENSED_HEATMAP");
} catch (Exception e) {
LOG.error("Unable to delete cached heatmap for set "+setId, e);
}
}
@Override
public Reader getHeatmap(final Long setId, final Long key, final boolean condensed ) {
try {
final String sql = "select data from "
+TABLE+" where set_id=? and config=? and data_type=?";
String type = "HEATMAP";
if ( condensed ) {
type = "CONDENSED_HEATMAP";
}
return DataAccessUtils.uniqueResult(
this.jdbcTemplate.query(sql, new RowMapper<Reader>(){
@Override
public Reader mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getCharacterStream("data");
}
}, setId, key.toString(), type) );
} catch (Exception e) {
LOG.error("Unable to retrieve cached heatmap for set "+setId, e);
return null;
}
}
@Override
public void cacheHeatmap(final Long setId, final Long key, final Reader data, final boolean condensed ) {
try {
final String sql = "insert into " + TABLE+ " (set_id, config, data_type, data) values (?,?,?,?)";
this.jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
String type = "HEATMAP";
if ( condensed ) {
type = "CONDENSED_HEATMAP";
}
ps.setLong(1, setId);
ps.setString(2, key.toString());
ps.setString(3, type);
ps.setCharacterStream(4, data);
}
});
} catch (Exception e) {
LOG.error("Unable to cache heatmap for set "+setId, e);
}
}
@Override
public boolean exportExists( final Long setId, final Long baseId ) {
try {
final String sql = "select count(*) as cnt from "
+TABLE+" where set_id=? and config=? and data_type=?";
long cnt = jdbcTemplate.queryForLong(sql, setId, baseId.toString(), "EXPORT");
return cnt > 0;
} catch (Exception e) {
LOG.error("Export exists failed for set "+setId, e);
return false;
}
}
@Override
public Reader getExport( final Long setId, final Long baseId ) {
try {
final String sql = "select data from "+TABLE+" where set_id=? and config=? and data_type=?";
return DataAccessUtils.uniqueResult(
this.jdbcTemplate.query(sql, new RowMapper<Reader>(){
@Override
public Reader mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getCharacterStream("data");
}
}, setId, baseId.toString(), "EXPORT") );
} catch (Exception e) {
LOG.error("Retrieve cached export failed for set "+setId, e);
return null;
}
}
@Override
public void cacheExport( final Long setId, final Long baseId, final Reader data) {
try {
final String sql = "insert into " + TABLE+ " (set_id, config, data_type, data) values (?,?,?,?)";
this.jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setLong(1, setId);
ps.setString(2, baseId.toString());
ps.setString(3, "EXPORT");
ps.setCharacterStream(4, data);
}
});
} catch (Exception e) {
LOG.error("Cache export failed for set "+setId, e);
}
}
@Override
public boolean editionExists( final Long setId, final long token ) {
try {
final String sql = "select count(*) as cnt from "
+TABLE+" where set_id=? and config=? and data_type=?";
long cnt = jdbcTemplate.queryForLong(sql, setId, token, "EDITION");
return cnt > 0;
} catch (Exception e) {
LOG.error("Edition exists failed for set "+setId, e);
return false;
}
}
@Override
public Reader getEdition( final Long setId, final long token ) {
try {
final String sql = "select data from "+TABLE+" where set_id=? and config=? and data_type=?";
return DataAccessUtils.uniqueResult(
this.jdbcTemplate.query(sql, new RowMapper<Reader>(){
@Override
public Reader mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getCharacterStream("data");
}
}, setId, token, "EDITION") );
} catch (Exception e) {
LOG.error("Unable to get Edition for set "+setId, e);
return null;
}
}
@Override
public void cacheEdition( final Long setId, final long token, final Reader data) {
try {
final String sql = "insert into " + TABLE+ " (set_id, config, data_type, data) values (?,?,?,?)";
this.jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setLong(1, setId);
ps.setString(2, Long.toString(token) );
ps.setString(3, "EDITION");
ps.setCharacterStream(4, data);
}
});
} catch (Exception e) {
LOG.error("Cache Edition failed for set "+setId, e);
}
}
@Override
public boolean histogramExists( final Long setId, final Long key ) {
try {
final String sql = "select count(*) as cnt from "
+TABLE+" where set_id=? and config=? and data_type=?";
long cnt = jdbcTemplate.queryForLong(sql, setId, key.toString(), "HISTOGRAM");
return cnt > 0;
} catch (Exception e) {
LOG.error("Check histogram failed for set "+setId, e);
return false;
}
}
@Override
public Reader getHistogram(final Long setId, final Long key ) {
try {
final String sql = "select data from "
+TABLE+" where set_id=? and config=? and data_type=?";
return DataAccessUtils.uniqueResult(
this.jdbcTemplate.query(sql, new RowMapper<Reader>(){
@Override
public Reader mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getCharacterStream("data");
}
}, setId, key.toString(), "HISTOGRAM") );
} catch (Exception e) {
LOG.error("Unable to get histogram for set "+setId, e);
return null;
}
}
@Override
public void cacheHistogram(final Long setId, final Long key, final Reader data) {
try {
final String sql = "insert into " + TABLE+ " (set_id, config, data_type, data) values (?,?,?,?)";
this.jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setLong(1, setId);
ps.setString(2, key.toString());
ps.setString(3, "HISTOGRAM");
ps.setCharacterStream(4, data);
}
});
} catch (Exception e) {
LOG.error("Unable to cache histogram for set "+setId, e);
}
}
@Override
public void deleteSideBySide(Long setId) {
try {
final String sql = "delete from "+TABLE+" where set_id=? and data_type=?";
jdbcTemplate.update(sql, setId, "SIDEBYSIDE");
} catch (Exception e) {
LOG.error("Unable to delete side-by-side for set "+setId, e);
}
}
@Override
public void cacheSideBySide(final Long setId, final Long witness1, final Long witness2, final Reader data) {
try {
final String sql = "insert into " + TABLE+ " (set_id, config, data_type, data) values (?,?,?,?)";
this.jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setLong(1, setId);
ps.setString(2, witness1.toString()+","+witness2.toString());
ps.setString(3, "SIDEBYSIDE");
ps.setCharacterStream(4, data);
}
});
} catch (Exception e) {
LOG.error("Unable to cache side-by-side for set "+setId+" witnesses "+witness1+","+witness2, e);
}
}
@Override
public boolean sideBySideExists(Long setId, Long witness1, Long witness2) {
try {
final String sql = "select count(*) as cnt from "
+TABLE+" where set_id=? and config=? and data_type=?";
final String wits = toList(witness1, witness2);
long cnt = jdbcTemplate.queryForLong(sql, setId, wits, "SIDEBYSIDE");
return cnt > 0;
} catch (Exception e) {
return false;
}
}
private String toList(final Long witness1, final Long witess2) {
return witness1.toString()+","+witess2.toString();
}
@Override
public Reader getSideBySide(Long setId, Long witness1, Long witness2) {
try {
final String sql = "select data from "
+TABLE+" where set_id=? and config=? and data_type=?";
final String witnessList = toList(witness1, witness2);
return DataAccessUtils.uniqueResult(
this.jdbcTemplate.query(sql, new RowMapper<Reader>(){
@Override
public Reader mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getCharacterStream("data");
}
}, setId, witnessList, "SIDEBYSIDE") );
} catch (Exception e) {
LOG.error("Unable to retrieve cached side-by-side for set "+setId+" witnesses "+witness1+","+witness2, e);
return null;
}
}
@Override
public void purgeExpired() {
if ( this.cacheLifespan < 0 ) {
LOG.info("Cache set to never expire; not purging");
return;
}
try {
final String sql = "delete from juxta_collation_cache where permanent=0 and created < ( NOW() - INTERVAL "+this.cacheLifespan+" HOUR)";
this.jdbcTemplate.update(sql);
} catch (Exception e) {
LOG.error("Unable to purge expired cache", e);
}
}
}
|
/*
* 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 carteira;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author maico
*/
@Entity
@Table(name = "carteira")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Carteira.findAll", query = "SELECT c FROM Carteira c"),
@NamedQuery(name = "Carteira.findById", query = "SELECT c FROM Carteira c WHERE c.id = :id"),
@NamedQuery(name = "Carteira.findByNome", query = "SELECT c FROM Carteira c WHERE c.nome = :nome"),
@NamedQuery(name = "Carteira.findByRg", query = "SELECT c FROM Carteira c WHERE c.rg = :rg"),
@NamedQuery(name = "Carteira.findByCurso", query = "SELECT c FROM Carteira c WHERE c.curso = :curso"),
@NamedQuery(name = "Carteira.findBySala", query = "SELECT c FROM Carteira c WHERE c.sala = :sala"),
@NamedQuery(name = "Carteira.findByTelefone", query = "SELECT c FROM Carteira c WHERE c.telefone = :telefone"),
@NamedQuery(name = "Carteira.findByDeter", query = "SELECT c FROM Carteira c WHERE c.deter = :deter"),
@NamedQuery(name = "Carteira.findByFretamento", query = "SELECT c FROM Carteira c WHERE c.fretamento = :fretamento")})
public class Carteira implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "situaco")
private int situaco;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "nome")
private String nome;
@Basic(optional = false)
@NotNull
@Column(name = "rg")
private int rg;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "curso")
private String curso;
@Size(max = 255)
@Column(name = "sala")
private String sala;
@Basic(optional = false)
@NotNull
@Column(name = "telefone")
private int telefone;
@Column(name = "deter")
private Integer deter;
@Column(name = "fretamento")
private Integer fretamento;
public Carteira() {
}
public Carteira(Integer id) {
this.id = id;
}
public Carteira(Integer id, String nome, int rg, String curso, int telefone) {
this.id = id;
this.nome = nome;
this.rg = rg;
this.curso = curso;
this.telefone = telefone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getRg() {
return rg;
}
public void setRg(int rg) {
this.rg = rg;
}
public String getCurso() {
return curso;
}
public void setCurso(String curso) {
this.curso = curso;
}
public String getSala() {
return sala;
}
public void setSala(String sala) {
this.sala = sala;
}
public int getTelefone() {
return telefone;
}
public void setTelefone(int telefone) {
this.telefone = telefone;
}
public Integer getDeter() {
return deter;
}
public void setDeter(Integer deter) {
this.deter = deter;
}
public Integer getFretamento() {
return fretamento;
}
public void setFretamento(Integer fretamento) {
this.fretamento = fretamento;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Carteira)) {
return false;
}
Carteira other = (Carteira) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "carteira.Carteira[ id=" + id + " ]";
}
public int getSituaco() {
return situaco;
}
public void setSituaco(int situaco) {
this.situaco = situaco;
}
}
|
package com.ngocdt.tttn.repository;
import com.ngocdt.tttn.entity.Invoice;
import org.springframework.data.jpa.repository.JpaRepository;
public interface InvoiceRepository extends JpaRepository<Invoice, Integer> {
}
|
package ru.vlapin.demo.paveldemo.common;
import static io.vavr.API.unchecked;
import static java.util.Spliterator.ORDERED;
import static java.util.Spliterators.spliteratorUnknownSize;
import io.vavr.CheckedFunction1;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public interface ReflectionUtil {
Function<String, Class<?>> CLASS_FOR_NAME = CheckedFunction1.<String, Class<?>>of(Class::forName).unchecked();
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param packageName The base package
* @return The classes
*/
static Stream<Class<?>> getClasses(String packageName) {
return unchecked(ClassLoader::getResources)
.andThen(Enumeration::asIterator)
.andThen(urlIterator -> spliteratorUnknownSize(urlIterator, ORDERED))
.andThen(urlSpliterator -> StreamSupport.stream(urlSpliterator, false))
.reversed()
.apply(packageName.replace('.', '/'))
.compose(Thread::getContextClassLoader)
.apply(Thread.currentThread())
.map(URL::getFile)
.map(File::new)
.flatMap(dir -> findClasses(dir, packageName));
}
/**
* Recursive method used to find all classes in a given directory and subdirectories.
*
* @param directory The base directory
* @param packageName The package name for classes found inside the base directory
* @return The classes
*/
private static Stream<Class<?>> findClasses(File directory, String packageName) {
return Stream.of(directory)
.filter(File::exists)
.map(File::listFiles)
.flatMap(Arrays::stream)
.flatMap(file -> file.isDirectory()
? findClasses(file, packageName + "." + file.getName())
: findClass(file.getName(), packageName)
);
}
private static Stream<? extends Class<?>> findClass(String fileName, String packageName) {
return Stream.of(fileName)
.filter(name -> name.endsWith(".class"))
.map(name -> CLASS_FOR_NAME.apply(packageName + '.' + name.substring(0, name.length() - 6)));
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servicios;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import modelos.Producto;
public class Productos_servicio {
private static Productos_servicio instance = null;
protected Productos_servicio() {
//Evita que la clase se instancie
}
public static Productos_servicio getInstance() {
if (instance == null) {
instance = new Productos_servicio();
}
return instance;
}
public void guardar(Producto prod) throws SQLException {
try {
PreparedStatement consulta;
if (prod.getIdProducto() == null) {
consulta = Conexion.getConnection().prepareStatement("INSERT INTO producto(idproducto, descripcion) VALUES(?, ?)");
consulta.setInt(1, prod.getIdProducto());
consulta.setString(2, prod.getDescripcion());
} else {
consulta = Conexion.getConnection().prepareStatement("UPDATE producto SET descripcion = ? WHERE idproducto = ?");
consulta.setString(1, prod.getDescripcion());
consulta.setInt(2, prod.getIdProducto());
}
consulta.executeUpdate();
} catch (SQLException ex) {
throw new SQLException(ex);
}
}
public Producto recuperarPorId(int id_prod) throws SQLException {
Producto prod = null;
try {
PreparedStatement consulta = Conexion.getConnection().prepareStatement("SELECT idproducto, descripcion, precio FROM producto WHERE idproducto = ?");
consulta.setInt(1, id_prod);
ResultSet resultado = consulta.executeQuery();
if (!resultado.isBeforeFirst()){
return prod;
}
while (resultado.next()) {
prod = new Producto(id_prod, resultado.getString("descripcion"), resultado.getDouble("precio"));
}
} catch (SQLException ex) {
throw new SQLException(ex);
}
return prod;
}
public Producto recuperarPorDescripcion(String desc) throws SQLException {
Producto prod = null;
try {
PreparedStatement consulta = Conexion.getConnection().prepareStatement("SELECT idproducto, descripcion, precio FROM producto WHERE descripcion like ? ;");
consulta.setString(1, desc+"%");
ResultSet resultado = consulta.executeQuery();
if (!resultado.isBeforeFirst()){
return prod;
}
while (resultado.next()) {
prod = new Producto(resultado.getInt("idproducto"), resultado.getString("descripcion"), resultado.getDouble("precio"));
}
} catch (SQLException ex) {
throw new SQLException(ex);
}
return prod;
}
// public void eliminar(Connection conexion, Producto prod) throws SQLException{
// try{
// PreparedStatement consulta = conexion.prepareStatement("DELETE FROM " + this.tabla + " WHERE id_prod = ?");
// consulta.setInt(1, prod.getId_prod());
// consulta.executeUpdate();
// }catch(SQLException ex){
// throw new SQLException(ex);
// }
// }
public List<Producto> recuperarTodas() throws SQLException {
List<Producto> prods = new ArrayList<>();
try {
PreparedStatement consulta = Conexion.getConnection().prepareStatement("SELECT idproducto, descripcion, precio FROM producto ORDER BY idproducto");
ResultSet resultado = consulta.executeQuery();
while (resultado.next()) {
prods.add(new Producto(resultado.getInt("idproducto"), resultado.getString("descripcion"), resultado.getDouble("precio")));
}
} catch (SQLException ex) {
throw new SQLException(ex);
}
return prods;
}
}
|
package example.mapper;
import java.sql.JDBCType;
import java.util.Date;
import javax.annotation.Generated;
import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable;
public final class RoleDynamicSqlSupport {
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.805+08:00", comments="Source Table: demo_role")
public static final Role role = new Role();
/**
* Database Column Remarks:
* 角色id
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.805+08:00", comments="Source field: demo_role.id")
public static final SqlColumn<String> id = role.id;
/**
* Database Column Remarks:
* 角色名称
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.805+08:00", comments="Source field: demo_role.name")
public static final SqlColumn<String> name = role.name;
/**
* Database Column Remarks:
* 是否通用
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.805+08:00", comments="Source field: demo_role.is_general")
public static final SqlColumn<Boolean> isGeneral = role.isGeneral;
/**
* Database Column Remarks:
* 记录是否已删除
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.805+08:00", comments="Source field: demo_role.deleted")
public static final SqlColumn<Boolean> deleted = role.deleted;
/**
* Database Column Remarks:
* 记录创建时间
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.806+08:00", comments="Source field: demo_role.gmt_create")
public static final SqlColumn<Date> gmtCreate = role.gmtCreate;
/**
* Database Column Remarks:
* 记录更新时间
*/
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.806+08:00", comments="Source field: demo_role.gmt_modified")
public static final SqlColumn<Date> gmtModified = role.gmtModified;
@Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2021-09-11T15:24:03.805+08:00", comments="Source Table: demo_role")
public static final class Role extends SqlTable {
public final SqlColumn<String> id = column("id", JDBCType.VARCHAR);
public final SqlColumn<String> name = column("name", JDBCType.VARCHAR);
public final SqlColumn<Boolean> isGeneral = column("is_general", JDBCType.BIT);
public final SqlColumn<Boolean> deleted = column("deleted", JDBCType.BIT);
public final SqlColumn<Date> gmtCreate = column("gmt_create", JDBCType.TIMESTAMP);
public final SqlColumn<Date> gmtModified = column("gmt_modified", JDBCType.TIMESTAMP);
public Role() {
super("demo_role");
}
}
} |
package org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.moditemblockreference;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.ModCreativeTabs;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.ModInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class ModBasicItemTemplate extends Item {
public ModBasicItemTemplate() {
super();
setCreativeTab(ModCreativeTabs.TabASU);
}
}
|
package com.xiv.gearplanner.models.inventory;
import javax.persistence.*;
import java.util.List;
@Entity
@Table
public class GearSlotCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private Integer originalId;
@ManyToOne
private GearSlot slot;
@ManyToMany
private List<GearSlot> disabled;
public GearSlotCategory() {
}
public GearSlotCategory(GearSlot slot) {
this.slot = slot;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public GearSlot getSlot() {
return slot;
}
public void setSlot(GearSlot slot) {
this.slot = slot;
}
public List<GearSlot> getDisabled() {
return disabled;
}
public void setDisabled(List<GearSlot> disabled) {
this.disabled = disabled;
}
@Override
public String toString() {
return "GearSlotCategory{" +
"id=" + id +
", slot=" + slot +
", disabled=" + disabled +
'}';
}
}
|
package com.pwq.utils;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.pwq.mavenT.CharsetCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @description
* @author YuYangjun
* @date 2016年8月30日 下午2:44:05
* @version V1.0
*/
public class PageHelper {
private static Logger logger = LoggerFactory.getLogger(PageHelper.class);
/**
* 获取页面
* @description
* @author YuYangjun
* @create 2016年8月13日 上午9:48:59
* @param webClient 访问客户端
* @param url 访问地址
* @param httpMethod 提交方法
* @param params 访问参数
* @param header 访问Header
* @return
*/
public static Page getPage(WebClient webClient,String url, HttpMethod httpMethod,List<NameValuePair> params, Map<String,String> header){
return getPage(webClient,url,httpMethod,params, CharsetCode.UTF8,header);
}
/**
* 获取页面
* <b>有重复尝试机制</b>
* @description
* @author YuYangjun
* @create 2016年8月13日 上午9:48:59
* @param webClient 访问客户端
* @param url 访问地址
* @param httpMethod 提交方法
* @param params 访问参数
* @param retryTimes 重复尝试次数
* @param logFlag 日志标志
* @return
*/
public static Page getPage(WebClient webClient,String url, HttpMethod httpMethod,List<NameValuePair> params,
int retryTimes, String logFlag, Map<String,String> header){
Page page;
int rt = 1;
while(rt <= retryTimes){
try{
logger.info(logFlag, rt);
page = getPage(webClient,url,httpMethod,params,CharsetCode.UTF8,header);
if(null != page){
return page;
}else{
logger.error("==>响应内容为空,正在两次尝试请求");
rt++;
}
}catch (Exception e) {
logger.error("==>获取响应出错了,正在两次尝试请求:" , e);
rt++;
}
}
return null;
}
/**
* 下载验证码图片并识别
* @param surl
* @return
*/
public static String getVerifyCode(WebClient webClient,String surl, int codeType, HashMap<String,String> header){
String verifyCode="";
try{
URL url = new URL(surl);
WebRequest webRequest = new WebRequest(url, HttpMethod.GET);
if(null!= header){
for(String key : header.keySet()){
webRequest.setAdditionalHeader(key, header.get("key"));
}
}
Page page = webClient.getPage(webRequest);
// verifyCode = CaptchaService.recognition(ImageIO.read(page.getWebResponse().getContentAsStream()),codeType);
}catch (Exception ex){
throw new RuntimeException(ex);
}
return verifyCode;
}
//--------------------------------------------------------
//以下方法无须关注
//--------------------------------------------------------
private static Page getPage(WebClient webClient,String url, HttpMethod httpMethod, List<NameValuePair> params,
CharsetCode charset, Map<String,String> header){
if(httpMethod==HttpMethod.GET){
return doGet(webClient,url,params,charset,header);
}else {
return doPost(webClient,url,params,charset,header);
}
}
private static Page doPost(WebClient webClient,String pageUrl, List<NameValuePair> reqParam,
CharsetCode charset, Map<String,String> header) {
try{
URL url = new URL(pageUrl);
WebRequest webRequest = new WebRequest(url, HttpMethod.POST);
webRequest.setAdditionalHeader("Accept-Language","zh-CN");
if(charset==null){
charset=CharsetCode.UTF8;
}
webRequest.setCharset(charset.getCode());
if(reqParam!=null){
webRequest.setRequestParameters(reqParam);
}
if(null!= header){
for(String key : header.keySet()){
webRequest.setAdditionalHeader(key, header.get("key"));
}
}
return webClient.getPage(webRequest);
}catch (Exception ex){
throw new RuntimeException(ex);
}
}
private static Page doGet(WebClient webClient,String pageUrl, List<NameValuePair> reqParam,
CharsetCode charset, Map<String, String> header) {
try{
URL url;
if(CollectionUtil.isEmpty(reqParam)){
url = new URL(pageUrl);
}else{
url = new URL(pageUrl+"?"+EntityUtils.toString(reqParam));
}
WebRequest webRequest = new WebRequest(url, HttpMethod.GET);
if(null!= header){
for(String key : header.keySet()){
webRequest.setAdditionalHeader(key, header.get("key"));
}
}
return webClient.getPage(webRequest);
}catch (Exception ex){
throw new RuntimeException(ex);
}
}
}
|
package com.sh.base.sort;
/**
* 在“堆排序”中的“堆”通常指“二叉堆(binary heap)”,许多不正规的说法说“二叉堆”其实就是一个完全二叉树(complete binary tree),这个说法正确但不准确。但在这基础上理解“二叉堆”就非常的容易了,二叉堆主要满足以下两项属性(properties):
#1 - Shape Property: 它是一个完全二叉树。
#2 - Heap Property: 主要分为max-heap property和min-heap property(这就是我以前说过的术语,很重要)
|--max-heap property :对于所有除了根节点(root)的节点 i,A[Parent]≥A[i]
|--min-heap property :对于所有除了根节点(root)的节点 i,A[Parent]≤A[i]
上图中的两个二叉树结构均是完全二叉树,但右边的才是满足max-heap property的二叉堆。
*
*
* @Auther: bjshaohang
* @Date: 2019/1/25
*/
public class b3HeapSort {
public static void main(String[] args) {
int[] array = {12,20,5,16,15,1,30,45,23,9};
sort(array);
for (int i : array) {
System.out.println(i);
}
}
public static void sort(int[] a){
for(int i = 0; i < a.length; i++){
maxHeap(a,a.length-i);
int temp = a[0];
a[0] = a[a.length-1-i];
a[a.length-1-i] = temp;
}
}
/**
* 完成一次建堆,最大值在堆的顶部(根节点)
* 从最后一个元素开始建堆,主要是为了操作非叶子节点,而且是交换倒数第i个
* @param a
* @param size
*/
public static void maxHeap(int[] a, int size){
for(int i = size-1; i >= 0; i--){
heapify(a,i,size);
}
}
/** 建堆
* 首先,堆维护MAX-HEAPIFY的前提条件是,只有堆顶元素违反堆性质,对其进行调整
* 建堆BUILD-MAX-HEAP是从后向前调整每一个非叶子结点开始……因为他是调用堆维护MAX-HEAPIFY来建堆的,故而如果要调整当前树,就要首先调整其两棵子树使其满足堆的性质,以保证MAX-HEAPIFY所需要的条件
* @param a 以完全二叉树理解
* @param currentRootNode 当前父节点的位置
* @param size 节点总数
*/
public static void heapify(int[] a, int currentRootNode,int size){
if(currentRootNode < size){
int left = 2 * currentRootNode + 1;
int right = 2 * currentRootNode + 2;
//把当前父节点的位置看成是最大的
int max = currentRootNode;
if(left < size){
if (a[left] > a[max]){
max = left;
}
}
if(right < size){
if(a[right] > a[max]){
max = right;
}
}
if(max != currentRootNode){
int temp = a[max];
a[max] = a[currentRootNode];
a[currentRootNode] = temp;
heapify(a,max,size);
}
}
}
}
|
package pt.sinfo.testDrive.web;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.ISODateTimeFormat;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import pt.sinfo.testDrive.domain.Booking;
import pt.sinfo.testDrive.domain.Root;
import pt.sinfo.testDrive.exception.TestDriveException;
@RestController
@EnableAutoConfiguration
public class BookingController {
@RequestMapping(value="/bookings/new" ,method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public Booking bookTestDrive(@RequestBody(required=true) Map<String,String> bookingInfo) {
String dealerId = bookingInfo.get("dealerId");
String vehicleId = bookingInfo.get("vehicleId");
String firstName = bookingInfo.get("firstName");
String lastName = bookingInfo.get("lastName");
String date = bookingInfo.get("pickupDate");
DateTime pickupDate = null;
try {
pickupDate = DateTime.parse(date,ISODateTimeFormat.dateTimeParser());
}catch(Exception e) {
throw new TestDriveException();
}
Booking booking = new Booking(vehicleId, firstName, lastName, pickupDate);
Root.getReference().bookVehicle(dealerId, booking);
return booking;
}
@RequestMapping(value="/bookings/cancel" ,method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void cancelBooking(@RequestParam(required=true) String bookingId,
@RequestBody(required=true) String reason) {
Root.getReference().cancelBooking(bookingId, reason);
}
}
|
/* BindingListModelMap.java
Purpose:
Description:
History:
Mon Jan 29 21:07:15 2007, Created by henrichen
Copyright (C) 2007 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zkplus.databind;
import org.zkoss.zul.ListModelMap;
import java.util.Map;
/**
* <p>This is the {@link BindingListModel} as a {@link java.util.Map} to be used with
* {@link org.zkoss.zul.Listbox}, {@link org.zkoss.zul.Grid},
* and {@link DataBinder}.
* Add or remove the contents of this model as a Map would cause the associated Listbox or Grid to change accordingly.</p>
* <p>Make as public class since 3.0.5</p>
* <p>Support BindingListModelEx since 3.1</p>
*
* @author Henri Chen
* @see BindingListModel
* @see BindingListModelExt
* @see org.zkoss.zul.ListModel
* @see org.zkoss.zul.ListModelMap
*/
public class BindingListModelMap extends ListModelMap
implements BindingListModelExt, java.io.Serializable {
private static final long serialVersionUID = 200808191420L;
/**
* @since 3.0.5
*/
public BindingListModelMap(Map map, boolean live) {
super(map, live);
}
//Map is naturally distinct
public boolean isDistinct() {
return true;
}
public int[] indexesOf(Object elm) {
final int idx = indexOf(elm);
return idx < 0 ? new int[0] : new int[] {idx};
}
}
|
public class Car extends Vehicle{
private Feature[] feature = new Feature[10];
private int carAxle;
public Car(){
super();
feature;
}
}
|
package io.rong.imlib.message;
import android.os.Parcel;
import io.rong.imlib.MessageTag;
import io.rong.message.CommandNotificationMessage;
@MessageTag(value = "RC:CmdNtf", flag = MessageTag.NONE)
public class DemoCommandNotificationMessage extends CommandNotificationMessage {
public DemoCommandNotificationMessage(Parcel in) {
super(in);
}
}
|
package com.daikit.graphql.meta.attribute;
import com.daikit.graphql.meta.GQLAbstractMetaData;
/**
* Abstract super class for GraphQL entity/data attribute meta data
*
* @author Thibaut Caselli
*/
public class GQLAttributeRightsMetaData extends GQLAbstractMetaData {
private Object role = null;
private boolean readable = true;
private boolean saveable = true;
private boolean nullableForCreate = true;
private boolean nullableForUpdate = true;
private boolean mandatoryForCreate = false;
private boolean mandatoryForUpdate = false;
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// CONSTRUCTORS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
/**
* Default constructor
*/
public GQLAttributeRightsMetaData() {
// Nothing done
}
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// METHODS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
@Override
protected void appendToString(final StringBuilder stringBuilder) {
stringBuilder.append("(RIGHTS: [").append(getRole() == null ? "ALL" : getRole()).append("] ")
.append(!isNullableForCreate() && !isNullableForUpdate() ? "[!NULL]" : "")
.append(!isNullableForCreate() ? "[!NULL-C]" : "").append(!isNullableForUpdate() ? "[!NULL-U]" : "")
.append(isMandatoryForCreate() && isMandatoryForUpdate() ? "[MAND]" : "")
.append(isMandatoryForCreate() ? "[MAND-C]" : "").append(isMandatoryForUpdate() ? "[MAND-U]" : "")
.append(readable ? "[R]" : "").append(saveable ? "[S]" : "").append(")");
}
/**
* Get whether this attribute can be null. This is a shortcut to
* ({@link #isNullableForCreate()} AND {@link #isNullableForUpdate()})
*
* @return the nullable
*/
public boolean isNullable() {
return isNullableForCreate() && isNullableForUpdate();
}
/**
* Set whether this attribute can be null. This will set
* {@link #nullableForCreate} AND {@link #nullableForUpdate} to the same
* given value
*
* @param nullable
* the nullable to set
* @return this instance
*/
public GQLAttributeRightsMetaData setNullable(final boolean nullable) {
this.setNullableForCreate(nullable);
this.setNullableForUpdate(nullable);
return this;
}
/**
* Get whether this attribute must be provided during save. This is a
* shortcut to ({@link #isMandatoryForCreate()} AND
* {@link #isMandatoryForUpdate()})
*
* @return the mandatory
*/
public boolean isMandatory() {
return isMandatoryForCreate() && isMandatoryForUpdate();
}
/**
* Set whether this attribute can be null. This will set
* {@link #mandatoryForCreate} AND {@link #mandatoryForUpdate} to the same
* given value
*
* @param mandatory
* the mandatory to set
* @return this instance
*/
public GQLAttributeRightsMetaData setMandatory(final boolean mandatory) {
this.setMandatoryForCreate(mandatory);
this.setMandatoryForUpdate(mandatory);
return this;
}
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// GETTERS / SETTERS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
/**
* Get whether this attribute will be available in schema queries for
* retrieving this attribute parent entity. Default is <code>true</code>.
*
* @return the readable
*/
public boolean isReadable() {
return readable;
}
/**
* Set whether this attribute will be available in schema queries for
* retrieving this attribute parent entity. Default is <code>true</code>.
*
* @param readable
* the readable to set
* @return this instance
*/
public GQLAttributeRightsMetaData setReadable(final boolean readable) {
this.readable = readable;
return this;
}
/**
* Get the role this attribute rights is configured for
*
* @return the role the role
*/
public Object getRole() {
return role;
}
/**
* Set the role this attribute rights is configured for
*
* @param role
* the role to set
* @return this instance
*/
public GQLAttributeRightsMetaData setRole(Object role) {
this.role = role;
return this;
}
/**
* Get whether this attribute will be available in schema mutations for
* saving this attribute parent entity. Default is <code>true</code>.
*
* @return the saveable
*/
public boolean isSaveable() {
return saveable;
}
/**
* Set whether this attribute will be available in schema mutations for
* saving this attribute parent entity. Default is <code>true</code>.
*
* @param saveable
* the saveable to set
* @return this instance
*/
public GQLAttributeRightsMetaData setSaveable(final boolean saveable) {
this.saveable = saveable;
return this;
}
/**
* Get whether this attribute can be null at parent entity creation time.
* Default is <code>true</code>.
*
* @return the nullableForCreate
*/
public boolean isNullableForCreate() {
return nullableForCreate;
}
/**
* Set whether this attribute can be null at parent entity creation time.
* Default is <code>true</code>.
*
* @param nullableForCreate
* the nullableForCreate to set
* @return this instance
*/
public GQLAttributeRightsMetaData setNullableForCreate(boolean nullableForCreate) {
this.nullableForCreate = nullableForCreate;
return this;
}
/**
* Get whether this attribute can be null at parent entity creation time.
* Default is <code>true</code>.
*
* @return the nullableForUpdate
*/
public boolean isNullableForUpdate() {
return nullableForUpdate;
}
/**
* Set whether this attribute can be null at parent entity creation time.
* Default is <code>true</code>.
*
* @param nullableForUpdate
* the nullableForUpdate to set
* @return this instance
*/
public GQLAttributeRightsMetaData setNullableForUpdate(boolean nullableForUpdate) {
this.nullableForUpdate = nullableForUpdate;
return this;
}
/**
* Get whether this attribute must be provided during parent entity
* creation. This does not mean it cannot be null, this is given by
* {@link #isNullable()} or {@link #isNullableForCreate()} methods. Default
* is <code>false</code>.
*
* @return the mandatoryForCreate
*/
public boolean isMandatoryForCreate() {
return mandatoryForCreate;
}
/**
* Set whether this attribute must be provided during parent entity
* creation. This does not mean it cannot be null, this is configurable with
* {@link #setNullable(boolean)} or {@link #setNullableForCreate(boolean)}
* methods. Default is <code>false</code>.
*
* @param mandatoryForCreate
* the mandatoryForCreate to set
* @return this instance
*/
public GQLAttributeRightsMetaData setMandatoryForCreate(boolean mandatoryForCreate) {
this.mandatoryForCreate = mandatoryForCreate;
return this;
}
/**
* Get whether this attribute must be provided during parent entity update.
* This does not mean it cannot be null, this is given by
* {@link #isNullable()} or {@link #isNullableForUpdate()} methods. Default
* is <code>false</code>.
*
* @return the mandatoryForUpdate
*/
public boolean isMandatoryForUpdate() {
return mandatoryForUpdate;
}
/**
* Set whether this attribute must be provided during parent entity update.
* This does not mean it cannot be null, this is configurable with
* {@link #setNullable(boolean)} or {@link #setNullableForUpdate(boolean)}
* methods. Default is <code>false</code>.
*
* @param mandatoryForUpdate
* the mandatoryForUpdate to set
* @return this instance
*/
public GQLAttributeRightsMetaData setMandatoryForUpdate(boolean mandatoryForUpdate) {
this.mandatoryForUpdate = mandatoryForUpdate;
return this;
}
}
|
/*
* @(#) INodeInfoService.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.nodeinfo.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.esum.appframework.service.IBaseService;
/**
*
* @author frimisun@esumtech.com
* @version $Revision: 1.2 $ $Date: 2009/01/16 08:22:31 $
*/
public interface INodeInfoService extends IBaseService {
Object insert(Object object);
Object update(Object object);
Object delete(Object object);
Object nodeInfoDetail(Object object);
Object nodeInfoPageList(Object object);
Object nodeInfoList(Object object);
void saveNodeInfoExcel (Object object, HttpServletRequest request, HttpServletResponse response) throws Exception;
Object reloadSystemLogLevel(Object object);
Object systemConfigProp(Object object);
Object reloadSystemConfigProp(Object object);
}
|
package net.awesomekorean.podo.lesson.lessons;
import net.awesomekorean.podo.R;
import java.io.Serializable;
public class Lesson28 extends LessonInit_Lock implements Lesson, LessonItem, Serializable {
private String lessonId = "L_28";
private String lessonTitle = "while";
private String lessonSubTitle = "~(으)면서";
private String[] wordFront = {"다이어트", "시작하다", "매일", "운동하다", "혼자", "재미없다"};
private String[] wordBack = {"(be on a)diet", "start", "everyday", "exercise", "alone", "not fun"};
private String[] wordPronunciation = {"-", "[시자카다]", "-", "-", "-", "[재미업따]"};
private String[] sentenceFront = {
"시작했어요.",
"다이어트를 시작했어요.",
"요즘 다이어트를 시작했어요.",
"운동해요.",
"집에서 운동해요.",
"매일 집에서 운동해요.",
"혼자 운동해요?",
"재미없지 않아요?",
"TV를 보다.",
"TV를 보면서 운동해요."
};
private String[] sentenceBack = {
"I started.",
"I started a diet.",
"I just started a diet.",
"I work out.",
"I work out at home.",
"I work out at home everyday.",
"Do you work out alone?",
"It's not fun, isn't it?",
"Watch TV.",
"I watch TV while I am working out."
};
private String[] sentenceExplain = {
"'시작해요' -> '시작했어요' (past tense)",
"You can say '다이어트' for losing weight.",
"-",
"-",
"-",
"-",
"-",
"You may got confused because this sentence used negative expression twice.\nWhen you want to ask if the other person has the same feelings/thoughts with you, you can ask '~지 않아요?'.\n'재미없다' -> '재미없' + '지 않아요?' = '재미없지 않아요?'\n\nIf there's no question mark like '~지 않아요.' it is just a negative sentence.",
"-",
"When you are doing two activities at the same time, use the '~(으)면서' form.\n\n'TV를 보다' + '운동하다' -> 'TV를 보면서 운동하다'\n'밥을 먹다' + 'TV를 보다' -> 밥을 먹으면서 TV를 보다'"
};
private String[] dialog = {
"요즘 다이어트를 시작했어요.\n매일 집에서 운동해요.",
"혼자 운동해요?\n재미없지 않아요?",
"네, 그래서 TV를 보면서 운동해요."
};
private int[] peopleImage = {R.drawable.male_b,R.drawable.female_p};
private int[] reviewId = {5,7,9};
@Override
public String getLessonSubTitle() {
return lessonSubTitle;
}
@Override
public String getLessonId() {
return lessonId;
}
@Override
public String[] getWordFront() {
return wordFront;
}
@Override
public String[] getWordPronunciation() {
return wordPronunciation;
}
@Override
public String[] getSentenceFront() {
return sentenceFront;
}
@Override
public String[] getDialog() {
return dialog;
}
@Override
public int[] getPeopleImage() {
return peopleImage;
}
@Override
public String[] getWordBack() {
return wordBack;
}
@Override
public String[] getSentenceBack() {
return sentenceBack;
}
@Override
public String[] getSentenceExplain() {
return sentenceExplain;
}
@Override
public int[] getReviewId() {
return reviewId;
}
// 레슨어뎁터 아이템
@Override
public String getLessonTitle() {
return lessonTitle;
}
}
|
package com.kheirallah.inc.graph;
/*
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
*/
public class FindTheTownJudge {
//Time: O(T + N)
//Space: O(N)
public static int findTheJudge(int N, int[][] trust) {
int[] count = new int[N + 1];
for (int[] t : trust) {
count[t[0]]--;
count[t[1]]++;
}
for (int i = 0; i < N; i++) {
if (count[i] == N - 1) return i;
}
return -1;
}
public static void main(String[] args) {
int[][] trust = new int[][]{{1, 3}, {1, 4}, {2, 3}, {2, 4}, {4, 3}};
int N = 4;
System.out.println(findTheJudge(N, trust));
}
}
|
package psoft.backend.documentacao;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("psoft.backend.controller"))
.build()
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("UCDb: classificações e reviews de cursos da UFCG")
.description("O UFCG Cursos database é uma aplicação para classificação e reviews de disciplinas de " +
"cursos da UFCG. Por enquanto, a versão 1 do sistema será alimentada apenas com disciplinas do " +
"curso de Ciência da Computação. Os usuários dessa aplicação irão construir conteúdo sobre as " +
"disciplinas de forma colaborativa através de comentários e likes nas disciplinas. O sistema " +
"deve usar essa informação construída para rankear as disciplinas do curso." +
"Esta API RESTful pode recebe e entrega dados em formato JSON e tenta se aderir ao máximo à" +
" arquitetura REST. Nesta página é possivél reconhecer e testar as rotas de acesso ao dados," +
"conhecer os parâmetro nescessários e as estruturas de dados retornadas. Além disso esta API" +
"tenta ao também ao máximo seguir boas práticas para nomes de rotas e uso de métodos HTTP. Por" +
" fim, está API trata de mananeira adequada os erros mais recorrentes que podem surgir.")
.version("1.0")
.contact(new Contact("Eduardo Henrique Silva", "", "eduardo.henrique.silva@ccc.ufcg.edu.br"))
.license("Apache License 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
.build();
}
}
|
package com.gaoshin.top;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.gaoshin.sorma.AndroidContentResolver;
import com.gaoshin.sorma.AnnotatedORM;
import common.android.AndroidUtil;
import common.android.PhoneInfo;
import common.util.web.WebServiceUtil;
public class BootReceiver extends BroadcastReceiver {
private AnnotatedORM orm = TopContentProvider.orm;
@Override
public void onReceive(Context context, Intent intent) {
TopApplication.startService(context, intent);
checkVersion(context);
}
private void checkVersion(final Context context) {
orm.setContentResolver(new AndroidContentResolver(context.getContentResolver()));
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
PhoneInfo info = AndroidUtil.getPhoneInfo(context);
String pkg = info.getApp();
String[] domain = pkg.split("[\\.]+");
int ver = info.getVersion();
String path = "http://" + domain[1] + "." + domain[0] + "/" + domain[2] + "/" + ver + "/conf.html";
ConfigurationList configurationList = WebServiceUtil.get(new DefaultHttpClient(), path, ConfigurationList.class);
for (Configuration conf : configurationList.getList()) {
orm.delete(Configuration.class, "ckey=?", new String[] { conf.getKey() });
orm.insert(conf);
}
} catch (Exception e) {
}
return null;
}
}.execute(new Void[0]);
}
}
|
package com.mercadolibre.bootcampmelifrescos.repository;
import com.mercadolibre.bootcampmelifrescos.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface ProductRepository extends JpaRepository<Product, Long> {
@Query(value = "SELECT p FROM Product p left join Category c on p.category.id = c.id where c.code = :categoryCode")
List<Product> findAllByCategoryCode(String categoryCode);
}
|
package com.nway.web.common.event;
import java.util.Map;
public class DbRecordUpdateEvent extends GenericEvent {
private static final long serialVersionUID = 7187657637813802346L;
public DbRecordUpdateEvent(Map<String, String> source) {
super(source);
}
}
|
package com.sinodynamic.hkgta.dto.mms;
import java.io.Serializable;
import org.apache.commons.lang.math.NumberUtils;
public class SpaRetreatDto implements Serializable{
private static final long serialVersionUID = 1L;
private Long displayOrder;
private Long retId;
private String retName;
private String picPath;
private String description;
private String status;
private Long itemSize;
public SpaRetreatDto(){
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPicPath() {
return picPath;
}
public void setPicPath(String picPath) {
this.picPath = picPath;
}
public Long getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Object displayOrder) {
this.displayOrder = (displayOrder!=null ? NumberUtils.toLong(displayOrder.toString()):null);
}
public Long getRetId() {
return retId;
}
public void setRetId(Object retId) {
this.retId = (retId!=null ? NumberUtils.toLong(retId.toString()):null);
}
public String getRetName() {
return retName;
}
public void setRetName(String retName) {
this.retName = retName;
}
public Long getItemSize() {
return itemSize;
}
public void setItemSize(Object itemSize) {
this.itemSize = (itemSize!=null ? NumberUtils.toLong(itemSize.toString()):null);
}
}
|
package com.yugy.twentyonedays.ui.fragment;
import com.yugy.twentyonedays.R;
import com.yugy.twentyonedays.dao.datahelper.DeletedProjectsDataHelper;
import com.yugy.twentyonedays.model.Project;
import com.yugy.twentyonedays.ui.activity.MainActivity;
import com.yugy.twentyonedays.ui.adapter.DeletedProjectsAdapter;
import com.yugy.twentyonedays.ui.view.AppMsg;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.ArrayList;
import eu.inmite.android.lib.dialogs.ISimpleDialogListener;
import eu.inmite.android.lib.dialogs.SimpleDialogFragment;
/**
* Created by yugy on 13-12-5.
*/
public class MainDeletedFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,
AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener, ActionMode.Callback,
ISimpleDialogListener{
private GridView mGridView;
private DeletedProjectsAdapter mAdapter;
private DeletedProjectsDataHelper mDataHelper;
private static final int DELETE_DIALOG_REQUEST_CODE = 10010;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_deleted, container, false);
mGridView = (GridView) rootView.findViewById(R.id.main_deleted_gridview);
mGridView.setEmptyView(rootView.findViewById(R.id.main_deleted_empty_view));
mAdapter = new DeletedProjectsAdapter(this);
mGridView.setAdapter(mAdapter);
mGridView.setOnItemClickListener(this);
mGridView.setOnItemLongClickListener(this);
mDataHelper = new DeletedProjectsDataHelper(getActivity());
getLoaderManager().initLoader(0, null, this);
return rootView;
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return mDataHelper.getCursorLoader();
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mAdapter.changeCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mAdapter.changeCursor(null);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AppMsg.makeText(getActivity(), "123", AppMsg.STYLE_CONFIRM).show();
}
private ArrayList<Integer> mItemChecked = new ArrayList<Integer>();
public ArrayList<Integer> getItemChecked(){
return mItemChecked;
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
mItemChecked.add(position);
view.setBackgroundResource(R.drawable.list_focused_apptheme);
mGridView.setOnItemClickListener(mMultiSelectItemClickListener);
mGridView.setOnItemLongClickListener(null);
((MainActivity)getActivity()).setActionMode(((ActionBarActivity)getActivity()).startSupportActionMode(this));
return true;
}
private AdapterView.OnItemClickListener mMultiSelectItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if(mItemChecked.contains(position)){
mItemChecked.remove(new Integer(position));
view.setBackgroundResource(R.drawable.bg_card_white);
}else{
mItemChecked.add(position);
view.setBackgroundResource(R.drawable.list_focused_apptheme);
}
if(mItemChecked.size() == 0){
((MainActivity)getActivity()).getActionMode().finish();
}else{
((MainActivity)getActivity()).getActionMode().setSubtitle("已选择" + mItemChecked.size() + "个");
}
}
};
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.main_project_deleted_contextual_menu, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
actionMode.setTitle("批量操作");
actionMode.setSubtitle("已选择1个");
return true;
}
private ActionMode mActionMode;
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.action_delete:
if(mItemChecked.size() != 0){
mActionMode = actionMode;
SimpleDialogFragment.createBuilder(getActivity(), getFragmentManager())
.setMessage("确定删除这些项目?此操作不可逆转")
.setTitle("警告")
.setPositiveButtonText("确定")
.setNegativeButtonText("取消")
.setTargetFragment(this, DELETE_DIALOG_REQUEST_CODE).show();
}
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
for(int position : mItemChecked){
mGridView.getChildAt(position).setBackgroundResource(R.drawable.bg_card_white);
}
mItemChecked = new ArrayList<Integer>();
mGridView.setOnItemClickListener(this);
mGridView.setOnItemLongClickListener(this);
}
@Override
public void onPositiveButtonClicked(int requestCode) {
switch (requestCode){
case DELETE_DIALOG_REQUEST_CODE:
ArrayList<Project> projectsToDelete = new ArrayList<Project>();
for(int i : mItemChecked){
Project project = mAdapter.getItem(i);
projectsToDelete.add(project);
}
mItemChecked = new ArrayList<Integer>();
if(mDataHelper.bulkDelete(projectsToDelete) != 0){
AppMsg.makeText(getActivity(), "项目已成功删除", AppMsg.STYLE_INFO).show();
}else{
AppMsg.makeText(getActivity(), "数据库操作失败,错误代码101", AppMsg.STYLE_ALERT).show();
}
mActionMode.finish();
break;
}
}
@Override
public void onNegativeButtonClicked(int requestCode) {
switch (requestCode){
case DELETE_DIALOG_REQUEST_CODE:
mActionMode.finish();
break;
}
}
}
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class ButtonSelectMinigame extends Actor
{
private String gameName;
private WorldMainMenu worldMainMenu;
public ButtonSelectMinigame(WorldMainMenu worldMainMenu, String gameName, String imageName )
{
this.worldMainMenu = worldMainMenu;
this.gameName = gameName;
setImage(imageName);
}
public void act()
{
if (Greenfoot.mouseClicked(this))
{
worldMainMenu.StartNewGame(gameName);
}
}
}
|
package ninja.pelirrojo.takibat.irc;
public class PrivMsg extends ParsedLine{
private User u;
private String line;
protected PrivMsg(String s,User u,String line){
super(s);
this.u = u;
this.line = line;
}
public User getUser(){
return u;
}
public String getLine(){
return line;
}
public String toString(){
try{
return String.format("<%s> %s",u.getNick(),line.trim());
}
catch(Exception e){
return super.toString();
}
}
}
|
package friend.group.bank.obj.domain.member.status;
public enum PaydayStauts {
FIX("급여일 고정"),
FIRST("첫째주"),
LAST("마지막주");
private String desc;
PaydayStauts(String desc) {
this.desc = desc;
}
}
|
package com.lesports.albatross.adapter.activities;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lesports.albatross.R;
import com.lesports.albatross.entity.activities.ActivitiesEntity;
import com.lesports.albatross.entity.community.CommunityUser;
import com.lesports.albatross.fragment.activities.ActivitiesFragment;
import com.lesports.albatross.utils.image.ImageLoader;
import com.lesports.albatross.utils.image.ImageLoaderUtil;
import com.lesports.albatross.utils.user.UserUtils;
import java.util.List;
/**
* 活动adapter
* Created by jiangjianxiong on 16/6/20.
*/
public class ActivitiesAdapter extends BaseAdapter {
private ActivitiesFragment mFragment;
private LayoutInflater inflater;
private List<ActivitiesEntity> mList;
private String userid = "-1";
public ActivitiesAdapter(ActivitiesFragment mFragment, List<ActivitiesEntity> list) {
this.mFragment = mFragment;
this.inflater = LayoutInflater.from(mFragment.getActivity());
this.mList = list;
if (UserUtils.isLogin(mFragment.getActivity())) {
userid = UserUtils.getUserId(mFragment.getActivity());
}
}
@Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
@Override
public ActivitiesEntity getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ActivitiesAdapter.ViewHolder holder;
if (convertView == null) {
holder = new ActivitiesAdapter.ViewHolder();
convertView = inflater.inflate(R.layout.activities_image_grid_item, parent, false);
holder.photo = (SimpleDraweeView) convertView.findViewById(R.id.gv_image_id);
holder.tv_title = (TextView) convertView.findViewById(R.id.title);
holder.tv_likes = (TextView) convertView.findViewById(R.id.tv_likes);
holder.iv_heart = (ImageView) convertView.findViewById(R.id.iv_heart);
convertView.setTag(holder);
} else {
holder = (ActivitiesAdapter.ViewHolder) convertView.getTag();
}
ActivitiesEntity entity = getItem(position);
if (null != entity) {
if (null != entity.getThumbnail_uris()) {
if (!entity.getThumbnail_uris().isEmpty()) {
if (null != entity.getThumbnail_uris().get(0)) {
ImageLoaderUtil.getInstance().loadImage(mFragment.getActivity(), new ImageLoader.Builder()
.url(entity.getThumbnail_uris().get(0)).widthAndHeight(364, 252).placeHolder(R.mipmap.default_image_bg)
.mImageView(holder.photo).build());
}
}
}
//message
String name = entity.getAuthor().getNickname();
if (!TextUtils.isEmpty(name)) {
holder.tv_title.setText(name.trim());
} else {
holder.tv_title.setText("");
}
//likes
holder.tv_likes.setText(String.valueOf(entity.getLikes()));
//isLike
if (!"-1".equals(userid)) {
if (null != entity.getMoment_likes()) {
holder.iv_heart.setImageResource(!getIsLike(entity.getMoment_likes()) ?
R.drawable.community_item_like_selector :
R.mipmap.community_ic_like_pre);
} else {
holder.iv_heart.setImageResource(R.mipmap.community_ic_like_nor);
}
} else {
holder.iv_heart.setImageResource(R.mipmap.community_ic_like_nor);
}
OnLikeListener listener = new OnLikeListener(position);
holder.iv_heart.setOnClickListener(listener);
holder.tv_likes.setOnClickListener(listener);
}
return convertView;
}
private class ViewHolder {
SimpleDraweeView photo;
TextView tv_title, tv_likes;
ImageView iv_heart;
}
private class OnLikeListener implements View.OnClickListener {
private int pos;
OnLikeListener(int pos) {
this.pos = pos;
}
@Override
public void onClick(View v) {
mFragment.like(!getIsLike(mList.get(pos).getMoment_likes()), pos);
}
}
/**
* 检查是否已经点赞
*/
private boolean getIsLike(List<CommunityUser> moment_likes) {
boolean isLike = Boolean.FALSE;
for (CommunityUser user : moment_likes) {
if (userid.equals(user.getUser().getUser_id())) {
isLike = true;
break;
}
}
return isLike;
}
} |
package DynamicProgramming;
public class ClimbingStairs {
public int climbStairs(int n){
if(n<=0) return 0;
if(n==1) return 1;
if(n==2) return 2;
int n_1 = 2;
int n_2 = 1;
int res = 0;
for(int i = 3; i <=n; i++){
res = n_2 + n_1;
n_2= n_1;
n_1 =res;
}
return res;
}
// public int climbStairs(int n) {
// int [] result = new int[n+1];
//
//
// result[0] = 0;
//
// result[1] = 1;
//
// result[2] = 2;
//
//
//
// for(int i = 3 ; i <= n ; i++){
//
// result[i] = result[i-1]+result[i-2];
// System.out.println(result[i]);
// }
//
//
//
// return result[n];
//
// }
public static void main(String[] args) {
// TODO Auto-generated method stub
ClimbingStairs cs = new ClimbingStairs();
System.out.println(cs.climbStairs(100));
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.xml;
import xyz.noark.core.annotation.tpl.TplAttr;
import xyz.noark.core.annotation.tpl.TplFile;
/**
* 游戏服务器启动配置对象.
*
* @author 小流氓[176543888@qq.com]
*/
@TplFile(value = "game-config.xml")
public class GameConfig {
@TplAttr(name = "pid")
private String pid = "dev";
@TplAttr(name = "sid")
private int sid = 1;
@TplAttr(name = "sname")
private String sname = "研发一区";
@TplAttr(name = "puc", required = false)
private int pcu = 3000;
@TplAttr(name = "mru", required = false)
private int mru = 18_0000;
@TplAttr(name = "network.port")
private int port = 12580;
@TplAttr(name = "network.heartBeat")
private int heartBeat = 300;
@TplAttr(name = "network.crypto")
private boolean crypto = false;
@TplAttr(name = "network.compress")
private boolean compress = false;
@TplAttr(name = "network.compressThreshold")
private int compressThreshold = 1024;
@TplAttr(name = "network.workThreads", required = false)
private int workThreads = 0;
@TplAttr(name = "data.templatePath")
private String templatePath = "/home/wdj/template/";
@TplAttr(name = "data.saveInterval")
private int saveInterval = 500;
@TplAttr(name = "data.offlineInterval")
private int offlineInterval = 3600;
@TplAttr(name = "GlobalRedis.ip")
private String redisIp;
public String getPid() {
return pid;
}
public int getSid() {
return sid;
}
public String getSname() {
return sname;
}
public int getPcu() {
return pcu;
}
public int getMru() {
return mru;
}
public int getPort() {
return port;
}
public int getHeartBeat() {
return heartBeat;
}
public boolean isCrypto() {
return crypto;
}
public boolean isCompress() {
return compress;
}
public int getCompressThreshold() {
return compressThreshold;
}
public int getWorkThreads() {
return workThreads;
}
public String getTemplatePath() {
return templatePath;
}
public int getSaveInterval() {
return saveInterval;
}
public int getOfflineInterval() {
return offlineInterval;
}
public String getRedisIp() {
return redisIp;
}
@Override
public String toString() {
return "GameConfig [pid=" + pid + ", sid=" + sid + ", sname=" + sname + ", pcu=" + pcu + ", mru=" + mru + ", port=" + port + ", heartBeat=" + heartBeat + ", crypto=" + crypto + ", compress=" + compress + ", compressThreshold=" + compressThreshold
+ ", workThreads=" + workThreads + ", templatePath=" + templatePath + ", saveInterval=" + saveInterval + ", offlineInterval=" + offlineInterval + "]";
}
} |
package exceptions;
public class CannotDeleteSomeFileException extends Exception {}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.instrument;
import java.lang.instrument.Instrumentation;
/**
* Java agent that saves the {@link Instrumentation} interface from the JVM
* for later use.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver
*/
public final class InstrumentationSavingAgent {
private static volatile Instrumentation instrumentation;
private InstrumentationSavingAgent() {
}
/**
* Save the {@link Instrumentation} interface exposed by the JVM.
*/
public static void premain(String agentArgs, Instrumentation inst) {
instrumentation = inst;
}
/**
* Save the {@link Instrumentation} interface exposed by the JVM.
* This method is required to dynamically load this Agent with the Attach API.
*/
public static void agentmain(String agentArgs, Instrumentation inst) {
instrumentation = inst;
}
/**
* Return the {@link Instrumentation} interface exposed by the JVM.
* <p>Note that this agent class will typically not be available in the classpath
* unless the agent is actually specified on JVM startup. If you intend to do
* conditional checking with respect to agent availability, consider using
* {@link org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver#getInstrumentation()}
* instead - which will work without the agent class in the classpath as well.
* @return the {@code Instrumentation} instance previously saved when
* the {@link #premain} or {@link #agentmain} methods was called by the JVM;
* will be {@code null} if this class was not used as Java agent when this
* JVM was started or it wasn't installed as agent using the Attach API.
* @see org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver#getInstrumentation()
*/
public static Instrumentation getInstrumentation() {
return instrumentation;
}
}
|
package com.jhfactory.aospimagepick.request;
import android.support.annotation.NonNull;
import com.jhfactory.aospimagepick.helper.PickImageHelper;
public class ImagePickRequest {
private PickImageHelper mHelper;
ImagePickRequest(PickImageHelper helper) {
this.mHelper = helper;
}
@NonNull
public PickImageHelper getHelper() {
return mHelper;
}
}
|
package dlmbg.pckg.sistem.akademik;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class RangkingActivity extends ListActivity {
public String nim;
JSONArray str_login = null;
ArrayList<HashMap<String, String>> angkatan = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.panel_rangking);
JSONParser jParser = new JSONParser();
String link_url = "http://10.0.2.2/siakad-andro/rangking.php";
JSONObject json = jParser.AmbilJson(link_url);
try {
str_login = json.getJSONArray("angk");
for(int i = 0; i < str_login.length(); i++){
JSONObject ar = str_login.getJSONObject(i);
String ang = ar.getString("angkatan");
String jur = ang.substring(0, 2);
String t_angkatan = ang.substring(2, 4);
String tampil = "";
if(jur.trim().equals("11"))
{
tampil = "Teknik Informatika 20"+t_angkatan;
}
else if(jur.trim().equals("31"))
{
tampil = "Manajemen Informatika 20"+t_angkatan;
}
HashMap<String, String> map = new HashMap<String, String>();
map.put("angkatan", tampil);
map.put("kodeangk", ang);
angkatan.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, angkatan,R.layout.list_item,new String[] { "angkatan", "kodeangk"}, new int[] {R.id.tangk, R.id.kodeangk});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String kode_ang = ((TextView) view.findViewById(R.id.kodeangk)).getText().toString();
Intent in = new Intent(getApplicationContext(), DetailRangkingActivity.class);
in.putExtra("kodeangk", kode_ang);
startActivity(in);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.opt_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.url:
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stikombanyuwangi.ac.id"));
startActivity(intent);
return true;
case R.id.tentang:
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("SIAKAD STIKOM BANYUWANGI");
alertDialog.setMessage("Aplikasi SIAKAD berbasis Android ini merupakan salah satu dari sekian banyak proyek 2M" +
" serta segelintir penelitian yang saya kerjakan di kampus. Semoga aplikasi ini bisa bermanfaat untuk " +
" kita semua.\n\nSalam, Gede Lumbung\nhttp://gedelumbung.com");
alertDialog.setButton("#OKOK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package be.kuleuven.mume.test;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class VraagTest {
@Before
public void startup() {
//Hello
}
@Test
public void testStoreVraag() throws IOException{
URL url = new URL("http://localhost:8888/vraag?q=add&text=Hoe zou dit moeten?&vakid=agltb2JpbGVudmlyCQsSA1ZhaxgBDA");
URLConnection conn = url.openConnection();
String responcecode = conn.getHeaderField(0);
Assert.assertEquals("HTTP/1.1 200 OK", responcecode);
}
//@Test
public void testWrongUrl() throws IOException{
URL url = new URL("http://localhost:8888/vak?q=add&name=reza&hashtag=mijnvak");
URLConnection conn = url.openConnection();
String responcecode = conn.getHeaderField(0);
Assert.assertNotSame("HTTP/1.1 200 OK", responcecode);
}
}
|
package com.cg.osce.apibuilder.pojo;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"petstore_auth"
})
public class Security {
@JsonProperty("petstore_auth")
private List<String> petstoreAuth = null;
@JsonProperty("petstore_auth")
public List<String> getPetstoreAuth() {
return petstoreAuth;
}
@JsonProperty("petstore_auth")
public void setPetstoreAuth(List<String> petstoreAuth) {
this.petstoreAuth = petstoreAuth;
}
}
|
package br.com.youse.redditfeed.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import java.util.concurrent.CountDownLatch;
public class SplashActivity extends AppCompatActivity {
private final CountDownLatch timeoutLatch = new CountDownLatch(1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
final Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
timeoutLatch.countDown();
}
});
thread.start();
goLogin();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
timeoutLatch.countDown();
return true;
}
private void goAfterSplashTimeout(final Intent intent) {
final Thread thread = new Thread(new Runnable() {
public void run() {
try {
timeoutLatch.await();
} catch (InterruptedException e) {
}
SplashActivity.this.runOnUiThread(new Runnable() {
public void run() {
startActivity(intent);
finish();
}
});
}
});
thread.start();
}
protected void goLogin() {
goAfterSplashTimeout(new Intent(this, PostsActivity.class));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.