text stringlengths 10 2.72M |
|---|
package hu.mitro.web.servlet.contractservlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import hu.mitro.ejb.domain.CarStub;
import hu.mitro.ejb.domain.ClientStub;
import hu.mitro.ejb.domain.ContractStub;
import hu.mitro.ejb.exception.FacadeLayerException;
import hu.mitro.ejb.facade.CarFacade;
import hu.mitro.ejb.facade.ClientFacade;
import hu.mitro.ejb.facade.ContractFacade;
@WebServlet("/CreateContractBefore")
public class CreateContractBeforeServlet extends HttpServlet {
@EJB
ContractFacade contractFacade;
@EJB
ClientFacade clientFacade;
@EJB
CarFacade carFacade;
private static final Logger LOGGER = Logger.getLogger(CreateContractBeforeServlet.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.service(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.service(request, response);
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LOGGER.info("Create a new Contract [servlet].");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
List<ContractStub> contracts = new ArrayList<>();
List<CarStub> cars = new ArrayList<>();
List<ClientStub> clients = new ArrayList<>();
String contractId = "";
try {
cars = carFacade.getAllLeasebleCars();
clients = clientFacade.getAllClients();
contracts = contractFacade.getAllOfContracts();
int contractCounts = contracts.size();
contractId = Integer.toString(Calendar.getInstance().get(Calendar.YEAR)) + "-" + (contractCounts + 1);
request.setAttribute("cars", cars);
request.setAttribute("clients", clients);
request.setAttribute("contractid", contractId);
LOGGER.info("[INFO] The initialization of createcontractform.jsp was successful [servlet].");
} catch (FacadeLayerException e) {
throw new ServletException(
"[ERROR] Error occured during the initialization of createcontractform.jsp [servlet].");
}
RequestDispatcher view = request.getRequestDispatcher("contract/createcontractform.jsp");
view.include(request, response);
out.close();
}
}
|
package com.cs.persistence;
import com.cs.item.PlayerItemId;
/**
* @author Joakim Gottzén
*/
public class NotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public static final String NO_ENTITY_WITH_ID_FOUND = "No entity with id %d found";
public static final String NO_ENTITY_WITH_COMPOUND_ID_FOUND = "No entity with id (%d, %d) found";
public static final String NO_ENTITY_WITH_STATUS_ACTIVE_FOUND = "No entity with status %S found";
public NotFoundException(final Long id) {
super(String.format(NO_ENTITY_WITH_ID_FOUND, id));
}
public NotFoundException(final Status status) {
super(String.format(NO_ENTITY_WITH_STATUS_ACTIVE_FOUND, status));
}
public NotFoundException(final String message) {
super(message);
}
public NotFoundException(final PlayerItemId id) {
super(String.format(NO_ENTITY_WITH_COMPOUND_ID_FOUND, id.getPlayer().getId(), id.getItem().getId()));
}
}
|
// Copyright 2019 The Cloud Robotics Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.cloudrobotics.tokenvendor;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import com.cloudrobotics.framework.HttpServerTestRule;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
/** Tests of {@link PublicKeyPublishHandler}. */
@RunWith(JUnitParamsRunner.class)
public class PublicKeyPublishHandlerTest {
private static final String PEM_CONTENT_TYPE = "application/x-pem-file";
private static final String PUBLIC_KEY_PEM =
"-----BEGIN PUBLIC KEY-----\n"
+ "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAID64aLO4Gui+Z3uRL0iu/zO6H+b6/jMGPcf"
+ "Gav4Xk5SS8wNEciSwT80Bbu5p2cBFcTHmnsaVhbgfkaeWefEiGcCAwEAAQ=="
+ "\n-----END PUBLIC KEY-----";
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock private PublicKeyPublisher publicKeyPublisher;
@Rule public HttpServerTestRule server = new HttpServerTestRule();
@Before
public void setUp() {
server.setHandler(new PublicKeyPublishHandler(publicKeyPublisher));
}
@Test
public void returnsOkOnCorrectRequest() throws IOException {
HttpURLConnection request = postRequestWithQuery("?device-id=my-robot");
setRequestBody(request, PEM_CONTENT_TYPE, PUBLIC_KEY_PEM);
sendRequest(request);
assertThat(request.getResponseCode(), is(HttpURLConnection.HTTP_OK));
}
@Test
public void publishesKeyOnCorrectRequest() throws IOException {
HttpURLConnection request = postRequestWithQuery("?device-id=my-robot");
setRequestBody(request, PEM_CONTENT_TYPE, PUBLIC_KEY_PEM);
sendRequest(request);
verify(publicKeyPublisher)
.publishKey(
DeviceId.of("my-robot"), PublicKeyPem.of(PUBLIC_KEY_PEM, PublicKeyPem.Format.RSA_PEM));
}
@Test
public void returnsErrorOnNonPostRequest() throws IOException {
HttpURLConnection request = requestWithQuery("?device-id=my-robot");
request.setRequestMethod("GET");
sendRequest(request);
assertThat(request.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
assertThat(getBody(request), containsString("This path only supports POST requests"));
}
@Test
@Parameters({"", "?foo=bar", "?device-id"})
public void returnsErrorIfDeviceIdNotSpecified(String query) throws IOException {
HttpURLConnection request = postRequestWithQuery(query);
setRequestBody(request, PEM_CONTENT_TYPE, PUBLIC_KEY_PEM);
sendRequest(request);
assertThat(request.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
assertThat(getBody(request), containsString("Missing query parameter: device-id"));
}
@Test
public void returnsErrorIfRequestHasWrongContentType() throws IOException {
HttpURLConnection request = postRequestWithQuery("?device-id=my-robot");
setRequestBody(request, "application/json", PUBLIC_KEY_PEM);
sendRequest(request);
assertThat(request.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
assertThat(
getBody(request), containsString("Expected content type \"application/x-pem-file\""));
}
@Test
public void returnsErrorIfRequestHasInvalidPublicKey() throws IOException {
HttpURLConnection request = postRequestWithQuery("?device-id=my-robot");
setRequestBody(request, PEM_CONTENT_TYPE, "Not a public key");
sendRequest(request);
assertThat(request.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
assertThat(getBody(request), containsString("has to be specified in PEM format"));
}
private static void sendRequest(HttpURLConnection request) throws IOException {
// Querying any part of the response implicitly sends the request (it should actually be
// sufficient to call URLConnction#connect, but that doesn't seem to work here).
request.getResponseCode();
}
private HttpURLConnection postRequestWithQuery(String query) throws IOException {
HttpURLConnection request = requestWithQuery(query);
request.setDoOutput(true); // Implicitly sets the method to POST
return request;
}
private HttpURLConnection requestWithQuery(String query) throws IOException {
URL url = new URL(server.urlWithPathToHandler() + query);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.setConnectTimeout(1000);
request.setReadTimeout(1000);
return request;
}
private static void setRequestBody(HttpURLConnection request, String contentType, String body)
throws IOException {
request.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType);
OutputStream out = request.getOutputStream();
out.write(body.getBytes(Charsets.UTF_8));
out.flush();
out.close();
}
private static String getBody(HttpURLConnection request) throws IOException {
InputStream body =
request.getResponseCode() == HttpURLConnection.HTTP_OK
? request.getInputStream()
: request.getErrorStream();
return CharStreams.toString(new InputStreamReader(body, Charsets.UTF_8));
}
}
|
package abilities;
import java.io.IOException;
import org.newdawn.slick.SlickException;
import actors.Effect;
import actors.Status;
public class FireballAbility extends Ability {
public FireballAbility(){
onCastEffects = new int[2][2];
onCastEffects[0][0] = Effect.EFFECT_CASTING_ABILITY;
onCastEffects[0][1] = 20;
onCastEffects[1][0] = Effect.EFFECT_WINDED;
onCastEffects[1][1] = 5;
}
@Override
public boolean hasAbilityObject() {
return true;
}
@Override
public AbilityObject instantiateAbilityObject(Status casterStatus)
throws SlickException, IOException {
float[] facingDirection = casterStatus.getFacingDirection();
float initialPositionOffset = 30f;
float casterX = casterStatus.getCenterX();
float casterY = casterStatus.getCenterY();
float startX = casterX + facingDirection[0]*initialPositionOffset;
float startY = casterY + facingDirection[1]*initialPositionOffset;
return new FireballAbilityObject( startX,startY, facingDirection);
}
}
|
package com.adi.interest;
public interface InterestService {
void addInterest(int u_id,int dept_id);
void removeInterest(int u_id,int dept_id);
void showInterest(int u_id);
} |
package com.atlassian.theplugin.idea.config.serverconfig;
import com.atlassian.theplugin.ConnectionWrapper;
import com.atlassian.theplugin.commons.ServerType;
import com.atlassian.theplugin.commons.cfg.JiraServerCfg;
import com.atlassian.theplugin.commons.cfg.ServerCfg;
import com.atlassian.theplugin.commons.cfg.ServerIdImpl;
import com.atlassian.theplugin.commons.cfg.UserCfg;
import com.atlassian.theplugin.commons.jira.IntelliJJiraServerFacade;
import com.atlassian.theplugin.commons.jira.JiraServerData;
import com.atlassian.theplugin.idea.TestConnectionProcessor;
import com.atlassian.theplugin.idea.TestConnectionTask;
import com.atlassian.theplugin.idea.config.serverconfig.util.ServerNameUtil;
import com.atlassian.theplugin.idea.ui.DialogWithDetails;
import com.atlassian.theplugin.idea.util.IdeaUiMultiTaskExecutor;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import org.jetbrains.annotations.NotNull;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.intellij.openapi.ui.Messages.showMessageDialog;
/**
* User: kalamon
* Date: Jul 8, 2009
* Time: 3:03:34 PM
*/
public class JiraStudioConfigDialog extends DialogWrapper {
private final ConfigPanel rootPanel;
private final JTextField serverName;
private final JTextField serverUrl;
private final JTextField userName;
private final JPasswordField password;
private final JCheckBox rememberPassword;
private final JButton testConnection;
private final JCheckBox useDefaultCredentials;
private final DocumentListener documentListener;
private final Project project;
private final ServerTreePanel serverTree;
private final UserCfg defaultUser;
private static final String JIRA_STUDIO_SUFFIX = " (JIRA Studio)";
protected JiraStudioConfigDialog(Project project, ServerTreePanel serverTree,
UserCfg defaultUser, Collection<ServerCfg> servers) {
super(project, false);
this.project = project;
this.serverTree = serverTree;
this.defaultUser = defaultUser;
setTitle("Create JIRA Studio Server");
documentListener = new DocumentListener() {
public void insertUpdate(DocumentEvent documentEvent) {
updateButtons();
}
public void removeUpdate(DocumentEvent documentEvent) {
updateButtons();
}
public void changedUpdate(DocumentEvent documentEvent) {
updateButtons();
}
};
serverName = new JTextField(ServerNameUtil.suggestNewName(servers));
serverName.getDocument().addDocumentListener(documentListener);
serverUrl = new JTextField();
serverUrl.getDocument().addDocumentListener(documentListener);
serverUrl.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent focusEvent) {
serverUrl.getDocument().removeDocumentListener(documentListener);
String url = GenericServerConfigForm.adjustUrl(serverUrl.getText());
serverUrl.setText(url);
serverUrl.getDocument().addDocumentListener(documentListener);
}
});
userName = new JTextField();
password = new JPasswordField();
rememberPassword = new JCheckBox("Remember Password");
testConnection = new JButton("Test Connection");
testConnection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
testServerConnections();
}
});
useDefaultCredentials = new JCheckBox("Use Default Credentials");
useDefaultCredentials.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
boolean enabled = !useDefaultCredentials.isSelected();
userName.setEnabled(enabled);
password.setEnabled(enabled);
rememberPassword.setEnabled(enabled);
}
});
rootPanel = new ConfigPanel();
updateButtons();
init();
}
private final Map<String, Throwable> connectionErrors = new HashMap<String, Throwable>();
private void testServerConnections() {
TestConnectionProcessor processor = new TestConnectionProcessor() {
// kalamon: ok, I know, this counter is lame as hell. But so what,
// it is "the simplest thing that could ever work". And I challenge
// you to invent something more clever that does not result in
// overcomplication of the code
private int counter = 1;
public void setConnectionResult(ConnectionWrapper.ConnectionState result) {
}
public void onSuccess() {
if (counter-- > 0) {
testJiraConnection(this);
} else {
showResultDialog();
}
}
public void onError(String errorMessage, Throwable exception, String helpUrl) {
connectionErrors.put(errorMessage, exception);
if (counter-- > 0) {
testJiraConnection(this);
} else {
showResultDialog();
}
}
};
connectionErrors.clear();
testJiraConnection(processor);
}
private void showResultDialog() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (connectionErrors.size() > 0) {
List<IdeaUiMultiTaskExecutor.ErrorObject> errors = new ArrayList<IdeaUiMultiTaskExecutor.ErrorObject>();
for (String error : connectionErrors.keySet()) {
errors.add(new IdeaUiMultiTaskExecutor.ErrorObject(error, connectionErrors.get(error)));
}
DialogWithDetails.showExceptionDialog(rootPanel, errors);
} else {
showMessageDialog(project, "Connected successfully", "Connection OK", Messages.getInformationIcon());
}
}
});
}
private void testJiraConnection(final TestConnectionProcessor processor) {
JiraServerData.Builder builder = new JiraServerData.Builder(generateJiraServerCfg());
builder.defaultUser(defaultUser);
final Task.Modal testConnectionTask = new TestConnectionTask(project,
new ProductConnector(IntelliJJiraServerFacade.getInstance()),
builder.build(),
processor, "Testing JIRA Connection", true, false, false);
testConnectionTask.setCancelText("Stop");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ProgressManager.getInstance().run(testConnectionTask);
}
});
}
@Override
protected JComponent createCenterPanel() {
return rootPanel;
}
@Override
protected Action[] createActions() {
return new Action[] {
getOKAction(),
getCancelAction()
};
}
@Override
protected void doOKAction() {
serverUrl.getDocument().removeDocumentListener(documentListener);
GenericServerConfigForm.adjustUrl(serverUrl.getText());
generateAllStudioServers();
super.doOKAction();
}
private @NotNull JiraServerCfg generateJiraServerCfg() {
ServerIdImpl idJira = new ServerIdImpl();
String name = serverName.getText().trim() + JIRA_STUDIO_SUFFIX;
JiraServerCfg jira = new JiraServerCfg(true, name, idJira, true, false);
jira.setUrl(serverUrl.getText());
String user = userName.getText();
if (user.length() > 0) {
jira.setUsername(user);
}
jira.setPassword(new String(password.getPassword()));
jira.setPasswordStored(rememberPassword.isSelected());
jira.setUseDefaultCredentials(useDefaultCredentials.isSelected());
return jira;
}
private void generateAllStudioServers() {
serverTree.addNewServerCfg(ServerType.JIRA_SERVER, generateJiraServerCfg());
}
private class ConfigPanel extends JPanel {
private ConfigPanel() {
setLayout(new FormLayout("3dlu, right:pref, 3dlu, fill:pref:grow, right:pref, 3dlu",
"3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu"));
CellConstraints cc = new CellConstraints();
//CHECKSTYLE:MAGIC:OFF
add(new JLabel("Server Name:"), cc.xy(2, 2));
add(serverName, cc.xyw(4, 2, 2));
add(new JLabel("Server URL:"), cc.xy(2, 4));
add(serverUrl, cc.xyw(4, 4, 2));
add(new JLabel("Username:"), cc.xy(2, 6));
add(userName, cc.xyw(4, 6, 2));
add(new JLabel("Password:"), cc.xy(2, 8));
add(password, cc.xyw(4, 8, 2));
add(rememberPassword, cc.xy(4, 10));
add(testConnection, cc.xy(5, 10));
add(useDefaultCredentials, cc.xy(4, 12));
//CHECKSTYLE:MAGIC:ON
}
}
private void updateButtons() {
boolean enabled =
serverName.getText().trim().length() > 0
&& serverUrl.getText().trim().length() > 0;
setOKActionEnabled(enabled);
testConnection.setEnabled(enabled);
}
}
|
package com.citibank.ods.modules.client.ipdocprvt.form;
import com.citibank.ods.modules.client.ipdocprvt.form.BaseIpDocPrvtDetailForm;
/**
* @author l.braga
*
*/
public class IpDocPrvtHistoryDetailForm extends BaseIpDocPrvtDetailForm
implements IpDocPrvtHistoryDetailable
{
// Data e Hora que o Usuario Aprovou o Registro Cadastrado.
private String m_lastAuthDate = "";
// Codigo do Usuario que Aprovou o Cadastro do Registro.
private String m_lastAuthUserId = "";
// Status do RegistroConstraint: 'S' (Ativo), 'N' (Inativo), 'A' (Aguardando
// Aprovacao)
private String m_recStatCode = "";
private String m_ipDocRefDate = "";
/**
* @return Returns m_ipDocRefDate.
*/
public String getIpDocRefDate()
{
return m_ipDocRefDate;
}
/**
* @param ipDocRefDate_ Field m_ipDocRefDate to be setted.
*/
public void setIpDocRefDate( String ipDocRefDate_ )
{
m_ipDocRefDate = ipDocRefDate_;
}
/**
* @return Returns m_lastAuthDate.
*/
public String getLastAuthDate()
{
return m_lastAuthDate;
}
/**
* @param lastAuthDate_ Field m_lastAuthDate to be setted.
*/
public void setLastAuthDate( String lastAuthDate_ )
{
m_lastAuthDate = lastAuthDate_;
}
/**
* @return Returns m_lastAuthUserId.
*/
public String getLastAuthUserId()
{
return m_lastAuthUserId;
}
/**
* @param lastAuthUserId_ Field m_lastAuthUserId to be setted.
*/
public void setLastAuthUserId( String lastAuthUserId_ )
{
m_lastAuthUserId = lastAuthUserId_;
}
/**
* @return Returns m_recStatCode.
*/
public String getRecStatCode()
{
return m_recStatCode;
}
/**
* @param recStatCode_ Field m_recStatCode to be setted.
*/
public void setRecStatCode( String recStatCode_ )
{
m_recStatCode = recStatCode_;
}
/**
* Método da interface IpDocPrvtHistoryDetailable.
*/
public String getSelectedIpDocRefDate()
{
return null;
}
/**
* Método da interface IpDocPrvtHistoryDetailable. Seta a data de referência.
*/
public void setSelectedIpDocRefDate( String ipDocRefDate_ )
{
setIpDocRefDate( ipDocRefDate_ );
}
} |
package org.spmin.customerrewards.services;
import org.spmin.customerrewards.models.Customer;
import org.spmin.customerrewards.models.Transaction;
import java.util.List;
public class PointsService {
// calculate points for an individual transaction and save to that transaction
// Every dollar spent over $100 is worth 2 points
// and every dollar spent over $50 is worth 1 point
static public int calculateTransactionPoints(double transactionAmt) {
int transactionPoints = 0;
if (transactionAmt > 100) {
transactionPoints += 50 + 2 * (Math.floor(transactionAmt) - 100);
} else if (transactionAmt > 50) {
transactionPoints += Math.floor(transactionAmt) - 50;
}
//else do nothing
return transactionPoints;
}
// calculates a customer's rewards points and sums them
static public void calculateCustomerPoints(Customer customer) {
int pointsTotal = 0;
List<Transaction> transactionList = customer.getTransactions();
for(Transaction transaction : transactionList) {
int transactionPoints = PointsService.calculateTransactionPoints(transaction.getTransactionAmount());
transaction.setTransactionPoints(transactionPoints);
pointsTotal += transactionPoints;
}
customer.setRewardsPoints(pointsTotal);
}
}
|
package de.scads.gradoop_service.server.helper.gelly.io;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.Vertex;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.flink.model.api.epgm.LogicalGraph;
public class GradoopToGellyGraph<VV extends Comparable, EV extends Comparable> {
private final Class<VV> protoVertexValue;
private final Class<EV> protoEdgeValue;
public GradoopToGellyGraph(Class<VV> protoVertexValue, Class<EV> protoEdgeValue) {
this.protoVertexValue = protoVertexValue;
this.protoEdgeValue = protoEdgeValue;
}
@SuppressWarnings("unchecked")
public Graph<GradoopId, VV, EV> transform(LogicalGraph graph) {
// Vertex<GradoopId, VV> vertexTypeIdent = new Vertex<>();
// TypeInformation vertexSetType = TypeExtractor.createTypeInfo(vertexTypeIdent.getClass());
// TypeInformation vertexSetType = TypeInformation.of(vertexTypeIdent.getClass());
// TypeInformation vertexSetType = TypeInformation.of(Vertex.class);
// TypeInformation vertexSetType = TypeExtractor.createTypeInfo(Vertex.class, vertexTypeIdent.getClass(), 1, null, null);
DataSet<Vertex<GradoopId, VV>> vertices = graph
.getVertices()
.map(new GenericVertexToGellyVertexMapper<>(protoVertexValue))
// .returns(vertexSetType)
;
// Edge<GradoopId, EV> edgeTypeIdent = new Edge<>();
// TypeInformation edgeSetType = TypeExtractor.createTypeInfo(edgeTypeIdent.getClass());
DataSet<Edge<GradoopId, EV>> edges = graph
.getEdges()
.map(new GenericEdgeToGellyEdgeMapper<>(protoEdgeValue))
// .returns(edgeSetType)
;
return Graph.fromDataSet(vertices, edges, graph.getConfig().getExecutionEnvironment());
}
}
|
package com.psl.training;
import java.util.Scanner;
public class CheckPrimes {
static Scanner scan = new Scanner (System.in);
static boolean isPrimeNumber( int num) {
int i,count=0;
for(i=2;i<=num/2;i++){
if(num%i==0)
count++;
}
if(count<2){
return true;
}
else{
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Number to check if it is Prime or Non Prime :");
int num = scan.nextInt();
boolean isPrime = isPrimeNumber(num);
if(isPrime==true){
System.out.println("Given number is a prime number.");
}
else{
System.out.println("Given number is not a prime number.");
}
}
}
|
package com.hfjy.framework.net.http;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hfjy.framework.common.util.ClassUtil;
import com.hfjy.framework.common.util.StringUtils;
import com.hfjy.framework.logging.LoggerFactory;
import com.hfjy.framework.net.http.entity.ControllerConfig;
import com.hfjy.framework.net.http.entity.ControllerContext;
import com.hfjy.framework.net.http.entity.DefaultControllerConfig;
import com.hfjy.framework.net.http.entity.ControllerDataChecker;
import com.hfjy.framework.net.http.entity.RequestMethod;
import com.hfjy.framework.net.http.processor.ControllerProcessor;
import com.hfjy.framework.net.util.Constant;
@MultipartConfig
public class CentralController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CentralController.class);
private ControllerProcessor controllerProcessor;
private ControllerDataChecker httpDataCheckers;
@Override
public final void init(ServletConfig initConfig) throws ServletException {
logger.info("init begin");
String className = initConfig.getInitParameter(Constant.CONTROLLER_INIT_CLASS_KEY);
if (className == null) {
logger.warn(StringUtils.unite("init parameter ", Constant.CONTROLLER_INIT_CLASS_KEY, " no configuration"));
} else {
logger.info(StringUtils.unite("init parameter ", Constant.CONTROLLER_INIT_CLASS_KEY, " configure ", className));
}
ControllerConfig config = (ControllerConfig) ClassUtil.newInstance(className);
if (config == null) {
logger.warn(StringUtils.unite("controller config ", className, " init error use the default configuration"));
config = new DefaultControllerConfig();
}
controllerProcessor = new ControllerProcessor(config);
httpDataCheckers = config.getDataChecker();
logger.info(StringUtils.unite("controller config is ", config.getClass()));
logger.info(StringUtils.unite("controller data checker is ", httpDataCheckers == null ? null : httpDataCheckers.getClass()));
logger.info(StringUtils.unite("controller encoding is ", config.getCharacterEncoding()));
logger.info(StringUtils.unite("controller return string prefix is ", config.getPrefix()));
logger.info(StringUtils.unite("controller return string suffix is ", config.getSuffix()));
logger.info(StringUtils.unite("controller packages is ", Arrays.asList(config.getControllersPackages())));
logger.info("init end");
}
@Override
protected final void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
HttpBaseController.setControllerContext(new ControllerContext(httpRequest, httpResponse));
if (httpDataCheckers == null || httpDataCheckers.inCheck(httpRequest, httpResponse, null)) {
super.service(httpRequest, httpResponse);
}
}
@Override
protected final void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
controllerProcessor.requestExecute(httpRequest, httpResponse, RequestMethod.GET);
}
@Override
protected final void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
controllerProcessor.requestExecute(httpRequest, httpResponse, RequestMethod.POST);
}
} |
package commonwealth.nations;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import commonwealth.game.BufferedImageLoader;
import commonwealth.game.Game;
import commonwealth.game.Map;
public class Democracy extends Nations{
public Democracy(int happiness, int resources, int defense, int religion, int tech, ID affiliation, Game game) {
super(happiness, resources, defense, religion, tech, affiliation);
}
public void tick() {
happiness = Game.clamp(happiness, 0, 100);
resources = Game.clamp(resources, 0, 100);
defense = Game.clamp(defense, 0, 100);
religion = Game.clamp(religion, 0, 100);
tech = Game.clamp(tech, 0, 100);
}
public void render(Graphics g) {
g.drawImage(Map.leftnation, 0, 0, Game.width, Game.height,null);
g.setColor(Color.black);
g.setFont(new Font("Arial", 2, 30));
g.drawString("Aegr Republic", 15, 280);
g.setFont(new Font("Arial", 0, 20));
g.drawImage(Map.icons, 35, 287, 100, 100, null);
if(happiness < 20){
g.setColor(Color.red);
}else{
g.setColor(Color.black);
}
g.drawString(happiness + "%", 65, 303);
if(resources < 60){
g.setColor(Color.red);
}else{
g.setColor(Color.black);
}
g.drawString(resources + "%", 140, 303);
if(defense < 40){
g.setColor(Color.red);
}else{
g.setColor(Color.black);
}
g.drawString(defense + "%", 65, 333);
if(religion < 50){
g.setColor(Color.red);
}else{
g.setColor(Color.black);
}
g.drawString(religion + "%", 140, 333);
if(tech < 50){
g.setColor(Color.red);
}else{
g.setColor(Color.black);
}
g.drawString(tech + "%", 65, 361);
}
}
|
package com.stocktrading.stockquote.serviceImpl;
import java.util.Map;
public interface TransactionService
{
Object service(Map<String, Object> params);
}
|
package com.dubboagent.context.trace;
import com.dubboagent.utils.GlobalIdGenerator;
import java.util.EmptyStackException;
import java.util.Stack;
/**
* Date:2017/11/23
*
* @author:chao.cheng
**/
public class DubboTrace implements AbstractTrace {
/**
* traceId的所有span
**/
private Stack<AbstractSpan> spanList;
/**
* 全局traceId
**/
private String traceId;
public DubboTrace() {
traceId = GlobalIdGenerator.generate();
spanList = new Stack<AbstractSpan>();
}
@Override
/**
* 查看栈顶元素
*/
public AbstractSpan peekSpan() {
try {
if(spanList.size() == 0) {
return null;
} else {
return spanList.peek();
}
} catch (EmptyStackException e) {
e.printStackTrace();
return null;
}
}
@Override
/**
* 将新的span信息压到栈顶
*/
public void pushSpan(AbstractSpan span) {
spanList.push(span);
}
/**
* 获取traceId
* @return
*/
@Override
public String getTraceId() {
return traceId;
}
@Override
public void setTraceId(String traceId) {
this.traceId = traceId;
}
@Override
public String getSpanListStr() {
StringBuffer stringBuffer = new StringBuffer();
spanList.stream().forEach((span)->
stringBuffer.append(span.getSpanId()+"-")
);
return stringBuffer.toString().substring(0,stringBuffer.length()-1);
}
}
|
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
package pwnbrew.options.panels;
import java.awt.Color;
import java.awt.Insets;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import pwnbrew.StubConfig;
import pwnbrew.generic.gui.PanelListener;
import pwnbrew.generic.gui.ValidTextField;
import pwnbrew.misc.Constants;
import pwnbrew.misc.FileFilterImp;
import pwnbrew.misc.JarItemException;
import pwnbrew.misc.StandardValidation;
import pwnbrew.misc.Utilities;
/**
*
*/
public class JarLibraryPanel extends OptionsJPanel implements JarTableListener {
private JFileChooser theJarChooser = null;
private final FileFilterImp theJarFilter = new FileFilterImp();
private JarTable theJarTable;
private static final String NAME_Class = JarLibraryPanel.class.getSimpleName();
private static final String JAR_EXT = "jar";
//===================================================================
/** Creates new form AdvancedlOptionsPanel
* @param passedTitle
* @param parent
*/
public JarLibraryPanel( String passedTitle, PanelListener parent ) {
super( passedTitle, parent );
initComponents();
initializeComponents();
}
//===================================================================
/**
* Initialize components
*/
private void initializeComponents() {
//Create a JFileChooser to select wim files...
theJarFilter.addExt( JAR_EXT);
theJarChooser = new JFileChooser();
theJarChooser.setMultiSelectionEnabled(false);
theJarChooser.setFileFilter(theJarFilter);
Utilities.setComponentIcon(addFile, 15, 15, Constants.ADD_IMAGE_STR);
Utilities.setComponentIcon(removeFile, 15, 15, Constants.DELETE_IMG_STR);
Utilities.setComponentIcon(buildStagerButton, 28, 28, Constants.BUILD_STAGER_IMG_STR);
buildStagerButton.setText("Build");
addFile.setToolTipText("Add JAR to Library");
removeFile.setToolTipText("Remove JAR from Library");
//Create a file table
theJarTable = new JarTable( this );
jarScrollPane.setViewportView(theJarTable);
jarScrollPane.getViewport().setBackground(Color.WHITE);
StubConfig theConf = StubConfig.getConfig();
String serverIp = theConf.getServerIp();
((ValidTextField)ipTextField).setValidation( StandardValidation.KEYWORD_Host);
ipTextField.setText(serverIp);
ipTextField.setMargin(new Insets(2,4,2,4));
((ValidTextField)cdnTextField).setValidation( StandardValidation.KEYWORD_Host);
cdnTextField.setText(serverIp);
cdnTextField.setMargin(new Insets(2,4,2,4));
((ValidTextField)portTextField).setValidation( StandardValidation.KEYWORD_Port);
portTextField.setMargin(new Insets(2,4,2,4));
}
/** 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() {
stagerSetupPanel = new javax.swing.JPanel();
buildStagerButton = new javax.swing.JButton();
ipLabel = new javax.swing.JLabel();
ipTextField = new ValidTextField( "0.0.0.0" );
portLabel = new javax.swing.JLabel();
portTextField = portTextField = new ValidTextField( "443" );
cdnLabel = new javax.swing.JLabel();
cdnTextField = new ValidTextField( "localhost.localhost" );
removeFile = new javax.swing.JButton();
addFile = new javax.swing.JButton();
jarScrollPane = new javax.swing.JScrollPane();
stagerSetupPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Stager Setup"));
buildStagerButton.setText("Build");
buildStagerButton.setIconTextGap(7);
buildStagerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buildStagerButtonActionPerformed(evt);
}
});
ipLabel.setText("Server Host/IP:");
portLabel.setText("Port:");
cdnLabel.setText("Host Header:");
cdnTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cdnTextFieldActionPerformed(evt);
}
});
javax.swing.GroupLayout stagerSetupPanelLayout = new javax.swing.GroupLayout(stagerSetupPanel);
stagerSetupPanel.setLayout(stagerSetupPanelLayout);
stagerSetupPanelLayout.setHorizontalGroup(
stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(stagerSetupPanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(stagerSetupPanelLayout.createSequentialGroup()
.addComponent(ipLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ipTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(portLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
.addComponent(buildStagerButton, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(stagerSetupPanelLayout.createSequentialGroup()
.addComponent(cdnLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cdnTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
stagerSetupPanelLayout.setVerticalGroup(
stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(stagerSetupPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(stagerSetupPanelLayout.createSequentialGroup()
.addGroup(stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ipTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ipLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cdnTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cdnLabel))
.addGap(11, 11, 11))
.addGroup(stagerSetupPanelLayout.createSequentialGroup()
.addGroup(stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buildStagerButton)
.addGroup(stagerSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(portLabel)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
removeFile.setText(" ");
removeFile.setIconTextGap(0);
removeFile.setMargin(new java.awt.Insets(2, 2, 2, 2));
removeFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeFileActionPerformed(evt);
}
});
addFile.setText(" ");
addFile.setIconTextGap(0);
addFile.setMargin(new java.awt.Insets(2, 2, 2, 2));
addFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addFileActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jarScrollPane)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(addFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeFile)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(stagerSetupPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(stagerSetupPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jarScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addFile)
.addComponent(removeFile))
.addGap(45, 45, 45))
);
}// </editor-fold>//GEN-END:initComponents
private void removeFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeFileActionPerformed
int[] selRowIndexes = theJarTable.getSelectedRows();
for( int anInt : selRowIndexes )
deleteJarItem(anInt);
}//GEN-LAST:event_removeFileActionPerformed
private void addFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFileActionPerformed
selectJar();
}//GEN-LAST:event_addFileActionPerformed
private void buildStagerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buildStagerButtonActionPerformed
ValidTextField ipField = (ValidTextField) ipTextField;
ValidTextField portField = (ValidTextField) portTextField;
if( ipField.isValid() && portField.isValid()){
//See if the table already contains the entry
DefaultTableModel theModel = (DefaultTableModel) theJarTable.getModel();
for( int i =0; i < theModel.getRowCount(); i++ ){
//Get table entries
String jarType = (String) theJarTable.getValueAt(i, 1);
if(jarType.equals(Constants.STAGER_TYPE)){
String ipStr = ipField.getText().trim();
String connectStr = "https://" + ipStr + ":" + portTextField.getText().trim();
//Get table entries
String jarName = (String) theJarTable.getValueAt(i, 0);
String jvmVersion = (String) theJarTable.getValueAt(i, 2);
String jarVersion = (String) theJarTable.getValueAt(i, 3);
//See if the host header has been set and it's different than the C2 IP
String hostHeaderStr = null;
ValidTextField cdnField = (ValidTextField) cdnTextField;
if(cdnField.isValid() ){
String cdnHost = cdnField.getText().trim();
if( !cdnHost.equals(ipStr))
hostHeaderStr = cdnHost;
}
getListener().getStagerFile( connectStr, jarName, jarType, jvmVersion, jarVersion, hostHeaderStr );
return;
}
}
JOptionPane.showMessageDialog( this, "No stager", "Unable to build Stager. No stager exist in the module library.", JOptionPane.ERROR_MESSAGE );
} else {
JOptionPane.showMessageDialog( this, "Invalid values","Unable to build Stager. IP and port must be valid values.", JOptionPane.ERROR_MESSAGE );
}
}//GEN-LAST:event_buildStagerButtonActionPerformed
private void cdnTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cdnTextFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cdnTextFieldActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addFile;
private javax.swing.JButton buildStagerButton;
private javax.swing.JLabel cdnLabel;
private javax.swing.JTextField cdnTextField;
private javax.swing.JLabel ipLabel;
private javax.swing.JTextField ipTextField;
private javax.swing.JScrollPane jarScrollPane;
private javax.swing.JLabel portLabel;
private javax.swing.JTextField portTextField;
private javax.swing.JButton removeFile;
private javax.swing.JPanel stagerSetupPanel;
// End of variables declaration//GEN-END:variables
// ==========================================================================
/**
*
*/
public void clearTable() {
theJarTable.clear();
}
// ==========================================================================
/**
* Selects the client jar.
*/
private void selectJar() {
File userSelectedFile = null;
int returnVal = theJarChooser.showDialog( this, "Select JAR File" ); //Show the dialogue
switch( returnVal ) {
case JFileChooser.CANCEL_OPTION: //If the user canceled the selecting...
break;
case JFileChooser.ERROR_OPTION: //If the dialogue was dismissed or an error occurred...
break; //Do nothing
case JFileChooser.APPROVE_OPTION: //If the user approved the selection...
userSelectedFile = theJarChooser.getSelectedFile(); //Get the files the user selected
break;
default:
break;
}
//Check if the returned file is valid
if(userSelectedFile == null || userSelectedFile.isDirectory() || !userSelectedFile.canRead())
return;
//Create the java item
String[] aStrArr;
try {
aStrArr = Utilities.getJavaItem(userSelectedFile );
} catch (JarItemException ex) {
JOptionPane.showMessageDialog( this, ex.getMessage(),"Error", JOptionPane.ERROR_MESSAGE );
return;
}
if( aStrArr != null ){
String selJarName = aStrArr[0];
String selJarType = aStrArr[1];
String selJarVersion = aStrArr[2];
String selJarJvmVersion = aStrArr[3];
//See if the table already contains the entry
DefaultTableModel theModel = (DefaultTableModel) theJarTable.getModel();
int rowToDelete = -1;
for( int i =0; i < theModel.getRowCount(); i++ ){
//Get table entries
String jarName = (String) theJarTable.getValueAt(i, 0);
String jarType = (String) theJarTable.getValueAt(i, 1);
String jvmVersion = (String) theJarTable.getValueAt(i, 2);
String jarVersion = (String) theJarTable.getValueAt(i, 3);
//Check if the jvm version is the same first
if( jvmVersion.equals(selJarJvmVersion) &&
jarType.equals( selJarType) ){
//Only one Stager and Payload are allowed
if( jarType.equals( Constants.STAGER_TYPE) || jarType.equals( Constants.PAYLOAD_TYPE)){
rowToDelete = i;
break;
//Check if one with the same name exists
} else if( jarName.equals( selJarName )) {
rowToDelete = i;
break;
}
}
}
//If a similar library already exist
if( rowToDelete != -1 ){
String theMessage = new StringBuilder("Would you like to replace the existing ")
.append( selJarType ).append(" named \"")
.append( selJarName ).append("\" versioned \"")
.append( selJarVersion ).append("\"?").toString();
int dialogValue = JOptionPane.showConfirmDialog(this, theMessage, "Replace JAR Library?", JOptionPane.YES_NO_OPTION);
//Add the JAR to utilities
if ( dialogValue == JOptionPane.YES_OPTION ){
deleteJarItem(rowToDelete);
} else {
return;
}
}
//Queue the file to be sent
getListener().sendJarFile( userSelectedFile, selJarType);
}
}
//========================================================================
/**
* Delete the file
*
* @param anInt
*/
@Override
public void deleteJarItem(int anInt ) {
//Get the model and remove the item
DefaultTableModel theTableModel = (DefaultTableModel) theJarTable.getModel();
String jarName = (String) theTableModel.getValueAt(anInt, 0);
String jarType = (String) theTableModel.getValueAt(anInt, 1);
String jvmVersion = (String) theTableModel.getValueAt(anInt, 2);
String jarVersion = (String) theTableModel.getValueAt(anInt, 3);
getListener().deleteJarItem(jarName, jarType, jvmVersion, jarVersion);
}
//========================================================================
/**
* Delete jar item entry
*
* @param jarName
* @param jarType
* @param jvmVersion
* @param jarVersion
*/
public synchronized void deleteJarItemFromTable(String jarName, String jarType, String jvmVersion, String jarVersion ) {
//Get the model and remove the item
DefaultTableModel theTableModel = (DefaultTableModel) theJarTable.getModel();
int rowCount = theTableModel.getRowCount();
for( int i = 0; i < rowCount; i++ ){
if( jarName.equals((String) theTableModel.getValueAt(i, 0)) &&
jarType.equals((String) theTableModel.getValueAt(i, 1)) &&
jvmVersion.equals((String) theTableModel.getValueAt(i, 2)) &&
jarVersion.equals((String) theTableModel.getValueAt(i, 3))){
//Remove from table
theTableModel.removeRow(i);
break;
}
}
}
//========================================================================
/**
*
* @param theJarName
* @param theJarType
* @param theJvmVersion
* @param theJarVersion
*/
public synchronized void addJarItem(String theJarName, String theJarType, String theJvmVersion, String theJarVersion) {
DefaultTableModel theModel = (DefaultTableModel) theJarTable.getModel();
theModel.addRow( new Object[]{ theJarName, theJarType, theJvmVersion, theJarVersion });
}
//========================================================================
/**
*
*/
@Override
public void saveChanges() {
}
//========================================================================
/**
*
* @return
*/
@Override
public JarLibraryPanelListener getListener() {
return (JarLibraryPanelListener)super.getListener();
}
}
|
package ua.training.controller.commands;
import ua.training.model.dao.mapper.DayRationMapper;
import ua.training.model.dao.mapper.DishMapper;
import ua.training.model.dao.mapper.UserMapper;
import ua.training.model.dao.service.implementation.DayRationServiceImp;
import ua.training.model.dao.service.implementation.DishServiceImp;
import ua.training.model.dao.service.implementation.RationCompositionServiceImp;
import ua.training.model.dao.service.implementation.UserServiceImp;
import javax.servlet.http.HttpServletRequest;
/**
* Description: This is the main Interface for commands
*
* @author Zakusylo Pavlo
*/
public interface Command {
UserServiceImp USER_SERVICE_IMP = new UserServiceImp();
DishServiceImp DISH_SERVICE_IMP = new DishServiceImp();
DayRationServiceImp DAY_RATION_SERVICE_IMP = new DayRationServiceImp();
RationCompositionServiceImp RATION_COMPOSITION_SERVICE_IMP = new RationCompositionServiceImp();
UserMapper USER_MAPPER = new UserMapper();
DishMapper DISH_MAPPER = new DishMapper();
DayRationMapper DAY_RATION = new DayRationMapper();
String execute(HttpServletRequest request);
}
|
package com.myth.springboot.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myth.springboot.entity.*;
import com.myth.springboot.service.CourseService;
import com.myth.springboot.service.StudentService;
import com.myth.springboot.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class CourseController {
@Autowired
CourseService courseService;
@Autowired
StudentService studentService;
@Autowired
TeacherService teacherService;
/**
* 班级业务
*/
/*
得到所有class信息
*/
@RequestMapping("/courseAdd")
@ResponseBody
public Msg courseInsert(String name){
Course course = new Course();
course.setCo_name(name);
List<Course> c = courseService.courseSelect(new Course());
for (Course cc:c){
System.out.println(cc.getCo_name());
if (cc.getCo_name().equals(name)){
return Msg.success().add("msg","请勿重复添加课程!!!");
}
}
int i = courseService.courseInsert(course);
if (i>0){
return Msg.success().add("msg","课程新增成功");
}else {
return Msg.success().add("msg","课程新增失败");
}
}
@RequestMapping("/courseListWithPage")
@ResponseBody
public Map<String, Object> courseListWithPage(String page,String limit){
PageHelper.startPage(Integer.valueOf(page).intValue(),Integer.valueOf(limit).intValue());
List<Course> courses = courseService.courseSelect(new Course());
PageInfo pageInfo = new PageInfo(courses,5);
Map<String,Object> map = new HashMap<>();
map.put("data",pageInfo);
return map;
}
@RequestMapping("/courseList")
@ResponseBody
public Msg courseList(){
List<Course> courses = courseService.courseSelect(new Course());
return Msg.success().add("courses",courses);
}
@RequestMapping("/courseGetById")
@ResponseBody
public ModelAndView classGetById(String id){
ModelAndView mv = new ModelAndView("course/course-update");
Integer co_id= Integer.valueOf(id).intValue();
Course course = new Course();
course.setCo_id(co_id);
List<Course> courses = courseService.courseSelect(course);
mv.addObject("course",courses.get(0));
return mv;
}
@RequestMapping("/courseUpdate")
@ResponseBody
public Msg classUpdate(String id,String name){
Integer co_id=Integer.valueOf(id).intValue();
String co_name=name;
Course course = new Course(co_id,co_name);
List<Course> c = courseService.courseSelect(new Course());
for (Course cc:c){
System.out.println(cc.getCo_name());
if (cc.getCo_name().equals(name)){
return Msg.success().add("msg","已有该课程,请勿修改!!!");
}
}
int i = courseService.courseUpdateById(course);
if (i>0){
return Msg.success().add("msg","修改成功,老弟!");
}else {
return Msg.success().add("msg","出错了,老弟!");
}
}
@RequestMapping("/courseDelete")
@ResponseBody
public Msg classDelete(String id){
Course course = new Course();
course.setCo_id(Integer.valueOf(id).intValue());
int i = courseService.courseDeleteById(course);
if (i>0){
return Msg.success().add("msg","删除课程成功");
}else {
return Msg.success().add("msg","删除课程失败");
}
}
@RequestMapping("/courseDeleteMany")
@ResponseBody
public Msg courseDeleteMany(String id){
String str[] = id.split(",");
String s="";
for (int i=0;i<str.length;i++){
Course course = new Course();
course.setCo_id(Integer.valueOf(str[i]).intValue());
int j = courseService.courseDeleteById(course);
if (j>0){
s+=str[i]+"删除课程成功";
}else {
s+=str[i]+"删除课程失败";
}
}
return Msg.success().add("msg",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 Project2;
/**
*
* @author NURUL IMAN
*/
public class MainClassArray {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayProcessing arr = new ArrayProcessing();
arr.input();
arr.output();
}
}
|
package com.kamus.bisindo.Common;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import com.kamus.bisindo.Dashboard;
import com.kamus.bisindo.MainActivity;
import com.kamus.bisindo.R;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class OnBoarding extends AppCompatActivity {
private ViewPager screenPager;
IntroViewPagerAdapter introViewPagerAdapter;
TabLayout tab_indicator;
Button btn_next;
int position = 0;
Button btnGetStarted;
Animation btnAnim;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//activity fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//open activity check
if (restorePrefData()){
Intent dashboard = new Intent(getApplicationContext(), Dashboard.class);
startActivity(dashboard);
finish();
}
setContentView(R.layout.activity_on_boarding);
//views
btn_next = findViewById(R.id.btn_next);
btnGetStarted = findViewById(R.id.btn_get_started);
tab_indicator = findViewById(R.id.tab_indicator);
btnAnim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.button_animation);
// fill list screen
final List<ScreenItem> mList = new ArrayList<>();
mList.add(new ScreenItem("Selamat Datang", "", R.drawable.onboard1));
mList.add(new ScreenItem("Kemudahan Belajar", "Teman BISINDO akan membantu kamu dalam mengenal Bahasa Isyarat.", R.drawable.onboard2));
mList.add(new ScreenItem("Ayo Mulai", "", R.drawable.onboard3));
//Setup ViewPager
screenPager = findViewById(R.id.screen_viewpager);
introViewPagerAdapter = new IntroViewPagerAdapter(this, mList);
screenPager.setAdapter(introViewPagerAdapter);
//Setup TabLayout with ViewPager
tab_indicator.setupWithViewPager(screenPager);
//next Button click Listener
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
position = screenPager.getCurrentItem();
if (position < mList.size()) {
position++;
screenPager.setCurrentItem(position);
}
if (position == mList.size()) {
// TODO : show the GETSTARTED Button to hide the indicator and next button
loadLastScreen();
}
}
});
//tabLayout add change listener
tab_indicator.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition()==mList.size()-1){
loadLastScreen();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//GET Started button click listener
btnGetStarted.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Open Main activity
Intent dashboard = new Intent(getApplicationContext(), Dashboard.class);
startActivity(dashboard);
//
//preference data
savePrefData();
finish();
}
});
}
private boolean restorePrefData() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("myPref",MODE_PRIVATE);
Boolean isIntroOpenedBefore = pref.getBoolean("isIntroOpened", false);
return isIntroOpenedBefore;
}
private void savePrefData() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("myPref",MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isIntroOpened",true);
editor.commit();
}
// show the GETSTARTED Button to hide the indicator and next button
private void loadLastScreen(){
btn_next.setVisibility(View.INVISIBLE);
btnGetStarted.setVisibility(View.VISIBLE);
tab_indicator.setVisibility(View.INVISIBLE);
//TODO : ADD an animation to the getStarted button
//Animation setup
btnGetStarted.setAnimation(btnAnim);
}
} |
package edu.palindrome.driscoll.aidan;
import edu.jenks.dist.palindrome.*;
/**
* Write a description of class Palindrome here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class PalindromeChecker extends AbstractPalindromeChecker
{
public static void main(String[] args){
System.out.println("Begin");
PalindromeChecker pc = new PalindromeChecker();
System.out.println(pc.isPalindrome("%%"));
System.out.println("End Without Error");
}
public boolean isPalindrome(String arg){
String reverse = "";
arg = arg.toLowerCase();
String forward = "";
for(int i = arg.length() - 1; i >= 0; i--){
char c = arg.charAt(i);
if(Character.isLetterOrDigit(c)){
reverse += c;
}
}
for(int i = 0; i < arg.length(); i++){
char c = arg.charAt(i);
if(Character.isLetterOrDigit(c)){
forward += c;
}
}
System.out.println(reverse);
System.out.println(forward);
if(forward.equals(reverse)){
if(forward != "" && reverse != ""){
return true;
}else{
return false;
}
}else{
return false;
}
}
}
|
package com.andrstudy.androidlottietest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieDrawable;
public class MainActivity extends AppCompatActivity {
// lottie 생성
private LottieAnimationView lottie;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lottie = (LottieAnimationView) findViewById(R.id.lottie);
// 폴더셋팅
lottie.setImageAssetsFolder("images/");
// 파일 셋팅
lottie.setAnimation("b_finish2.json");
// 무한 반복
lottie.setRepeatCount(LottieDrawable.INFINITE);
// 실행
lottie.playAnimation();
}
}
|
package swiss.kamyh.elo.gui.scorboard;
/**
* Created by Vincent on 10.06.2016.
*/
public interface ITimerized {
public void callbackTimer(ScoreboardItemTimed item);
public void timesUp();
}
|
package com.ipartek.formacion.nombreproyecto.pojo;
import static org.junit.Assert.*;
import java.util.HashMap;
import org.junit.Test;
public class HashMapTest {
@Test
public void test() {
HashMap<String, Persona> hmPersonas = new HashMap<String, Persona>();
assertEquals(0, hmPersonas.size());
assertTrue(hmPersonas.isEmpty());
hmPersonas.put("1111111H", new Persona("Periko", "Palotes", "Gorrito", "1111111H", "periko@palotes.com") );
assertEquals(1, hmPersonas.size());
assertFalse(hmPersonas.isEmpty());
Persona periko = hmPersonas.get("1111111H");
}
}
|
package coolc.codegenerator;
import java.util.ArrayList;
import java.util.List;
public class InitializeMethodCode extends MethodCode
{
private List < String > _attributePointersCode;
public InitializeMethodCode(String classType)
{
super("initializeAttributes", classType);
this._attributePointersCode = new ArrayList < String >();
}
public InitializeMethodCode(String classType, InitializeMethodCode parentInitializer)
{
this(classType);
this._bodyCode.addAll(parentInitializer._bodyCode);
//Se copian los códigos que obtienen el puntero reemplazando el nombre de la clase padre por el hijo
for(String attrCode : parentInitializer._attributePointersCode)
{
this._attributePointersCode.add(attrCode.replaceAll(parentInitializer._classType, classType));
}
}
public void addAttributePointerCode(String code)
{
this._attributePointersCode.add(code);
}
@Override
public String getCode()
{
String code = "define %" + this._classType +"* @_new" + this._classType + "()\n";
code += "{\n";
code += "\t%vptr = call i8* @malloc(i64 ptrtoint (%" + this._classType + "* getelementptr" +
" (%" + this._classType + "* null , i32 1) to i64))\n";
code += "\t%self = bitcast i8* %vptr to %" + this._classType + "*\n";
code += "\t%class_type = getelementptr %" + this._classType + "* %self, i32 0, i32 0\n";
code += "\tstore i8* bitcast([" + (this._classType.length() + 1) + " x i8]* @_type_" + this._classType +
" to i8*), i8** %class_type\n";
//Separamos la parte genérica
code += "\n";
if(this._superCast)
{
code += "\t" + this._superVarNam + " = bitcast %" + this._classType + "* %_" +
this._classType.toLowerCase().charAt(0) + " to %" + this._superClassType + "*\n";
}
//Antes de llamar al cuerpo del método, llamamos a las variables que piden los punteros
for(String ptrCode : this._attributePointersCode)
{
code += "\t" + ptrCode + "\n";
}
for(String exprCode : this._bodyCode)
{
code += "\t" + exprCode + "\n";
}
code += "\tret %" + this._classType + "* %self\n";
code += "}\n";
return code;
}
@Override
public String getParamName(int pos)
{
return "%" + this._classType.toLowerCase().charAt(0);
}
public String getDefaultValue(String type)
{
switch(type)
{
case "i8*":
return "getelementptr inbounds ([1 x i8]* @.empty_str, i64 0, i64 0)";
case "i32":
return "0";
case "i1":
return "0";
default:
return "void";
}
}
}
|
import java.util.LinkedList;
import java.util.Queue;
public class BreadthFirstTraversalOfBinaryTree {
public static void traverseLevelOrder(BinaryTree binaryTree) {
if (binaryTree.root == null) {
return;
}
Queue<Node> queue = new LinkedList<>();
queue.add(binaryTree.root);
while (!queue.isEmpty()) {
Node current = queue.remove();
System.out.println(" " + current.data);
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
}
}
}
|
package com.tms.lazytip;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.ambit.city_guide.R;
import com.gtambit.gt.app.api.GtApi;
import com.gtambit.gt.app.api.GtLayoutApi;
import com.gtambit.gt.app.api.GtRequestApi;
import com.gtambit.gt.app.api.gson.NewsBannerObj;
import com.gtambit.gt.app.api.gson.NewsListObj;
//import com.gtambit.gt.app.api.gson.PoiSearchObj;
import com.gtambit.gt.app.mission.api.TaskApi;
import com.gtambit.gt.app.news.NewsActivity;
import com.gtambit.gt.app.news.NewsContentActivity;
import com.google.gson.Gson;
import com.hyxen.MobileLocusMap.MobileLocusMap;
import com.hyxen.app.ZeroCard.Api.ImageLoader;
import java.util.ArrayList;
import java.util.HashMap;
import ur.ui_component.drawer.URMenuType;
public class MyLoveList extends DrawerActivity implements View.OnClickListener{
private TextView textView,textView2;
private Button goToBtn;
private boolean intGoTo=false;
private LinearLayout mLoveLinearLayout;
private ListView mLoveListView;
// private PoiSearchObj poiFav;
private NewsListObj newsFav;
private String KEY_POI_KM = "poikm";
private String KEY_POI_NAME = "poiname";
private String KEY_POI_ADD = "poiadd";
private String KEY_POI_TEL = "poitel";
private int intResouce = R.layout.poi_fav_list;
private String[] poifrom = {
KEY_POI_KM,
KEY_POI_NAME,
KEY_POI_TEL,
KEY_POI_ADD,
};
private int[] poito = {
R.id.TextViewPoiKm,
R.id.TextViewPoiName,
R.id.TextViewPoiAdd,
R.id.TextViewPoiTel,
};
private String KEY_ITEM = "item";
private String KEY_ITEM_FEED = "itemFeed";
private String KEY_ITEM_TEXT = "itemText";
private String KEY_ITEM_FEED_CLK = "itemFeedClick";
private String KEY_ITEM_TEXT_CLK = "itemTextClick";
// private String KYE_ICON = "icon";
private String KEY_ITEM_IS_READE = "itemIsRead";
private String KEY_PICTURE = "picture";
private String kEY_PICTURE_MATRIX = "pictureMatrix";
private String KEY_TITLE = "title";
// private String KEY_TITLE_COLOR = "titleColor";
private String KEY_CATEGORY = "category";
private String KEY_TIME = "time";
private String KEY_VIEWS = "views";
//private String KYE_ICON = "icon";
private int markNews,markPoi;
private String KEY_TEXT_TITLE = "textTitle";
private String KEY_TEXT_TIME = "textTime";
private String KEY_TEXT_CATEGORY = "textCatergory";
private String KEY_TEXT_VIEWS = "textViews";
private int intNewsFav = R.layout.gt_news_listitem_feed;
private String[] from = {
KEY_ITEM,
KEY_ITEM_FEED,
KEY_ITEM_TEXT,
KEY_ITEM_FEED_CLK,
KEY_ITEM_TEXT_CLK,
// KEY_ITEM_IS_READE,
KEY_PICTURE,
kEY_PICTURE_MATRIX,
KEY_TITLE,
KEY_CATEGORY,
KEY_TIME,
KEY_VIEWS,
// KYE_ICON,
KEY_TEXT_TITLE,
KEY_TEXT_TIME,
KEY_TEXT_CATEGORY,
KEY_TEXT_VIEWS,
};
private int[] to = {
R.id.LayoutItem,
R.id.LayoutFeed,
R.id.LayoutText,
R.id.LayoutFeed,
R.id.LayoutText,
// R.id.LayoutItem,
R.id.ImageViewPicture,
R.id.ImageViewPicture,
R.id.TextViewTitle,
R.id.TextViewCategory,
R.id.TextViewTime,
R.id.TextViewViews,
//R.id.ImageViewIcon,
R.id.TextViewTitleText,
R.id.TextViewTimeText,
R.id.TextViewCategoryText,
R.id.TextViewViewsText,
};
private Button my_love_list_btn1,my_love_list_btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_love_list);
setTitleName(getResources().getString(R.string.title_activity_my_love_list));
initLayout();
checkByNewsFavorite();
getNewsFav();
}
@Override
public URMenuType onCurrentMenuType() {
return null;
}
private void initLayout(){
findViewById(R.id.my_love_list_btn1).setOnClickListener(this);
findViewById(R.id.my_love_list_btn2).setOnClickListener(this);
my_love_list_btn1 = (Button) findViewById(R.id.my_love_list_btn1);
my_love_list_btn1.setBackground(getResources().getDrawable(R.drawable.htab_btn_click));
my_love_list_btn2 = (Button) findViewById(R.id.my_love_list_btn2);
mLoveLinearLayout = (LinearLayout) findViewById(R.id.myTestLayout);
mLoveListView = (ListView) findViewById(R.id.myLoveList);
goToBtn =(Button) findViewById(R.id.my_love_list_btn3);
textView=(TextView) findViewById(R.id.my_love_list_text);
textView2=(TextView) findViewById(R.id.my_love_list_text2);
textView.setText("您還沒有收藏任何文章喔!");
textView2.setText("立即去看看");
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.my_love_list_btn1:
my_love_list_btn1.setBackground(getResources().getDrawable(R.drawable.htab_btn_click));
my_love_list_btn2.setBackground(getResources().getDrawable(R.drawable.htab_btn));
checkByNewsFavorite();
getNewsFav();
goToBtn.setText("開車懶人包");
textView.setText("您還沒有收藏任何文章喔!");
textView2.setText("立即去看看");
goList(false);
break;
case R.id.my_love_list_btn2:
my_love_list_btn1.setBackground(getResources().getDrawable(R.drawable.htab_btn));
my_love_list_btn2.setBackground(getResources().getDrawable(R.drawable.htab_btn_click));
// checkPoiByFavorite();
// getPoiFav();
textView.setText("您還沒有任何收藏保養廠喔!");
goToBtn.setText("保養廠");
textView2.setText("立即去看看");
goList(true);
break;
}
}
public boolean goList(boolean mboolean){
if(mboolean==false){
goToBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent NewsIntent = new Intent(MyLoveList.this,NewsActivity.class);
startActivity(NewsIntent);
}
});
}else {
goToBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent MapIntent = new Intent(MyLoveList.this,MobileLocusMap.class);
startActivity(MapIntent);
}
});
}
return mboolean;
}
// private void checkPoiByFavorite(){
// new Thread(new Runnable() {
// @Override
// public void run() {
// poiFav=GtRequestApi.getPoiByFaverite(MyLoveList.this);
// for (final PoiSearchObj.Poi obj: poiFav.poi) {
// markPoi= obj.mark;
// }
// if(markPoi ==1){
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// textView.setVisibility(View.GONE);
// goToBtn.setVisibility(View.GONE);
// textView2.setVisibility(View.GONE);
// mLoveLinearLayout.setVisibility(View.GONE);
// mLoveListView.setVisibility(View.VISIBLE);
// }
// });
//
// }else {
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// textView.setVisibility(View.VISIBLE);
// goToBtn.setVisibility(View.VISIBLE);
// textView2.setVisibility(View.VISIBLE);
// mLoveLinearLayout.setVisibility(View.VISIBLE);
// mLoveListView.setVisibility(View.GONE);
// }
// });
//
// }
//
// }
// }).start();
//
//
//
// }
private void checkByNewsFavorite(){
new Thread(new Runnable() {
@Override
public void run() {
newsFav =GtRequestApi.getNewsByFaverite(MyLoveList.this);
for (final NewsListObj.NewsItem obj : newsFav.news) {
markNews =obj.mark;
}
if(markNews ==1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setVisibility(View.GONE);
goToBtn.setVisibility(View.GONE);
textView2.setVisibility(View.GONE);
mLoveLinearLayout.setVisibility(View.GONE);
mLoveListView.setVisibility(View.VISIBLE);
}
});
}else {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setVisibility(View.VISIBLE);
goToBtn.setVisibility(View.VISIBLE);
textView2.setVisibility(View.VISIBLE);
mLoveLinearLayout.setVisibility(View.VISIBLE);
mLoveListView.setVisibility(View.GONE);
}
});
}
}
}).start();
}
// private void getPoiFav()
// {
// new Thread(new Runnable() {
//
// @Override
// public void run() {
//// poiFav=GtRequestApi.getPoiByFaverite(MyLoveList.this);
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// final ArrayList<HashMap<String, Object>> poiFavdata = new ArrayList<HashMap<String, Object>>();
// MySimpleAdapter mSimpleAdapter;
//
// ListView listView = (ListView)findViewById(R.id.myLoveList);
// listView.setDividerHeight(0);
//
// listView.setDivider(null);
// for (final PoiSearchObj.Poi obj: poiFav.poi) {
// HashMap<String, Object> hm = addData(obj);
// poiFavdata.add(hm);
// }
// mSimpleAdapter = new MySimpleAdapter(MyLoveList.this, poiFavdata, intResouce, poifrom, poito);
// listView.setAdapter(mSimpleAdapter);
// listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// HashMap<String, Object> hm = poiFavdata.get(position);
// PoiSearchObj.Poi obj = (PoiSearchObj.Poi) hm.get("obj");
// goDetail(obj);
// }
// });
//
// }
//// private HashMap<String, Object> addData(final PoiSearchObj.Poi obj) {
//// HashMap<String, Object> hm = new HashMap<String, Object>();
//// hm.put(KEY_POI_KM, "km");
//// hm.put(KEY_POI_NAME, obj.poi_name);
//// hm.put(KEY_POI_TEL, obj.poi_phn);
//// hm.put(KEY_POI_ADD, obj.poi_addr);
//// hm.put("obj", obj);
//// return hm;
//// }
//
//
// });
// }
//
// }).start();
// }
// private void goDetail(PoiSearchObj.Poi poi){
//
// Intent intent = new Intent();
// intent.setClass(MyLoveList.this, TmsPoiWeb.class);
// Bundle bundle = new Bundle();
// bundle.putString("json", new Gson().toJson(poi));
// bundle.putString("mPoiHtml", poi.poi_body);
// bundle.putString("mGooglelat", poi.poi_lat+"");
// bundle.putString("mGooglelon", poi.poi_lon+"");
// intent.putExtras(bundle);
// startActivity(intent);
// }
private void getNewsFav()
{
new Thread(new Runnable() {
@Override
public void run() {
newsFav = GtRequestApi.getNewsByFaverite(MyLoveList.this);
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("newFav",newsFav+"");
final ArrayList<HashMap<String, Object>> NewsFavdata = new ArrayList<HashMap<String, Object>>();
com.hyxen.app.ZeroCard.Api.MySimpleAdapter mSimpleAdapter;
ListView listView = (ListView)findViewById(R.id.myLoveList);
listView.setDividerHeight(0);
listView.setDivider(null);
for (final NewsListObj.NewsItem obj : newsFav.news) {
HashMap<String, Object> hm = addNewsData(obj);
NewsFavdata.add(hm);
}
mSimpleAdapter = new com.hyxen.app.ZeroCard.Api.MySimpleAdapter(MyLoveList.this, NewsFavdata, intNewsFav, from, to);
listView.setAdapter(mSimpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
});
}
}).start();
}
private HashMap<String, Object> addNewsData(final NewsListObj.NewsItem obj) {
HashMap<String, Object> hm = new HashMap<String, Object>();
final View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
GtRequestApi.notifyHyxenServer(MyLoveList.this, obj.click_url);
Intent i = new Intent(MyLoveList.this, NewsContentActivity.class);
i.putExtra(NewsBannerObj.KEY_JSON, new Gson().toJson(obj));
startActivity(i);
}
};
hm.put(KEY_ITEM_FEED, obj.thumb_pic.equals("http://tms-dev.hxcld.com/pub/news_default.png")? View.GONE:View.VISIBLE);
hm.put(KEY_ITEM_TEXT, !obj.thumb_pic.equals("http://tms-dev.hxcld.com/pub/news_default.png")? View.GONE:View.VISIBLE);
Log.e("obj.thumb_pic",obj.thumb_pic);
final CustomImageLoader mCustomImageLoader = new CustomImageLoader(obj.thumb_pic);
hm.put(KEY_PICTURE, mCustomImageLoader);
hm.put(kEY_PICTURE_MATRIX, GtLayoutApi.setRelativeLayoutParamsScale(MyLoveList.this, 576, 300, 576));
String subtitle = obj.news_cat.equals("新聞懶人包") ? obj.news_cat:obj.news_cat+"/"+obj.news_cat_sub;
String time = obj.news_cat.equals("新聞懶人包") ? GtApi.getNewsTimeString(obj.pub_ts) + "|" : "";
//For LayoutFeed
hm.put(KEY_TITLE, obj.title);
hm.put(KEY_CATEGORY, subtitle);
hm.put(KEY_TIME, time);
hm.put(KEY_VIEWS, obj.viewed + "");
//For LayoutText
hm.put(KEY_TEXT_TITLE, obj.title);
hm.put(KEY_TEXT_TIME, time);
hm.put(KEY_TEXT_CATEGORY, subtitle);
hm.put(KEY_TEXT_VIEWS, obj.viewed + "");
hm.put(KEY_ITEM, clickListener);
hm.put(KEY_ITEM_FEED_CLK, clickListener);
hm.put(KEY_ITEM_TEXT_CLK, clickListener);
return hm;
}
private class CustomImageLoader implements ImageLoader {
private String mUrl;
private Object mImage;
public CustomImageLoader(String url) {
mUrl = url;
}
@Override
public void loadImage(final ImageCallback callback) {
if (mImage == null) {
Thread t = new Thread() {
@Override
public void run() {
Bitmap mBitmap = TaskApi.downloadImage(mUrl);
final Object o = mBitmap == null ? R.drawable.news_default : mBitmap;
mImage = o;
runOnUiThread(new Runnable() {
@Override
public void run() {
callback.imageLoaded(o);
}
});
}
};
t.start();
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
callback.imageLoaded(mImage);
}
});
}
}
public Object getImage() {
return mImage;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.e("Exit","Exit");
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
GtApi.ExitPage(MyLoveList.this);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
|
package br.com.estore.web.model;
public class BookBean {
/*
* ID_BOOK INT NOT NULL , TITLE BLOB , PRICE FLOAT , ISBN INT , NUMBER_PAGES
* INT , DESCRIPTION VARCHAR (300) , IMAGE_DIRETORY VARCHAR (500) , LIKEBOOK
* INT , ID_AUTHOR INT NOT NULL , ID_PUBLISHING_HOUSE INT NOT NULL ,
* ID_CATEGORY INT NOT NULL
*/
private int id;
private String title;
private Double price;
private int isbn;
private int numerPages;
private String description;
private String imageDirectory;
private int likebook;
private int authorId;
private int publishingHouseId;
private int categoryId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public int getNumerPages() {
return numerPages;
}
public void setNumerPages(int numerPages) {
this.numerPages = numerPages;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageDirectory() {
return imageDirectory;
}
public void setImageDirectory(String imageDirectory) {
this.imageDirectory = imageDirectory;
}
public int getLikebook() {
return likebook;
}
public void setLikebook(int likebook) {
this.likebook = likebook;
}
public int getAuthorId() {
return authorId;
}
public void setAuthorId(int authorId) {
this.authorId = authorId;
}
public int getPublishingHouseId() {
return publishingHouseId;
}
public void setPublishingHouseId(int publishingHouseId) {
this.publishingHouseId = publishingHouseId;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
}
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
int number;
srand(time(0));
number = rand()%100 + 1; // Generates a random number between 1 and 100
printf("The number is %d", number);
return 0;
} |
package org.notice.gui.panels;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;
import org.notice.beans.Skill;
import org.notice.beans.User;
import org.notice.tablemodel.SkillsUtilTableModel;
import org.notice.tablemodel.UserSelectorModel;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JTable;
import java.awt.FlowLayout;
public class UserSelector extends JPanel implements ListSelectionListener {
private JTextField txtSearch;
private JTable tableUser;
private User selectedUser;
private TableRowSorter<UserSelectorModel> sorter;
private UserSelectorModel userModel;
private ArrayList<User> users;
/**
* Create the panel.
*/
public UserSelector(ArrayList<User> users) {
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
txtSearch = new JTextField();
txtSearch.setText("Search");
add(txtSearch);
txtSearch.setColumns(10);
txtSearch.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
newFilter();
}
@Override
public void insertUpdate(DocumentEvent e) {
newFilter();
}
@Override
public void changedUpdate(DocumentEvent e) {
newFilter();
}
});
userModel = new UserSelectorModel(users);
tableUser = new JTable(userModel);
tableUser.getSelectionModel().addListSelectionListener(this);
sorter = new TableRowSorter<UserSelectorModel>(userModel);
tableUser.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(tableUser);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scrollPane);
selectedUser = new User("-1", null, null, null, null, null);
}
private void newFilter() {
RowFilter<? super UserSelectorModel, ? super Integer> rf = null;
rf = RowFilter.regexFilter("(?i)" + txtSearch.getText());
sorter.setRowFilter(rf);
//selectedUser = new User("-1", null, null, null, null, null);
}
public User getSelectedUser() {
return selectedUser;
}
@Override
public void valueChanged(ListSelectionEvent e) {
//System.out.println("Selected User " + tableUser.getSelectedRow() );
if (tableUser.getSelectedRow() > -1) {
//int row = tableUser.convertRowIndexToModel(tableUser.getSelectedRow());
int row = tableUser.getSelectedRow();
String userId = (String) tableUser.getValueAt(row, 3);
selectedUser = new User(userId, null, null, null, null, null);
} else {
selectedUser = new User("-1", null, null, null, null, null);
}
}
public JTable getUserTable() {
return tableUser;
}
public void setUserTable(JTable tableUser) {
this.tableUser = tableUser;
}
public UserSelectorModel getUserModel() {
return userModel;
}
public void setUserModel(UserSelectorModel userModel) {
this.userModel = userModel;
}
}
|
package com.t11e.discovery.datatool;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import javax.sql.DataSource;
import javax.xml.stream.XMLStreamException;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {"applicationContext-test.xml"})
public class SqlChangesetExtractorTest
{
@Autowired
private DataSource dataSource;
private Mockery mockery;
@Before
public void setup()
{
mockery = new Mockery();
}
@Test
public void testEmptyChangeset()
{
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
}
});
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from empty_table");
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testDateRange()
throws ParseException, XMLStreamException
{
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, String> makeMap());
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, String> makeMap());
}
});
final DateFormat format = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss.S");
final Date start = format.parse("2010-02-01-00.00.00.0000");
final Date end = format.parse("2010-02-01-00.00.03.0000");
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery(
"select id " +
"from date_range_test " +
"where last_updated >= :start and last_updated < :end");
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
extractor.writeChangeset(writer, "delta", start, end);
mockery.assertIsSatisfied();
}
@Test
public void testStringColumns()
throws XMLStreamException
{
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, String> makeMap());
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, String> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, String> makeMap(
"col_fixed", "a",
"col_string", "b",
"col_clob", "c"));
oneOf(writer).setItem(
"4",
CollectionsFactory.<String, String> makeMap(
"col_fixed", "a",
"col_string", "b",
"col_clob", "c"));
}
});
testExtractor(writer, "string_column_test");
}
@Test
public void testNumericColumns()
throws XMLStreamException
{
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, String> makeMap());
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, String> makeMap(
"col_int", "0",
"col_double", "0.0"));
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, String> makeMap(
"col_int", "12",
"col_double", "34.56"));
}
});
testExtractor(writer, "numeric_column_test");
}
@Test
public void testDateTimeColumns()
throws XMLStreamException
{
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, String> makeMap());
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, String> makeMap(
"col_date", "2010-01-01",
"col_time", "00:00:00",
"col_datetime", "2010-01-01T00:00:00.000"));
}
});
testExtractor(writer, "datetime_column_test");
}
@Test
public void testSubQueryDelimitedProperty()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.DELIMITED,
"select name from subquery_joined_test where parent_id=:id", "fish", null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fish", "redfish,bluefish"));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fish", "onefish,twofish"));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryArrayProperty()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.ARRAY,
"select name from subquery_joined_test where parent_id=:id", "fish", null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fish", Arrays.asList("redfish", "bluefish")));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fish", Arrays.asList("onefish", "twofish")));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryNonDelimitedProperty()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.ARRAY,
"select name from subquery_joined_test where parent_id=:id", "fish", null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fish", Arrays.asList("redfish", "bluefish")));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fish", Arrays.asList("onefish", "twofish")));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryDelimitedPropertyPrefix()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.DELIMITED,
"select name from subquery_joined_test where parent_id=:id", null, "fish_", ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fish_name", "redfish,bluefish"));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fish_name", "onefish,twofish"));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryDelimitedPropertyPrefixMultiColumns()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.DELIMITED,
"select parent_id as id, name from subquery_joined_test where parent_id=:id", null, "fish_", ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fish_name", "redfish,bluefish",
"fish_id", "1,1"));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fish_name", "onefish,twofish",
"fish_id", "3,3"));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@SuppressWarnings("unchecked")
@Test
public void testSubQueryArrayPropertyMultiColumns()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.ARRAY,
"select parent_id as id, name from subquery_joined_test where parent_id=:id", "fish", null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fish", Arrays.asList(
CollectionsFactory.<String, Object> makeMap("id", "1", "name", "redfish"),
CollectionsFactory.<String, Object> makeMap("id", "1", "name", "bluefish"))));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fish", Arrays.asList(
CollectionsFactory.<String, Object> makeMap("id", "3", "name", "onefish"),
CollectionsFactory.<String, Object> makeMap("id", "3", "name", "twofish"))));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryDelimitedPropertyMultiColumns()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.DELIMITED,
"select parent_id as id, name from subquery_joined_test where parent_id=:id", "fish", null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fish", CollectionsFactory.<String, Object> makeMap("id", "1,1", "name", "redfish,bluefish")));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fish", CollectionsFactory.<String, Object> makeMap("id", "3,3", "name", "onefish,twofish")));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryNonDelimitedNoProperty()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.ARRAY,
"select name as fishname from subquery_joined_test where parent_id=:id", null, null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fishname", Arrays.asList("redfish", "bluefish")));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fishname", Arrays.asList("onefish", "twofish")));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryDelimitedNoProperty()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.DELIMITED,
"select name as fishname from subquery_joined_test where parent_id=:id", null, null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fishname", "redfish,bluefish"));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fishname", "onefish,twofish"));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryDelimitedNoPropertyMultiColumns()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.DELIMITED,
"select parent_id as fishid, name as fishname from subquery_joined_test where parent_id=:id", null, null, ",",
null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fishid", "1,1",
"fishname", "redfish,bluefish"));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fishid", "3,3",
"fishname", "onefish,twofish"));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryArrayNoProperty()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.ARRAY,
"select name as fishname from subquery_joined_test where parent_id=:id", null, null, ",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fishname", Arrays.asList("redfish", "bluefish")));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fishname", Arrays.asList("onefish", "twofish")));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
@Test
public void testSubQueryArrayNoPropertyMultiColumns()
throws XMLStreamException
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from subquery_test");
action.setSubqueries(Arrays.asList(new SubQuery(SubQuery.Type.ARRAY,
"select parent_id as fishfoo, name as fishname from subquery_joined_test where parent_id=:id", null, null,
",", null)));
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
final ChangesetWriter writer = mockery.mock(ChangesetWriter.class);
mockery.checking(new Expectations()
{
{
never(writer);
oneOf(writer).setItem(
"1",
CollectionsFactory.<String, Object> makeMap(
"fishfoo", Arrays.asList("1", "1"),
"fishname", Arrays.asList("redfish", "bluefish")));
oneOf(writer).setItem(
"2",
CollectionsFactory.<String, Object> makeMap());
oneOf(writer).setItem(
"3",
CollectionsFactory.<String, Object> makeMap(
"fishfoo", Arrays.asList("3", "3"),
"fishname", Arrays.asList("onefish", "twofish")));
}
});
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
private void testExtractor(
final ChangesetWriter writer,
final String tableName)
{
final SqlChangesetExtractor extractor = new SqlChangesetExtractor();
extractor.setDataSource(dataSource);
{
final SqlAction action = new SqlAction();
action.setPropertyCase(PropertyCase.LEGACY);
action.setAction("create");
action.setIdColumn("id");
action.setQuery("select * from " + tableName);
extractor.setFilteredActions(CollectionsFactory.makeList(action));
}
extractor.writeChangeset(writer, "snapshot", null, null);
mockery.assertIsSatisfied();
}
}
|
package com.Action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.dao.zzglDao;
import com.model.tree;
public class newtreeAction {
private List<tree> list;
public List<tree> getList() {
return list;
}
public void setList(List<tree> list) {
this.list = list;
}
public String toList() throws Exception {
HttpServletResponse res = ServletActionContext.getResponse();
JSONArray tree = new JSONArray(); // return[]
JSONObject jsonObj = new JSONObject();// return{}
HttpServletRequest request = ServletActionContext.getRequest();
String mytree = request.getParameter("tree");
zzglDao gl = new zzglDao();
list = gl.tree(mytree);
for (tree x : list) {
jsonObj.put("id", x.getTree());
jsonObj.put("name",x.getTreename());
jsonObj.put("sjid", x.getSjtree());
jsonObj.put("sjname", x.getSjtreename());
tree.add(jsonObj);
}
res.setContentType("text/html;charset=utf-8");
res.getWriter().print(tree);
res.getWriter().close();
return null;
}
}
|
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(SpringJdbcConfiguration.class);
Repository repository = context.getBean(Repository.class);
Menu menu = new Menu(repository);
menu.show();
}
}
|
package com.example.findwitness;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ChatSQLiteHelper extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "chat.db";
public static final String TABLE_NAME = "chat";
public static final String TID = "_id";
public static final String SENDER = "sender";
public static final String RCV = "rcv";
public static final String SEND = "send";
public static final String MESSAGE = "message";
public static final String DATE = "date";
public static final String TIME = "time";
public ChatSQLiteHelper(Context context, String name) {
super(context, name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db){
String sql= "create table if not exists "+TABLE_NAME+ "("
+TID+" integer PRIMARY KEY autoincrement,"
+SENDER+" text,"+RCV+" integer,"+SEND+" integer,"
+MESSAGE+" text,"+DATE+" text,"+TIME+" text);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "drop table if exists student;";
db.execSQL(sql);
onCreate(db); // 다시 테이블 생성
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
|
package com.delaroystudios.teacherassistant;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v)
{
if(v.getId() == R.id.bAdmin)
{
Intent iA = new Intent(MainActivity.this, admin.class);
startActivity(iA);
}
if(v.getId() == R.id.bStaff)
{
Intent iS = new Intent(MainActivity.this, staff.class);
startActivity(iS);
}
}
}
|
package sfwinstaladorscript.createusers;
import java.awt.Cursor;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;
import sfwinstaladorscript.Utils;
import sfwinstaladorscript.createusers.objects.Role;
import sfwinstaladorscript.createusers.objects.TablespaceData;
import sfwinstaladorscript.createusers.objects.TablespaceIndex;
import sfwinstaladorscript.createusers.objects.Usuario;
import sfwinstaladorscript.createusers.objects.UsuarioSombra;
public class SfwInstaladorCreateUsers extends javax.swing.JDialog {
DefaultTableModel v_table_space;
DefaultTableModel v_table_usuario;
List<Usuario> v_list_usuario;
TablespaceData v_table_space_data;
TablespaceIndex v_table_space_index;
Role v_role;
UsuarioSombra v_usuario_sombra;
public SfwInstaladorCreateUsers(java.awt.Frame parent) {
super(parent);
initComponents();
//
v_role = new Role();
//
v_usuario_sombra = new UsuarioSombra();
//
v_list_usuario = new ArrayList<Usuario>();
//
v_table_space = (DefaultTableModel) jTableTablespace.getModel();
v_table_space.setNumRows(0);
//
v_table_usuario = (DefaultTableModel) jTableUsuarios.getModel();
v_table_usuario.setNumRows(0);
//
jTextFieldSigla.requestFocus();
}
@Action
/**
*
*/
public void geraArquivoUsuariosAndTablespaces() {
Thread geraArquivoUsuariosAndTablespaces = new Thread("geraArquivoUsuariosAndTablespaces") {
@Override
public void run() {
setLoader();
// Atualiza as informações da tela;
atualizaInformações();
// Cria a tela de visualização;
ScriptCriacaoUsuario v_criacao = new ScriptCriacaoUsuario(v_list_usuario, v_table_space_data, v_table_space_index, v_role, v_usuario_sombra);
// Reseta a tela anterior;
v_table_space.setNumRows(0);
v_table_usuario.setNumRows(0);
v_list_usuario.removeAll(v_list_usuario);
jTextFieldSigla.setText("");
jTextFieldRole.setText("");
jTextFieldUsuarioSombra.setText("");
jTextFieldPassSombra.setText("");
jButtonCriaArquivo.setEnabled(false);
jButtonCriaBase.setEnabled(false);
// Mostra a tela de visualização;
v_criacao.spool();
//
jTextFieldSigla.requestFocus();
//
setLoaderDisables();
}
};
geraArquivoUsuariosAndTablespaces.start();
}
@Action
/**
*
*/
public void geraUsuariosAndTablespaces() {
Thread geraUsuariosAndTablespaces = new Thread("geraUsuariosAndTablespaces") {
@Override
public void run() {
setLoader();
// Reseta as variáveis;
v_table_space.setNumRows(0);
v_table_usuario.setNumRows(0);
v_list_usuario.removeAll(v_list_usuario);
// Se não for preenchida a sigla, mostra um alerta;
if (jTextFieldSigla.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Digite a sigla.", Utils.getDefaultBundle().getString("Validation.warn"), JOptionPane.WARNING_MESSAGE);
jTextFieldSigla.requestFocus();
// Se for tudo ok, preenche as informações na tela;
} else {
// Informações de tablespace de data;
v_table_space.addRow(new Object[]{"TR_" + jTextFieldSigla.getText() + "_DATA", "TR_" + jTextFieldSigla.getText() + "_DATA01.ora"});
// Informações de tablespace de index;
v_table_space.addRow(new Object[]{"TR_" + jTextFieldSigla.getText() + "_INDEX", "TR_" + jTextFieldSigla.getText() + "_INDEX01.ora"});
// Informações do usuário de Base Genérica;
v_table_usuario.addRow(new Object[]{"TR" + jTextFieldSigla.getText(), "TR" + jTextFieldSigla.getText()});
// Informações do usuário de InOut;
v_table_usuario.addRow(new Object[]{"TRIO" + jTextFieldSigla.getText(), "TRIO" + jTextFieldSigla.getText()});
// Informações do usuário de Import;
v_table_usuario.addRow(new Object[]{"TRIS" + jTextFieldSigla.getText(), "TRIS" + jTextFieldSigla.getText()});
// Informações do usuário de Broker;
v_table_usuario.addRow(new Object[]{"TRBS" + jTextFieldSigla.getText(), "TRBS" + jTextFieldSigla.getText()});
// Informações do usuário de Export;
v_table_usuario.addRow(new Object[]{"TRES" + jTextFieldSigla.getText(), "TRES" + jTextFieldSigla.getText()});
// Informações do usuário de Drawback;
v_table_usuario.addRow(new Object[]{"TRDB" + jTextFieldSigla.getText(), "TRDB" + jTextFieldSigla.getText()});
// Informações do usuário de Cambio Exp;
v_table_usuario.addRow(new Object[]{"TRCE" + jTextFieldSigla.getText(), "TRCE" + jTextFieldSigla.getText()});
// Informações do usuário de Cambio Imp;
v_table_usuario.addRow(new Object[]{"TRCI" + jTextFieldSigla.getText(), "TRCI" + jTextFieldSigla.getText()});
// Informações do usuário de Integração;
v_table_usuario.addRow(new Object[]{"TRIT" + jTextFieldSigla.getText(), "TRIT" + jTextFieldSigla.getText()});
// Informações do usuário de TrackingSys;
v_table_usuario.addRow(new Object[]{"TRTS" + jTextFieldSigla.getText(), "TRTS" + jTextFieldSigla.getText()});
// Informações do usuário de Integração;
v_table_usuario.addRow(new Object[]{"TRCST" + jTextFieldSigla.getText(), "TRCST" + jTextFieldSigla.getText()});
// Cria a role;
jTextFieldRole.setText("RTR" + jTextFieldSigla.getText());
// Cria usuario sombra;
jTextFieldUsuarioSombra.setText("STR" + jTextFieldSigla.getText());
jTextFieldPassSombra.setText("TR" + jTextFieldSigla.getText());
// jButtonCriaBase.setEnabled(true);
jButtonCriaArquivo.setEnabled(true);
}
setLoaderDisables();
}
};
geraUsuariosAndTablespaces.start();
}
/**
*
*/
private void atualizaInformações() {
// Atualiza informações da ROLE;
v_role.setRole(jTextFieldRole.getText());
// Atualiza informações do sombra
v_usuario_sombra.setUsuario(jTextFieldUsuarioSombra.getText());
v_usuario_sombra.setPassword(jTextFieldPassSombra.getText());
// Cria uma tablespace de data;
v_table_space_data = new TablespaceData();
v_table_space_data.setTable_space_data(v_table_space.getValueAt(0, 0).toString());
v_table_space_data.setData_file_data(v_table_space.getValueAt(0, 1).toString());
// Cria uma tablespace de index;
v_table_space_index = new TablespaceIndex();
v_table_space_index.setTable_space_index(v_table_space.getValueAt(1, 0).toString());
v_table_space_index.setData_file_index(v_table_space.getValueAt(1, 1).toString());
// Cria um usuário para cada linha;
for (int i = 0; i < v_table_usuario.getRowCount(); i++) {
Usuario usuario = new Usuario();
usuario.setUsuario(v_table_usuario.getValueAt(i, 0).toString());
usuario.setPassword(v_table_usuario.getValueAt(i, 1).toString());
v_list_usuario.add(usuario);
}
}
/**
*
* @return
*/
private void setLoaderDisables() {
jLabelLoader.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("sfwinstaladorscript/atualizacmschema/resources/loading.png")));
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
/**
*
* @return
*/
private void setLoader() {
jLabelLoader.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("sfwinstaladorscript/atualizacmschema/resources/loading.gif")));
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanelCreateUsers = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jTextFieldSigla = new javax.swing.JTextField();
jButtonGerar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTableTablespace = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
jTableUsuarios = new javax.swing.JTable();
jButtonCriaBase = new javax.swing.JButton();
jButtonCriaArquivo = new javax.swing.JButton();
jLabelLoader = new javax.swing.JLabel();
jTextFieldRole = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jTextFieldUsuarioSombra = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jTextFieldPassSombra = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sfwinstaladorscript.SfwInstaladorScriptApp.class).getContext().getResourceMap(SfwInstaladorCreateUsers.class);
setTitle(resourceMap.getString("Form.title")); // NOI18N
setName("Form"); // NOI18N
setResizable(false);
jPanelCreateUsers.setName("jPanelCreateUsers"); // NOI18N
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel2.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel2.border.titleFont"), resourceMap.getColor("jPanel2.border.titleColor"))); // NOI18N
jPanel2.setName("jPanel2"); // NOI18N
jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jTextFieldSigla.setText(resourceMap.getString("jTextFieldSigla.text")); // NOI18N
jTextFieldSigla.setName("jTextFieldSigla"); // NOI18N
jTextFieldSigla.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldSiglaFocusGained(evt);
}
});
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(sfwinstaladorscript.SfwInstaladorScriptApp.class).getContext().getActionMap(SfwInstaladorCreateUsers.class, this);
jButtonGerar.setAction(actionMap.get("geraUsuariosAndTablespaces")); // NOI18N
jButtonGerar.setIcon(resourceMap.getIcon("jButtonGerar.icon")); // NOI18N
jButtonGerar.setText(resourceMap.getString("jButtonGerar.text")); // NOI18N
jButtonGerar.setName("jButtonGerar"); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(jLabel3)
.addGap(41, 41, 41)
.addComponent(jTextFieldSigla, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
.addGap(82, 82, 82)
.addComponent(jButtonGerar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
.addComponent(jButtonGerar)
.addComponent(jTextFieldSigla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jScrollPane1.setName("jScrollPane1"); // NOI18N
jTableTablespace.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Tablespace", "Datafile"
}
));
jTableTablespace.setName("jTableTablespace"); // NOI18N
jScrollPane1.setViewportView(jTableTablespace);
jTableTablespace.getColumnModel().getColumn(0).setResizable(false);
jTableTablespace.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTableTablespace.columnModel.title0")); // NOI18N
jTableTablespace.getColumnModel().getColumn(1).setResizable(false);
jTableTablespace.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTableTablespace.columnModel.title1")); // NOI18N
jScrollPane2.setName("jScrollPane2"); // NOI18N
jTableUsuarios.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Usuário", "Senha"
}
));
jTableUsuarios.setName("jTableUsuarios"); // NOI18N
jScrollPane2.setViewportView(jTableUsuarios);
jTableUsuarios.getColumnModel().getColumn(0).setResizable(false);
jTableUsuarios.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTableUsuarios.columnModel.title0")); // NOI18N
jTableUsuarios.getColumnModel().getColumn(1).setResizable(false);
jTableUsuarios.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTableUsuarios.columnModel.title1")); // NOI18N
jButtonCriaBase.setIcon(resourceMap.getIcon("jButtonCriaBase.icon")); // NOI18N
jButtonCriaBase.setText(resourceMap.getString("jButtonCriaBase.text")); // NOI18N
jButtonCriaBase.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButtonCriaBase.setEnabled(false);
jButtonCriaBase.setName("jButtonCriaBase"); // NOI18N
jButtonCriaArquivo.setAction(actionMap.get("geraArquivoUsuariosAndTablespaces")); // NOI18N
jButtonCriaArquivo.setIcon(resourceMap.getIcon("jButtonCriaArquivo.icon")); // NOI18N
jButtonCriaArquivo.setText(resourceMap.getString("jButtonCriaArquivo.text")); // NOI18N
jButtonCriaArquivo.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButtonCriaArquivo.setEnabled(false);
jButtonCriaArquivo.setName("jButtonCriaArquivo"); // NOI18N
jLabelLoader.setIcon(resourceMap.getIcon("jLabelLoader.icon")); // NOI18N
jLabelLoader.setName("jLabelLoader"); // NOI18N
jTextFieldRole.setName("jTextFieldRole"); // NOI18N
jTextFieldRole.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldRoleFocusGained(evt);
}
});
jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
jLabel5.setFont(resourceMap.getFont("jLabel5.font")); // NOI18N
jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
jLabel5.setName("jLabel5"); // NOI18N
jTextFieldUsuarioSombra.setName("jTextFieldUsuarioSombra"); // NOI18N
jTextFieldUsuarioSombra.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldUsuarioSombraFocusGained(evt);
}
});
jLabel6.setFont(resourceMap.getFont("jLabel6.font")); // NOI18N
jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
jLabel6.setName("jLabel6"); // NOI18N
jTextFieldPassSombra.setName("jTextFieldPassSombra"); // NOI18N
jTextFieldPassSombra.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldPassSombraFocusGained(evt);
}
});
javax.swing.GroupLayout jPanelCreateUsersLayout = new javax.swing.GroupLayout(jPanelCreateUsers);
jPanelCreateUsers.setLayout(jPanelCreateUsersLayout);
jPanelCreateUsersLayout.setHorizontalGroup(
jPanelCreateUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelCreateUsersLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelCreateUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelCreateUsersLayout.createSequentialGroup()
.addComponent(jLabelLoader)
.addContainerGap())
.addGroup(jPanelCreateUsersLayout.createSequentialGroup()
.addGroup(jPanelCreateUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE)
.addGroup(jPanelCreateUsersLayout.createSequentialGroup()
.addComponent(jButtonCriaBase, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonCriaArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelCreateUsersLayout.createSequentialGroup()
.addGap(164, 164, 164)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldUsuarioSombra, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldPassSombra, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE))
.addGap(17, 17, 17))
.addGroup(jPanelCreateUsersLayout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldRole, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanelCreateUsersLayout.setVerticalGroup(
jPanelCreateUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelCreateUsersLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelCreateUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel4)
.addComponent(jTextFieldRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jTextFieldUsuarioSombra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(jTextFieldPassSombra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(8, 8, 8)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelCreateUsersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonCriaArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonCriaBase, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelLoader, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(145, 145, 145))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelCreateUsers, 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(jPanelCreateUsers, javax.swing.GroupLayout.PREFERRED_SIZE, 541, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextFieldSiglaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldSiglaFocusGained
jTextFieldSigla.selectAll();
}//GEN-LAST:event_jTextFieldSiglaFocusGained
private void jTextFieldRoleFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldRoleFocusGained
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldRoleFocusGained
private void jTextFieldUsuarioSombraFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldUsuarioSombraFocusGained
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldUsuarioSombraFocusGained
private void jTextFieldPassSombraFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldPassSombraFocusGained
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldPassSombraFocusGained
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonCriaArquivo;
private javax.swing.JButton jButtonCriaBase;
private javax.swing.JButton jButtonGerar;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabelLoader;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanelCreateUsers;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTableTablespace;
private javax.swing.JTable jTableUsuarios;
private javax.swing.JTextField jTextFieldPassSombra;
private javax.swing.JTextField jTextFieldRole;
private javax.swing.JTextField jTextFieldSigla;
private javax.swing.JTextField jTextFieldUsuarioSombra;
// End of variables declaration//GEN-END:variables
}
|
package com.test;
import java.util.HashMap;
/**
* https://leetcode.com/problems/perfect-squares/
*
* Given a positive integer n, find the least number of perfect square numbers
* (for example, 1, 4, 9, 16, ...) which sum to n.
*
* Example 1:
*
* Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.
*
* Example 2:
*
* Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.
*
* n = (k1)^2 * a1 + (k2)^2 * a2 + (k3)^2 * a3 + ... + (1)^2 * an
*
* @author yline
*
*/
public class SolutionA {
private HashMap<Integer, Integer> minMap = new HashMap<Integer, Integer>();
public int numSquares(int n) {
minMap.put(0, 0);
minMap.put(1, 1);
minMap.put(2, 2);
minMap.put(3, 3);
minMap.put(4, 1);
return dfsFindMinCount(n);
}
/**
* 对于 n, 找到次数最少的方案
*
* @param n 字母
* @return 最少的数
*/
private int dfsFindMinCount(int n) {
// 边界条件处理
if (minMap.containsKey(n)) {
return minMap.get(n);
}
int minResult = n; // 无论如何不可能比n本身还要大
int maxK = (int) Math.sqrt(n); // 计算出当前最大值所消耗的量
int maxA = n / (maxK * maxK);
while (maxA < minResult) {
int remainN = n - maxA * maxK * maxK; // 剩余量的计算
minResult = Math.min(minResult, maxA + dfsFindMinCount(remainN)); // 剩余量的最小值 加上 这次的量;对比最小值
maxK--;
maxA = n / (maxK * maxK);
}
// 缓存一下,并返回值
minMap.put(n, minResult);
return minResult;
}
}
|
package com.Premium.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.Premium.entity.AddressEntity;
@Repository
public interface AddressRepository extends JpaRepository<AddressEntity, Integer>{
}
|
package com.fudanscetool.springboot.service;
import com.fudanscetool.springboot.dao.FeedbackDAO;
import com.fudanscetool.springboot.pojo.Feedback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FeedbackService {
@Autowired
private FeedbackDAO fdao;
/**
* 根据userID返回用户的所有反馈
* @param userID
* @return
*/
public List<Feedback> showUserFeedback(String userID) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
System.out.println(stackTrace[1].getMethodName());
return fdao.searchUserFeedback(userID);
}
public List<Feedback> showAllFeedback() {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
System.out.println(stackTrace[1].getMethodName());
return fdao.searchAllFeedback();
}
public boolean createFeedback(Feedback feedback) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
System.out.println(stackTrace[1].getMethodName());
return fdao.insertFeedback(feedback) != 0;
}
public boolean changeFeedbackStatus(Feedback feedback) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
System.out.println(stackTrace[1].getMethodName());
return fdao.updateFeedbackStatus(feedback, "read") != 0;
}
public int countUnreadFeedbackNumber() {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
System.out.println(stackTrace[1].getMethodName());
return fdao.countUnreadFeedbackNumber();
}
}
|
package at.ac.tuwien.sepm.groupphase.backend.datagenerator;
import at.ac.tuwien.sepm.groupphase.backend.entity.Category;
import at.ac.tuwien.sepm.groupphase.backend.entity.Customer;
import at.ac.tuwien.sepm.groupphase.backend.entity.Invoice;
import at.ac.tuwien.sepm.groupphase.backend.entity.InvoiceItem;
import at.ac.tuwien.sepm.groupphase.backend.entity.InvoiceItemKey;
import at.ac.tuwien.sepm.groupphase.backend.entity.InvoiceType;
import at.ac.tuwien.sepm.groupphase.backend.entity.Order;
import at.ac.tuwien.sepm.groupphase.backend.entity.Product;
import at.ac.tuwien.sepm.groupphase.backend.entity.TaxRate;
import at.ac.tuwien.sepm.groupphase.backend.exception.NotFoundException;
import at.ac.tuwien.sepm.groupphase.backend.repository.CategoryRepository;
import at.ac.tuwien.sepm.groupphase.backend.repository.CustomerRepository;
import at.ac.tuwien.sepm.groupphase.backend.repository.InvoiceItemRepository;
import at.ac.tuwien.sepm.groupphase.backend.repository.InvoiceRepository;
import at.ac.tuwien.sepm.groupphase.backend.repository.OrderRepository;
import at.ac.tuwien.sepm.groupphase.backend.repository.ProductRepository;
import at.ac.tuwien.sepm.groupphase.backend.repository.TaxRateRepository;
import at.ac.tuwien.sepm.groupphase.backend.service.OrderService;
import com.github.javafaker.Faker;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.lang.invoke.MethodHandles;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Profile("generateData")
@Component
public class ProductDataGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final Map<Double, Double> TAX_RATES = Map.of(10.0, 1.10, 13.00, 1.13, 20.0, 1.20);
private final ProductRepository productRepository;
private final CategoryRepository categoryRepository;
private final TaxRateRepository taxRateRepository;
private final InvoiceRepository invoiceRepository;
private final InvoiceItemRepository invoiceItemRepository;
private final CustomerRepository customerRepository;
private final OrderService orderService;
private final OrderRepository orderRepository;
public ProductDataGenerator(ProductRepository productRepository, CategoryRepository categoryRepository,
TaxRateRepository taxRateRepository, InvoiceRepository invoiceRepository,
InvoiceItemRepository invoiceItemRepository, CustomerRepository customerRepository,
OrderService orderService, OrderRepository orderRepository) {
this.productRepository = productRepository;
this.categoryRepository = categoryRepository;
this.taxRateRepository = taxRateRepository;
this.invoiceRepository = invoiceRepository;
this.invoiceItemRepository = invoiceItemRepository;
this.customerRepository = customerRepository;
this.orderService = orderService;
this.orderRepository = orderRepository;
}
@PostConstruct
public void generateProducts() {
if (productRepository.count() > 0) {
LOGGER.debug("products already generated");
} else {
for (Map.Entry<Double, Double> entry : TAX_RATES.entrySet()) {
TaxRate taxRate = TaxRate.TaxRateBuilder.getTaxRateBuilder()
.withPercentage(entry.getKey())
.withCalculationFactor(entry.getValue())
.build();
taxRateRepository.save(taxRate);
}
Category category1 = Category.CategoryBuilder.getCategoryBuilder()
.withName("IT & Elektronik")
.build();
categoryRepository.save(category1);
Category category2 = Category.CategoryBuilder.getCategoryBuilder()
.withName("Möbel")
.build();
categoryRepository.save(category2);
Category category3 = Category.CategoryBuilder.getCategoryBuilder()
.withName("Obst & Gemüse")
.build();
categoryRepository.save(category3);
Category category4 = Category.CategoryBuilder.getCategoryBuilder()
.withName("Kleidung")
.build();
categoryRepository.save(category4);
TaxRate taxRate2 = this.taxRateRepository.findById(2L).orElseThrow(() -> new NotFoundException("Steuersatz konnte nicht gefunden werden"));
Product product1 = Product.ProductBuilder.getProductBuilder()
.withName("Banane")
.withDescription("leckere Bananen aus Ecuador")
.withPrice(1.49)
.withTaxRate(taxRate2)
.withCategory(category3).withSaleCount(0L)
.build();
productRepository.save(product1);
TaxRate taxRate3 = this.taxRateRepository.findById(3L).orElseThrow(() -> new NotFoundException("Steuersatz konnte nicht gefunden werden"));
Faker faker = new Faker(new Locale("de-AT"));
TaxRate taxRate1 = this.taxRateRepository.findById(1L).orElseThrow(() -> new NotFoundException("Steuersatz konnte nicht gefunden werden"));
generateProductsWithTaxRate(taxRate1, category1, category2, category3, category4, faker);
generateProductsWithTaxRate(taxRate2, category1, category2, category3, category4, faker);
generateProductsWithTaxRate(taxRate3, category1, category2, category3, category4, faker);
generateInvoices();
}
}
@Transactional
public void generateProductsWithTaxRate(TaxRate taxRate, Category category1, Category category2, Category category3, Category category4, Faker faker) {
for (int i = 0; i < 10; i++) {
Date past = faker.date().past(10, 4, TimeUnit.DAYS);
LocalDateTime pastLocalDateTime = LocalDateTime.ofInstant(past.toInstant(), ZoneId.of("UTC"));
Date future = faker.date().future(10, 4, TimeUnit.DAYS);
LocalDateTime futureLocalDateTime = LocalDateTime.ofInstant(future.toInstant(), ZoneId.of("UTC"));
Product prod = Product.ProductBuilder.getProductBuilder()
.withName(faker.space().nasaSpaceCraft())
.withDescription(faker.lorem().sentence(2))
.withPrice(faker.number().randomDouble(2, 1, 100))
.withTaxRate(taxRate)
.withCategory(category1)
.withExpiresAt(futureLocalDateTime).withSaleCount(0L)
.build();
Long prodId = productRepository.save(prod).getId();
Product prod1 = Product.ProductBuilder.getProductBuilder()
.withName(faker.food().ingredient())
.withDescription(faker.lorem().sentence(2))
.withPrice(faker.number().randomDouble(2, 1, 100))
.withTaxRate(taxRate)
.withCategory(category2)
.withExpiresAt(pastLocalDateTime).withSaleCount(0L)
.build();
Long prodId1 = productRepository.save(prod1).getId();
Product prod2 = Product.ProductBuilder.getProductBuilder()
.withName(faker.food().spice())
.withDescription(faker.lorem().sentence(2))
.withPrice(faker.number().randomDouble(2, 1, 100))
.withTaxRate(taxRate)
.withCategory(category3).withSaleCount(0L)
.build();
Long prodId2 = productRepository.save(prod2).getId();
Product prod3 = Product.ProductBuilder.getProductBuilder()
.withName(faker.food().vegetable())
.withDescription(faker.lorem().sentence(2))
.withPrice(faker.number().randomDouble(2, 1, 100))
.withTaxRate(taxRate)
.withCategory(category4).withSaleCount(0L)
.build();
Long prodId3 = productRepository.save(prod3).getId();
}
}
private void generateInvoices() {
if (invoiceRepository.count() > 0) {
LOGGER.debug("invoices already generated");
} else {
List<Product> products = productRepository.findAll();
for (int i = 1; i <= 700; i++) {
int rand = (int) (Math.random() * 10) + 1;
List<InvoiceItem> items = new ArrayList<>();
int[] used = new int[rand];
Invoice invoice = new Invoice();
double amount = 0;
for (int j = 0; j < rand; j++) {
InvoiceItem item = new InvoiceItem();
int prodId = (int) (Math.random() * products.size());
while (ArrayUtils.contains(used, prodId)) {
prodId = (int) (Math.random() * products.size());
}
used[j] = prodId;
Product p = products.get(prodId);
item.setProduct(p);
int quantity = (int) (Math.random() * 4) + 1;
item.setNumberOfItems(quantity);
items.add(item);
amount += (item.getNumberOfItems() * (p.getPrice() * p.getTaxRate().getCalculationFactor()));
}
int daysPast = (int) (Math.random() * 400) + 1;
invoice.setDate(LocalDateTime.now().minus(daysPast, ChronoUnit.DAYS));
invoice.setAmount((double) Math.round(amount * 100) / 100);
invoice.setInvoiceNumber(i + "Operator" + invoice.getDate().getYear());
if (i % 100 == 0) {
invoice.setInvoiceType(InvoiceType.canceled);
} else {
invoice.setInvoiceType(InvoiceType.operator);
}
Invoice newInvoice = invoiceRepository.save(invoice);
for (InvoiceItem item : items) {
item.setInvoice(newInvoice);
InvoiceItemKey itemId = new InvoiceItemKey();
itemId.setInvoiceId(newInvoice.getId());
item.setId(itemId);
Set<InvoiceItem> itemSet = new HashSet<>();
itemSet.add(item);
invoice.setItems(itemSet);
invoiceItemRepository.save(item);
}
}
List<Customer> customers = customerRepository.findAll();
for (int i = 1; i <= 1000; i++) {
int rand = (int) (Math.random() * 10) + 1;
List<InvoiceItem> items = new ArrayList<>();
int[] used = new int[rand];
Invoice invoice = new Invoice();
double amount = 0;
for (int j = 0; j < rand; j++) {
InvoiceItem item = new InvoiceItem();
int prodId = (int) (Math.random() * products.size());
while (ArrayUtils.contains(used, prodId)) {
prodId = (int) (Math.random() * products.size());
}
used[j] = prodId;
Product p = products.get(prodId);
item.setProduct(p);
int quantity = (int) (Math.random() * 4) + 1;
item.setNumberOfItems(quantity);
items.add(item);
amount += (item.getNumberOfItems() * (p.getPrice() * p.getTaxRate().getCalculationFactor()));
}
int daysPast = (int) (Math.random() * 400) + 1;
invoice.setDate(LocalDateTime.now().minus(daysPast, ChronoUnit.DAYS));
invoice.setAmount((double) Math.round(amount * 100) / 100);
invoice.setInvoiceNumber(i + "Customer" + invoice.getDate().getYear());
int custId = (int) (Math.random() * customers.size());
invoice.setCustomerId(customers.get(custId).getId());
invoice.setOrderNumber("Test" + i);
if (i % 100 == 0) {
invoice.setInvoiceType(InvoiceType.canceled);
} else {
invoice.setInvoiceType(InvoiceType.customer);
}
Invoice newInvoice = invoiceRepository.save(invoice);
for (InvoiceItem item : items) {
item.setInvoice(newInvoice);
InvoiceItemKey itemId = new InvoiceItemKey();
itemId.setInvoiceId(newInvoice.getId());
item.setId(itemId);
Set<InvoiceItem> itemSet = new HashSet<>();
itemSet.add(item);
invoice.setItems(itemSet);
invoiceItemRepository.save(item);
}
Order order = new Order(invoice, customers.get(custId));
orderService.updateProductsInOrder(order);
orderRepository.save(order);
}
}
}
}
|
package by.bytechs.fileSystem;
import by.bytechs.fileSystem.interfaces.ScreenShot;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author Romanovich Andrei
*/
@Service
public class ScreenShotImpl implements ScreenShot {
@Override
public BufferedImage getScreenshot() throws AWTException, IOException {
System.setProperty("java.awt.headless", "false");
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Rectangle screenRect = new Rectangle(screenSize);
Robot robot = new Robot();
return robot.createScreenCapture(screenRect);
}
@Override
public byte[] bufferedImageToByteArray(BufferedImage image, String format) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, format, baos);
return baos.toByteArray();
}
@Override
public BufferedImage scale(BufferedImage source, int w, int h) {
Image image = source
.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING);
BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = result.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return result;
}
@Override
public BufferedImage shrink(BufferedImage source, double factor) {
int w = (int) (source.getWidth() * factor);
int h = (int) (source.getHeight() * factor);
return scale(source, w, h);
}
@Override
public BufferedImage copyBufferedImage(BufferedImage image) {
BufferedImage copyOfIm = new BufferedImage(image.getWidth(), image
.getHeight(), image.getType());
Graphics2D g = copyOfIm.createGraphics();
g.drawRenderedImage(image, null);
g.dispose();
return copyOfIm;
}
} |
package com.gaoshin.entity;
import java.util.Calendar;
import java.util.TimeZone;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.gaoshin.beans.Location;
@Entity
@Table(name = "device_loc")
public class DeviceLocationEntity extends GenericEntity {
@Column(columnDefinition = "FLOAT", length = 12, precision = 12, scale = 5)
private Float latitude;
@Column(columnDefinition = "FLOAT", length = 12, precision = 12, scale = 5)
private Float longitude;
@Column(length = 255)
private String address;
@Column(length = 128)
private String city;
@Column(length = 128)
private String state;
@Column(length = 20)
private String zipcode;
@Column(length = 255)
private String country;
@Column(name = "FIRST_UPDATE")
@Temporal(TemporalType.TIMESTAMP)
private Calendar firstUpdate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
@Column(name = "LAST_UPDATE")
@Temporal(TemporalType.TIMESTAMP)
private Calendar lastUpdate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
@JoinColumn(name = "user_id")
private UserEntity userEntity;
public DeviceLocationEntity() {
}
public DeviceLocationEntity(Location bean) {
super(bean);
}
public Float getLatitude() {
return latitude;
}
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
public Float getLongitude() {
return longitude;
}
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
public void setLastUpdate(Calendar lastUpdate) {
this.lastUpdate = lastUpdate;
}
public void resetLastUpdate() {
this.lastUpdate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
}
public Calendar getLastUpdate() {
return lastUpdate;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setUserEntity(UserEntity userEntity) {
this.userEntity = userEntity;
}
public UserEntity getUserEntity() {
return userEntity;
}
public void setFirstUpdate(Calendar firstUpdate) {
this.firstUpdate = firstUpdate;
}
public Calendar getFirstUpdate() {
return firstUpdate;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getZipcode() {
return zipcode;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
}
|
package com.minhvu.proandroid.sqlite.database.receiver;
import com.minhvu.proandroid.sqlite.database.services.SignInService;
/**
* Created by vomin on 1/9/2018.
*/
public class SignInReceiver extends ALongRunningReceiver {
@Override
public Class getLRSClass() {
return SignInService.class;
}
}
|
package io.github.yanhu32.xpathkit.parser;
import io.github.yanhu32.xpathkit.utils.Strings;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
/**
* Jaxp XPath解析
*
* @author yh
* @since 2021/4/22
*/
public class JaxpXPathParser extends AbstractXPathParser {
private final Document document;
private final XPath xpath;
public JaxpXPathParser(String xml) {
super(xml);
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(getXml().getBytes(StandardCharsets.UTF_8))) {
// 根据xml构建Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
document = builder.parse(inputStream);
xpath = XPathFactory.newInstance().newXPath();
} catch (Exception e) {
System.err.println("读取xml异常 e: " + e.getClass().getName() + " -> " + e.getMessage());
throw new IllegalArgumentException(e);
}
}
@Override
public String getText(String xpath) {
if (Strings.isNotEmpty(xpath)) {
try {
return this.xpath.evaluate(xpath, document);
} catch (XPathExpressionException e) {
System.err.println("XPath表达式(" + xpath + ")解析异常 e: " + e.getClass().getName() + " -> " + e.getMessage());
e.printStackTrace();
}
}
return null;
}
public static JaxpXPathParser of(String xml) {
return new JaxpXPathParser(xml);
}
public Document getDocument() {
return document;
}
public XPath getXpath() {
return xpath;
}
}
|
package com.karya.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="costcenter001mb")
public class CostCenter001MB implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "centId")
private int centId;
@Column(name="centerName")
private String centerName;
public int getCentId() {
return centId;
}
public void setCentId(int centId) {
this.centId = centId;
}
public String getCenterName() {
return centerName;
}
public void setCenterName(String centerName) {
this.centerName = centerName;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package com.BDD.blue_whale.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.BDD.blue_whale.entities.World_language;
@Service
public interface World_languageService {
public void addWorld_language(World_language world_language);
public List<World_language> listWorld_language();
public Optional<World_language> getWorld_languageById(String alpha2);
public void deleteWorld_language(String alpha2);
public void updateWorld_language(World_language world_language);
}
|
package com.wenyuankeji.spring.dao;
import java.util.List;
import com.wenyuankeji.spring.model.BaseBusinessareaModel;
import com.wenyuankeji.spring.model.BaseConfigModel;
import com.wenyuankeji.spring.util.BaseException;
public interface IBaseConfigDao {
/**
* 查询基础设置表
* @param configcode 配置编码
* @return
* @throws BaseException
*/
public BaseConfigModel searchBaseConfigByCode(String configcode)throws BaseException;
/**
* 查询基础设置表
* @param configcode 配置编码
* @return
* @throws BaseException
*/
public List<BaseConfigModel> searchBaseConfigList(String configcode)throws BaseException;
/**
* 修改配置信息
* @param configcode 配置编码
* @param cofigvalue 值
* @return
*/
public boolean updateBaseConfig(String configcode, String configvalue);
/**
* 查询首页图片
* @param configcode 配置编码
* @param cofigvalue 值
* @return
*/
public BaseConfigModel searchBaseConfigByCode(String configcode, String configvalue)throws BaseException;
/**
* 修改首页图片
* @param configcode 配置编码
* @param cofigvalue 值
* @param value1 picid值
* @return
*/
public boolean updateBaseConfig(String configcode, String configvalue, String value1)throws BaseException;
public List<BaseConfigModel> searchBaseConfig(String configcode)throws BaseException;
/**
* 根据编码更新配置信息
* @param configcode
* @param configvalue
* @return
* @throws BaseException
*/
public boolean updateBaseConfigByConfigCode(String configcode, String configvalue)throws BaseException;
/**
* 添加商圈
* @return
* @throws BaseException
*/
public boolean addBaseBusinessarea(BaseBusinessareaModel o)
throws BaseException;
/**
* 设置配置表
* @return
* @throws BaseException
*/
public boolean addBaseConfig(BaseConfigModel o)
throws BaseException;
}
|
import java.io.*;
import java.util.*;
public class sortZeroOneTwo{
public static void main(String[] args){
/*
Swapping index 1 and index 0
Swapping index 2 and index 9
Swapping index 2 and index 8
Swapping index 2 and index 1
Swapping index 3 and index 7
Swapping index 5 and index 2
Swapping index 6 and index 6
0
0
0
1
1
1
2
2
2
2
*/
int n = 10;
int[] arr = { 1, 0, 2, 2, 1, 0, 2, 1, 0, 2};
sortZeroOneTwo(arr);
print(arr);
}
public static void sortZeroOneTwo(int[] arr){
int i = 0, j = 0, k = arr.length - 1;
while(i <= k){
if(arr[i] == 0){
swap(arr, i, j);
i++;
j++;
}
else if (arr[i] == 1){
i++;
}
else{
swap(arr, i, k);
k--;
}
}
}
public static void swap(int[] arr, int i, int j) {
System.out.println("Swapping index " + i + " and index " + j);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void print(int[] arr){
for(int i = 0 ; i < arr.length; i++){
System.out.println(arr[i]);
}
}
} |
package com.esum.comp.pull.handler;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.pull.PullCode;
import com.esum.comp.pull.PullConfig;
import com.esum.comp.pull.PullException;
import com.esum.comp.pull.PullRequester;
import com.esum.comp.pull.table.PullInfoRecord;
import com.esum.framework.common.util.ClassUtil;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.pull.PullSoapDataRequester;
import com.esum.framework.http.HttpClientTemplate;
import com.esum.framework.http.HttpClientTemplateFactory;
import com.esum.framework.http.HttpOperationException;
import com.esum.framework.http.HttpPostCreator;
import com.esum.framework.http.HttpResponse;
import com.esum.framework.net.http.HTTPException;
import com.esum.framework.security.auth.HTTPAuthInfo;
import com.esum.framework.security.auth.HTTPAuthManager;
import com.esum.framework.security.auth.HTTPBasicAuthentication;
import com.esum.framework.security.pki.manager.PKIException;
/**
* SOAP 메시지를 수신 받는 클래스
*/
public class SoapPullRequester implements PullRequester {
private Logger logger = LoggerFactory.getLogger(SoapPullRequester.class);
private PullInfoRecord infoRecord;
private String traceId;
private PullSoapDataRequester dataRequester;
public SoapPullRequester(PullInfoRecord infoRecord){
this.infoRecord = infoRecord;
}
public byte[] process(String messageCtrlId) throws ComponentException {
this.traceId = "["+infoRecord.getInterfaceId()+"] ["+messageCtrlId+"] ";
logger.info(traceId+"SOAP Message Receiving start.");
String creatorClass = infoRecord.getHttpMessageCreator();
if(StringUtils.isNotEmpty(creatorClass)) {
if(this.dataRequester==null) {
try {
this.dataRequester = (PullSoapDataRequester)ClassUtil.forName(creatorClass).newInstance();
} catch (Exception e) {
logger.error(traceId+"Could not invoke class. class : "+creatorClass, e);
throw new PullException(PullCode.ERROR_CREATE_PULL_CLASS, "request()", e.getMessage());
}
}
} else {
this.dataRequester = new PullSoapDataRequester() {
private HttpEntity createRequestEntity(SOAPMessage message) throws PullException {
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
message.writeTo(out);
ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
entity.setContentType("application/xml");
return entity;
} catch (Exception e) {
throw new PullException(PullCode.ERROR_SEND_MESSAGE, "createRequestEntity()", e.getMessage(), e);
} finally {
IOUtils.closeQuietly(out);
}
}
@Override
public byte[] request(String url, final Map<String, String> headerList, final SOAPMessage soapMessage, HttpClientTemplate client)
throws PullException {
try {
HttpResponse httpResponse = client.invokePost(url, new HttpPostCreator(){
@Override
public HttpPost createHttpPost(HttpPost httpPost) throws HttpOperationException {
Iterator<String> i = headerList.keySet().iterator();
while(i.hasNext()) {
String name = i.next();
String value = headerList.get(name);
httpPost.addHeader(name, value);
}
try {
httpPost.setEntity(createRequestEntity(soapMessage));
} catch (PullException e) {
throw new HttpOperationException(e.getMessage());
}
return httpPost;
}
});
if(!httpResponse.isCompleted())
throw new HttpOperationException("Received '"+httpResponse.getStatusCode()+"' Response status("+httpResponse.getStatusString()+")");
return httpResponse.getData();
} catch (Exception e) {
throw new PullException(PullCode.ERROR_SEND_HTTP_MESSAGE, "request()", e.getMessage());
}
}
};
}
HttpClientTemplate httpClient = null;
try {
httpClient = HttpClientTemplateFactory.getInstance().getDefaultHttpClientTemplate();
httpClient.setConnectionTimeout(PullConfig.HTTP_CONNECTION_TIMEOUT);
httpClient.setSocketTimeout(PullConfig.HTTP_READ_TIMEOUT);
} catch (Exception e) {
throw new PullException(PullCode.ERROR_SEND_HTTP_MESSAGE, "request()", e.getMessage());
}
Map<String, String> headerList = createRequestHeader();
SOAPMessage soapMessage = null;
try {
soapMessage = createSOAPMessage();
return this.dataRequester.request(infoRecord.getHttpEndpointUrl(), headerList, soapMessage, httpClient);
} catch (SOAPException e) {
throw new PullException(PullCode.ERROR_SEND_MESSAGE, "request()", e.getMessage());
} finally {
if(httpClient!=null) {
httpClient.close();
}
httpClient = null;
}
}
private SOAPMessage createSOAPMessage() throws SOAPException {
MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
return factory.createMessage();
}
private Map<String, String> createRequestHeader() throws PullException {
Map<String, String> headerList = new HashMap<String, String>();
try {
headerList.put("SOAPAction", "\"\"");
headerList.put("Connection", "Keep-Alive");
headerList.put("User-Agent", "xTrus SOAP Pull Connector");
headerList.put("Content-Type", "text/xml");
if(StringUtils.isNotEmpty(infoRecord.getHttpAuthId())) {
HTTPAuthInfo authInfo = HTTPAuthManager.getInstance().getHTTPAuthInfo(infoRecord.getHttpAuthId());
if(authInfo==null)
throw new PullException(PullCode.ERROR_HTTP_AUTH_GENERATE, "createRequestHeader()",
"Can not found http auth info. check the http auth info. id : "+infoRecord.getHttpAuthId());
String basicAuth = HTTPBasicAuthentication.getInstance().generateValue(authInfo);
if (basicAuth != null && basicAuth.length() != 0) {
headerList.put("Authorization", basicAuth);
}
}
} catch (HTTPException e) {
throw new PullException(PullCode.ERROR_HTTP_AUTH_GENERATE, "createRequestHeader()", e.toString());
} catch (PKIException e) {
throw new PullException(PullCode.ERROR_HTTP_AUTH_GENERATE, "createRequestHeader()", e.toString());
} catch (Exception e) {
logger.error(traceId+"unknown error", e);
throw new PullException(PullCode.ERROR_UNDEFINED, "createRequestHeader()", e.toString());
}
return headerList;
}
}
|
// **********************************************************
// 1. 제 목: 역량 분류
// 2. 프로그램명: UserAbilityBean.java
// 3. 개 요: 역량 분류
// 4. 환 경: JDK 1.4
// 5. 버 젼: 1.0
// 6. 작 성: jang dong jin 2007.12.10
// 7. 수 정:
// **********************************************************
package com.ziaan.ability;
import java.util.*;
import java.sql.*;
import com.ziaan.library.*;
import com.ziaan.ability.*;
public class UserAbilityBean {
public UserAbilityBean() { }
/**
내 직급 정보
@param box receive from the form object and session
@return ArrayList 리스트
*/
public DataBox myInfo(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
//직급 직위 성별 가져오기.
sql = "SELECT COMP, JIKUP, JIKWI, GET_JIKUPNM(JIKWI, COMP) JIKWINM, ";
sql += " GET_JIKUPNM(JIKUP, COMP) JIKUPNM , GET_COMPNM(COMP,2,2) COMPNM, ";
sql += " DECODE(SUBSTR(birth_date, 7,1), '3', '1', '4', '2', SUBSTR(birth_date, 7, 1)) AS SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
//직급. 직위 정보 넣기
box.put("p_jikup", ls.getString("jikup"));
box.put("p_jikupnm", ls.getString("jikupnm"));
box.put("p_jikwi", ls.getString("jikwi"));
box.put("p_jikwinm", ls.getString("jikwinm"));
box.put("p_deptnm", ls.getString("compnm"));
dbox = ls.getDataBox();
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return dbox;
}
/**
역량 군 Select Box 조회
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList selectAbilityCdDt(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getStringDefault("p_gubuncd", "10002");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT GUBUNCDDT, GUBUNCDDTNM ";
sql += "FROM TZ_ABILITY_CODE_DT ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "ORDER BY GUBUNCDDT ASC ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
역량 분류 안내 목록
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getStringDefault("p_gubuncd", "NOT");
String v_gubuncddt = box.getStringDefault("p_gubuncddt", "NOT");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT ABILITY, ABILITYNM, DESCS, INDATE ";
sql += "FROM TZ_ABILITY ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
// if(!v_gubuncddt.equals("ALL")){
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
// }
sql += "ORDER BY ORDERS ASC ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
역량 분류 실행/결과 목록
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityResultList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String s_userid = box.getSession("userid");
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
//String v_gubuncd = box.getStringDefault("p_gubuncd", "10002");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
/*
sql = "SELECT C.NAME, C.USERID, A.INDATE, A.RESULTSEQ, TO_CHAR(A.RESULTPOINT) RESULTPOINT, ";
sql += " A.GUBUNCD, A.GUBUNCDDT, f.gubuncdnm, B.GUBUNCDDTNM, GET_JIKUPNM(C.JIKWI, C.COMP) JIKWINM, ";
sql += " GET_JIKUPNM(C.JIKUP, C.COMP) JIKUPNM , GET_COMPNM(C.COMP,2,2) COMPNM, ";
sql += " NVL(E.CNT,0) AS SELCNT, NVL(D.TOTCNT,0) AS TOTCNT, ";
sql += " DECODE(NVL(D.TOTCNT,0),0,0,ROUND(NVL(E.CNT,0) / NVL(D.TOTCNT,0) * 100,1)) AS PERCENT ";
sql += "FROM TZ_ABILITY_RSLT_MAS A ";
sql += " LEFT OUTER JOIN TZ_ABILITY_CODE_DT B ";
sql += " ON A.GUBUNCD = B.GUBUNCD ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT ";
sql += " INNER JOIN TZ_MEMBER C ";
sql += " ON A.USERID = C.USERID ";
sql += " AND C.USERID = '"+ s_userid +"' LEFT OUTER JOIN tz_ability_code f on a.gubuncd=f.GUBUNCD ";
sql += " LEFT OUTER JOIN ( ";
sql += " SELECT GUBUNCD, GUBUNCDDT, COUNT(GUBUNCD) AS TOTCNT ";
sql += " FROM TZ_ABILITY_PRO ";
sql += " GROUP BY GUBUNCD, GUBUNCDDT) D ";
sql += " ON A.GUBUNCD = D.GUBUNCD ";
sql += " AND A.GUBUNCDDT = D.GUBUNCDDT ";
sql += " LEFT OUTER JOIN ( ";
sql += " SELECT RESULTSEQ, GUBUNCD, GUBUNCDDT, COUNT(USERID) AS CNT ";
sql += " FROM TZ_ABILITY_RSLT_DT ";
sql += " WHERE USERID = '"+ s_userid +"' ";
sql += " GROUP BY RESULTSEQ, GUBUNCD, GUBUNCDDT) E ";
sql += " ON A.GUBUNCD = E.GUBUNCD ";
sql += " AND A.GUBUNCDDT = E.GUBUNCDDT ";
sql += " AND A.RESULTSEQ = E.RESULTSEQ ";
sql += "WHERE A.USERID = '"+ s_userid +"' ";
sql += "AND F.GUBUN = 'Y' and a.resultseq <1000000 ";
*/
/* 직위, 직급삭제, 다면진단 수행내역 제외*/
sql = "SELECT C.NAME, C.USERID, A.INDATE, A.RESULTSEQ, TO_CHAR(A.RESULTPOINT) RESULTPOINT, \n ";
sql += " A.GUBUNCD, A.GUBUNCDDT, f.gubuncdnm, B.GUBUNCDDTNM, \n ";
sql += " GET_COMPNM(C.COMP) COMPNM, \n ";
sql += " NVL(E.CNT,0) AS SELCNT, NVL(D.TOTCNT,0) AS TOTCNT, \n ";
sql += " DECODE(NVL(D.TOTCNT,0),0,0,ROUND(NVL(E.CNT,0) / NVL(D.TOTCNT,0) * 100,1)) AS PERCENT \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS A \n ";
sql += " LEFT OUTER JOIN TZ_ABILITY_CODE_DT B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " INNER JOIN TZ_MEMBER C \n ";
sql += " ON A.USERID = C.USERID \n ";
sql += " AND C.USERID = '"+ s_userid +"' \n ";
sql += " LEFT OUTER JOIN TZ_ABILITY_CODE F \n ";
sql += " ON A.GUBUNCD = F.GUBUNCD \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, COUNT(GUBUNCD) AS TOTCNT \n ";
sql += " FROM TZ_ABILITY_PRO \n ";
sql += " GROUP BY GUBUNCD, GUBUNCDDT) D \n ";
sql += " ON A.GUBUNCD = D.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = D.GUBUNCDDT \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT AA.RESULTSEQ, AA.GUBUNCD, AA.GUBUNCDDT, COUNT(AA.USERID) AS CNT, PUSERID \n ";
sql += " FROM TZ_ABILITY_RSLT_DT AA LEFT OUTER JOIN TZ_ABILITY_RSLT_ABL BB \n ";
sql += " ON AA.GUBUNCD = BB.GUBUNCD \n ";
sql += " AND AA.GUBUNCDDT = BB.GUBUNCDDT \n ";
sql += " AND AA.USERID = BB.USERID \n ";
sql += " AND AA.RESULTSEQ = BB.RESULTSEQ \n ";
sql += " AND AA.ABILITY = BB.ABILITY \n ";
sql += " WHERE AA.USERID = '"+ s_userid +"' \n ";
sql += " GROUP BY AA.RESULTSEQ, AA.GUBUNCD, AA.GUBUNCDDT, PUSERID) E \n ";
sql += " ON A.GUBUNCD = E.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = E.GUBUNCDDT \n ";
sql += " AND A.RESULTSEQ = E.RESULTSEQ \n ";
sql += " WHERE A.USERID = '"+ s_userid +"' \n ";
sql += " AND F.GUBUN = 'Y' \n ";
sql += " AND E.PUSERID = '"+ s_userid +"' \n ";
sql += " AND A.RESULTSEQ < 1000000 \n ";
/*
if(!v_gubuncd.equals("")){
sql += "AND A.GUBUNCD = '"+ v_gubuncd +"' \n ";
}
*/
sql += "ORDER BY F.GUBUNCDNM, B.GUBUNCDDTNM, A.INDATE DESC \n ";
ls = connMgr.executeQuery(sql);
//Log.sys.println("=============역량 분류 실행/결과 목록========\n"+sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
역량 실행 목록
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityDtList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getStringDefault("p_gubuncd", "NOT");
String v_gubuncddt = box.getStringDefault("p_gubuncddt","NOT");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT A.GUBUNCD, A.GUBUNCDDT, A.GUBUNCDDTNM, B.CNT_GUBUNCD, A.DESCS ";
sql += " FROM TZ_ABILITY_CODE_DT a, \n" +
" (SELECT GUBUNCD, GUBUNCDDT, COUNT(GUBUNCD) CNT_GUBUNCD FROM TZ_MSIDEPAR_MAS \n" +
" WHERE GUBUNCD = '"+ v_gubuncd +"' \n" +
" AND GUBUNCDDT = '"+ v_gubuncddt +"' \n" +
" GROUP BY GUBUNCD, GUBUNCDDT ) B \n" +
" WHERE A.GUBUNCD = B.GUBUNCD(+) \n" +
" AND A.GUBUNCDDT = B.GUBUNCDDT(+) ";
sql += " and a.GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND a.GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "ORDER BY a.GUBUNCD, a.GUBUNCDDT ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
역량 실행 목록
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityProList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String v_userid = box.getSession("userid");
String s_userid = "";
//다면진단 여부
String v_ismulti = box.getString("p_ismulti"); //
//다면진단일 경우
if(v_ismulti.equals("multi")){
s_userid = box.getString("p_userid"); //피진단자 = userid
}else{
s_userid = box.getSession("userid");
}
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT A.GUBUNCD, A.GUBUNCDDT, A.ABILITY, A.ABILITYPRO,A.ABILITYPRODESC, ";
sql += " B.INPUTS, B.INDATE ";
sql += "FROM TZ_ABILITY_PRO A ";
sql += " LEFT OUTER JOIN TZ_ABILITY_RSLT_DT B ";
sql += " ON A.GUBUNCD = B.GUBUNCD ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT ";
sql += " AND A.ABILITY = B.ABILITY ";
sql += " AND A.ABILITYPRO = B.ABILITYPRO ";
sql += " and b.puserid ='"+v_userid+"' \n";
sql += " AND B.USERID = '"+ s_userid +"' ";
if (!v_resultseq.equals("")){
sql += " AND B.RESULTSEQ = '"+ v_resultseq +"' ";
}
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "ORDER BY A.ORDERS ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
역량 평가 처음 입장 했을때 마스터에 등록
@param box receive from the form object and session
@return isOk 1:insert success,0:insert fail
*/
public int insertMas(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
PreparedStatement pstmt = null;
String sql = "";
String sql1 = "";
int isOk = 0;
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String s_userid = box.getSession("userid");
String v_resultseq = "0";
String v_comp = "";
String v_jikup = box.getString("p_jikup");
String v_jikryul = "";
String v_sex = "";
try {
connMgr = new DBConnectionManager();
sql = "SELECT NVL(MAX(RESULTSEQ),0) + 1 AS RESULTSEQ ";
sql += "FROM TZ_ABILITY_RSLT_MAS \n" +
" where RESULTSEQ < 1000000 ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_resultseq = ls.getString("resultseq");
}
if(ls!=null)ls.close();
box.put("p_resultseq", v_resultseq);
/*
sql = "SELECT COMP, JIKUP, JIKRYUL, SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_comp = ls.getString("comp");
v_jikup = ls.getString("jikup");
v_jikryul = ls.getString("jikryul");
v_sex = ls.getString("sex");
}
*/
/* comp, birth_date만 멤버테이블에서 가져옴, 직급은 진단실시 시작시 선택한 값으로 대체 09.11.10 수정 */
sql = " SELECT COMP, birth_date \n ";
sql += " FROM TZ_MEMBER \n ";
sql += " WHERE USERID = '"+ s_userid +"' \n ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_comp = ls.getString("comp");
v_sex = ls.getString("birth_date").substring(6,7); //1:남자, 2:여자
}
if(ls!=null)ls.close();
sql1 = "INSERT INTO TZ_ABILITY_RSLT_MAS(GUBUNCD, GUBUNCDDT, USERID, RESULTSEQ, RESULTPOINT, INDATE, INUSERID, JIKUP, COMP, SEX) ";
sql1 += " VALUES (?, ?, ?, ?, ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), ?, ?, ?, ?) ";
pstmt = connMgr.prepareStatement(sql1);
pstmt.setString(1, v_gubuncd);
pstmt.setString(2, v_gubuncddt);
pstmt.setString(3, s_userid);
pstmt.setString(4, v_resultseq);
pstmt.setInt (5, 0);
pstmt.setString(6, s_userid);
pstmt.setString(7, v_jikup);
pstmt.setString(8, v_comp);
pstmt.setString(9, v_sex);
//pstmt.setString(10, v_jikryul); //직렬사용하지않음
isOk = pstmt.executeUpdate();
if(pstmt!=null)pstmt.close();
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql1);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk;
}
/**
역량 평가 등록할때
@param box receive from the form object and session
@return isOk 1:insert success,0:insert fail
*/
public int insert(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
PreparedStatement pstmt = null;
String sql = "";
String sql1 = "";
int isOk = 0;
int v_cnt = 0;
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_ability = box.getString("p_ability");
String v_abilitypro = box.getString("p_abilitypro");
String v_resultseq = box.getString("p_resultseq");
String v_inputs = box.getString("p_inputs");
String v_puserid = box.getSession("userid"); //진단자 = s_userid = puserid
String s_userid = "";
//다면진단 여부
String v_ismulti = box.getString("p_ismulti"); //
//다면진단일 경우
if(v_ismulti.equals("multi")){
s_userid = box.getString("p_userid"); //피진단자 = userid
}else{
s_userid = box.getSession("userid");
}
//
try {
connMgr = new DBConnectionManager();
//해당 문항 등록 여부
sql = "SELECT COUNT(ABILITY) AS CNT ";
sql += "FROM TZ_ABILITY_RSLT_DT ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "AND USERID = '"+ s_userid +"' ";
sql += "AND PUSERID = '"+ v_puserid +"' ";
sql += "AND RESULTSEQ = '"+ v_resultseq +"' ";
sql += "AND ABILITY = '"+ v_ability +"' ";
sql += "AND ABILITYPRO = '"+ v_abilitypro +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_cnt = ls.getInt("cnt");
}
if(ls!=null)ls.close();
//문항 입력/수정
if (v_cnt == 0){
sql1 = "INSERT INTO TZ_ABILITY_RSLT_DT(GUBUNCD, GUBUNCDDT, USERID, RESULTSEQ, ABILITY, ABILITYPRO, INPUTS, INDATE, INUSERID, ABILITYPOINT, puserid) ";
sql1 += " VALUES (?, ?, ?, ?, ?, ?, ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), ?, ? ,?) ";
pstmt = connMgr.prepareStatement(sql1);
pstmt.setString(1, v_gubuncd);
pstmt.setString(2, v_gubuncddt);
pstmt.setString(3, s_userid);
pstmt.setString(4, v_resultseq);
pstmt.setString(5, v_ability);
pstmt.setString(6, v_abilitypro);
pstmt.setString(7, v_inputs);
pstmt.setString(8, v_puserid);
pstmt.setString(9, v_inputs);
pstmt.setString(10, v_puserid);
}
else{
sql = "UPDATE TZ_ABILITY_RSLT_DT ";
sql += "SET INPUTS = ? , ";
sql += " LUSERID = ? , ";
sql += " LDATE = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "AND USERID = '"+ s_userid +"' ";
sql += "AND PUSERID = '"+ v_puserid +"' ";
sql += "AND RESULTSEQ = '"+ v_resultseq +"' ";
sql += "AND ABILITY = '"+ v_ability +"' ";
sql += "AND ABILITYPRO = '"+ v_abilitypro +"' ";
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1, v_inputs);
pstmt.setString(2, v_puserid);
}
isOk = pstmt.executeUpdate();
if(pstmt!=null)pstmt.close();
//역량별 통계 입력 여부
sql = "SELECT COUNT(ABILITY) AS CNT ";
sql += "FROM TZ_ABILITY_RSLT_ABL ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "AND USERID = '"+ s_userid +"' ";
sql += "AND RESULTSEQ = '"+ v_resultseq +"' ";
sql += "AND ABILITY = '"+ v_ability +"' ";
ls = connMgr.executeQuery(sql);
v_cnt = 0;
if ( ls.next() ) {
v_cnt = ls.getInt("cnt");
}
if(ls!=null)ls.close();
//역량별 통계 입력
if (v_cnt == 0){
sql1 = "INSERT INTO TZ_ABILITY_RSLT_ABL(GUBUNCD, GUBUNCDDT, USERID, RESULTSEQ, ABILITY, ABILITYPOINT, INDATE, INUSERID) ";
sql1 += " VALUES (?, ?, ?, ?, ?, ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), ?) ";
pstmt = connMgr.prepareStatement(sql1);
pstmt.setString(1, v_gubuncd);
pstmt.setString(2, v_gubuncddt);
pstmt.setString(3, s_userid);
pstmt.setString(4, v_resultseq);
pstmt.setString(5, v_ability);
pstmt.setInt (6, 0);
pstmt.setString(7, v_puserid);
isOk = pstmt.executeUpdate();
if(pstmt!=null)pstmt.close();
}
//역량별 통계 입력
sql = "UPDATE TZ_ABILITY_RSLT_ABL ";
sql += "SET ABILITYPOINT= NVL(( SELECT AVG(INPUTS) ";
sql += " FROM TZ_ABILITY_RSLT_DT ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += " AND ABILITY = '"+ v_ability +"' ";
sql += " AND USERID = '"+ s_userid +"' ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ),0) , ";
sql += " LUSERID = '"+ v_puserid +"' , ";
sql += " LDATE = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "AND USERID = '"+ s_userid +"' ";
sql += "AND RESULTSEQ = '"+ v_resultseq +"' ";
sql += "AND ABILITY = '"+ v_ability +"' ";
pstmt = connMgr.prepareStatement(sql);
isOk = pstmt.executeUpdate();
if(pstmt!=null)pstmt.close();
sql = "SELECT COUNT(GUBUNCD) AS CNT ";
sql += "FROM TZ_ABILITY_RSLT_MAS ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "AND USERID = '"+ s_userid +"' ";
sql += "AND RESULTSEQ = '"+ v_resultseq +"' ";
ls = connMgr.executeQuery(sql);
v_cnt = 0;
if ( ls.next() ) {
v_cnt = ls.getInt("cnt");
}
if(ls!=null)ls.close();
if (v_cnt == 0){
String avg = "";
sql = " SELECT AVG(INPUTS)avg ";
sql += " FROM TZ_ABILITY_RSLT_DT ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += " AND USERID = '"+ s_userid +"' ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ";
ls = connMgr.executeQuery(sql);
v_cnt = 0;
if ( ls.next() ) {
avg = ls.getString("avg");
}
if(ls!=null)ls.close();
String jikup ="";
String comp ="";
String sex ="";
String jikryul ="";
/*
sql = " select jikup,comp,sex,jikryul from tz_member where userid='"+s_userid+"' \n";
ls = connMgr.executeQuery(sql);
v_cnt = 0;
if ( ls.next() ) {
jikup = ls.getString("jikup");
comp = ls.getString("comp");
sex = ls.getString("sex");
jikryul = ls.getString("jikryul");
}
*/
/* comp, birth_date, jikup tz_msidepar_user 테이블에서 직급을 가져옴*/
sql = " select a.comp, a.birth_date, b.jikup \n ";
sql += " from tz_member a, (select jikup, tuserid from tz_msidepar_user where msidecode='"+v_resultseq+"' and tuserid='"+s_userid+"') b \n ";
sql += " where a.userid=b.tuserid ";
sql += " and a.userid='"+s_userid+"' \n ";
ls = connMgr.executeQuery(sql);
v_cnt = 0;
if ( ls.next() ) {
jikup = ls.getString("jikup");
comp = ls.getString("comp");
sex = ls.getString("birth_date").substring(6, 7);
}
if(ls!=null)ls.close();
/*
sql1 = "insert into TZ_ABILITY_RSLT_MAS (gubuncd,gubuncddt,userid,resultseq,resultpoint,indate,inuserid,ldate,luserid,jikup,comp,sex,jikryul) ";
sql1 += " VALUES (?, ?, ?, ?, ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), ?,TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), ?,?,?,?,?) ";
pstmt = connMgr.prepareStatement(sql1);
pstmt.setString(1, v_gubuncd);
pstmt.setString(2, v_gubuncddt);
pstmt.setString(3, s_userid);
pstmt.setString(4, v_resultseq);
pstmt.setString(5, avg);
pstmt.setString(6, v_puserid);
pstmt.setString(7, v_puserid);
pstmt.setString(8, jikup);
pstmt.setString(9, comp);
pstmt.setString(10, sex);
pstmt.setString(11, jikryul);
*/
sql1 = "insert into TZ_ABILITY_RSLT_MAS (gubuncd,gubuncddt,userid,resultseq,resultpoint,indate,inuserid,ldate,luserid,jikup,comp,sex) ";
sql1 += " VALUES (?, ?, ?, ?, ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), ?,TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), ?,?,?,?) ";
pstmt = connMgr.prepareStatement(sql1);
pstmt.setString(1, v_gubuncd);
pstmt.setString(2, v_gubuncddt);
pstmt.setString(3, s_userid);
pstmt.setString(4, v_resultseq);
pstmt.setString(5, avg);
pstmt.setString(6, v_puserid);
pstmt.setString(7, v_puserid);
pstmt.setString(8, jikup);
pstmt.setString(9, comp);
pstmt.setString(10, sex);
isOk = pstmt.executeUpdate();
if(pstmt!=null)pstmt.close();
}
//해당 테스트 통계 업데이트
sql = "UPDATE TZ_ABILITY_RSLT_MAS ";
sql += "SET RESULTPOINT = NVL(( SELECT AVG(INPUTS) ";
sql += " FROM TZ_ABILITY_RSLT_DT ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += " AND USERID = '"+ s_userid +"' ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ),0) ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' \n" +
" AND GUBUNCDDT = '"+ v_gubuncddt +"' \n" +
" AND USERID = '"+ s_userid +"' \n" +
" AND RESULTSEQ = '"+ v_resultseq +"' ";
pstmt = connMgr.prepareStatement(sql);
isOk = pstmt.executeUpdate();
if(pstmt!=null)pstmt.close();
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql1);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk;
}
/**
추천 역량
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityMyBest(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT A.ABILITYNM, B.ABILITYPOINT ";
sql += "FROM TZ_ABILITY A ";
sql += " INNER JOIN ( ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, ABILITYPOINT ";
sql += " FROM TZ_ABILITY_RSLT_ABL ";
sql += " WHERE USERID = '"+ s_userid +"' ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ";
sql += " ORDER BY ABILITYPOINT DESC) B ";
sql += " ON A.GUBUNCD = B.GUBUNCD ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT ";
sql += " AND A.ABILITY = B.ABILITY ";
sql += "WHERE ROWNUM < 3 ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
내가 가장 못하는 역량
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityMyWorst(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT A.ABILITYNM, B.ABILITYPOINT ";
sql += "FROM TZ_ABILITY A ";
sql += " INNER JOIN ( ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, ABILITYPOINT ";
sql += " FROM TZ_ABILITY_RSLT_ABL ";
sql += " WHERE USERID = '"+ s_userid +"' ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ";
sql += " ORDER BY ABILITYPOINT ASC) B ";
sql += " ON A.GUBUNCD = B.GUBUNCD ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT ";
sql += " AND A.ABILITY = B.ABILITY ";
sql += "WHERE ROWNUM < 3 ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
전체 리더십 역량수준(나의 점수, 직급 평균)
@param box receive from the form object and session
@return ArrayList 리스트
*/
public DataBox ablilityTotBest(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String v_jikup = box.getSession("jikup");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
/*
sql = "SELECT TO_CHAR(NVL(A.RESULTPOINT,0)) AS MY_POINT, \n ";
sql += " TO_CHAR(NVL(B.RESULTPOINT,0)) AS TOT_POINT \n ";
sql += "FROM TZ_ABILITY_RSLT_MAS A \n";
sql += " LEFT OUTER JOIN ( \n";
sql += " SELECT GUBUNCD, GUBUNCDDT, ROUND(AVG(RESULTPOINT),1) AS RESULTPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n";
sql += " WHERE JIKUP = '"+ v_jikup +"' \n";
sql += " GROUP BY GUBUNCD, GUBUNCDDT) B \n";
sql += " ON A.GUBUNCD = B.GUBUNCD \n";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "AND A.USERID = '"+ s_userid +"' \n ";
sql += "AND A.RESULTSEQ = '"+ v_resultseq +"' \n ";
*/
/* 직급은 해당 역량평가 당시의 직급을 가져온다. */
sql = "SELECT TO_CHAR(NVL(A.RESULTPOINT,0)) AS MY_POINT, \n ";
sql += " TO_CHAR(NVL(B.RESULTPOINT,0)) AS TOT_POINT \n ";
sql += "FROM TZ_ABILITY_RSLT_MAS A \n";
sql += " LEFT OUTER JOIN ( \n";
sql += " SELECT GUBUNCD, GUBUNCDDT, ROUND(AVG(RESULTPOINT),1) AS RESULTPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n";
sql += " WHERE JIKUP=(select jikup from TZ_ABILITY_RSLT_MAS where GUBUNCD = '"+ v_gubuncd +"' and GUBUNCDDT = '"+ v_gubuncddt +"' and USERID = '"+ s_userid +"' and RESULTSEQ = '"+ v_resultseq +"') \n ";
sql += " GROUP BY GUBUNCD, GUBUNCDDT) B \n";
sql += " ON A.GUBUNCD = B.GUBUNCD \n";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "AND A.USERID = '"+ s_userid +"' \n ";
sql += "AND A.RESULTSEQ = '"+ v_resultseq +"' \n ";
ls = connMgr.executeQuery(sql);
if (ls.next()) {
dbox = ls.getDataBox();
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return dbox;
}
/**
전체 리더십 역량수준(나의 점수, 직급 평균) _ 다면평가
@param box receive from the form object and session
@return ArrayList 리스트
*/
public DataBox ablilityTotBest_m(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String v_jikup = box.getSession("jikup");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT TO_CHAR(NVL(A.RESULTPOINT,0)) AS MY_POINT, \n ";
sql += " TO_CHAR(NVL(B.RESULTPOINT,0)) AS TOT_POINT \n ";
sql += "FROM TZ_ABILITY_RSLT_MAS A ";
sql += " LEFT OUTER JOIN ( ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ROUND(AVG(RESULTPOINT),1) AS RESULTPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKUP = (select jikup from tz_member where userid='"+s_userid+"') \n ";
sql += " GROUP BY GUBUNCD, GUBUNCDDT) B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "AND A.USERID = '"+ s_userid +"' \n ";
sql += "AND A.RESULTSEQ = '"+ v_resultseq +"' \n ";
ls = connMgr.executeQuery(sql);
if (ls.next()) {
dbox = ls.getDataBox();
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return dbox;
}
/**
현재 리더십 역량진단 결과
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityStatus(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String v_result = box.getString("p_result");
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
String v_jikryul = "";
String v_sex = "";
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
//직급 직위 성별 가져오기.
/*
sql = "SELECT COMP, JIKUP, ";
sql += " JIKRYUL, SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_jikryul = ls.getString("jikryul");
v_sex = ls.getString("sex");
}
*/
/* 결과보기를 원하는 역량의 직급, 성별을 가져온다. */
sql = " SELECT a.comp, substr(a.birth_date,7,1) sex, b.jikup \n ";
sql += " FROM TZ_MEMBER a, (select userid, jikup from tz_ability_rslt_mas where gubuncd = '"+v_gubuncd+"' and gubuncddt = '"+v_gubuncddt+"' and resultseq = '"+v_resultseq+"' and userid='"+s_userid+"') b \n ";
sql += " where a.userid = b.userid \n ";
sql += " and a.userid = '"+ s_userid +"' \n";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_sex = ls.getString("sex");
}
//end
if(ls!=null)ls.close();
sql = "SELECT A.ABILITYNM, TO_CHAR(NVL(B.ABILITYPOINT,0)) AS MY_ABL, \n ";
sql += " TO_CHAR(NVL(C.ABILITYPOINT,0)) AS TOT_ABL \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, ABILITYPOINT \n";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE USERID = '"+ s_userid +"' \n ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ) B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, \n ";
sql += " ROUND(AVG(ABILITYPOINT),2) ABILITYPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
if (v_result.equals("2")){ //직급
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKUP = '"+ v_jikup +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
else if (v_result.equals("3")){ //성별
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE SEX = '"+ v_sex +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
/* 직렬 사용하지 않음
else if (v_result.equals("4")){ //직렬 (제거)
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKRYUL = '"+ v_jikryul +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
*/
else if (v_result.equals("5")){ //소속기관
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE COMP = '"+ v_comp +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
sql += " GROUP BY GUBUNCD, GUBUNCDDT, ABILITY) C \n ";
sql += " ON A.GUBUNCD = C.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = C.GUBUNCDDT \n ";
sql += " AND A.ABILITY = C.ABILITY \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ABILITY ASC \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
if(ls!=null)ls.close();
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
현재 리더십 역량진단 결과 - 부하(다면진단)
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityStatus21(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String v_result = box.getString("p_result");
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
//String v_jikryul = "";
String v_sex = "";
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
//직급 직위 성별 가져오기.
/*
sql = "SELECT COMP, JIKUP, ";
sql += " JIKRYUL, SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_jikryul = ls.getString("jikryul");
v_sex = ls.getString("sex");
}
*/
/* 결과보기를 원하는 역량의 직급, 성별을 가져온다. */
sql = " SELECT a.comp, substr(a.birth_date,7,1) sex, b.jikup \n ";
sql += " FROM TZ_MEMBER a, (select userid, jikup from tz_ability_rslt_mas where gubuncd = '"+v_gubuncd+"' and gubuncddt = '"+v_gubuncddt+"' and resultseq = '"+v_resultseq+"' and userid='"+s_userid+"') b \n ";
sql += " where a.userid = b.userid \n ";
sql += " and a.userid = '"+ s_userid +"' \n";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_sex = ls.getString("sex");
}
//end
if(ls!=null)ls.close();
sql = "SELECT A.ABILITYNM, TO_CHAR(NVL(B.ABILITYPOINT,0)) AS MY_ABL, \n ";
sql += " TO_CHAR(NVL(C.ABILITYPOINT,0)) AS TOT_ABL \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT a.gubuncd, a.gubuncddt, a.ability, \n ";
sql += " ROUND (AVG (a.abilitypoint), 1) abilitypoint \n ";
sql += " FROM tz_ability_rslt_dt a, tz_msidepar_target b \n ";
sql += " WHERE a.userid = '"+s_userid+"' \n ";
sql += " AND a.userid = b.tuserid \n ";
sql += " AND b.idgubun = '3' AND a.RESULTSEQ = '"+ v_resultseq +"' \n ";
sql += " AND b.suserid = a.puserid \n ";
sql += " GROUP BY a.gubuncd, a.gubuncddt, a.ability \n ";
sql += " ORDER BY a.ability \n ";
sql += " ) B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, \n ";
sql += " ROUND(AVG(ABILITYPOINT),2) ABILITYPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
if (v_result.equals("2")){ //직급
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKUP = '"+ v_jikup +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
else if (v_result.equals("3")){ //성별
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE SEX = '"+ v_sex +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
/* 직렬 사용하지 않음
else if (v_result.equals("4")){ //직렬 (제거)
sql += " AND USERID IN ( ";
sql += " SELECT USERID ";
sql += " FROM TZ_ABILITY_RSLT_MAS ";
sql += " WHERE JIKRYUL = '"+ v_jikryul +"' ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) ";
}
*/
else if (v_result.equals("5")){ //소속기관
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE COMP = '"+ v_comp +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
sql += " GROUP BY GUBUNCD, GUBUNCDDT, ABILITY) C \n ";
sql += " ON A.GUBUNCD = C.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = C.GUBUNCDDT \n ";
sql += " AND A.ABILITY = C.ABILITY \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ABILITY ASC \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
if(ls!=null)ls.close();
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
현재 리더십 역량진단 결과 - 동료(다면진단)
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityStatus22(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String v_result = box.getString("p_result");
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
String v_jikryul = "";
String v_sex = "";
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
//직급 직위 성별 가져오기.
/*
sql = "SELECT COMP, JIKUP, ";
sql += " JIKRYUL, SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_jikryul = ls.getString("jikryul");
v_sex = ls.getString("sex");
}
*/
/* 결과보기를 원하는 역량의 직급, 성별을 가져온다. */
sql = " SELECT a.comp, substr(a.birth_date,7,1) sex, b.jikup \n ";
sql += " FROM TZ_MEMBER a, (select userid, jikup from tz_ability_rslt_mas where gubuncd = '"+v_gubuncd+"' and gubuncddt = '"+v_gubuncddt+"' and resultseq = '"+v_resultseq+"' and userid='"+s_userid+"') b \n ";
sql += " where a.userid = b.userid \n ";
sql += " and a.userid = '"+ s_userid +"' \n";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_sex = ls.getString("sex");
}
//end
if(ls!=null)ls.close();
sql = "SELECT A.ABILITYNM, TO_CHAR(NVL(B.ABILITYPOINT,0)) AS MY_ABL, \n ";
sql += " TO_CHAR(NVL(C.ABILITYPOINT,0)) AS TOT_ABL \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT a.gubuncd, a.gubuncddt, a.ability, \n ";
sql += " ROUND (AVG (a.abilitypoint), 1) abilitypoint \n ";
sql += " FROM tz_ability_rslt_dt a, tz_msidepar_target b \n ";
sql += " WHERE a.userid = '"+s_userid+"' \n ";
sql += " AND a.userid = b.tuserid \n ";
sql += " AND b.idgubun = '2' AND a.RESULTSEQ = '"+ v_resultseq +"' \n ";
sql += " AND b.suserid = a.puserid \n ";
sql += " GROUP BY a.gubuncd, a.gubuncddt, a.ability \n ";
sql += " ORDER BY a.ability \n ";
sql += " ) B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, \n ";
sql += " ROUND(AVG(ABILITYPOINT),2) ABILITYPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
if (v_result.equals("2")){ //직급
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKUP = '"+ v_jikup +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
else if (v_result.equals("3")){ //성별
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE SEX = '"+ v_sex +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
/*
else if (v_result.equals("4")){ //직렬 (제거)
sql += " AND USERID IN ( ";
sql += " SELECT USERID ";
sql += " FROM TZ_ABILITY_RSLT_MAS ";
sql += " WHERE JIKRYUL = '"+ v_jikryul +"' ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) ";
}
*/
else if (v_result.equals("5")){ //소속기관
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE COMP = '"+ v_comp +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
sql += " GROUP BY GUBUNCD, GUBUNCDDT, ABILITY) C \n ";
sql += " ON A.GUBUNCD = C.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = C.GUBUNCDDT \n ";
sql += " AND A.ABILITY = C.ABILITY \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ABILITY ASC \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
if(ls!=null)ls.close();
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
현재 리더십 역량진단 결과 - 상사(다면진단)
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityStatus23(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_resultseq = box.getString("p_resultseq");
String v_result = box.getString("p_result");
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
String v_jikryul = "";
String v_sex = "";
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
//직급 직위 성별 가져오기.
/*
sql = "SELECT COMP, JIKUP, ";
sql += " JIKRYUL, SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_jikryul = ls.getString("jikryul");
v_sex = ls.getString("sex");
}
*/
/* 결과보기를 원하는 역량의 직급, 성별을 가져온다. */
sql = " SELECT a.comp, substr(a.birth_date,7,1) sex, b.jikup \n ";
sql += " FROM TZ_MEMBER a, (select userid, jikup from tz_ability_rslt_mas where gubuncd = '"+v_gubuncd+"' and gubuncddt = '"+v_gubuncddt+"' and resultseq = '"+v_resultseq+"' and userid='"+s_userid+"') b \n ";
sql += " where a.userid = b.userid \n ";
sql += " and a.userid = '"+ s_userid +"' \n";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_sex = ls.getString("sex");
}
//end
if(ls!=null)ls.close();
sql = "SELECT A.ABILITYNM, TO_CHAR(NVL(B.ABILITYPOINT,0)) AS MY_ABL, \n ";
sql += " TO_CHAR(NVL(C.ABILITYPOINT,0)) AS TOT_ABL \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT a.gubuncd, a.gubuncddt, a.ability, \n ";
sql += " ROUND (AVG (a.abilitypoint), 1) abilitypoint \n ";
sql += " FROM tz_ability_rslt_dt a, tz_msidepar_target b \n ";
sql += " WHERE a.userid = '"+s_userid+"' \n ";
sql += " AND a.userid = b.tuserid \n ";
sql += " AND b.idgubun = '1' AND a.RESULTSEQ = '"+ v_resultseq +"' \n ";
sql += " AND b.suserid = a.puserid \n ";
sql += " GROUP BY a.gubuncd, a.gubuncddt, a.ability \n ";
sql += " ORDER BY a.ability \n ";
sql += " ) B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, \n ";
sql += " ROUND(AVG(ABILITYPOINT),2) ABILITYPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
if (v_result.equals("2")){ //직급
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKUP = '"+ v_jikup +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
else if (v_result.equals("3")){ //성별
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE SEX = '"+ v_sex +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
/*
else if (v_result.equals("4")){ //직렬 (제거)
sql += " AND USERID IN ( ";
sql += " SELECT USERID ";
sql += " FROM TZ_ABILITY_RSLT_MAS ";
sql += " WHERE JIKRYUL = '"+ v_jikryul +"' ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) ";
}
*/
else if (v_result.equals("5")){ //소속기관
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE COMP = '"+ v_comp +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
sql += " GROUP BY GUBUNCD, GUBUNCDDT, ABILITY) C \n ";
sql += " ON A.GUBUNCD = C.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = C.GUBUNCDDT \n ";
sql += " AND A.ABILITY = C.ABILITY \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ABILITY ASC \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
if(ls!=null)ls.close();
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
3개월전 리더십 역량진단 결과
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityStatus3(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_result = box.getString("p_result");
String v_resultseq = "0";
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
//String v_jikryul = "";
String v_sex = "";
//String v_selmonth = "3";
String v_selmonth = box.getStringDefault("p_selmonth", "3");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
//직급 직위 성별 가져오기.
/*
sql = "SELECT COMP, JIKUP, JIKRYUL, SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_jikryul = ls.getString("jikryul");
v_sex = ls.getString("sex");
}
if(ls!=null)ls.close();
//3개월전 평가 데이터 가져오기
sql = "SELECT NVL(MAX(RESULTSEQ),0) RESULTSEQ ";
sql += "FROM TZ_ABILITY_RSLT_MAS ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "AND USERID = '"+ s_userid +"' ";
sql += "AND LDATE <= TO_CHAR(ADD_MONTHS(SYSDATE, -"+ v_selmonth +"),'YYYYMMDDHH24MISS') ";
ls = connMgr.executeQuery(sql);
*/
/* 소속, 성별만 가져온다. */
sql = "SELECT COMP, substr(birth_date,7,1) as sex \n ";
sql += " FROM TZ_MEMBER \n ";
sql += " WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_comp = ls.getString("comp");
v_sex = ls.getString("sex");
}
if(ls!=null)ls.close();
//3개월전 평가 데이터의 데이터를 가져온다.(직급, 성별)
sql = " select resultseq, jikup \n ";
sql += " from TZ_ABILITY_RSLT_MAS \n ";
sql += " where resultseq = ( \n ";
sql += " select NVL(MAX(resultseq),0) resultseq \n ";
sql += " from TZ_ABILITY_RSLT_MAS \n ";
sql += " ) ";
sql += " and gubuncd = '"+ v_gubuncd +"' \n ";
sql += " and gubuncddt = '"+ v_gubuncddt +"' \n ";
sql += " and userid = '"+ s_userid +"' \n ";
sql += " and ldate <= to_char(add_months(sysdate, -"+ v_selmonth +"),'yyyymmddhh24miss') \n ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_resultseq = ls.getString("resultseq");
v_jikup = ls.getString("jikup");
//v_sex = ls.getString("sex");
}
if(ls!=null)ls.close();
sql = "SELECT A.ABILITYNM, TO_CHAR(NVL(B.ABILITYPOINT,0)) AS MY_ABL, \n ";
sql += " TO_CHAR(NVL(C.ABILITYPOINT,0)) AS TOT_ABL \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, ABILITYPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE USERID = '"+ s_userid +"' \n ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ) B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, \n ";
sql += " ROUND(AVG(ABILITYPOINT),1) ABILITYPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
if (v_result.equals("2")){ //직급
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKUP = '"+ v_jikup +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
else if (v_result.equals("3")){ //성별
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE SEX = '"+ v_sex +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
/*
else if (v_result.equals("4")){ //직렬(제거)
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE JIKRYUL = '"+ v_jikryul +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
*/
else if (v_result.equals("5")){ //소속기관
sql += " AND USERID IN ( \n ";
sql += " SELECT USERID \n ";
sql += " FROM TZ_ABILITY_RSLT_MAS \n ";
sql += " WHERE COMP = '"+ v_comp +"' \n ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) \n ";
}
sql += " GROUP BY GUBUNCD, GUBUNCDDT, ABILITY ) C \n ";
sql += " ON A.GUBUNCD = C.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = C.GUBUNCDDT \n ";
sql += " AND A.ABILITY = C.ABILITY \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ABILITY ASC \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
if(ls!=null)ls.close();
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
3개월전 리더십 역량진단 결과 - (다면평가)부하
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityStatus31(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_result = box.getString("p_result");
String v_resultseq = "0";
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
//String v_jikryul = "";
String v_sex = "";
String v_selmonth = "3";
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
//직급 직위 성별 가져오기.
/*
sql = "SELECT COMP, JIKUP, JIKRYUL, SEX ";
sql += "FROM TZ_MEMBER ";
sql += "WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_jikup = ls.getString("jikup");
v_comp = ls.getString("comp");
v_jikryul = ls.getString("jikryul");
v_sex = ls.getString("sex");
}
if(ls!=null)ls.close();
//3개월전 평가 데이터 가져오기
sql = "SELECT NVL(MAX(RESULTSEQ),0) RESULTSEQ ";
sql += "FROM TZ_ABILITY_RSLT_MAS ";
sql += "WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "AND USERID = '"+ s_userid +"' ";
sql += "AND LDATE <= TO_CHAR(ADD_MONTHS(SYSDATE, -"+ v_selmonth +"),'YYYYMMDDHH24MISS') ";
ls = connMgr.executeQuery(sql);
*/
/* 소속만 가져온다. */
sql = "SELECT COMP \n ";
sql += " FROM TZ_MEMBER \n ";
sql += " WHERE USERID = '"+ s_userid +"' ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_comp = ls.getString("comp");
}
if(ls!=null)ls.close();
//3개월전 평가 데이터의 데이터를 가져온다.(직급, 성별)
sql = " select resultseq, jikup, sex \n ";
sql += " from TZ_ABILITY_RSLT_MAS \n ";
sql += " where resultseq = ( \n ";
sql += " select NVL(MAX(resultseq),0) resultseq \n ";
sql += " from TZ_ABILITY_RSLT_MAS \n ";
sql += " ) ";
sql += " and gubuncd = '"+ v_gubuncd +"' \n ";
sql += " and gubuncddt = '"+ v_gubuncddt +"' \n ";
sql += " and userid = '"+ s_userid +"' \n ";
sql += " and ldate <= to_char(add_months(sysdate, -"+ v_selmonth +"),'yyyymmddhh24miss') \n ";
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
v_resultseq = ls.getString("resultseq");
v_jikup = ls.getString("jikup");
v_sex = ls.getString("sex");
}
if(ls!=null)ls.close();
sql = "SELECT A.ABILITYNM, TO_CHAR(NVL(B.ABILITYPOINT,0)) AS MY_ABL, ";
sql += " TO_CHAR(NVL(C.ABILITYPOINT,0)) AS TOT_ABL ";
sql += "FROM TZ_ABILITY A ";
sql += " LEFT OUTER JOIN ( ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, ABILITYPOINT ";
sql += " FROM TZ_ABILITY_RSLT_ABL ";
sql += " WHERE USERID = '"+ s_userid +"' ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' ) B ";
sql += " ON A.GUBUNCD = B.GUBUNCD ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT ";
sql += " AND A.ABILITY = B.ABILITY ";
sql += " LEFT OUTER JOIN ( ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, ";
sql += " ROUND(AVG(ABILITYPOINT),1) ABILITYPOINT ";
sql += " FROM TZ_ABILITY_RSLT_ABL ";
sql += " WHERE GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ";
if (v_result.equals("2")){ //직급
sql += " AND USERID IN ( ";
sql += " SELECT USERID ";
sql += " FROM TZ_ABILITY_RSLT_MAS ";
sql += " WHERE JIKUP = '"+ v_jikup +"' ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) ";
}
else if (v_result.equals("3")){ //성별
sql += " AND USERID IN ( ";
sql += " SELECT USERID ";
sql += " FROM TZ_ABILITY_RSLT_MAS ";
sql += " WHERE SEX = '"+ v_sex +"' ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) ";
}
/*
else if (v_result.equals("4")){ //직렬(제거)
sql += " AND USERID IN ( ";
sql += " SELECT USERID ";
sql += " FROM TZ_ABILITY_RSLT_MAS ";
sql += " WHERE JIKRYUL = '"+ v_jikryul +"' ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) ";
}
*/
else if (v_result.equals("5")){ //소속기관
sql += " AND USERID IN ( ";
sql += " SELECT USERID ";
sql += " FROM TZ_ABILITY_RSLT_MAS ";
sql += " WHERE COMP = '"+ v_comp +"' ";
sql += " AND GUBUNCD = '"+ v_gubuncd +"' ";
sql += " AND GUBUNCDDT = '"+ v_gubuncddt +"' ) ";
}
sql += " GROUP BY GUBUNCD, GUBUNCDDT, ABILITY) C ";
sql += " ON A.GUBUNCD = C.GUBUNCD ";
sql += " AND A.GUBUNCDDT = C.GUBUNCDDT ";
sql += " AND A.ABILITY = C.ABILITY ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' ";
sql += "ORDER BY A.ABILITY ASC ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
if(ls!=null)ls.close();
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
3개월간 과정 수강 이력
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilitySubjStudent3(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_result = box.getString("p_result");
String v_resultseq = "0";
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
String v_sex = "";
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT A.ABILITY, A.ABILITYNM, C.SUBJ, \n ";
sql += " (SELECT SUBJNM FROM TZ_SUBJ X WHERE X.SUBJ = C.SUBJ) AS SUBJNM \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " LEFT OUTER JOIN TZ_ABILITY_SUBJ B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT UNIQUE SUBJ \n ";
sql += " FROM TZ_STUDENT \n ";
sql += " WHERE USERID = '"+ s_userid +"' \n ";
sql += " AND LDATE <= TO_CHAR(ADD_MONTHS(SYSDATE, -3),'YYYYMMDDHH24MISS') \n ";
sql += " ) C \n ";
sql += " ON B.SUBJ = C.SUBJ \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ABILITY, A.ORDERS, B.ORDERS \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
3개월 전까지 과정 수강 이력
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilitySubjStudent(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_result = box.getString("p_result");
String v_resultseq = "0";
String s_userid = box.getSession("userid");
String v_comp = "";
String v_jikup = "";
String v_sex = "";
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT A.ABILITY, A.ABILITYNM, C.SUBJ, \n ";
sql += " (SELECT SUBJNM FROM TZ_SUBJ X WHERE X.SUBJ = C.SUBJ) AS SUBJNM \n ";
sql += "FROM TZ_ABILITY A ";
sql += " LEFT OUTER JOIN TZ_ABILITY_SUBJ B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " LEFT OUTER JOIN ( \n ";
sql += " SELECT UNIQUE SUBJ \n ";
sql += " FROM TZ_STUDENT \n ";
sql += " WHERE USERID = '"+ s_userid +"' \n ";
sql += " AND LDATE > TO_CHAR(ADD_MONTHS(SYSDATE, -3),'YYYYMMDDHH24MISS') \n ";
sql += " ) C \n ";
sql += " ON B.SUBJ = C.SUBJ \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ABILITY, A.ORDERS, B.ORDERS \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
나에게 추천 하는 과정
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityBestSubj(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_result = box.getString("p_result");
String v_resultseq = box.getString("p_resultseq");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "SELECT A.ABILITY, A.ABILITYNM, B.SUBJ, \n ";
sql += " (SELECT SUBJNM FROM TZ_SUBJ X WHERE X.SUBJ = B.SUBJ) AS SUBJNM \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " INNER JOIN TZ_ABILITY_SUBJ B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " INNER JOIN ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY \n ";
sql += " FROM ( \n ";
sql += " SELECT GUBUNCD, GUBUNCDDT, ABILITY, ABILITYPOINT \n ";
sql += " FROM TZ_ABILITY_RSLT_ABL \n ";
sql += " WHERE USERID = '"+ s_userid +"' \n ";
sql += " AND RESULTSEQ = '"+ v_resultseq +"' \n ";
sql += " ORDER BY ABILITYPOINT ASC) X \n ";
sql += " WHERE ROWNUM < 3 \n ";
sql += " ) C \n ";
sql += " ON A.GUBUNCD = C.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = C.GUBUNCDDT \n ";
sql += " AND A.ABILITY = C.ABILITY \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ORDERS, B.ORDERS \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
직급 추천 (최근 3개월간 수강한 교육과정)
@param box receive from the form object and session
@return ArrayList 리스트
*/
public ArrayList ablilityBestSubjGroup(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
DataBox dbox = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
String v_result = box.getString("p_result");
String v_jikup = box.getString("p_jikup");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
/*
sql = "SELECT A.ABILITY, A.ABILITYNM, B.SUBJ, \n ";
sql += " (SELECT SUBJNM FROM TZ_SUBJ X WHERE X.SUBJ = B.SUBJ) AS SUBJNM \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " INNER JOIN TZ_ABILITY_SUBJ B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " INNER JOIN ( \n ";
sql += " SELECT UNIQUE SUBJ \n ";
sql += " FROM TZ_STUDENT \n ";
sql += " WHERE JIKUP = '"+ v_jikup +"' \n ";
sql += " AND LDATE > TO_CHAR(ADD_MONTHS(SYSDATE, -3),'YYYYMMDDHH24MISS') \n ";
sql += " ) C \n ";
sql += " ON B.SUBJ = C.SUBJ \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ORDERS, B.ORDERS \n ";
*/
sql = "SELECT A.ABILITY, A.ABILITYNM, B.SUBJ, \n ";
sql += " (SELECT SUBJNM FROM TZ_SUBJ X WHERE X.SUBJ = B.SUBJ) AS SUBJNM \n ";
sql += "FROM TZ_ABILITY A \n ";
sql += " INNER JOIN TZ_ABILITY_SUBJ B \n ";
sql += " ON A.GUBUNCD = B.GUBUNCD \n ";
sql += " AND A.GUBUNCDDT = B.GUBUNCDDT \n ";
sql += " AND A.ABILITY = B.ABILITY \n ";
sql += " INNER JOIN ( \n ";
sql += " SELECT UNIQUE SUBJ \n ";
sql += " FROM TZ_STUDENT \n ";
sql += " WHERE 1=1 \n ";
sql += " AND LDATE > TO_CHAR(ADD_MONTHS(SYSDATE, -3),'YYYYMMDDHH24MISS') \n ";
sql += " ) C \n ";
sql += " ON B.SUBJ = C.SUBJ \n ";
sql += "WHERE A.GUBUNCD = '"+ v_gubuncd +"' \n ";
sql += "AND A.GUBUNCDDT = '"+ v_gubuncddt +"' \n ";
sql += "ORDER BY A.ORDERS, B.ORDERS \n ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("\n SQL : [\n" + sql + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e ) { } }
}
return list;
}
/**
역량 평가 삭제할때
@param box receive from the form object and session
@return isOk 1:insert success,0:insert fail
*/
public int delete(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls1 = null;
ListSet ls2 = null;
ListSet ls3 = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
PreparedStatement pstmt3 = null;
StringBuffer sql = new StringBuffer();
int isOk1 = 1;
int isOk2 = 1;
int isOk3 = 1;
int v_cnt = 0;
int idx = 1;
String v_gubuncd = box.getString("p_gubuncd");
String v_gubuncddt = box.getString("p_gubuncddt");
int v_resultseq = box.getInt("p_resultseq");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
//해당 문항 등록 여부
sql.append("SELECT COUNT(userid) AS cnt ");
sql.append(" FROM TZ_ABILITY_RSLT_DT ");
sql.append(" WHERE GUBUNCD = '"+ v_gubuncd +"' ");
sql.append(" AND GUBUNCDDT = '"+ v_gubuncddt +"' ");
sql.append(" AND USERID = '"+ s_userid +"' ");
sql.append(" AND RESULTSEQ = '"+ v_resultseq +"' ");
ls1 = connMgr.executeQuery(sql.toString());
if ( ls1.next() ) {
v_cnt = ls1.getInt("cnt");
}
if(ls1 != null) ls1.close();
sql = new StringBuffer();
//문항 입력/수정
if (v_cnt > 0){
sql.append(" DELETE FROM TZ_ABILITY_RSLT_DT ");
sql.append(" WHERE GUBUNCD = ? ");
sql.append(" AND GUBUNCDDT = ? ");
sql.append(" AND USERID = ? ");
sql.append(" AND RESULTSEQ = ? ");
pstmt1 = connMgr.prepareStatement(sql.toString());
idx = 1;
pstmt1.setString(idx++, v_gubuncd);
pstmt1.setString(idx++, v_gubuncddt);
pstmt1.setString(idx++, s_userid);
pstmt1.setInt (idx++, v_resultseq);
isOk1 = pstmt1.executeUpdate();
if(pstmt1 != null) pstmt1.close();
}
sql = new StringBuffer();
//해당 문항 마스터 등록 여부
sql.append("SELECT COUNT(userid) AS cnt ");
sql.append(" FROM TZ_ABILITY_RSLT_MAS ");
sql.append(" WHERE GUBUNCD = '"+ v_gubuncd +"' ");
sql.append(" AND GUBUNCDDT = '"+ v_gubuncddt +"' ");
sql.append(" AND USERID = '"+ s_userid +"' ");
sql.append(" AND RESULTSEQ = '"+ v_resultseq +"' ");
ls2 = connMgr.executeQuery(sql.toString());
if ( ls2.next() ) {
v_cnt = ls2.getInt("cnt");
} else {
v_cnt = 0;
}
if(ls2 != null) ls2.close();
sql = new StringBuffer();
//문항 입력/수정
if (v_cnt > 0){
sql.append(" DELETE FROM TZ_ABILITY_RSLT_MAS ");
sql.append(" WHERE GUBUNCD = ? ");
sql.append(" AND GUBUNCDDT = ? ");
sql.append(" AND USERID = ? ");
sql.append(" AND RESULTSEQ = ? ");
pstmt2 = connMgr.prepareStatement(sql.toString());
idx = 1;
pstmt2.setString(idx++, v_gubuncd);
pstmt2.setString(idx++, v_gubuncddt);
pstmt2.setString(idx++, s_userid);
pstmt2.setInt (idx++, v_resultseq);
isOk2 = pstmt2.executeUpdate();
if(pstmt2 != null) pstmt2.close();
}
sql = new StringBuffer();
//해당 진단 실시 여부
sql.append("SELECT COUNT(userid) AS cnt ");
sql.append(" FROM TZ_ABILITY_RSLT_ABL ");
sql.append(" WHERE GUBUNCD = '"+ v_gubuncd +"' ");
sql.append(" AND GUBUNCDDT = '"+ v_gubuncddt +"' ");
sql.append(" AND USERID = '"+ s_userid +"' ");
sql.append(" AND RESULTSEQ = '"+ v_resultseq +"' ");
ls3 = connMgr.executeQuery(sql.toString());
if ( ls3.next() ) {
v_cnt = ls3.getInt("cnt");
} else {
v_cnt = 0;
}
if(ls3 != null) ls3.close();
sql = new StringBuffer();
//문항 입력/수정
if (v_cnt > 0){
sql.append(" DELETE FROM TZ_ABILITY_RSLT_ABL ");
sql.append(" WHERE GUBUNCD = ? ");
sql.append(" AND GUBUNCDDT = ? ");
sql.append(" AND USERID = ? ");
sql.append(" AND RESULTSEQ = ? ");
pstmt3 = connMgr.prepareStatement(sql.toString());
idx = 1;
pstmt3.setString(idx++, v_gubuncd);
pstmt3.setString(idx++, v_gubuncddt);
pstmt3.setString(idx++, s_userid);
pstmt3.setInt (idx++, v_resultseq);
isOk3 = pstmt3.executeUpdate();
if(pstmt3 != null) pstmt3.close();
}
if (isOk1 * isOk2 * isOk3 > 0 ) {
connMgr.commit();
} else {
connMgr.rollback();
}
} catch ( Exception ex ) {
connMgr.rollback();
ErrorManager.getErrorStackTrace(ex, box, sql.toString());
throw new Exception("sql = " + sql.toString() + "\r\n" + ex.getMessage() );
} finally {
connMgr.setAutoCommit(true);
if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } }
if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { } }
if ( ls3 != null ) { try { ls3.close(); } catch ( Exception e ) { } }
if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } }
if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } }
if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk1 * isOk2 * isOk3;
}
} |
/**
* Package for junior.pack2.p5.ch4 Set.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-06-01
*/
package ru.job4j.set; |
package com.codefundo.votenew;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.security.AccessController;
import java.util.Random;
import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
public class Emailsend extends AppCompatActivity {
private TextView user;
private FirebaseAuth mAuth;
private TextView pass;
private TextView subject;
private TextView body;
private TextView recipient;
EditText pin;
Button vote;
String code,email="",aadhaar="";
int code1,code2,code3,code4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emailsend);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
email="";
try{
email=getIntent().getExtras().get("email").toString().toLowerCase();
aadhaar=getIntent().getExtras().get("aadhaar").toString();
}catch (Exception e ){e.printStackTrace();}
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
fab.performClick();
}
}, 3000);
sendMessage(email);
pin=findViewById(R.id.pin);
vote=findViewById(R.id.vote);
user = findViewById(R.id.username);
pass = findViewById(R.id.password);
subject =findViewById(R.id.subject);
body = findViewById(R.id.body);
recipient = findViewById(R.id.recipient);
vote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(pin.getText().toString().equals(code)){
Intent i =new Intent(getApplicationContext(),VOTEFINAL.class);
i.putExtra("aadhaar",aadhaar);
i.putExtra("email",email);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
}
});
}
private void sendMessage(String email1) {
String rec="gptshubham595@gmail.com";
String str[]=email1.split(" ");
String user="vote4usiitg@gmail.com";
String pass="iitg00000000";
Random rand = new Random();
code1 = rand.nextInt(9);
code2 = code1*10+rand.nextInt(8)+1;
code3 = code2*10+rand.nextInt(7)+2;
code4 = code3*10+rand.nextInt(6)+3;
code=code4+"";
code=code.trim();
add(email,code,aadhaar);
// String[] recipients = { recipient.getText().toString() };
SendEmailAsyncTask email = new SendEmailAsyncTask();
email.activity = this;
email.m = new Mail(user, pass);
email.m.set_from(user);
email.m.setBody("YOUR OTP To VOTE IS :"+code);
email.m.set_to(str);
email.m.set_subject("VOTE4US CODE FOR VOTING");
email.execute();
}
public void displayMessage(String message) {
Snackbar.make(findViewById(R.id.fab), message, Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
public void add(String email,String code,String aadhaar){
String emailpartwithout[] =email.split("@",2);
DatabaseReference allpoliticalparty= FirebaseDatabase.getInstance().getReference().child("Users").child(emailpartwithout[0]).child("familymember").child(aadhaar).child("code");
allpoliticalparty.keepSynced(true);
allpoliticalparty.setValue(code).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
vote.setEnabled(true);
}
}
});
}
}
class SendEmailAsyncTask extends AsyncTask<Void, Void, Boolean> {
Mail m;
Emailsend activity;
public SendEmailAsyncTask() {}
@Override
protected Boolean doInBackground(Void... params) {
try {
if (m.send()) {
activity.displayMessage("Email sent.");
} else {
activity.displayMessage("Email failed to send.");
}
return true;
} catch (AuthenticationFailedException e) {
Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
e.printStackTrace();
activity.displayMessage("Authentication failed.");
return false;
} catch (MessagingException e) {
Log.e(SendEmailAsyncTask.class.getName(), "Email failed");
e.printStackTrace();
activity.displayMessage("Email failed to send.");
return false;
} catch (Exception e) {
e.printStackTrace();
activity.displayMessage("Unexpected error occured.");
return false;
}
}
}
|
package com.a.roombooking.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.a.roombooking.EndPointUrl;
import com.a.roombooking.R;
import com.a.roombooking.ResponseData;
import com.a.roombooking.RetrofitInstance;
import com.a.roombooking.Utils;
import com.a.roombooking.model.EditProfilePojo;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class EditProfileActivity extends AppCompatActivity {
EditText et_name, et_phno, et_uname, et_password,et_email;
TextView tv1,tv2,tv4,tv5,tv3;
Button btn_submit;
List<EditProfilePojo> a1;
ProgressDialog progressDialog;
SharedPreferences sharedPreferences;
String session;
ResponseData a2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_edit_profile);
getSupportActionBar().setTitle("Edit Profile");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sharedPreferences = getSharedPreferences(Utils.SHREF, Context.MODE_PRIVATE);
session = sharedPreferences.getString("user_name", "def-val");
tv1=(TextView)findViewById(R.id.tv1);
tv2=(TextView)findViewById(R.id.tv2);
tv4=(TextView)findViewById(R.id.tv4);
tv5=(TextView)findViewById(R.id.tv5);
tv3=(TextView)findViewById(R.id.tv3);
btn_submit = (Button) findViewById(R.id.btn_submit);
et_name = (EditText) findViewById(R.id.et_name);
et_phno = (EditText) findViewById(R.id.et_phno);
et_uname = (EditText) findViewById(R.id.et_uname);
et_password = (EditText) findViewById(R.id.et_password);
et_email = (EditText) findViewById(R.id.et_email);
et_uname.setText(session);
et_uname.setEnabled(false);
Typeface fontstyle=Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/Lato-Medium.ttf");
tv1.setTypeface(fontstyle);
tv2.setTypeface(fontstyle);
tv4.setTypeface(fontstyle);
tv5.setTypeface(fontstyle);
btn_submit.setTypeface(fontstyle);
et_name.setTypeface(fontstyle);
et_phno.setTypeface(fontstyle);
et_uname.setTypeface(fontstyle);
et_password.setTypeface(fontstyle);
et_email.setTypeface(fontstyle);
tv3.setTypeface(fontstyle);
progressDialog = new ProgressDialog(EditProfileActivity.this);
progressDialog.setMessage("Loading....");
progressDialog.show();
EndPointUrl service = RetrofitInstance.getRetrofitInstance().create(EndPointUrl.class);
Call<List<EditProfilePojo>> call = service.getUserProfile(session);
call.enqueue(new Callback<List<EditProfilePojo>>() {
@Override
public void onResponse(Call<List<EditProfilePojo>> call, Response<List<EditProfilePojo>> response) {
progressDialog.dismiss();
a1 = response.body();
// Toast.makeText(getApplicationContext(),""+response.body().size(),Toast.LENGTH_LONG).show();
EditProfilePojo user = a1.get(0);
et_name.setText(user.getName());
et_phno.setText(user.getPhone());
et_email.setText(user.getEmailid());
et_password.setText(user.getPwd());
}
@Override
public void onFailure(Call<List<EditProfilePojo>> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(EditProfileActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submitData();
//finish();
}
});
}
private void submitData() {
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String phno = et_phno.getText().toString();
String pwd = et_password.getText().toString();
progressDialog = new ProgressDialog(EditProfileActivity.this);
progressDialog.setMessage("Loading....");
progressDialog.show();
session = sharedPreferences.getString("user_name", "def-val");
Toast.makeText(EditProfileActivity.this, session, Toast.LENGTH_SHORT).show();
EndPointUrl service = RetrofitInstance.getRetrofitInstance().create(EndPointUrl.class);
Call<ResponseData> call = service.update_user_profile(name, phno, email, pwd, session);
call.enqueue(new Callback<ResponseData>() {
@Override
public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
progressDialog.dismiss();
a2 = response.body();
/*EditProfilePojo user = a1.get(0);
et_name.setText(user.getName());
et_phno.setText(user.getPhone());
et_email.setText(user.getEmailid());
et_password.setText(user.getPwd());*/
if (response.body().status.equals("true")) {
Toast.makeText(EditProfileActivity.this, response.body().message, Toast.LENGTH_LONG).show();
Intent intent=new Intent(EditProfileActivity.this, DisplayBlocksActivity.class);
startActivity(intent);
} else {
Toast.makeText(EditProfileActivity.this, response.body().message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<ResponseData> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(EditProfileActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
//add this method in your program
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.PauseTransition;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.util.Duration;
public class LoginController implements Initializable
{
static Main application;
@FXML
TextField name_t;
@FXML
PasswordField password_p;
@FXML
Label prompt_l;
public void setApp(Main application)
{
this.application=application;
}
public void exit()
{
System.exit(0);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void signupPage(ActionEvent event) {
application.gotoSignup();
// System.out.println(application.toString());
}
public void homePage(ActionEvent event) throws Exception
{
String query="SELECT * FROM admins WHERE user='"+name_t.getText()+"' AND password='"+password_p.getText()+"'";
if(Database.checkLogin(query))
{
prompt_l.setText("Sign in Successfull");
PauseTransition pause = new PauseTransition(Duration.seconds(1));
pause.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
application.gotoHomepage();
}
});
pause.play();
}
else
{
prompt_l.setText("Username or password is not correct.");
}
}
}
|
package com.rachelgrau.rachel.health4theworldstroke;
/**
* Created by rachel on 12/14/16.
*/
public class Utilities {
/* Returns a time string of the form "5:32PM" */
public static String getAmPmTimeString(int hr, int min) {
boolean isAM = false;
if (hr < 12) {
isAM = true;
} else if (hr > 12){
hr -= 12;
}
String hrStr = String.valueOf(hr);
String minStr = String.valueOf(min);
String timeStr = String.valueOf(hr) + ":";
if (minStr.length() == 1) {
minStr = "0" + minStr;
}
timeStr += minStr;
if (isAM) {
timeStr += " AM";
} else {
timeStr += " PM";
}
return timeStr;
}
/* Returns a time string of the form "5:32PM" */
public static String getMilitaryTimeString(int hr, int min) {
String hrStr = String.valueOf(hr);
String minStr = String.valueOf(min);
String timeStr = String.valueOf(hr) + ":";
if (minStr.length() == 1) {
minStr = "0" + minStr;
}
timeStr += minStr;
return timeStr;
}
}
|
package de.hpi.is.ddd.evaluation;
import de.hpi.is.ddd.evaluation.utils.UnionFind;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.tuple.Pair;
import java.io.File;
import java.io.FileReader;
import java.util.*;
/**
*
* Generates an Evaluation given the gold standard and the current algorithms performance.
*
* Evaluator.java
*/
public class Evaluator {
private final static CSVFormat FORMAT = CSVFormat.TDF.withFirstRecordAsHeader();
/* Gold Standard file path */
private File goldStandard;
/* Gold Standard */
private UnionFind<String> ufGS;
private Set<Pair<String, String>> pairsGS;
// XXX: Keep ufA OR pairsA in the Evaluator?
// /* Algorithm */
// private UnionFind<String> ufA;
// private Set<Pair<String, String>> pairsA;
private long totalComparisons;
private long startTime;
public Evaluator(File goldStandard) {
this.totalComparisons = 0;
this.goldStandard = goldStandard;
pairsGS = new HashSet<Pair<String, String>>();
try (CSVParser parser = new CSVParser(new FileReader(goldStandard), FORMAT)) {
Iterator<CSVRecord> itRec = parser.iterator();
while (itRec.hasNext()) {
CSVRecord rec = itRec.next();
pairsGS.add(Pair.of(rec.get("id1"), rec.get("id2")));
}
ufGS = convertPairsToUnionFind(pairsGS);
startTime = System.currentTimeMillis();
} catch (java.io.IOException e) {
System.out.println("There was a problem while reading the gold standard. Aborting...");
e.printStackTrace();
System.exit(1);
}
}
public Evaluation evaluate(Set<Pair<String, String>> pairsA) {
return evaluate(convertPairsToUnionFind(pairsA));
}
/**
* Calculates the number of correct or wrong pairs, using the transitivity for both the gold standard and
* the algorithm's pairs.
*
* @param ufA: The UnionFind of the algorithm's result.
*/
public Evaluation evaluate(UnionFind<String> ufA) {
int tp = 0, fp = 0, fn = 0;
/* What the result found
* Results --> GoldStandard */
for (Set<String> component : ufA) {
List<String> elements = new ArrayList<>(component);
for (int i = 0; i < elements.size(); i++) {
for (int j = i + 1; j < elements.size(); j++) {
if (ufGS.connected(elements.get(i), elements.get(j))) {
++tp;
} else {
++fp;
}
}
}
}
/* What the result should have found
* GroundTruth --> Results */
/* For the following, we are going to need to remove the elements that we haven't met, from the components. */
int pairsGS = 0; // Pairs in Gold Standard
int entriesGS = 0; // Entries in Gold Standard
for (Set<String> component : ufGS) {
List<String> elements = new ArrayList<>(component);
entriesGS += elements.size();
for (int i = 0; i < elements.size(); i++) {
for (int j = i + 1; j < elements.size(); j++) {
++pairsGS;
if (!ufA.connected(elements.get(i), elements.get(j))) {
++fn;
}
}
}
}
Evaluation evl = new Evaluation();
evl.setTp(tp);
int allPossiblePairs = (int) (entriesGS * (entriesGS - 1) / 2.0);
int tn = allPossiblePairs - pairsGS - fp;
evl.setTn(tn);
evl.setFp(fp);
evl.setFn(fn);
evl.setExecutionTime(System.currentTimeMillis() - startTime);
evl.setAvailableProcessors(Runtime.getRuntime().availableProcessors());
evl.setMaxMemory((Runtime.getRuntime().maxMemory() / 1024) / 1024);
evl.setTotalMemory((Runtime.getRuntime().totalMemory() / 1024) / 1024);
evl.setFreeMemory((Runtime.getRuntime().freeMemory() / 1024) / 1024);
evl.setUsedMemory(evl.getTotalMemory() - evl.getFreeMemory());
evl.setTotalComparisons(totalComparisons);
return evl;
}
public static UnionFind<String> convertPairsToUnionFind(Set<Pair<String, String>> pairs) {
UnionFind<String> uf = new UnionFind<>();
for (Pair<String, String> p: pairs) {
uf.union(p.getKey(), p.getValue());
}
return uf;
}
public void setTotalComparisons(long totalComparisons) {
this.totalComparisons = totalComparisons;
}
}
|
package mvc.com.my_mvc.Controller;
/**
* @date on 18:22 2018/8/12
* @author yuyong
* @Email yu1183688986@163.com
* @describe controller层
*/
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import mvc.com.my_mvc.Bean.Book;
import mvc.com.my_mvc.Model.IModel;
import mvc.com.my_mvc.Model.MyModel;
import mvc.com.my_mvc.R;
import mvc.com.my_mvc.Utils.BookAdapter;
import mvc.com.my_mvc.Utils.MyApplication;
import mvc.com.my_mvc.View.IView;
public class MainActivity extends AppCompatActivity implements IView,View.OnClickListener{
private ListView lv_book;
private List<Book> list;
private BookAdapter adapter;
private IModel iModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv_book = findViewById(R.id.lv);
iModel = new MyModel(this);
list = iModel.query();
adapter = new BookAdapter(this,R.layout.book_item,list);
showBook();
Button bt_add = findViewById(R.id.bt_add);
Button bt_delete = findViewById(R.id.bt_delete);
bt_add.setOnClickListener(this);
bt_delete.setOnClickListener(this);
}
@Override
public void showBook() {
lv_book.setAdapter(adapter);
lv_book.setOnItemClickListener((parent,view,position,id)->{
Book book = list.get(position);
Toast.makeText(MyApplication.getContext(),book.getName()+"被选中",Toast.LENGTH_SHORT).show();
});
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bt_add:
iModel.addBook(getRandomBook().getName(),getRandomBook().getImageId(),()->{
adapter.notifyDataSetChanged();
});
break;
case R.id.bt_delete:
iModel.deleteBook(()->{
adapter.notifyDataSetChanged();
});
break;
default:
break;
}
}
private Book getRandomBook(){
String[] bookNames = {"Java从入门到精通","Android从入门到精通","JavaWeb从入门到精通"};
Random random = new Random();
String name = bookNames[random.nextInt(bookNames.length)];
int imageId = 0;
switch (name){
case "Java从入门到精通":
imageId = R.drawable.java;
break;
case "Android从入门到精通":
imageId = R.drawable.android;
break;
case "JavaWeb从入门到精通":
imageId = R.drawable.javaweb;
break;
default:
break;
}
return new Book(name,imageId);
}
}
|
package Test;
import Main.PlusMinus;
import org.junit.Assert;
/**
* Created by Samarth on 5/29/16.
*/
public class PlusMinusTest {
@org.junit.Test
public void plusMinusTest() {
double[] res = PlusMinus.plusMinus(new int[] {-4, 3, -9, 0, 4, 1});
Assert.assertTrue(res[0] == 0.5);
Assert.assertTrue(res[1] < 0.333334 && res[1] > 0.333332);
Assert.assertTrue(res[2] < 0.166668 && res[2] > 0.166666);
}
}
|
package org.point85.domain.plant;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.point85.domain.dto.EntityScheduleDto;
import org.point85.domain.dto.PlantEntityDto;
import org.point85.domain.persistence.EntityLevelConverter;
import org.point85.domain.schedule.WorkSchedule;
/**
* The PlantEntity class is an object in the S95 hierarchy (Enterprise, Site,
* Area, ProductionLine, WorkCell or Equipment). It is also a class for each
* type.
*
* @author Kent Randall
*
*/
@Entity
@Table(name = "PLANT_ENTITY")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "HIER_LEVEL", discriminatorType = DiscriminatorType.STRING)
@AttributeOverride(name = "primaryKey", column = @Column(name = "ENT_KEY"))
public class PlantEntity extends NamedObject {
public static final String ROOT_ENTITY_NAME = "All Entities";
// parent object in the S95 hierarchy
@ManyToOne
@JoinColumn(name = "PARENT_KEY")
private PlantEntity parent;
// children
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private final Set<PlantEntity> children = new HashSet<>();
// level in the hierarchy
@Column(name = "HIER_LEVEL", insertable = false, updatable = false)
@Convert(converter = EntityLevelConverter.class)
private EntityLevel level;
// work schedules
@OneToMany(mappedBy = "plantEntity", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<EntitySchedule> entitySchedules = new HashSet<>();
// retention period for database records
@Column(name = "RETENTION")
private Duration retentionDuration;
public PlantEntity() {
super();
}
public PlantEntity(String name, String description, EntityLevel nodeLevel) {
super(name, description);
this.level = nodeLevel;
}
public PlantEntity(PlantEntityDto dto) throws Exception {
super(dto.getName(), dto.getDescription());
this.retentionDuration = dto.getRetentionDuration() != null ? Duration.ofSeconds(dto.getRetentionDuration())
: null;
for (EntityScheduleDto scheduleDto : dto.getEntitySchedules()) {
EntitySchedule schedule = new EntitySchedule(scheduleDto);
schedule.setPlantEntity(this);
entitySchedules.add(schedule);
}
}
public PlantEntity getParent() {
return this.parent;
}
public void setParent(PlantEntity parent) {
this.parent = parent;
}
public Set<PlantEntity> getChildren() {
return this.children;
}
public void addChild(PlantEntity child) {
if (!children.contains(child)) {
children.add(child);
child.setParent(this);
}
}
public void removeChild(PlantEntity child) {
if (children.contains(child)) {
children.remove(child);
child.setParent(null);
}
}
public EntityLevel getLevel() {
return level;
}
public void setLevel(EntityLevel level) {
this.level = level;
}
public Set<EntitySchedule> getSchedules() {
return this.entitySchedules;
}
public void setSchedules(Set<EntitySchedule> schedules) {
this.entitySchedules = schedules;
}
public void addEntitySchedule(EntitySchedule entitySchedule) {
if (!entitySchedules.contains(entitySchedule)) {
this.entitySchedules.add(entitySchedule);
}
}
public void removeEntitySchedule(EntitySchedule entitySchedule) {
if (entitySchedules.contains(entitySchedule)) {
this.entitySchedules.remove(entitySchedule);
}
}
public WorkSchedule findWorkSchedule() {
WorkSchedule schedule = null;
LocalDateTime now = LocalDateTime.now();
for (EntitySchedule entitySchedule : entitySchedules) {
if (now.isAfter(entitySchedule.getStartDateTime()) && now.isBefore(entitySchedule.getEndDateTime())) {
schedule = entitySchedule.getWorkSchedule();
break;
}
}
if (schedule == null && parent != null) {
schedule = parent.findWorkSchedule();
}
return schedule;
}
public Duration getRetentionDuration() {
return retentionDuration;
}
public void setRetentionDuration(Duration retentionDuration) {
this.retentionDuration = retentionDuration;
}
public Duration findRetentionPeriod() {
Duration duration = retentionDuration;
if (duration == null && parent != null) {
duration = parent.findRetentionPeriod();
}
return duration;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PlantEntity) {
return super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(getName(), getDescription());
}
@Override
public String toString() {
String parentName = parent != null ? parent.getName() : "none";
return super.toString() + ", Level: " + getLevel() + ", Parent: " + parentName;
}
}
|
package com.nps.hellow.service;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.nps.hellow.ConversationActivity;
import com.nps.hellow.ProfilActivity;
import com.nps.hellow.R;
import com.nps.hellow.VolleyConnexion;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Daniel on 17/01/2015.
*/
public class NotificationIntentService extends IntentService {
public final static String TAG = NotificationIntentService.class.getSimpleName();
public NotificationIntentService() {
super("NotificationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
System.out.println(TAG + " Intent Service started");
while (true) {
checkNotifs();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void checkNotifs() {
JSONObject js = new JSONObject();
try {
js.put("id",VolleyConnexion.getInstance().getId_uti());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest requestNotifMessage = new JsonObjectRequest(Request.Method.POST,"http://nodejs-hellowapp.rhcloud.com:8000/getNotifMessage", js,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Response OK du serveur
System.out.println("Response request notif message : " + response.toString());
try {
// Envoyer la notif si j'ai reçu message
if (response.names().getString(0).equals("result")) {
// System.out.println("Pas de nouvelle notif");
} else {
// Sinon on reçoit une response avec utilisateur
JSONArray array = response.getJSONArray("utilisateur");
for (int i = 0; i < array.length(); i++) {
int idSender = Integer.parseInt(array.getJSONObject(i).getString("id"));
final String contenuSender = array.getJSONObject(i).getString("contenu");
// System.out.println("Response NOTIFMessage idSender : " + idSender);
// System.out.println("Response NOTIFMESSAGE contenuSender : " + contenuSender);
JSONObject js = new JSONObject();
try {
js.put("id", idSender);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(js);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "http://nodejs-hellowapp.rhcloud.com:8000/getUtilisateurId", js,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
System.out.println(response);
// GET PSEUDO
// System.out.println("Response getPseudoById getString Pseudo : " + response.getString("pseudo"));
String pseudoAmi = response.getString("pseudo");
System.out.println("Response imbriqué NOTIF getPseudoAmi() : " + pseudoAmi);
generateNotificationMessage(getApplicationContext(), contenuSender, pseudoAmi);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
VolleyConnexion.getInstance().getRequestQueue().add(request);
// generateNotificationMessage(getApplicationContext(), contenuSender, pseudoSender);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// NetworkResponse networkResponse = error.networkResponse;
// System.err.println("GetNotifMessage réponse ERREUR");
}
}
);
VolleyConnexion.getInstance().getRequestQueue().add(requestNotifMessage);
JsonObjectRequest requestNotifFriend = new JsonObjectRequest(Request.Method.POST,"http://nodejs-hellowapp.rhcloud.com:8000/getNotifFriend", js,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// System.out.println("Response request notif friend : " + response.toString());
try {
// Envoyer la notif si j'ai reçu un message
if (response.names().getString(0).equals("result")) {
// System.out.println("Pas de nouvelle notif");
} else {
// Sinon on reçoit une response avec utilisateur
JSONArray array = response.getJSONArray("utilisateur");
for (int i = 0; i < array.length(); i++) {
int idSender = Integer.parseInt(array.getJSONObject(i).getString("id"));
System.out.println("Response NOTIF Friend idSender : " + idSender);
JSONObject js = new JSONObject();
try {
js.put("id", idSender);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "http://nodejs-hellowapp.rhcloud.com:8000/getUtilisateurId", js,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
// GET PSEUDO
// System.out.println("Response getPseudoById getString Pseudo : " + response.getString("pseudo"));
String pseudoAmi = new String(response.getString("pseudo"));
// System.out.println("Response imbriqué NOTIF getPseudoAmi() : " + pseudoAmi);
generateNotificationFriend(getApplicationContext(), pseudoAmi);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
VolleyConnexion.getInstance().getRequestQueue().add(request);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// // Sinon {"result":"ok"} ne rien faire
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// NetworkResponse networkResponse = error.networkResponse;
// System.err.println("GetNotifMessage réponse ERREUR");
}
}
);
VolleyConnexion.getInstance().getRequestQueue().add(requestNotifFriend);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private static void generateNotificationMessage(Context context, String message, String extraPseudo) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
System.out.println(extraPseudo);
Intent notificationIntent = null;
notificationIntent = new Intent(context, ConversationActivity.class);
notificationIntent.putExtra("pseudotest", extraPseudo.toString());
notificationIntent.putExtra("test","trolololo");
VolleyConnexion.getInstance().setFriend(extraPseudo);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
String title = context.getString(R.string.app_name);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(context)
.setContentText(extraPseudo + " : " + message)
.setSmallIcon(icon)
.setWhen(when)
.setContentTitle(title)
.setContentIntent(intent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private static void generateNotificationFriend(Context context, String extraPseudo) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = null;
notificationIntent = new Intent(context, ProfilActivity.class);
notificationIntent.putExtra("pseudo", extraPseudo);
notificationIntent.putExtra("activity", " ");
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
String title = context.getString(R.string.app_name);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(context)
.setContentText("Nouvelle demande d'ami de " + extraPseudo)
.setSmallIcon(icon)
.setWhen(when)
.setContentTitle(title)
.setContentIntent(intent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
// public String getPseudoAmi() {
// return pseudoAmi;
// }
//
// public void setPseudoAmi(String pseudoAmi) {
// this.pseudoAmi = pseudoAmi;
// }
}
|
package com.oriaxx77.javaplay.java8features.stream;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.oriaxx77.javaplay.Example;
@Example("Parallel processing with streams")
public class PrimeCountWithParallelStream {
@Example
public Integer getPrimeCount( int treshold ) throws InterruptedException, ExecutionException {
final List<Integer> candidates = IntStream.range(2, treshold).boxed().collect(Collectors.toList());
final ForkJoinPool forkJoinPool = new ForkJoinPool(5);
final List<Integer> primeNumbers = forkJoinPool.submit(() -> candidates.parallelStream().filter( this::isPrime).
collect(Collectors.toList())).get();
return primeNumbers.size();
}
private boolean isPrime( int candidate ){
for (int i = 2; i * i <= candidate; i++) {
if (candidate % i == 0) {
return false;
}
}
return true;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.scf.core.context;
/**
* 唯一标示上下文
* @author wub
*
*/
public interface IdentityContext {
public Identity getIdentity();
public void setIdentity(Identity identity);
}
|
package modelo;
public abstract class ObjetoJuego {
protected String nombre;
protected Tablero tablero;
public String getNombre(){
return this.nombre;
}
public boolean esPersonaje(){
return (this instanceof Personaje);
}
public boolean esConsumible(){
return (this instanceof Consumible);
}
} |
package com.mingrisoft;
import java.util.*;
import java.io.*;
import java.math.*;
public class Test
{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;private byte[] buffer;private int bufferPointer, bytesRead;
public Reader(){buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;
}private void fillBuffer() throws IOException{bytesRead=System.in.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;
}private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];
}public String next() throws IOException{StringBuilder sb = new StringBuilder();byte c;while((c=read())<=' ');do{sb.append((char)c);} while((c=read())>' ');return sb.toString();
}public String nextLine() throws IOException{StringBuilder sb = new StringBuilder();byte c;while((c=read())!=-1){if(c=='\n')break;sb.append((char)c);}return sb.toString();
}public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
}public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10L+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;
}public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;
}public void close() throws IOException{if(System.in==null) return;System.in.close();}
}
public static Reader in = new Reader();
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException
{
Scanner cin = new Scanner(System.in);
while(cin.hasNext())
{
long a = cin.nextLong();
long b = cin.nextLong();
long t = a+b;
int ans = 0;
while(t!=0)
{
ans++;
t /= 10;
}
System.out.println(ans);
}
}
} |
package com.legaoyi.protocol.down.messagebody;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.legaoyi.protocol.message.MessageBody;
/**
* 提问下发
*
* @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a>
* @version 1.0.0
* @since 2015-01-30
*/
@Scope("prototype")
@Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "8302_2011" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX)
public class JTT808_8302_MessageBody extends MessageBody {
private static final long serialVersionUID = -1826119762827732057L;
public static final String MESSAGE_ID = "8302";
/** 标志 **/
@JsonProperty("flag")
private String flag;
/** 问题 **/
@JsonProperty("question")
private String question;
/** 候选答案列表,key/val键值对,包括答案id:answerId,答案内容:answer **/
private List<Map<String, Object>> answerList;
public final String getFlag() {
return flag;
}
public final void setFlag(String flag) {
this.flag = flag;
}
public final String getQuestion() {
return question;
}
public final void setQuestion(String question) {
this.question = question;
}
public final List<Map<String, Object>> getAnswerList() {
return answerList;
}
public final void setAnswerList(List<Map<String, Object>> answerList) {
this.answerList = answerList;
}
}
|
/**
*
*/
package net.imagej.domains;
import net.imglib2.RealRandomAccessible;
/**
* @author Stephan Saalfeld <saalfelds@janelia.hhmi.org>
*
*/
public class ContinuousDomain<A, T> implements Domain<A, T>, RealRandomAccessible<A> {
/**
* Get a flattened {@link RealRandomAccessible} that provides
* access to the terminal values. The number of dimensions
* is this.numDimensions + the number of dimensions of the
* co-domains.
*
* TODO This is not necessarily possible if any of the co-domains
* is discrete as long as we haven't solved how to do interpolation.
* It requires that each co-domain can be transferred into a
* continuous domain. If interpolation is necessary to do so, then
* this only makes sense if T can be interpolated (nearest neighbor
* is always possible?).
*
* @return
*/
RealRandomAccessible<T> flatAccessible();
}
|
package com.citibank.ods.entity.pl.valueobject;
import java.math.BigInteger;
import com.citibank.ods.entity.pl.TplMrDocPrvtEntity;
/**
* @author m.nakamura
*
* Representação da tabela de Memória de Risco.
*/
public class TplMrDocPrvtMovEntityVO extends BaseTplMrDocPrvtEntityVO
{
/**
* @param mrDocPrvtEntity_
* @param lastAuthDate_
* @param lastAuthUserId_
*/
public TplMrDocPrvtMovEntityVO( TplMrDocPrvtEntity mrDocPrvtEntity_,
BigInteger prvtMrCode_, String prodAcctCode_,
String prodUnderAcctCode_ )
{
TplMrDocPrvtEntityVO mrDocPrvtEntityVO = ( TplMrDocPrvtEntityVO ) mrDocPrvtEntity_.getData();
String prodAcctCode = prodAcctCode_;
String prodUnderAcctCode = prodUnderAcctCode_;
BigInteger prvtMrCode = prvtMrCode_;
this.setMrDocCode( mrDocPrvtEntityVO.getMrDocPrvt() );
this.setMrDocText( mrDocPrvtEntityVO.getMrDocText() );
this.setMrInvstCurAcctInd( mrDocPrvtEntityVO.getMrInvstCurAcctInd() );
this.setProdAcctCode( mrDocPrvtEntityVO.getProdAcctCode() );
this.setProdUnderAcctCode( mrDocPrvtEntityVO.getProdUnderAcctCode() );
}
/**
* Cria novo objeto TplMrDocPrvtEntityVO.
*/
public TplMrDocPrvtMovEntityVO()
{
//
}
//Codigo Documento MR
private BigInteger m_mrDocCode = null;
// Código da ação que originou o registro
private String m_opernCode = "";
/**
* Recupera Codigo Documento MR
*
* @return Retorna Codigo Documento MR
*/
public BigInteger getMrDocCode()
{
return m_mrDocCode;
}
/**
* Seta Codigo Documento MR
*
* @param mrDocCode_ - Codigo Documento MR
*/
public void setMrDocCode( BigInteger mrDocCode_ )
{
m_mrDocCode = mrDocCode_;
}
/**
* Recupera o Código da ação que originou o registro
*
* @return Retorna o Código da ação que originou o registro
*/
public String getOpernCode()
{
return m_opernCode;
}
/**
* Seta o Código da ação que originou o registro
*
* @param opernCode_ - O Código da ação que originou o registro
*/
public void setOpernCode( String opernCode_ )
{
m_opernCode = opernCode_;
}
} |
package eden.mobv.api.fei.stu.sk.mobv_eden.resources;
import android.app.Activity;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.FloatingActionButton;
import android.view.View;
import eden.mobv.api.fei.stu.sk.mobv_eden.R;
public class UploadMediaButton {
private Activity activity;
private ConstraintLayout constraintLayout;
private FloatingActionButton floatingActionButton;
private int MEDIA_PICKER_SELECT;
// input: Activity where is button placed, ConstraintLayout of activity, variable to determine if file was picked
public UploadMediaButton(Activity _activity, ConstraintLayout _constraintLayout, int _MEDIA_PICKER_SELECT) {
activity = _activity;
constraintLayout = _constraintLayout;
MEDIA_PICKER_SELECT = _MEDIA_PICKER_SELECT;
// create button
floatingActionButton = activity.findViewById(R.id.fab_add);
}
// set on click listener to pick video/image from gallery
private void setMediaPickListener() {
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Handle the click.
Intent pickMediaIntent = new Intent();
pickMediaIntent.setType("*/*");
pickMediaIntent.setAction(Intent.ACTION_GET_CONTENT);
pickMediaIntent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"image/jpeg", "image/png", "video/mp4"});
activity.startActivityForResult(pickMediaIntent, MEDIA_PICKER_SELECT);
}
});
}
public void setEverything() {
setMediaPickListener();
}
}
|
package com.example.faisal.models;
import com.example.faisal.configs.postgres.PostgresEnumType;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Data
@TypeDef(name = "enum_postgres", typeClass = PostgresEnumType.class)
public abstract class Base implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
}
|
package com.test.automation.repository;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.test.automation.common.SeHelper;
public class CommonRepo {
public static By username = By.xpath("//*[@id='UserName']");
public static WebElement UserName(SeHelper se) {
return se.element().getElement(username);
}
public static WebElement ElementObject(SeHelper se, String expression) {
long startWait = System.nanoTime();
String typeOfExpression = getTypeOfExpression(expression);
//
//
// if(typeOfExpression != null)
// {
// typeOfExpression = expression.substring(expression.indexOf('=') + 1);
// }
if (expression.startsWith("/") || expression.startsWith("(/")) {
WebElement element = getXPathElement(se, expression);
if (element == null) {
//se.waits().waitForElement(By.xpath(expression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.xpath(expression));
}
return getXPathElement(se, expression);
}
else if(typeOfExpression == null)
{
WebElement element = getCSSElement(se, expression);
if (element == null) {
//se.waits().waitForElement(By.cssSelector(expression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.cssSelector(expression));
}
return getCSSElement(se, expression);
}
else
{
String newExpression = expression.substring(expression.indexOf('=') + 1);
System.out.print(newExpression);
return getElementBasedOnExpression(se, newExpression, typeOfExpression);
}
// return se.element().getElement(By.xpath(xPathExpression));
}
private static WebElement getElementBasedOnExpression(SeHelper se, String newExpression, String typeOfExpression) {
long stopWait;
WebElement element;
switch(typeOfExpression)
{
case "CSS":
element = getCSSElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.cssSelector(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.cssSelector(newExpression));
}
return getCSSElement(se, newExpression);
case "Xpath":
element = getXPathElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.xpath(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.xpath(newExpression));
}
return getXPathElement(se, newExpression);
case "id":
element = getIdElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.id(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.id(newExpression));
}
return getIdElement(se, newExpression);
case "name":
element = getNameElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.name(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.name(newExpression));
}
return getNameElement(se, newExpression);
case "Linktext":
element = getLinkTextElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.linkText(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.linkText(newExpression));
}
return getLinkTextElement(se, newExpression);
case "PartialLinktext":
element = getPartialLinkTextElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.partialLinkText(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.partialLinkText(newExpression));
}
return getPartialLinkTextElement(se, newExpression);
case "TagName":
element = getTagNameElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.tagName(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.tagName(newExpression));
}//
return getTagNameElement(se, newExpression);
case "Classname":
element = getClassnameElement(se, newExpression);
if (element == null) {
//se.waits().waitForElement(By.className(newExpression));
}
if (!element.isDisplayed()) {
//se.waits().waitForElementIsDisplayed(By.className(newExpression));
}
return getClassnameElement(se, newExpression);
}
return null;
}
private static String getTypeOfExpression(String expression) {
String[] selectors = { "Xpath", "CSS", "id", "name", "Linktext", "PartialLinktext", "TagName", "Classname" };
for (int i = 0; i < selectors.length; i++) {
if (expression.startsWith(selectors[i]))
return selectors[i];
}
return null;
}
private static WebElement getXPathElement(SeHelper se, String xPathExpression) {
return se.element().getElement(By.xpath(xPathExpression));
}
private static WebElement getCSSElement(SeHelper se, String cssExpression) {
return se.element().getElement(By.cssSelector(cssExpression));
}
private static WebElement getIdElement(SeHelper se, String idExpression) {
return se.element().getElement(By.id(idExpression));
}
private static WebElement getNameElement(SeHelper se, String nameExpression) {
return se.element().getElement(By.name(nameExpression));
}
private static WebElement getLinkTextElement(SeHelper se, String linkTextExpression) {
return se.element().getElement(By.linkText(linkTextExpression));
}
private static WebElement getTagNameElement(SeHelper se, String tagNameExpression) {
return se.element().getElement(By.tagName(tagNameExpression));
}
private static WebElement getPartialLinkTextElement(SeHelper se, String partialLinkTextExpression) {
return se.element().getElement(By.partialLinkText(partialLinkTextExpression));
}
private static WebElement getClassnameElement(SeHelper se, String classNameExpression) {
return se.element().getElement(By.className(classNameExpression));
}
}
|
/*
* 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 userInterface.MunicipalCorpAdminWorkArea;
import Business.FedGoverment;
import Business.MunicipalCorporation.MunicipalCorporation;
import java.awt.CardLayout;
import javax.swing.JPanel;
/**
*
* @author User
*/
public class MunicipalCorpAdminWorkAreaJPanel extends javax.swing.JPanel {
/**
* Creates new form MunicipalCorpAdminWorkAreaJPanel
*/
private JPanel userProcessContainer;
private MunicipalCorporation municipalCorp;
public MunicipalCorpAdminWorkAreaJPanel(JPanel userProcessContainer,MunicipalCorporation municipalCorp) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.municipalCorp=municipalCorp;
// lblAccount.setText(municipalCorp.getName());
}
/**
* 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() {
btnOrganization = new javax.swing.JButton();
btnOrganizationEntity = new javax.swing.JButton();
btnEntitytLogin = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 255, 255));
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btnOrganization.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
btnOrganization.setText("Manage Organization Panel");
btnOrganization.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOrganizationActionPerformed(evt);
}
});
add(btnOrganization, new org.netbeans.lib.awtextra.AbsoluteConstraints(125, 124, 190, 40));
btnOrganizationEntity.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
btnOrganizationEntity.setText("Manage Organization Entitity");
btnOrganizationEntity.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOrganizationEntityActionPerformed(evt);
}
});
add(btnOrganizationEntity, new org.netbeans.lib.awtextra.AbsoluteConstraints(125, 190, 190, 40));
btnEntitytLogin.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
btnEntitytLogin.setText("Manage Entity LogIn");
btnEntitytLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEntitytLoginActionPerformed(evt);
}
});
add(btnEntitytLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 260, 190, 40));
jLabel1.setFont(new java.awt.Font("Calibri", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 51, 51));
jLabel1.setText("MUNICIPAL CORPORATION ADMIN WORK AREA");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 20, 500, 33));
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/administrator-clipart-sysadmin.jpg"))); // NOI18N
add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 730, 510));
}// </editor-fold>//GEN-END:initComponents
private void btnOrganizationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOrganizationActionPerformed
// TODO add your handling code here:
ManageOrganizationJPanel moj=new ManageOrganizationJPanel(userProcessContainer, municipalCorp.getOrganizationDirectory());
userProcessContainer.add("ManageOrganizationJPanel", moj);
CardLayout layout=(CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_btnOrganizationActionPerformed
private void btnOrganizationEntityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOrganizationEntityActionPerformed
// TODO add your handling code here
ManageOrganizationEnitityJPanel moe=new ManageOrganizationEnitityJPanel(userProcessContainer, municipalCorp.getOrganizationDirectory());
userProcessContainer.add("ManageOrganizationEnitityJPanel", moe);
CardLayout layout=(CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_btnOrganizationEntityActionPerformed
private void btnEntitytLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEntitytLoginActionPerformed
// TODO add your handling code here:
ManageEntityLoginJPanel mel=new ManageEntityLoginJPanel(userProcessContainer, municipalCorp);
userProcessContainer.add("ManageEntityLoginJPanel", mel);
CardLayout layout=(CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}//GEN-LAST:event_btnEntitytLoginActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnEntitytLogin;
private javax.swing.JButton btnOrganization;
private javax.swing.JButton btnOrganizationEntity;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
// End of variables declaration//GEN-END:variables
}
|
/*
* @(#) ErrorCodeService.java
* Copyright (c) 2006 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.errorcode.service.impl;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.esum.appframework.exception.ApplicationException;
import com.esum.appframework.service.impl.BaseService;
import com.esum.imsutil.util.ExcelCreater;
import com.esum.wp.ims.errorcode.ErrorCode;
import com.esum.wp.ims.errorcode.dao.IErrorCodeDAO;
import com.esum.wp.ims.errorcode.service.IErrorCodeService;
import com.esum.wp.ims.tld.XtrusLangTag;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.1 $ $Date: 2008/07/31 01:49:06 $
*/
public class ErrorCodeService extends BaseService implements IErrorCodeService {
/**
* Default constructor. Can be used in place of getInstance()
*/
public ErrorCodeService () {}
public Object insertErrorCode(Object object) {
try {
IErrorCodeDAO iErrorCodeDAO = (IErrorCodeDAO)iBaseDAO;
return iErrorCodeDAO.insertErrorCode(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object uploadErrorCode(Object object) {
try {
IErrorCodeDAO iErrorCodeDAO = (IErrorCodeDAO)iBaseDAO;
return iErrorCodeDAO.uploadErrorCode(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object selectPageList(Object object) {
try {
IErrorCodeDAO iErrorCodeDAO = (IErrorCodeDAO)iBaseDAO;
return iErrorCodeDAO.selectPageList(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object selectDetail(Object object) {
try {
IErrorCodeDAO iErrorCodeDAO = (IErrorCodeDAO)iBaseDAO;
return iErrorCodeDAO.selectDetail(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
@Override
public void saveErrorCodeExcel(Object object, HttpServletRequest request, HttpServletResponse response) throws Exception{
ErrorCode info = (ErrorCode) object;
IErrorCodeDAO iErrorCodeDAO = (IErrorCodeDAO)iBaseDAO;
Map map = iErrorCodeDAO.saveErrorCodeExcel(object);
List data = (List) map.get("data");
String table = (String) map.get("table");
String[] titles = (String[]) map.get("header");
int[] size = (int[]) map.get("size");
ExcelCreater excel = new ExcelCreater();
excel.createSheet(table, titles, size, data);
excel.download(info.getRootPath(), XtrusLangTag.getMessage("lm.ims.setting.errorcode"), request, response);
}
@Override
public Object selectCategoryList(Object object) {
try {
IErrorCodeDAO iErrorCodeDAO = (IErrorCodeDAO)iBaseDAO;
return iErrorCodeDAO.selectCategoryList(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
}
|
package com.gaoshin.top;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import common.util.web.JsonUtil;
public class PhoneListener extends BroadcastReceiver {
private static final String tag = PhoneListener.class.getSimpleName();
/**
* For outgoing call, we will get msgs below
* 1. null, null, outgoingnumber
* 2. OFFHOOK, null, null
* 3. IDLE, null, null
* For incoming call, we will get msgs below
* 1. RINGING, incomingnumber, null
* 2. OFFHOOK, null, null
* 3. IDLE, null, null
* or
* 1. RINGING, incomingnumber, null
* 2. IDLE, incomingnumber, null
*/
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(null == bundle)
return;
CallEvent callState = new CallEvent();
String extraState = bundle.getString(TelephonyManager.EXTRA_STATE);
if(extraState != null) {
try {
callState.setType(CallState.valueOf(extraState));
}
catch (Exception e) {
e.printStackTrace();
}
}
String number = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
callState.setIncomingNumber(number);
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
callState.setOutgoingNumber(number);
if(callState.getOutgoingNumber() != null)
callState.setType(CallState.CALL);
String json = JsonUtil.toJsonString(callState);
Log.i(tag, "CALL STATE CHANGE: " + json);
Intent serviceIntent = new Intent(context, TopService.class);
serviceIntent.setAction("CallEvent");
serviceIntent.putExtra("data", json);
context.startService(serviceIntent);
}
}
|
package com.taim.backendservice.service.transaction;
import com.taim.backendservice.model.Transaction;
import com.taim.backendservice.service.IBaseService;
public interface ITransactionService extends IBaseService<Transaction> {}
|
/*
* @(#)ChatServantFactoryjava 1.0 09/13/2000
*
*/
package org.google.code.netapps.chat.basic;
import org.google.code.servant.net.ServantFactory;
import org.google.code.servant.net.Servant;
/**
* This class represents a factory object for creation servants
* for serving chat conversation
*
* @version 1.0 09/13/2000
* @author Alexander Shvets
*/
public class ChatServantFactory implements ServantFactory {
/** The stateful server */
private ChatServer server;
/**
* Creates a factory
*
* @param server stateful server
*/
public ChatServantFactory(ChatServer server) {
this.server = server;
}
/**
* Creates servant
*
* @return servant object
*/
public Servant create() {
return new ChatServant(server);
}
}
|
package com.example.oscar.citiappdemo.domain;
import com.example.oscar.citiappdemo.data.remote.models.GetClientNameRequest;
import com.example.oscar.citiappdemo.data.remote.models.GetClientNameResponse;
import com.example.oscar.citiappdemo.data.repository.GetClientNameDataRepository;
import com.example.oscar.citiappdemo.data.repository.GetClientNameRepository;
import javax.inject.Inject;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.functions.Function;
/**
* This class is an implementation of {@link UseCase} that represents a use case for
* retrieving a collection of all {@link GetClientNameRequest}.
*/
public class GetClientName extends UseCase<String, String> {
private final GetClientNameDataRepository getClientNameDataRepository;
@Inject
GetClientName(GetClientNameRepository getClientNameDataRepository,
ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) {
super(threadExecutor, postExecutionThread);
this.getClientNameDataRepository = getClientNameDataRepository;
}
/**
* Builds an {@link Single} which will be used when executing the current {@link UseCase}.
*
* @param clientNumber a client number
*/
@Override
Single<String> buildUseCaseObservable(String clientNumber) {
return getClientNameDataRepository.getClientName(new GetClientNameRequest(clientNumber))
.flatMap((Function<GetClientNameResponse, SingleSource<String>>) getClientNameResponse -> {
if (!getClientNameResponse.getOpstatus().equals("0")) return Single.error(new Throwable("Valio"));
return Single.just(getClientNameResponse.getClientName());
});
}
} |
package com.wangzhu.other;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wang.zhu on 2021-03-28 23:59.
**/
public class LRUCacheInteger {
static class Node {
final int key;
int value;
Node next;
Node prev;
Node(final int key, int value) {
this.key = key;
this.value = value;
}
}
final int capacity;
final Map<Integer, Node> map;
int size;
Node head, tail;
public LRUCacheInteger(int capacity) {
this.capacity = capacity;
final int initialCapacity = (int) ((float) capacity / 0.75F + 1.0F);
this.map = new HashMap<>(initialCapacity);
}
public int get(int key) {
final Node node = this.map.get(key);
if (node == null) {
return -1;
}
removeNode(node);
addHeadNode(node);
return node.value;
}
public void put(int key, int value) {
Node node = this.map.get(key);
if (node != null) {
//存在更新
removeNode(node);
node.value = value;
} else {
if (this.size == this.capacity) {
Node tail = this.tail;
this.map.remove(tail.key);
size--;
removeNode(tail);
}
node = new Node(key, value);
this.map.put(key, node);
this.size++;
}
addHeadNode(node);
}
private void removeNode(final Node node) {
final Node prev = node.prev, next = node.next;
if (prev == null && next == null) {
this.head = this.tail = null;
} else if (prev == null) {
//头节点
this.head = next;
next.prev = null;
} else if (next == null) {
//尾节点
this.tail = prev;
prev.next = null;
} else {
//中间节点
prev.next = next;
next.prev = prev;
}
node.prev = null;
node.next = null;
}
private void addHeadNode(final Node node) {
if (this.tail == null) {
this.tail = node;
} else {
Node head = this.head;
node.next = head;
head.prev = node;
}
this.head = node;
}
}
|
package com.soa.beer.model;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@Stateless
public class ExpertBean {
private Map<String, List<String>> beers = new HashMap<>();
@PostConstruct
public void postConstruct() {
initBeers();
}
private void initBeers() {
beers.put("jasny", new LinkedList<String>() {{
add("piwo jasne 1");
add("piwo jasne 2");
add("piwo jasne 3");
add("piwo jasne 4");
}});
beers.put("bursztynowy", new LinkedList<String>() {{
add("piwo bursztynowy 1");
add("piwo bursztynowy 2");
add("piwo bursztynowy 3");
add("piwo bursztynowy 4");
}});
beers.put("brazowy", new LinkedList<String>() {{
add("piwo brazowy 1");
add("piwo brazowy 2");
add("piwo brazowy 3");
add("piwo brazowy 4");
}});
beers.put("ciemny", new LinkedList<String>() {{
add("piwo ciemny 1");
add("piwo ciemny 2");
add("piwo ciemny 3");
add("piwo ciemny 4");
}});
}
public List<String> getBeersByType(String beerType) {
return beers.getOrDefault(beerType, Collections.emptyList());
}
}
|
package fr.skytasul.quests.players;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import fr.skytasul.quests.BeautyQuests;
import fr.skytasul.quests.structure.Quest;
import fr.skytasul.quests.structure.pools.QuestPool;
import fr.skytasul.quests.utils.Utils;
public class PlayerPoolDatas {
protected final PlayerAccount acc;
protected final int poolID;
private long lastGive;
private Set<Integer> completedQuests;
private Quest tempStartQuest;
public PlayerPoolDatas(PlayerAccount acc, int poolID) {
this(acc, poolID, 0, new HashSet<>());
}
public PlayerPoolDatas(PlayerAccount acc, int poolID, long lastGive, Set<Integer> completedQuests) {
this.acc = acc;
this.poolID = poolID;
this.lastGive = lastGive;
this.completedQuests = completedQuests;
}
public PlayerAccount getAccount() {
return acc;
}
public int getPoolID() {
return poolID;
}
public QuestPool getPool() {
return BeautyQuests.getInstance().getPoolsManager().getPool(poolID);
}
public long getLastGive() {
return lastGive;
}
public void setLastGive(long lastGive) {
this.lastGive = lastGive;
}
public Set<Integer> getCompletedQuests() {
return completedQuests;
}
public void setCompletedQuests(Set<Integer> completedQuests) {
this.completedQuests = completedQuests;
updatedCompletedQuests();
}
public void updatedCompletedQuests() {}
public Quest getTempStartQuest() {
return tempStartQuest;
}
public void setTempStartQuest(Quest tempStartQuest) {
this.tempStartQuest = tempStartQuest;
}
public Map<String, Object> serialize() {
Map<String, Object> map = new HashMap<>();
map.put("poolID", poolID);
map.put("lastGive", lastGive);
map.put("completedQuests", completedQuests);
return map;
}
public static PlayerPoolDatas deserialize(PlayerAccount acc, Map<String, Object> map) {
PlayerPoolDatas datas = new PlayerPoolDatas(acc, (int) map.get("poolID"));
datas.lastGive = Utils.parseLong(map.get("lastGive"));
datas.completedQuests = (Set<Integer>) map.get("completedQuests");
return datas;
}
}
|
package ogm.arbitrage;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
public EditText phone1;
public EditText pass1;
public Button btnForget;
public Button btnSignIn;
public Button btnRegister;
public TextView lblWelcome;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.activity_register);
//Context mAppContext = null;
// TelephonyManager tMgr = (TelephonyManager) mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
phone1 = (EditText) findViewById(R.id.txtPhone);
phone1.setText(mPhoneNumber);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
setMenu(menu);
return true;
}
@Override
public void onResume() {
super.onResume();
if (Globals.login != "No") { showWelcome(); }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
setMenu(menu);
return true;
}
private void setMenu(Menu menu) {
switch (Globals.memberType){
case "Assignor":
menu.findItem(R.id.mnuGames).setVisible(false);
menu.findItem(R.id.mnuTransfer).setVisible(false);
menu.findItem(R.id.mnuPassword).setVisible(true);
menu.findItem(R.id.mnuModify).setVisible(true);
menu.findItem(R.id.mnuAssociation).setVisible(true);
menu.findItem(R.id.mnuAssignGames).setVisible(true);
break;
case "Referee":
menu.findItem(R.id.mnuAssociation).setVisible(false);
menu.findItem(R.id.mnuAssignGames).setVisible(false);
menu.findItem(R.id.mnuPassword).setVisible(true);
menu.findItem(R.id.mnuModify).setVisible(true);
menu.findItem(R.id.mnuGames).setVisible(true);
menu.findItem(R.id.mnuTransfer).setVisible(true);
break;
default:
menu.findItem(R.id.mnuPassword).setVisible(false);
menu.findItem(R.id.mnuModify).setVisible(false);
menu.findItem(R.id.mnuGames).setVisible(false);
menu.findItem(R.id.mnuTransfer).setVisible(false);
menu.findItem(R.id.mnuAssociation).setVisible(false);
menu.findItem(R.id.mnuAssignGames).setVisible(false);
break;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.mnuPassword:
intent = new Intent(this, ChangePassword.class);
startActivity(intent);
return true;
case R.id.mnuModify:
intent = new Intent(this, Register.class);
intent.putExtra("activity", "Modify");
startActivity(intent);
return true;
case R.id.mnuAssignGames:
intent = new Intent(this, AssignGames.class);
intent.putExtra("activity", "AssignGames");
startActivity(intent);
case R.id.action_settings:
//perform settings
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void activate_Register(View view) {
Intent intent = new Intent(this, Register.class);
intent.putExtra("activity", "Register");
startActivity(intent);
}
public void Log_In(View view) {
String urlString1 = "";
phone1 = (EditText) findViewById(R.id.txtPhone);
pass1 = (EditText) findViewById(R.id.txtPassword);
/* prepare your search string to be put in a URL. It might have reserved characters or something*/
String urlString = phone1.getText().toString() + ",";
urlString = urlString + pass1.getText().toString();
try { urlString1 = URLEncoder.encode(urlString, "UTF-8"); }
catch (UnsupportedEncodingException e) {
/* if this fails for some reason, let the user know why */
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); }
/*create a client to perform networking*/
AsyncHttpClient client = new AsyncHttpClient();
//Have the client get a JSONArray of data and define how to respond*/
client.get(Globals.QUERY_URL + "L=" + urlString1, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
/* display a Toast message to announce your success*/
if (jsonObject.optJSONArray("log").optString(0).contains("Error")) {
Toast.makeText(getApplicationContext(), jsonObject.optJSONArray("log").optString(0), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Log in was Successful!", Toast.LENGTH_LONG).show();
/*update the data in your custom method*/
//mJSONAdapter.updateData(jsonObject.optJSONArray("refs"));
Globals.login = "Yes";
Globals.name = jsonObject.optJSONArray("log").optString(0);
Globals.memberType = jsonObject.optJSONArray("log").optString(1);
Globals.phone = jsonObject.optJSONArray("log").optString(2);
Globals.eMail = jsonObject.optJSONArray("log").optString(4);
Globals.password = jsonObject.optJSONArray("log").optString(3);
Globals.grade = jsonObject.optJSONArray("log").optString(5);
Globals.expiratioDate = jsonObject.optJSONArray("log").optString(6);
Globals.associatoinCode = jsonObject.optJSONArray("log").optString(7);
Globals.associatoinName = jsonObject.optJSONArray("log").optString(8);
Globals.associatoinAddress = jsonObject.optJSONArray("log").optString(9);
showWelcome();
}
}
@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("omg android", statusCode + " " + throwable.getMessage());
}
});
}
private void showWelcome() {
phone1.setVisibility(View.INVISIBLE);
pass1 = (EditText) findViewById(R.id.txtPassword);
pass1.setVisibility(View.INVISIBLE);
btnSignIn = (Button) findViewById(R.id.btnLogIn);
btnSignIn.setVisibility(View.INVISIBLE);
btnForget = (Button) findViewById(R.id.btnForget);
btnForget.setVisibility(View.INVISIBLE);
btnRegister = ( Button) findViewById(R.id.btnRegister);
btnRegister.setVisibility(View.INVISIBLE);
lblWelcome = (TextView) findViewById(R.id.lblWelcome);
lblWelcome.setText("Welcome! " + Globals.name );
lblWelcome.setVisibility(View.VISIBLE);
}
public void sendNewPassword(View view) {
String urlString1 = "";
phone1 = (EditText) findViewById(R.id.txtPhone);
/* prepare your search string to be put in a URL. It might have reserved characters or something*/
String urlString = phone1.getText().toString();
try { urlString1 = URLEncoder.encode(urlString, "UTF-8"); }
catch (UnsupportedEncodingException e) {
/* if this fails for some reason, let the user know why */
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); }
/*create a client to perform networking*/
AsyncHttpClient client = new AsyncHttpClient();
//Have the client get a JSONArray of data and define how to respond*/
client.get(Globals.QUERY_URL + "FP=" + urlString1, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
/* display a Toast message to announce your success*/
if (jsonObject.optString("created").contains("Error")) {
//if (jsonObject.optJSONArray("new").optString(0).contains("Error")) {
Toast.makeText(getApplicationContext(), jsonObject.optString("new"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Process was Successful!", Toast.LENGTH_LONG).show();
/*inform about the email sent with the new password.
//mJSONAdapter.updateData(jsonObject.optJSONArray("refs")); */
showDialog("Your new password has been sent to the email address in your registration"); }
}
@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("omg android", statusCode + " " + throwable.getMessage());
}
});
}
private void showDialog(String msg) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(msg);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
|
package main;
import creator.EmissorCreator;
import product.Emissor;
public class TestaEMissores {
public static void main(String[] args) {
EmissorCreator creator = new EmissorCreator();
Emissor emissor1 = creator.create(EmissorCreator.SMS);
emissor1.enviar("K19 Treinamentos");
Emissor emissor2 = creator.create(EmissorCreator.EMAIL);
emissor2.enviar("K19 Treinamentos");
Emissor emissor3 = creator.create(EmissorCreator.JMS);
emissor3.enviar("K19 Treinamentos");
}
}
|
package com.lenovohit.mnis.base.model;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "BASE_CONFIG")
public class Config extends AuditableModel {
private static final long serialVersionUID = -4408551405034621735L;
private String code;
private String value;
private String type;
private String system;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSystem() {
return system;
}
public void setSystem(String system) {
this.system = system;
}
}
|
/*
* Copyright © 2017-2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.topn;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import io.cdap.cdap.api.artifact.ArtifactSummary;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.api.dataset.table.Table;
import io.cdap.cdap.datapipeline.DataPipelineApp;
import io.cdap.cdap.datapipeline.SmartWorkflow;
import io.cdap.cdap.etl.api.Engine;
import io.cdap.cdap.etl.api.batch.BatchAggregator;
import io.cdap.cdap.etl.mock.batch.MockSink;
import io.cdap.cdap.etl.mock.batch.MockSource;
import io.cdap.cdap.etl.mock.common.MockPipelineConfigurer;
import io.cdap.cdap.etl.mock.test.HydratorTestBase;
import io.cdap.cdap.etl.proto.v2.ETLBatchConfig;
import io.cdap.cdap.etl.proto.v2.ETLPlugin;
import io.cdap.cdap.etl.proto.v2.ETLStage;
import io.cdap.cdap.proto.ProgramRunStatus;
import io.cdap.cdap.proto.artifact.AppRequest;
import io.cdap.cdap.proto.id.ApplicationId;
import io.cdap.cdap.proto.id.ArtifactId;
import io.cdap.cdap.proto.id.NamespaceId;
import io.cdap.cdap.test.ApplicationManager;
import io.cdap.cdap.test.DataSetManager;
import io.cdap.cdap.test.WorkflowManager;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Tests for TopN
*/
public class TopNTest extends HydratorTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TopNTest.class);
private static final String INPUT_TABLE = "input";
private static final ArtifactId APP_ARTIFACT_ID = NamespaceId.DEFAULT.artifact("app", "1.0.0");
private static final ArtifactSummary APP_ARTIFACT = new ArtifactSummary("app", "1.0.0");
private static final Schema SCHEMA =
Schema.recordOf("people",
Schema.Field.of("name", Schema.of(Schema.Type.STRING)),
Schema.Field.of("id", Schema.of(Schema.Type.LONG)),
Schema.Field.of("kg", Schema.of(Schema.Type.DOUBLE)),
Schema.Field.of("cm", Schema.of(Schema.Type.FLOAT)),
Schema.Field.of("age", Schema.nullableOf(Schema.of(Schema.Type.INT))));
private static final StructuredRecord LEO = StructuredRecord.builder(SCHEMA).set("name", "Leo").set("id", 1L)
.set("kg", 11.1).set("cm", 111.1f).set("age", 11).build();
private static final StructuredRecord EVE = StructuredRecord.builder(SCHEMA).set("name", "Eve").set("id", 2L)
.set("kg", 22.2).set("cm", 222.2f).set("age", 22).build();
private static final StructuredRecord BOB_NULL_AGE = StructuredRecord.builder(SCHEMA).set("name", "Bob").set("id", 3L)
.set("kg", 33.3).set("cm", 333.3f).set("age", null).build();
private static final StructuredRecord ALICE = StructuredRecord.builder(SCHEMA).set("name", "Alice").set("id", 4L)
.set("kg", 44.4).set("cm", 444.4f).set("age", 44).build();
private static final List<StructuredRecord> INPUT = ImmutableList.of(LEO, EVE, BOB_NULL_AGE, ALICE);
private static final MockPipelineConfigurer MOCK_PIPELINE_CONFIGURER =
new MockPipelineConfigurer(SCHEMA, new HashMap<String, Object>());
private static boolean inputDone = false;
@BeforeClass
public static void init() throws Exception {
setupBatchArtifacts(APP_ARTIFACT_ID, DataPipelineApp.class);
// add TopN plugin
addPluginArtifact(NamespaceId.DEFAULT.artifact("topn", "1.0.0"), APP_ARTIFACT_ID, TopN.class);
}
private void testTopN(String field, int size, boolean ignoreNull,
String testName, Set<StructuredRecord> expected) throws Exception {
ETLBatchConfig config = ETLBatchConfig.builder("* * * * *")
.setEngine(Engine.MAPREDUCE)
.addStage(new ETLStage("input", MockSource.getPlugin(INPUT_TABLE, SCHEMA)))
.addStage(new ETLStage("topn", new ETLPlugin("TopN", BatchAggregator.PLUGIN_TYPE,
ImmutableMap.of("field", field,
"size", Integer.toString(size),
"ignoreNull", Boolean.toString(ignoreNull)),
null)))
.addStage(new ETLStage("output", MockSink.getPlugin(testName)))
.addConnection("input", "topn")
.addConnection("topn", "output")
.build();
AppRequest<ETLBatchConfig> appRequest = new AppRequest<>(APP_ARTIFACT, config);
ApplicationId appId = NamespaceId.DEFAULT.app(testName + "App");
ApplicationManager appManager = deployApplication(appId, appRequest);
// write records to input table for only once
if (!inputDone) {
DataSetManager<Table> inputManager = getDataset(NamespaceId.DEFAULT.dataset(INPUT_TABLE));
MockSource.writeInput(inputManager, INPUT);
inputDone = true;
}
// Run the workflow with TopN plugin
WorkflowManager workflowManager = appManager.getWorkflowManager(SmartWorkflow.NAME);
workflowManager.start();
workflowManager.waitForRun(ProgramRunStatus.COMPLETED, 5, TimeUnit.MINUTES);
// check sink
DataSetManager<Table> sinkManager = getDataset(testName);
List<StructuredRecord> actual = MockSink.readOutput(sinkManager);
// Records from sink are out of order, so use Sets to compare
Assert.assertEquals(expected, Sets.newHashSet(actual));
}
@Test
public void testAllNumericFields() throws Exception {
// Sort records with field "age" of int type and skip records with null value in field "age"
testTopN("age", 4, true, "skipNull", Sets.newHashSet(ALICE, EVE, LEO));
// Sort records with field "age" of int type and keep records with null value in field "age"
testTopN("age", 4, false, "keepNull", Sets.newHashSet(ALICE, EVE, LEO, BOB_NULL_AGE));
// Sort records with field "id" of long type
testTopN("id", 2, false, "largest", Sets.newHashSet(ALICE, BOB_NULL_AGE));
// Sort records with field "kg" of double type
testTopN("kg", 2, false, "heaviest", Sets.newHashSet(ALICE, BOB_NULL_AGE));
// Sort records with field "cm" of float type
testTopN("cm", 2, false, "tallest", Sets.newHashSet(ALICE, BOB_NULL_AGE));
}
}
|
package assertsEj;
import java.io.File;
import java.nio.file.Paths;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
//ASSERTIONS son metodos TestNG para indicar si un TestCase falla o no, al indicarle unos resultados esperados
//HARDASSERT DETIENE LA EJECUCION DEL TEST
//Se usan a traves de las librerias y seteando el POM.xml
//Son ejecutables con la instruccion @Test
//Esta es una class tipo TestNG
//Hard Assertion, puede manejar el error utilizando un bloque de captura como una excepción de Java
//METODOS HARD
//Assert.assertEquals(actual,expected); Assert.assertNotEquals(actual,expected,Message);
//Assert.assertTrue(condition); Assert.assertFalse(condition);
//Assert.assertNull(object); Assert.assertNotNull(object);
public class HardAssertEj {
@Test
public void assertEquals() { //para Java esto es un metodo pero al crear este tipo de clase TestNG se reconoce ejecutable con el @Test
int a = 10; //ejemplo para comparar ints
int b = 10;
Assert.assertEquals(a,b); //verifica si las variables son iguales
//RESULTADO CONSOLA muestra los totales, corridos, fallados y saltados
//RESULTADO "Results of running method HardAssertEj muestra el detalle del test case ejecutado en verde o azul fallado
}
@Test
public void assertNotEquals() {
int a = 5;
int b = 10;
Assert.assertNotEquals(a,b);
}
@Test
public void assertTrue() {
int a = 10;
int b = 10;
Assert.assertTrue(a==b); //retorna boolean
}
@Test
public void verificarTituloDePagina () {
//1. Uso del WebDriver
String exePath = Paths.get("").toAbsolutePath().toString() + File.separator + "drivers" + File.separator;
System.setProperty("webdriver.chrome.driver", exePath + "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://opensource-demo.orangehrmlive.com/");//abriendo la URL especificada
driver.manage().window().maximize();//maximizar ventana
//2. Variables para interactuar con la pagina
String actualTitle = driver.getTitle();
String expectedTitle = "Orange"; //valor real OrangeHRM
Assert.assertEquals(actualTitle, expectedTitle);//falla test ya que compara y no encuentra igual los valores
}
}
|
package com.zopa.quote.service;
import com.zopa.quote.model.Lender;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* Class responsible for fetching the best offers among the various lenders
*
*/
public class LenderEvaluator {
/**
* Method to fetch best available lenders , and make sure the sum is equal to loan amount
*
*
* @param lenders list of lenders
* @param loanAmount total loan amount
* @return list of best offers
*/
public List<Lender> getAvailableOffers(List<Lender> lenders, int loanAmount){
List<Lender> availableOffers = new ArrayList();
//Sort the list to get lowest interest rates first
lenders.sort((o1, o2) -> o1.getRate().compareTo(o2.getRate()));
for(Lender lender : lenders){
if(loanAmount - lender.getAvailableAmount().intValue() >0)
availableOffers.add(lender);
else {
availableOffers.add(new Lender(lender.getName(),lender.getRate(),
new BigDecimal(loanAmount)));
break;
}
loanAmount-=lender.getAvailableAmount().intValue();
}
return availableOffers;
}
}
|
package hungergames.hungerg.Listener;
import hungergames.hungerg.HungerG;
import org.bukkit.GameMode;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
public class DeathHandler implements Listener {
@EventHandler
public void DamageEventHandler(EntityDamageByEntityEvent event){
if(HungerG.GameStarting) {
if (event.getEntity().getType().equals(EntityType.PLAYER)) {
Player player = (Player) event.getEntity();
if (player.getHealth() <= 1) {
event.getDamager().sendMessage("Ты убил: " + player.getName());
player.sendMessage("Ты был убит: " + event.getDamager().getName());
}
} else if (event.getEntity().getType().equals(EntityType.ITEM_FRAME)) {
event.setCancelled(true);
}
}
else{event.setCancelled(true);}
}
@EventHandler
public void DeathEventHandler(PlayerDeathEvent event){
if(HungerG.GameStarting) {
event.getEntity().setHealth(20);
event.getEntity().setGameMode(GameMode.SPECTATOR);
event.setDeathMessage("");
}
else{
event.getEntity().teleport(event.getEntity().getWorld().getSpawnLocation());
}
}
}
|
package cards;
/**
* Classe que define uma carta.
*
* @author Rui Guerra 75737
* @author Joao Castanheira 77206
*
*/
public class Card {
public String face, naipe;
public int val;
public Card(String face, String naipe){
this.face=face;
this.naipe=naipe;
if(face.equals("A"))
this.val=11;
if(face.equals("2"))
this.val=2;
if(face.equals("3"))
this.val=3;
if(face.equals("4"))
this.val=4;
if(face.equals("5"))
this.val=5;
if(face.equals("6"))
this.val=6;
if(face.equals("7"))
this.val=7;
if(face.equals("8"))
this.val=8;
if(face.equals("9"))
this.val=9;
if(face.equals("10"))
this.val=10;
if(face.equals("J"))
this.val=10;
if(face.equals("Q"))
this.val=10;
if(face.equals("K"))
this.val=10;
}
@Override
public String toString() {
return face + naipe;
}
}
|
package com.si.ha.vaadin.security;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import com.si.ha.events.EventBus;
import com.si.ha.vaadin.HomeView;
import com.si.ha.vaadin.MainUI;
import com.vaadin.server.FontAwesome;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
public class LoginComp extends CustomComponent implements ClickListener {
private static final Logger logger = Logger.getLogger(LoginComp.class);
private TextField usernameField = new TextField("Username");
private PasswordField passwordField = new PasswordField("Password");
private Button loginButton = new Button("Sign In", FontAwesome.UNLOCK);
private Label invalidPasswordField = new Label("Invalid username or password");
@Override
public void buttonClick(ClickEvent event) {
Subject currentUser = VaadinSecurityContext.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(usernameField.getValue(), passwordField.getValue());
try {
currentUser.login(token);
EventBus.post(new SuccessfulLoginEvent());
// TODO ne ide, hanem az uri fragmentre amit kaptunk
MainUI.getCurrent().getNavigator().navigateTo(HomeView.NAME);
} catch (Exception e) {
logger.debug(e);
usernameField.setValue("");
passwordField.setValue("");
invalidPasswordField.setVisible(true);
}
}
public LoginComp() {
FormLayout l = new FormLayout();
l.setSizeUndefined();
l.setSpacing(true);
usernameField.focus();
l.addComponent(usernameField);
usernameField.setRequired(true);
usernameField.focus();
l.addComponent(passwordField);
passwordField.setRequired(true);
loginButton.addClickListener(this);
l.addComponent(loginButton);
l.addComponent(invalidPasswordField);
invalidPasswordField.setVisible(false);
setCompositionRoot(l);
}
public static interface LoginListener {
void onSuccessfulLogin();
}
}
|
package com.peerless2012.customerview;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;
/**
* @Author peerless2012
* @Email peerless2012@126.com
* @HomePage http://peerless2012.github.io
* @DateTime 2016年6月3日 上午11:30:37
* @Version V1.0
* @Description: 展示
*/
public class MainActivity extends Activity {
private int [] mLayoutRes = new int[]{
R.layout.view_clock,R.layout.view_record,R.layout.view_wifi
,R.layout.view_qq_health
};
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mViewPager.setLayoutParams(params);
setContentView(mViewPager);
mViewPager.setAdapter(new CustomerViewAdapter(mLayoutRes));
}
}
|
package com.hg.sb_helloworld;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.hg.sb_helloworld.dao.UserRepository;
import com.hg.sb_helloworld.service.UserService;
import junit.framework.Assert;
@SuppressWarnings( "deprecation" )
@RunWith( SpringJUnit4ClassRunner.class )
@WebAppConfiguration
@SpringApplicationConfiguration( classes = Application.class )
public class UserMongoTest
{
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Test
public void userTest(){
userService.goToSchool();
Assert.assertEquals( 2, userRepository.findAll().size() );
Assert.assertEquals( 20, userRepository.findByUserName( "U1" ).getAge().intValue() );
}
}
|
package com.grandsea.ticketvendingapplication.constant;
/**
* Created by Administrator on 2017/9/18.
*/
public class IntentKey {
//DestCityActivity.class 下面的
public static final String INTENT_DEPART_CITY_ID = "depart_city_id";
public static final String INTENT_DEST_CITY = "dest_city";
public static final String INTENT_DEST_CITY_BUNDLE = "dest_city_name";
//站点--> 班次相关
public static final String SHIFT_OBJ = "shift_obj";
//班次--> 乘客
public static final String EXTRA_SHIFT_TO_PASSENGER_OBJ = "order_info_obj";
//乘客 --> 下单
public static final String ORDER_INFO = "order_info";
//
public static final String TICKET_DATE = "ticket_date";
public static final String ORDER_ID = "order_Id";
public static final String PERSON_INFO = "person_info";
public static final String TOTAL_TICKETS = "total_tickets";
public static final String CHANGE_DEPART_STATION = "change_dpart_station";
}
|
package memCache.ring;
import common.Hash;
import common.Key;
import memCache.config.Settings;
import memCache.fileUtils.Cache;
import memCache.fileUtils.FileManager;
import memCache.fileUtils.Record;
import memCache.network.FileReceiver;
import memCache.network.FileTransmitter;
import memCache.network.Server;
import java.io.*;
import java.math.BigInteger;
import java.net.InetAddress;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
public class Node extends UnicastRemoteObject implements Reachable{
/** The ip address of the logged node **/
private InetAddress ip;
/** The port that the logged node listens to for requests**/
private int listeningPort;
/** The port to receive the files for which is responsible **/
private int fileReceivingPort;
/** Server that handles the incoming requests **/
private Server server;
/** Cache system of the node **/
private Cache<Key, Record<String>> cache;
/** Stores/Retrieves files stored in the node's disk **/
private FileManager fileManager;
/** Status of the node **/
private boolean isAlive;
/** Distinct id of the node inside the ring **/
private Key nodeKey;
/** Predecessor node according to the key values **/
private Reachable predecessor;
/** Successor node according to the key values **/
private Reachable successor;
/** Shortcut nodes inside the ring **/
private FingerTable fingerTable;
/** Stabilizes node refreshing it's information **/
private Stabilizer stabilizer;
/** The timer used to invoke stabilization **/
private Timer stabilizeTimer;
public Node(InetAddress ip,int listeningPort) throws RemoteException {
this.ip = ip;
this.listeningPort = listeningPort;
this.fileReceivingPort = Settings.FILE_RECEIVING_PORT;
this.nodeKey = new Key(ip.getHostAddress() + ":" + listeningPort);
this.server = new Server(this);
this.fingerTable = new FingerTable(Hash.getKeyLength());
this.cache = new Cache<>(10000, 1); //TODO: configure options (cacheSize,purgeFreq in minutes)
this.fileManager = new FileManager();
this.stabilizer = new Stabilizer(this);
this.stabilizeTimer = new Timer();
this.isAlive = true;
}
/**
* ------------Methods used to initialize the node or balance the ring------------
*/
/**
* Join the ring asking the node n for the appropriate neighbours
* @param n
*/
public void join(Reachable n) throws RemoteException{
if (this.equals(n)){
this.predecessor = this;
this.successor = this;
for(int i=0; i<this.fingerTable.length(); i++){
this.fingerTable.put(this, i);
}
}
else{
this.initFingerTable(n);
this.updateOthers();
this.successor.transferFilesTo(this);
}
this.stabilizeTimer.scheduleAtFixedRate(this.stabilizer,10000,5000); //TODO: config stabilization start time & period
}
/**
* Leave gracefully the ring restoring the balance
*/
public void leave() throws RemoteException{
this.server.stop();
this.stabilizeTimer.cancel(); //TODO: update fingers of others
this.successor.setPredecessor(this.predecessor);
this.predecessor.setSuccessor(this.successor);
this.transferFilesTo(this.successor);
}
/**
* Initialize the fingers/shortcuts to other nodes using node n.
* @param n
*/
public void initFingerTable(Reachable n){
try {
this.successor = n.findSuccessor(this.getNodeKey());
this.fingerTable.put(this.successor,0);
this.predecessor = this.successor.getPredecessor();
this.successor.setPredecessor(this);
this.predecessor.setSuccessor(this);
for(int i=1; i<this.fingerTable.length(); i++){
Key nextFingerKey = this.successor(i);
boolean isBetweenThisAndFinger = nextFingerKey.isBetween(this.nodeKey, this.fingerTable.getFingers()[i-1].getNodeKey(), Key.ClBoundsComparison.LOWER);
if(isBetweenThisAndFinger){
this.fingerTable.put(this.fingerTable.getFingers()[i-1], i);
}
else {
Reachable finger = n.findSuccessor(nextFingerKey);
if (!finger.equals(this)) {
this.fingerTable.put(finger, i);
}
else {
this.fingerTable.put(this.successor,i);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Update the entries of others inside the ring
*/
public void updateOthers() throws RemoteException{
this.predecessor.setFinger(this,0);
for(int i=0; i<this.fingerTable.length(); i++){
try {
Key predFingerKey = this.predecessor(i);
Reachable p;
p = this.findPredecessor(predFingerKey);
if (!p.equals(this)){
p.updateFingerTable(this,i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void updateFingerTable(Reachable s,int i) throws RemoteException {
if (s.getNodeKey().isBetween(this.nodeKey, this.fingerTable.getFingers()[i].getNodeKey(), Key.ClBoundsComparison.LOWER)) {
this.fingerTable.put(s, i);
this.predecessor.updateFingerTable(s, i);
}
}
/**
* Periodically verify immediate successor
*/
public void stabilize() throws RemoteException{
Reachable x = this.successor.getPredecessor();
if(x.getNodeKey().isBetween(this.nodeKey,this.successor.getNodeKey(), Key.ClBoundsComparison.NONE)){
this.setSuccessor(x);
this.successor.notify(this);
}
}
/** Fix predecessor if notifier is closer than the current one **/
public void notify(Reachable candidatePredecessor) throws RemoteException{
if(this.predecessor==null || candidatePredecessor.getNodeKey().isBetween(this.predecessor.getNodeKey(),this.getNodeKey(), Key.ClBoundsComparison.NONE)){
this.setPredecessor(candidatePredecessor);
}
}
/**
* Periodically refresh finger table entries
*/
public void fixFingers() throws RemoteException{
int i = (int)(this.fingerTable.length()*Math.random());
if (i>0 && this.fingerTable.getFingers()[i] != null){
this.fingerTable.put(this.findSuccessor(this.fingerTable.getFingers()[i].getNodeKey()),i);
}
}
/**
* Checks whether predecessor has failed
*/
public void checkPredecessor() throws RemoteException {
if (this.predecessor!= null && !this.predecessor.isAlive()) {
this.predecessor = null;
}
}
/**
* Used by other nodes to identify status
* @return
*/
public boolean isAlive(){
return this.isAlive;
}
/**
* Transfer files to the responsible node (called upon node join/leave incidents)
* @param responsible
*/
public void transferFilesTo(Reachable responsible) throws RemoteException {
System.out.println("Seeking for candidate files/key for transfer...");
boolean joinIncident = responsible.equals(this.predecessor);
boolean leaveIncident = !joinIncident && responsible.equals(this.successor);
List<File> filesToTransfer = new ArrayList<>();
if (joinIncident) {
if (responsible.getPredecessor().getNodeKey().compareTo(responsible.getNodeKey()) == -1) {
filesToTransfer = this.fileManager.getFilesInRange(responsible.getPredecessor().getNodeKey(), responsible.getNodeKey());
} else {
BigInteger minKeyInRing = BigInteger.valueOf(0);
BigInteger maxKeyInRing = BigInteger.valueOf(2);
maxKeyInRing = maxKeyInRing.pow(Hash.getKeyLength());
filesToTransfer = this.fileManager.getFilesInRange(responsible.getPredecessor().getNodeKey(), new Key(maxKeyInRing.toByteArray()));
filesToTransfer.addAll(this.fileManager.getFilesInRange(new Key(minKeyInRing.toByteArray()), responsible.getNodeKey()));
}
}
else if (leaveIncident) {
File filesDir = new File(Settings.FILES_DIR);
File[] files = filesDir.listFiles();
if (files != null) {
filesToTransfer = Arrays.asList(files);
}
}
try {
if (!filesToTransfer.isEmpty()){
System.out.println("Transferring files to : "+responsible.getIp()+":"+responsible.getListeningPort());
responsible.awakeToReceive(this);
Thread fileTransmission = new Thread(new FileTransmitter(responsible,filesToTransfer));
fileTransmission.start();
fileTransmission.join();
this.fileManager.removeFiles(filesToTransfer);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
/**
* Used by other nodes to notify (this), so that it starts receiving
* @param notifier
*/
public void awakeToReceive(Reachable notifier){
if (notifier.equals(this.predecessor) || notifier.equals(this.successor)){
this.receiveFilesUnderResponsibility();
}
}
/**
* Receive the files that fall under responsibility -> within the range of (pred.Key-this.Key]
*/
private void receiveFilesUnderResponsibility(){
System.out.println("Receiving files under responsibility");
Thread receiveService = new Thread(new FileReceiver(this.fileReceivingPort));
receiveService.start();
System.out.println("Files Received successfully!");
}
/**
* ------------Auxiliary key calculation methods used for finger creation------------
*/
/**
* Calculates the ith entry of the fingerTable.
* @param i entry number
* @return appropriate key value.
*/
private Key successor(int i) {
BigInteger rterm = BigInteger.valueOf(2);
rterm = rterm.pow(i);
BigInteger fingerKey = this.nodeKey.toBigInt().add(rterm);
BigInteger divisor = BigInteger.valueOf(2);
divisor = divisor.pow(Hash.getKeyLength());
fingerKey = fingerKey.mod(divisor);
return new Key(fingerKey.toByteArray());
}
/**
* Calculates the ith key of incoming neighbours to this node.
* @param i entry number
* @return appropriate key value.
*/
private Key predecessor(int i) {
BigInteger rterm = BigInteger.valueOf(2);
rterm = rterm.pow(i);
BigInteger fingerKey = this.nodeKey.toBigInt().subtract(rterm);
if (fingerKey.compareTo(BigInteger.ZERO)== -1){
BigInteger maxKeyVal = BigInteger.valueOf(2);
maxKeyVal = maxKeyVal.pow(Hash.getKeyLength());
fingerKey = maxKeyVal.add(fingerKey).add(BigInteger.ONE);
}
return new Key(fingerKey.toByteArray());
}
/**
* ------------Methods that search inside the ring based on a given key------------
*/
/**
* Finds the logged successor of the given key
* @param key given key
* @return the successor
*/
public Reachable findSuccessor(Key key) throws RemoteException{
return findPredecessor(key).getSuccessor();
}
/**
* Finds the logged predecessor of the given key
* @param key given key
* @return the successor
*/
public Reachable findPredecessor(Key key) throws RemoteException {
Reachable n = this;
Reachable lastCandidatePred = this;
while (!key.isBetween(n.getNodeKey(), n.getSuccessor().getNodeKey(), Key.ClBoundsComparison.UPPER)) {
n = n.closestPrecedingFinger(key);
//if we meet the same node twice then the new key doesn't belong to the current intervals
//so it must either be the minimum or the maximum in the ring(either way it's pred is the current max key)
if (n.equals(lastCandidatePred)) {
return n.findMax();
}
lastCandidatePred = n;
}
return n;
}
/**
* Returns the closest to the given key preceding node from the fingerTable.
* @param key given key
* @return closest predecessor
*/
public Reachable closestPrecedingFinger(Key key) throws RemoteException{
for(int i=this.fingerTable.length()-1; i>=0; i--){
if(this.nodeKey.equals(this.nodeKey.min(this.fingerTable.getFingers()[i].getNodeKey()))){
if(this.fingerTable.getFingers()[i].getNodeKey().isBetween(this.nodeKey,key, Key.ClBoundsComparison.NONE)){
return this.fingerTable.getFingers()[i];
}
}
else {
if (key.isBetween(this.fingerTable.getFingers()[i].getNodeKey(),this.nodeKey, Key.ClBoundsComparison.NONE)){
return this.fingerTable.getFingers()[i];
}
}
}
return this;
}
/**
* Returns the node with the maximum key inside the ring.
* @return
*/
public Reachable findMax() throws RemoteException{
for(int i=this.fingerTable.length()-1; i>=0; i--) {
Reachable finger = this.fingerTable.getFingers()[i];
if (!this.equals(finger)) {
if (finger.getNodeKey().equals(finger.getNodeKey().max(this.nodeKey))) {
return finger.findMax();
}
}
}
return this;
}
/**
* ------------Accessors - Mutators------------
*/
public InetAddress getIp(){ return this.ip; }
public int getFileReceivingPort(){ return this.fileReceivingPort; }
public int getListeningPort(){ return this.listeningPort; }
public Server getServer(){ return server; }
public Key getNodeKey(){ return this.nodeKey; }
public Reachable getSuccessor(){ return successor; }
public synchronized void setSuccessor(Reachable successor){ this.successor = successor; }
public Reachable getPredecessor(){ return predecessor; }
public synchronized void setPredecessor(Reachable predecessor){ this.predecessor = predecessor; }
public synchronized void setFinger(Reachable finger,int i){
if (finger.equals(this.successor)){
this.fingerTable.put(finger,i);
}
}
public Cache<Key, Record<String>> getCache() { return this.cache; }
public FileManager getFileManager() { return this.fileManager; }
public String printFingerTable() throws RemoteException{
String result="\n\t=== FingerTable ===\n";
int entry = 0;
for(Reachable f: this.fingerTable.getFingers()){
result+="\nEntry: "+entry+"-->"+f.getNodeKey().toBigInt();
entry++;
}
return result;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode *37 + this.listeningPort;
hashCode = hashCode*23+ this.ip.hashCode();
return hashCode;
}
@Override
public String toString() {
try {
String res = "\nNode: "+this.ip.toString()+":"+this.listeningPort;
res+= "\nkey:"+this.nodeKey.toBigInt();
res+= "\nprd:"+this.predecessor.getNodeKey().toBigInt()+"\nsuc:"+this.successor.getNodeKey().toBigInt()+"\n";
res+= this.printFingerTable();
return res;
}catch (RemoteException re){
return re.getMessage();
}
}
public void notifyUpdates() throws RemoteException{
printUpdates();
}
private void printUpdates()throws RemoteException{
BigInteger predKey = this.predecessor.getNodeKey().toBigInt();
BigInteger succKey = this.successor.getNodeKey().toBigInt();
System.out.println("\n UPDATES \nkey: "+this.nodeKey.toBigInt()+"\npred: "+predKey+"\nsucc: "+succKey);
}
}
|
package com.gxjtkyy.standardcloud.common.domain.dto;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import java.util.Map;
/**
* API日志存储类
* @Package com.gxjtkyy.standardcloud.common.domain.dto
* @Author lizhenhua
* @Date 2018/7/3 15:23
*/
@Setter
@Getter
@ToString(callSuper = true)
public class ApiLogDTO extends BaseDTO{
/**id*/
@Id
private String logIndex;
/**requesturi*/
private String requestURI;
/**ip*/
private String ip;
/**操作员*/
private String operator;
/**操作员ID*/
private String operatorId;
/**请求*/
private Map request;
/**响应*/
private Map response;
}
|
package com.zjx.returnResult;
/**
* @program: common
* @description 统一返回结果
* @author: zhujingxing
* @create: 2021-01-13 09:42
**/
public class ReturnResult<T> {
private T data;
private Boolean success;
public ReturnResult(T t) {
this.data = t;
this.success = true;
}
public ReturnResult() {
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Boolean isSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
}
|
// Copyright (C) 2016 The Android Open Source Project
//
// 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.google.reviewit.widget;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import com.google.reviewit.BaseFragment;
import com.google.reviewit.R;
import com.google.reviewit.util.WidgetUtil;
import java.util.List;
import static com.google.reviewit.util.WidgetUtil.setGone;
import static com.google.reviewit.util.WidgetUtil.setVisible;
public abstract class InfoBox<T> extends RelativeLayout {
private static final int PAGE_SIZE = 10;
protected final WidgetUtil widgetUtil;
protected BaseFragment fragment;
public InfoBox(Context context) {
this(context, null, 0);
}
public InfoBox(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public InfoBox(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.widgetUtil = new WidgetUtil(context);
inflate(context, R.layout.info_box, this);
init();
}
private void init() {
((TextView)findViewById(R.id.info_title)).setText(getTitle());
if (getIcon() > 0) {
ImageView action = (ImageView)findViewById(R.id.info_action);
action.setImageDrawable(widgetUtil.getDrawable(getIcon()));
setVisible(action);
action.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
onAction(fragment);
}
});
}
WidgetUtil.underline((TextView) findViewById(R.id.show_more));
WidgetUtil.underline((TextView) findViewById(R.id.show_all));
}
protected abstract @StringRes int getTitle();
protected @DrawableRes int getIcon() {
return -1;
}
protected void onAction(BaseFragment fragment) {
}
protected void display(BaseFragment fragment, List<T> entries) {
this.fragment = fragment;
display(entries, 1, false);
}
private void display(
final List<T> entries, final int page, boolean showAll) {
TableLayout tl = (TableLayout) findViewById(R.id.info_table);
int count = 0;
for (T e : entries) {
count++;
if (count <= (page - 1) * PAGE_SIZE) {
continue;
}
if (!showAll && count > page * PAGE_SIZE) {
break;
}
addRow(tl, e);
}
if (!showAll && entries.size() > page * PAGE_SIZE) {
WidgetUtil.setText(findViewById(R.id.show_all),
fragment.getString(R.string.show_all, entries.size() - page *
PAGE_SIZE));
setVisible(findViewById(R.id.info_buttons));
findViewById(R.id.show_all).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
display(entries, page + 1, true);
}
});
if (entries.size() > (page + 1) * PAGE_SIZE) {
WidgetUtil.setText(findViewById(R.id.show_more),
fragment.getString(R.string.show_more, PAGE_SIZE));
setVisible(findViewById(R.id.show_more_area),
findViewById(R.id.show_more));
findViewById(R.id.show_more).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
display(entries, page + 1, false);
}
});
} else {
setGone(findViewById(R.id.show_more_area),
findViewById(R.id.show_more));
}
} else {
setGone(findViewById(R.id.info_buttons));
}
}
public void clear() {
TableLayout tl = (TableLayout) findViewById(R.id.info_table);
View child = tl.getChildAt(1);
while (child != null) {
tl.removeView(child);
child = tl.getChildAt(1);
}
}
protected abstract void addRow(TableLayout tl, T entry);
}
|
package org.didierdominguez.bean;
public class CreditCard {
private Integer id;
private String cardNo;
private Customer customer;
private String expirationDate;
private Double creditLimit;
private Double amountOwed;
private Double amountPaid;
private Boolean authorization;
public CreditCard(Integer id, String cardNo, Customer customer, String expirationDate,
Double creditLimit, Double amountOwed, Double amountPaid, Boolean authorization) {
this.id = id;
this.cardNo = cardNo;
this.customer = customer;
this.expirationDate = expirationDate;
this.creditLimit = creditLimit;
this.amountOwed = amountOwed;
this.amountPaid = amountPaid;
this.authorization = authorization;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
public Double getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(Double creditLimit) {
this.creditLimit = creditLimit;
}
public Double getAmountOwed() {
return amountOwed;
}
public void setAmountOwed(Double amountOwed) {
this.amountOwed = amountOwed;
}
public Double getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(Double amountPaid) {
this.amountPaid = amountPaid;
}
public Boolean getAuthorization() {
return authorization;
}
public void setAuthorization(Boolean authorization) {
this.authorization = authorization;
}
}
|
/**
* $Id: ListEditor.java,v 1.4 2005/09/13 18:07:02 nicks Exp $
*
* Originally part of the AMATO application.
*
* @author Nick Seidenman <nick@seidenman.net>
* @version $Revision: 1.4 $
*
* $Log: ListEditor.java,v $
* Revision 1.4 2005/09/13 18:07:02 nicks
* Entry field (JTextArea) is now cleared when the Add button is pressed.
*
* Revision 1.3 2005/08/17 20:35:23 nicks
* Converted comment header to comply with javadoc conventions.
*
* Revision 1.2 2005/07/26 21:10:47 nicks
* Removed debug cruft.
*
* Revision 1.1 2005/07/25 21:41:40 nicks
* Initial revision
*
*/
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListEditor
extends JPanel
implements ActionListener, ListSelectionListener
{
private static final long serialVersionUID = 20050725142500L;
private JButton add_btn;
private JButton rem_btn;
private JList le_list;
private JScrollPane le_scroller;
private ListEditorList lem;
private int selectedListIndex;
private JPanel entry_panel;
private JComponent entry_component;
public ListEditor ()
{
super (new BorderLayout());
selectedListIndex = -1;
// Create "ADD" and REMOVE buttons.
add_btn = new JButton ("ADD");
rem_btn = new JButton ("REMOVE");
add_btn.addActionListener (this);
rem_btn.addActionListener (this);
JPanel le_btns = new JPanel (new GridLayout (0,2));
le_btns.add (add_btn);
le_btns.add (rem_btn);
// Leave room for the entry component.
entry_panel = new JPanel (new GridLayout (0, 1));
// Create the (scrolling) list.
lem = new ListEditorList ();
le_list = new JList (lem);
le_list.setCellRenderer (new ListEditorCellRenderer());
le_list.getSelectionModel().setSelectionMode
(ListSelectionModel.SINGLE_SELECTION);
le_list.addListSelectionListener (this);
le_scroller = new JScrollPane (le_list);
JPanel le_main = new JPanel (new GridLayout (0, 1));
le_main.add (le_scroller);
// Put 'em all together.
add (le_main, BorderLayout.NORTH);
add (entry_panel, BorderLayout.CENTER);
add (le_btns, BorderLayout.SOUTH);
}
public void setEditor (JComponent ec)
{
entry_panel.add (ec);
entry_component = ec;
}
public void addItem (String s)
{
lem.add (s);
}
public void addOption (String s)
{
if (entry_component instanceof JComboBox)
((JComboBox) entry_component).addItem (s);
}
class ListEditorCellRenderer extends JLabel implements ListCellRenderer
{
private static final long serialVersionUID = 20050725112660L;
public Component getListCellRendererComponent (JList l,
Object v,
int ndx,
boolean isSelected,
boolean cellHasFocus)
{
setText ((String) v);
if (isSelected) {
setBackground (l.getSelectionBackground());
setForeground (l.getSelectionForeground());
}
else {
setBackground (l.getBackground());
setForeground (l.getForeground());
}
setEnabled (l.isEnabled());
setFont (l.getFont());
setOpaque (true);
return this;
}
}
/** Required by ListSelectionListener interface. **/
public void valueChanged (ListSelectionEvent e)
{
JList jl = (JList) e.getSource ();
selectedListIndex = jl.getSelectedIndex ();
// System.out.println ("selectedListIndex: " + selectedListIndex);
}
/** Required for ActionListener interface. **/
public void actionPerformed (ActionEvent e) {
if ("ADD".equals (e.getActionCommand())) {
addNode (e);
}
else if ("REMOVE".equals (e.getActionCommand())) {
deleteNode (e);
}
else {
System.err.println ("Shouldn't happen!");
}
}
private void addNode (ActionEvent e)
{
if (entry_component instanceof JComboBox) {
int si = ((JComboBox) entry_component).getSelectedIndex ();
lem.add ((String) ((JComboBox) entry_component).getItemAt (si));
}
else if (entry_component instanceof JTextField) {
lem.add ((String) ((JTextField) entry_component).getText());
((JTextField) entry_component).setText ("");
}
else {
System.err.println ("addNode: Unknown entry_component: " +
entry_component.getClass());
}
le_list.updateUI ();
}
private void deleteNode (ActionEvent e)
{
// System.out.println ("REMOVE button pressed: " + selectedListIndex);
if (selectedListIndex >= 0) {
lem.remove (selectedListIndex);
}
selectedListIndex = -1;
le_list.updateUI ();
}
private class ListEditorList extends AbstractListModel
{
private static final long serialVersionUID = 20050708112710L;
private ArrayList<String> sList;
public ListEditorList ()
{
super ();
sList = new ArrayList<String> ();
}
public ListEditorList (String[] cl)
{
super ();
sList = new ArrayList<String> ();
for (String s: cl) sList.add (s);
}
public void add (String s)
{
sList.add (s);
fireIntervalAdded (s, sList.size(), sList.size());
}
public void remove (int ndx)
{
String s = sList.get (ndx);
sList.remove (ndx);
fireIntervalRemoved (s, 0, sList.size());
}
public Object getElementAt (int ndx)
{
if (ndx < 0 || ndx > sList.size()) return null;
return sList.get (ndx);
}
final public int getSize () { return sList.size(); }
final public String toString ()
{
return sList.toString().substring(1, sList.toString().length()-1);
}
}
final public String toString ()
{
return lem.toString();
}
private class EntryField extends JTextField
{
private static final long serialVersionUID = 20050725162500L;
public EntryField () { super (); }
public EntryField (String s) { super (s); }
public Object getItemAt (int ignored) { return getText (); }
}
static public void main (String[] args)
{
JFrame f1 = new JFrame ("List Editor");
f1.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
String[] opts = {"this", "that", "other"};
ListEditor le1 = new ListEditor ();
//JComboBox e = new JComboBox (opts);
JTextField e = new JTextField ();
le1.setEditor ((JComponent) e);
le1.setBorder (BorderFactory.createTitledBorder ("List Editor 1"));
f1.add (le1);
f1.pack ();
f1.setVisible (true);
}
}
|
package kui.crawlingClient.entity;
public class News_souhu {
private String authorId;
private String authorName;
private String id;
private String title;
private String picUrl;
private String publicTime;
private String originalSource;
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getPublicTime() {
return publicTime;
}
public void setPublicTime(String publicTime) {
this.publicTime = publicTime;
}
public String getOriginalSource() {
return originalSource;
}
public void setOriginalSource(String originalSource) {
this.originalSource = originalSource;
}
@Override
public String toString() {
return "News_souhu [authorId=" + authorId + ", authorName=" + authorName + ", id=" + id + ", title=" + title
+ ", picUrl=" + picUrl + ", publicTime=" + publicTime + ", originalSource=" + originalSource + "]";
}
}
|
package company.classes;
import static company.classes.FunUtils.floatFromat;
/**
* Class triangle
*/
public class Triangle {
/**
* The first side of triangle
*/
protected double sideA;
/**
* The second side of triangle
*/
protected double sideB;
/**
* The third side of triangle
*/
protected double sideC;
/**
* The first corner of triangle
*/
protected double alpha;
/**
* The second corner of triangle
*/
protected double betta;
/**
* The third corner of triangle
*/
protected double gamma;
/**
* The perimeter of triangle
*/
protected double perimeter;
/**
* The area of triangle
*/
protected double area;
/**
* Construct of Triangle class
* @param sideA The first side of triangle
* @param sideB The second side of triangle
* @param sideC The third side of triangle
*/
public Triangle(final double sideA, final double sideB, final double sideC) {
if (sideA < sideB + sideC && sideB < sideA + sideC && sideC < sideA + sideB) {
this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
calculation();
}
}
/**
* Calculation of unknown values
*/
private void calculation() {
alpha = (Math.acos((Math.pow(sideB, 2) + Math.pow(sideC, 2) - Math.pow(sideA, 2)) / (2 * sideB * sideC)) * 180) / Math.PI;
betta = (Math.acos((Math.pow(sideA, 2) + Math.pow(sideC, 2) - Math.pow(sideB, 2)) / (2 * sideA * sideC)) * 180) / Math.PI;
gamma = (Math.acos((Math.pow(sideA, 2) + Math.pow(sideB, 2) - Math.pow(sideC, 2)) / (2 * sideA * sideB)) * 180) / Math.PI;
perimeter = sideA + sideB + sideC;
area = Math.sqrt((perimeter / 2) * (perimeter / 2 - sideA) * (perimeter / 2 - sideB) * (perimeter / 2 - sideC));
}
/**
* Get info about triangle
*/
@Override
public String toString() {
String result;
if (sideA < sideB + sideC && sideB < sideA + sideC && sideC < sideA + sideB) {
result = "Triangle exists!!! Sides: a = " + sideA + " cm ; b = " + sideB + " cm ; c = " + sideC + " cm. Corner: alpha = " + floatFromat(alpha) + " degrees; betta = " + floatFromat(betta) + " degrees; gamma = " + floatFromat(gamma) + " degrees. Perimeter: P = " + floatFromat(perimeter) + " cm. Area: S = " + floatFromat(area) + " cm^2.";
} else {
result = "Triangle doesn't exist !!!";
}
return result;
}
} |
package org.appsugar.controller.account.dto;
import java.util.ArrayList;
import java.util.List;
import org.appsugar.entity.account.User;
/**
* 用户数据实体
* @author NewYoung
* 2016年2月29日下午2:08:43
*/
public class UserDto {
private Long id;
private String name;
private String loginName;
public UserDto(String name, String loginName) {
super();
this.name = name;
this.loginName = loginName;
}
public UserDto(User user) {
this.name = user.getName();
this.loginName = user.getLoginName();
this.id = user.getId();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UserDto [id=").append(id).append(", name=").append(name).append(", loginName=")
.append(loginName).append("]");
return builder.toString();
}
public static List<UserDto> transfer(List<User> userList) {
List<UserDto> result = new ArrayList<>(userList.size());
for (User user : userList) {
result.add(new UserDto(user));
}
return result;
}
}
|
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
boolean flag=false;
int n=sc.nextInt();
for(int i=0;i<n;i++){
int a=sc.nextInt();
for(int j=2;j*j<=a;j++){
if(a%j==0){
flag=true;
}
}
if(a==1)
flag=true;
if(!flag){
System.out.println("Prime");
}
else{
System.out.println("Not prime");
flag=false;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.