text
stringlengths 10
2.72M
|
|---|
package com.beiyelin.commonwx.openportal.service;
import com.beiyelin.commonwx.common.exception.WxErrorException;
import com.beiyelin.commonwx.common.session.WxSessionManager;
import com.beiyelin.commonwx.mp.api.WxMpMessageHandler;
import com.beiyelin.commonwx.mp.api.WxMpService;
import com.beiyelin.commonwx.mp.bean.message.WxMpXmlMessage;
import com.beiyelin.commonwx.mp.bean.message.WxMpXmlOutMessage;
import com.beiyelin.commonwx.open.api.impl.WxOpenMessageRouter;
import com.beiyelin.commonwx.open.api.impl.WxOpenServiceImpl;
import com.beiyelin.commonwx.openportal.config.WechatOpenProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Map;
/**
* @Description:
* @Author: newmannhu@qq.com
* @Date: Created in 2018-04-07 15:34
**/
@Service
@Slf4j
public class WxOpenPortalService extends WxOpenServiceImpl {
@Autowired
private WechatOpenProperties wechatOpenProperties;
private WxOpenMessageRouter wxOpenMessageRouter;
@PostConstruct
public void init() {
wxOpenMessageRouter = new WxOpenMessageRouter(this);
wxOpenMessageRouter.rule().handler(new WxMpMessageHandler() {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
log.info("\n接收到 {} 公众号请求消息,内容:{}", wxMpService.getWxMpConfigStorage().getAppId(), wxMpXmlMessage);
return null;
}
}).next();
}
public WxOpenMessageRouter getWxOpenMessageRouter(){
return wxOpenMessageRouter;
}
}
|
/*
* HodroistView.java
*/
package org.hodroist.app;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
/**
* The application's main frame.
*/
public class HodroistView extends FrameView {
public static ArrayList<Track> mp3Collection;
DefaultTableModel tableModel;
public HodroistView(SingleFrameApplication app) {
super(app);
//Create table model
tableModel = new DefaultTableModel();
tableModel.addColumn("Artist");
tableModel.addColumn("Title");
tableModel.addColumn("Album");
tableModel.addColumn("Year");
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
//Obtain mp3 collection and show items on GUI
mp3Collection = new Collection().scanFiles();
showCollection();
}
@Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = HodroistApp.getApplication().getMainFrame();
aboutBox = new HodroistAboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
HodroistApp.getApplication().show(aboutBox);
}
@Action
public void showConnectBox(){
if (connectionBox == null) {
JFrame mainFrame = HodroistApp.getApplication().getMainFrame();
connectionBox = new HodroistConnectBox(mainFrame,statusMessageLabel,mp3Collection);
connectionBox.setLocationRelativeTo(mainFrame);
}
HodroistApp.getApplication().show(connectionBox);
}
//Show mp3 files info on GUI
public void showCollection(){
for (int i=0; i<mp3Collection.size(); i++){
Track track = (Track) mp3Collection.get(i);
addRowToTable(track.artist,track.title,track.album,track.year);
}
}
//Add a new mp3 file to table on GUI
public void addRowToTable(String artist,String title, String album, String year){
tableModel.insertRow(tableModel.getRowCount(), new Object[]{artist,title,album,year});
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel = new javax.swing.JPanel();
tracksTableScrollPane = new javax.swing.JScrollPane();
tracksTable = new javax.swing.JTable();
viewLabel = new javax.swing.JLabel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
connectionMenu = new javax.swing.JMenu();
connectionMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.hodroist.app.HodroistApp.class).getContext().getResourceMap(HodroistView.class);
mainPanel.setBackground(resourceMap.getColor("mainPanel.background")); // NOI18N
mainPanel.setName("mainPanel"); // NOI18N
mainPanel.setPreferredSize(new java.awt.Dimension(800, 161));
tracksTableScrollPane.setName("tracksTableScrollPane"); // NOI18N
tracksTable.setBackground(resourceMap.getColor("tracksTable.background")); // NOI18N
tracksTable.setModel(tableModel);
tracksTable.setName("tracksTable"); // NOI18N
tracksTable.getTableHeader().setReorderingAllowed(false);
tracksTableScrollPane.setViewportView(tracksTable);
tracksTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tracksTable.columnModel.title0")); // NOI18N
tracksTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tracksTable.columnModel.title1")); // NOI18N
tracksTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tracksTable.columnModel.title2")); // NOI18N
tracksTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tracksTable.columnModel.title3")); // NOI18N
viewLabel.setFont(resourceMap.getFont("viewLabel.font")); // NOI18N
viewLabel.setForeground(resourceMap.getColor("viewLabel.foreground")); // NOI18N
viewLabel.setText(resourceMap.getString("viewLabel.text")); // NOI18N
viewLabel.setName("viewLabel"); // NOI18N
org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainPanelLayout.createSequentialGroup()
.add(viewLabel)
.addContainerGap(676, Short.MAX_VALUE))
.add(tracksTableScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 859, Short.MAX_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainPanelLayout.createSequentialGroup()
.add(viewLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(tracksTableScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE))
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.hodroist.app.HodroistApp.class).getContext().getActionMap(HodroistView.class, this);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
connectionMenu.setText(resourceMap.getString("connectionMenu.text")); // NOI18N
connectionMenu.setName("connectionMenu"); // NOI18N
connectionMenuItem.setAction(actionMap.get("showConnectBox")); // NOI18N
connectionMenuItem.setText(resourceMap.getString("connectionMenuItem.text")); // NOI18N
connectionMenuItem.setName("connectionMenuItem"); // NOI18N
connectionMenu.add(connectionMenuItem);
menuBar.add(connectionMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setBackground(resourceMap.getColor("statusPanel.background")); // NOI18N
statusPanel.setName("statusPanel"); // NOI18N
statusPanel.setPreferredSize(new java.awt.Dimension(800, 60));
statusPanelSeparator.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("statusPanelSeparator.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("statusPanelSeparator.border.titleFont"))); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setFont(resourceMap.getFont("statusMessageLabel.font")); // NOI18N
statusMessageLabel.setForeground(resourceMap.getColor("statusMessageLabel.foreground")); // NOI18N
statusMessageLabel.setText(resourceMap.getString("statusMessageLabel.text")); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.add(statusMessageLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 655, Short.MAX_VALUE)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(statusAnimationLabel)
.addContainerGap())
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 859, Short.MAX_VALUE)
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, statusPanelLayout.createSequentialGroup()
.add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusPanelLayout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(statusMessageLabel)
.add(statusAnimationLabel))
.add(114, 114, 114))
.add(statusPanelLayout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu connectionMenu;
private javax.swing.JMenuItem connectionMenuItem;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JProgressBar progressBar;
private javax.swing.JLabel statusAnimationLabel;
public javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
private javax.swing.JTable tracksTable;
private javax.swing.JScrollPane tracksTableScrollPane;
private javax.swing.JLabel viewLabel;
// End of variables declaration//GEN-END:variables
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
private JDialog connectionBox;
}
|
package api.lang.stringbuilder;
public class StringBuildEx {
public static void main(String[] args) {
//StringBuffer, StringBuilder
String str = new String("java");
StringBuffer sb = new StringBuffer("java");
System.out.println(str);
System.out.println(sb);
//차이점
str = str + "choco";
sb.append("choco");
System.out.println(str);
System.out.println(sb);
//끝에 문자열 추가
sb.append("chip");
System.out.println(sb);
//중간에 문자열 추가
sb.insert(4, " ");
System.out.println(sb);
//문자열 변경 replace(해당 인덱스 번째를 변경)
sb.replace(0, 4,"자바");
System.out.println(sb);
//문자열 삭제 delete
sb.delete(2, sb.length());
System.out.println(sb);
//문자열 거꾸로 reverse()
sb.reverse();
System.out.println(sb);
//다시거꾸로
sb.reverse();
System.out.println(sb);
//toString()
if(sb.toString().equals("자바")) {
System.out.println("문자열이 같음");
}
}
}
|
package com.mx.profuturo.bolsa.model.common;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class GenericParamRequestBean {
private String param;
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
|
package uk.co.rentalcars.main;
import java.util.HashMap;
public class StringIntegerHashMap {
public StringIntegerHashMap(){
HashMap<String, Integer> stringInt = new HashMap<String, Integer>();
stringInt.put("zero", 0);
stringInt.put("one", 1);
stringInt.put("two", 2);
stringInt.put("three", 3);
stringInt.put("four", 4);
stringInt.put("five", 5);
stringInt.put("six", 6);
stringInt.put("seven", 7);
stringInt.put("eight", 8);
stringInt.put("nine", 9);
}
}
|
package de.zarncke.lib.log;
import javax.annotation.Nonnull;
import de.zarncke.lib.ctx.Context;
import de.zarncke.lib.err.ExceptionUtil;
import de.zarncke.lib.util.Replacer;
import de.zarncke.lib.util.Replacer.Builder;
import de.zarncke.lib.value.Default;
/**
* Provides methods for cleaning stack traces and making them more human readable.
* Derived classes may add to the rules.
* static methods are available to use the currently set {@link StackTraceCleaner}.
*
* @author Gunnar Zarncke
* @clean 20.03.2012
*/
public class StackTraceCleaner {
public static final Context<StackTraceCleaner> CTX = Context.of(Default.of(new StackTraceCleaner(),
StackTraceCleaner.class));
private static final String PATTERN_EXCEPTION_NOT_INTENDED_TO_BE_THROWN = //
"reported by de.zarncke.lib.err.ExceptionNotIntendedToBeThrown\n";
private final Replacer reportCleaner;
protected StackTraceCleaner() {
Builder builder = Replacer.multiline();
addPatterns(builder); // NOPMD intended extensibility
this.reportCleaner = builder.done();
}
/**
* Derived classes may add patterns here - note that the class is not fully initialized yet!
* The replacements are executed in the order they are added.
* Add complex patterns before the call to super.addPatterns().
* Basic patterns should be added afterwards.
*
* @param cleanerBuilder to add patterns to
*/
protected void addPatterns(final Replacer.Builder cleanerBuilder) {
String contextPattern = "(?:"
+ quoteStacktrace(" at de.zarncke.lib.block.ABlock$2.execute(ABlock.java:41)\n")
+ "|"
+ quoteStacktrace(" at de.zarncke.lib.ctx.Context.runWith(Context.java:230)\n")
+ "|"
+ quoteStacktrace(" at de.zarncke.lib.ctx.Context$7.execute(Context.java:279)\n")
+ "|"
+ quoteStacktrace(" at de.zarncke.lib.block.Running.execute(Running.java:10)\n")
+ "|"
+ quoteStacktrace(" at de.zarncke.lib.block.Running.execute(Running.java:8)\n")
+ ")*"
+ quoteStacktrace(" at de.zarncke.lib.ctx.Context.runWith(Context.java:230)\n"
+ " at de.zarncke.lib.ctx.Context.runWith(Context.java:216)\n");
cleanerBuilder
.replaceAllRegex("(?:" + quoteStacktrace(" at org.eclipse.jdt.internal.junit") + ".*\\r?\\n)+",
" at [Eclipse.JDT]\n")
.replaceAllRegex(
quoteStacktrace(" at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
+ " at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n"
+ " at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n"
+ " at java.lang.reflect.Method.invoke(Method.java:597)\n"
+ " at junit.framework.TestCase.runTest(TestCase.java:168)\n"
+ " at junit.framework.TestCase.runBare(TestCase.java:134)\n"
+ " at junit.framework.TestResult$1.protect(TestResult.java:110)\n"
+ " at junit.framework.TestResult.runProtected(TestResult.java:128)\n"
+ " at junit.framework.TestResult.run(TestResult.java:113)\n"
+ " at junit.framework.TestCase.run(TestCase.java:124)\n"
+ " at junit.framework.TestSuite.runTest(TestSuite.java:243)\n"
+ " at junit.framework.TestSuite.run(TestSuite.java:238)"), " at [JUnit]")
.replaceAllRegex(
quoteStacktrace(" at junit.framework.TestCase.runBare(TestCase.java:134)\n"
+ " at junit.framework.TestResult$1.protect(TestResult.java:110)\n"
+ " at junit.framework.TestResult.runProtected(TestResult.java:128)\n"
+ " at junit.framework.TestResult.run(TestResult.java:113)\n"
+ " at junit.framework.TestCase.run(TestCase.java:124)\n"
+ " at junit.framework.TestSuite.runTest(TestSuite.java:243)\n"
+ " at junit.framework.TestSuite.run(TestSuite.java:238)"), " at [JUnit call]")
.replaceAllRegex(
quoteStacktrace(PATTERN_EXCEPTION_NOT_INTENDED_TO_BE_THROWN
+ " at de.zarncke.lib.log.group.GroupingLog.report(GroupingLog.java:53)\n"
+ " at de.zarncke.lib.err.Warden.logFromWithinLogging(Warden.java:63)\n"
+ " at de.zarncke.lib.err.Warden.disregard(Warden.java:43)"),
"reported by [disregardAndReport]")
.replaceAllRegex(
quoteStacktrace(PATTERN_EXCEPTION_NOT_INTENDED_TO_BE_THROWN
+ " at de.zarncke.lib.log.group.GroupingLog.report(GroupingLog.java:98)\n"
+ " at de.zarncke.lib.err.Warden.log(Warden.java:57)\n"
+ " at de.zarncke.lib.err.Warden.report(Warden.java:50)\n"
+ " at de.zarncke.lib.err.Warden.encounter(Warden.java:157)\n"
+ " at de.zarncke.lib.err.Warden.finish(Warden.java:145)\n"
+ " at de.zarncke.lib.err.Warden.guard(Warden.java:173)"), "reported by Warden.guard()")
.replaceAllRegex(
quoteStacktrace(PATTERN_EXCEPTION_NOT_INTENDED_TO_BE_THROWN
+ " at de.zarncke.lib.log.group.GroupingLog.report(GroupingLog.java:135)\n"
+ " at de.zarncke.lib.err.Warden.log(Warden.java:57)\n"
+ " at de.zarncke.lib.err.Warden.disregardAndReport(Warden.java:38)"),
"reported by [Warden.disregardAndReport]")
.replaceAllRegex(
quoteStacktrace(PATTERN_EXCEPTION_NOT_INTENDED_TO_BE_THROWN
+ " at de.zarncke.lib.log.group.GroupingLog.report(GroupingLog.java:135)\n"
+ " at de.zarncke.lib.err.Warden.log(Warden.java:57)\n"
+ " at de.zarncke.lib.err.Warden.report(Warden.java:50)"),
"reported by [Warden.report]")
.replaceAllRegex(
quoteStacktrace(PATTERN_EXCEPTION_NOT_INTENDED_TO_BE_THROWN
+ " at de.zarncke.lib.log.group.GroupingLog.report(GroupingLog.java:135)"),
"reported by")
.replaceAllRegex(
contextPattern + quoteStacktrace(" at de.zarncke.lib.db.Db.transactional(Db.java:94)"),
" at [transactional]")
.replaceAllRegex(contextPattern, " at [Context*]\n")
.replaceAllRegex(
quoteStacktrace(" at de.zarncke.lib.block.Running.execute(Running.java:10)\n"
+ " at de.zarncke.lib.block.Running.execute(Running.java:8)\n"
+ " at de.zarncke.lib.err.Warden.guard(Warden.java:166)"),
" at [Guarded->Running]")
.replaceAllRegex(
"("
+ quoteStacktrace(" at sun.reflect.")
+ ".*\\r?\\n)*"
+ quoteStacktrace(" at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)"),
" at [Reflection*]")
.replaceAllRegex(
"(" + quoteStacktrace(" org.junit.") + ".*\\r?\\n|" + quoteStacktrace(" junit.framework.Test")
+ ".*\\r?\\n)+", " at [JUnit*]\n").done();
}
/**
* May be used by implementations to convert a verbatim stacktrace into a useful regex.
*
* @param stackTraceFragment to escape
* @return a regex matching that stacktrace
*/
public static String quoteStacktrace(final String stackTraceFragment) {
return stackTraceFragment.replaceAll("\n\\s+", "\\\\r?\\\\n\\\\s+").replaceAll("\\n$", "\\\\r?\\\\n")
.replaceAll("^\\s+", "^\\\\s+").replaceAll("\\.", "\\\\.").replaceAll("\\$[0-9]*", ".[0-9]*")
.replaceAll(":[0-9]*\\)", ":[0-9]*\\)").replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)");
}
public String makeHumanReadableReport(final CharSequence textContainingStackTraces) {
return this.reportCleaner.apply(textContainingStackTraces).toString();
}
/**
* Cleans the {@link Report#getFullReport()}.
*
* @param report to clean
* @return clean String
*/
@Nonnull
public static String makeHumanReadableReport(@Nonnull final Report report) {
return CTX.get().makeHumanReadableReport(report.getFullReport());
}
/**
* Cleans the stacktrace.
*
* @param throwable to clean
* @return clean String
*/
@Nonnull
public static String makeHumanReadableReport(@Nonnull final Throwable throwable) {
return CTX.get().makeHumanReadableReport(ExceptionUtil.getStackTrace(throwable));
}
@Override
public String toString() {
return this.reportCleaner.toString();
}
}
|
package com.tencent.mm.g.c;
import android.content.ContentValues;
import android.database.Cursor;
import com.tencent.mm.sdk.e.c;
public abstract class dq extends c {
private static final int cNa = "from_username".hashCode();
private static final int cNb = "consumer".hashCode();
private static final int cNc = "share_time".hashCode();
private static final int cNd = "local_updateTime".hashCode();
private static final int cNe = "begin_time".hashCode();
private static final int cNf = "end_time".hashCode();
private static final int cNg = "block_mask".hashCode();
private static final int cNh = "dataInfoData".hashCode();
private static final int cNi = "cardTpInfoData".hashCode();
private static final int cNj = "shareInfoData".hashCode();
private static final int cNk = "shopInfoData".hashCode();
private static final int cNl = "categoryType".hashCode();
private static final int cNm = "itemIndex".hashCode();
public static final String[] ciG = new String[]{"CREATE INDEX IF NOT EXISTS ShareCardInfo_card_tp_id_index ON ShareCardInfo(card_tp_id)"};
private static final int ciP = "rowid".hashCode();
private static final int ciV = "status".hashCode();
private static final int clj = "updateTime".hashCode();
private static final int cqC = "card_id".hashCode();
private static final int cqD = "card_tp_id".hashCode();
private static final int cvW = "app_id".hashCode();
private static final int cyk = "updateSeq".hashCode();
private boolean cMN = true;
private boolean cMO = true;
private boolean cMP = true;
private boolean cMQ = true;
private boolean cMR = true;
private boolean cMS = true;
private boolean cMT = true;
private boolean cMU = true;
private boolean cMV = true;
private boolean cMW = true;
private boolean cMX = true;
private boolean cMY = true;
private boolean cMZ = true;
private boolean ciS = true;
private boolean clh = true;
private boolean cqj = true;
private boolean cqk = true;
private boolean cvu = true;
private boolean cxW = true;
public String field_app_id;
public long field_begin_time;
public long field_block_mask;
public byte[] field_cardTpInfoData;
public String field_card_id;
public String field_card_tp_id;
public int field_categoryType;
public String field_consumer;
public byte[] field_dataInfoData;
public long field_end_time;
public String field_from_username;
public int field_itemIndex;
public long field_local_updateTime;
public byte[] field_shareInfoData;
public long field_share_time;
public byte[] field_shopInfoData;
public int field_status;
public long field_updateSeq;
public long field_updateTime;
public final void d(Cursor cursor) {
String[] columnNames = cursor.getColumnNames();
if (columnNames != null) {
int length = columnNames.length;
for (int i = 0; i < length; i++) {
int hashCode = columnNames[i].hashCode();
if (cqC == hashCode) {
this.field_card_id = cursor.getString(i);
this.cqj = true;
} else if (cqD == hashCode) {
this.field_card_tp_id = cursor.getString(i);
} else if (cNa == hashCode) {
this.field_from_username = cursor.getString(i);
} else if (cNb == hashCode) {
this.field_consumer = cursor.getString(i);
} else if (cvW == hashCode) {
this.field_app_id = cursor.getString(i);
} else if (ciV == hashCode) {
this.field_status = cursor.getInt(i);
} else if (cNc == hashCode) {
this.field_share_time = cursor.getLong(i);
} else if (cNd == hashCode) {
this.field_local_updateTime = cursor.getLong(i);
} else if (clj == hashCode) {
this.field_updateTime = cursor.getLong(i);
} else if (cNe == hashCode) {
this.field_begin_time = cursor.getLong(i);
} else if (cNf == hashCode) {
this.field_end_time = cursor.getLong(i);
} else if (cyk == hashCode) {
this.field_updateSeq = cursor.getLong(i);
} else if (cNg == hashCode) {
this.field_block_mask = cursor.getLong(i);
} else if (cNh == hashCode) {
this.field_dataInfoData = cursor.getBlob(i);
} else if (cNi == hashCode) {
this.field_cardTpInfoData = cursor.getBlob(i);
} else if (cNj == hashCode) {
this.field_shareInfoData = cursor.getBlob(i);
} else if (cNk == hashCode) {
this.field_shopInfoData = cursor.getBlob(i);
} else if (cNl == hashCode) {
this.field_categoryType = cursor.getInt(i);
} else if (cNm == hashCode) {
this.field_itemIndex = cursor.getInt(i);
} else if (ciP == hashCode) {
this.sKx = cursor.getLong(i);
}
}
}
}
public final ContentValues wH() {
ContentValues contentValues = new ContentValues();
if (this.cqj) {
contentValues.put("card_id", this.field_card_id);
}
if (this.cqk) {
contentValues.put("card_tp_id", this.field_card_tp_id);
}
if (this.cMN) {
contentValues.put("from_username", this.field_from_username);
}
if (this.cMO) {
contentValues.put("consumer", this.field_consumer);
}
if (this.cvu) {
contentValues.put("app_id", this.field_app_id);
}
if (this.ciS) {
contentValues.put("status", Integer.valueOf(this.field_status));
}
if (this.cMP) {
contentValues.put("share_time", Long.valueOf(this.field_share_time));
}
if (this.cMQ) {
contentValues.put("local_updateTime", Long.valueOf(this.field_local_updateTime));
}
if (this.clh) {
contentValues.put("updateTime", Long.valueOf(this.field_updateTime));
}
if (this.cMR) {
contentValues.put("begin_time", Long.valueOf(this.field_begin_time));
}
if (this.cMS) {
contentValues.put("end_time", Long.valueOf(this.field_end_time));
}
if (this.cxW) {
contentValues.put("updateSeq", Long.valueOf(this.field_updateSeq));
}
if (this.cMT) {
contentValues.put("block_mask", Long.valueOf(this.field_block_mask));
}
if (this.cMU) {
contentValues.put("dataInfoData", this.field_dataInfoData);
}
if (this.cMV) {
contentValues.put("cardTpInfoData", this.field_cardTpInfoData);
}
if (this.cMW) {
contentValues.put("shareInfoData", this.field_shareInfoData);
}
if (this.cMX) {
contentValues.put("shopInfoData", this.field_shopInfoData);
}
if (this.cMY) {
contentValues.put("categoryType", Integer.valueOf(this.field_categoryType));
}
if (this.cMZ) {
contentValues.put("itemIndex", Integer.valueOf(this.field_itemIndex));
}
if (this.sKx > 0) {
contentValues.put("rowid", Long.valueOf(this.sKx));
}
return contentValues;
}
}
|
package com.example.demo.controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.demo.form.LoginForm;
import com.example.demo.form.PersonForm;
import com.example.demo.model.Person;
/**
* Spingboot sẽ lấy data từ body of Form post request "/loginForm"=> mapping LoginForm.class
*
*/
@Controller
public class FormController {
/**
* form nay de tao POST request voi url = "/post"
*/
@RequestMapping(path = "/loginForm", method = RequestMethod.GET)
public String showFormForPost(){
System.out.println("/loginForm");
return "loginForm"; // trả về templates/loginForm.html
}
/**
* @modelAtribute("personForm") PersonForm personForm:
* Springboot sẽ lấy dữ liệu từ Post Request (html form) ghi vào PersonForm và
* save ở Model với attribute name = "personForm"
*/
@RequestMapping(value = { "/logintest" }, method = RequestMethod.POST)
public @ResponseBody String savePerson(@ModelAttribute("loginForm") LoginForm loginForm) {
System.out.println("/logintest");
String userName = loginForm.getUserName();
String passWord = loginForm.getPassword();
return "userName:"+ userName +" ,password:"+passWord;
}
}
|
package com.example.demostream;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.SubscribableChannel;
public interface Distination {
String INPUT = "inputD";
String OUTPUT = "outputD";
@Input(Distination.INPUT)
SubscribableChannel input();
@Output(Distination.OUTPUT)
SubscribableChannel output();
}
|
package com.one.sugarcane.search.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.annotation.Resource;
import org.apache.lucene.queryparser.classic.ParseException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.one.sugarcane.entity.Searcher;
/**
* 根据索引搜索培训机构 并且高亮显示 TODO
*
* @author 秦晓宇
* @date 2018年5月29日
*
*/
@Service
@Transactional(readOnly = false)
public class SellerInfoSearchService {
public static String pt;
private SellerInfoSearch sellerInfoSearch = new SellerInfoSearch() ;
public ArrayList<Searcher> searchBySellerName(String name,int currentPage) throws Exception {
pt = "E:\\gitRepository\\sugarcane\\sugarcane\\src\\com\\one\\sugarcane\\search\\dataIndex\\sellerIndex";
return sellerInfoSearch.search(pt, name,currentPage);
}
public String[] totalNumber(String name) throws IOException, ParseException {
return this.sellerInfoSearch.findIndex(pt, name);
}
}
|
package com.wannajob.core.common.utility;
public class CommonUtility {
public static Object getCurrentDateInUTC() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.zokistone.zokinewsapp;
public class News {
private String mWebTitle;
private String mPillarName;
private String mUrl;
public News(String webTitle, String pillarName, String Url) {
mWebTitle = webTitle;
mPillarName = pillarName;
mUrl = Url;
}
public String getWebTitle() {
return mWebTitle;
}
public String getPillarName() {
return mPillarName;
}
public String getUrl() {
return mUrl;
}
}
|
package kh.cocoa.dto;
import java.util.Date;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data //lombok을 사용하기 때문에 getter/setter를 포함된것
@NoArgsConstructor // 기본 생성자 역활 - DTO에 없는 경우
public class FilesDTO {
private int seq;
private String oriname;
private String savedname;
private Date uploadeddate;
private int board_seq;
private int document_seq;
private int msg_seq;
private int email_seq;
@Builder // 생성자가 id,nmae등 부분적으로 필요한것도 알아서 생성. 단, controller에서 해주어야할께 있음
public FilesDTO(int seq, String oriname, String savedname, Date uploadeddate, int board_seq, int document_seq, int msg_seq, int email_seq) {
this.seq = seq;
this.oriname = oriname;
this.savedname = savedname;
this.uploadeddate = uploadeddate;
this.board_seq = board_seq;
this.document_seq = document_seq;
this.msg_seq = msg_seq;
this.email_seq = email_seq;
}
public FilesDTO(String oriname, String savedname,int email_seq) {
this.oriname = oriname;
this.savedname = savedname;
this.email_seq = email_seq;
}
}
|
package uk.gov.companieshouse.api.testdata.service.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.crypto.bcrypt.BCrypt;
import uk.gov.companieshouse.api.testdata.exception.NoDataFoundException;
import uk.gov.companieshouse.api.testdata.model.entity.CompanyAuthCode;
import uk.gov.companieshouse.api.testdata.model.rest.CompanySpec;
import uk.gov.companieshouse.api.testdata.repository.CompanyAuthCodeRepository;
import uk.gov.companieshouse.api.testdata.service.RandomService;
@ExtendWith(MockitoExtension.class)
class CompanyAuthCodeServiceImplTest {
private static final String COMPANY_NUMBER = "12345678";
private static final Long COMPANY_AUTH_CODE = 123456L;
@Mock
private CompanyAuthCodeRepository repository;
@Mock
private RandomService randomService;
@InjectMocks
private CompanyAuthCodeServiceImpl companyAuthCodeServiceImpl;
@Test
void create() throws Exception {
CompanySpec spec = new CompanySpec();
spec.setCompanyNumber(COMPANY_NUMBER);
when(this.randomService.getNumber(6)).thenReturn(COMPANY_AUTH_CODE);
CompanyAuthCode savedAuthCode = new CompanyAuthCode();
when(repository.save(any())).thenReturn(savedAuthCode);
final byte[] password = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_256)
.digest(String.valueOf(COMPANY_AUTH_CODE).getBytes(StandardCharsets.UTF_8));
CompanyAuthCode returnedAuthCode = this.companyAuthCodeServiceImpl.create(spec);
assertEquals(savedAuthCode, returnedAuthCode);
ArgumentCaptor<CompanyAuthCode> authCodeCaptor = ArgumentCaptor.forClass(CompanyAuthCode.class);
verify(repository).save(authCodeCaptor.capture());
CompanyAuthCode authCode = authCodeCaptor.getValue();
assertNotNull(authCode);
assertEquals(String.valueOf(COMPANY_AUTH_CODE), authCode.getAuthCode());
assertTrue(authCode.getIsActive());
assertEquals(COMPANY_NUMBER, authCode.getId());
assertTrue(BCrypt.checkpw(password, authCode.getEncryptedAuthCode()));
}
@Test
void verifyAuthCodeCorrect() throws NoSuchAlgorithmException, NoDataFoundException {
final String plainCode = "222";
// Create a valid encrypted auth code
final String encryptedAuthCode = BCrypt.hashpw(MessageDigest.getInstance(MessageDigestAlgorithms.SHA_256)
.digest(plainCode.getBytes(StandardCharsets.UTF_8)), BCrypt.gensalt());
CompanyAuthCode authCode = new CompanyAuthCode();
authCode.setAuthCode(plainCode);
authCode.setEncryptedAuthCode(encryptedAuthCode);
when(repository.findById(COMPANY_NUMBER)).thenReturn(Optional.ofNullable(authCode));
assertTrue(companyAuthCodeServiceImpl.verifyAuthCode(COMPANY_NUMBER, plainCode));
}
@Test
void verifyAuthCodeIncorrect() throws NoDataFoundException {
final String plainCode = "222";
final String encryptedAuthCode = "$2a$10$randomrandomrandomrandomrandomrandomrandomrandom12345";
CompanyAuthCode authCode = new CompanyAuthCode();
authCode.setAuthCode(plainCode);
authCode.setEncryptedAuthCode(encryptedAuthCode);
when(repository.findById(COMPANY_NUMBER)).thenReturn(Optional.ofNullable(authCode));
assertFalse(companyAuthCodeServiceImpl.verifyAuthCode(COMPANY_NUMBER, plainCode));
}
@Test
void verifyAuthCodeNotFound() {
final String plainCode = "222";
CompanyAuthCode authCode = null;
when(repository.findById(COMPANY_NUMBER)).thenReturn(Optional.ofNullable(authCode));
assertThrows(NoDataFoundException.class,
() -> companyAuthCodeServiceImpl.verifyAuthCode(COMPANY_NUMBER, plainCode));
}
@Test
void delete() {
CompanyAuthCode authCode = new CompanyAuthCode();
when(repository.findById(COMPANY_NUMBER))
.thenReturn(Optional.of(authCode));
assertTrue(this.companyAuthCodeServiceImpl.delete(COMPANY_NUMBER));
verify(repository).delete(authCode);
}
@Test
void deleteNoDataException() {
when(repository.findById(COMPANY_NUMBER)).thenReturn(Optional.empty());
assertFalse(this.companyAuthCodeServiceImpl.delete(COMPANY_NUMBER));
verify(repository, never()).delete(any());
}
}
|
package tema13;
import tema13.estrutura.*;
import tema13.interfaces.*;
public class Main {
public static void main(String[] args) {
try {
IContato iContato = new Contato("Isabella", "+553493362378", "vecchisabella@gmail.com");
MensagemOlaCliente mensagemOlaCliente = new MensagemOlaCliente(iContato);
EnviaEmail enviadorDeEmail = new EnviaEmail();
EnviaNotificacao notificacao = new EnviaNotificacao(enviadorDeEmail, mensagemOlaCliente);
notificacao.enviaNotificacao();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.sankozi.rogueland.model;
import com.google.common.collect.ImmutableMap;
import org.sankozi.rogueland.model.coords.Direction;
import java.util.Map;
/**
*
* @author sankozi
*/
public interface Move {
public static final Move WAIT = new Move(){};
public static enum Go implements Move{
NORTHWEST(Direction.NW),
NORTH(Direction.N),
NORTHEAST(Direction.NE),
WEST(Direction.W),
EAST(Direction.E),
SOUTH(Direction.S),
SOUTHEAST(Direction.SE),
SOUTHWEST(Direction.SW);
public final Direction direction;
static final Map<Direction, Move> DIRECTION_TO_MOVE;
static {
ImmutableMap.Builder<Direction, Move> builder = ImmutableMap.<Direction, Move>builder();
for(Go move : Go.values()){
builder.put(move.direction, move);
}
builder.put(Direction.C, Move.WAIT);
DIRECTION_TO_MOVE = builder.build();
}
public static Move fromDirection(Direction dir){
Move ret = DIRECTION_TO_MOVE.get(dir);
return ret;
}
private Go(Direction direction) {
this.direction = direction;
}
}
public static enum Rotate implements Move{
CLOCKWISE,
COUNTERCLOCKWISE
}
}
|
package com.example.movie;
import java.util.ArrayList;
public class MovieListResult {
String boxofficeType;
String showRange;
String yearWeekTime;
ArrayList<Movie> weeklyBoxOfficeList = new ArrayList<Movie>();
}
|
package edu.wpi.cs.justice.cardmaker.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import edu.wpi.cs.justice.cardmaker.model.Image;
import edu.wpi.cs.justice.cardmaker.model.Text;
public class ElementDAO {
java.sql.Connection conn;
public ElementDAO() {
try {
conn = DatabaseUtil.connect();
} catch (Exception e) {
conn = null;
}
}
public boolean addText(Text text) throws Exception {
try {
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO elements (element_id, type, text, font_name,font_size,font_type,imageUrl) values(?,?,?,?,?,?,?);");
ps.setString(1, text.getElementId());
ps.setString(2, "text");
ps.setString(3, text.getText());
ps.setString(4, text.getFontName());
ps.setString(5, text.getFontSize());
ps.setString(6, text.getFontType());
ps.setString(7, null);
ps.execute();
return true;
} catch (Exception e) {
throw new Exception("Failed to add text: " + e.getMessage());
}
}
public boolean addImage(Image image) throws Exception {
try {
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO elements (element_id, type, text, font_name, font_size, font_type, imageUrl) values(?,?,?,?,?,?,?);");
ps.setString(1, image.getElementId());
ps.setString(2, "image");
ps.setString(3, null);
ps.setString(4, null);
ps.setString(5, null);
ps.setString(6, null);
ps.setString(7, image.getImageUrl());
ps.execute();
return true;
} catch (Exception e) {
throw new Exception("Failed to add image: " + e.getMessage());
}
}
public boolean UpdateImageUrl(String imageUrl, String elementId) throws Exception {
try {
PreparedStatement ps = conn.prepareStatement("UPDATE elements set imageUrl=? WHERE element_id = ?");
ps.setString(1, imageUrl);
ps.setString(2, elementId);
ps.execute();
return true;
} catch (Exception ex) {
throw new Exception("Fail to edit image:" + ex.getMessage());
}
}
public boolean UpdateImage(String elementId, String pageId, String locationX, String locationY, String width, String height) throws Exception {
String query = "UPDATE pageElements "
+ "SET location_X = ?, location_Y = ?, width = ?, height = ? "
+ "WHERE element_id = ? AND page_id = ?";
try {
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, locationX);
ps.setString(2, locationY);
ps.setString(3, width);
ps.setString(4, height);
ps.setString(5, elementId);
ps.setString(6, pageId);
ps.execute();
return true;
} catch (Exception e) {
throw new Exception("Failed to update image: " + e.getMessage());
}
}
public boolean addPageElement(String elementId, String locationX, String locationY, String pageId, String width,
String height) throws Exception {
try {
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO pageElements (element_id, page_id, location_X, location_Y,width,height) values(?,?,?,?,?,?);");
ps.setString(1, elementId);
ps.setString(2, pageId);
ps.setString(3, locationX);
ps.setString(4, locationY);
ps.setString(5, width);
ps.setString(6, height);
ps.execute();
return true;
} catch (Exception e) {
throw new Exception("Failed to add pageElement: " + e.getMessage());
}
}
public ArrayList<String> getPageElement(String pageId) throws Exception {
ArrayList<String> ElementIds = new ArrayList<String>();
try {
String query = "SELECT * FROM pageElements WHERE page_id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, pageId);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()) {
String elementId = resultSet.getString("element_id");
ElementIds.add(elementId);
}
return ElementIds;
} catch (Exception e) {
throw new Exception("Failed to get pageElement: " + e.getMessage());
}
}
public boolean duplicatePageElement(String elementId, String pageId, String newPageId) throws Exception {
try {
PreparedStatement ps = conn
.prepareStatement("SELECT * FROM pageElements WHERE element_id = ? AND page_id = ?");
ps.setString(1, elementId);
ps.setString(2, pageId);
ps.execute();
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()) {
String locationX = resultSet.getString("location_X");
String locationY = resultSet.getString("location_Y");
String width = resultSet.getString("width");
String height = resultSet.getString("height");
addPageElement(elementId, locationX, locationY, newPageId, width, height);
}
return true;
} catch (Exception e) {
throw new Exception("Failed to duplicate pageElement: " + e.getMessage());
}
}
public boolean duplicateText(Text text) throws Exception {
try {
String newElementId = util.Util.generateUniqueId();
addText(new Text(newElementId, text.getText(), text.getFontName(), text.getFontSize(), text.getFontType(),
text.getLocationX(), text.getLocationY()));
return true;
} catch (Exception e) {
throw new Exception("Failed to duplicate text " + e.getMessage());
}
}
public boolean duplicateImage(Image image) throws Exception {
try {
String newElementId = util.Util.generateUniqueId();
addImage(new Image(newElementId, image.getImageUrl(), image.getLocationX(), image.getLocationY(),
image.getWidth(), image.getHeight()));
return true;
} catch (Exception e) {
throw new Exception("Failed to duplicate image " + e.getMessage());
}
}
public ArrayList<Text> getTexts(String pageId) throws Exception {
ArrayList<Text> texts = new ArrayList<Text>();
String query = "SELECT location_X, location_Y, elements.element_id, text, font_name, font_size, font_type "
+ "FROM pageElements " + "inner join elements " + "WHERE pageElements.element_id = elements.element_id "
+ "AND page_id = ?" + "AND type = 'text'";
try {
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, pageId);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()) {
String elementId = resultSet.getString("element_id");
String locationX = resultSet.getString("location_X");
String locationY = resultSet.getString("location_Y");
String text = resultSet.getString("text");
String fontName = resultSet.getString("font_name");
String fontSize = resultSet.getString("font_size");
String fontType = resultSet.getString("font_type");
texts.add(new Text(elementId, text, fontName, fontSize, fontType, locationX, locationY));
}
} catch (SQLException e) {
throw new Exception("Failed to get texts: " + e.getMessage());
}
return texts;
}
public boolean UpdateText(Text text, String pageId) throws Exception {
String queryForElement = "UPDATE elements " + "SET font_name = ?, font_type = ?, font_size = ?, text = ? "
+ "WHERE element_id = ?";
String queryForPageElement = "UPDATE pageElements " + "SET location_X = ?, location_Y = ? "
+ "WHERE element_id = ? AND page_id = ?";
try {
PreparedStatement ps = conn.prepareStatement(queryForElement);
ps.setString(1, text.getFontName());
ps.setString(2, text.getFontType());
ps.setString(3, text.getFontSize());
ps.setString(4, text.getText());
ps.setString(5, text.getElementId());
ps.executeUpdate();
ps.close();
PreparedStatement ps2 = conn.prepareStatement(queryForPageElement);
ps2.setString(1, text.getLocationX());
ps2.setString(2, text.getLocationY());
ps2.setString(3, text.getElementId());
ps2.setString(4, pageId);
ps2.executeUpdate();
ps2.close();
return true;
} catch (Exception ex) {
throw new Exception("Failed to update text: " + ex.getMessage());
} finally {
return false;
}
}
public ArrayList<Image> getImages(String pageId) throws Exception {
ArrayList<Image> images = new ArrayList<Image>();
String query = "SELECT location_X, location_Y, elements.element_id, imageUrl, width, height "
+ "FROM pageElements " + "inner join elements " + "WHERE pageElements.element_id = elements.element_id "
+ "AND page_id = ?" + "AND type = 'image'";
try {
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, pageId);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()) {
String elementId = resultSet.getString("element_id");
String locationX = resultSet.getString("location_X");
String locationY = resultSet.getString("location_Y");
String imageUrl = resultSet.getString("imageUrl");
String width = resultSet.getString("width");
String height = resultSet.getString("height");
images.add(new Image(elementId, imageUrl, locationX, locationY, width, height));
}
} catch (SQLException e) {
throw new Exception("Failed to get images: " + e.getMessage());
}
return images;
}
public boolean deletePageElement(String elementId, String pageId) throws Exception {
try {
PreparedStatement ps = conn
.prepareStatement("DELETE FROM pageElements WHERE element_id = ? AND page_id = ?;");
ps.setString(1, elementId);
ps.setString(2, pageId);
int numAffect = ps.executeUpdate();
ps.close();
return (numAffect == 1);
} catch (Exception e) {
throw new Exception("Failed to delete text: " + e.getMessage());
}
}
public boolean deleteText(String elementId) throws Exception {
try {
PreparedStatement ps = conn
.prepareStatement("DELETE FROM elements WHERE element_id = ?;");
ps.setString(1, elementId);
int numAffect = ps.executeUpdate();
ps.close();
return (numAffect == 1);
} catch (Exception e) {
throw new Exception("Failed to delete text: " + e.getMessage());
}
}
public ArrayList<String> getAllImage() throws Exception{
try {
ArrayList<String> imaUrls = new ArrayList<String>();
PreparedStatement ps = conn.prepareStatement("SELECT DISTINCT imageUrl FROM elements WHERE imageUrl IS NOT NULL");
ResultSet resultSet = ps.executeQuery();
while(resultSet.next()){
String imageUrl= resultSet.getString("imageUrl");
imaUrls.add(imageUrl);
}
return imaUrls;
} catch (Exception e) {
throw new Exception("Failed to get images: " + e.getMessage());
}
}
}
|
package net.razorvine.pyro;
import java.io.IOException;
/**
* Dummy class to be able to unpickle Pyro Proxy objects.
*
* @author Irmen de Jong (irmen@razorvine.net)
*/
public class DummyPyroSerializer {
/**
* called by the Unpickler to restore state
*/
public void __setstate__(java.util.HashMap<?,?> args) throws IOException {
}
}
|
package com.fleet.jasypt;
import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JasyptApplicationTests {
@Resource
private StringEncryptor stringEncryptor;
@Test
public void encrypt() {
String encrypt = stringEncryptor.encrypt("");
System.out.println(encrypt);
}
@Test
public void decrypt() {
String encrypt = "ZPuwhwfeVTiCHBXqX3tRRgfetivI/wtYAgiBday2VOkK50ixRVnwSHxPyrLLXNLr";
String decrypt = stringEncryptor.decrypt(encrypt);
System.out.println(decrypt);
}
}
|
package api.longpoll.bots.methods.impl.messages;
import api.longpoll.bots.http.params.BoolInt;
import api.longpoll.bots.methods.AuthorizedVkApiMethod;
import api.longpoll.bots.methods.VkApiProperties;
import java.util.Arrays;
import java.util.List;
/**
* Implements <b>messages.getConversations</b> method.
* <p>
* Returns a list of conversations.
*
* @see <a href="https://vk.com/dev/messages.getConversations">https://vk.com/dev/messages.getConversations</a>
*/
public class GetConversations extends AuthorizedVkApiMethod<GetConversations.Response> {
public GetConversations(String accessToken) {
super(accessToken);
}
@Override
protected String getUrl() {
return VkApiProperties.get("messages.getConversations");
}
@Override
protected Class<Response> getResponseType() {
return Response.class;
}
public GetConversations setOffset(int offset) {
return addParam("offset", offset);
}
public GetConversations setCount(int count) {
return addParam("count", count);
}
public GetConversations setFilter(String filter) {
return addParam("filter", filter);
}
public GetConversations setExtended(boolean extended) {
return addParam("extended", new BoolInt(extended));
}
public GetConversations setStartMessageId(int startMessageId) {
return addParam("start_message_id", startMessageId);
}
public GetConversations setFields(String... fields) {
return setFields(Arrays.asList(fields));
}
public GetConversations setFields(List<String> fields) {
return addParam("fields", fields);
}
public GetConversations setGroupId(int groupId) {
return addParam("group_id", groupId);
}
@Override
public GetConversations addParam(String key, Object value) {
return (GetConversations) super.addParam(key, value);
}
/**
* Response to <b>messages.getConversations</b> request.
*/
public static class Response extends GetConversationsById.Response {
}
}
|
package com.eureka.zuul.security;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import com.eureka.zuul.repo.JwtRepo;
import com.eureka.zuul.security.GeneratedToken;
//import com.eureka.auth.security.GeneratedToken;
import com.eureka.common.security.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
@Autowired
public final JwtConfig jwtConfig;
private final JwtRepo jwtRepo;
public JwtTokenAuthenticationFilter(JwtConfig jwtConfig,JwtRepo jwtRepo) {
this.jwtConfig = jwtConfig;
this.jwtRepo=jwtRepo;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
GeneratedToken gt=jwtRepo.findByUsername("admin");
String token1=gt.getGeneratedtoken();
//validate the Token and check the prefix
if(token1 == null || !token1.startsWith(jwtConfig.getPrefix())) {
chain.doFilter(request, response); // If not valid, go to the next filter.
return;
}
//Get the token
String token=token1.replace(jwtConfig.getPrefix(), "");
try {
//Validate the token
Claims claims = Jwts.parser()
.setSigningKey(jwtConfig.getSecret().getBytes())
.parseClaimsJws(token)
.getBody();
String username = claims.getSubject();
if(username != null) {
@SuppressWarnings("unchecked")
List<String> authorities = (List<String>) claims.get("authorities");
//Create auth object
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
username, null, authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
//Authenticate the user
SecurityContextHolder.getContext().setAuthentication(auth);
}
} catch (Exception e) {
// In case of failure, user won't be authenticated
SecurityContextHolder.clearContext();
}
chain.doFilter(request, response);
}
}
|
package org.workers.impl.combat_instructor;
import org.OrionTutorial;
import org.osbot.rs07.api.map.Position;
import org.workers.TutorialWorker;
import viking.api.Timing;
public class CombatInstructorDialogue extends TutorialWorker
{
private static final Position REACHABLE_POS = new Position(3107, 9508, 0);
public CombatInstructorDialogue(OrionTutorial mission)
{
super(mission);
}
@Override
public boolean shouldExecute()
{
return true;
}
@Override
public void work()
{
script.log(this, false, "Combat Instructor Dialogue");
if(map.canReach(REACHABLE_POS))
iFact.dialogue("Talk-to", "Combat Instructor", 20).execute();
else if(iFact.clickObject("Open", "Gate", EnterRatCage.GATE_AREA).execute())
Timing.waitCondition(() -> map.canReach(REACHABLE_POS), 5500);
}
}
|
package com.rofour.baseball.common;
import com.rofour.baseball.controller.model.Permission;
import com.rofour.baseball.dao.manager.bean.UserManagerLogBean;
import com.rofour.baseball.dao.user.bean.UserManagerLoginBean;
import com.rofour.baseball.service.manager.UserManagerLog;
import com.rofour.baseball.service.user.impl.UserManagerServiceImp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class WebUtils {
/**
* 操作类型枚举 持续添加
*/
// public enum OperationType {
// ADD, DELETE, EDIT, QUERY, PRINT, AUDIT, INITPWD
// }
@Autowired
@Qualifier("userManagerLog")
UserManagerLog userManagerLog;
private static final Logger logger = LoggerFactory.getLogger(UserManagerServiceImp.class);
public String getRemoteAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getRemoteAddr();
}
return ip;
}
private String strRemark = "";
private String strNewValue = "";
private String strOldValue = "";
/**
* 添加系统日志
*
* @param request
* @param remark 操作备注
* @param menuId 菜单ID
* @param operationType 操作类型枚举
*/
public void userLog(HttpServletRequest request, String remark, long menuId, String newValue, String oldValue, String operationType) {
UserManagerLogBean model = new UserManagerLogBean();
UserManagerLoginBean userManagerLoginBean = (UserManagerLoginBean) request.getSession().getAttribute("user");
model.setRemark(remark);
model.setNewValue(newValue);
model.setOldValue(oldValue);
model.setMenuId(menuId);
model.setOperationTime(new Date());
model.setOperationType(operationType);
model.setUserManagerId(userManagerLoginBean.getUserManagerId());
model.setUserName(userManagerLoginBean.getUserName());
model.setUserIp(getRemoteAddress(request));
userManagerLog.insert(model);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.info(String.format("日期 :%s,操作人:%s,操作:%s%s%s", format.format(new Date()), userManagerLoginBean.getUserManagerId(), remark,strNewValue,strOldValue ));
}
/**
* 数据新增系统日志
*
* @param request
* @param menuId 菜单ID
* @param model 新增的对象
*/
public void userAddLog(HttpServletRequest request, long menuId, Object model) {
try {
strRemark = "新增";
strNewValue = JsonUtils.translateToJson(model);
} catch (IOException e) {
e.printStackTrace();
}
userLog(request, strRemark, menuId, strNewValue, "", Permission.ADD.name());
}
/**
* 数据编辑日志
*
* @param request
* @param menuId 菜单ID
* @param editModel 旧数据对象
* @param updateModel 更新的新对象
*/
public void userEditLog(HttpServletRequest request, long menuId, Object editModel, Object updateModel) {
try {
strRemark = "编辑";
strOldValue = JsonUtils.translateToJson(editModel);
strNewValue = JsonUtils.translateToJson(updateModel);
} catch (IOException e) {
e.printStackTrace();
}
userLog(request, strRemark, menuId, strNewValue, strOldValue, Permission.EDIT.name());
}
/**
* 数据删除日志
*
* @param request
* @param menuId 菜单ID
* @param deleteModel 删除的数据对象
*/
public void userDeleteLog(HttpServletRequest request, long menuId, Object deleteModel) {
try {
strRemark = "删除";
strOldValue = JsonUtils.translateToJson(deleteModel);
} catch (IOException e) {
e.printStackTrace();
}
userLog(request, strRemark, menuId, "", strOldValue, Permission.DELETE.name());
}
}
|
package com.zjclugger.qrcode.encode;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.Hashtable;
/**
* 二维码生成器
*/
public class QRCodeGenerator {
/**
* 生成二维码
*
* @param QRString 字符串内容
* @param width 二维码宽度
* @param height 二维码高度
* @param characterSet 编码方式(一般使用UTF-8)
* @param errorCorrectionLevel 容错率 L:7% M:15% Q:25% H:35%
* @param margin 空白边距(二维码与边框的空白区域)
* @param lineColor 线色
* @param background 背景色
* @param logoBitmap logo图片
* @param logoPercent logo所占百分比
* @param lineBitmap 用来代替线的图片(传null时不代替)
* @return
*/
public static Bitmap create(String QRString, int width, int height, String characterSet,
String errorCorrectionLevel, String margin, int lineColor,
int background, Bitmap logoBitmap, float logoPercent,
Bitmap lineBitmap) {
// 字符串内容判空
if (TextUtils.isEmpty(QRString)) {
return null;
}
// 宽和高>=0
if (width < 0 || height < 0) {
return null;
}
try {
/** 1.设置二维码相关配置,生成BitMatrix(位矩阵)对象 */
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
// 字符转码格式设置
if (!TextUtils.isEmpty(characterSet)) {
hints.put(EncodeHintType.CHARACTER_SET, characterSet);
}
// 容错率设置
if (!TextUtils.isEmpty(errorCorrectionLevel)) {
hints.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel);
}
// 空白边距设置
if (!TextUtils.isEmpty(margin)) {
hints.put(EncodeHintType.MARGIN, margin);
}
/** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
BitMatrix bitMatrix = new QRCodeWriter().encode(QRString, BarcodeFormat.QR_CODE, width
, height, hints);
/** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
if (lineBitmap != null) {
//从当前位图按一定的比例创建一个新的位图
lineBitmap = Bitmap.createScaledBitmap(lineBitmap, width, height, false);
}
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//bitMatrix.get(x,y)方法返回true是黑色色块,false是白色色块
if (bitMatrix.get(x, y)) {// 黑色色块像素设置
if (lineBitmap != null) {//图片不为null,则将黑色色块换为新位图的像素。
pixels[y * width + x] = lineBitmap.getPixel(x, y);
} else {
pixels[y * width + x] = lineColor;
}
} else {
pixels[y * width + x] = background;// 白色色块像素设置
}
}
}
/** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
/** 5.为二维码添加logo图标 */
if (logoBitmap != null) {
return addQRCodeLogo(bitmap, logoBitmap, logoPercent);
}
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
/**
* 向二维码中间添加logo图片(图片合成)
*
* @param srcBitmap 原图片(生成的简单二维码图片)
* @param logoBitmap logo图片
* @param logoPercent 百分比 (用于调整logo图片在原图片中的显示大小, 取值范围[0,1] )
* 原图片是二维码时,建议使用0.2F,百分比过大可能导致二维码扫描失败。
* @return
*/
@Nullable
private static Bitmap addQRCodeLogo(@Nullable Bitmap srcBitmap, @Nullable Bitmap logoBitmap,
float logoPercent) {
if (srcBitmap == null) {
return null;
}
if (logoBitmap == null) {
return srcBitmap;
}
//传值不合法时使用0.2F
if (logoPercent < 0F || logoPercent > 1F) {
logoPercent = 0.2F;
}
/** 1. 获取原图片和Logo图片各自的宽、高值 */
int srcWidth = srcBitmap.getWidth();
int srcHeight = srcBitmap.getHeight();
int logoWidth = logoBitmap.getWidth();
int logoHeight = logoBitmap.getHeight();
/** 2. 计算画布缩放的宽高比 */
float scaleWidth = srcWidth * logoPercent / logoWidth;
float scaleHeight = srcHeight * logoPercent / logoHeight;
/** 3. 使用Canvas绘制,合成图片 */
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(srcBitmap, 0, 0, null);
canvas.scale(scaleWidth, scaleHeight, srcWidth / 2, srcHeight / 2);
canvas.drawBitmap(logoBitmap, srcWidth / 2 - logoWidth / 2,
srcHeight / 2 - logoHeight / 2, null);
return bitmap;
}
/**
* 生成二维码
*
* @param QRString
* @param width
* @param height
* @param logo
* @return
*/
public static Bitmap create(String QRString, int width, int height, Bitmap logo) {
if (TextUtils.isEmpty(QRString)) {
return null;
}
/*偏移量*/
int offsetX = width / 2;
int offsetY = height / 2;
/*生成logo*/
Bitmap logoBitmap = null;
if (logo != null) {
Matrix matrix = new Matrix();
float scaleFactor = Math.min(width * 1.0f / 5 / logo.getWidth(),
height * 1.0f / 5 / logo.getHeight());
matrix.postScale(scaleFactor, scaleFactor);
logoBitmap = Bitmap.createBitmap(logo, 0, 0, logo.getWidth(), logo.getHeight(),
matrix, true);
}
/*如果log不为null,重新计算偏移量*/
int logoW = 0;
int logoH = 0;
if (logoBitmap != null) {
logoW = logoBitmap.getWidth();
logoH = logoBitmap.getHeight();
offsetX = (width - logoW) / 2;
offsetY = (height - logoH) / 2;
}
/*指定为UTF-8*/
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
hints.put(EncodeHintType.MARGIN, 0);
// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
BitMatrix matrix = null;
try {
matrix = new MultiFormatWriter().encode(QRString, BarcodeFormat.QR_CODE, width,
height, hints);
// 二维矩阵转为一维像素数组,也就是一直横着排了
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x >= offsetX && x < offsetX + logoW && y >= offsetY && y < offsetY + logoH) {
int pixel = logoBitmap.getPixel(x - offsetX, y - offsetY);
if (pixel == 0) {
if (matrix.get(x, y)) {
pixel = 0xff000000;
} else {
pixel = 0xffffffff;
}
}
pixels[y * width + x] = pixel;
} else {
if (matrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else {
pixels[y * width + x] = 0xffffffff;
}
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
System.out.print(e);
return null;
}
}
}
|
/*
* Copyright 2006 Ameer Antar.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.antfarmer.ejce.encoder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.regex.Pattern;
/**
* Abstract encoder for encoding/decoding bytes and text using the Base-32 format. The
* encoded results contain only US-ASCII letters and numbers. The character set includes: [A-Z2-7].
* This format results in a 60% increase in output length at best. <b>This class is thread-safe.</b>
*
* @author Ameer Antar
* @version 1.2
*/
public abstract class AbstractBase32Encoder implements TextEncoder {
private static final Pattern WHITE_SPACE_PATTERN = Pattern.compile("\\s");
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
/**
* Array used for encoding text to Base32.
*/
private final byte[] encodeArray = new byte[32];
/**
* Array used for decoding text from Base32.
*/
private final byte[] decodeArray = new byte[121];
/**
* Character to be used for padding Base32 encoded text.
*/
private final byte paddingChar;
/**
* Indicates whether padding should be used for encoding/decoding data.
*/
private final boolean usePadding;
/**
* Initializes the AbstractBase32Encoder.
*/
protected AbstractBase32Encoder() {
// setup encode array
for (int i = 0; i < 26; i++)
encodeArray[i] = (byte) (i + 65);
for (int i = 26; i < 32; i++)
encodeArray[i] = (byte) (i + 24);
// setup decode array
Arrays.fill(decodeArray, (byte) -1);
for (int i = 65; i < 91; i++)
decodeArray[i] = (byte) (i - 65);
for (int i = 50; i < 56; i++)
decodeArray[i] = (byte) (i - 24);
paddingChar = getPaddingChar();
usePadding = isUsePadding();
}
/**
* Returns the encodeArray.
* @return the encodeArray
*/
protected final byte[] getEncodeArray() {
return encodeArray;
}
/**
* Returns the decodeArray.
* @return the decodeArray
*/
protected final byte[] getDecodeArray() {
return decodeArray;
}
/**
* Returns the padding character.
* @return the padding character
*/
protected byte getPaddingChar() {
return '=';
}
/**
* Returns true if this encoder uses padding.
* @return true if this encoder uses padding; false otherwise
*/
protected boolean isUsePadding() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String encode(final byte[] bytes) {
if (bytes == null)
return null;
int originalSize = bytes.length;
if (originalSize < 1) {
return "";
}
int i;
// convert bytes to unsigned chars
final char[] chars = new char[originalSize];
for (i = 0; i < originalSize; i++) {
if (bytes[i] < 0)
chars[i] = (char) (bytes[i] + 256);
else
chars[i] = (char) bytes[i];
}
byte[] encodedBytes;
final int remainder = originalSize % 5;
if (remainder == 0) {
encodedBytes = new byte[((originalSize << 3) / 5)];
}
else {
if (!usePadding) {
encodedBytes = new byte[(int) Math.ceil((originalSize << 3) / 5.0)];
}
else {
encodedBytes = new byte[(((originalSize + 5 - remainder) << 3) / 5)];
}
originalSize -= remainder;
}
int k = 0;
for (i = 0; i < originalSize; i += 5) {
encodedBytes[k] = encodeArray[chars[i] >> 3];
encodedBytes[k + 1] = encodeArray[((chars[i] & 0x07) << 2) + (chars[i + 1] >> 6)];
encodedBytes[k + 2] = encodeArray[((chars[i + 1] & 0x3F) >> 1)];
encodedBytes[k + 3] = encodeArray[((chars[i + 1] & 0x01) << 4) + (chars[i + 2] >> 4)];
encodedBytes[k + 4] = encodeArray[((chars[i + 2] & 0x0F) << 1) + (chars[i + 3] >> 7)];
encodedBytes[k + 5] = encodeArray[((chars[i + 3] & 0x7F) >> 2)];
encodedBytes[k + 6] = encodeArray[((chars[i + 3] & 0x03) << 3) + (chars[i + 4] >> 5)];
encodedBytes[k + 7] = encodeArray[(chars[i + 4] & 0x1F)];
k += 8;
}
if (remainder == 1) {
// 1 extra byte
encodedBytes[k] = encodeArray[chars[i] >> 3];
encodedBytes[k + 1] = encodeArray[((chars[i] & 0x07) << 2)];
if (usePadding) {
encodedBytes[k + 2] = paddingChar;
encodedBytes[k + 3] = paddingChar;
encodedBytes[k + 4] = paddingChar;
encodedBytes[k + 5] = paddingChar;
encodedBytes[k + 6] = paddingChar;
encodedBytes[k + 7] = paddingChar;
}
}
else if (remainder == 2) {
// 2 extra bytes
encodedBytes[k] = encodeArray[chars[i] >> 3];
encodedBytes[k + 1] = encodeArray[((chars[i] & 0x07) << 2) + (chars[i + 1] >> 6)];
encodedBytes[k + 2] = encodeArray[((chars[i + 1] & 0x3F) >> 1)];
encodedBytes[k + 3] = encodeArray[((chars[i + 1] & 0x01) << 4)];
if (usePadding) {
encodedBytes[k + 4] = paddingChar;
encodedBytes[k + 5] = paddingChar;
encodedBytes[k + 6] = paddingChar;
encodedBytes[k + 7] = paddingChar;
}
}
else if (remainder == 3) {
// 3 extra bytes
encodedBytes[k] = encodeArray[chars[i] >> 3];
encodedBytes[k + 1] = encodeArray[((chars[i] & 0x07) << 2) + (chars[i + 1] >> 6)];
encodedBytes[k + 2] = encodeArray[((chars[i + 1] & 0x3F) >> 1)];
encodedBytes[k + 3] = encodeArray[((chars[i + 1] & 0x01) << 4) + (chars[i + 2] >> 4)];
encodedBytes[k + 4] = encodeArray[((chars[i + 2] & 0x0F) << 1)];
if (usePadding) {
encodedBytes[k + 5] = paddingChar;
encodedBytes[k + 6] = paddingChar;
encodedBytes[k + 7] = paddingChar;
}
}
else if (remainder == 4) {
// 4 extra bytes
encodedBytes[k] = encodeArray[chars[i] >> 3];
encodedBytes[k + 1] = encodeArray[((chars[i] & 0x07) << 2) + (chars[i + 1] >> 6)];
encodedBytes[k + 2] = encodeArray[((chars[i + 1] & 0x3F) >> 1)];
encodedBytes[k + 3] = encodeArray[((chars[i + 1] & 0x01) << 4) + (chars[i + 2] >> 4)];
encodedBytes[k + 4] = encodeArray[((chars[i + 2] & 0x0F) << 1) + (chars[i + 3] >> 7)];
encodedBytes[k + 5] = encodeArray[((chars[i + 3] & 0x7F) >> 2)];
encodedBytes[k + 6] = encodeArray[((chars[i + 3] & 0x03) << 3)];
if (usePadding) {
encodedBytes[k + 7] = paddingChar;
}
}
return new String(encodedBytes, DEFAULT_CHARSET);
}
/**
* {@inheritDoc}
*/
@Override
public byte[] decode(final String text) {
if (text == null)
return null;
// cleanup input string
final String encodedText = WHITE_SPACE_PATTERN.matcher(text).replaceAll("");
int originalSize = encodedText.length();
if (originalSize < 1) {
return new byte[0];
}
if (usePadding && originalSize % 8 != 0) {
throw new IllegalArgumentException("Encoded string does not match Base-32 format with padding.");
}
int newSize = (originalSize * 5) >> 3;
int remainder = 8;
if (usePadding) {
final int p = encodedText.indexOf(paddingChar);
if (p > 0) {
newSize -= Math.round((originalSize - p) * 5 / 8.0);
remainder = p % 8;
}
}
else {
final int m = originalSize % 8;
if (m > 0)
remainder = m;
}
final byte[] byteArr = new byte[newSize];
originalSize -= 8;
int i, j = 0;
final byte[] hexArr = new byte[8];
for (i = 0; i < originalSize; i += 8) {
for (int k = 0; k < 8; k++)
hexArr[k] = getDecodedValue(encodedText.charAt(i + k));
byteArr[j] = (byte) (hexArr[0] << 3);
byteArr[j] += (hexArr[1] >> 2);
byteArr[j + 1] = (byte) (hexArr[1] << 6);
byteArr[j + 1] += (hexArr[2] << 1);
byteArr[j + 1] += (hexArr[3] >> 4);
byteArr[j + 2] = (byte) (hexArr[3] << 4);
byteArr[j + 2] += (hexArr[4] >> 1);
byteArr[j + 3] = (byte) (hexArr[4] << 7);
byteArr[j + 3] += (hexArr[5] << 2);
byteArr[j + 3] += (hexArr[6] >> 3);
byteArr[j + 4] = (byte) (hexArr[6] << 5);
byteArr[j + 4] += hexArr[7];
j += 5;
}
for (int k = 0; k < remainder; k++)
hexArr[k] = getDecodedValue(encodedText.charAt(i + k));
byteArr[j] = (byte) (hexArr[0] << 3);
byteArr[j] += (hexArr[1] >> 2);
if (newSize > j + 1) {
byteArr[j + 1] = (byte) (hexArr[1] << 6);
byteArr[j + 1] += (hexArr[2] << 1);
byteArr[j + 1] += (hexArr[3] >> 4);
}
if (newSize > j + 2) {
byteArr[j + 2] = (byte) (hexArr[3] << 4);
byteArr[j + 2] += (hexArr[4] >> 1);
}
if (newSize > j + 3) {
byteArr[j + 3] = (byte) (hexArr[4] << 7);
byteArr[j + 3] += (hexArr[5] << 2);
byteArr[j + 3] += (hexArr[6] >> 3);
}
if (newSize > j + 4) {
byteArr[j + 4] = (byte) (hexArr[6] << 5);
byteArr[j + 4] += hexArr[7];
}
return byteArr;
}
private byte getDecodedValue(final int ch) {
if (ch < 0 || ch >= decodeArray.length || decodeArray[ch] == -1) {
throw new IllegalArgumentException("Base-32 encoded string contained invalid character: " + (char)(ch));
}
return decodeArray[ch];
}
}
|
public class changevalue {
public static void main(String [] args){
circle circle1 = new circle(1);
circle circle2 = new circle(2);
swap(circle1, circle2);
System.out.println("circle1 radius:" + circle1.radius);
System.out.println("circle2 radius:" + circle2.radius);
}
public static void swap(circle x, circle y){
double temp = x.radius;
x.radius = y.radius;
y.radius = temp;
}
}
class circle{
double radius;
circle(double newradius){
radius = newradius;
}
}
|
package t6;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Random;
public class Tablero extends java.util.Observable{
public static final int VACIO=0;
public static final int VIVO=1;
public static final int MUERTO=2;
private int[][] tablero;
private int size;
private PropertyChangeSupport support;
public void addPropertyChangeListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
public Tablero(int size) {
support = new PropertyChangeSupport(this);
tablero = new int[size][size];
this.size = size;
}
public void setCasilla (int x, int y, int estado) {
tablero[x][y] = estado;
}
public int getCasilla (int x, int y) {
return tablero[x][y];
}
public int size() {
return size;
}
public int size(int estado) {
int cont=0;
for (int x=0;x<size;x++)
for (int y=0;y<size;y++)
if (tablero[x][y]==estado)
cont++;
return cont;
}
public void initRandom(int numCasillas, int estado) {
Random rx = new Random();
Random ry = new Random();
int i=0;
do {
int x = rx.nextInt(size);
int y = ry.nextInt(size);
if (tablero[x][y]==VACIO) {
tablero[x][y] = estado;
i++;
}
} while(i<numCasillas);
}
public soluciont6.Tablero clone() {
soluciont6.Tablero t = new soluciont6.Tablero(size);
for (int x=0;x<size;x++)
for (int y=0;y<size;y++)
t.setCasilla(x,y,tablero[x][y]);
return t;
}
public void set(Tablero tablero) {
System.out.println("Tablero.set()");
support.firePropertyChange("tablero", this.tablero, tablero); // ******** Modelo Vista Controlador
for (int x=0;x<size;x++)
for (int y=0;y<size;y++)
this.tablero[x][y] = tablero.getCasilla(x,y);
}
public String toString() {
String aux="";
for (int x=0;x<size;x++) {
for (int y=0;y<size;y++)
aux=aux+tablero[x][y];
aux=aux+"\n";
}
return aux;
}
}
|
package com.hy.flinktest.kafka2mysql;
import com.hy.flinktest.entity.User;
import com.hy.flinktest.utils.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
/**
* ClassName: WriteMysqlSink
* Description: 写入目标数据库sink
*
* @Author: dengchangshi
* @Date: 2020/9/24 10:19
*/
@Slf4j
public class MysqlRichSinkFunction extends RichSinkFunction<List<User>> {
private Connection connection = null;
private PreparedStatement ps = null;
@Override
public void open(Configuration parameters) throws Exception {
// super.open(parameters);
log.info("获取数据库连接");
connection = DbUtil.getConnection();
String sql = "insert into user1(id,name) values (?,?)";
ps = connection.prepareStatement(sql);
}
public void invoke(List<User> users, Context ctx) throws Exception {
//获取ReadMysqlResoure发送过来的结果
for(User user : users) {
ps.setLong(1, user.getId());
ps.setString(2, user.getName());
ps.addBatch();
}
//一次性写入
int[] count = ps.executeBatch();
log.info("成功写入Mysql数量:" + count.length);
}
@Override
public void close() throws Exception {
//关闭并释放资源
if(connection != null) {
connection.close();
}
if(ps != null) {
ps.close();
}
}
}
|
package com.projet3.library_webservice.library_webservice_consumer.DAO;
import com.projet3.library_webservice.library_webservice_consumer.RowMapper.BookRowMapper;
import com.projet3.library_webservice.library_webservice_model.beans.Book;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
public class BookDAOImpl extends AbstractDAO implements BookDAO{
@Autowired
private AuthorDAO authorDAO;
@Autowired
private PublisherDAO publisherDAO;
@Override
public List<Book> getBookByTitle(String title) throws SQLException {
String sql = "SELECT * FROM book WHERE title = :title";
SqlParameterSource namedParameters = new MapSqlParameterSource("title", title);
List<Book> bookList = namedParameterTemplate.query(sql, namedParameters, new BookRowMapper(authorDAO, publisherDAO));
return bookList;
}
@Override
public Book getBookById(int id) throws SQLException {
String sql = "SELECT * FROM book WHERE book_id = :book_id";
SqlParameterSource namedParameters = new MapSqlParameterSource("book_id", id);
Book book = namedParameterTemplate.queryForObject(sql, namedParameters, new BookRowMapper(authorDAO, publisherDAO));
return book;
}
@Override
public List<Book> getBookList() throws SQLException {
String sql = "SELECT * FROM book";
List<Book> bookList = new ArrayList<Book>();
bookList = template.query(sql, new BookRowMapper(authorDAO, publisherDAO));
return bookList;
}
@Override
public List<Book> bookResearch(String title) throws SQLException {
String sql = "SELECT * FROM book WHERE title LIKE :title";
SqlParameterSource namedParameters = new MapSqlParameterSource("title", "%"+title+"%");
List<Book> bookFound = new ArrayList<Book>();
bookFound = namedParameterTemplate.query(sql, namedParameters, new BookRowMapper(authorDAO, publisherDAO));
return bookFound;
}
@Override
public void createBook(Book book) {
String sql = "INSERT INTO book (title, description, available, author_id, publisher_id) VALUES (:title, :description, :available, :author_id, :publisher_id)";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("title", book.getTitle());
params.addValue("description", book.getDescription());
params.addValue("available", book.getAvailable());
params.addValue("author_id", book.getAuthor().getId());
params.addValue("publisher_id", book.getPublisher().getId());
namedParameterTemplate.update(sql, params);
}
@Override
public void updateBook(Book book) throws SQLException {
String sql = "UPDATE book SET title = :title, description = :description, available = :available, author_id = :author_id, publisher_id = :publisher_id WHERE book_id = :book_id";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("book_id", book.getId());
params.addValue("title", book.getTitle());
params.addValue("description", book.getDescription());
params.addValue("available", book.getAvailable());
params.addValue("author_id", book.getAuthor().getId());
params.addValue("publisher_id", book.getPublisher().getId());
namedParameterTemplate.update(sql, params);
}
@Override
public void deleteBook(Book book) throws SQLException {
String sql = "DELETE FROM book WHERE book_id = :book_id";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("book_id", book.getId());
namedParameterTemplate.update(sql, params);
}
@Override
public int countBook(String title) throws SQLException {
String sql = "SELECT COUNT(*) FROM book WHERE title = :title AND available = 1";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("title", title);
return namedParameterTemplate.queryForObject(sql, params, Integer.class);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.client.config.services.impl;
import de.hybris.platform.servicelayer.keygenerator.KeyGenerator;
import org.apache.log4j.Logger;
import com.cnk.travelogix.client.config.core.document.model.DocumentManagementModel;
import com.cnk.travelogix.client.config.services.DocumentManagementService;
/**
* Generates code using keyGenerator and set into documentId attribute.
*/
public class DefaultDocumentManagementService implements DocumentManagementService
{
private final Logger LOG = Logger.getLogger(DefaultDocumentManagementService.class);
private KeyGenerator keyGenerator;
@Override
public void generateDocumentId(final DocumentManagementModel documentManagementModel)
{
if (documentManagementModel.getDocumentId() == null)
{
documentManagementModel.setDocumentId("DOC" + keyGenerator.generate().toString());
LOG.debug("Set new code for DocumentManagement Model -" + documentManagementModel.getDocumentId());
}
}
/**
* @return the keyGenerator
*/
public KeyGenerator getKeyGenerator()
{
return keyGenerator;
}
/**
* @param keyGenerator
* the keyGenerator to set
*/
public void setKeyGenerator(final KeyGenerator keyGenerator)
{
this.keyGenerator = keyGenerator;
}
}
|
package com.tencent.mm.plugin.account.bind.ui;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tencent.mm.aa.c;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.account.a$c;
import com.tencent.mm.plugin.account.a$e;
import com.tencent.mm.plugin.account.a.f;
import com.tencent.mm.plugin.account.a.i;
import com.tencent.mm.plugin.account.a.j;
import com.tencent.mm.plugin.account.friend.a.n;
import com.tencent.mm.plugin.account.friend.a.o;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.r;
public final class a extends r<n> {
private String eEW;
a eHS;
private Context mContext;
private String mFilter;
private LayoutInflater mLayoutInflater = LayoutInflater.from(this.mContext);
class b {
ImageView eBM;
TextView eBR;
String eHT;
TextView eHU;
TextView eHV;
View eHW;
ProgressBar eHX;
int position;
public b(View view) {
this.eBM = (ImageView) view.findViewById(f.gcontact_avatar_iv);
this.eHU = (TextView) view.findViewById(f.gcontact_name_tv);
this.eHW = view.findViewById(f.gcontact_operation_view);
this.eBR = (TextView) view.findViewById(f.gcontact_status_tv);
this.eHX = (ProgressBar) view.findViewById(f.gcontact_invita_pb);
this.eHV = (TextView) view.findViewById(f.gcontact_email_tv);
this.eHW.setOnClickListener(new 1(this, a.this));
}
}
public final /* synthetic */ Object a(Object obj, Cursor cursor) {
n nVar = (n) obj;
if (nVar == null) {
nVar = new n();
}
nVar.d(cursor);
return nVar;
}
public a(Context context, String str) {
super(context, new n());
this.eEW = str;
this.mContext = context;
}
protected final void WS() {
WT();
}
public final void WT() {
o oVar = (o) ((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).getGoogleFriendStorage();
String str = this.mFilter;
String str2 = this.eEW;
StringBuilder stringBuilder = new StringBuilder();
if (TextUtils.isEmpty(str)) {
stringBuilder.append(" WHERE ( GoogleFriend.googlegmail!='" + str2 + "' )");
} else {
stringBuilder.append(" WHERE ( ");
stringBuilder.append("GoogleFriend.googlegmail!='" + str2 + "' AND ");
stringBuilder.append("GoogleFriend.googlename LIKE '%" + str + "%' OR ");
stringBuilder.append("GoogleFriend.googlenamepy LIKE '%" + str + "%' OR ");
stringBuilder.append("GoogleFriend.googlegmail LIKE '%" + str + "%' OR ");
stringBuilder.append("GoogleFriend.nickname LIKE '%" + str + "%' ) ");
}
stringBuilder.append(" GROUP BY googleid,contecttype");
stringBuilder.append(" ORDER BY status , googlenamepy ASC , usernamepy ASC");
setCursor(oVar.diF.rawQuery("SELECT GoogleFriend.googleid,GoogleFriend.googlename,GoogleFriend.googlephotourl,GoogleFriend.googlegmail,GoogleFriend.username,GoogleFriend.nickname,GoogleFriend.nicknameqp,GoogleFriend.usernamepy,GoogleFriend.small_url,GoogleFriend.big_url,GoogleFriend.ret,GoogleFriend.status,GoogleFriend.googleitemid,GoogleFriend.googlecgistatus,GoogleFriend.contecttype,GoogleFriend.googlenamepy FROM GoogleFriend " + stringBuilder.toString(), null));
super.notifyDataSetChanged();
}
public final void pi(String str) {
this.mFilter = bi.oU(str);
aYc();
WT();
}
public final View getView(int i, View view, ViewGroup viewGroup) {
b bVar;
if (view == null || view.getTag() == null) {
view = this.mLayoutInflater.inflate(com.tencent.mm.plugin.account.a.g.gcontact_friend_list_item, null);
b bVar2 = new b(view);
view.setTag(bVar2);
bVar = bVar2;
} else {
bVar = (b) view.getTag();
}
n nVar = (n) getItem(i);
if (nVar != null) {
bVar.position = i;
bVar.eHT = nVar.field_googlegmail;
Bitmap a;
switch (nVar.field_status) {
case 0:
case 2:
if (nVar.field_small_url != null) {
a = c.a(nVar.field_username, false, -1);
} else {
a = null;
}
if (a != null) {
bVar.eBM.setImageBitmap(a);
break;
}
bVar.eBM.setImageDrawable(com.tencent.mm.bp.a.f(this.mContext, i.default_avatar));
break;
case 1:
a = c.jF(nVar.field_googleid);
if (a != null) {
bVar.eBM.setImageBitmap(a);
break;
}
bVar.eBM.setImageDrawable(com.tencent.mm.bp.a.f(this.mContext, i.default_avatar));
break;
}
if (TextUtils.isEmpty(nVar.field_googlename)) {
bVar.eHU.setText(bi.Xe(nVar.field_googlegmail));
} else {
bVar.eHU.setText(nVar.field_googlename);
}
switch (nVar.field_status) {
case 0:
bVar.eHW.setClickable(true);
bVar.eHW.setBackgroundResource(a$e.btn_solid_green);
bVar.eBR.setText(j.gcontact_add);
bVar.eBR.setTextColor(this.mContext.getResources().getColor(a$c.white));
break;
case 1:
bVar.eHW.setClickable(true);
bVar.eHW.setBackgroundResource(a$e.btn_solid_grey);
bVar.eBR.setText(j.gcontact_invite);
bVar.eBR.setTextColor(this.mContext.getResources().getColor(a$c.lightgrey));
break;
case 2:
bVar.eHW.setClickable(false);
bVar.eHW.setBackgroundDrawable(null);
bVar.eBR.setText(j.gcontact_added);
bVar.eBR.setTextColor(this.mContext.getResources().getColor(a$c.lightgrey));
break;
}
switch (nVar.field_googlecgistatus) {
case 0:
bVar.eBR.setVisibility(4);
bVar.eHX.setVisibility(0);
break;
case 1:
bVar.eHW.setClickable(false);
bVar.eHW.setBackgroundDrawable(null);
bVar.eBR.setVisibility(0);
bVar.eHX.setVisibility(8);
bVar.eBR.setTextColor(this.mContext.getResources().getColor(a$c.lightgrey));
switch (nVar.field_status) {
case 0:
bVar.eBR.setText(j.gcontact_add_done);
break;
case 1:
bVar.eBR.setText(j.gcontact_invite_done);
break;
}
break;
case 2:
bVar.eBR.setVisibility(0);
bVar.eHX.setVisibility(8);
switch (nVar.field_status) {
case 0:
bVar.eBR.setText(j.gcontact_add);
bVar.eBR.setTextColor(this.mContext.getResources().getColor(a$c.white));
break;
case 1:
bVar.eBR.setText(j.gcontact_invite);
bVar.eBR.setTextColor(this.mContext.getResources().getColor(a$c.lightgrey));
break;
}
break;
}
bVar.eHV.setText(nVar.field_googlegmail);
}
return view;
}
}
|
package com.quoai.challenge.ws.rest;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.quoai.challenge.service.MetricService;
@RestController
@RequestMapping("/api")
public class MetricResource {
@Autowired
private MetricService metricService;
@RequestMapping(method = RequestMethod.GET, value="/metrics",produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
public ResponseEntity<?> getGitHubMetrics(HttpServletResponse response) throws FileNotFoundException, IOException {
String data = metricService.downloadGitHubDataSource();
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=metrics.csv")
.contentType(MediaType.parseMediaType("text/csv"))
.body(data);
}
}
|
/* 1: */ package com.kaldin.test.executetest.dto;
/* 2: */
/* 3: */ public class DetailResultDTO
/* 4: */ {
/* 5: */ private int questionid;
/* 6: */ private int topicid;
/* 7: */ private String question;
/* 8: */ private String remark;
/* 9: */ private int markperquestion;
/* 10: */ private int negativemark;
/* 11: */ private String topicName;
/* 12: */ private String givenAnswer;
/* 13: */ private String correctAnswer;
/* 14: */
/* 15: */ public int getQuestionid()
/* 16: */ {
/* 17:19 */ return this.questionid;
/* 18: */ }
/* 19: */
/* 20: */ public int getMarkperquestion()
/* 21: */ {
/* 22:22 */ return this.markperquestion;
/* 23: */ }
/* 24: */
/* 25: */ public void setMarkperquestion(int markperquestion)
/* 26: */ {
/* 27:25 */ this.markperquestion = markperquestion;
/* 28: */ }
/* 29: */
/* 30: */ public int getNegativemark()
/* 31: */ {
/* 32:28 */ return this.negativemark;
/* 33: */ }
/* 34: */
/* 35: */ public void setNegativemark(int negativemark)
/* 36: */ {
/* 37:31 */ this.negativemark = negativemark;
/* 38: */ }
/* 39: */
/* 40: */ public void setQuestionid(int questionid)
/* 41: */ {
/* 42:34 */ this.questionid = questionid;
/* 43: */ }
/* 44: */
/* 45: */ public int getTopicid()
/* 46: */ {
/* 47:37 */ return this.topicid;
/* 48: */ }
/* 49: */
/* 50: */ public void setTopicid(int topicid)
/* 51: */ {
/* 52:40 */ this.topicid = topicid;
/* 53: */ }
/* 54: */
/* 55: */ public String getGivenAnswer()
/* 56: */ {
/* 57:43 */ return this.givenAnswer;
/* 58: */ }
/* 59: */
/* 60: */ public void setGivenAnswer(String givenAnswer)
/* 61: */ {
/* 62:46 */ this.givenAnswer = givenAnswer;
/* 63: */ }
/* 64: */
/* 65: */ public String getCorrectAnswer()
/* 66: */ {
/* 67:49 */ return this.correctAnswer;
/* 68: */ }
/* 69: */
/* 70: */ public void setCorrectAnswer(String correctAnswer)
/* 71: */ {
/* 72:52 */ this.correctAnswer = correctAnswer;
/* 73: */ }
/* 74: */
/* 75: */ public String getTopicName()
/* 76: */ {
/* 77:55 */ return this.topicName;
/* 78: */ }
/* 79: */
/* 80: */ public void setTopicName(String topicName)
/* 81: */ {
/* 82:58 */ this.topicName = topicName;
/* 83: */ }
/* 84: */
/* 85: */ public String getQuestion()
/* 86: */ {
/* 87:61 */ return this.question;
/* 88: */ }
/* 89: */
/* 90: */ public void setQuestion(String question)
/* 91: */ {
/* 92:64 */ this.question = question;
/* 93: */ }
/* 94: */
/* 95: */ public String getRemark()
/* 96: */ {
/* 97:67 */ return this.remark;
/* 98: */ }
/* 99: */
/* :0: */ public void setRemark(String remark)
/* :1: */ {
/* :2:70 */ this.remark = remark;
/* :3: */ }
/* :4: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.test.executetest.dto.DetailResultDTO
* JD-Core Version: 0.7.0.1
*/
|
package es.uma.sportjump.sjs.web.ajax;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import es.uma.sportjump.sjs.model.entities.Coach;
import es.uma.sportjump.sjs.model.entities.ExerciseBlock;
import es.uma.sportjump.sjs.model.entities.Training;
import es.uma.sportjump.sjs.service.services.ExerciseService;
import es.uma.sportjump.sjs.service.services.TrainingService;
import es.uma.sportjump.sjs.web.beans.ExerciseBean;
import es.uma.sportjump.sjs.web.beans.TrainingBean;
import es.uma.sportjump.sjs.web.beans.mappings.TrainingBeanMapping;
@Controller
@RequestMapping("/ajax/training")
public class TrainigAjax<E> {
@Autowired
TrainingService trainingService;
@Autowired
ExerciseService exerciseService;
@RequestMapping(value ="/day/{idTrainingDay}" , method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody TrainingBean getTrainingDay(@PathVariable("idTrainingDay") Long idTrainingDay){
Training training = trainingService.findTraining(idTrainingDay);
if (training == null){
throw new EmptyResultDataAccessException("Training element not found", 1);
}
TrainingBean result = TrainingBeanMapping.fillTrainingBean(training);
return result;
}
@RequestMapping(value ="/exercise/{idExerciseBlock}" , method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody ExerciseBean getExerciseBlock(@PathVariable("idExerciseBlock") Long idExerciseBlock){
ExerciseBlock exererciseBlock = exerciseService.findExerciseBlock(idExerciseBlock);
if (exererciseBlock == null){
throw new EmptyResultDataAccessException("Training element not found", 1);
}
ExerciseBean result = TrainingBeanMapping.fillExerciseBlock(exererciseBlock);
return result;
}
@RequestMapping(value ="/exercise/name/{nameExerciseBlock}" , method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody ExerciseBean getExerciseBlockByName(@PathVariable("nameExerciseBlock") String nameExerciseBlock, HttpSession session){
Coach coach = (Coach) session.getAttribute("loggedUser");
ExerciseBlock exererciseBlock = exerciseService.findExerciseBlockByNameAndCoach(nameExerciseBlock, coach);
if (exererciseBlock == null){
throw new EmptyResultDataAccessException("Training element not found", 1);
}
ExerciseBean result = TrainingBeanMapping.fillExerciseBlock(exererciseBlock);
return result;
}
@RequestMapping(value ="/exercise/names/{namesExerciseBlock}" , method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody TrainingBean getTrainingDay(@PathVariable("namesExerciseBlock") String names, HttpSession session){
TrainingBean result = new TrainingBean();
String[] nameArray = names.split("-");
Coach coach = (Coach) session.getAttribute("loggedUser");
List<ExerciseBean> listExerciseWebBean = new ArrayList<ExerciseBean>();
for(String name : nameArray){
ExerciseBlock block = exerciseService.findExerciseBlockByNameAndCoach(name, coach);
listExerciseWebBean.add(TrainingBeanMapping.fillExerciseBlock(block));
}
result.setListBlock(listExerciseWebBean);
return result;
}
//
// @ExceptionHandler(NullPointerException.class)
// @ResponseBody
// public String handleException1(NullPointerException ex)
// {
// return ex.getMessage();
// }
//
// @ExceptionHandler(TrainingNotFoundException.class)
// @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Element not Found")
// public void notFound() {
// }
@ExceptionHandler(EmptyResultDataAccessException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Element not Found")
public void notFound() {
}
}
|
package page;
public class Review {
} // end class Review
|
package co.aurasphere.courseware.j2ee.spring.boot.webflux;
public class ControllerResponse {
private String content;
public ControllerResponse() {
this.content = "some content";
}
public ControllerResponse(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "BenchmarkResponse [content=" + content + "]";
}
}
|
package com.pangpang6.books.offer.chapter4;
import com.pangpang6.books.offer.structure.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
/**
* 分行从上到下打印二叉树
*/
public class P174_printTreeInLine {
public static void printTreeInLine(TreeNode<Integer> root) {
if (root == null) {
return;
}
Queue<TreeNode<Integer>> queue = new LinkedList<>();
queue.offer(root);
TreeNode<Integer> temp;
while (!queue.isEmpty()) {
for (int size = queue.size(); size > 0; size--) {
temp = queue.poll();
System.out.print(temp.val);
System.out.print("\t");
if (temp.left != null) {
queue.offer(temp.left);
}
if (temp.right != null) {
queue.offer(temp.right);
}
}
System.out.println();
}
}
public static void main(String[] args) {
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
TreeNode<Integer> root = new TreeNode<Integer>(1);
root.left = new TreeNode<Integer>(2);
root.right = new TreeNode<Integer>(3);
root.left.left = new TreeNode<Integer>(4);
root.left.right = new TreeNode<Integer>(5);
root.right.left = new TreeNode<Integer>(6);
root.right.right = new TreeNode<Integer>(7);
printTreeInLine(root);
}
}
|
package c10.s02.t05;
/**SinglycCircularLinked
* 10.2-5
* @author he
*@email wubuqilai@gmail.com
*/
public class SinglycCircularLinked<T> {
private Node<T> head=null;
private Node<T> tail=null;
private int count=0;
/** O(1)
* insert to head
* @param element
*/
public void insert(T element) {
if (head==null) {
head=new Node<T>(element);
head.next=head;
tail=head;
}else {
Node<T> newHead=new Node<T>(element);
newHead.next=head;
tail.next=head=newHead;
}
++count;
}
/** worst O(n)
* @param element
* @return
*/
public int search(T element) {
if (head==null) {
return -1;
}
if (head.element.equals(element)) {
return 0;
}
int poistion=1;
for (Node<T> node=head.next;node!=head;node=node.next,++poistion) {
if (node.element.equals(element)) {
return poistion;
}
}
return -1;
}
/** 10.2-6
* @param candidate
* @return
*/
public SinglycCircularLinked<T> union(SinglycCircularLinked<T> candidate) {
if (candidate!=null) {
this.tail.next=candidate.head;
candidate.tail.next=this.head;
this.tail=candidate.tail;
this.count+=candidate.count;
}
return this;
}
/**O(n)
* 10.2-7
* @return
*/
public SinglycCircularLinked<T> reverse() {
if (this.head!=null) {
for (Node<T> prev=this.head,cur=this.head.next;cur!=this.head;) {
Node<T> next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
this.head.next=this.tail;
//wrap head tail
Node<T> temp=this.head;
this.head=this.tail;
this.tail=temp;
}
return this;
}
/** worst O(n)
* @param element
* @return
*/
public boolean delete(T element) {
if (head==null) {
return false;
}
if (head.element.equals(element)) {
if (head.next==head) {
head=tail=null;
}else {
tail.next=head=head.next;
}
--count;
return true;
}
for (Node<T> node=head;node.next!=head;node=node.next) {
if (node.next.element.equals(element)) {
node.next=node.next.next;
--count;
return true;
}
}
return false;
}
public boolean isEmpty() {
return head==null;
}
public int size() {
return count;
}
@Override
public String toString() {
StringBuilder resultBuilder=new StringBuilder();
if (this.head!=null) {
resultBuilder.append(this.head.element.toString()+",");
for (Node<T> node=this.head.next;node!=this.head;node=node.next) {
resultBuilder.append(node.element.toString()+",");
}
}
String result=resultBuilder.toString();
return "SinglycCircularLinked ["+(result.length()>0 ? result.substring(0,result.length()-1) : "")+"]";
}
private class Node<T>{
public Node<T> next=null;
public T element;
public Node(T element) {
this.element = element;
}
}
}
|
package com.TokChatBackend.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.TokChatBackend.models.ApplyJob;
import com.TokChatBackend.models.Blog;
import com.TokChatBackend.models.BlogComment;
import com.TokChatBackend.models.Forum;
import com.TokChatBackend.models.friends;
import com.TokChatBackend.models.Job;
import com.TokChatBackend.models.ProfilePicture;
import com.TokChatBackend.models.User;
@Configuration
@ComponentScan("com.TokChatBackend")
@EnableTransactionManagement
public class DBconfg {
@Bean(name="dataSource")
public DataSource getDataSource(){
System.out.println("About to create DataSource");
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
dataSource.setUsername("user_127");
dataSource.setPassword("127");
System.out.println("Data source created");
return dataSource;
}
@Bean(name="sessionFactory")
public SessionFactory getSessionFactory(){
System.out.println("About to create SessionFactory");
Properties p=new Properties();
p.setProperty("hibernate.dialect","org.hibernate.dialect.OracleDialect");
p.setProperty("hibernate.show_sql", "true");
p.setProperty("hibernate.hbm2ddl.auto","update");
LocalSessionFactoryBuilder factory=new LocalSessionFactoryBuilder(getDataSource());
factory.addAnnotatedClass(Blog.class);
factory.addProperties(p);
factory.addAnnotatedClass(User.class);
factory.addAnnotatedClass(BlogComment.class);
factory.addAnnotatedClass(Job.class);
factory.addAnnotatedClass(friends.class);
factory.addAnnotatedClass(ApplyJob.class);
factory.addAnnotatedClass(Forum.class);
factory.addAnnotatedClass(ProfilePicture.class);
System.out.println("SessionFactory created");
return factory.buildSessionFactory();
}
@Bean(name="transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory){
System.out.println("About to create Hibernate transaction manager");
HibernateTransactionManager tx=new HibernateTransactionManager(sessionFactory);
System.out.println("Transaction manager created");
return tx;
}
}
|
package com.huawei.esdk.tp.professional.local.bean;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.huawei.esdk.tp.professional.local.impl.autogen.Adapter3;
/**
* <p>Java class for ConferenceStatusEx complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ConferenceStatusEx">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="status" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="chair" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="broadcast" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="speaking" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="presentation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="isLock" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="isAudioSwitch" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="switchGate" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="beginTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* <element name="endTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ConferenceStatusEx", propOrder = {
"id",
"name",
"status",
"chair",
"broadcast",
"speaking",
"presentation",
"isLock",
"isAudioSwitch",
"switchGate",
"beginTime",
"endTime"
})
public class ConferenceStatusEx {
protected String id;
protected String name;
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter3 .class)
@XmlSchemaType(name = "int")
protected Integer status;
protected String chair;
protected String broadcast;
protected String speaking;
protected String presentation;
@XmlElement(type = String.class)
@XmlJavaTypeAdapter(Adapter3 .class)
@XmlSchemaType(name = "int")
protected Integer isLock;
@XmlElement(type = String.class)
@XmlJavaTypeAdapter(Adapter3 .class)
@XmlSchemaType(name = "int")
protected Integer isAudioSwitch;
@XmlElement(type = String.class)
@XmlJavaTypeAdapter(Adapter3 .class)
@XmlSchemaType(name = "int")
protected Integer switchGate;
@XmlElement(required = true)
@XmlSchemaType(name = "dateTime")
protected Date beginTime;
@XmlElement(required = true)
@XmlSchemaType(name = "dateTime")
protected Date endTime;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatus(Integer value) {
this.status = value;
}
/**
* Gets the value of the chair property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getChair() {
return chair;
}
/**
* Sets the value of the chair property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setChair(String value) {
this.chair = value;
}
/**
* Gets the value of the broadcast property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBroadcast() {
return broadcast;
}
/**
* Sets the value of the broadcast property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBroadcast(String value) {
this.broadcast = value;
}
/**
* Gets the value of the speaking property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpeaking() {
return speaking;
}
/**
* Sets the value of the speaking property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpeaking(String value) {
this.speaking = value;
}
/**
* Gets the value of the presentation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPresentation() {
return presentation;
}
/**
* Sets the value of the presentation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPresentation(String value) {
this.presentation = value;
}
/**
* Gets the value of the isLock property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getIsLock() {
return isLock;
}
/**
* Sets the value of the isLock property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIsLock(Integer value) {
this.isLock = value;
}
/**
* Gets the value of the isAudioSwitch property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getIsAudioSwitch() {
return isAudioSwitch;
}
/**
* Sets the value of the isAudioSwitch property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIsAudioSwitch(Integer value) {
this.isAudioSwitch = value;
}
/**
* Gets the value of the switchGate property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getSwitchGate() {
return switchGate;
}
/**
* Sets the value of the switchGate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSwitchGate(Integer value) {
this.switchGate = value;
}
/**
* Gets the value of the beginTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public Date getBeginTime() {
return beginTime;
}
/**
* Sets the value of the beginTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setBeginTime(Date value) {
this.beginTime = value;
}
/**
* Gets the value of the endTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public Date getEndTime() {
return endTime;
}
/**
* Sets the value of the endTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndTime(Date value) {
this.endTime = value;
}
}
|
package quickacademy;
import org.testng.annotations.Test;
public class SeleniumTest {
@Test
public void BrowserAutomation()
{
System.out.println("BrowserAutomation");
System.out.println("X 2nd day Github modified 3");
}
@Test
public void elementsUI()
{
System.out.println("elementsUI");
System.out.println("X 3rd day branch modified 4");
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.share;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.tencent.mm.plugin.appbrand.jsapi.share.JsApiShowUpdatableMessageSubscribeButton.ShowUpdatableMessageSubscribeButtonTask;
class JsApiShowUpdatableMessageSubscribeButton$ShowUpdatableMessageSubscribeButtonTask$1 implements Creator<ShowUpdatableMessageSubscribeButtonTask> {
JsApiShowUpdatableMessageSubscribeButton$ShowUpdatableMessageSubscribeButtonTask$1() {
}
public final /* synthetic */ Object createFromParcel(Parcel parcel) {
return new ShowUpdatableMessageSubscribeButtonTask(parcel);
}
public final /* bridge */ /* synthetic */ Object[] newArray(int i) {
return new ShowUpdatableMessageSubscribeButtonTask[i];
}
}
|
/*
* *********************************************************
* Copyright (c) 2019 @alxgcrz All rights reserved.
* This code is licensed under the MIT license.
* Images, graphics, audio and the rest of the assets be
* outside this license and are copyrighted.
* *********************************************************
*/
package com.codessus.ecnaris.ambar.models.combate;
import org.apache.commons.lang3.StringUtils;
public class Monster {
private String name, description, imageFileName;
private int ataque, defensa, damage, absorcion, life, health, level, minEffectiveDamage, maxEffectiveDamage;
private boolean isActive;
// ------ CONSTRUCTOR ---------- //
public Monster() {
isActive = false;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getHumanReadableName() {
String name = StringUtils.replacePattern( this.name, "[0-9]", "" );
name = StringUtils.abbreviate( name, 20 );
return name;
}
private String getDescription() {
return description;
}
public void setDescription( String description ) {
this.description = description;
}
public String getImageNamePrefixedAndWithoutExtension() {
imageFileName = imageFileName.toLowerCase();
return "monster_" + StringUtils.substringBefore( imageFileName, "." );
}
public void setImageFileName( String imageFileName ) {
this.imageFileName = imageFileName;
}
public int getAtaque() {
return ataque;
}
public void setAtaque( int ataque ) {
this.ataque = ataque;
}
public int getDefensa() {
return defensa;
}
public void setDefensa( int defensa ) {
this.defensa = defensa;
}
public int getMinDamageEffective() {
return damage + minEffectiveDamage;
}
public int getMaxEffectiveDamage() {
return damage + maxEffectiveDamage;
}
public void setDamage( int damage ) {
this.damage = damage;
}
public int getDamage() {
return damage;
}
public void setMinEffectiveDamage( int minEffectiveDamage ) {
this.minEffectiveDamage = minEffectiveDamage;
}
public void setMaxEffectiveDamage( int maxEffectiveDamage ) {
this.maxEffectiveDamage = maxEffectiveDamage;
}
public int getAbsorcion() {
return absorcion;
}
public void setAbsorcion( int absorcion ) {
this.absorcion = absorcion;
}
public int getLife() {
return life < 0 ? 0 : life;
}
public void setLife( int life ) {
this.life = life;
health = life;
}
public void reduceHealth( int damage ) {
health -= damage;
}
public boolean isDead() {
return health <= 0;
}
public int getLevel() {
return level;
}
public void setLevel( int level ) {
this.level = level;
}
public boolean isActive() {
return isActive;
}
public void setActive( boolean isActive ) {
this.isActive = isActive;
}
@Override
public String toString() {
return "-- Monstruo # Datos básicos --\n" +
"Nombre: " + getName() + "\n" +
"Descripción: " + getDescription() + "\n" +
"Imagen: " + getImageNamePrefixedAndWithoutExtension() + "\n" +
"Nivel: " + getLevel() + "\n" +
"-- Monstruo # Atributos --\n" +
"\tAtaque: " + getAtaque() + "\n" +
"\tDefensa: " + getDefensa() + "\n" +
"\tDaño base: " + getDamage() + "\n" +
"\tRango de Daño: [" + getMinDamageEffective() + "," + getMaxEffectiveDamage() + "]\n" +
"\tAbsorción: " + getAbsorcion() + "\n" +
"\tVida: " + getLife() + "\n";
}
}
|
package co.com.devco.certificacion.task;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.Tasks;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.SelectFromOptions;
import java.util.List;
import java.util.Map;
import static co.com.devco.certificacion.userinterfase.InformacionHotel.BTN_BUSCAR;
import static co.com.devco.certificacion.userinterfase.InformacionHotel.BTN_CHECKIN;
import static co.com.devco.certificacion.userinterfase.InformacionHotel.BTN_FECHA;
import static co.com.devco.certificacion.userinterfase.InformaciónCrucero.BTN_HECHO;
import static co.com.devco.certificacion.userinterfase.InformaciónCrucero.SLC_DESTINO;
public class LlenarInformacionCrucero implements Task {
private List<Map<String,String>> informacion;
public LlenarInformacionCrucero(List<Map<String, String>> informacion) {
this.informacion = informacion;
}
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
SelectFromOptions.byVisibleText(informacion.get(0).get("destino")).from(SLC_DESTINO),
Click.on(BTN_CHECKIN),
BuscarFecha.deCalentario(informacion.get(0).get("fecha_inicial")),
Click.on(BTN_FECHA.of(informacion.get(0).get("fecha_final"))),
Click.on(BTN_HECHO),
Click.on(BTN_BUSCAR)
);
}
public static LlenarInformacionCrucero con(List<Map<String,String>> informacion){
return Tasks.instrumented(LlenarInformacionCrucero.class,informacion);
}
}
|
package com.involves.json;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.involves.json.JSONArray;
import com.involves.json.JSONGenerator;
import com.involves.json.JSONListObject;
import com.involves.json.JSONObject;
import com.involves.json.JSONSimpleData;
import com.involves.json.JSONListObject.JSONListObjectBuilder;
import com.involves.json.JSONObject.JSONObjectBuilder;
import com.involves.json.JSONSimpleData.JSONSimpleDataBuilder;
public class JSONGeneratorTest {
private static final String BANDS = "\"bandas\":[\"Iron Maiden\",\"Metallica\",\"Angra\"]";
private static final String CARS = "\"carros\":[{\"modelo\":\"Vectra\",\"ano\":2015,\"cor\":\"Azul\"},{\"modelo\":\"Corsa\",\"ano\":2014,\"cor\":\"Verde\"}]";
private static final String ADDRESSANDJOB = "\"endereco\":[{\"logradouro\":\"Rua joão martins de sousa\",\"numero\":480}],\"emprego\":[{\"cargo\":\"Desenvolvedor\",\"empresa\":\"involves\"}]";
private static final String BASICSDATA = "\"nome\":\"Samuel\",\"idade\":28";
private static final String COMPLETEJSON = "{".concat(BASICSDATA).concat(",").concat(ADDRESSANDJOB).concat(",")
.concat(CARS).concat(",").concat(BANDS).concat("}");
JSONGenerator generator = new JSONGenerator();
@Test
public void mustReturnJsonFormatedWithSimpleValue() {
generator.setJsonSimpleDatas(getJsonSimpleDatas());
String jsonString = generator.generatorJSON();
assertEquals("{".concat(BASICSDATA).concat("}"), jsonString);
}
@Test
public void mustReturnJsonFormatedWithObject() {
generator.setJsonObjects(getJsonObjects());
String jsonString = generator.generatorJSON();
assertEquals("{".concat(ADDRESSANDJOB).concat("}"), jsonString);
}
@Test
public void mustReturnJsonFormatedWithListObject() {
generator.setJsonListObjects(getJSONListObject());
String jsonString = generator.generatorJSON();
assertEquals("{".concat(CARS).concat("}"), jsonString);
}
@Test
public void mustReturnJsonFormatedWithListArray() {
generator.setJsonArrays(getJSONArrayObject());
String jsonString = generator.generatorJSON();
assertEquals("{".concat(BANDS).concat("}"), jsonString);
}
@Test
public void mustReturnJsonFormatedWithAllTypes() {
generator.setJsonSimpleDatas(getJsonSimpleDatas());
generator.setJsonObjects(getJsonObjects());
generator.setJsonListObjects(getJSONListObject());
generator.setJsonArrays(getJSONArrayObject());
String jsonString = generator.generatorJSON();
assertEquals(COMPLETEJSON, jsonString);
}
private List<JSONSimpleData> getJsonSimpleDatas() {
List<JSONSimpleData> jsonSimpleDatas = new ArrayList<>();
jsonSimpleDatas.add(new JSONSimpleData.JSONSimpleDataBuilder().key("nome").value("Samuel").build());
jsonSimpleDatas.add(new JSONSimpleData.JSONSimpleDataBuilder().key("idade").value(28).build());
return jsonSimpleDatas;
}
private List<JSONObject> getJsonObjects() {
List<JSONObject> jsonObjects = new ArrayList<>();
List<JSONSimpleData> addressData = new ArrayList<>();
List<JSONSimpleData> jobData = new ArrayList<>();
addressData.add(new JSONSimpleData.JSONSimpleDataBuilder().key("logradouro").value("Rua joão martins de sousa")
.build());
addressData.add(new JSONSimpleData.JSONSimpleDataBuilder().key("numero").value(480).build());
jobData.add(new JSONSimpleData.JSONSimpleDataBuilder().key("cargo").value("Desenvolvedor").build());
jobData.add(new JSONSimpleData.JSONSimpleDataBuilder().key("empresa").value("involves").build());
JSONObject address = new JSONObject.JSONObjectBuilder().key("endereco").jsonSimpleDatas(addressData).build();
JSONObject job = new JSONObject.JSONObjectBuilder().key("emprego").jsonSimpleDatas(jobData).build();
jsonObjects.add(address);
jsonObjects.add(job);
return jsonObjects;
}
private List<JSONListObject> getJSONListObject() {
List<JSONSimpleData> car1Data = new ArrayList<>();
List<JSONSimpleData> car2Data = new ArrayList<>();
car1Data.add(new JSONSimpleData.JSONSimpleDataBuilder().key("modelo").value("Vectra").build());
car1Data.add(new JSONSimpleData.JSONSimpleDataBuilder().key("ano").value(2015).build());
car1Data.add(new JSONSimpleData.JSONSimpleDataBuilder().key("cor").value("Azul").build());
car2Data.add(new JSONSimpleData.JSONSimpleDataBuilder().key("modelo").value("Corsa").build());
car2Data.add(new JSONSimpleData.JSONSimpleDataBuilder().key("ano").value(2014).build());
car2Data.add(new JSONSimpleData.JSONSimpleDataBuilder().key("cor").value("Verde").build());
JSONObject car1 = new JSONObject.JSONObjectBuilder().jsonSimpleDatas(car1Data).build();
JSONObject car2 = new JSONObject.JSONObjectBuilder().jsonSimpleDatas(car2Data).build();
List<JSONObject> jsonObjects = new ArrayList<>();
jsonObjects.add(car1);
jsonObjects.add(car2);
List<JSONListObject> jsonListObjects = new ArrayList<>();
jsonListObjects.add(new JSONListObject.JSONListObjectBuilder().key("carros").jsonObjects(jsonObjects).build());
return jsonListObjects;
}
private List<JSONArray> getJSONArrayObject() {
JSONArray jsonArray = new JSONArray("bandas");
jsonArray.add("Iron Maiden");
jsonArray.add("Metallica");
jsonArray.add("Angra");
List<JSONArray> jsonArrays = new ArrayList<>();
jsonArrays.add(jsonArray);
return jsonArrays;
}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int x = scan.nextInt();
int dx = x;
int y = scan.nextInt();
int i = 1;
int f = 1;
for (f = 1; f <= y / x; f++) {
for (i = i; i < dx; i++) {
System.out.printf( "%d ", i);
}
System.out.println(i);
i = i+1;
dx += x;
}
}
}
|
package jp.mironal.java.aws.app.glacier;
/**
* @author mironal
*/
public class AwsTools {
/**
* AWSの種類を定義する列挙体.<br>
* サービス接続に使うURLの作成に使用する.
*/
// @formatter:off
public enum AwsService {
Glacier,
Sqs,
Sns,
}
// @formatter:on
protected static final String HTTPS = "https://";
protected static final String URL_TAIL = ".amazonaws.com";
/**
* AWSのリージョンを定義する列挙体.<br>
* サービス接続に使うURLの作成に使用する.
*/
// @formatter:off
public enum Region {
/**
* US East (Northern Virginia) Region
*/
US_EAST_1("us-east-1"),
/**
* US West (Northern California) Region
*/
US_WEST_1("us-west-1"),
/**
* US West (Oregon) Region
*/
US_WEST_2("us-west-2"),
/**
* EU (Ireland) Region
*/
EU_WEST_1("eu-west-1"),
/**
* Asia Pacific (Tokyo) Region
*/
AP_NORTHEAST_1("ap-northeast-1"),
;
//リージョンを識別するURLの部分.
private final String endpoint;
private Region(String endpoint) {
this.endpoint = endpoint;
}
public String getEndpoint() {
return this.endpoint;
}
}
// @formatter:on
public static final String AWS_PROPERTIES_FILENAME = "AwsCredentials.properties";
/**
* 指定されたサービスとリージョンから接続用URLを生成する.
*
* @param service AWSの種類
* @param region リージョン
* @return URLを示す文字列.
*/
public static String makeUrl(AwsService service, Region region) {
if (service == null) {
throw new NullPointerException("service is null.");
}
if (region == null) {
throw new NullPointerException("region is null.");
}
return HTTPS + service.toString().toLowerCase() + "." + region.getEndpoint() + URL_TAIL;
}
}
|
package com.github.emailtohl.integration.core.role;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.junit.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import com.github.emailtohl.integration.core.config.CorePresetData;
import com.github.emailtohl.integration.core.coreTestConfig.CoreTestEnvironment;
import com.github.emailtohl.lib.jpa.Paging;
import com.google.gson.Gson;
/**
* 业务类测试
* @author HeLei
*/
public class RoleServiceImplTest extends CoreTestEnvironment {
@Inject
RoleService roleService;
@Inject
Gson gson;
@Inject
CorePresetData cpd;
@Test
public void testCRUD() {
Role r = new Role("test_role", RoleType.EMPLOYEE, "for test");
r.getAuthorities().addAll(Arrays.asList(
new Authority("not exist", "不存在的权限", null),
cpd.auth_customer_lock, cpd.auth_customer_reset_password
));
r = roleService.create(r);
Long id = r.getId();
r = roleService.get(id);
assertEquals(2, r.getAuthorities().size());
r = roleService.get("test_role");
assertNotNull(r);
r.getAuthorities().remove(cpd.auth_customer_lock);
r.getAuthorities().add(cpd.auth_customer_level);
r.getAuthorities().add(cpd.auth_employee_role);
r.setDescription("for update");
roleService.update(id, r);
r = roleService.get(id);
assertEquals("for update", r.getDescription());
assertEquals(3, r.getAuthorities().size());
roleService.delete(id);
r = roleService.get(id);
assertNull(r);
}
@Test
public void testExist() {
boolean b = roleService.exist(cpd.role_guest.getName());
assertTrue(b);
b = roleService.exist("foo");
assertFalse(b);
}
@Test
public void testQueryRolePageable() {
Pageable pageable = PageRequest.of(0, 20);
Paging<Role> p = roleService.query(null, pageable);
assertFalse(p.getContent().isEmpty());
Role param = new Role(cpd.role_manager.getName(), cpd.role_manager.getRoleType(), cpd.role_manager.getDescription());
p = roleService.query(param, pageable);
assertFalse(p.getContent().isEmpty());
System.out.println(gson.toJson(p));
}
@Test
public void testQueryRole() {
List<Role> ls = roleService.query(null);
assertFalse(ls.isEmpty());
Role param = new Role(cpd.role_staff.getName(), cpd.role_staff.getRoleType(), cpd.role_staff.getDescription());
ls = roleService.query(param);
assertFalse(ls.isEmpty());
System.out.println(gson.toJson(ls));
}
@Test
public void testGetAuthorities() {
List<Authority> ls = roleService.getAuthorities();
assertFalse(ls.isEmpty());
System.out.println(gson.toJson(ls));
}
}
|
package com.ease.azeroth.security.service;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;
/**
* Created by fumanix on 2/25/16.
*/
@Service("systemAuthorizingRealm")
public class SystemAuthorizingRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return null;
}
}
|
package java04;
import java.util.Scanner;
public class java0406 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
System.out.println("Input char:");
char str = scn.next().charAt(0);
if (65 <= (int) str && (int) str <= 90) {
System.out.println("Upper case");
} else if (97 <= (int) str && (int) str <= 122) {
System.out.println("Lower case");
} else {
System.out.println("Other characters");
}
}
}
|
package com.weida.easycollege.security;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* springmvc 初始化类 AbstractAnnotationConfigDispatcherServletInitializer 是所有 WebApplicationInitializer 实现的基类。
*/
public class SecurityWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SecurityConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[] { SpringBootConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
|
package com.ibrahim.androidTask;
import android.content.Context;
import android.content.res.Configuration;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;
/**
* Created by ibrahim on 19/03/2018.
*/
public class AppController extends MultiDexApplication {
private static AppController mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public static AppController getContext() {
return mContext;
} // fun of getContext
}
|
package com.pacodam.springhbtutorial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringHbTutorialApplication {
public static void main(String[] args) {
System.out.println("hola");
SpringApplication.run(SpringHbTutorialApplication.class, args);
}
}
|
package com.bingo.code.example.design.command.cancel;
/**
* �����࣬����ʵ�ּӼ�������
*/
public class Operation implements OperationApi{
/**
* ��¼����Ľ��
*/
private int result;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public void add(int num){
//ʵ�ּӷ�����
result += num;
}
public void substract(int num){
//ʵ�ּ�������
result -= num;
}
}
|
package com.ifre.form.api;
import java.util.List;
/**
* 模型所有属性集合
*
* @author CaiPeng
*
*/
public class Model {
/** 模型名称,暂时不使用 **/
private String modelName;
private String prodId;
/** 模型类型,暂时不使用 **/
private String modelType;
// 模型属性及模型变量集合
private List<ModelElement> modelElement;
private ModelResultWy modelResultWy;
// 模型约束暂时不考虑,后台进行约束,前台直接展示
private ModelResultWyConstraintTruncation constraintTruncation;
// 模型结果枚举,相互约束校验暂时不考虑,优先使用min为准
private List<ModelResultWyEnumerationItem> enumerationItem;
public String getProdId() {
return prodId;
}
public void setProdId(String prodId) {
this.prodId = prodId;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public String getModelType() {
return modelType;
}
public void setModelType(String modelType) {
this.modelType = modelType;
}
public List<ModelElement> getModelElement() {
return modelElement;
}
public void setModelElement(List<ModelElement> modelElement) {
this.modelElement = modelElement;
}
public ModelResultWy getModelResultWy() {
return modelResultWy;
}
public void setModelResultWy(ModelResultWy modelResultWy) {
this.modelResultWy = modelResultWy;
}
public ModelResultWyConstraintTruncation getConstraintTruncation() {
return constraintTruncation;
}
public void setConstraintTruncation(ModelResultWyConstraintTruncation constraintTruncation) {
this.constraintTruncation = constraintTruncation;
}
public List<ModelResultWyEnumerationItem> getEnumerationItem() {
return enumerationItem;
}
public void setEnumerationItem(List<ModelResultWyEnumerationItem> enumerationItem) {
// 添加升序排序功能,展示更方便,边界值以排序值为准
int num = enumerationItem.size();
double tempMinScore;
ModelResultWyEnumerationItem temp;
for (int i = 0; i < num; i++) {
tempMinScore = enumerationItem.get(i).getMinScore();
for (int j = i + 1; j < num; j++) {
if (enumerationItem.get(j).getMinScore() < tempMinScore) {
tempMinScore = enumerationItem.get(j).getMinScore();
temp = enumerationItem.get(j);
enumerationItem.set(j, enumerationItem.get(i));
enumerationItem.set(i, temp);
}
}
}
this.enumerationItem = enumerationItem;
}
@Override
public String toString() {
return "Model [modelName=" + modelName + ", prodId=" + prodId + ", modelType=" + modelType + ", modelElement="
+ modelElement + ", modelResultWy=" + modelResultWy + ", constraintTruncation=" + constraintTruncation
+ ", enumerationItem=" + enumerationItem + "]";
}
}
|
/*
* 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 fetchfinance1;
import java.awt.Color;
import static java.lang.Double.parseDouble;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Kat
*/
public class financeJFrame extends javax.swing.JInternalFrame {
// Connection con = null;
// PreparedStatement pst = null;
// ResultSet rs = null;
/**
* Creates new form financeJFrame
*/
public financeJFrame() {
initComponents();
showJournals();
showInvoice();
}
// function to connect to mysql database
public ArrayList<journalModel> listJournals()
{
ArrayList<journalModel> journalList = new ArrayList<journalModel>();
Statement st = null;
ResultSet rs = null;
Connection con = null;
try{
con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
st = con.createStatement();
String query = "SELECT * FROM financedb.journal";
rs = st.executeQuery(query);
journalModel journal;
while(rs.next())
{
journal = new journalModel(rs.getInt("entryId"),(rs.getDate("entryDate")),rs.getString("entryType"),rs.getString("entryStmt"));
journalList.add(journal);
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { st.close(); } catch (Exception e) { /* ignored */ }
try { con.close(); } catch (Exception e) { /* ignored */ }
}
return journalList;
}
public void showJournals()
{
ArrayList<journalModel> journals = listJournals();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"Entry ID","Entry Date","Entry Type"});
Object[] row = new Object[3];
for(int i = 0; i < journals.size(); i++)
{
row[0] = journals.get(i).getEntryId();
row[1] = journals.get(i).getEntryDate();
row[2] = journals.get(i).getEntryType();
model.addRow(row);
}
jTable2.setModel(model);
}
public ArrayList<invoiceModel> listInvoice()
{
ArrayList<invoiceModel> invoiceList = new ArrayList<invoiceModel>();
Statement st = null;
ResultSet rs = null;
Connection con = null;
try{
con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
st = con.createStatement();
String query = "SELECT * FROM financedb.invoice";
rs = st.executeQuery(query);
invoiceModel invoice;
while(rs.next())
{
invoice = new invoiceModel(rs.getInt("invoiceId"),(rs.getDate("invoiceDate")),rs.getString("invoiceType"),rs.getDouble("invoiceTotal"),rs.getString("invoiceSource"),rs.getString("invoiceTags"));
invoiceList.add(invoice);
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { st.close(); } catch (Exception e) { /* ignored */ }
try { con.close(); } catch (Exception e) { /* ignored */ }
}
return invoiceList;
}
public void showInvoice()
{
DecimalFormat twoDigits = new DecimalFormat("$#,###.00");
ArrayList<invoiceModel> invoice = listInvoice();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"Invoice ID","Invoice Date","Invoice Type", "Invoice Total","Invoice Source","Invoice Tags"});
Object[] row = new Object[6];
for(int i = 0; i < invoice.size(); i++)
{
row[0] = invoice.get(i).getInvoiceId();
row[1] = invoice.get(i).getInvoiceDate();
row[2] = invoice.get(i).getInvoiceType();
row[3] = twoDigits.format(invoice.get(i).getInvoiceTotal());
row[4] = invoice.get(i).getInvoiceSource();
row[5] = invoice.get(i).getInvoiceTags();
model.addRow(row);
}
jTable1.setModel(model);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
menuBar1 = new java.awt.MenuBar();
menu1 = new java.awt.Menu();
menu2 = new java.awt.Menu();
menuBar2 = new java.awt.MenuBar();
menu3 = new java.awt.Menu();
menu4 = new java.awt.Menu();
jMenu3 = new javax.swing.JMenu();
buttonGroup1 = new javax.swing.ButtonGroup();
menuBar3 = new java.awt.MenuBar();
menu5 = new java.awt.Menu();
menu6 = new java.awt.Menu();
jFrame1 = new javax.swing.JFrame();
jFrame2 = new javax.swing.JFrame();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
label1 = new java.awt.Label();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
label2 = new java.awt.Label();
sortChoice1 = new java.awt.Choice();
sortChoice1.add("Date");
sortChoice1.add("Type");
sortChoice1.add("Total");
label3 = new java.awt.Label();
label4 = new java.awt.Label();
yearChoice1 = new java.awt.Choice();
yearChoice1.add("2015");
yearChoice1.add("2016");
yearChoice1.add("2017");
yearChoice1.add("2018");
label5 = new java.awt.Label();
jSeparator1 = new javax.swing.JSeparator();
label6 = new java.awt.Label();
label7 = new java.awt.Label();
label8 = new java.awt.Label();
jSeparator2 = new javax.swing.JSeparator();
checkbox1 = new java.awt.Checkbox();
checkbox2 = new java.awt.Checkbox();
checkbox3 = new java.awt.Checkbox();
checkbox4 = new java.awt.Checkbox();
checkbox5 = new java.awt.Checkbox();
apButton = new java.awt.Button();
apEndDate = new org.jdesktop.swingx.JXDatePicker();
apStartDate = new org.jdesktop.swingx.JXDatePicker();
jPanel2 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
sortChoice2 = new java.awt.Choice();
sortChoice2.add("Date");
sortChoice2.add("Type");
sortChoice2.add("Total");
jLabel10 = new javax.swing.JLabel();
choice4 = new java.awt.Choice();
choice4.add("2015");
choice4.add("2016");
choice4.add("2017");
choice4.add("2018");
jLabel11 = new javax.swing.JLabel();
jSeparator3 = new javax.swing.JSeparator();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jSeparator4 = new javax.swing.JSeparator();
checkbox6 = new java.awt.Checkbox();
checkbox7 = new java.awt.Checkbox();
checkbox8 = new java.awt.Checkbox();
checkbox9 = new java.awt.Checkbox();
arButton = new java.awt.Button();
arEndDate = new org.jdesktop.swingx.JXDatePicker();
arStartDate = new org.jdesktop.swingx.JXDatePicker();
jPanel3 = new javax.swing.JPanel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
sortChoice3 = new java.awt.Choice();
sortChoice3.add("Date");
sortChoice3.add("Type");
sortChoice3.add("Amount Ascending");
sortChoice3.add("Amount Descending");
yearChoice3 = new java.awt.Choice();
yearChoice3.add("2015");
yearChoice3.add("2016");
yearChoice3.add("2017");
yearChoice3.add("2018");
jLabel18 = new javax.swing.JLabel();
jSeparator5 = new javax.swing.JSeparator();
jLabel19 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
button2 = new java.awt.Button();
jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker();
jXDatePicker2 = new org.jdesktop.swingx.JXDatePicker();
jPanel4 = new javax.swing.JPanel();
jLabel21 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
button3 = new java.awt.Button();
button5 = new java.awt.Button();
panel1 = new java.awt.Panel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
choice1 = new java.awt.Choice();
invTypeChoice = new java.awt.Choice();
invTypeChoice.add("Credit");
invTypeChoice.add("Debit");
jLabel4 = new javax.swing.JLabel();
choice3 = new java.awt.Choice();
invSourceChoice = new java.awt.Choice();
invSourceChoice.removeAll();
invSourceChoice.add("Sale");
invSourceChoice.add("Endoresment");
invSourceChoice.add("Grant");
invSourceChoice.add("Payment/Royalty");
label9 = new java.awt.Label();
label11 = new java.awt.Label();
jLabel5 = new javax.swing.JLabel();
invTagTextField = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
invAmntTextField = new javax.swing.JTextField();
madeInvoiceLabel = new javax.swing.JLabel();
invDate = new org.jdesktop.swingx.JXDatePicker();
panel2 = new java.awt.Panel();
jLabel6 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
menu1.setLabel("File");
menuBar1.add(menu1);
menu2.setLabel("Edit");
menuBar1.add(menu2);
menu3.setLabel("File");
menuBar2.add(menu3);
menu4.setLabel("Edit");
menuBar2.add(menu4);
jMenu3.setText("jMenu3");
menu5.setLabel("File");
menuBar3.add(menu5);
menu6.setLabel("Edit");
menuBar3.add(menu6);
jFrame1.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jFrame1.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
jFrame2.getContentPane().setLayout(jFrame2Layout);
jFrame2Layout.setHorizontalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame2Layout.setVerticalGroup(
jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
label1.setBackground(new java.awt.Color(255, 255, 255));
label1.setFont(new java.awt.Font("Arial Black", 0, 36)); // NOI18N
label1.setText("Fetch Reports");
jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
label2.setFont(new java.awt.Font("Arial", 2, 14)); // NOI18N
label2.setText("Generate an accoutns payable report");
label3.setText("Sort By");
label4.setText("Fiscal Year");
yearChoice1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
yearChoice1ItemStateChanged(evt);
}
});
label5.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
label5.setText("Dates");
jSeparator1.setForeground(new java.awt.Color(167, 213, 39));
label6.setText("Start Date: ");
label7.setText("End Date: ");
label8.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
label8.setText("Filters");
jSeparator2.setForeground(new java.awt.Color(167, 213, 39));
checkbox1.setLabel("Payroll");
checkbox1.setState(true);
checkbox2.setLabel("Products");
checkbox2.setState(true);
checkbox3.setLabel("Utitlities");
checkbox3.setState(true);
checkbox4.setLabel("Services");
checkbox4.setState(true);
checkbox5.setLabel("Other");
checkbox5.setState(true);
apButton.setLabel("Generate Report");
apButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
apButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(sortChoice1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)))
.addComponent(yearChoice1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(102, 102, 102)
.addComponent(checkbox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(52, 52, 52)
.addComponent(checkbox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(checkbox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addComponent(checkbox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addComponent(checkbox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(314, 314, 314)
.addComponent(apButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(138, 138, 138)
.addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(apEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 117, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(yearChoice1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(sortChoice1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(51, 51, 51)
.addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(apStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(apEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkbox3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkbox1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkbox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkbox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(checkbox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
.addComponent(apButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jTabbedPane1.addTab("Accounts Payable", jPanel1);
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel8.setFont(new java.awt.Font("Arial", 2, 14)); // NOI18N
jLabel8.setText("Generate an accounts receivable report ");
jLabel9.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel9.setText("Sort By: ");
jLabel10.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel10.setText("Fiscal year");
choice4.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
choice4ItemStateChanged(evt);
}
});
choice4.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
choice4FocusLost(evt);
}
});
jLabel11.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel11.setText("Dates");
jSeparator3.setForeground(new java.awt.Color(167, 213, 39));
jLabel12.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel12.setText("Start Date:");
jLabel13.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel13.setText("End Date: ");
jLabel14.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel14.setText("Filters");
jSeparator4.setForeground(new java.awt.Color(167, 213, 39));
checkbox6.setLabel("Sales");
checkbox6.setName("Sales"); // NOI18N
checkbox6.setState(true);
checkbox7.setLabel("Endorsements");
checkbox7.setState(true);
checkbox8.setLabel("Grants");
checkbox8.setState(true);
checkbox9.setLabel("Payments/Royalties");
checkbox9.setState(true);
arButton.setLabel("Generate Report");
arButton.setName(""); // NOI18N
arButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
arButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator3)
.addComponent(jSeparator4)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(jLabel9)
.addGap(1, 1, 1)
.addComponent(sortChoice2, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(76, 76, 76)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(choice4, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(arStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(167, 167, 167)
.addComponent(jLabel13)
.addGap(18, 18, 18)
.addComponent(arEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel14))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel11))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(109, 109, 109)
.addComponent(checkbox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(82, 82, 82)
.addComponent(checkbox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addComponent(checkbox8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(77, 77, 77)
.addComponent(checkbox9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(298, 298, 298)
.addComponent(arButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(85, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel8)
.addGap(50, 50, 50)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(sortChoice2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(choice4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)))
.addGap(46, 46, 46)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(21, 21, 21)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(arStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(arEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(78, 78, 78)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(54, 54, 54)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkbox8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkbox7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkbox9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkbox6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
.addComponent(arButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jTabbedPane1.addTab("Accounts Receiveable", jPanel2);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel15.setFont(new java.awt.Font("Arial", 2, 14)); // NOI18N
jLabel15.setText("Generate a general ledger with details of the account journal");
jLabel16.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel16.setText("Sort By: ");
jLabel17.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel17.setText("Fiscal Year: ");
yearChoice3.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
yearChoice3ItemStateChanged(evt);
}
});
jLabel18.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel18.setText("Date");
jSeparator5.setForeground(new java.awt.Color(167, 213, 39));
jLabel19.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel19.setText("Start Date:");
jLabel19.setToolTipText("");
jLabel20.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel20.setText("End Date:");
button2.setLabel("Generate Ledger");
button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel15)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sortChoice3, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 73, Short.MAX_VALUE)
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(yearChoice3, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(214, 214, 214))))
.addComponent(jSeparator5)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(64, 64, 64)
.addComponent(jLabel19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jXDatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel20)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jXDatePicker2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(197, 197, 197))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel18))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(287, 287, 287)
.addComponent(button2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(jLabel15)
.addGap(45, 45, 45)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel16))
.addComponent(jLabel17))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(yearChoice3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3))
.addComponent(sortChoice3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(70, 70, 70)
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(60, 60, 60)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(jLabel20)
.addComponent(jXDatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jXDatePicker2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 120, Short.MAX_VALUE)
.addComponent(button2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(56, 56, 56))
);
jTabbedPane1.addTab("General Ledger", jPanel3);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jLabel21.setFont(new java.awt.Font("Arial", 2, 14)); // NOI18N
jLabel21.setText("View and edit journal entries");
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"EntryId", "Date", "Entry Type"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable2.setColumnSelectionAllowed(true);
jScrollPane2.setViewportView(jTable2);
jTable2.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (jTable2.getColumnModel().getColumnCount() > 0) {
jTable2.getColumnModel().getColumn(1).setResizable(false);
jTable2.getColumnModel().getColumn(2).setResizable(false);
}
button3.setLabel("Delete");
button3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button3ActionPerformed(evt);
}
});
button5.setLabel("Open");
button5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button5ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel21))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(306, 306, 306)
.addComponent(button5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)
.addComponent(button3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 627, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(96, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel21)
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(button3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49))
);
jTabbedPane1.addTab("Journals", jPanel4);
panel1.setFont(new java.awt.Font("Arial", 2, 14)); // NOI18N
jLabel1.setFont(new java.awt.Font("Arial", 2, 18)); // NOI18N
jLabel1.setText("Manually create invoices");
jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel2.setText("Invoice Date :");
jButton1.setText("Create Invoice");
jButton1.setToolTipText("");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Clear");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel3.setText("Invoice Type:");
invTypeChoice.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
invTypeChoiceItemStateChanged(evt);
}
});
jLabel4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel4.setText("Invoice Source ");
label9.setText("label9");
label11.setText("label11");
jLabel5.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel5.setText("Tags :");
invTagTextField.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
invTagTextField.setToolTipText("Seperate tags by ,");
jLabel7.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel7.setText("Invoice Amount: $");
invAmntTextField.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
invAmntTextField.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
invAmntTextFieldFocusLost(evt);
}
});
invAmntTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invAmntTextFieldActionPerformed(evt);
}
});
madeInvoiceLabel.setFont(new java.awt.Font("Arial", 2, 14)); // NOI18N
madeInvoiceLabel.setForeground(new java.awt.Color(0, 153, 0));
madeInvoiceLabel.setToolTipText("");
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(268, 268, 268)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2))
.addGroup(panel1Layout.createSequentialGroup()
.addGap(204, 204, 204)
.addComponent(madeInvoiceLabel))
.addGroup(panel1Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(invTypeChoice, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel1Layout.createSequentialGroup()
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(invTagTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(invSourceChoice, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(79, 79, 79)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(invAmntTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(invDate, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(invTypeChoice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel4)
.addComponent(invSourceChoice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(invAmntTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(85, 85, 85)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invTagTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jLabel2)
.addComponent(invDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addComponent(madeInvoiceLabel)
.addGap(26, 26, 26)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1))
.addGap(65, 65, 65))
);
jTabbedPane1.addTab("Create Invoice", panel1);
jLabel6.setFont(new java.awt.Font("Arial", 2, 18)); // NOI18N
jLabel6.setText("Invoices");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"01/15/2016", "Debit", "$255.50", "Payroll", null},
{"05/25/2016", "Credit", "$65.00", "Sale", "UNPAID"},
{"03/26/2017", "Credit", "$170.00", "Endorsement", null},
{"11/07/2017", "Debit", "$500.00", "Service", null}
},
new String [] {
"Date", "Invoice Type", "Invoice Total", "Invoice Source", "Tags"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout panel2Layout = new javax.swing.GroupLayout(panel2);
panel2.setLayout(panel2Layout);
panel2Layout.setHorizontalGroup(
panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel2Layout.createSequentialGroup()
.addGroup(panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel2Layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 564, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel2Layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(150, Short.MAX_VALUE))
);
panel2Layout.setVerticalGroup(
panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel2Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jLabel6)
.addGap(37, 37, 37)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(147, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Invoices", panel2);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 533, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void invTypeChoiceItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_invTypeChoiceItemStateChanged
// TODO add your handling code here:
String invType = (String) invTypeChoice.getSelectedItem();
if(invType.equals(invTypeChoice.getItem(0))){
invSourceChoice.removeAll();
invSourceChoice.add("Sale");
invSourceChoice.add("Endoresment");
invSourceChoice.add("Grant");
invSourceChoice.add("Payment/Royalty");
}else{
invSourceChoice.removeAll();
invSourceChoice.add("Payroll");
invSourceChoice.add("Products");
invSourceChoice.add("Utilities");
invSourceChoice.add("Services");
invSourceChoice.add("Other");
}
}//GEN-LAST:event_invTypeChoiceItemStateChanged
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
DecimalFormat twoDigits = new DecimalFormat("$#,###.00");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
double total;
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Connection con = null;
PreparedStatement pst = null;
total = parseDouble(invAmntTextField.getText());
try{
con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
String stmt;
Date date = invDate.getDate();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
stmt = "INSERT INTO financedb.invoice (invoiceDate,invoiceType,invoiceTotal,invoiceSource,invoiceTags) VALUES (?,?,?,?,?);" ;
pst = con.prepareStatement(stmt);
pst.setDate(1, sqlDate);
pst.setString(2,invTypeChoice.getSelectedItem());
pst.setDouble(3,total);
pst.setString(4,invSourceChoice.getSelectedItem());
pst.setString(5,invTagTextField.getText());
pst.executeUpdate();
showInvoice();
invAmntTextField.setText("");
invTagTextField.setText("");
JOptionPane.showMessageDialog(null, "The invoice has been successfully created");
madeInvoiceLabel.setText("");
}catch(Exception ex){
madeInvoiceLabel.setText("An error has occured");
System.out.println(ex.getMessage());
}finally{
try { pst.close(); } catch (Exception e) { /* ignored */ }
try { con.close(); } catch (Exception e) { /* ignored */ }
}
}//GEN-LAST:event_jButton1ActionPerformed
private void invAmntTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_invAmntTextFieldFocusLost
// TODO add your handling code here:
try{
Double invAmnt = Double.parseDouble(invAmntTextField.getText());
invAmntTextField.setBackground(Color.white);
}catch(Exception e){
e.printStackTrace();
invAmntTextField.setBackground(Color.red);
System.out.println(e.getMessage());
}
}//GEN-LAST:event_invAmntTextFieldFocusLost
private void invAmntTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invAmntTextFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_invAmntTextFieldActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
invAmntTextField.setText("");
invTagTextField.setText("");
madeInvoiceLabel.setText("");
}//GEN-LAST:event_jButton2ActionPerformed
private void apButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_apButtonActionPerformed
// java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
// DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
// DefaultTableModel model2 = (DefaultTableModel)jTable2.getModel();
//
// Connection con = null;
//
// try{
// Date start = formatter.parse(formatter.format(arStartDate.getDate()));
// Date end = formatter.parse(formatter.format(arEndDate.getDate()));
// java.sql.Date sqlStart = new java.sql.Date(start.getTime());
// java.sql.Date sqlEnd = new java.sql.Date(end.getTime());
// con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
// String stmt;
// String search = "SELECT * FROM financedb.invoice WHERE (";
// String sortBy ;
//
// if(checkbox1.getState()){
// search = search.concat(" invoiceSource = 'Payroll' ");
// }
// if(checkbox2.getState()){
// search = search.concat("OR invoiceSource = 'Products' ");
// }
// if(checkbox3.getState()){
// search = search.concat("OR invoiceSource = 'Utilities' ");
// }
// if(checkbox4.getState()){
// search = search.concat("OR invoiceSource = 'Services' ");
// }
// if(checkbox5.getState()){
// search = search.concat("OR invoiceSource = 'Other' ");
// }
//
// search = search.concat(") AND ");
//
// search = search.concat(" invoiceDate >= '" + sqlStart +"' AND invoiceDate <= '" + sqlEnd +"'");
//
// switch (sortChoice2.getSelectedIndex()) {
// case 0:
// sortBy = "invoiceDate;";
// break;
// case 1:
// sortBy = "invoiceType;";
// break;
// default:
// sortBy = "invoiceTotal;";
// break;
// }
//
// search = search.concat(" ORDER BY " + sortBy);
//
//
//
// stmt = "INSERT INTO financedb.journal (entryDate,entryType,entryStmt) VALUES (?,?,?);" ;
// pst = con.prepareStatement(stmt);
//
// pst.setDate(1, date);
// pst.setString(2,"Accounts Payable");
// pst.setString(3,search);
// pst.executeUpdate();
//
//
//
//
// showJournals();
//
//
// JOptionPane.showMessageDialog(null, "The journal entry has been created.");
// DefaultTableModel model2 = (DefaultTableModel)jTable2.getModel();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Connection con = null;
PreparedStatement pst = null;
String stmt;
try{
Date start = formatter.parse(formatter.format(arStartDate.getDate()));
Date end = formatter.parse(formatter.format(arEndDate.getDate()));
java.sql.Date sqlStart = new java.sql.Date(start.getTime());
java.sql.Date sqlEnd = new java.sql.Date(end.getTime());
con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
String search = "SELECT * FROM financedb.invoice WHERE (";
String sortBy ;
if(checkbox1.getState()){
search = search.concat(" invoiceSource = 'Payroll' ");
}
if(checkbox2.getState()){
search = search.concat("OR invoiceSource = 'Products' ");
}
if(checkbox3.getState()){
search = search.concat("OR invoiceSource = 'Utilites' ");
}
if(checkbox4.getState()){
search = search.concat("OR invoiceSource = 'Services' ");
}
if(checkbox5.getState()){
search = search.concat("OR invoiceSource = 'Other' ");
}
search = search.concat(") AND ");
search = search.concat(" invoiceDate >= '" + sqlStart +"' AND invoiceDate <= '" + sqlEnd +"'");
switch (sortChoice1.getSelectedIndex()) {
case 0:
sortBy = "'invoiceDate';";
break;
case 1:
sortBy = "invoiceType';";
break;
default:
sortBy = "invoiceTotal;";
break;
}
search = search.concat(" ORDER BY " + sortBy);
stmt = "INSERT INTO financedb.journal (entryDate,entryType,entryStmt) VALUES (?,?,?);" ;
pst = con.prepareStatement(stmt);
pst.setDate(1, date);
pst.setString(2,"Accounts Payable");
pst.setString(3,search);
pst.executeUpdate();
showJournals();
JOptionPane.showMessageDialog(null, "The journal entry has been created.");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error has occured. Unable to generate report.");
System.out.println(e.getMessage());
}finally {
try { pst.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); }
try { con.close(); } catch (Exception ex1) { System.out.println(ex1.getMessage()); }
}
//WHERE CONCAT(`invoiceId`, `fname`, `lname`, `age`) LIKE '%"+tags+"%'"
//model.addRow(Object[] date,'Credit');
}//GEN-LAST:event_apButtonActionPerformed
private void arButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_arButtonActionPerformed
DefaultTableModel model2 = (DefaultTableModel)jTable2.getModel();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
// Date myDate = format.parse(date);
// java.sql.Date sqlDate = new java.sql.Date(myDate);
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
Date start = formatter.parse(formatter.format(arStartDate.getDate()));
Date end = formatter.parse(formatter.format(arEndDate.getDate()));
java.sql.Date sqlStart = new java.sql.Date(start.getTime());
java.sql.Date sqlEnd = new java.sql.Date(end.getTime());
con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
String stmt;
String search = "SELECT * FROM financedb.invoice WHERE (";
String sortBy ;
if(checkbox6.getState()){
search = search.concat(" invoiceSource = 'Sale' ");
}
if(checkbox7.getState()){
search = search.concat("OR invoiceSource = 'Endorsement' ");
}
if(checkbox8.getState()){
search = search.concat("OR invoiceSource = 'Grant' ");
}
if(checkbox9.getState()){
search = search.concat("OR invoiceSource = 'Payment/Royalty' ");
}
search = search.concat(") AND ");
search = search.concat(" invoiceDate >= '" + sqlStart +"' AND invoiceDate <= '" + sqlEnd +"'");
switch (sortChoice2.getSelectedIndex()) {
case 0:
sortBy = "invoiceDate;";
break;
case 1:
sortBy = "invoiceType;";
break;
default:
sortBy = "invoiceTotal;";
break;
}
search = search.concat(" ORDER BY " + sortBy);
stmt = "INSERT INTO financedb.journal (entryDate,entryType,entryStmt) VALUES (?,?,?);" ;
pst = con.prepareStatement(stmt);
pst.setDate(1, date);
pst.setString(2,"Accounts Receivable");
pst.setString(3,search);
pst.executeUpdate();
showJournals();
JOptionPane.showMessageDialog(null, "The journal entry has been created.");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error has occured. Unable to generate report.");
System.out.println(e.getMessage());
}finally {
try { pst.close(); } catch (Exception e) { /* ignored */ }
try { con.close(); } catch (Exception e) { /* ignored */ }
}
}//GEN-LAST:event_arButtonActionPerformed
private void button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button2ActionPerformed
DefaultTableModel model2 = (DefaultTableModel)jTable2.getModel();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Connection con = null;
ResultSet rs = null;
PreparedStatement pst1 = null;
try{
Date start = formatter.parse(formatter.format(arStartDate.getDate()));
Date end = formatter.parse(formatter.format(arEndDate.getDate()));
java.sql.Date sqlStart = new java.sql.Date(start.getTime());
java.sql.Date sqlEnd = new java.sql.Date(end.getTime());
con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
String stmt;
Statement st1 = null;
String search = "SELECT * FROM financedb.invoice WHERE (";
String sortBy ;
search = search.concat(" invoiceDate >= '" + sqlStart +"' AND invoiceDate <= '" + sqlEnd +"'");
switch (sortChoice2.getSelectedIndex()) {
case 0:
sortBy = "invoiceDate;";
break;
case 1:
sortBy = "invoiceType;";
break;
default:
sortBy = "invoiceTotal;";
break;
}
search = search.concat(" ORDER BY " + sortBy);
stmt = "INSERT INTO financedb.journal (entryDate,entryType,entryStmt) VALUES (?,?,?);" ;
pst1 = con.prepareStatement(stmt);
pst1.setDate(1, date);
pst1.setString(2,"General Ledger");
pst1.setString(3,search);
pst1.executeUpdate();
showJournals();
JOptionPane.showMessageDialog(null, "The journal entry has been created.");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error has occured. Unable to generate report.");
System.out.println(e.getMessage());
}finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { pst1.close(); } catch (Exception e) { /* ignored */ }
try { con.close(); } catch (Exception e) { /* ignored */ }
}//GEN-LAST:event_button2ActionPerformed
}
private void button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button3ActionPerformed
//JOURNAL DELETE BUTTON
DefaultTableModel model2 = (DefaultTableModel)jTable2.getModel();
int selected = jTable2.getSelectedRow();
if(jTable2.getSelectedRowCount()>0){
model2.removeRow(selected);
}
}//GEN-LAST:event_button3ActionPerformed
private void yearChoice1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_yearChoice1ItemStateChanged
// TODO add your handling code here:
String stDate,endDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
stDate = (yearChoice1.getSelectedItem() + "-01-01");
endDate = (yearChoice1.getSelectedItem() + "-12-31");
try{
apStartDate.setDate(formatter.parse(stDate));
apEndDate.setDate(formatter.parse(endDate));
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error has occured. Unable to generate report.");
System.out.println(e.getMessage());
}
}//GEN-LAST:event_yearChoice1ItemStateChanged
private void choice4ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_choice4ItemStateChanged
// TODO add your handling code here:
String stDate,endDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
stDate = (choice4.getSelectedItem() + "-01-01");
endDate = (choice4.getSelectedItem() + "-12-31");
try{
arStartDate.setDate(formatter.parse(stDate));
arEndDate.setDate(formatter.parse(endDate));
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error has occured. Unable to generate report.");
System.out.println(e.getMessage());
}
}//GEN-LAST:event_choice4ItemStateChanged
private void choice4FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_choice4FocusLost
// TODO add your handling code here:
String stDate,endDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
stDate = (choice4.getSelectedItem() + "-01-01");
endDate = (choice4.getSelectedItem() + "-12-31");
try{
arStartDate.setDate(formatter.parse(stDate));
arEndDate.setDate(formatter.parse(endDate));
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error has occured. Unable to generate report.");
System.out.println(e.getMessage());
}
}//GEN-LAST:event_choice4FocusLost
private void yearChoice3ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_yearChoice3ItemStateChanged
// TODO add your handling code here:
String stDate,endDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
stDate = (yearChoice3.getSelectedItem() + "-01-01");
endDate = (yearChoice3.getSelectedItem() + "-12-31");
try{
jXDatePicker1.setDate(formatter.parse(stDate));
jXDatePicker2.setDate(formatter.parse(endDate));
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error has occured. Unable to generate report.");
System.out.println(e.getMessage());
}
}//GEN-LAST:event_yearChoice3ItemStateChanged
private void button5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button5ActionPerformed
// TODO add your handling code here:
int selectRow;
int id = 0;
Statement stmt = null;
DefaultTableModel table = new DefaultTableModel();
DecimalFormat twoDigits = new DecimalFormat("$#,###.00");
ResultSet rs = null;
ResultSet rs2 = null;
Connection con = null;
Object[] row = new Object[6];
String sql = "";
if(jTable2.getSelectedRow()>-1){
try{
selectRow = jTable2.getSelectedRow();
id = (int) jTable2.getValueAt(selectRow,0);
con = DriverManager.getConnection("jdbc:mysql://fetch-mobile-grooming.mysql.database.azure.com/Fetchdb","malderson@fetch-mobile-grooming","Puppy123");
String search = "SELECT entryStmt FROM financedb.journal WHERE entryId = '" + id + "';";
table.setColumnIdentifiers(new Object[]{"Invoice ID","Invoice Date","Invoice Type", "Invoice Total","Invoice Source","Invoice Tags"});
stmt = con.createStatement();
rs = stmt.executeQuery(search);
while(rs.next()){
sql = rs.getString("entryStmt");
}
stmt = con.createStatement();
rs2 = stmt.executeQuery(sql);
while (rs2.next()){
row[0] = rs2.getInt("invoiceId");
row[1] = rs2.getDate("invoiceDate");
row[2] = rs2.getString("invoiceType");
row[3] = twoDigits.format(rs2.getDouble("invoiceTotal"));
row[4] = rs2.getString("invoicesource");
row[5] = rs2.getString("invoiceTags");
table.addRow(row);
}
JTable table1 = new JTable();
table1.setModel(table);
JOptionPane.showMessageDialog(null, new JScrollPane(table1));
}catch(Exception e){
System.out.println(e.getMessage() + "id = " + id);
}finally{
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { rs2.close(); } catch (Exception e) { /* ignored */ }
try { con.close(); } catch (Exception e) { /* ignored */ }
}
}
}//GEN-LAST:event_button5ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(financeJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(financeJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(financeJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(financeJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new financeJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Button apButton;
private org.jdesktop.swingx.JXDatePicker apEndDate;
private org.jdesktop.swingx.JXDatePicker apStartDate;
private java.awt.Button arButton;
private org.jdesktop.swingx.JXDatePicker arEndDate;
private org.jdesktop.swingx.JXDatePicker arStartDate;
private java.awt.Button button2;
private java.awt.Button button3;
private java.awt.Button button5;
private javax.swing.ButtonGroup buttonGroup1;
private java.awt.Checkbox checkbox1;
private java.awt.Checkbox checkbox2;
private java.awt.Checkbox checkbox3;
private java.awt.Checkbox checkbox4;
private java.awt.Checkbox checkbox5;
private java.awt.Checkbox checkbox6;
private java.awt.Checkbox checkbox7;
private java.awt.Checkbox checkbox8;
private java.awt.Checkbox checkbox9;
private java.awt.Choice choice1;
private java.awt.Choice choice3;
private java.awt.Choice choice4;
private javax.swing.JTextField invAmntTextField;
private org.jdesktop.swingx.JXDatePicker invDate;
private java.awt.Choice invSourceChoice;
private javax.swing.JTextField invTagTextField;
private java.awt.Choice invTypeChoice;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JFrame jFrame1;
private javax.swing.JFrame jFrame2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private org.jdesktop.swingx.JXDatePicker jXDatePicker1;
private org.jdesktop.swingx.JXDatePicker jXDatePicker2;
private java.awt.Label label1;
private java.awt.Label label11;
private java.awt.Label label2;
private java.awt.Label label3;
private java.awt.Label label4;
private java.awt.Label label5;
private java.awt.Label label6;
private java.awt.Label label7;
private java.awt.Label label8;
private java.awt.Label label9;
private javax.swing.JLabel madeInvoiceLabel;
private java.awt.Menu menu1;
private java.awt.Menu menu2;
private java.awt.Menu menu3;
private java.awt.Menu menu4;
private java.awt.Menu menu5;
private java.awt.Menu menu6;
private java.awt.MenuBar menuBar1;
private java.awt.MenuBar menuBar2;
private java.awt.MenuBar menuBar3;
private java.awt.Panel panel1;
private java.awt.Panel panel2;
private java.awt.Choice sortChoice1;
private java.awt.Choice sortChoice2;
private java.awt.Choice sortChoice3;
private java.awt.Choice yearChoice1;
private java.awt.Choice yearChoice3;
// End of variables declaration//GEN-END:variables
}
|
package com.flutterwave.raveandroid.rave_presentation.di.francmobilemoney;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface FrancophoneScope {
}
|
package com.asiainfo.serviceRegistAndFound;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
/**
* 服务器注册与发现——模拟服务端
*
* @author zhangzhiwang
* @date 2017年8月22日 下午1:05:42
*/
public class Server {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper = new ZooKeeper("192.168.181.158:2181", 1000, null);
if(zooKeeper.exists("/servers", false) == null) {
zooKeeper.create("/servers", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
String stat = zooKeeper.create("/servers/", (args[0] + ":" + args[1]).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(args[0] + ":" + args[1] + " registed.");
System.out.println("---------------------");
Thread.sleep(Integer.MAX_VALUE);
}
}
|
package com.mahanthesh.africar.model;
import java.io.Serializable;
public class JobRequest implements Serializable {
private String id;
private String OTP;
private String accepted;
private String acceptedTime;
private String isVerified;
private LocationInfo drop;
private LocationInfo pickup;
private String duration;
private String distance;
private double ride_cost;
private String isCompleted;
private String driverId;
private String type;
private int required_seats;
public int getRequired_seats() {
return required_seats;
}
public void setRequired_seats(int required_seats) {
this.required_seats = required_seats;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOTP() {
return OTP;
}
public void setOTP(String OTP) {
this.OTP = OTP;
}
public String getAccepted() {
return accepted;
}
public void setAccepted(String accepted) {
this.accepted = accepted;
}
public String getIsVerified() {
return isVerified;
}
public void setIsVerified(String isVerified) {
this.isVerified = isVerified;
}
public LocationInfo getDrop() {
return drop;
}
public void setDrop(LocationInfo drop) {
this.drop = drop;
}
public LocationInfo getPickup() {
return pickup;
}
public void setPickup(LocationInfo pickup) {
this.pickup = pickup;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public double getRide_cost() {
return ride_cost;
}
public void setRide_cost(double ride_cost) {
this.ride_cost = ride_cost;
}
public String getIsCompleted() {
return isCompleted;
}
public void setIsCompleted(String isCompleted) {
this.isCompleted = isCompleted;
}
public String getDriverId() {
return driverId;
}
public void setDriverId(String driverId) {
this.driverId = driverId;
}
public String getAcceptedTime() {
return acceptedTime;
}
public void setAcceptedTime(String acceptedTime) {
this.acceptedTime = acceptedTime;
}
}
|
/*
Version Change history
1.4.4 - Support to set URL via Android Intents.
1.4.3 - Camera fixes
1.4.2 - Changed config file location & inject.js to Storage/Android/data/com.zebra.webkiosk/files
*/
package com.zebra.webkiosk;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.RenderProcessGoneDetail;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import static android.support.design.widget.Snackbar.LENGTH_LONG;
public class MainActivity extends AppCompatActivity implements RemoteIntentConfig.RemoteConfigListener, ScannerMgr.DatawedgeListener, NetworkConnectivityReceiver.NetworkChangeListener, NetworkConnectivityReceiver.NetworkEventListener, BatteryReceiver.BatteryListener {
// ****************************************************
private boolean CUSTOM_MULTIBARCODE = false;
// ****************************************************
public static final String TAG = "WEBKIOSK_";
private CustomWebView mWebView;
JavaScriptInterface jsInterface;
public ScannerMgr mScanner = null;
public RemoteIntentConfig mRemoteConfig = null;
private SettingsMgr mSettingsMgr;
private NetworkConnectivityReceiver mNetReceiver;
private BatteryReceiver mBatteryReceiver;
private boolean ekbShowState = true;
private static final int FILECHOOSER_RESULTCODE = 2888;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private static final int INPUT_FILE_REQUEST_CODE = 1;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
@Override
public void onNetworkChange(Boolean connected) {
Log.d(TAG,"onNetworkChange connected: "+connected);
mWebView.evaluateJavascript("javascript:if(typeof onNetworkChange === \"function\") onNetworkChange('"+ mSettingsMgr.mSettingsData.homeURL+"', "+connected+");",null);
}
@Override
public void onNetworkEvent(String json) {
json = json.replace("\"\"","\"");
Log.d(TAG,"onNetworkEvent: "+json);
mWebView.evaluateJavascript("javascript:if(typeof onNetworkEvent === \"function\") onNetworkEvent("+json+");",null);
}
@Override
public void onRemoteConfigEvent(Intent intent) {
String url = intent.getStringExtra("url");
if(url.isEmpty()==false) {
mSettingsMgr.mSettingsData.homeURL = url;
mSettingsMgr.writeSettingFile();
}
initWebView();
}
@Override
public void onDatawedgeEvent(Intent i) {
String data = i.getStringExtra(ScannerMgr.DATA_STRING_TAG);
String type = i.getStringExtra(ScannerMgr.LABEL_TYPE);
String source = i.getStringExtra(ScannerMgr.SOURCE_TAG);
String decode = "";//i.getStringExtra(ScannerMgr.DECODE_DATA_TAG);
String json = "{data:\""+data+"\",type:\""+type+"\", source:\""+source+"\", decode:\""+decode+"\"}";
Log.d(TAG,"***barcode (json obj):"+json);
mWebView.evaluateJavascript("javascript:if(typeof onDatawedgeEvent === \"function\") onDatawedgeEvent("+json+");",null);
mWebView.evaluateJavascript("javascript:if(typeof onScan === \"function\") onScan('"+data+"');",null);
}
@Override
public void onBatteryEvent(Intent intent) {
Log.d(TAG,"Battery event!");
Bundle bundle = intent.getExtras();
//extras
JSONObject json = new JSONObject();
Set<String> keys = bundle.keySet();
for (String key : keys) {
try {
// json.put(key, bundle.get(key)); see edit below
json.put(key, JSONObject.wrap(bundle.get(key)));
} catch(JSONException e) {
//Handle exception here
}
}
// Log.d(TAG,json.toString());
mWebView.evaluateJavascript("javascript:if(typeof onBatteryEvent === \"function\") onBatteryEvent("+json.toString() +");",null);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mWebView.loadUrl(mSettingsMgr.mSettingsData.homeURL);
return true;
case R.id.navigation_dashboard:
if(mSettingsMgr.mSettingsData.ekbFullControl){
ekbShowState = !ekbShowState;
Log.d(TAG, "EKB Show state: "+ekbShowState);
jsInterface.enableEKB(ekbShowState);
if(ekbShowState)
jsInterface.showEKB(true);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
Menu menu = bottomNavigationView.getMenu();
if(ekbShowState==false)
menu.findItem(R.id.navigation_dashboard).setIcon(R.drawable.nokeyboard);
else
menu.findItem(R.id.navigation_dashboard).setIcon(R.drawable.ic_keyboard_black_24dp);
} else {
showSip();
}
return true;
case R.id.navigation_notifications:
onSettings();
return true;
}
return false;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
mRemoteConfig.unregisterReceiver();
mNetReceiver.unregisterReceiver();
mScanner.unregisterReceiver();
mBatteryReceiver.unregisterReceiver();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG,"onResume");
mSettingsMgr.onLoadSettings();
if(mSettingsMgr.mSettingsData.forcePortrait)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
CUSTOM_MULTIBARCODE = mSettingsMgr.mSettingsData.customMultiBarcode;
mWebView.setWebContentsDebuggingEnabled(mSettingsMgr.mSettingsData.chromeDebugging);
if(mSettingsMgr.mSettingsData.useEKB)
jsInterface.setEKBLayout(mSettingsMgr.mSettingsData.ekbDefaultGroup, mSettingsMgr.mSettingsData.ekbDefaultName);
if(mScanner!=null && mSettingsMgr.mSettingsData.useScannerAPI==false) {
// mScanner.unregisterReceiver(BroadcastReceiver);
mScanner.unregisterReceiver();
} else if ( mSettingsMgr.mSettingsData.useScannerAPI) {
if(mScanner == null)
mScanner = new ScannerMgr(this);
if(CUSTOM_MULTIBARCODE)
mScanner.createScannerProfile();
else
mScanner.createScannerProfileClean();
}
setBottomNavBarVisibility();
checkWiFi();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSettingsMgr = new SettingsMgr(this);
Intent intent = this.getIntent();
boolean rebooted = false;
if(intent!=null) {
if( intent.getAction().equals("com.zebra.webkiosk.LOAD_CONFIG")) {
String configfile = intent.getStringExtra("config");
Log.d(TAG, "Detected to load config file: "+configfile);
if(configfile!=null)
mSettingsMgr.setSettingFile(configfile);
else
Log.d(TAG,"Invalid setting filename provided via intent");
} else if( intent.getAction().equals("com.zebra.webkiosk.SET_URL")) {
String url = intent.getStringExtra("url");
Log.d(TAG, "Detected to new URL save that to config file: "+url);
if(url!=null) {
mSettingsMgr.mSettingsData.homeURL = url;
mSettingsMgr.onSaveSettings();
} else {
Log.d(TAG, "Invalid setting url provided via intent");
}
}
else if( intent.getAction().equals("android.intent.action.MAIN")) {
rebooted = intent.getBooleanExtra("BOOT_COMPLETED", false);
}
}
Log.d(TAG,"onCreate");
mSettingsMgr.onLoadSettings();
if(rebooted == true && mSettingsMgr.mSettingsData.autoStartOnBoot == false) {
Log.d(TAG, "No auto start needed - shutting down app");
// shutdownApp();
}
/*********************************************************
Set up layout
*********************************************************/
//Remove notification bar
if(mSettingsMgr.mSettingsData.forcePortrait)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
/**************************************************
Set up permissions and platform check
**************************************************/
checkPlatform();
checkForPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
checkForPermission(Manifest.permission.CAMERA);
checkForPermission(Manifest.permission.ACCESS_FINE_LOCATION);
if(mSettingsMgr.mSettingsData.useScannerAPI) {
mScanner = new ScannerMgr(this);
mScanner.registerReceiver();
CUSTOM_MULTIBARCODE = mSettingsMgr.mSettingsData.customMultiBarcode;
if(CUSTOM_MULTIBARCODE) {
mScanner.createScannerProfile();
} else {
mScanner.createScannerProfileClean();
}
}
mRemoteConfig = new RemoteIntentConfig(this);
mNetReceiver = new NetworkConnectivityReceiver(this);
mBatteryReceiver = new BatteryReceiver(this);
initWebView();
}
public void initWebView(){
Log.d(TAG,"initialize WebView component.");
mWebView = (CustomWebView) findViewById(R.id.activity_main_webview);
mWebView.setWebViewClient(new MyWebViewClient());
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebContentsDebuggingEnabled(mSettingsMgr.mSettingsData.chromeDebugging);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setAllowContentAccess(true);
mWebView.getSettings().setAllowFileAccess(true);
//mWebView.getSettings().setSavePassword(false);
mWebView.clearFormData();
mWebView.getSettings().setSaveFormData(false);
mWebView.clearHistory();
mWebView.clearCache(true);
mWebView.clearSslPreferences();
// mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
// if(mSettingsMgr.mSettingsData.allowMixedContent)
// mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setAcceptThirdPartyCookies(mWebView,true);
cookieManager.setAcceptFileSchemeCookies(true);
jsInterface = new JavaScriptInterface(this);
mWebView.addJavascriptInterface(jsInterface, "JSInterface");
mWebView.setWebChromeClient(new MyChromeClient());
mWebView.loadUrl(mSettingsMgr.mSettingsData.homeURL);
}
public void checkForPermission(String permissionType) {
if (ContextCompat.checkSelfPermission(this,
permissionType)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
permissionType)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
showCustomDialog("Permission", "Permission type is not granted:\n"+permissionType+"\nApp may not support all features.");
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{permissionType},
1001);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
if(mSettingsMgr.mSettingsData.chromeDebugging)
Toast.makeText(getApplicationContext(), "Permission already granted \n"+permissionType, Toast.LENGTH_SHORT).show();
}
}
public void showCustomDialog(String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
public void checkWiFi() {
onNetworkEvent(mNetReceiver.fetchWiFiState());
}
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| "google_sdk".equals(Build.PRODUCT);
}
public void shutdownApp(){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Shutting down app! ***");
moveTaskToBack(false);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}, 3000);
}
public void checkPlatform() {
if(isEmulator())
return;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (Build.BRAND.compareTo("Zebra") != 0) {
Log.d(TAG, "Not a valid platform!");
Toast.makeText(getApplicationContext(), "Invalid platform! Will close the app.", Toast.LENGTH_LONG).show();
shutdownApp();
}
}
});
}
public void setBottomNavBarVisibility(){
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
if(mSettingsMgr.mSettingsData.hideNavbar)
navigation.setVisibility(View.GONE);
else
navigation.setVisibility(View.VISIBLE);
}
@Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"requestCode: "+requestCode);
Log.d(TAG,"resultCode: "+resultCode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
Log.d(TAG,"mCameraPhotoPath: "+mCameraPhotoPath);
// Check that the response is a good one
if (resultCode == RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
Log.d(TAG,"mCameraPhotoPath: "+mCameraPhotoPath);
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
// for(String s : data.getExtras().keySet())
// Log.d(TAG,"Key: "+s+" value:"+data.getExtras().getString(s));
String dataString = data.getDataString();
Log.d(TAG,"dataString: "+dataString);
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
private class MyChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
Log.d(TAG,"Open File chooser 5.0+");
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
// openFileChooser for Android 3.0+
/* public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
Log.d(TAG,"Open File chooser");
// Update message
mUploadMessage = uploadMsg;
try{
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Exception:"+e,
Toast.LENGTH_LONG).show();
}
}
*/
// The webPage has 2 filechoosers and will send a
// console message informing what action to perform,
// taking a photo or updating the file
/* public boolean onConsoleMessage(ConsoleMessage cm) {
onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
return true;
}*/
}
private class MyWebViewClient extends WebViewClient {
private Handler handler = new Handler();
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url); // load the url
return true;
}
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if(errorCode == 404){
Log.d(TAG, "Invalid URL: "+failingUrl);
} else if(errorCode == 500){
Log.d(TAG, "Internal Server error: "+failingUrl);
} else {
Log.d(TAG, "Page load error (code: "+String.valueOf(errorCode)+") URL: "+failingUrl);
}
final int errorCode_ = errorCode;
if (errorCode == WebViewClient.ERROR_HOST_LOOKUP) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Delayed loadURL " + errorCode_);
if (mWebView == null)
Log.d(TAG, "webview is null");
mWebView.setActivated(true);
if (mWebView != null && mWebView.isActivated()) {
// String url = "file:///" + Environment.getExternalStorageDirectory().getPath() + "/offline.html";
String url = "file:///android_asset/badurl.html";
mWebView.loadUrl(url);
Handler hdler = new Handler();
hdler.postDelayed(new Runnable() {
@Override
public void run() {
mWebView.evaluateJavascript("javascript:onError('" + errorCode_ + "');", null);
}
}, 500);
}
}
}, 500);
}
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// handler.proceed();
Log.d(TAG,"ssl_error: " + error.toString());
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d(TAG,"Inject JS file?");
if(mSettingsMgr.mSettingsData.injectJavascript)
injectScriptFile(mWebView,"inject.js");
checkWiFi();
}
@Override
public boolean onRenderProcessGone(WebView view,
RenderProcessGoneDetail detail) {
if (!detail.didCrash()) {
// Renderer was killed because the system ran out of memory.
// The app can recover gracefully by creating a new WebView instance
// in the foreground.
Log.e(TAG, "System killed the WebView rendering process " +
"to reclaim memory. Recreating...");
if (mWebView != null) {
ViewGroup webViewContainer =
(ViewGroup) findViewById(R.id.activity_main_webview);
webViewContainer.removeView(mWebView);
mWebView.destroy();
mWebView = null;
}
// By this point, the instance variable "mWebView" is guaranteed
// to be null, so it's safe to reinitialize it.
mWebView.clearCache(true);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebContentsDebuggingEnabled(mSettingsMgr.mSettingsData.chromeDebugging);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setAcceptThirdPartyCookies(mWebView,true);
cookieManager.setAcceptFileSchemeCookies(true);
mWebView.loadUrl(mSettingsMgr.mSettingsData.homeURL);
JavaScriptInterface jsInterface = new JavaScriptInterface(getParent());
mWebView.addJavascriptInterface(jsInterface, "JSInterface");
return true; // The app continues executing.
}
// Renderer crashed because of an internal error, such as a memory
// access violation.
Log.e(TAG, "The WebView rendering process crashed!");
// In this example, the app itself crashes after detecting that the
// renderer crashed. If you choose to handle the crash more gracefully
// and allow your app to continue executing, you should 1) destroy the
// current WebView instance, 2) specify logic for how the app can
// continue executing, and 3) return "true" instead.
return false;
}
}
public void showSip(){
Log.d(TAG, "showSip()");
mWebView.bKeyboardShowState = true;
Activity a = (Activity) this;
InputMethodManager inputMethodManager = (InputMethodManager) a.getSystemService(Activity.INPUT_METHOD_SERVICE);
// inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
FileInputStream fis;
try {
Log.d(TAG,"Inject file: "+mSettingsMgr.getPath() + "/"+scriptFile);
File f = new File(mSettingsMgr.getPath() + "/"+scriptFile);
fis = new FileInputStream(f); //getAssets().open(scriptFile);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onSettings() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please enter password for settings");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String m_Text = "";
m_Text = input.getText().toString();
if (m_Text.compareTo(mSettingsMgr.mSettingsData.settingsPassword) == 0) {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),"Invalid password", Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
|
package week5.day2;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel {
public static void main(String[] args) throws IOException {
XSSFWorkbook wb = new XSSFWorkbook("./Data/MarksName.xlsx");
// OpenSheet
XSSFSheet sheet = wb.getSheet("Sheet1");
// row counts
int rownum = sheet.getLastRowNum();
// column counts
int columnnum = sheet.getRow(0).getLastCellNum();
// To take Rows
for (int i = 1; i <= rownum; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j < columnnum; j++) {
// go to cell
XSSFCell cell = row.getCell(j);
// Read data from cell in string
String name = cell.getStringCellValue();
System.out.println(name);
}
}
wb.close();
}
}
|
package kr.or.ddit.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.command.SearchCriteria;
import kr.or.ddit.dto.BoardVO;
public interface BoardDAO {
// 목록 조회
List<BoardVO> selectSearchBoardList(SqlSession session, SearchCriteria cri) throws SQLException;
// 목록 개수
int selectSearchBoardListCount(SqlSession session, SearchCriteria cri) throws SQLException;
// 게시글 조회
BoardVO selectBoardByBno(SqlSession session, int bno) throws SQLException;
// 시퀀스 가져오기
int selectBoardSequenceNextValue(SqlSession session) throws SQLException;
// 조회수 증가
void increaseViewCount(SqlSession session, int bno) throws SQLException;
// 작성
public void insertBoard(SqlSession session, BoardVO board) throws SQLException;
// 수정
public void updateBoard(SqlSession session, BoardVO board) throws SQLException;
// 삭제
public void deleteBoard(SqlSession session, int bno) throws SQLException;
}
|
package com.cn.jingfen.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import com.cn.jingfen.vo.User;
public class Gridme {
//查看用户类型
public static Map userType(User user){
int typeNum;
String unitCode;
Map<String,Object> map = new HashMap<String,Object>();
if(user.getCITY_CODE().equals("290")){
//省用户
typeNum=1;
unitCode="290";
}else if(user.getCOUNTY_CODE().equals("0000")){
//地市用户
typeNum=2;
unitCode=user.getCITY_CODE();
}else if(user.getVILLAGE_CODE().equals("00000")||user.getVILLAGE_CODE().equals("")||null==user.getVILLAGE_CODE()){
//区县用户
typeNum=3;
unitCode=user.getCOUNTY_CODE();
}else{
//网格用户
typeNum=4;
unitCode=user.getVILLAGE_CODE();
}
map.put("typeNum", typeNum);
map.put("unitCode", unitCode);
return map;
}
public static String readfile(String path) {
StringBuffer str = new StringBuffer();
try {
String encoding="UTF-8";
File file=new File(path);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
str.append(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return str.toString();
}
/** 分割字符串 */
public static String[] split(String str, String regex)
{
// 存放分割后的字符串
String newStr[] = new String[str.length()];
// 临时存放字符串数组的一个元素
String temp = null;
// 复制存放分割后的字符串
String[] result = null;
// 分隔符所在的下一个索引和当前索引
int start = 0, end = 0;
// 字符串数组的索引
int index = 0;
/** 遍历字符串的每一个字符 */
for (int i = 0; i < str.length(); i++)
{
temp = str.substring(i, i + 1); // 截取一个字符
// 判断截取的字符是否为分隔符
if (temp.equals(regex))
{
temp = null;
end = i; // 当前的分隔符的索引(字符串截取的最后位置)
newStr[index] = str.substring(start, end); // 截取字符串并赋值给字符串数组
index++; // 字符串数组索引加1
start = end + 1; // 当前的分隔符的索引后一索引(字符串截取的开始位置)
}
}
// 最后一个分隔符的索引不等于字符串长度
if (str.lastIndexOf(regex) != str.length())
{
newStr[index] = str.substring(start, str.length());
index++;
}
result = new String[index];
// 从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束
System.arraycopy(newStr, 0, result, 0, index);
return result;
}
}
|
package org.fao.unredd.servlet;
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
import it.geosolutions.geostore.core.model.Resource;
import it.geosolutions.unredd.geostore.UNREDDGeostoreManager;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import org.fao.unredd.Util;
/**
*
* @author sgiaccio
*/
public class ChartDataList extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get HTTP parameters
String chartScriptName = request.getParameter("chart_script");
try {
UNREDDGeostoreManager manager = Util.getGeostoreManager(getServletContext());
List<Resource> relatedStatsDef = manager.searchChartDataByChartScript(chartScriptName);
request.setAttribute("chartData", relatedStatsDef);
request.setAttribute("geostoreURL", Util.getGeostoreRestURL(getServletContext()));
RequestDispatcher rd = request.getRequestDispatcher("chart-data-list.jsp");
rd.forward(request, response);
} catch (JAXBException ex) {
throw new ServletException(ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.zero.votes.web;
import com.zero.votes.beans.UrlsPy;
import com.zero.votes.persistence.PollFacade;
import com.zero.votes.persistence.entities.Poll;
import com.zero.votes.web.util.JsfUtil;
import com.zero.votes.web.util.PaginationHelper;
import com.zero.votes.web.util.ZVotesUtils;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Named;
@Named("adminPollController")
@SessionScoped
public class AdminPollController implements Serializable {
private DataModel items = null;
@EJB
private com.zero.votes.persistence.PollFacade ejbFacade;
@EJB
private com.zero.votes.persistence.TokenFacade tokenFacade;
private PaginationHelper pagination;
public AdminPollController() {
}
private PollFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
@Override
public int getItemsCount() {
return getFacade().count();
}
@Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String destroy(Poll poll) {
performDestroy(poll);
recreatePagination();
recreateModel();
return UrlsPy.ADMIN_POLL_LIST.getUrl(true);
}
private void performDestroy(Poll poll) {
try {
getFacade().remove(poll);
ZVotesUtils.addInternationalizedInfoMessage("PollDeleted");
} catch (Exception e) {
ZVotesUtils.addInternationalizedErrorMessage("PersistenceErrorOccured");
}
}
public DataModel getItems() {
return getPagination().createPageDataModel();
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return UrlsPy.ADMIN_POLL_LIST.getUrl(true);
}
public String previous() {
getPagination().previousPage();
recreateModel();
return UrlsPy.ADMIN_POLL_LIST.getUrl(true);
}
public String page(String page) {
getPagination().setPage(Integer.valueOf(page));
recreateModel();
return UrlsPy.ADMIN_POLL_LIST.getUrl(true);
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Poll getPoll(java.lang.Long id) {
return ejbFacade.find(id);
}
@FacesConverter(forClass = Poll.class)
public static class PollControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
AdminPollController controller = (AdminPollController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "pollController");
return controller.getPoll(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Long value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Poll) {
Poll o = (Poll) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Poll.class.getName());
}
}
}
}
|
/*
* 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 codefights;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
*
* @author CongThanh
*/
public class Dropbox {
public static void main(String[] args) {
String a[] = {"thanh@hust.edu", "cong@neu.edu", "ftu@edu.vn", "thanh@hust.edu"};
campusCup(a);
}
public static void campusCup(String[] emails) {
//Creat a array of School
ArrayList<School> schoolArray = new ArrayList();
for (String email : emails) {
boolean check = false; //Check if the email exsist in arraylist or not
String standEmail = email.substring(email.indexOf("@") + 1); //
for(School objschool: schoolArray){
if(standEmail.equals(objschool.name)) {
objschool.add();
check = true;
break;
}
}
if(check==false){
School objSchool = new School(standEmail, 1);
schoolArray.add(objSchool);
}
}
Collections.sort(schoolArray, new Comparator<School>() {
@Override
public int compare(School sc1, School sc2) {
if (sc1.count < sc2.count) {
return 1;
} else if (sc1.count == sc2.count) {
return 0;
} else {
return -1;
}
}
});
for (School objSchool : schoolArray) {
System.out.println(objSchool.name);
}
}
}
class School {
public String name;
public int count;
School(String name, int count) {
this.name = name;
this.count = count;
}
public void add() {
this.count += 1;
}
}
|
/*
* Copyright (c) 2014. igitras.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igitras.codegen.common.utils;
import com.igitras.codegen.common.java.element.file.part.AbstractJavaFilePart;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* Created by mason on 12/17/14.
*/
public class TemplateUtils {
public static void processFields(Object object, StringBuilder templateBuilder) {
Iterable<Field> declaredFields = ReflectionUtils.fieldsOf(object.getClass());
for (Field field : declaredFields) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
Class<?> type = field.getType();
if (type.isPrimitive()) {
type = ReflectionUtils.resolvePrimitiveWrapperType(type);
}
if (type.isEnum()) {
Object fieldValue = ReflectionUtils.getFieldValue(field, object);
Assert.notNull(fieldValue, "Enum value must not be null.");
String value = fieldValue.toString();
if ("DEFAULT".equalsIgnoreCase(value)) {
value = "";
} else {
value = value.toLowerCase();
}
replaceProperty(field.getName(), value, templateBuilder);
continue;
}
if (AbstractJavaFilePart.class.isAssignableFrom(type)) {
AbstractJavaFilePart javaFilePart = (AbstractJavaFilePart) ReflectionUtils.getFieldValue(field, object);
String value = javaFilePart.build();
replaceJavaFilePartProperty(type.getSimpleName(), value, templateBuilder);
continue;
}
if (ReflectionUtils.isInPrimitiveWrapperType(type)) {
Object fieldValue = ReflectionUtils.getFieldValue(field, object);
String value;
if (null == fieldValue) {
value = "";
} else {
value = fieldValue.toString();
}
replaceProperty(field.getName(), value, templateBuilder);
continue;
}
if (Serializable.class.isAssignableFrom(type)) {
Object fieldValue = ReflectionUtils.getFieldValue(field, object);
String value;
if (null == fieldValue) {
value = "";
} else {
value = fieldValue.toString();
}
if (field.getType() == String.class) {
value = StringUtils.getClassName(value);
}
replaceProperty(field.getName(), value, templateBuilder);
continue;
}
}
}
public static void replaceProperty(String fieldName, String value, StringBuilder templateBuilder) {
String keyword = String.format("##%s", fieldName);
replace(value, keyword, templateBuilder);
}
public static void replaceJavaFilePartProperty(String typeName, String replacement, StringBuilder templateBuilder) {
String keyword = String.format("#%s#", typeName);
replace(replacement, keyword, templateBuilder);
}
public static void replaceMultipleJavaFilePartProperty(
String typeName, String replacement, StringBuilder templateBuilder) {
String keyword =
"##Each##" + System.lineSeparator() + "#" + typeName + "#" + System.lineSeparator() + "##Each##";
replace(replacement, keyword, templateBuilder);
}
/**
* Replace all the keyword in the templateBuilder with replacement.
*
* @param replacement
* @param keyword
*/
private static void replace(String replacement, String keyword, StringBuilder templateBuilder) {
int keywordStartIndex;
if (replacement == null) {
replacement = "";
}
while ((keywordStartIndex = templateBuilder.indexOf(keyword)) >= 0) {
int keywordEndIndex = keywordStartIndex + keyword.length();
if (keywordEndIndex <= keywordStartIndex) {
break;
}
templateBuilder.replace(keywordStartIndex, keywordEndIndex, replacement);
}
}
}
|
package com.bih.nic.saathi.Model;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import java.io.Serializable;
import java.util.Hashtable;
public class JobOfferPostedEntity implements KvmSerializable, Serializable {
public static Class<JobOfferPostedEntity> JobOffer_CLASS = JobOfferPostedEntity.class;
private String DistrictCode = "";
private String DistrictName = "";
private String ttlReg = "";
private String TotalJobOffer = "";
private String ttlRegA = "";
private String ttlRegR = "";
public JobOfferPostedEntity(SoapObject obj) {
this.DistrictCode = obj.getProperty("DistrictCode").toString();
this.DistrictName = obj.getProperty("DistrictName").toString();
this.ttlReg = obj.getProperty("ttlReg").toString();
this.TotalJobOffer = obj.getProperty("TotalJobOffer").toString();
this.ttlRegA = obj.getProperty("ttlRegA").toString();
this.ttlRegR = obj.getProperty("ttlRegR").toString();
//this.skillName = obj.getProperty("SkillNameHn").toString();
}
public static Class<JobOfferPostedEntity> getJobOffer_CLASS() {
return JobOffer_CLASS;
}
public static void setJobOffer_CLASS(Class<JobOfferPostedEntity> jobOffer_CLASS) {
JobOffer_CLASS = jobOffer_CLASS;
}
public String getDistrictCode() {
return DistrictCode;
}
public void setDistrictCode(String districtCode) {
DistrictCode = districtCode;
}
public String getDistrictName() {
return DistrictName;
}
public void setDistrictName(String districtName) {
DistrictName = districtName;
}
public String getTtlReg() {
return ttlReg;
}
public void setTtlReg(String ttlReg) {
this.ttlReg = ttlReg;
}
public String getTotalJobOffer() {
return TotalJobOffer;
}
public void setTotalJobOffer(String totalJobOffer) {
TotalJobOffer = totalJobOffer;
}
public String getTtlRegA() {
return ttlRegA;
}
public void setTtlRegA(String ttlRegA) {
this.ttlRegA = ttlRegA;
}
public String getTtlRegR() {
return ttlRegR;
}
public void setTtlRegR(String ttlRegR) {
this.ttlRegR = ttlRegR;
}
@Override
public Object getProperty(int index) {
return null;
}
@Override
public int getPropertyCount() {
return 0;
}
@Override
public void setProperty(int index, Object value) {
}
@Override
public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
}
}
|
package com.singtel.nsb.mobile.sync.config;
import java.util.Date;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Configuration
@RestController
public class CamelRouteConfig extends RouteBuilder {
@Value("${swaggerContextPath}")
private String contextPath;
@Override
public void configure() throws Exception {
restConfiguration().component("servlet").apiContextPath("/swagger").apiContextRouteId("swagger")
// Swagger properties
.apiProperty("cors", "true")
.contextPath(contextPath)
.apiProperty("api.title", "Service Activation & Configuration")
.apiProperty("api.version", "1.0")
.apiProperty("api.contact.name", "Singtel")
.apiProperty("api.contact.email", "Singtel.Admin@singtel.com")
.apiProperty("api.contact.url", "https://Singtel.com")
.apiProperty("host", "")
.apiProperty("port", "8011")
.apiProperty("schemes", "");
}
@GetMapping("/")
public String ping() {
return "Welcome to NSBHttpListener" + new Date();
}
}
|
package Web;
//https://mdago.tistory.com/2
// good
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Scanner;
import Student.StudentInfo;
public class StatusManager {
public static void main(String[] args) {
try {
Scanner s=new Scanner(System.in);
int n,i,j=1,p;
while(j>0) {
for(i=0;i<StudentInfo.ClassNumber;i++)
System.out.print(i+1+": "+StudentInfo.Class[i]+" ");
System.out.print("\n0 to end: ");
n=s.nextInt()-1;
System.out.print("C?: 0-N 1-Y ");
p=s.nextInt();
if(n<0)break;
for(i=0;i<StudentInfo.StudentNumber[n];i++)
Desktop.getDesktop().browse(new URI("https://www.acmicpc.net/status?problem_id=&user_id="+StudentInfo.ID_LIST[n][i]+"&language_id=-1&result_id="+(p>0?4:-1)));
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
|
package com.yinghai.a24divine_user.module.address.delete;
import com.example.fansonlib.base.BaseModel;
import com.example.fansonlib.http.HttpResponseCallback;
import com.example.fansonlib.http.HttpUtils;
import com.example.fansonlib.utils.SharePreferenceHelper;
import com.yinghai.a24divine_user.bean.AddressListBean;
import com.yinghai.a24divine_user.constant.ConHttp;
import com.yinghai.a24divine_user.constant.ConResultCode;
import com.yinghai.a24divine_user.constant.ConstantPreference;
import com.yinghai.a24divine_user.utils.ValidateAPITokenUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author Created by:fanson
* Created Time: 2017/11/17 13:40
* Describe:删除地址M层
*/
public class DeleteAddressModel extends BaseModel implements ContractDeleteAddress.IModel {
private IDeleteCallback mCallback;
@Override
public void deleteAddress(int addressId, IDeleteCallback callback) {
mCallback = callback;
String time = String.valueOf(System.currentTimeMillis());
Map<String, Object> maps = new HashMap<>(4);
maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID, 0));
maps.put("addressId", addressId);
maps.put("apiSendTime",time);
maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time));
HttpUtils.getHttpUtils().post(ConHttp.DELETE_ADDRESS, maps, new HttpResponseCallback<AddressListBean>() {
@Override
public void onSuccess(AddressListBean bean) {
if (mCallback == null) {
return;
}
switch (bean.getCode()) {
case ConResultCode.SUCCESS:
mCallback.onDeleteSuccess(bean);
break;
default:
mCallback.handlerResultCode(bean.getCode());
break;
}
}
@Override
public void onFailure(String errorMsg) {
if (mCallback != null) {
mCallback.onDeleteFailure(errorMsg);
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mCallback = null;
}
}
|
package leecode.DP;
//https://blog.csdn.net/qq_28114615/article/details/86483709#2.1%20
//dp的边界条件是长度为1和2的子串,这个不是开头两个字符,而是所有长度为1和2的子串
public class 最长回文子串_5 {
public String longestPalindrome1(String s) {
int max=0;
int len=0;
String sub="";
for (int i = 0; i <s.length() ; i++) {
for (int j = i+1; j <=s.length() ; j++) {
if(is_string(s.substring(i,j).toCharArray())){
len=s.substring(i,j).length();
if(max<len){
max=len;
sub=s.substring(i,j);
}
}
}
}
return sub;
}
public boolean is_string(char[]res){
int len=res.length;
for (int i = 0; i <len/2 ; i++) {
if(res[i]!=res[len-i-1]){
return false;
}
}
return true;
}
// github 解法 双指针 https://github.com/labuladong/fucking-algorithm/blob/master/%E9%AB%98%E9%A2%91%E9%9D%A2%E8%AF%95%E7%B3%BB%E5%88%97/%E6%9C%80%E9%95%BF%E5%9B%9E%E6%96%87%E5%AD%90%E4%B8%B2.md
// 这个是中心扩散法 也可以看liweiwei的题解
public static String longestpalind(String s){
String res=new String();
for (int i = 0; i <s.length() ; i++) {//这里是i <s.length()!! 如果i <s.length()-1,case:对于"a" 应该返回a
String s1=panlindrome(s,i,i); //对于 aba
String s2=panlindrome(s,i,i+1);//对于 abba 回文串长度为偶数,只能从s[i]和s[i+1]向两边扩散
res=res.length()>s1.length()?res:s1;
res=res.length()>s2.length()?res:s2;
}
return res;
}
public static String panlindrome(String s,int l,int r){
while (l>=0&&r<s.length()&&(s.charAt(l)==s.charAt(r))){//s.indexOf(l)==s.indexOf(r) 这个一定要加括号
l--;
r++;
}
System.out.println("l:"+l+"r:"+r);
//推出循环前 执行了 l-- r++
return s.substring(l+1,r);//包括起始,不包括结束,看着不太对
}
/*
动态规划 liweiwei:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zhong-xin-kuo-san-dong-tai-gui-hua-by-liweiwei1419/
*/
public String longestPalindrome(String s) {
int len=s.length();
//dp[i][j] 表示 s[i, j] 是否是回文串
boolean[][]dp=new boolean[len][len];
//单个字符是回文
for (int i = 0; i <len ; i++) {
dp[i][i]=true;
}
int maxLen=1;
int begin=0;
for (int j = 1; j <len ; j++) {
for (int i = 0; i <j ; i++) {
if(s.charAt(i)!=s.charAt(j)){
dp[i][j]=false;
}else {//i 和 j 位置上相等
if(j-i<3){// dp[i+1][j-1] 即j-1-(i+1)+1<2 => [i+1,j-1]不构成区间, j-i<3 即[i,j]长度(j-i+1<4)为2 或者 3
dp[i][j]=true;
}else {
dp[i][j]=dp[i+1][j-1];
}
}
// 只要 dp[i][j] == true 成立,就表示子串 s[i..j] 是回文,此时记录回文长度和起始位置
if(dp[i][j]&&j-i+1>maxLen){
maxLen=j-i+1;
begin=i;
}
}
}
return s.substring(begin,begin+maxLen);
}
//暴力解法 找到所有的子串 然后判断回文 更新最大长度
public static void main(String[] args) {
String s="a";
// s.toCharArray().length
System.out.println(longestpalind(s));
}
}
|
/*
* 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 agendascc.UI;
import agendascc.AgendaSCC;
import java.awt.Color;
import javax.swing.Icon;
import javax.swing.ImageIcon;
/**
*
* @author JTF
*/
public class MainViewTest extends javax.swing.JFrame {
/**
* Creates new form MainView
*/
/*protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = AgendaSCC.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}*/
public MainViewTest() {
/* Icon icon;
icon=createImageIcon("RESOURCES/ICOTODOS.png");
tabbedPaneContactos.setIconAt(0, icon); */
initComponents();
getContentPane().setBackground(Color.white);
tabbedPaneContactos.add(new ContactosPanel3(entityManager1, "cliente"), tabbedPaneContactos.getTabCount());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
entityManager1 = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("AgendaSCCPU").createEntityManager();
toolBarBotones = new javax.swing.JToolBar();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jXStatusBar1 = new org.jdesktop.swingx.JXStatusBar();
tabbedPaneContactos = new javax.swing.JTabbedPane();
jXPanel1 = new org.jdesktop.swingx.JXPanel();
jXPanel2 = new org.jdesktop.swingx.JXPanel();
jXPanel3 = new org.jdesktop.swingx.JXPanel();
jXPanel4 = new org.jdesktop.swingx.JXPanel();
jXPanel5 = new org.jdesktop.swingx.JXPanel();
jXPanel6 = new org.jdesktop.swingx.JXPanel();
menuBarPrincipal = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
setMinimumSize(new java.awt.Dimension(800, 600));
org.jdesktop.swingx.border.DropShadowBorder dropShadowBorder1 = new org.jdesktop.swingx.border.DropShadowBorder();
dropShadowBorder1.setShadowSize(3);
dropShadowBorder1.setShowLeftShadow(true);
toolBarBotones.setBorder(dropShadowBorder1);
toolBarBotones.setFloatable(false);
toolBarBotones.setRollover(true);
jButton1.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
jButton1.setText("jButton1");
jButton1.setFocusable(false);
jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
toolBarBotones.add(jButton1);
jButton2.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
jButton2.setText("jButton2");
jButton2.setFocusable(false);
jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton2.setIconTextGap(1);
toolBarBotones.add(jButton2);
tabbedPaneContactos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "CONTACTOS", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
tabbedPaneContactos.setTabPlacement(javax.swing.JTabbedPane.LEFT);
tabbedPaneContactos.setFont(new java.awt.Font("Calibri", 1, 14)); // NOI18N
javax.swing.GroupLayout jXPanel1Layout = new javax.swing.GroupLayout(jXPanel1);
jXPanel1.setLayout(jXPanel1Layout);
jXPanel1Layout.setHorizontalGroup(
jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 687, Short.MAX_VALUE)
);
jXPanel1Layout.setVerticalGroup(
jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 495, Short.MAX_VALUE)
);
tabbedPaneContactos.addTab("", new javax.swing.ImageIcon(getClass().getResource("/agendascc/RESOURCES/ICOTODOS.png")), jXPanel1); // NOI18N
javax.swing.GroupLayout jXPanel2Layout = new javax.swing.GroupLayout(jXPanel2);
jXPanel2.setLayout(jXPanel2Layout);
jXPanel2Layout.setHorizontalGroup(
jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 687, Short.MAX_VALUE)
);
jXPanel2Layout.setVerticalGroup(
jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 495, Short.MAX_VALUE)
);
tabbedPaneContactos.addTab("CLIENTES", jXPanel2);
javax.swing.GroupLayout jXPanel3Layout = new javax.swing.GroupLayout(jXPanel3);
jXPanel3.setLayout(jXPanel3Layout);
jXPanel3Layout.setHorizontalGroup(
jXPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 687, Short.MAX_VALUE)
);
jXPanel3Layout.setVerticalGroup(
jXPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 495, Short.MAX_VALUE)
);
tabbedPaneContactos.addTab("EMPLEADOS", jXPanel3);
javax.swing.GroupLayout jXPanel4Layout = new javax.swing.GroupLayout(jXPanel4);
jXPanel4.setLayout(jXPanel4Layout);
jXPanel4Layout.setHorizontalGroup(
jXPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 687, Short.MAX_VALUE)
);
jXPanel4Layout.setVerticalGroup(
jXPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 495, Short.MAX_VALUE)
);
tabbedPaneContactos.addTab("PERSONALES", jXPanel4);
javax.swing.GroupLayout jXPanel5Layout = new javax.swing.GroupLayout(jXPanel5);
jXPanel5.setLayout(jXPanel5Layout);
jXPanel5Layout.setHorizontalGroup(
jXPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 687, Short.MAX_VALUE)
);
jXPanel5Layout.setVerticalGroup(
jXPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 495, Short.MAX_VALUE)
);
tabbedPaneContactos.addTab("GENERAL", jXPanel5);
jXPanel6.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jXPanel6Layout = new javax.swing.GroupLayout(jXPanel6);
jXPanel6.setLayout(jXPanel6Layout);
jXPanel6Layout.setHorizontalGroup(
jXPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 687, Short.MAX_VALUE)
);
jXPanel6Layout.setVerticalGroup(
jXPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 495, Short.MAX_VALUE)
);
tabbedPaneContactos.addTab("PROVEEDORES", jXPanel6);
jMenu1.setText("File");
menuBarPrincipal.add(jMenu1);
jMenu2.setText("Edit");
menuBarPrincipal.add(jMenu2);
setJMenuBar(menuBarPrincipal);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(toolBarBotones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jXStatusBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tabbedPaneContactos)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(toolBarBotones, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tabbedPaneContactos)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jXStatusBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.persistence.EntityManager entityManager1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private org.jdesktop.swingx.JXPanel jXPanel1;
private org.jdesktop.swingx.JXPanel jXPanel2;
private org.jdesktop.swingx.JXPanel jXPanel3;
private org.jdesktop.swingx.JXPanel jXPanel4;
private org.jdesktop.swingx.JXPanel jXPanel5;
private org.jdesktop.swingx.JXPanel jXPanel6;
private org.jdesktop.swingx.JXStatusBar jXStatusBar1;
private javax.swing.JMenuBar menuBarPrincipal;
private javax.swing.JTabbedPane tabbedPaneContactos;
private javax.swing.JToolBar toolBarBotones;
// End of variables declaration//GEN-END:variables
}
|
package aplicacao;
import java.util.Scanner;
public class Tela {
public static int menu(Scanner sc) {
System.out.println("1 - Cadastrar um novo espetáculo e as participações dele");
System.out.println("2 - Mostrar os dados de um espetáculo (nome, preço total e participações");
System.out.println("3 - Sair");
return Integer.parseInt(sc.nextLine());
}
}
|
package by.bsu.lab6.part2.util;
import by.bsu.lab6.part2.entity.GemStone;
import by.bsu.lab6.part2.entity.Necklace;
import by.bsu.lab6.part2.entity.Stone;
import java.math.BigDecimal;
public class NecklaceCounter {
public double getWeightAtNecklace(Necklace necklace) {
return necklace.getStones()
.parallelStream()
.reduce(0.0, (acc, stone) -> acc + stone.getWeight(), (left, right) -> left + right);
}
public BigDecimal getPriceAtNecklace(Necklace necklace) {
BigDecimal sum = new BigDecimal(0);
for (Stone stone : necklace.getStones()) {
sum = sum.add(((GemStone) stone).getPrice());
}
return sum;
}
}
|
package com.magit.logic.exceptions;
public class FastForwardException extends Exception{
private final String mMessage;
public FastForwardException(String mMessage) {
this.mMessage = mMessage;
}
@Override
public String getMessage() {
return mMessage;
}
}
|
/*
* Copyright (c) 2019 LINE Corporation. All rights reserved.
* LINE Corporation PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.libedi.demo.repository;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import com.libedi.demo.domain.Child;
import com.libedi.demo.domain.Parent;
/**
* ParentRepositoryTest - 1:1 식별관계 매핑
*
* @author Sang-jun, Park (libedi@linecorp.com)
* @since 2019. 04. 19
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class ParentRepositoryTest {
@Autowired
private ParentRepository parentRepository;
@Autowired
private ChildRepository childRepository;
// @Test
@Before
public void testChild() {
// given
Parent parent = parentRepository.save(Parent.builder().name("parent name").build());
// when
Child child = childRepository.save(Child.builder().content("child content").parent(parent).build());
parent.setChild(child);
// then
assertThat(child).isNotNull();
System.out.println(parent.toString());
System.out.println(child.toString());
parentRepository.flush();
childRepository.flush();
}
@Test
public void testParent() {
// given
long id = 1L;
// when
Optional<Parent> parent = parentRepository.findById(id);
// then
assertThat(parent.isPresent()).isTrue();
parent.ifPresent(p -> {
Child child = p.getChild();
assertThat(child).isNotNull();
System.out.println(p.toString());
});
}
}
|
package br.com.utfpr.eventos.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
import br.com.utfpr.eventos.models.Cart;
@Repository
@Transactional
public class CartDAO {
@PersistenceContext
private EntityManager manager;
public void insert(Cart cartItem){
manager.persist(cartItem);
}
public int remove(int id){
return manager.createQuery("delete from Cart c where c.id = :id")
.setParameter("id", id)
.executeUpdate();
}
public List<Cart> getAllFromUser(String email){
return manager
.createQuery("select c from Cart c where c.userEmail = :email AND c.status = :status", Cart.class)
.setParameter("email", email)
.setParameter("status", "C")
.getResultList();
}
public Cart getByUserAndId(int id, String email) {
return manager
.createQuery("select c from Cart c where c.userEmail = :email AND c.idEvent = :idEvent AND c.status = :status", Cart.class)
.setParameter("email", email)
.setParameter("idEvent", id)
.setParameter("status", "C")
.getResultList().get(0);
}
public int updateStatus(int id) {
return manager
.createQuery("update Cart c set c.status = :status where c.id = :id")
.setParameter("status", "P")
.setParameter("id", id)
.executeUpdate();
}
public List<Cart> getByUserAndStatus(String email, String status) {
return manager
.createQuery("select c from Cart c where c.userEmail = :email AND c.status = :status", Cart.class)
.setParameter("email", email)
.setParameter("status", status)
.getResultList();
}
public List<Cart> getById(int id) {
return manager
.createQuery("select c from Cart c where c.idEvent = :id", Cart.class)
.setParameter("id", id)
.getResultList();
}
}
|
/**
* Created on 2020/3/30.
*
* @author ray
*/
public class LastRemaining {
public static int lastRemaining(int n, int m) {
int idx = 0;
for (int i = 2; i <= n; i++) {
idx = (idx + m) % i;
}
return idx;
}
public static void main(String[] args) {
System.out.println(lastRemaining(10, 17));
}
}
|
package com.inter;
public class ICircle implements IShape{
int r;
public ICircle(int r) {
this.r = r;
}
@Override
public double getArea() {
return Math.PI*r*r;
}
@Override
public double getCircum() {
return 2*Math.PI*r;
}
}
|
package Loja;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class lojaTeste
{
public static void main(String[] args)
{
Scanner leia = new Scanner(System.in);
Calendar data = Calendar.getInstance();
Collection <String >produtosEstoque = new ArrayList();
int anoNascimento, quantidadeVenda;
int numeroNotaFiscal = 1994062100;
int numeroCodigoBarras = 2020271100;
char generoCliente, opcaoContinuar='S', opcaoVoltarMenuInicial ='S', opcaoMenuInicial='S', adicionarNoCarrinho, formaPagamento, opcaoMenuFuncionario;
String nomeCliente, cpfCliente, escolhaDisco, nomeFuncionario, codigoFuncionario;
int tamanhoLinha = 80;
int anoAtual = data.get(Calendar.YEAR);
double subTotal=0, totalCompra = 0;
List<Produto> listaProdutos = new ArrayList();
List<Produto> carrinho = new ArrayList();
listaProdutos.add(new Produto("Ac/Dc - Let There Be Rock","LP001",200, 10));
listaProdutos.add(new Produto("Childish Gambino - Because the Internet","LP002",170, 10));
listaProdutos.add(new Produto("Djavan - Vesuvio","LP003",110, 10));
listaProdutos.add(new Produto("Gorillaz - Gorillaz","LP004",170, 10));
listaProdutos.add(new Produto("Metallica - Ride The Lightning ","LP005",200, 10));
listaProdutos.add(new Produto("Milton Nascimento - Clube da Esquina 1","LP006",200, 10));
listaProdutos.add(new Produto("Queen - The Works","LP007",220, 10));
listaProdutos.add(new Produto("Raimundos - Raimundos","LP008",100, 10));
listaProdutos.add(new Produto("Tim Maia - Tim Maia 1973","LP009",110, 10));
listaProdutos.add(new Produto("System of a Down - Toxicity","LP010",150, 10));
do
{
linha(tamanhoLinha);
System.out.println("\n\t\t\tMcFly - Discos de Vinil");
linha(tamanhoLinha);
System.out.println("\n[1] - COMPRAR PRODUTOS\n[2] - CONTROLE DE PRODUTOS\n[3] - SAIR");
System.out.print("\nDigite a opção desejada: ");
opcaoMenuInicial = leia.next().charAt(0);
linha(tamanhoLinha);
totalCompra = 0;
carrinho.clear();
if (opcaoMenuInicial == '1')
{
System.out.println("\nCadastro Necessario para Compra.\nPreencha com as informações necessarias:");
System.out.print("Nome: ");
nomeCliente = leia.next().toUpperCase();
System.out.print("CPF: ");
cpfCliente = leia.next();
System.out.print("Genêro - Digite [F] para Feminino [M] para Masculino [O] para Outro: ");
generoCliente = leia.next().toUpperCase().charAt(0);
System.out.print("Ano de nascimento: ");
anoNascimento = leia.nextInt();
Cliente clienteTeste = new Cliente(nomeCliente, generoCliente, anoNascimento, cpfCliente);
clienteTeste.voltaIdade(anoAtual, anoNascimento);
System.out.println();
linha(tamanhoLinha);
do
{
if (clienteTeste.getGenero() == 'M')
{
System.out.printf("\nSeja bem-vindo a McFly Discos Sr. %s.\n", clienteTeste.getNome());
}
else if (clienteTeste.getGenero() == 'F')
{
System.out.printf("\nSeja bem-vinda a McFly Discos Sra. %s.\n", clienteTeste.getNome());
}
else if (clienteTeste.getGenero() == 'O')
{
System.out.printf("\nSeja bem-vindx a McFly Discos Srx. %s.\n", clienteTeste.getNome());
}
linha(tamanhoLinha);
listarProdutos(listaProdutos);
System.out.println();
linha(tamanhoLinha);
System.out.printf("\nDigite o código do disco desejado: ");
escolhaDisco = leia.next().toUpperCase();
System.out.print("Digite a quantidade desejada: ");
quantidadeVenda = leia.nextInt();
//linha(tamanhoLinha);
for (Produto indiceListaProdutos : listaProdutos)
{
if (escolhaDisco.equals(indiceListaProdutos.getCodigoProduto()) && quantidadeVenda <= indiceListaProdutos.getQtdProdutoEstoque()
&& quantidadeVenda > 0)
{
subTotal = indiceListaProdutos.getPrecoUnitario()*quantidadeVenda;
System.out.printf("\nDisco selecionado: %d Unidade(s) - %s\nValor Unitário: R$%.2f - SubTotal: R$%.2f\n",
quantidadeVenda, indiceListaProdutos.getNomeProduto(),indiceListaProdutos.getPrecoUnitario(), subTotal);
System.out.print("\nAdicionar ao carrinho? S/N: " );
adicionarNoCarrinho = leia.next().toUpperCase().charAt(0);
if (adicionarNoCarrinho == 'S')
{
carrinho.add(new Produto(indiceListaProdutos.getNomeProduto(), quantidadeVenda, indiceListaProdutos.getPrecoUnitario()));
indiceListaProdutos.retiraEstoque(quantidadeVenda);
totalCompra+=subTotal;
System.out.printf("\nValor Total no Carrinho: R$%.2f\n",totalCompra);
System.out.print("\nDeseja continuar comprando? S/N: ");
opcaoContinuar = leia.next().toUpperCase().charAt(0);
}
}
else if (escolhaDisco.equals(indiceListaProdutos.getCodigoProduto()) && quantidadeVenda > indiceListaProdutos.getQtdProdutoEstoque())
{
System.out.print("\nQuantidade indisponivel. Deseja selecionar outro produto? S/N: ");
opcaoContinuar = leia.next().toUpperCase().charAt(0);
}
else if (escolhaDisco.equals(indiceListaProdutos.getCodigoProduto()) && quantidadeVenda <= 0)
{
System.out.print("\nQuantidade inválida. Deseja selecionar outro produto? S/N: ");
opcaoContinuar = leia.next().toUpperCase().charAt(0);
}
}
}
while (opcaoContinuar == 'S');
linha (tamanhoLinha);
System.out.println();
System.out.println("\n\t\t\tCARRINHO DE COMPRAS");
System.out.printf("\nQuantidade | Valor Unitário | SubTotal | Produto\n");
linha(tamanhoLinha);
for (Produto indiceCarrinho : carrinho)
{
subTotal = indiceCarrinho.getPrecoUnitario()*indiceCarrinho.getQtdVendida();
System.out.printf("\n %d | R$%.2f | R$%.2f | %s",indiceCarrinho.getQtdVendida(), indiceCarrinho.getPrecoUnitario(),
subTotal, indiceCarrinho.getNomeProduto());
}
System.out.printf("\n\nValor Total da Compra: R$%.2f", totalCompra);
System.out.println();
linha (tamanhoLinha);
numeroNotaFiscal ++;
numeroCodigoBarras ++;
finalizarVenda (totalCompra, clienteTeste.getCpfCliente(), numeroNotaFiscal, numeroCodigoBarras);
}
else if(opcaoMenuInicial == '2')
{
System.out.println("\nAcesso Restrito a Funcionários ");
System.out.print("Digite seu nome: ");
nomeFuncionario = leia.next();
System.out.print("Digite o seu código de funcionário: ");
codigoFuncionario = leia.next();
listarProdutos(listaProdutos);
System.out.println("\n\n[1] - ADICIONAR PRODUTO\n[2] - REMOVER PRODUTO\n[3] - ALTERAR NOME\n"
+ "[4] - ALTERAR PREÇO\n[5] - SAIR");
System.out.print("\nDigite a opção desejada: ");
opcaoMenuFuncionario = leia.next().charAt(0);
}
else if(opcaoMenuInicial == '3')
{
System.out.println("\nObrigado por visitar a McFly Discos. Volte sempre!");
break;
}
System.out.println("\n");
}
while (true);
}
public static void listarProdutos(List<Produto> produtosListados)
{
int tamanhoLinha = 80;
System.out.printf("\nCODIGO | Preço Unit R$ | Estoque | Produto\n");
linha (tamanhoLinha);
for (Produto produtos : produtosListados)
{
System.out.printf("\n %s | %.2f | %d | %s ", produtos.getCodigoProduto(), produtos.getPrecoUnitario(),
produtos.getQtdProdutoEstoque(), produtos.getNomeProduto());
}
}
public static void finalizarVenda (double valorTotalCompra, String cpfCliente, int numeroNotaFiscal, int numeroCodigoBarras)
{
Random sorteia = new Random();
Scanner leia = new Scanner(System.in);
double valorParcelas=0, valorDesconto=0, valorImpostos=0, valorJuros=0, valorFinalCompra=0;
int numeroParcelas, formaPagamento;
System.out.print("\nFORMAS DE PAGAMENTO\n\n[1] - A Vista em Dinheiro - Desconto 10%\n[2] - Débito a Vista\n"
+ "[3] - Crédito a Vista - Juros de 5%\n[4] - Crédito em até 3x - Juros de 10%\nEscolha a opção desejada: ");
formaPagamento = leia.nextInt();
//pagamento a vista em dinheiro
if (formaPagamento == 1)
{
valorDesconto = valorTotalCompra*0.10;
valorJuros = valorTotalCompra*0;
valorImpostos = (valorTotalCompra-valorDesconto+valorJuros)*0.09;
valorFinalCompra = valorTotalCompra-valorDesconto+valorImpostos+valorJuros;
System.out.println("\nCompra realizada com sucesso. Obrigado por escolher a McFly Discos!");
System.out.println("╔══════════════════════════╗");
System.out.printf("║NOTA FISCAL %d ║\n",numeroNotaFiscal);
System.out.println("║ ║ ");
System.out.printf("║CPF: %s ║\n",cpfCliente);
System.out.println("║PAGAMENTO À VISTA-DINHEIRO║");
System.out.printf("║SUBTOTAL: R$%.2f ║\n",valorTotalCompra);
System.out.printf("║DESCONTOS: R$%.2f ║\n",valorDesconto);
System.out.printf("║JUROS: R$%.2f ║\n",valorJuros);
System.out.printf("║IMPOSTOS: R$%.2f ║\n",valorImpostos);
System.out.printf("║VALOR FINAL: R$%.2f ║\n",valorFinalCompra);
System.out.println("║ ║");
System.out.println("║ ║|║|║║║║|║║ ║");
System.out.printf ("║ %d ║\n",numeroCodigoBarras);
System.out.println("╚══════════════════════════╝");
}
//pagamento a vista no Debito
else if (formaPagamento == 2)
{
valorDesconto = valorTotalCompra*0;
valorJuros = valorTotalCompra*0;
valorImpostos = (valorTotalCompra-valorDesconto+valorJuros)*0.09;
valorFinalCompra = valorTotalCompra-valorDesconto+valorImpostos+valorJuros;
System.out.println("\nCompra realizada com sucesso. Obrigado por escolher a McFly Discos!");
System.out.println("╔══════════════════════════╗");
System.out.printf("║NOTA FISCAL %d ║\n",numeroNotaFiscal);
System.out.println("║ ║ ");
System.out.printf("║CPF: %s ║\n",cpfCliente);
System.out.println("║PAGAMENTO À VISTA-DÉBITO ║");
System.out.printf("║SUBTOTAL: R$%.2f ║\n",valorTotalCompra);
System.out.printf("║DESCONTOS: R$%.2f ║\n",valorDesconto);
System.out.printf("║JUROS: R$%.2f ║\n",valorJuros);
System.out.printf("║IMPOSTOS: R$%.2f ║\n",valorImpostos);
System.out.printf("║VALOR FINAL: R$%.2f ║\n",valorFinalCompra);
System.out.println("║ ║");
System.out.println("║ ║|║|║║║║|║║ ║");
System.out.printf ("║ %d ║\n",numeroCodigoBarras);
System.out.println("╚══════════════════════════╝");
}
//pagamento a vista no Crédito
else if (formaPagamento == 3)
{
valorDesconto = valorTotalCompra*0;
valorJuros = valorTotalCompra*0.05;
valorImpostos = (valorTotalCompra-valorDesconto+valorJuros)*0.09;
valorFinalCompra = valorTotalCompra-valorDesconto+valorImpostos+valorJuros;
System.out.println("\nCompra realizada com sucesso. Obrigado por escolher a McFly Discos!");
System.out.println("╔══════════════════════════╗");
System.out.printf("║NOTA FISCAL %d ║\n",numeroNotaFiscal);
System.out.println("║ ║ ");
System.out.printf("║CPF: %s ║\n",cpfCliente);
System.out.println("║PAGAMENTO À VISTA-CRÉDITO ║");
System.out.printf("║SUBTOTAL: R$%.2f ║\n",valorTotalCompra);
System.out.printf("║DESCONTOS: R$%.2f ║\n",valorDesconto);
System.out.printf("║JUROS: R$%.2f ║\n",valorJuros);
System.out.printf("║IMPOSTOS: R$%.2f ║\n",valorImpostos);
System.out.printf("║VALOR FINAL: R$%.2f ║\n",valorFinalCompra);
System.out.println("║ ║");
System.out.println("║ ║|║|║║║║|║║ ║");
System.out.printf ("║ %d ║\n",numeroCodigoBarras);
System.out.println("╚══════════════════════════╝");
}
//pagamento parcelado
else if (formaPagamento == 4)
{
do {
System.out.print("Digite o número de parcelas que deseja dividir: ");
numeroParcelas = leia.nextInt();
//pagamento em 2x
if (numeroParcelas == 2)
{
valorDesconto = valorTotalCompra*0;
valorJuros = valorTotalCompra*0.05;
valorImpostos = (valorTotalCompra-valorDesconto+valorJuros)*0.09;
valorFinalCompra = valorTotalCompra-valorDesconto+valorImpostos+valorJuros;
valorParcelas = valorFinalCompra/numeroParcelas;
System.out.println("\nCompra realizada com sucesso. Obrigado por escolher a McFly Discos!");
System.out.println("╔══════════════════════════╗");
System.out.printf("║NOTA FISCAL %d ║\n",numeroNotaFiscal);
System.out.println("║ ║ ");
System.out.printf("║CPF: %s ║\n",cpfCliente);
System.out.println("║PAGAMENTO PARCELADO-2X ║");
System.out.printf("║SUBTOTAL: R$%.2f ║\n",valorTotalCompra);
System.out.printf("║DESCONTOS: R$%.2f ║\n",valorDesconto);
System.out.printf("║JUROS: R$%.2f ║\n",valorJuros);
System.out.printf("║IMPOSTOS: R$%.2f ║\n",valorImpostos);
System.out.printf("║PARCELAS: R$%.2f ║\n",valorParcelas);
System.out.printf("║VALOR FINAL: R$%.2f ║\n",valorFinalCompra);
System.out.println("║ ║");
System.out.println("║ ║|║|║║║║|║║ ║");
System.out.printf ("║ %d ║\n",numeroCodigoBarras);
System.out.println("╚══════════════════════════╝");
break;
}
//pagamento em 2x
else if (numeroParcelas == 3)
{
valorDesconto = valorTotalCompra*0;
valorJuros = valorTotalCompra*0.05;
valorImpostos = (valorTotalCompra-valorDesconto+valorJuros)*0.09;
valorFinalCompra = valorTotalCompra-valorDesconto+valorImpostos+valorJuros;
valorParcelas = valorFinalCompra/numeroParcelas;
System.out.println("\nCompra realizada com sucesso. Obrigado por escolher a McFly Discos!");
System.out.println("╔══════════════════════════╗");
System.out.printf("║NOTA FISCAL %d ║\n",numeroNotaFiscal);
System.out.println("║ ║ ");
System.out.printf("║CPF: %s ║\n",cpfCliente);
System.out.println("║PAGAMENTO PARCELADO-3X ║");
System.out.printf("║SUBTOTAL: R$%.2f ║\n",valorTotalCompra);
System.out.printf("║DESCONTOS: R$%.2f ║\n",valorDesconto);
System.out.printf("║JUROS: R$%.2f ║\n",valorJuros);
System.out.printf("║IMPOSTOS: R$%.2f ║\n",valorImpostos);
System.out.printf("║PARCELAS: R$%.2f ║\n",valorParcelas);
System.out.printf("║VALOR FINAL: R$%.2f ║\n",valorFinalCompra);
System.out.println("║ ║");
System.out.println("║ ║|║|║║║║|║║ ║");
System.out.printf ("║ %d ║\n",numeroCodigoBarras);
System.out.println("╚══════════════════════════╝");
break;
}
else if (numeroParcelas > 3 || numeroParcelas <=1)
{
System.out.println("Numero de parcelas indisponivel.");
}
}
while (true);
}
}
static void linha(int tamanho)
{
for (int x = 1; x <= tamanho; x++) {
System.out.print("—");
}
}
}
|
package com.tencent.mm.modelvoiceaddr.ui;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
class VoiceSearchLayout$3 implements OnErrorListener {
final /* synthetic */ VoiceSearchLayout erE;
final /* synthetic */ a erF = null;
VoiceSearchLayout$3(VoiceSearchLayout voiceSearchLayout) {
this.erE = voiceSearchLayout;
}
public final boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
return false;
}
}
|
package com.kindy.common;
public class Constants {
public static String InputValidNumber="请输入有效的1-4的数字";
public static String TabDelimiter=" ";
}
|
public class Main {
// public static void main(String[] args) throws InterruptedException {
// Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
//
// Thread thread1 = new Thread(() -> {
// Thread currentThread = Thread.currentThread();
// System.out.println(currentThread.getName() + " priority = " + currentThread.getPriority());
// });
//
// thread1.setName("Thread_1");
// thread1.setPriority(Thread.MAX_PRIORITY);
//
// Thread thread2 = new Thread(() -> {
// Thread currentThread = Thread.currentThread();
// System.out.println(currentThread.getName() + " priority = " + currentThread.getPriority());
// });
//
// thread2.setName("Thread_2");
// thread2.setPriority(Thread.MIN_PRIORITY);
//
// thread1.start();
// thread2.start();
//
// thread1.join();
// thread2.join();
// }
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
Thread currentThread = Thread.currentThread();
System.out.println("[1] State: " + currentThread.getState());
});
System.out.println("[2] State: " + thread.getState());
thread.start();
System.out.println("[3] State: " + thread.getState());
thread.join();
System.out.println("[4] State: " + thread.getState());
}
}
|
package enthu_l;
class NewException extends Exception {
}
class AnotherException extends Exception {
}
public class e_1006 {
public static void main(String [] args) throws Exception{
try{
m2();}
finally{ m3(); }}
public static void m2() throws NewException{throw new NewException();}
public static void m3() throws AnotherException{throw new AnotherException();}
}
|
package com.tencent.mm.plugin.backup.backuppcmodel;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import com.jg.EType;
import com.jg.JgClassChecked;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.backup.a.d;
import com.tencent.mm.plugin.backup.bakoldlogic.bakoldmodel.BakOldUSBService;
import com.tencent.mm.plugin.backup.f.e;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa.a;
@JgClassChecked(author = 20, fComment = "checked", lastDate = "20140422", reviewer = 20, vComment = {EType.SERVICESCHECK})
public class BackupPcService extends Service {
private boolean fTW = false;
private boolean gWY = false;
public void onCreate() {
x.i("MicroMsg.BackupPcService", "onCreate.");
super.onCreate();
}
public int onStartCommand(Intent intent, int i, int i2) {
x.i("MicroMsg.BackupPcService", "onStartCommand.");
if (intent == null) {
x.w("MicroMsg.BackupPcService", "onStartCommand intent is null");
} else {
final String stringExtra = intent.getStringExtra("url");
if (bi.oW(stringExtra)) {
x.e("MicroMsg.BackupPcService", "onStartCommand url is null");
stopSelf();
} else if (stringExtra.contains("mm.gj.qq.com")) {
x.i("MicroMsg.BackupPcService", "onStartCommand url from gj stop and start BakOldUSBService");
startService(new Intent(this, BakOldUSBService.class).putExtra("url", intent.getStringExtra("url")).putExtra("isFromWifi", true));
stopSelf();
} else {
this.gWY = intent.getBooleanExtra("isFromWifi", false);
this.fTW = intent.getBooleanExtra("isMove", false);
x.i("MicroMsg.BackupPcService", "onStartCommand Broadcast url:%s, isFromWifi:%b, isMove:%b", new Object[]{stringExtra, Boolean.valueOf(this.gWY), Boolean.valueOf(this.fTW)});
if (this.fTW || au.HW()) {
ah.A(new Runnable() {
public final void run() {
c arW = b.arV().arW();
x.w("MicroMsg.BackupPcProcessMgr", "~~~~~~~~~~~~ start by url:%s", new Object[]{stringExtra});
d.mx(1);
au.HU();
arW.gWC = ((Integer) c.DT().get(a.sUX, Integer.valueOf(0))).intValue();
b.arV();
Editor edit = b.aqU().edit();
edit.putInt("BACKUP_PC_CHOOSE_SELECT_TIME_MODE", 0);
edit.putInt("BACKUP_PC_CHOOSE_SELECT_CONTENT_TYPE", 0);
edit.putLong("BACKUP_PC_CHOOSE_SELECT_START_TIME", 0);
edit.putLong("BACKUP_PC_CHOOSE_SELECT_END_TIME", 0);
edit.commit();
arW.gWD = true;
au.DF().a(595, arW.gUj);
au.DF().a(new e(r2), 0);
}
});
} else {
x.e("MicroMsg.BackupPcService", "onStartCommand onStartCommand not in Login state");
Intent className = new Intent().setClassName(this, "com.tencent.mm.ui.LauncherUI");
className.addFlags(335544320);
className.putExtra("nofification_type", "back_to_pcmgr_notification");
startActivity(className);
}
}
}
return 2;
}
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
super.onDestroy();
x.i("MicroMsg.BackupPcService", "onDestroy thread:" + Thread.currentThread().getName());
}
}
|
package com.google.android.exoplayer2.i;
public interface b {
public static final b aBU = new p();
long elapsedRealtime();
}
|
package com.ArcLancer.Test.Hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static final SessionFactory SESSION_FACTORY = buildSessionFactory();
private static SessionFactory buildSessionFactory() throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.addResource("TestEntity.hbm.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
// Create the SessionFactory from hibernate.cfg.xml
return configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactory() throws HibernateException {
return SESSION_FACTORY;
}
}
|
package com.mondia.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Entity
@Table(name = "role")
@Data
@ToString
@EqualsAndHashCode(callSuper = false)
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
String name;
Role() {}
public Role(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.paleimitations.schoolsofmagic.client.data;
import com.paleimitations.schoolsofmagic.common.data.books.BookPage;
import com.paleimitations.schoolsofmagic.common.data.books.PageElement;
import com.paleimitations.schoolsofmagic.common.data.books.ParagraphsPageElement;
import com.paleimitations.schoolsofmagic.common.registries.BookPageRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.IResource;
import net.minecraft.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.resource.IResourceType;
import net.minecraftforge.resource.ISelectiveResourceReloadListener;
import net.minecraftforge.resource.VanillaResourceType;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
public enum BookTextManager implements ISelectiveResourceReloadListener {
INSTANCE;
private IResourceManager manager;
private final Map<ResourceLocation, IResource> cache = new HashMap<>();
@Nullable
@Override
public IResourceType getResourceType() {
return VanillaResourceType.LANGUAGES;
}
@Override
public void onResourceManagerReload(IResourceManager resourceManager, Predicate<IResourceType> resourcePredicate) {
if (resourcePredicate.test(getResourceType())) {
onResourceManagerReload(resourceManager);
}
}
@Override
public void onResourceManagerReload(IResourceManager resourceManager) {
System.out.println("Book Text reloaded");
this.manager = resourceManager;
cache.clear();
loadText();
}
public IResource loadTextFile(ResourceLocation fileLoc, ResourceLocation backupLoc) {
if(this.manager==null) {
this.manager = Minecraft.getInstance().getResourceManager();
}
if(cache.containsKey(fileLoc))
return cache.get(fileLoc);
else {
IResource resource = null;
try {
resource = this.manager.getResource(fileLoc);
} catch (IOException e) {
e.printStackTrace();
}
if(resource!=null)
return resource;
}
if(cache.containsKey(backupLoc))
return cache.get(backupLoc);
else {
IResource resource = null;
try {
resource = this.manager.getResource(backupLoc);
} catch (IOException e) {
e.printStackTrace();
}
return resource;
}
}
public static void loadText() {
for(BookPage page : BookPageRegistry.PAGES){
for(PageElement element : page.elements)
if(element instanceof ParagraphsPageElement)
((ParagraphsPageElement)element).loadText();
}
}
public static void loadText(BookPage page) {
for(PageElement element : page.elements)
if(element instanceof ParagraphsPageElement)
((ParagraphsPageElement)element).loadText();
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import com.google.common.base.Charsets;
/**
* Calculate the support and confidence given in input the file, this is the
* first analysis for the Apriori algorithm. Please set correctly the
* NumberOfLinesInFile variable, for a rule of this kind p1 -> p2 it calculate
* X->Y => frequency ( x and y ) / NumberOfLinesInFile ; frequency ( x and y ) / frequency ( x)
* the support and the confidence of the rule
*
* @author francescotangari
*
*/
public class MarketBasketSupportConfidence {
public final static float NumberOfLinesInFile = 18;
public static class TokenizerMapper extends Mapper<Object, Text, Text, Text> {
private static Text one = new Text("1");
private Text KeyPair = new Text();
private Text FreqItem = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] split = line.split(",");
// String[] getMonth = split[0].split("-");
// String month = getMonth[0] + "-" + getMonth[1];
for (int i = 1; i < split.length; i++) {
for (int j = i + 1; j < split.length; j++) {
KeyPair.set("rule:" +split[i] + "," + split[j]);
context.write(KeyPair, one);
}
FreqItem.set("fq:" + split[i]);
context.write(FreqItem , one);
}
}
}
private static class Combine extends Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int count = 0;
for (Text value : values) {
count += Integer.parseInt(value.toString());
}
context.write(key, new Text(String.valueOf(count)));
}
}
public static class IntSumReducer extends Reducer<Text, Text, Text, Text> {
private Text result = new Text();
private Text resultfq = new Text();
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String keyStr = key.toString();
if(keyStr.contains("fq:")){
int sum = 0;
for (Text val : values) {
sum = sum + Integer.parseInt(val.toString());
}
resultfq = new Text(String.valueOf(sum));
context.write(key, resultfq);
}
else {
float sum = 0;
float sum2 = 0;
float freqRule = 0;
for (Text val : values) {
sum = sum + Integer.parseInt(val.toString());
sum2 = sum2 + Integer.parseInt(val.toString());
}
sum = (float) ((float)sum / NumberOfLinesInFile)*100;
freqRule = (float) ((float)sum2);
result = new Text(String.valueOf(sum) + "-" +freqRule);
context.write(key, result);
}
}
}
private static void readAndCalcConf(Path path, Configuration conf)
throws IOException {
FileSystem fs = FileSystem.get(conf);
Path file = new Path(path, "part-r-00000");
HashMap<String,Float> h = new HashMap<String,Float>();
if (!fs.exists(file))
throw new IOException("Output not found!");
BufferedReader br = null;
// average = total sum / number of elements;
try {
br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8));
float frequencyItem = 0;
float supportRule = 0;
long confidence = 0;
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
// grab type
String type = st.nextToken();
// differentiate
if (type.equals("rule:".toString())) {
String rule = st.nextToken();
supportRule = Long.parseLong(rule);
float freq = (float) h.get(rule.split(",")[0].replace("rule:",""));
confidence = (long) (((supportRule/100) * NumberOfLinesInFile) / freq);
System.out.println("Confidence: " + confidence);
} else {
String item = st.nextToken();
frequencyItem = Long.parseLong(item);
h.put(item.split("fq:")[1], (float) frequencyItem);
}
}
} finally {
if (br != null) {
br.close();
}
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length < 2) {
System.err.println("Usage: <in> [<in>...] <out>");
System.exit(2);
}
Job job = Job.getInstance(conf, "count");
job.setJarByClass(MarketBasketMostSoldPerMonth.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(Combine.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
for (int i = 0; i < otherArgs.length - 1; ++i) {
FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
}
FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1]));
Path outputpath = new Path(args[1]);
readAndCalcConf(outputpath,conf);
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
package br.com.pcmaker.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import br.com.pcmaker.common.util.StringUtils;
import br.com.pcmaker.entity.Equipamento;
import br.com.pcmaker.service.CrudService;
import br.com.pcmaker.service.EquipamentoService;
@RestController
@RequestMapping("/equipamento")
public class EquipamentoController extends CrudController<Equipamento>{
@Autowired
EquipamentoService service;
@Override
public CrudService<Equipamento> getService() {
return service;
}
@RequestMapping(method = RequestMethod.GET)
public List<Equipamento> query(@RequestParam(required=false, defaultValue="") String nome) {
return service.query(StringUtils.decode(nome));
}
}
|
package com.company;
public class Animal extends AnimalComponent
{
private String animalName;
public Animal(String animalName)
{
this.animalName = animalName;
}
@Override
public String getAnimalName()
{
return animalName;
}
public void displayAnimalInformation()
{
System.out.println("Animal name: " + getAnimalName());
}
}
|
package actions.gameoflife;
import java.util.ArrayList;
import actions.Action;
import javafx.scene.paint.Color;
import util.Cell;
import util.Grid;
public class GameLife extends Action {
private static final Color ALIVE = Color.BLACK;
private static final Color DEAD = Color.WHITE;
@Override
public void execute(Cell cell, Grid grid) {
ArrayList<Cell> neighbours = grid.getNeighbours(cell);
int aliveNeighbors = 0;
for (Cell neighbour : neighbours) {
if (neighbour != null && neighbour.getFill() == ALIVE) aliveNeighbors++;
}
update(cell, aliveNeighbors);
}
/**
* Decides whether a cell should live or die
* @param cell
* @param aliveNeighbors
*/
private void update(Cell cell, int aliveNeighbors) {
if (cell.getFill() == ALIVE) {
if (aliveNeighbors < 2 || aliveNeighbors > 3) {
cell.setFill(DEAD);
}
} else if (aliveNeighbors == 3) {
cell.setFill(ALIVE);
}
}
}
|
package za.co.edusys.domain.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
import java.util.List;
import java.util.Set;
/**
* Created by marc.marais on 2017/02/10.
*/
@Entity
public class School {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
boolean enabled;
@OneToMany(mappedBy = "school")
Set<User> userList;
@OneToMany(mappedBy = "school")
Set<Term> termList;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass = Grade.class)
@CollectionTable(name = "schoolgrade", joinColumns = @JoinColumn(name = "school_id"))
@Enumerated(EnumType.STRING)
List<Grade> grades;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass = Subject.class)
@CollectionTable(name = "schoolsubject", joinColumns = @JoinColumn(name = "school_id"))
@Enumerated(EnumType.STRING)
List<Subject> subjects;
public School(){}
public School(String name, boolean enabled, List<Grade> grades, List<Subject> subjects) {
this.name = name;
this.enabled = enabled;
this.grades = grades;
this.subjects = subjects;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<User> getUserList() {
return userList;
}
public void setUserList(Set<User> userList) {
this.userList = userList;
}
public List<Grade> getGrades() {
return grades;
}
public void setGrades(List<Grade> grades) {
this.grades = grades;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public Set<Term> getTermList() {
return termList;
}
public void setTermList(Set<Term> termList) {
this.termList = termList;
}
}
|
package com.example.testapp.utils.http;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class HttpUtils {
private static HttpUtils instance=null;
private HttpUtils(){};
private final static String ROOT_URL="http://192.168.0.104:8080/";
public static HttpUtils getInstance(){
if(instance==null){
instance=new HttpUtils();
}
return instance;
}
public <T> T getHttpClient(Class<T> cls){
return (T)getRetrofit(ROOT_URL).create(cls);
}
private Retrofit getRetrofit(String url){
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit;
}
}
|
package ba.bitcamp.LabS12D01;
public class MatrixAdd {
public static void main(String[] args) {
int[][] matrix1 = new int[10][10];
int[][] matrix2 = new int[10][10];
filMatrix(matrix1);
filMatrix(matrix2);
System.out.println("matrix 1");
printMatrix(matrix1);
System.out.println("********************");
System.out.println("matrix 2");
printMatrix(matrix2);
System.out.println("********************");
System.out.println("matrix 3");
int[][] matrix3 = addMatrix(matrix1, matrix2);
printMatrix(matrix3);
}
private static int[][] addMatrix(int[][] matrix1, int[][] matrix2) {
int[][] matrix = new int[10][10];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return matrix;
}
private static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
System.out.printf("%4d ", matrix[i][j]);
}
System.out.println();
}
}
private static void filMatrix(int[][] matrix) {
int num = 1;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = num;
num++;
}
}
}
}
|
package net.sssanma.mc.custommobs;
import net.minecraft.server.v1_7_R4.*;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;
public class BossGiantZombie extends EntityGiantZombie implements Boss {
private HashMap<UUID, Float> damageCounter = new HashMap<>();
private float takenDamage;
public BossGiantZombie(World world) {
super(world);
getAttributeInstance(GenericAttributes.maxHealth).setValue(200);
setHealth(200);
}
@Override
public boolean damageEntity(DamageSource damagesource, float f) {
// 窒息死/ポーションダメージは無視!!
if (damagesource == DamageSource.STUCK || damagesource == DamageSource.MAGIC) return false;
float beforeHealth = getHealth();
boolean isEnable = super.damageEntity(damagesource, f);
ECustomMob.damageEntity(damagesource, this, beforeHealth, getHealth());
if (damagesource instanceof EntityDamageSourceIndirect) {
EntityDamageSourceIndirect indirectSrc = (EntityDamageSourceIndirect) damagesource;
if (indirectSrc.getProximateDamageSource() instanceof EntityArrow && ((EntityArrow) indirectSrc.getProximateDamageSource()).shooter instanceof EntityHuman) {
Player player = (Player) ((EntityHuman) ((EntityArrow) indirectSrc.getProximateDamageSource()).shooter).getBukkitEntity();
if (getBukkitEntity().getLocation().distance(player.getLocation()) > 8) {
player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 400, 1));
world.getWorld().spawnEntity(player.getLocation(), EntityType.CREEPER);
}
}
}
return isEnable;
}
@Override
public float getAllTakenDamage() {
return takenDamage;
}
@Override
public void setAllTakenDamage(float takenDamage) {
this.takenDamage = takenDamage;
}
@Override
public HashMap<UUID, Float> getAttackers() {
return damageCounter;
}
@Override
public int getDropPoint() {
return (int) (getMaxHealth() * 10);
}
@Override
public String getDyingMessage() {
return ChatColor.GRAY + "[ジャイアント]ぐぉっ…ごふごふ…";
}
@Override
public int getExpReward() {
return 0;
}
@Override
public EntityLiving getLivingEntity() {
return this;
}
@Override
public String getSpawnMessage() {
return ChatColor.GRAY + "[ジャイアント]ぐぁぁぁ!!";
}
@Override
public void heal(float f, RegainReason regainReason) {
if (regainReason == RegainReason.MAGIC || regainReason == RegainReason.MAGIC_REGEN) return;
super.heal(f, regainReason);
}
@Override
public void C() {
if (ticksLived % 80 == 0) {
List<org.bukkit.entity.Entity> nearby = getBukkitEntity().getNearbyEntities(15, 5, 15);
if (!(nearby.size() >= 30)) {
Random rnd = new Random();
for (int ttttt = 0; ttttt < 7; ttttt++) {
double plusPosX, plusPosZ;
plusPosX = (rnd.nextInt(4000) - rnd.nextInt(4000)) / 1000D;
plusPosZ = (rnd.nextInt(4000) - rnd.nextInt(4000)) / 1000D;
double x = locX - plusPosX;
double y = locY;
double z = locZ - plusPosZ;
Location loc = new Location(world.getWorld(), x, y, z);
Material blockType = loc.getBlock().getType();
if (blockType != Material.AIR && blockType != Material.WATER && blockType != Material.STATIONARY_WATER && blockType != Material.LAVA && blockType != Material.STATIONARY_LAVA) {
continue;
}
EntityCreature newent = null;
switch (rnd.nextInt(6)) {
case 0:
newent = new EntityCreeper(world);
break;
case 1:
newent = new EntitySkeleton(world);
newent.setEquipment(0, new ItemStack(Items.BOW));
break;
case 2:
newent = new EntitySpider(world);
break;
case 3:
newent = new EntityZombie(world);
break;
case 4:
newent = new EntityEnderman(world);
break;
case 5:
newent = new EntityCaveSpider(world);
break;
default:
newent = new EntityZombie(world);
}
newent.setPosition(x, y, z);
newent.target = this.target;
newent.getBukkitEntity().getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 4);
world.addEntity(newent, SpawnReason.CUSTOM);
}
}
}
if (ticksLived % 20 == 0) world.getWorldData().setDayTime(14000);
super.C();
}
}
|
package com.hesoyam.pharmacy.util.report;
import java.util.List;
public class ReportResult {
List<String> labels;
List<Double> data;
public ReportResult(List<String> labels, List<Double> data) {
this.labels = labels;
this.data = data;
}
public List<String> getLabels() {
return labels;
}
public List<Double> getData() {
return data;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.